void quisk_start_sound_portaudio(struct sound_dev * pCapture, struct sound_dev * pPlayback,
		struct sound_dev * pMicCapture, struct sound_dev * pMicPlayback)
{
	int index, err;

	Pa_Initialize();
	// Set the portaudio index from the name; or set -1.  Return on error.
	if (quisk_pa_name2index (pCapture, 1))
		return;		// Error
	if (quisk_pa_name2index (pPlayback, 0))
		return;
	if (quisk_pa_name2index (pMicCapture, 1))
		return;
	if (quisk_pa_name2index (pMicPlayback, 0))
		return;

	// Open the sound cards
	index = pCapture->portaudio_index;
	if (index >= 0) {		// This is a portaudio device
		if (pPlayback->portaudio_index == index)			// same device
			err = quisk_open_portaudio (pCapture, pPlayback);
		else if (pMicPlayback->portaudio_index == index)	// same device
			err = quisk_open_portaudio (pCapture, pMicPlayback);
		else
			err = quisk_open_portaudio (pCapture, NULL);		// no matching device
		if (err)
			return;		// error
		strncpy (quisk_sound_state.msg1, pCapture->msg1, QUISK_SC_SIZE);
	}
	index = pMicCapture->portaudio_index;
	if (index >= 0) {		// This is a portaudio device
		if (pPlayback->portaudio_index == index)			// same device
			err = quisk_open_portaudio (pMicCapture, pPlayback);
		else if (pMicPlayback->portaudio_index == index)	// same device
			err = quisk_open_portaudio (pMicCapture, pMicPlayback);
		else
			err = quisk_open_portaudio (pMicCapture, NULL);		// no matching device
		if (err)
			return;		// error
	}
	// Open remaining portaudio devices
	if (pPlayback->portaudio_index >= 0 && ! pPlayback->handle) {
		if (quisk_open_portaudio (NULL, pPlayback))
			return;		// error
        if ( ! quisk_sound_state.msg1[0])
			strncpy (quisk_sound_state.msg1, pPlayback->msg1, QUISK_SC_SIZE);
	}
	if (pMicPlayback->portaudio_index >= 0 && ! pMicPlayback->handle)
		if (quisk_open_portaudio (NULL, pMicPlayback))
			return;		// error
	if (pCapture->handle)
		Pa_StartStream((PaStream * )pCapture->handle);
	if (pMicCapture->handle)
		Pa_StartStream((PaStream * )pMicCapture->handle);
	if (pPlayback->handle && Pa_IsStreamStopped((PaStream * )pPlayback->handle))
		Pa_StartStream((PaStream * )pPlayback->handle);
	if (pMicPlayback->handle && Pa_IsStreamStopped((PaStream * )pMicPlayback->handle))
		Pa_StartStream((PaStream * )pMicPlayback->handle);
}
Exemple #2
0
bool	audioSink::selectDevice (int16_t odev) {
PaError err;
	fprintf (stderr, "select device with %d\n", odev);
	if (!isValidDevice (odev))
	   return false;

	if ((ostream != NULL) && !Pa_IsStreamStopped (ostream)) {
	   paCallbackReturn = paAbort;
	   (void) Pa_AbortStream (ostream);
	   while (!Pa_IsStreamStopped (ostream))
	      Pa_Sleep (1);
	   writerRunning = false;
	}

	if (ostream != NULL)
	   Pa_CloseStream (ostream);

	outputParameters. device		= odev;
	outputParameters. channelCount		= 2;
	outputParameters. sampleFormat		= paFloat32;
	outputParameters. suggestedLatency	= 
	                          Pa_GetDeviceInfo (odev) ->
	                                      defaultHighOutputLatency * 6;
//	bufSize	= (int)((float)outputParameters. suggestedLatency);
	bufSize	= 80 * 256;

//	if (bufSize < 0 || bufSize > 17300)
//	   bufSize = 16384;

	outputParameters. hostApiSpecificStreamInfo = NULL;
//
	fprintf (stderr, "Suggested size for outputbuffer = %d\n", bufSize);
	err = Pa_OpenStream (
	             &ostream,
	             NULL,
	             &outputParameters,
	             48000,
	             bufSize,
	             0,
	             this	-> paCallback_o,
	             this
	      );

	if (err != paNoError) {
	   qDebug ("Open ostream error\n");
	   return false;
	}
	fprintf (stderr, "stream opened\n");
	paCallbackReturn = paContinue;
	err = Pa_StartStream (ostream);
	if (err != paNoError) {
	   qDebug ("Open startstream error\n");
	   return false;
	}
	fprintf (stderr, "stream started\n");
	writerRunning	= true;
	return true;
}
Exemple #3
0
void	paWriter::stopWriter	(void) {
	if (Pa_IsStreamStopped (ostream))
	   return;

	paCallbackReturn	= paAbort;
	(void)Pa_StopStream	(ostream);
	while (!Pa_IsStreamStopped (ostream))
	   Pa_Sleep (1);
	writerRunning		= false;
}
Exemple #4
0
bool PortAudioSystem::stopStream(PaStream *stream) {
	PaError err;

	if (!stream) {
		qWarning("PortAudioSystem: NULL PaStream passed to stopStream()");
		return false;
	}

	err = Pa_IsStreamStopped(stream);
	if (err == 1) { // stream already stopped
		return true;
	} else if (err != 0) { // some error, 0 means "running"
		qCritical("PortAudioSystem: Could not determine status of PortAudio stream, error %s", Pa_GetErrorText(err));
		return false;
	}

	err = Pa_StopStream(stream);
	if (err != paNoError) {
		qWarning("PortAudioSystem: Could not stop PortAudio stream, error %s",Pa_GetErrorText(err));
		return false;
	}

	//qWarning() << "PortAudioSystem::stopStream(); stopped stream" << stream ;
	return true;
}
bool AudioOutputPortAudio::write()
{
    DPTR_D(AudioOutputPortAudio);
    QMutexLocker lock(&d.mutex);
    Q_UNUSED(lock);
    if (!d.available)
        return false;
    if (Pa_IsStreamStopped(d.stream))
        Pa_StartStream(d.stream);
#if KNOW_WHY
#ifndef Q_OS_MAC //?
    int diff = Pa_GetStreamWriteAvailable(d.stream) - d.outputLatency * d.sample_rate;
    if (diff > 0) {
        int newsize = diff * d.channels * sizeof(float);
        static char *a = new char[newsize];
        memset(a, 0, newsize);
        Pa_WriteStream(d.stream, a, diff);
    }
#endif
#endif //KNOW_WHY
    PaError err = Pa_WriteStream(d.stream, d.data.constData(), d.data.size()/audioFormat().channels()/audioFormat().bytesPerSample());
    if (err == paUnanticipatedHostError) {
        qWarning("Write portaudio stream error: %s", Pa_GetErrorText(err));
        return   false;
    }
    return true;
}
RTC::ReturnCode_t PortAudioInput::onFinalize()
{
  RTC_DEBUG(("onFinalize start"));
  is_active = false;
  m_mutex.lock();
  RTC_DEBUG(("onFinalize:mutex lock"));
  try {
    m_out_dataOut.deactivateInterfaces();
    if ( m_stream ) {
      if ( !Pa_IsStreamStopped( m_stream ) ) {
        m_err = Pa_AbortStream( m_stream );
        if ( m_err != paNoError ) {
          throw m_err;
        }
      }

      m_err = Pa_CloseStream( m_stream );
      if ( m_err != paNoError ) {
        throw m_err;
      }
      m_stream = NULL;
    }
  } catch (...) {
    std::string error_str = Pa_GetErrorText(m_err);
    RTC_WARN(("PortAudio Stream close failed onFinalize:%s", error_str.c_str()));
    return RTC::RTC_ERROR;
  }
  m_mutex.unlock();
  RTC_DEBUG(("onFinalize:mutex unlock"));
  RTC_DEBUG(("onFinalize finish"));
  return RTC::RTC_OK;
}
Exemple #7
0
_BOOLEAN
CPaCommon::Write(CVector < short >&psData)
{
    if (device_changed)
        ReInit();

    if (stream==NULL)
        return TRUE;

    size_t bytes = psData.Size() * sizeof(short);

    //cout << "Write: got " << bytes << " can put " << PaUtil_GetRingBufferWriteAvailable(&ringBuffer) << endl;
    if (PaUtil_GetRingBufferWriteAvailable(&ringBuffer) < int(bytes))
        return FALSE;			/* TODO use newer data in preference to draining old */

    PaUtil_WriteRingBuffer(&ringBuffer, &psData[0], bytes);
    if (Pa_IsStreamStopped( stream ))
    {
        int err = Pa_StartStream(stream);
        if (err != paNoError) {
            //throw string("PortAudio error: ") + Pa_GetErrorText(err);
		}
    }
    if (xruns==0)
        return FALSE;
    else
        cout << "underrun" << endl;
    xruns = 0;
    return TRUE;
}
bool play(QString *reason)
{
    try
    {
        // when playing throws by the paComplite(paAbort) we should correct
        // call the Pa_StopStream, otherwise we cannot start plaing the stream
        // again
        if (Pa_IsStreamActive(stream) == 0 && Pa_IsStreamStopped(stream) == 0)
        {
            PaError err = Pa_StopStream(stream);
            if (err != paNoError)
                throw QString(Pa_GetErrorText(err));
        }

        PaError err = Pa_StartStream(stream);
        if (err != paNoError)
            throw QString(Pa_GetErrorText(err));

        return true;
    }
    catch (const QString &error)
    {
        if (reason)
            *reason = error;
    }

    return false;
}
Exemple #9
0
_JATTA_EXPORT bool Jatta::PortAudio::Stream::IsStopped()
{
    if (Pa_IsStreamStopped(stream) == 1)
    {
        return true;
    }
    return false;
}
Exemple #10
0
_CGUL_EXPORT bool CGUL::PortAudio::Stream::IsStopped()
{
    if (Pa_IsStreamStopped(stream) == 1)
    {
        return true;
    }
    return false;
}
Exemple #11
0
	paWriter::~paWriter	(void) {
	if ((ostream != NULL) && !Pa_IsStreamStopped (ostream)) {
	   paCallbackReturn = paAbort;
	   (void) Pa_AbortStream (ostream);
	   while (!Pa_IsStreamStopped (ostream))
	      Pa_Sleep (1);
	   writerRunning = false;
	}

	if (ostream != NULL)
	   Pa_CloseStream (ostream);

	if (portAudio)
	   Pa_Terminate ();

	delete	_O_Buffer;
}
Exemple #12
0
//check for mem leaks - will this free all chainlinks associated with a chain?
int removeChain(int chainIndex)
{
	if(rootChain == NULL){
		//this totally shouldn't happen but I'll keep it here for debug purposes
		printf("rootChain is null!?\n");
		return -1;
	}
	Chain* chainToRemove = rootChain;
	int i;
	
	//start by removing all chainLinks from the chain to free memory
	ChainLink * chainLinkIterator = chainToRemove->chainLink;
	i = 0;
	while(chainLinkIterator->nextLink != NULL){
		chainLinkIterator = chainLinkIterator->nextLink;
		i++;
	}
	int j;
	for(j = i; j >= 0; j--){
		fprintf(stderr, "in for loop, removing link %d \n", j);
		removeChainLink(chainIndex, j);
	}
	
	//if root chain: 
	if(chainIndex == 0){
		//if next chain exists:
		if(chainToRemove->nextChain != NULL){
		//set root chain to next chain
			rootChain = chainToRemove->nextChain;
		}
		else{
			rootChain = NULL;
		}
	}
	else{
		Chain* preChainToRemove;
		for(i = 0; i < chainIndex; i++){
			preChainToRemove = chainToRemove;
			chainToRemove = chainToRemove->nextChain;
		}
		preChainToRemove->nextChain = chainToRemove->nextChain;
	}
	if(chainToRemove == NULL){
		//this totally shouldn't happen but I'll keep it here for debug purposes
		printf("chainToRemove was null!\n");
		return -1;
	}
	
	Pa_StopStream(chainToRemove->stream);
	//this returns 1 when stream is still active
	while(Pa_IsStreamStopped(chainToRemove->stream) != 1){
		//do nothing; block until stream is finished
	}
	Pa_CloseStream(chainToRemove->stream);
	
	free(chainToRemove);
	return 0;
}
Exemple #13
0
// stops the portaudio stream
int PortAudioSound::StopStream()
{
	int ierr = paNoError;
	if (!Pa_IsStreamStopped(pStream)){
		ierr = Pa_StopStream(pStream);
		error(ierr);
		logFile.WriteString(L"Stream stopped\n");
	}
	return ierr;
}
Exemple #14
0
audioSink::~audioSink	(void) {
    if ((ostream != NULL) && !Pa_IsStreamStopped (ostream)) {
        paCallbackReturn = paAbort;
        (void) Pa_AbortStream (ostream);
        while (!Pa_IsStreamStopped (ostream))
            Pa_Sleep (1);
        writerRunning = false;
    }

    if (ostream != NULL)
        Pa_CloseStream (ostream);

    if (portAudio)
        Pa_Terminate ();

    delete	_O_Buffer;
    delete[] outTable;
    streamSelector	-> hide ();
}
Exemple #15
0
	~portaudio_stream_blocking_raii() {
		if ( stream ) {
			PaError stopped = Pa_IsStreamStopped( stream );
			check_portaudio_error( stopped );
			if ( !stopped ) {
				check_portaudio_error( Pa_StopStream( stream ) );
			}
			check_portaudio_error( Pa_CloseStream( stream ) );
			stream = NULL;
		}
	}
