File: sound.cpp

package info (click to toggle)
jamulus 3.6.2%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 16,444 kB
  • sloc: ansic: 53,088; cpp: 19,791; sh: 4,697; asm: 723; makefile: 346; perl: 264; python: 56; xml: 37
file content (375 lines) | stat: -rw-r--r-- 13,103 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
/******************************************************************************\
 * Copyright (c) 2004-2020
 *
 * Author(s):
 *  Simon Tomlinson, Volker Fischer
 *
 ******************************************************************************
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
\******************************************************************************/

#include "sound.h"
#include "androiddebug.cpp"

/* Implementation *************************************************************/

const uint8_t CSound::RING_FACTOR = 20;

CSound::CSound ( void           (*fpNewProcessCallback) ( CVector<short>& psData, void* arg ),
                 void*          arg,
                 const QString& strMIDISetup,
                 const bool     ,
                 const QString& ) :
    CSoundBase ( "Oboe", fpNewProcessCallback, arg, strMIDISetup )
{
#ifdef ANDROIDDEBUG
    qInstallMessageHandler(myMessageHandler);
#endif
}

void CSound::setupCommonStreamParams ( oboe::AudioStreamBuilder* builder )
{
    // We request EXCLUSIVE mode since this will give us the lowest possible
    // latency. If EXCLUSIVE mode isn't available the builder will fall back to SHARED mode
    builder
            ->setFormat(oboe::AudioFormat::Float)
            ->setSharingMode(oboe::SharingMode::Exclusive)
            ->setChannelCount(oboe::ChannelCount::Stereo)
            ->setSampleRate(SYSTEM_SAMPLE_RATE_HZ)
            ->setFramesPerCallback(iOboeBufferSizeMono)
            ->setSampleRateConversionQuality(oboe::SampleRateConversionQuality::Medium)
            ->setPerformanceMode(oboe::PerformanceMode::LowLatency);

    return;
}

void CSound::closeStream ( oboe::ManagedStream& stream )
{
    if ( stream )
    {
        oboe::Result requestStopRes = stream->requestStop();
        oboe::Result result         = stream->close();

        if ( result != oboe::Result::OK )
        {
            throw CGenErr ( tr ( "Error closing stream: $s",
                                 oboe::convertToText ( result ) ) );
        }

        stream.reset();
    }
}


void CSound::openStreams()
{
    // Setup output stream
    oboe::AudioStreamBuilder inBuilder, outBuilder;

    outBuilder.setDirection ( oboe::Direction::Output );
    outBuilder.setCallback(this);
    setupCommonStreamParams ( &outBuilder );

    oboe::Result result = outBuilder.openManagedStream ( mPlayStream );

    if ( result != oboe::Result::OK )
    {
        return;
    }
    mPlayStream->setBufferSizeInFrames ( iOboeBufferSizeStereo );

    warnIfNotLowLatency ( mPlayStream, "PlayStream" );
    printStreamDetails ( mPlayStream );

    // Setup input stream
    inBuilder.setDirection ( oboe::Direction::Input );

    // Only set callback for the input direction
    // the output will be handled writing directly on the stream
    inBuilder.setCallback(this);
    setupCommonStreamParams ( &inBuilder );

    result = inBuilder.openManagedStream ( mRecordingStream );

    if ( result != oboe::Result::OK )
    {
        closeStream ( mPlayStream );
        return;
    }

    mRecordingStream->setBufferSizeInFrames ( iOboeBufferSizeStereo );

    warnIfNotLowLatency ( mRecordingStream, "RecordStream" );
    printStreamDetails ( mRecordingStream );
    printStreamDetails ( mPlayStream );
}

