audiolayer.cpp 12.8 KB
Newer Older
jpbl's avatar
jpbl committed
1
2
3
4
/*
 *  Copyright (C) 2005 Savoir-Faire Linux inc.
 *  Author: Yan Morin <yan.morin@savoirfairelinux.com>
 *  Author: Jerome Oufella <jerome.oufella@savoirfairelinux.com> 
5
 *  Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com>
jpbl's avatar
jpbl committed
6
7
8
 *
 *  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
9
 *  the Free Software Foundation; either version 3 of the License, or
jpbl's avatar
jpbl committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 *  (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., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <stdio.h>
#include <stdlib.h>

#include "audiolayer.h"
#include "../global.h"
#include "../manager.h"

29
30
31
32
33
34
35
36
//#define SFL_TEST
//#define SFL_TEST_SINE

#ifdef SFL_TEST_SINE
#include <cmath>
#endif

AudioLayer::AudioLayer(ManagerImpl* manager)
jpbl's avatar
jpbl committed
37
38
39
  : _urgentRingBuffer(SIZEBUF)
  , _mainSndRingBuffer(SIZEBUF)
  , _micRingBuffer(SIZEBUF)
40
  , _defaultVolume(100)
jpbl's avatar
jpbl committed
41
42
  , _stream(NULL)
  , _errorMessage("")
43
  , _manager(manager)
jpbl's avatar
jpbl committed
44
45
{
  _sampleRate = 8000;
yanmorin's avatar
yanmorin committed
46
  
47
48
  _inChannel  = 1; // don't put in stereo
  _outChannel = 1; // don't put in stereo
49
  _echoTesting = false;
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

  try {
     portaudio::AutoSystem autoSys;
     portaudio::System::initialize();
  }
  catch (const portaudio::PaException &e) {
    setErrorMessage(e.paErrorText());
  }
  catch (const portaudio::PaCppException &e) {
    setErrorMessage(e.what());
  } // std::runtime_error &e     (e.what())
  catch (...) {
    setErrorMessage("Unknown type error in portaudio initialization");
  }

#ifdef SFL_TEST_SINE
  leftPhase_ = 0;
  tableSize_ = 200;
  const double PI = 3.14159265;
  table_ = new float[tableSize_];
  for (int i = 0; i < tableSize_; ++i)
  {
    table_[i] = 0.125f * (float)sin(((double)i/(double)tableSize_)*PI*2.);
    _debug("%9.8f\n", table_[i]);
  }
#endif
jpbl's avatar
jpbl committed
76
77
78
79
}

// Destructor
AudioLayer::~AudioLayer (void) 
80
81
82
83
{ 
  stopStream();
  closeStream();

jpbl's avatar
jpbl committed
84
85
86
  try {
    portaudio::System::terminate();
  } catch (const portaudio::PaException &e) {
87
    _debug("! AL: Catch an exception when portaudio tried to terminate\n");
jpbl's avatar
jpbl committed
88
  }
89
90
91
#ifdef SFL_TEST_SINE
  delete [] table_;
#endif
jpbl's avatar
jpbl committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
}

void
AudioLayer::closeStream (void) 
{
  ost::MutexLock guard(_mutex);
  if(_stream) {
    _stream->close();
    delete _stream; _stream = NULL;
  }
}

bool
AudioLayer::hasStream(void) {
  ost::MutexLock guard(_mutex);
  return (_stream!=0 ? true : false); 
}


void
112
AudioLayer::openDevice (int indexIn, int indexOut, int sampleRate, int frameSize) 
jpbl's avatar
jpbl committed
113
114
115
{
  closeStream();

116
  _sampleRate = sampleRate;
117
  _frameSize = frameSize;	
118
  int portaudioFramePerBuffer = FRAME_PER_BUFFER; //=FRAME_PER_BUFFER; //= paFramesPerBufferUnspecified;
119
120
  //int portaudioFramePerBuffer = (int) (8000 * frameSize / 1000); 
//= paFramesPerBufferUnspecified;
121
122
123
124
125
126

  int nbDevice = getDeviceCount();
  if (nbDevice == 0) {
    _debug("Portaudio detect no sound card.");
    return;
  } else {
yanmorin's avatar
yanmorin committed
127
128
129
130
131
132
133
134
135
//    not good, 
//    if (indexIn >= nbDevice) {
//      _debug(" Portaudio auto-select device #0 for input because device #%02d is not found\n", indexIn);
//      indexIn = 0;
//    }
//    if (indexOut >= nbDevice) {
//      _debug(" Portaudio auto-select device #0 for output because device #%02d is not found\n", indexOut);
//      indexOut = 0;
//    }
136
137
138
139
140
141
142

    _debug(" Setting audiolayer: device     in=%2d, out=%2d\n", indexIn, indexOut);
    _debug("                   : nb channel in=%2d, out=%2d\n", _inChannel, _outChannel);
    _debug("                   : sample rate=%5d, format=%s\n", _sampleRate, SFLPortaudioFormatString);
    _debug("                   : frame per buffer=%d\n", portaudioFramePerBuffer);
  }

jpbl's avatar
jpbl committed
143
  try {
144
145
146
147
    // Set up the parameters required to open a (Callback)Stream:
    portaudio::DirectionSpecificStreamParameters 
      inParams(portaudio::System::instance().deviceByIndex(indexIn), 
	     _inChannel, SFLPortaudioFormat, true, 
jpbl's avatar
jpbl committed
148
149
	     portaudio::System::instance().deviceByIndex(indexIn).defaultLowInputLatency(), 
	     NULL);
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

     portaudio::DirectionSpecificStreamParameters outParams(
                portaudio::System::instance().deviceByIndex(indexOut), 
	        _outChannel, SFLPortaudioFormat, true, 
	        portaudio::System::instance().deviceByIndex(indexOut).defaultLowOutputLatency(), 
	        NULL);

    // like audacity
    // DON'T USE paFramesPerBufferUnspecified, it's 32, instead of 160 for FRAME_PER_BUFFER
    // DON'T USE paDitherOff or paClipOff, 
    // FRAME_PER_BUFFER | paFramesPerBufferUnspecified
    // paNoFlag | paClipOff || paDitherOff | paPrimeOutputBuffersUsingStreamCallback | paNeverDropInput
     
    portaudio::StreamParameters const params(
		inParams,
		outParams, 
		_sampleRate, portaudioFramePerBuffer, paClipOff);
		
    // Create (and open) a new Stream, using the AudioLayer::audioCallback
    ost::MutexLock guard(_mutex);
#ifdef SFL_TEST
    _stream = new portaudio::MemFunCallbackStream<AudioLayer>(params, *this, &AudioLayer::miniAudioCallback);
#else
    _stream = new portaudio::MemFunCallbackStream<AudioLayer>(params,*this, &AudioLayer::audioCallback);
#endif
 
  }
  catch (const portaudio::PaException &e) {
    setErrorMessage(e.paErrorText());
    _debug("Portaudio openDevice error: %s\n", e.paErrorText());
jpbl's avatar
jpbl committed
180
  }
181
182
183
184
185
186
187
188
189
  catch (const portaudio::PaCppException &e) {
    setErrorMessage(e.what());
    _debug("Portaudio openDevice error: %s\n", e.what());
  } // std::runtime_error &e     (e.what())
  catch (...) {
    setErrorMessage("Unknown type error in portaudio openDevice");
    _debug("Portaudio openDevice: unknown error\n");
  }

jpbl's avatar
jpbl committed
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
int
AudioLayer::getDeviceCount()
{
  return portaudio::System::instance().deviceCount();
}

AudioDevice*
AudioLayer::getAudioDeviceInfo(int index, int ioDeviceMask)
{

  try {
    portaudio::System& sys = portaudio::System::instance();
    portaudio::Device& device = sys.deviceByIndex(index);
    int deviceIsSupported = false;

    if (ioDeviceMask == InputDevice && !device.isOutputOnlyDevice()) {
      deviceIsSupported = true;
    } else if (ioDeviceMask == OutputDevice && !device.isInputOnlyDevice()) {
      deviceIsSupported = true;
    } else if (device.isFullDuplexDevice()) {
      deviceIsSupported = true;
    }

    if (deviceIsSupported) {
      AudioDevice* audiodevice = new AudioDevice(index, device.hostApi().name(), device.name());
      if (audiodevice) {
        audiodevice->setRate(device.defaultSampleRate());
      }
      return audiodevice;
    }
  } catch (...) {
    return 0;
  }
  return 0;
}



jpbl's avatar
jpbl committed
230
231
232
233
234
235
void
AudioLayer::startStream(void) 
{
  try {
    ost::MutexLock guard(_mutex);
    if (_stream && !_stream->isActive()) {
236
        _debug("- AL Action: Starting sound stream\n");
jpbl's avatar
jpbl committed
237
        _stream->start();
238
    } else { 
239
      _debug ("* AL Info: Stream doesn't exist or is already active\n");
240
    }
jpbl's avatar
jpbl committed
241
  } catch (const portaudio::PaException &e) {
242
    _debugException("! AL: Portaudio error: error on starting audiolayer stream");
jpbl's avatar
jpbl committed
243
244
    throw;
  } catch(...) {
245
    _debugException("! AL: Stream start error");
jpbl's avatar
jpbl committed
246
247
248
249
250
251
252
    throw;
  }
}
	
void
AudioLayer::stopStream(void) 
{
253
  _debug("- AL Action: Stopping sound stream\n");
jpbl's avatar
jpbl committed
254
255
256
257
258
259
260
261
262
  try {
    ost::MutexLock guard(_mutex);
    if (_stream && !_stream->isStopped()) {
      _stream->stop();
      _mainSndRingBuffer.flush();
      _urgentRingBuffer.flush();
      _micRingBuffer.flush();
    }
  } catch (const portaudio::PaException &e) {
263
    _debugException("! AL: Portaudio error: stoping audiolayer stream failed");
jpbl's avatar
jpbl committed
264
265
    throw;
  } catch(...) {
266
    _debugException("! AL: Stream stop error");
jpbl's avatar
jpbl committed
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
    throw;
  }
}

void
AudioLayer::sleep(int msec) 
{
  if (_stream) {
    portaudio::System::instance().sleep(msec);
  }
}

bool
AudioLayer::isStreamActive (void) 
{
  ost::MutexLock guard(_mutex);
283
284
285
286
287
  try {
    if(_stream && _stream->isActive()) {
      return true;
    }
  } catch (const portaudio::PaException &e) {
288
      _debugException("! AL: Portaudio error: isActive returned an error");
jpbl's avatar
jpbl committed
289
  }
290
  return false;
jpbl's avatar
jpbl committed
291
292
293
294
295
296
297
298
299
}

int 
AudioLayer::putMain(void* buffer, int toCopy)
{
  ost::MutexLock guard(_mutex);
  if (_stream) {
    int a = _mainSndRingBuffer.AvailForPut();
    if ( a >= toCopy ) {
300
      return _mainSndRingBuffer.Put(buffer, toCopy, _defaultVolume);
jpbl's avatar
jpbl committed
301
    } else {
302
303
      _debug("Chopping sound, Ouch! RingBuffer full ?\n");
      return _mainSndRingBuffer.Put(buffer, a, _defaultVolume);
jpbl's avatar
jpbl committed
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
    }
  }
  return 0;
}

void
AudioLayer::flushMain()
{
  ost::MutexLock guard(_mutex);
  _mainSndRingBuffer.flush();
}

int
AudioLayer::putUrgent(void* buffer, int toCopy)
{
319
  ost::MutexLock guard(_mutex);
jpbl's avatar
jpbl committed
320
321
322
  if (_stream) {
    int a = _urgentRingBuffer.AvailForPut();
    if ( a >= toCopy ) {
323
      return _urgentRingBuffer.Put(buffer, toCopy, _defaultVolume);
jpbl's avatar
jpbl committed
324
    } else {
325
      return _urgentRingBuffer.Put(buffer, a, _defaultVolume);
jpbl's avatar
jpbl committed
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
    }
  }
  return 0;
}

int
AudioLayer::canGetMic()
{
  if (_stream) {
    return _micRingBuffer.AvailForGet();
  } else {
    return 0;
  }
}

int 
AudioLayer::getMic(void *buffer, int toCopy)
{
  if(_stream) {
    return _micRingBuffer.Get(buffer, toCopy, 100);
  } else {
    return 0;
  }
}

void
AudioLayer::flushMic()
{
  _micRingBuffer.flush();
}

bool
AudioLayer::isStreamStopped (void) 
{
  ost::MutexLock guard(_mutex);
361
362
363
364
365
  try {
    if(_stream && _stream->isStopped()) {
      return true;
    }
  } catch (const portaudio::PaException &e) {
366
      _debugException("! AL: Portaudio error: isStopped returned an exception");
jpbl's avatar
jpbl committed
367
  }
368
  return false;
jpbl's avatar
jpbl committed
369
370
}

371
372
373
374
375
376
void
AudioLayer::toggleEchoTesting() {
  ost::MutexLock guard(_mutex);
  _echoTesting = (_echoTesting == true) ? false : true;
}

jpbl's avatar
jpbl committed
377
378
379
380
381
382
383
384
385
int 
AudioLayer::audioCallback (const void *inputBuffer, void *outputBuffer, 
			   unsigned long framesPerBuffer, 
			   const PaStreamCallbackTimeInfo *timeInfo, 
			   PaStreamCallbackFlags statusFlags) {

  (void) timeInfo;
  (void) statusFlags;
	
386
387
  SFLDataFormat *in  = (SFLDataFormat *) inputBuffer;
  SFLDataFormat *out = (SFLDataFormat *) outputBuffer;
388
389
390
391
392
393

  if (_echoTesting) {
    memcpy(out, in, framesPerBuffer*sizeof(SFLDataFormat));
    return paContinue;
  }

yanmorin's avatar
   
yanmorin committed
394
395
  int toGet; 
  int toPut;
396
397
  int urgentAvail; // number of data right and data left
  int normalAvail; // number of data right and data left
yanmorin's avatar
   
yanmorin committed
398
  int micAvailPut;
399
400
  unsigned short spkrVolume = _manager->getSpkrVolume();
  unsigned short micVolume  = _manager->getMicVolume();
jpbl's avatar
jpbl committed
401
402

  // AvailForGet tell the number of chars inside the buffer
403
  // framePerBuffer are the number of data for one channel (left)
jpbl's avatar
jpbl committed
404
405
  urgentAvail = _urgentRingBuffer.AvailForGet();
  if (urgentAvail > 0) {
406
    // Urgent data (dtmf, incoming call signal) come first.		
407
    toGet = (urgentAvail < (int)(framesPerBuffer * sizeof(SFLDataFormat))) ? urgentAvail : framesPerBuffer * sizeof(SFLDataFormat);
jpbl's avatar
jpbl committed
408
409
410
    _urgentRingBuffer.Get(out, toGet, spkrVolume);
    // Consume the regular one as well (same amount of bytes)
    _mainSndRingBuffer.Discard(toGet);
411
412
  } else {
    AudioLoop* tone = _manager->getTelephoneTone();
jpbl's avatar
jpbl committed
413
    if ( tone != 0) {
414
415
416
      tone->getNext(out, framesPerBuffer, spkrVolume);
    } else if ( (tone=_manager->getTelephoneFile()) != 0 ) {
      tone->getNext(out, framesPerBuffer, spkrVolume);
jpbl's avatar
jpbl committed
417
418
419
    } else {
      // If nothing urgent, play the regular sound samples
      normalAvail = _mainSndRingBuffer.AvailForGet();
420
      toGet = (normalAvail < (int)(framesPerBuffer * sizeof(SFLDataFormat))) ? normalAvail : framesPerBuffer * sizeof(SFLDataFormat);
jpbl's avatar
jpbl committed
421
422
423
424

      if (toGet) {
        _mainSndRingBuffer.Get(out, toGet, spkrVolume);
      } else {
425
        bzero(out, framesPerBuffer * sizeof(SFLDataFormat));
jpbl's avatar
jpbl committed
426
427
      }
    }
yanmorin's avatar
   
yanmorin committed
428
  }
jpbl's avatar
jpbl committed
429

yanmorin's avatar
   
yanmorin committed
430
  // Additionally handle the mic's audio stream 
jpbl's avatar
jpbl committed
431
  micAvailPut = _micRingBuffer.AvailForPut();
432
  toPut = (micAvailPut <= (int)(framesPerBuffer * sizeof(SFLDataFormat))) ? micAvailPut : framesPerBuffer * sizeof(SFLDataFormat);
yanmorin's avatar
yanmorin committed
433
  //_debug("AL: Nb sample: %d char, [0]=%f [1]=%f [2]=%f\n", toPut, in[0], in[1], in[2]);
434
  _micRingBuffer.Put(in, toPut, micVolume);
jpbl's avatar
jpbl committed
435
436
437
438

  return paContinue;
}

439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
int 
AudioLayer::miniAudioCallback (const void *inputBuffer, void *outputBuffer, 
			   unsigned long framesPerBuffer, 
			   const PaStreamCallbackTimeInfo *timeInfo, 
			   PaStreamCallbackFlags statusFlags) {
  (void) timeInfo;
  (void) statusFlags;
	
 _debug("mini audio callback!!\n");
#ifdef SFL_TEST_SINE
  assert(outputBuffer != NULL);

  float *out = static_cast<float *>(outputBuffer);
  for (unsigned int i = 0; i < framesPerBuffer; ++i) {
    out[i] = table_[leftPhase_];
    leftPhase_ += 1;
    if (leftPhase_ >= tableSize_) {
      leftPhase_ -= tableSize_;
jpbl's avatar
jpbl committed
457
458
    }
  }
459
460
461
462
463
464
465
466
#else
  SFLDataFormat *out = (SFLDataFormat *) outputBuffer;
  AudioLoop* tone = _manager->getTelephoneTone();
  if ( tone != 0) {
    //_debug("Frames Per Buffer: %d\n", framesPerBuffer);
    tone->getNext(out, framesPerBuffer, 100);
  }
#endif
jpbl's avatar
jpbl committed
467

468
469
  return paContinue;
}