Exemple #16
0
void	audioSink::restart	(void) {
PaError err;

	if (!Pa_IsStreamStopped (ostream))
	   return;

	_O_Buffer	-> FlushRingBuffer ();
	paCallbackReturn = paContinue;
	err = Pa_StartStream (ostream);
	if (err == paNoError)
	   writerRunning	= true;
}
Exemple #17
0
bool CCPortAudio::write()
{
	DPTR_D(CCPortAudio);
	if (Pa_IsStreamStopped(d.stream))
		Pa_StartStream(d.stream);

	PaError err = Pa_WriteStream(d.stream, d.data.data(), d.data.size() / d.channels / sizeof(float));
	if (err == paUnanticipatedHostError) {
		qWarning("Write portaudio stream error: %s", Pa_GetErrorText(err));
		return false;
	}
	return true;
}
Exemple #18
0
bool	paWriter::restartWriter	(void) {
PaError err;

	if (!Pa_IsStreamStopped (ostream))
	   return true;

	paCallbackReturn = paContinue;
	err = Pa_StartStream (ostream);
	if (err == paNoError)
	   writerRunning	= true;

	return writerRunning;
}
Exemple #19
0
void PortAudioDriver::stop(bool refreshDevicesList){
    if (paStream != NULL){
        if (!Pa_IsStreamStopped(paStream)){
            qCDebug(jtAudio) << "closing portaudio stream";
            PaError error = Pa_CloseStream(paStream);
            if(error != paNoError){
                qCCritical(jtAudio) << "error closing portaudio stream: " << Pa_GetErrorText(error);
            }
            emit stopped();
        }
    }
    if(refreshDevicesList){
        Pa_Terminate(); //terminate and reinitialize to refresh portaudio internal devices list
        Pa_Initialize();
    }
}
bool AudioOutputPortAudio::write(const QByteArray& data)
{
    DPTR_D(AudioOutputPortAudio);
    QMutexLocker lock(&d.mutex);
    Q_UNUSED(lock);
    if (!d.available)
        return false;
    if (Pa_IsStreamStopped(d.stream))
        Pa_StartStream(d.stream);
    PaError err = Pa_WriteStream(d.stream, data.constData(), data.size()/audioFormat().channels()/audioFormat().bytesPerSample());
    if (err == paUnanticipatedHostError) {
        qWarning("Write portaudio stream error: %s", Pa_GetErrorText(err));
        return   false;
    }
    return true;
}
Exemple #21
0
/*-----------------------------------------------------------------------------------------*/
static int TestBadActions( void )
{
    PaStream*           stream = NULL;
    PaError             result;
    PaQaData            myData;
    PaStreamParameters  opp;
    const PaDeviceInfo* info = NULL;

    /* Setup data for synthesis thread. */
    myData.framesLeft = (unsigned long)(SAMPLE_RATE * 100); /* 100 seconds */
    myData.numChannels = 1;
    myData.mode = MODE_OUTPUT;

    opp.device                    = Pa_GetDefaultOutputDevice(); /* Default output. */
    opp.channelCount              = 2;                           /* Stereo output.  */
    opp.hostApiSpecificStreamInfo = NULL;
    opp.sampleFormat              = paFloat32;
    info = Pa_GetDeviceInfo(opp.device);
    opp.suggestedLatency          = info ? info->defaultLowOutputLatency : 0.100;

    if (opp.device != paNoDevice) {
        HOPEFOR(((result = Pa_OpenStream(&stream, NULL, /* Take NULL as input parame-     */
                                         &opp,          /* ters, meaning try only output. */
                                         SAMPLE_RATE, FRAMES_PER_BUFFER,
                                         paClipOff, QaCallback, &myData )) == paNoError));
    }

    HOPEFOR(((result = Pa_StartStream(NULL))    == paBadStreamPtr));
    HOPEFOR(((result = Pa_StopStream(NULL))     == paBadStreamPtr));
    HOPEFOR(((result = Pa_IsStreamStopped(NULL)) == paBadStreamPtr));
    HOPEFOR(((result = Pa_IsStreamActive(NULL)) == paBadStreamPtr));
    HOPEFOR(((result = Pa_CloseStream(NULL))    == paBadStreamPtr));
    HOPEFOR(((result = Pa_SetStreamFinishedCallback(NULL, NULL)) == paBadStreamPtr));
    HOPEFOR(((result = !Pa_GetStreamInfo(NULL))));
    HOPEFOR(((result = Pa_GetStreamTime(NULL))  == 0.0));
    HOPEFOR(((result = Pa_GetStreamCpuLoad(NULL))  == 0.0));
    HOPEFOR(((result = Pa_ReadStream(NULL, NULL, 0))  == paBadStreamPtr));
    HOPEFOR(((result = Pa_WriteStream(NULL, NULL, 0))  == paBadStreamPtr));

    /** @todo test Pa_GetStreamReadAvailable and Pa_GetStreamWriteAvailable */

    if (stream != NULL) Pa_CloseStream(stream);
    return result;
}
Exemple #22
0
PaError IPortAudio::start_Device()
{
  if(!m_PaStream)
	{
		return paBadStreamPtr;
	}

  PaError paErr = Pa_StartStream(m_PaStream);
  if(paErr != paNoError)
  {
    return paErr;
  }

  // wait until the device is started
  do
  {
      paErr = Pa_IsStreamStopped(m_PaStream);
  }
  while(paErr > paNoError);

  return paErr;
}
RTC::ReturnCode_t PortAudioInput::onDeactivated(RTC::UniqueId ec_id)
{
  RTC_DEBUG(("onDeactivated start"));
  is_active = false;
  m_mutex.lock();
  RTC_DEBUG(("onDeactivated:mutex lock"));
  try {
    if ( m_stream ) {
      if ( !Pa_IsStreamStopped( m_stream ) ) {
        m_err = Pa_AbortStream( m_stream );
        if ( m_err != paNoError ) {
          throw m_err;
        }
      }
#ifdef HAVE_LIBPORTMIXER
      Px_CloseMixer(m_mixer);
#elif defined(__linux)
      if ( m_fd > 0 ) {
        close( m_fd );
        m_fd = -1;
      }
#endif

      m_err = Pa_CloseStream( m_stream );
      if ( m_err != paNoError ) {
          throw m_err;
      }
      m_stream = NULL;
    }
  } catch (...) {
    std::string error_str = Pa_GetErrorText(m_err);
    RTC_WARN(("PortAudio Stream close failed onDeactivated:%s", error_str.c_str()));
    return RTC::RTC_ERROR;
  }
  m_mutex.unlock();
  RTC_DEBUG(("onDeactivated:mutex unlock"));
  RTC_DEBUG(("onDeactivated finish"));
  return RTC::RTC_OK;
}
Exemple #24
0
static int pa_stream_isstopped(lua_State *L)
{
  pa_Stream *stream = NULL;
  int narg = lua_gettop(L);
  PaError err = 0;

  if(narg == 1 && luaT_isudata(L, 1, "pa.Stream"))
    stream = luaT_toudata(L, 1, "pa.Stream");
  else
    luaL_error(L, "expected arguments: Stream");

  if(!stream->id)
    luaL_error(L, "attempt to operate on a closed stream");

  err = Pa_IsStreamStopped(stream->id);
  if(err == 1)
    lua_pushboolean(L, 1);
  else if(err == 0)
    lua_pushboolean(L, 0);
  else
    pa_checkerror(L, err);

  return 1;
}
Exemple #25
0
bool PortAudioSystem::startStream(PaStream *stream) {
	PaError err;

	if (!stream) {
		qWarning("PortAudioSystem: NULL PaStream passed to startStream()");
		return false;
	}

	err = Pa_IsStreamStopped(stream);
	if (err == 0) { // stream running
		return true;
	} else if (err != 1) { // some error, 1 means "stopped"
		qCritical("PortAudioSystem: Could not determine status of PortAudio stream, error %s", Pa_GetErrorText(err));
		return false;
	}

	err = Pa_StartStream(stream);
	if (err != paNoError) {
		qCritical("PortAudioSystem: Could not start PortAudio stream, error %s",Pa_GetErrorText(err));
		return false;
	}

	return true;
}
/*!
   Stop audio input
 */