void CSound::printStreamDetails ( oboe::ManagedStream& stream )
{
    QString sDirection              = ( stream->getDirection()==oboe::Direction::Input ? "Input" : "Output" );
    QString sFramesPerBurst         = QString::number ( stream->getFramesPerBurst() );
    QString sBufferSizeInFrames     = QString::number ( stream->getBufferSizeInFrames() );
    QString sBytesPerFrame          = QString::number ( stream->getBytesPerFrame() );
    QString sBytesPerSample         = QString::number ( stream->getBytesPerSample() );
    QString sBufferCapacityInFrames = QString::number ( stream->getBufferCapacityInFrames() );
    QString sPerformanceMode        = ( stream->getPerformanceMode() == oboe::PerformanceMode::LowLatency ? "LowLatency" : "NotLowLatency" );
    QString sSharingMode            = ( stream->getSharingMode() == oboe::SharingMode::Exclusive ? "Exclusive" : "Shared" );
    QString sDeviceID               = QString::number ( stream->getDeviceId() );
    QString sSampleRate             = QString::number ( stream->getSampleRate() );
    QString sAudioFormat            = ( stream->getFormat()==oboe::AudioFormat::I16 ? "I16" : "Float" );
    QString sFramesPerCallback      = QString::number ( stream->getFramesPerCallback() );
    qInfo() << "Stream details: [sDirection: " << sDirection <<
               ", FramesPerBurst: "            << sFramesPerBurst <<
               ", BufferSizeInFrames: "        << sBufferSizeInFrames <<
               ", BytesPerFrame: "             << sBytesPerFrame <<
               ", BytesPerSample: "            << sBytesPerSample <<
               ", BufferCapacityInFrames: "    << sBufferCapacityInFrames <<
               ", PerformanceMode: "           << sPerformanceMode <<
               ", SharingMode: "               << sSharingMode <<
               ", DeviceID: "                  << sDeviceID <<
               ", SampleRate: "                << sSampleRate <<
               ", AudioFormat: "               << sAudioFormat <<
               ", FramesPerCallback: "         << sFramesPerCallback << "]";
}

void CSound::warnIfNotLowLatency ( oboe::ManagedStream& stream,
                                   QString              streamName )
{
    if ( stream->getPerformanceMode() != oboe::PerformanceMode::LowLatency )
    {
        QString latencyMode = ( stream->getPerformanceMode() == oboe::PerformanceMode::None ? "None" : "Power Saving" );
    }
}

void CSound::closeStreams()
{
    // clean up
    closeStream ( mRecordingStream );
    closeStream ( mPlayStream );
}

void CSound::Start()
{
    openStreams();

    // call base class
    CSoundBase::Start();

    // finally start the streams so the callback begins, start with inputstream first.
    mRecordingStream->requestStart();
    mPlayStream->requestStart();
}

void CSound::Stop()
{
    closeStreams();

    // call base class
    CSoundBase::Stop();
}

int CSound::Init ( const int iNewPrefMonoBufferSize )
{
    // store buffer size
    iOboeBufferSizeMono = iNewPrefMonoBufferSize; // 512

    // init base class
    CSoundBase::Init ( iOboeBufferSizeMono );

    // set internal buffer size value and calculate stereo buffer size
    iOboeBufferSizeStereo = 2 * iOboeBufferSizeMono;

    // create memory for intermediate audio buffer
    vecsTmpInputAudioSndCrdStereo.Init ( iOboeBufferSizeStereo );
    mOutBuffer.reset ( iOboeBufferSizeStereo * RING_FACTOR );

    return iOboeBufferSizeMono;
}

// This is the main callback method for when an audio stream is ready to publish data to an output stream
// or has received data on an input stream. As per manual much be very careful not to do anything in this back that
// can cause delays such as sleeping, file processing, allocate memory, etc.
oboe::DataCallbackResult CSound::onAudioReady ( oboe::AudioStream* oboeStream,
                                                void*              audioData,
                                                int32_t            numFrames )
{
    // only process if we are running
    if ( !bRun )
    {
        return oboe::DataCallbackResult::Continue;
    }

    if ( mStats.in_callback_calls % 1000 == 0 )
    {
        mStats.log();
    }

    if ( oboeStream == mRecordingStream.get() && audioData )
    {
        return onAudioInput(oboeStream, audioData, numFrames);
    }

    if ( oboeStream == mPlayStream.get() && audioData)
    {
        return onAudioOutput(oboeStream, audioData, numFrames);
    }

    return oboe::DataCallbackResult::Continue;
}