void AudioReaderPortAudio::stop()
{
    if (!running || Pa_IsStreamStopped(stream)) {
        return;
    }
    do {
        err = Pa_CloseStream(stream);
        delay(100);
        if (err != paNoError) {
            emit(error("ERROR: could not close PortAudio stream"));
            delay(1000);
        }
    } while (err != paNoError);

    do {
        err = Pa_Terminate();
        if (err != paNoError) {
            emit(error("ERROR: could not terminate PortAudio"));
            delay(1000);
        }
    } while (err != paNoError);
    running = false;
    emit(stopped());
}
Exemple #27
0
int wave_close(void* theHandler)
{
  SHOW_TIME("wave_close > ENTER");

  static int aStopStreamCount = 0;

#if (USE_PORTAUDIO == 19)
  if( pa_stream == NULL )
    {
      SHOW_TIME("wave_close > LEAVE (NULL stream)");
      return 0;
    }
      
  if( Pa_IsStreamStopped( pa_stream ) )
    {
      SHOW_TIME("wave_close > LEAVE (stopped)");
      return 0;
    }
#else
  if( pa_stream == NULL )
    {
      SHOW_TIME("wave_close > LEAVE (NULL stream)");
      return 0;
    }
  
  if( Pa_StreamActive( pa_stream ) == false && mInCallbackFinishedState == false )
    {
      SHOW_TIME("wave_close > LEAVE (not active)");
      return 0;
    }
#endif

  // Avoid race condition by making sure this function only
  // gets called once at a time
  aStopStreamCount++;
  if (aStopStreamCount != 1)
    {
      SHOW_TIME("wave_close > LEAVE (stopStreamCount)");
      return 0;
    }
  
  // Comment from Audacity-1.2.4b adapted to the eSpeak context. 
  //
  // We got here in one of two ways:
  //
  // 1. The calling program calls the espeak_Cancel function and we 
  //    therefore want to stop as quickly as possible.  
  //    So we use AbortStream().  If this is
  //    the case the portaudio stream is still in the Running state
  //    (see PortAudio state machine docs).
  //
  // 2. The callback told PortAudio to stop the stream since it had
  //    reached the end of the selection.  
  //    The event polling thread discovered this by noticing that 
  //    wave_is_busy() returned false.
  //    wave_is_busy() (which calls Pa_GetStreamActive()) will not return
  //    false until all buffers have finished playing, so we can call
  //    AbortStream without losing any samples.  If this is the case
  //    we are in the "callback finished state" (see PortAudio state
  //    machine docs).
  //
  // The moral of the story: We can call AbortStream safely, without
  // losing samples.
  //
  // DMM: This doesn't seem to be true; it seems to be necessary to
  // call StopStream if the callback brought us here, and AbortStream
  // if the user brought us here.
  //
  
#if (USE_PORTAUDIO == 19)
  if (pa_stream)
    {
      Pa_AbortStream( pa_stream );
      SHOW_TIME("wave_close > Pa_AbortStream (end)");

      Pa_CloseStream( pa_stream );
      SHOW_TIME("wave_close > Pa_CloseStream (end)");
      pa_stream = NULL;
      mInCallbackFinishedState = false;
    }
#else
  if (pa_stream)
    {
      if (mInCallbackFinishedState)
	{
	  Pa_StopStream( pa_stream );
	  SHOW_TIME("wave_close > Pa_StopStream (end)");
	}
      else
	{
	  Pa_AbortStream( pa_stream );
	  SHOW_TIME("wave_close > Pa_AbortStream (end)");
	}
      Pa_CloseStream( pa_stream );
      SHOW_TIME("wave_close > Pa_CloseStream (end)");

      pa_stream = NULL;
      mInCallbackFinishedState = false;
    }
#endif
  init_buffer();

  aStopStreamCount = 0; // last action
  SHOW_TIME("wave_close > LEAVE");
  return 0;
}
int pa_wavplayrec(SAMPLE *buffer, int buflen, int bufchannels, SAMPLE *recbuffer, int recbuffirstchannel, int recbufflastchannel, int recbuflen, int deviceID, int recdevID, int samplerate)
{
	//mexPrintf("buflen=%i bufchannels=%i samplerate=%i\n", buflen, bufchannels, samplerate);

	// Make our wavData object, to pass to OpenStream. This gets given to us again in the
	// callback. I guess you could just have a global variable instead...
	paWavData wav;
	wav.buffer = buffer;
	wav.recbuffer = recbuffer;
	wav.buflen = buflen;
	wav.recbuflen = recbuflen;
	wav.bufchannels = bufchannels;
	wav.recbuffirstchan = recbuffirstchannel;
	wav.recbufflastchan = recbufflastchannel;
	wav.bufpos = 0;
	wav.recbufpos = 0;
	
	if (recbuffer == NULL)
		if (buffer == NULL)
			mexErrMsgTxt("recbuffer && buffer NULL in pa_wavplay");
		else
		{
			mexPrintf("Playing on device %i\n", deviceID);
			wav.recmode = play;
		}
	else
		if (buffer == NULL)
		{
			mexPrintf("Recording on device %i\n", recdevID);
			wav.recmode = record;
		}
		else
		{
			mexPrintf("Recording on device %i\n", recdevID);
			mexPrintf("Playing on device %i\n", deviceID);

			wav.recmode = playrecord;
		}

	PaStream *stream;
    PaError err;

    err = Pa_Initialize();
    if( err != paNoError ) 
		goto error;

	int dev_type_indx = -1;
	const PaHostApiInfo* Api_Info;
	int num_APIs = (int )Pa_GetHostApiCount();
	for (int i=0; i<num_APIs; i++) {
 		Api_Info = Pa_GetHostApiInfo(i);
		if (strcmp(Api_Info->name,API_NAME)==0)
			dev_type_indx = i;
	}
	if (dev_type_indx == -1) {
		goto error;
	}
	Api_Info = Pa_GetHostApiInfo(dev_type_indx);
	if (recdevID != -1)
		recdevID = Pa_HostApiDeviceIndexToDeviceIndex(dev_type_indx, recdevID);
	if (deviceID != -1)
		deviceID = Pa_HostApiDeviceIndexToDeviceIndex(dev_type_indx, deviceID);
	
	// Open an audio I/O stream. 
	PaWasapiStreamInfo api_info;
	api_info.size = sizeof(PaWasapiStreamInfo);
	api_info.version = 1;
	api_info.hostApiType = paWASAPI;
	api_info.flags = paWinWasapiExclusive;
	void *p_api_info;
	if ((strcmp(API_NAME, "Windows WASAPI")== 0)) {
		p_api_info = &api_info;
	} else {
		p_api_info = NULL;
	}
    PaStreamParameters inputParameters;		// Parameters governing portaudio input stream
	PaStreamParameters outputParameters;	// Parameters governing portaudio output stream
    inputParameters.channelCount = recbufflastchannel;
    inputParameters.device = recdevID;
    inputParameters.hostApiSpecificStreamInfo = p_api_info;
    inputParameters.sampleFormat = paFloat32;	// Input data returned as floating point
	if (recdevID != -1)
	    inputParameters.suggestedLatency = Pa_GetDeviceInfo(recdevID)->defaultLowInputLatency ;
	outputParameters.channelCount = bufchannels;
    outputParameters.device = deviceID;
    outputParameters.hostApiSpecificStreamInfo = p_api_info;
    outputParameters.sampleFormat = paFloat32;	// Output data returned as floating point
	if (deviceID != -1)
	    outputParameters.suggestedLatency = Pa_GetDeviceInfo(deviceID)->defaultLowInputLatency ;

	err = Pa_IsFormatSupported(NULL, &outputParameters, (double )samplerate);

	if (recbuffer == NULL)
		err = Pa_OpenStream(
			  &stream,
			  NULL,
			  &outputParameters,
			  samplerate,     // stream sample rate
			  BLOCK,            // frames per buffer 
			  paNoFlag,       // stream flag
			  (PaStreamCallback (__cdecl *))paWavCallback,  // callback function
			  &wav);          // user data
	else
		if (buffer == NULL)
			err = Pa_OpenStream(
				  &stream,
				  &inputParameters,
				  NULL,
				  samplerate,     // stream sample rate
				  BLOCK,            // frames per buffer 
				  paNoFlag,       // stream flag
				  (PaStreamCallback (__cdecl *))paWavCallback,  // callback function
				  &wav);          // user data
		else
			err = Pa_OpenStream(
				  &stream,
				  &inputParameters,
				  &outputParameters,
				  samplerate,     // stream sample rate
				  BLOCK,            // frames per buffer 
				  paNoFlag,       // stream flag
				  (PaStreamCallback (__cdecl *))paWavCallback,  // callback function
				  &wav);          // user data


    if( err != paNoError ) 
		goto error;

    err = Pa_StartStream( stream );
    
	if( err != paNoError ) 
		goto error;
    
	// sleep while stream's active
	while( Pa_IsStreamActive(stream) )
		Pa_Sleep( 50 );

	if (err = Pa_IsStreamStopped( stream ) == 0) {
	    err = Pa_StopStream( stream );
	    if( err != paNoError ) 
			goto error;
	} else if (err != paNoError )
		goto error;

	err = Pa_CloseStream( stream );
    
	if( err != paNoError ) 
		goto error;
    
	Pa_Terminate();

	return err;

	// wtf? A goto? Yeah, that's leftover from the portaudio example code
error:
    Pa_Terminate();
    mexPrintf( "An error occured while using the portaudio stream\n" );
    mexPrintf( "Error number: %d\n", err );
    mexPrintf( "Error message: %s\n", Pa_GetErrorText( err ) );
    return err;
	
}
Exemple #29
0
/*
 * start portaudio stream capture
 * args:
 *   audio_ctx - pointer to audio context data
 *
 * asserts:
 *   audio_ctx is not null
 *
 * returns: error code
 */
int audio_start_portaudio(audio_context_t *audio_ctx)
{
	/*assertions*/
	assert(audio_ctx != NULL);

	PaError err = paNoError;
	PaStream *stream = (PaStream *) audio_ctx->stream;

	if(stream)
	{
		if( !(Pa_IsStreamStopped( stream )))
		{
			Pa_AbortStream( stream );
			Pa_CloseStream( stream );
			audio_ctx->stream = NULL;
			stream = audio_ctx->stream;
		}
	}

	PaStreamParameters inputParameters;

	inputParameters.device = audio_ctx->list_devices[audio_ctx->device].id;
	inputParameters.channelCount = audio_ctx->channels;
	inputParameters.sampleFormat = paFloat32; /*sample_t - float*/

	if (Pa_GetDeviceInfo( inputParameters.device ))
		inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency;
		//inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency;
	else
		inputParameters.suggestedLatency = DEFAULT_LATENCY_DURATION/1000.0;
	inputParameters.hostApiSpecificStreamInfo = NULL;

	/*---------------------------- start recording Audio. ----------------------------- */
	audio_ctx->snd_begintime = ns_time_monotonic();

	audio_ctx->stream_flag = AUDIO_STRM_ON;

	err = Pa_OpenStream(
		&stream,                     /* stream */
		&inputParameters,            /* inputParameters    */
		NULL,                        /* outputParameters   */
		audio_ctx->samprate,         /* sample rate        */
		paFramesPerBufferUnspecified,/* buffer in frames (use API optimal)*/
		paNoFlag,                    /* PaNoFlag - clip and dhiter*/
		recordCallback,              /* sound callback     */
		audio_ctx );                 /* callback userData  */

	if( err == paNoError )
	{
		err = Pa_StartStream( stream );
		audio_ctx->stream = (void *) stream; /* store stream pointer*/
	}

	if( err != paNoError )
	{
		fprintf(stderr, "AUDIO: An error occured while starting the portaudio API\n" );
		fprintf(stderr, "       Error number: %d\n", err );
		fprintf(stderr, "       Error message: %s\n", Pa_GetErrorText( err ) );

		if(stream) Pa_AbortStream( stream );
		audio_ctx->stream_flag = AUDIO_STRM_OFF;

		return(-1);
	}

	const PaStreamInfo* stream_info = Pa_GetStreamInfo (stream);
	if(verbosity > 1)
		printf("AUDIO: latency of %8.3f msec\n", 1000 * stream_info->inputLatency);

	return 0;
}
Exemple #30
0
bool	paWriter::selectDevice (int16_t odev) {
PaError err;

	if (!isValidDevice (odev))
	   return false;

	if ((ostream != NULL) && !Pa_IsStreamStopped (ostream)) {
	   paCallbackReturn = paAbort;
	   (void) Pa_AbortStream (ostream);
	   while (!Pa_IsStreamStopped (ostream))
	      Pa_Sleep (1);
	   writerRunning = false;
	}

	if (ostream != NULL)
	   Pa_CloseStream (ostream);

	outputParameters. device		= odev;
	outputParameters. channelCount		= 2;
	outputParameters. sampleFormat		= paFloat32;
	if (Latency == LOWLATENCY) {
	   outputParameters. suggestedLatency	=
	                             Pa_GetDeviceInfo (odev) ->
	                                      defaultLowOutputLatency;
	   bufSize	= (int)((float)outputParameters. suggestedLatency * 
	                                         (float)CardRate);
	}
	else
	if (Latency == HIGHLATENCY) {
	   outputParameters. suggestedLatency	=
	                             Pa_GetDeviceInfo (odev) ->
	                                      defaultHighOutputLatency;
	   bufSize	= (int)((float)outputParameters. suggestedLatency * 
	                                         (float)CardRate);
	}
	else {		// VERY HIGH LATENCY
	   outputParameters. suggestedLatency	=
	                             Pa_GetDeviceInfo (odev) ->
	                                      defaultHighOutputLatency;
	   bufSize	= 3 * (int)((float)outputParameters. suggestedLatency * 
	                                         (float)CardRate);
	}
	
	outputParameters. hostApiSpecificStreamInfo = NULL;
//
	fprintf (stderr, "Suggested size for outputbuffer = %d\n", bufSize);
	err = Pa_OpenStream (
	             &ostream,
	             NULL,
	             &outputParameters,
	             CardRate,
	             bufSize,
	             0,
	             this	-> paCallback_o,
	             this
	      );

	if (err != paNoError) {
	   qDebug ("Open ostream error\n");
	   return false;
	}

	return true;
}