oboe::DataCallbackResult CSound::onAudioInput ( oboe::AudioStream* oboeStream, void* audioData, int32_t numFrames )
{
    mStats.in_callback_calls++;

    // First things first, we need to discard the input queue a little for 500ms or so
    if ( mCountCallbacksToDrain > 0 )
    {
        // discard the input buffer
        int32_t numBytes = numFrames * oboeStream->getBytesPerFrame();

        memset ( audioData, 0 /* value */, numBytes );

        mCountCallbacksToDrain--;
    }

    // We're good to start recording now
    // Take the data from the recording device output buffer and move
    // it to the vector ready to send up to the server
    float* floatData = static_cast<float*> ( audioData );

    // Copy recording data to internal vector
    for ( int frmNum = 0; frmNum < numFrames; ++frmNum )
    {
        for ( int channelNum = 0; channelNum < oboeStream->getChannelCount(); channelNum++ )
        {
            vecsTmpInputAudioSndCrdStereo[frmNum * oboeStream->getChannelCount() + channelNum] =
                static_cast<int16_t>(floatData[frmNum * oboeStream->getChannelCount() + channelNum] * _MAXSHORT);
        }
    }

    if ( numFrames != iOboeBufferSizeMono )
    {
        qDebug() << "Received " << numFrames << " expecting " << iOboeBufferSizeMono;
    }

    mStats.frames_in += numFrames;

    // Tell parent class that we've put some data ready to send to the server
    ProcessCallback ( vecsTmpInputAudioSndCrdStereo  );

    // The callback has placed in the vector the samples to play
    addOutputData(oboeStream->getChannelCount());

    return oboe::DataCallbackResult::Continue;
}

void CSound::addOutputData(int channel_count)
{
    QMutexLocker locker ( &MutexAudioProcessCallback );

    // Only copy data if we have data to copy, otherwise fill with silence
    if ( !vecsTmpInputAudioSndCrdStereo.empty() )
    {
        for ( int frmNum = 0; frmNum < iOboeBufferSizeMono; ++frmNum )
        {
            for ( int channelNum = 0; channelNum < channel_count; channelNum++ )
            {
                // copy sample received from server into output buffer

                // convert to 32 bit
                const int32_t iCurSam = static_cast<int32_t> (
                    vecsTmpInputAudioSndCrdStereo[frmNum * channel_count+ channelNum] );

                mOutBuffer.put ( ( static_cast<float> ( iCurSam ) ) / _MAXSHORT );
            }
        }
    }
    else
    {
        // prime output stream buffer with silence
        for ( int frmNum = 0; frmNum < iOboeBufferSizeMono; ++frmNum )
        {
            for ( int channelNum = 0; channelNum < channel_count; channelNum++ )
            {
                mOutBuffer.put ( 0 );
            }
        }
    }

    if ( mOutBuffer.isFull() )
    {
        mStats.ring_overrun++;
    }
}

oboe::DataCallbackResult CSound::onAudioOutput ( oboe::AudioStream* oboeStream,
                                                 void*              audioData,
                                                 int32_t            numFrames )
{
    mStats.frames_out += numFrames;
    mStats.out_callback_calls++;

    QMutexLocker locker ( &MutexAudioProcessCallback );

    std::size_t to_write = numFrames*oboeStream->getChannelCount();
    std::size_t count    = std::min ( mOutBuffer.size(), to_write );

    mOutBuffer.get ( (float*) audioData, count );

    if ( to_write > count )
    {
        mStats.frames_filled_out += ( to_write - count );
        memset ( ( (float*) audioData ) + count, 0, ( to_write - count ) * sizeof ( float ) );
    }

    return oboe::DataCallbackResult::Continue;
}

// TODO better handling of stream closing errors
void CSound::onErrorAfterClose ( oboe::AudioStream* oboeStream,
                                 oboe::Result       result )
{
    qDebug() << "CSound::onErrorAfterClose";
}

// TODO better handling of stream closing errors
void CSound::onErrorBeforeClose ( oboe::AudioStream* oboeStream,
                                  oboe::Result       result )
{
    qDebug() << "CSound::onErrorBeforeClose";
}

void CSound::Stats::reset() 
{
    frames_in          = 0;
    frames_out         = 0;
    frames_filled_out  = 0;
    in_callback_calls  = 0;
    out_callback_calls = 0;
    ring_overrun       = 0;
}

void CSound::Stats::log() const 
{
    qDebug() << "Stats: "
             << "frames_in: " << frames_in
             << ",frames_out: " << frames_out
             << ",frames_filled_out: " << frames_filled_out
             << ",in_callback_calls: " << in_callback_calls
             << ",out_callback_calls: " << out_callback_calls
             << ",ring_overrun: " << ring_overrun;
}