Various updates for pulseaudio API and default ALSA device enumeration (gs).
[rtaudio.git] / RtAudio.cpp
index 4a3966b5700ba3e16caa1a5897e41bde199a3dcf..70414a68297577db58426f2ab46b9c3c5d9860e0 100644 (file)
@@ -10,7 +10,7 @@
     RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/\r
 \r
     RtAudio: realtime audio i/o C++ classes\r
-    Copyright (c) 2001-2011 Gary P. Scavone\r
+    Copyright (c) 2001-2012 Gary P. Scavone\r
 \r
     Permission is hereby granted, free of charge, to any person\r
     obtaining a copy of this software and associated documentation files\r
@@ -38,7 +38,7 @@
 */\r
 /************************************************************************/\r
 \r
-// RtAudio: Version 4.0.9\r
+// RtAudio: Version 4.0.11\r
 \r
 #include "RtAudio.h"\r
 #include <iostream>\r
@@ -58,7 +58,7 @@ const unsigned int RtApi::SAMPLE_RATES[] = {
   #define MUTEX_DESTROY(A)    DeleteCriticalSection(A)\r
   #define MUTEX_LOCK(A)       EnterCriticalSection(A)\r
   #define MUTEX_UNLOCK(A)     LeaveCriticalSection(A)\r
-#elif defined(__LINUX_ALSA__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)\r
+#elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)\r
   // pthread API\r
   #define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)\r
   #define MUTEX_DESTROY(A)    pthread_mutex_destroy(A)\r
@@ -87,6 +87,9 @@ void RtAudio :: getCompiledApi( std::vector<RtAudio::Api> &apis ) throw()
 #if defined(__LINUX_ALSA__)\r
   apis.push_back( LINUX_ALSA );\r
 #endif\r
+#if defined(__LINUX_PULSE__)\r
+  apis.push_back( LINUX_PULSE );\r
+#endif\r
 #if defined(__LINUX_OSS__)\r
   apis.push_back( LINUX_OSS );\r
 #endif\r
@@ -106,6 +109,10 @@ void RtAudio :: getCompiledApi( std::vector<RtAudio::Api> &apis ) throw()
 \r
 void RtAudio :: openRtApi( RtAudio::Api api )\r
 {\r
+  if ( rtapi_ )\r
+    delete rtapi_;\r
+  rtapi_ = 0;\r
+\r
 #if defined(__UNIX_JACK__)\r
   if ( api == UNIX_JACK )\r
     rtapi_ = new RtApiJack();\r
@@ -114,6 +121,10 @@ void RtAudio :: openRtApi( RtAudio::Api api )
   if ( api == LINUX_ALSA )\r
     rtapi_ = new RtApiAlsa();\r
 #endif\r
+#if defined(__LINUX_PULSE__)\r
+  if ( api == LINUX_PULSE )\r
+    rtapi_ = new RtApiPulse();\r
+#endif\r
 #if defined(__LINUX_OSS__)\r
   if ( api == LINUX_OSS )\r
     rtapi_ = new RtApiOss();\r
@@ -412,6 +423,8 @@ struct CoreHandle {
     :deviceBuffer(0), drainCounter(0), internalDrain(false) { nStreams[0] = 1; nStreams[1] = 1; id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }\r
 };\r
 \r
+ThreadHandle threadId;\r
+\r
 RtApiCore:: RtApiCore()\r
 {\r
 #if defined( AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER )\r
@@ -1080,7 +1093,7 @@ bool RtApiCore :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
 \r
     // We'll try higher bit rates first and then work our way down.\r
     std::vector< std::pair<UInt32, UInt32>  > physicalFormats;\r
-    formatFlags = description.mFormatFlags | kLinearPCMFormatFlagIsFloat & ~kLinearPCMFormatFlagIsSignedInteger;\r
+    formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsFloat) & ~kLinearPCMFormatFlagIsSignedInteger;\r
     physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );\r
     formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;\r
     physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );\r
@@ -1351,8 +1364,6 @@ void RtApiCore :: startStream( void )
     return;\r
   }\r
 \r
-  MUTEX_LOCK( &stream_.mutex );\r
-\r
   OSStatus result = noErr;\r
   CoreHandle *handle = (CoreHandle *) stream_.apiHandle;\r
   if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
@@ -1381,8 +1392,6 @@ void RtApiCore :: startStream( void )
   stream_.state = STREAM_RUNNING;\r
 \r
  unlock:\r
-  MUTEX_UNLOCK( &stream_.mutex );\r
-\r
   if ( result == noErr ) return;\r
   error( RtError::SYSTEM_ERROR );\r
 }\r
@@ -1396,13 +1405,6 @@ void RtApiCore :: stopStream( void )
     return;\r
   }\r
 \r
-  MUTEX_LOCK( &stream_.mutex );\r
-\r
-  if ( stream_.state == STREAM_STOPPED ) {\r
-    MUTEX_UNLOCK( &stream_.mutex );\r
-    return;\r
-  }\r
-\r
   OSStatus result = noErr;\r
   CoreHandle *handle = (CoreHandle *) stream_.apiHandle;\r
   if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
@@ -1412,9 +1414,7 @@ void RtApiCore :: stopStream( void )
       pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled\r
     }\r
 \r
-    MUTEX_UNLOCK( &stream_.mutex );\r
     result = AudioDeviceStop( handle->id[0], callbackHandler );\r
-    MUTEX_LOCK( &stream_.mutex );\r
     if ( result != noErr ) {\r
       errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping callback procedure on device (" << stream_.device[0] << ").";\r
       errorText_ = errorStream_.str();\r
@@ -1424,9 +1424,7 @@ void RtApiCore :: stopStream( void )
 \r
   if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {\r
 \r
-    MUTEX_UNLOCK( &stream_.mutex );\r
     result = AudioDeviceStop( handle->id[1], callbackHandler );\r
-    MUTEX_LOCK( &stream_.mutex );\r
     if ( result != noErr ) {\r
       errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping input callback procedure on device (" << stream_.device[1] << ").";\r
       errorText_ = errorStream_.str();\r
@@ -1437,8 +1435,6 @@ void RtApiCore :: stopStream( void )
   stream_.state = STREAM_STOPPED;\r
 \r
  unlock:\r
-  MUTEX_UNLOCK( &stream_.mutex );\r
-\r
   if ( result == noErr ) return;\r
   error( RtError::SYSTEM_ERROR );\r
 }\r
@@ -1458,11 +1454,25 @@ void RtApiCore :: abortStream( void )
   stopStream();\r
 }\r
 \r
+// This function will be called by a spawned thread when the user\r
+// callback function signals that the stream should be stopped or\r
+// aborted.  It is better to handle it this way because the\r
+// callbackEvent() function probably should return before the AudioDeviceStop()\r
+// function is called.\r
+extern "C" void *coreStopStream( void *ptr )\r
+{\r
+  CallbackInfo *info = (CallbackInfo *) ptr;\r
+  RtApiCore *object = (RtApiCore *) info->object;\r
+\r
+  object->stopStream();\r
+  pthread_exit( NULL );\r
+}\r
+\r
 bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,\r
                                  const AudioBufferList *inBufferList,\r
                                  const AudioBufferList *outBufferList )\r
 {\r
-  if ( stream_.state == STREAM_STOPPED ) return SUCCESS;\r
+  if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;\r
   if ( stream_.state == STREAM_CLOSED ) {\r
     errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
     error( RtError::WARNING );\r
@@ -1474,21 +1484,15 @@ bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
 \r
   // Check if we were draining the stream and signal is finished.\r
   if ( handle->drainCounter > 3 ) {\r
+\r
+    stream_.state = STREAM_STOPPING;\r
     if ( handle->internalDrain == true )\r
-      stopStream();\r
+      pthread_create( &threadId, NULL, coreStopStream, info );\r
     else // external call to stopStream()\r
       pthread_cond_signal( &handle->condition );\r
     return SUCCESS;\r
   }\r
 \r
-  MUTEX_LOCK( &stream_.mutex );\r
-\r
-  // The state might change while waiting on a mutex.\r
-  if ( stream_.state == STREAM_STOPPED ) {\r
-    MUTEX_UNLOCK( &stream_.mutex );\r
-    return SUCCESS;\r
-  }\r
-\r
   AudioDeviceID outputDevice = handle->id[0];\r
 \r
   // Invoke user callback to get fresh output data UNLESS we are\r
@@ -1507,15 +1511,18 @@ bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
       handle->xrun[1] = false;\r
     }\r
 \r
-    handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
-                                     stream_.bufferSize, streamTime, status, info->userData );\r
-    if ( handle->drainCounter == 2 ) {\r
-      MUTEX_UNLOCK( &stream_.mutex );\r
+    int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
+                                  stream_.bufferSize, streamTime, status, info->userData );\r
+    if ( cbReturnValue == 2 ) {\r
+      stream_.state = STREAM_STOPPING;\r
+      handle->drainCounter = 2;\r
       abortStream();\r
       return SUCCESS;\r
     }\r
-    else if ( handle->drainCounter == 1 )\r
+    else if ( cbReturnValue == 1 ) {\r
+      handle->drainCounter = 1;\r
       handle->internalDrain = true;\r
+    }\r
   }\r
 \r
   if ( stream_.mode == OUTPUT || ( stream_.mode == DUPLEX && deviceId == outputDevice ) ) {\r
@@ -1713,7 +1720,7 @@ bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
   }\r
 \r
  unlock:\r
-  MUTEX_UNLOCK( &stream_.mutex );\r
+  //MUTEX_UNLOCK( &stream_.mutex );\r
 \r
   RtApi::tickStreamTime();\r
   return SUCCESS;\r
@@ -1901,6 +1908,7 @@ RtAudio::DeviceInfo RtApiJack :: getDeviceInfo( unsigned int device )
   }\r
 \r
   if ( device >= nDevices ) {\r
+    jack_client_close( client );\r
     errorText_ = "RtApiJack::getDeviceInfo: device ID is invalid!";\r
     error( RtError::INVALID_USE );\r
   }\r
@@ -2086,8 +2094,17 @@ bool RtApiJack :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
 \r
   // Get the latency of the JACK port.\r
   ports = jack_get_ports( client, deviceName.c_str(), NULL, flag );\r
-  if ( ports[ firstChannel ] )\r
-    stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );\r
+  if ( ports[ firstChannel ] ) {\r
+    // Added by Ge Wang\r
+    jack_latency_callback_mode_t cbmode = (mode == INPUT ? JackCaptureLatency : JackPlaybackLatency);\r
+    // the range (usually the min and max are equal)\r
+    jack_latency_range_t latrange; latrange.min = latrange.max = 0;\r
+    // get the latency range\r
+    jack_port_get_latency_range( jack_port_by_name( client, ports[firstChannel] ), cbmode, &latrange );\r
+    // be optimistic, use the min!\r
+    stream_.latency[mode] = latrange.min;\r
+    //stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );\r
+  }\r
   free( ports );\r
 \r
   // The jack server always uses 32-bit floating-point data.\r
@@ -2294,8 +2311,6 @@ void RtApiJack :: startStream( void )
     return;\r
   }\r
 \r
-  MUTEX_LOCK(&stream_.mutex);\r
-\r
   JackHandle *handle = (JackHandle *) stream_.apiHandle;\r
   int result = jack_activate( handle->client );\r
   if ( result ) {\r
@@ -2357,8 +2372,6 @@ void RtApiJack :: startStream( void )
   stream_.state = STREAM_RUNNING;\r
 \r
  unlock:\r
-  MUTEX_UNLOCK(&stream_.mutex);\r
-\r
   if ( result == 0 ) return;\r
   error( RtError::SYSTEM_ERROR );\r
 }\r
@@ -2372,13 +2385,6 @@ void RtApiJack :: stopStream( void )
     return;\r
   }\r
 \r
-  MUTEX_LOCK( &stream_.mutex );\r
-\r
-  if ( stream_.state == STREAM_STOPPED ) {\r
-    MUTEX_UNLOCK( &stream_.mutex );\r
-    return;\r
-  }\r
-\r
   JackHandle *handle = (JackHandle *) stream_.apiHandle;\r
   if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
 \r
@@ -2390,8 +2396,6 @@ void RtApiJack :: stopStream( void )
 \r
   jack_deactivate( handle->client );\r
   stream_.state = STREAM_STOPPED;\r
-\r
-  MUTEX_UNLOCK( &stream_.mutex );\r
 }\r
 \r
 void RtApiJack :: abortStream( void )\r
@@ -2420,13 +2424,12 @@ extern "C" void *jackStopStream( void *ptr )
   RtApiJack *object = (RtApiJack *) info->object;\r
 \r
   object->stopStream();\r
-\r
   pthread_exit( NULL );\r
 }\r
 \r
 bool RtApiJack :: callbackEvent( unsigned long nframes )\r
 {\r
-  if ( stream_.state == STREAM_STOPPED ) return SUCCESS;\r
+  if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;\r
   if ( stream_.state == STREAM_CLOSED ) {\r
     errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
     error( RtError::WARNING );\r
@@ -2443,6 +2446,8 @@ bool RtApiJack :: callbackEvent( unsigned long nframes )
 \r
   // Check if we were draining the stream and signal is finished.\r
   if ( handle->drainCounter > 3 ) {\r
+\r
+    stream_.state = STREAM_STOPPING;\r
     if ( handle->internalDrain == true )\r
       pthread_create( &threadId, NULL, jackStopStream, info );\r
     else\r
@@ -2450,14 +2455,6 @@ bool RtApiJack :: callbackEvent( unsigned long nframes )
     return SUCCESS;\r
   }\r
 \r
-  MUTEX_LOCK( &stream_.mutex );\r
-\r
-  // The state might change while waiting on a mutex.\r
-  if ( stream_.state == STREAM_STOPPED ) {\r
-    MUTEX_UNLOCK( &stream_.mutex );\r
-    return SUCCESS;\r
-  }\r
-\r
   // Invoke user callback first, to get fresh output data.\r
   if ( handle->drainCounter == 0 ) {\r
     RtAudioCallback callback = (RtAudioCallback) info->callback;\r
@@ -2471,16 +2468,19 @@ bool RtApiJack :: callbackEvent( unsigned long nframes )
       status |= RTAUDIO_INPUT_OVERFLOW;\r
       handle->xrun[1] = false;\r
     }\r
-    handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
-                                     stream_.bufferSize, streamTime, status, info->userData );\r
-    if ( handle->drainCounter == 2 ) {\r
-      MUTEX_UNLOCK( &stream_.mutex );\r
+    int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
+                                  stream_.bufferSize, streamTime, status, info->userData );\r
+    if ( cbReturnValue == 2 ) {\r
+      stream_.state = STREAM_STOPPING;\r
+      handle->drainCounter = 2;\r
       ThreadHandle id;\r
       pthread_create( &id, NULL, jackStopStream, info );\r
       return SUCCESS;\r
     }\r
-    else if ( handle->drainCounter == 1 )\r
+    else if ( cbReturnValue == 1 ) {\r
+      handle->drainCounter = 1;\r
       handle->internalDrain = true;\r
+    }\r
   }\r
 \r
   jack_default_audio_sample_t *jackbuffer;\r
@@ -2535,8 +2535,6 @@ bool RtApiJack :: callbackEvent( unsigned long nframes )
   }\r
 \r
  unlock:\r
-  MUTEX_UNLOCK(&stream_.mutex);\r
-\r
   RtApi::tickStreamTime();\r
   return SUCCESS;\r
 }\r
@@ -2719,6 +2717,8 @@ RtAudio::DeviceInfo RtApiAsio :: getDeviceInfo( unsigned int device )
     info.nativeFormats |= RTAUDIO_FLOAT32;\r
   else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )\r
     info.nativeFormats |= RTAUDIO_FLOAT64;\r
+  else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB )\r
+    info.nativeFormats |= RTAUDIO_SINT24;\r
 \r
   if ( info.outputChannels > 0 )\r
     if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;\r
@@ -2871,6 +2871,10 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
     stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;\r
     if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true;\r
   }\r
+  else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB ) {\r
+    stream_.deviceFormat[mode] = RTAUDIO_SINT24;\r
+    if ( channelInfo.type == ASIOSTInt24MSB ) stream_.doByteSwap[mode] = true;\r
+  }\r
 \r
   if ( stream_.deviceFormat[mode] == 0 ) {\r
     drivers.removeCurrentDriver();\r
@@ -3153,8 +3157,6 @@ void RtApiAsio :: startStream()
     return;\r
   }\r
 \r
-  //MUTEX_LOCK( &stream_.mutex );\r
-\r
   AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
   ASIOError result = ASIOStart();\r
   if ( result != ASE_OK ) {\r
@@ -3170,8 +3172,6 @@ void RtApiAsio :: startStream()
   asioXRun = false;\r
 \r
  unlock:\r
-  //MUTEX_UNLOCK( &stream_.mutex );\r
-\r
   stopThreadCalled = false;\r
 \r
   if ( result == ASE_OK ) return;\r
@@ -3187,23 +3187,11 @@ void RtApiAsio :: stopStream()
     return;\r
   }\r
 \r
-  /*\r
-  MUTEX_LOCK( &stream_.mutex );\r
-\r
-  if ( stream_.state == STREAM_STOPPED ) {\r
-    MUTEX_UNLOCK( &stream_.mutex );\r
-    return;\r
-  }\r
-  */\r
-\r
   AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
   if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
     if ( handle->drainCounter == 0 ) {\r
       handle->drainCounter = 2;\r
-      //      MUTEX_UNLOCK( &stream_.mutex );\r
       WaitForSingleObject( handle->condition, INFINITE );  // block until signaled\r
-      //ResetEvent( handle->condition );\r
-      //      MUTEX_LOCK( &stream_.mutex );\r
     }\r
   }\r
 \r
@@ -3215,8 +3203,6 @@ void RtApiAsio :: stopStream()
     errorText_ = errorStream_.str();\r
   }\r
 \r
-  //  MUTEX_UNLOCK( &stream_.mutex );\r
-\r
   if ( result == ASE_OK ) return;\r
   error( RtError::SYSTEM_ERROR );\r
 }\r
@@ -3250,15 +3236,13 @@ extern "C" unsigned __stdcall asioStopStream( void *ptr )
   RtApiAsio *object = (RtApiAsio *) info->object;\r
 \r
   object->stopStream();\r
-\r
   _endthreadex( 0 );\r
   return 0;\r
 }\r
 \r
 bool RtApiAsio :: callbackEvent( long bufferIndex )\r
 {\r
-  if ( stream_.state == STREAM_STOPPED ) return SUCCESS;\r
-  if ( stopThreadCalled ) return SUCCESS;\r
+  if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;\r
   if ( stream_.state == STREAM_CLOSED ) {\r
     errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
     error( RtError::WARNING );\r
@@ -3270,22 +3254,18 @@ bool RtApiAsio :: callbackEvent( long bufferIndex )
 \r
   // Check if we were draining the stream and signal if finished.\r
   if ( handle->drainCounter > 3 ) {\r
+\r
+    stream_.state = STREAM_STOPPING;\r
     if ( handle->internalDrain == false )\r
       SetEvent( handle->condition );\r
     else { // spawn a thread to stop the stream\r
       unsigned threadId;\r
-      stopThreadCalled = true;\r
       stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,\r
                                                     &stream_.callbackInfo, 0, &threadId );\r
     }\r
     return SUCCESS;\r
   }\r
 \r
-  /*MUTEX_LOCK( &stream_.mutex );\r
-\r
-  // The state might change while waiting on a mutex.\r
-  if ( stream_.state == STREAM_STOPPED ) goto unlock; */\r
-\r
   // Invoke user callback to get fresh output data UNLESS we are\r
   // draining stream.\r
   if ( handle->drainCounter == 0 ) {\r
@@ -3300,19 +3280,20 @@ bool RtApiAsio :: callbackEvent( long bufferIndex )
       status |= RTAUDIO_INPUT_OVERFLOW;\r
       asioXRun = false;\r
     }\r
-    handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
+    int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
                                      stream_.bufferSize, streamTime, status, info->userData );\r
-    if ( handle->drainCounter == 2 ) {\r
-      //      MUTEX_UNLOCK( &stream_.mutex );\r
-      //      abortStream();\r
+    if ( cbReturnValue == 2 ) {\r
+      stream_.state = STREAM_STOPPING;\r
+      handle->drainCounter = 2;\r
       unsigned threadId;\r
-      stopThreadCalled = true;\r
       stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,\r
                                                     &stream_.callbackInfo, 0, &threadId );\r
       return SUCCESS;\r
     }\r
-    else if ( handle->drainCounter == 1 )\r
+    else if ( cbReturnValue == 1 ) {\r
+      handle->drainCounter = 1;\r
       handle->internalDrain = true;\r
+    }\r
   }\r
 \r
   unsigned int nChannels, bufferBytes, i, j;\r
@@ -3408,8 +3389,6 @@ bool RtApiAsio :: callbackEvent( long bufferIndex )
   // drivers apparently do not function correctly without it.\r
   ASIOOutputReady();\r
 \r
-  //  MUTEX_UNLOCK( &stream_.mutex );\r
-\r
   RtApi::tickStreamTime();\r
   return SUCCESS;\r
 }\r
@@ -3664,9 +3643,9 @@ unsigned int RtApiDs :: getDeviceCount( void )
   std::vector< int > indices;\r
   for ( unsigned int i=0; i<dsDevices.size(); i++ )\r
     if ( dsDevices[i].found == false ) indices.push_back( i );\r
-  for ( unsigned int nErased=0, unsigned int i=0; i<indices.size(); i++, nErased++ ) {\r
-    dsDevices.erase( dsDevices.begin()-nErased );\r
-  }\r
+  unsigned int nErased = 0;\r
+  for ( unsigned int i=0; i<indices.size(); i++ )\r
+    dsDevices.erase( dsDevices.begin()-nErased++ );\r
 \r
   return dsDevices.size();\r
 }\r
@@ -3915,7 +3894,7 @@ bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned
   // Determine the device buffer size. By default, we'll use the value\r
   // defined above (32K), but we will grow it to make allowances for\r
   // very large software buffer sizes.\r
-  DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;;\r
+  DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;\r
   DWORD dsPointerLeadTime = 0;\r
 \r
   void *ohandle = 0, *bhandle = 0;\r
@@ -4408,8 +4387,6 @@ void RtApiDs :: startStream()
     return;\r
   }\r
 \r
-  //MUTEX_LOCK( &stream_.mutex );\r
-  \r
   DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
 \r
   // Increase scheduler frequency on lesser windows (a side-effect of\r
@@ -4454,8 +4431,6 @@ void RtApiDs :: startStream()
   stream_.state = STREAM_RUNNING;\r
 \r
  unlock:\r
-  //  MUTEX_UNLOCK( &stream_.mutex );\r
-\r
   if ( FAILED( result ) ) error( RtError::SYSTEM_ERROR );\r
 }\r
 \r
@@ -4468,15 +4443,6 @@ void RtApiDs :: stopStream()
     return;\r
   }\r
 \r
-  /*\r
-  MUTEX_LOCK( &stream_.mutex );\r
-\r
-  if ( stream_.state == STREAM_STOPPED ) {\r
-    MUTEX_UNLOCK( &stream_.mutex );\r
-    return;\r
-  }\r
-  */\r
-\r
   HRESULT result = 0;\r
   LPVOID audioPtr;\r
   DWORD dataLen;\r
@@ -4484,10 +4450,7 @@ void RtApiDs :: stopStream()
   if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
     if ( handle->drainCounter == 0 ) {\r
       handle->drainCounter = 2;\r
-      //      MUTEX_UNLOCK( &stream_.mutex );\r
       WaitForSingleObject( handle->condition, INFINITE );  // block until signaled\r
-      //ResetEvent( handle->condition );\r
-      //      MUTEX_LOCK( &stream_.mutex );\r
     }\r
 \r
     stream_.state = STREAM_STOPPED;\r
@@ -4565,8 +4528,6 @@ void RtApiDs :: stopStream()
 \r
  unlock:\r
   timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.\r
-  //  MUTEX_UNLOCK( &stream_.mutex );\r
-\r
   if ( FAILED( result ) ) error( RtError::SYSTEM_ERROR );\r
 }\r
 \r
@@ -4587,7 +4548,7 @@ void RtApiDs :: abortStream()
 \r
 void RtApiDs :: callbackEvent()\r
 {\r
-  if ( stream_.state == STREAM_STOPPED ) {\r
+  if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) {\r
     Sleep( 50 ); // sleep 50 milliseconds\r
     return;\r
   }\r
@@ -4603,6 +4564,8 @@ void RtApiDs :: callbackEvent()
 \r
   // Check if we were draining the stream and signal is finished.\r
   if ( handle->drainCounter > stream_.nBuffers + 2 ) {\r
+\r
+    stream_.state = STREAM_STOPPING;\r
     if ( handle->internalDrain == false )\r
       SetEvent( handle->condition );\r
     else\r
@@ -4610,16 +4573,6 @@ void RtApiDs :: callbackEvent()
     return;\r
   }\r
 \r
-  /*\r
-  MUTEX_LOCK( &stream_.mutex );\r
-\r
-  // The state might change while waiting on a mutex.\r
-  if ( stream_.state == STREAM_STOPPED ) {\r
-    MUTEX_UNLOCK( &stream_.mutex );\r
-    return;\r
-  }\r
-  */\r
-\r
   // Invoke user callback to get fresh output data UNLESS we are\r
   // draining stream.\r
   if ( handle->drainCounter == 0 ) {\r
@@ -4634,15 +4587,18 @@ void RtApiDs :: callbackEvent()
       status |= RTAUDIO_INPUT_OVERFLOW;\r
       handle->xrun[1] = false;\r
     }\r
-    handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
-                                     stream_.bufferSize, streamTime, status, info->userData );\r
-    if ( handle->drainCounter == 2 ) {\r
-      //      MUTEX_UNLOCK( &stream_.mutex );\r
+    int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
+                                  stream_.bufferSize, streamTime, status, info->userData );\r
+    if ( cbReturnValue == 2 ) {\r
+      stream_.state = STREAM_STOPPING;\r
+      handle->drainCounter = 2;\r
       abortStream();\r
       return;\r
     }\r
-    else if ( handle->drainCounter == 1 )\r
+    else if ( cbReturnValue == 1 ) {\r
+      handle->drainCounter = 1;\r
       handle->internalDrain = true;\r
+    }\r
   }\r
 \r
   HRESULT result;\r
@@ -4908,7 +4864,7 @@ void RtApiDs :: callbackEvent()
       }\r
     }\r
     else { // mode == INPUT\r
-      while ( safeReadPointer < endRead ) {\r
+      while ( safeReadPointer < endRead && stream_.callbackInfo.isRunning ) {\r
         // See comments for playback.\r
         double millis = (endRead - safeReadPointer) * 1000.0;\r
         millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);\r
@@ -4969,8 +4925,6 @@ void RtApiDs :: callbackEvent()
   }\r
 \r
  unlock:\r
-  //  MUTEX_UNLOCK( &stream_.mutex );\r
-\r
   RtApi::tickStreamTime();\r
 }\r
 \r
@@ -5206,6 +5160,12 @@ unsigned int RtApiAlsa :: getDeviceCount( void )
     snd_card_next( &card );\r
   }\r
 \r
+  result = snd_ctl_open( &handle, "default", 0 );\r
+  if (result == 0) {\r
+    nDevices++;\r
+    snd_ctl_close( handle );\r
+  }\r
+\r
   return nDevices;\r
 }\r
 \r
@@ -5252,6 +5212,15 @@ RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
     snd_card_next( &card );\r
   }\r
 \r
+  result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );\r
+  if ( result == 0 ) {\r
+    if ( nDevices == device ) {\r
+      strcpy( name, "default" );\r
+      goto foundDevice;\r
+    }\r
+    nDevices++;\r
+  }\r
+\r
   if ( nDevices == 0 ) {\r
     errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!";\r
     error( RtError::INVALID_USE );\r
@@ -5268,6 +5237,7 @@ RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
   // Thus, use the saved results.\r
   if ( stream_.state != STREAM_CLOSED &&\r
        ( stream_.device[0] == device || stream_.device[1] == device ) ) {\r
+    snd_ctl_close( chandle );\r
     if ( device >= devices_.size() ) {\r
       errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened.";\r
       error( RtError::WARNING );\r
@@ -5284,16 +5254,18 @@ RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
   snd_pcm_hw_params_t *params;\r
   snd_pcm_hw_params_alloca( &params );\r
 \r
-  // First try for playback\r
+  // First try for playback unless default device (which has subdev -1)\r
   stream = SND_PCM_STREAM_PLAYBACK;\r
-  snd_pcm_info_set_device( pcminfo, subdevice );\r
-  snd_pcm_info_set_subdevice( pcminfo, 0 );\r
   snd_pcm_info_set_stream( pcminfo, stream );\r
+  if ( subdevice != -1 ) {\r
+    snd_pcm_info_set_device( pcminfo, subdevice );\r
+    snd_pcm_info_set_subdevice( pcminfo, 0 );\r
 \r
-  result = snd_ctl_pcm_info( chandle, pcminfo );\r
-  if ( result < 0 ) {\r
-    // Device probably doesn't support playback.\r
-    goto captureProbe;\r
+    result = snd_ctl_pcm_info( chandle, pcminfo );\r
+    if ( result < 0 ) {\r
+      // Device probably doesn't support playback.\r
+      goto captureProbe;\r
+    }\r
   }\r
 \r
   result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK );\r
@@ -5328,16 +5300,18 @@ RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
   snd_pcm_close( phandle );\r
 \r
  captureProbe:\r
-  // Now try for capture\r
   stream = SND_PCM_STREAM_CAPTURE;\r
   snd_pcm_info_set_stream( pcminfo, stream );\r
 \r
-  result = snd_ctl_pcm_info( chandle, pcminfo );\r
-  snd_ctl_close( chandle );\r
-  if ( result < 0 ) {\r
-    // Device probably doesn't support capture.\r
-    if ( info.outputChannels == 0 ) return info;\r
-    goto probeParameters;\r
+  // Now try for capture unless default device (with subdev = -1)\r
+  if ( subdevice != -1 ) {\r
+    result = snd_ctl_pcm_info( chandle, pcminfo );\r
+    snd_ctl_close( chandle );\r
+    if ( result < 0 ) {\r
+      // Device probably doesn't support capture.\r
+      if ( info.outputChannels == 0 ) return info;\r
+      goto probeParameters;\r
+    }\r
   }\r
 \r
   result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);\r
@@ -5528,6 +5502,15 @@ bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
       snd_card_next( &card );\r
     }\r
 \r
+    result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );\r
+    if ( result == 0 ) {\r
+      if ( nDevices == device ) {\r
+        strcpy( name, "default" );\r
+        goto foundDevice;\r
+      }\r
+      nDevices++;\r
+    }\r
+\r
     if ( nDevices == 0 ) {\r
       // This should not happen because a check is made before this function is called.\r
       errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!";\r
@@ -5672,6 +5655,7 @@ bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
   }\r
 \r
   // If we get here, no supported format was found.\r
+  snd_pcm_close( phandle );\r
   errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio.";\r
   errorText_ = errorStream_.str();\r
   return FAILURE;\r
@@ -5769,6 +5753,7 @@ bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
   // If attempting to setup a duplex stream, the bufferSize parameter\r
   // MUST be the same in both directions!\r
   if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {\r
+    snd_pcm_close( phandle );\r
     errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";\r
     errorText_ = errorStream_.str();\r
     return FAILURE;\r
@@ -5855,6 +5840,7 @@ bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
     apiInfo = (AlsaHandle *) stream_.apiHandle;\r
   }\r
   apiInfo->handles[mode] = phandle;\r
+  phandle = 0;\r
 \r
   // Allocate necessary internal buffers.\r
   unsigned long bufferBytes;\r
@@ -5923,22 +5909,21 @@ bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
     pthread_attr_t attr;\r
     pthread_attr_init( &attr );\r
     pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );\r
+\r
 #ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)\r
     if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {\r
-      struct sched_param param;\r
+      // We previously attempted to increase the audio callback priority\r
+      // to SCHED_RR here via the attributes.  However, while no errors\r
+      // were reported in doing so, it did not work.  So, now this is\r
+      // done in the alsaCallbackHandler function.\r
+      stream_.callbackInfo.doRealtime = true;\r
       int priority = options->priority;\r
       int min = sched_get_priority_min( SCHED_RR );\r
       int max = sched_get_priority_max( SCHED_RR );\r
       if ( priority < min ) priority = min;\r
       else if ( priority > max ) priority = max;\r
-      param.sched_priority = priority;\r
-      pthread_attr_setschedparam( &attr, &param );\r
-      pthread_attr_setschedpolicy( &attr, SCHED_RR );\r
+      stream_.callbackInfo.priority = priority;\r
     }\r
-    else\r
-      pthread_attr_setschedpolicy( &attr, SCHED_OTHER );\r
-#else\r
-    pthread_attr_setschedpolicy( &attr, SCHED_OTHER );\r
 #endif\r
 \r
     stream_.callbackInfo.isRunning = true;\r
@@ -5962,6 +5947,8 @@ bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
     stream_.apiHandle = 0;\r
   }\r
 \r
+  if ( phandle) snd_pcm_close( phandle );\r
+\r
   for ( int i=0; i<2; i++ ) {\r
     if ( stream_.userBuffer[i] ) {\r
       free( stream_.userBuffer[i] );\r
@@ -6091,11 +6078,6 @@ void RtApiAlsa :: stopStream()
   stream_.state = STREAM_STOPPED;\r
   MUTEX_LOCK( &stream_.mutex );\r
 \r
-  //if ( stream_.state == STREAM_STOPPED ) {\r
-  //  MUTEX_UNLOCK( &stream_.mutex );\r
-  //  return;\r
-  //}\r
-\r
   int result = 0;\r
   AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
   snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;\r
@@ -6121,7 +6103,6 @@ void RtApiAlsa :: stopStream()
   }\r
 \r
  unlock:\r
-  stream_.state = STREAM_STOPPED;\r
   MUTEX_UNLOCK( &stream_.mutex );\r
 \r
   if ( result >= 0 ) return;\r
@@ -6140,11 +6121,6 @@ void RtApiAlsa :: abortStream()
   stream_.state = STREAM_STOPPED;\r
   MUTEX_LOCK( &stream_.mutex );\r
 \r
-  //if ( stream_.state == STREAM_STOPPED ) {\r
-  //  MUTEX_UNLOCK( &stream_.mutex );\r
-  //  return;\r
-  //}\r
-\r
   int result = 0;\r
   AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
   snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;\r
@@ -6167,7 +6143,6 @@ void RtApiAlsa :: abortStream()
   }\r
 \r
  unlock:\r
-  stream_.state = STREAM_STOPPED;\r
   MUTEX_UNLOCK( &stream_.mutex );\r
 \r
   if ( result >= 0 ) return;\r
@@ -6366,6 +6341,14 @@ extern "C" void *alsaCallbackHandler( void *ptr )
   RtApiAlsa *object = (RtApiAlsa *) info->object;\r
   bool *isRunning = &info->isRunning;\r
 \r
+#ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)\r
+  if ( &info->doRealtime ) {\r
+    pthread_t tID = pthread_self();     // ID of this thread\r
+    sched_param prio = { info->priority }; // scheduling priority of thread\r
+    pthread_setschedparam( tID, SCHED_RR, &prio );\r
+  }\r
+#endif\r
+\r
   while ( *isRunning == true ) {\r
     pthread_testcancel();\r
     object->callbackEvent();\r
@@ -6377,6 +6360,462 @@ extern "C" void *alsaCallbackHandler( void *ptr )
 //******************** End of __LINUX_ALSA__ *********************//\r
 #endif\r
 \r
+#if defined(__LINUX_PULSE__)\r
+\r
+// Code written by Peter Meerwald, pmeerw@pmeerw.net\r
+// and Tristan Matthews.\r
+\r
+#include <pulse/error.h>\r
+#include <pulse/simple.h>\r
+#include <cstdio>\r
+\r
+namespace {\r
+const unsigned int SUPPORTED_SAMPLERATES[] = { 8000, 16000, 22050, 32000,\r
+                                               44100, 48000, 96000, 0}; }\r
+\r
+struct rtaudio_pa_format_mapping_t {\r
+  RtAudioFormat rtaudio_format;\r
+  pa_sample_format_t pa_format;\r
+};\r
+\r
+static const rtaudio_pa_format_mapping_t supported_sampleformats[] = {\r
+  {RTAUDIO_SINT16, PA_SAMPLE_S16LE},\r
+  {RTAUDIO_SINT32, PA_SAMPLE_S32LE},\r
+  {RTAUDIO_FLOAT32, PA_SAMPLE_FLOAT32LE},\r
+  {0, PA_SAMPLE_INVALID}};\r
+\r
+struct PulseAudioHandle {\r
+  pa_simple *s_play;\r
+  pa_simple *s_rec;\r
+  pthread_t thread;\r
+  pthread_cond_t runnable_cv;\r
+  bool runnable;\r
+  PulseAudioHandle() : s_play(0), s_rec(0), runnable(false) { }\r
+};\r
+\r
+RtApiPulse::~RtApiPulse()\r
+{\r
+  if ( stream_.state != STREAM_CLOSED )\r
+    closeStream();\r
+}\r
+\r
+unsigned int RtApiPulse::getDeviceCount( void )\r
+{\r
+  return 1;\r
+}\r
+\r
+RtAudio::DeviceInfo RtApiPulse::getDeviceInfo( unsigned int device )\r
+{\r
+  RtAudio::DeviceInfo info;\r
+  info.probed = true;\r
+  info.name = "PulseAudio";\r
+  info.outputChannels = 2;\r
+  info.inputChannels = 2;\r
+  info.duplexChannels = 2;\r
+  info.isDefaultOutput = true;\r
+  info.isDefaultInput = true;\r
+\r
+  for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr )\r
+    info.sampleRates.push_back( *sr );\r
+\r
+  info.nativeFormats = RTAUDIO_SINT16 | RTAUDIO_SINT32 | RTAUDIO_FLOAT32;\r
+\r
+  return info;\r
+}\r
+\r
+extern "C" void *pulseaudio_callback( void * user )\r
+{\r
+  CallbackInfo *cbi = static_cast<CallbackInfo *>( user );\r
+  RtApiPulse *context = static_cast<RtApiPulse *>( cbi->object );\r
+  volatile bool *isRunning = &cbi->isRunning;\r
+\r
+  while ( *isRunning ) {\r
+    pthread_testcancel();\r
+    context->callbackEvent();\r
+  }\r
+\r
+  pthread_exit( NULL );\r
+}\r
+\r
+void RtApiPulse::closeStream( void )\r
+{\r
+  PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
+\r
+  stream_.callbackInfo.isRunning = false;\r
+  if ( pah ) {\r
+    MUTEX_LOCK( &stream_.mutex );\r
+    if ( stream_.state == STREAM_STOPPED ) {\r
+      pah->runnable = true;\r
+      pthread_cond_signal( &pah->runnable_cv );\r
+    }\r
+    MUTEX_UNLOCK( &stream_.mutex );\r
+\r
+    pthread_join( pah->thread, 0 );\r
+    if ( pah->s_play ) {\r
+      pa_simple_flush( pah->s_play, NULL );\r
+      pa_simple_free( pah->s_play );\r
+    }\r
+    if ( pah->s_rec )\r
+      pa_simple_free( pah->s_rec );\r
+\r
+    pthread_cond_destroy( &pah->runnable_cv );\r
+    delete pah;\r
+    stream_.apiHandle = 0;\r
+  }\r
+\r
+  if ( stream_.userBuffer[0] ) {\r
+    free( stream_.userBuffer[0] );\r
+    stream_.userBuffer[0] = 0;\r
+  }\r
+  if ( stream_.userBuffer[1] ) {\r
+    free( stream_.userBuffer[1] );\r
+    stream_.userBuffer[1] = 0;\r
+  }\r
+\r
+  stream_.state = STREAM_CLOSED;\r
+  stream_.mode = UNINITIALIZED;\r
+}\r
+\r
+void RtApiPulse::callbackEvent( void )\r
+{\r
+  PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
+\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    MUTEX_LOCK( &stream_.mutex );\r
+    while ( !pah->runnable )\r
+      pthread_cond_wait( &pah->runnable_cv, &stream_.mutex );\r
+\r
+    if ( stream_.state != STREAM_RUNNING ) {\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
+      return;\r
+    }\r
+    MUTEX_UNLOCK( &stream_.mutex );\r
+  }\r
+\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiPulse::callbackEvent(): the stream is closed ... "\r
+      "this shouldn't happen!";\r
+    error( RtError::WARNING );\r
+    return;\r
+  }\r
+\r
+  RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;\r
+  double streamTime = getStreamTime();\r
+  RtAudioStreamStatus status = 0;\r
+  int doStopStream = callback( stream_.userBuffer[OUTPUT], stream_.userBuffer[INPUT],\r
+                               stream_.bufferSize, streamTime, status,\r
+                               stream_.callbackInfo.userData );\r
+\r
+  if ( doStopStream == 2 ) {\r
+    abortStream();\r
+    return;\r
+  }\r
+\r
+  MUTEX_LOCK( &stream_.mutex );\r
+  void *pulse_in = stream_.doConvertBuffer[INPUT] ? stream_.deviceBuffer : stream_.userBuffer[INPUT];\r
+  void *pulse_out = stream_.doConvertBuffer[OUTPUT] ? stream_.deviceBuffer : stream_.userBuffer[OUTPUT];\r
+\r
+  if ( stream_.state != STREAM_RUNNING )\r
+    goto unlock;\r
+\r
+  int pa_error;\r
+  size_t bytes;\r
+  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+    if ( stream_.doConvertBuffer[OUTPUT] ) {\r
+        convertBuffer( stream_.deviceBuffer,\r
+                       stream_.userBuffer[OUTPUT],\r
+                       stream_.convertInfo[OUTPUT] );\r
+        bytes = stream_.nDeviceChannels[OUTPUT] * stream_.bufferSize *\r
+                formatBytes( stream_.deviceFormat[OUTPUT] );\r
+    } else\r
+        bytes = stream_.nUserChannels[OUTPUT] * stream_.bufferSize *\r
+                formatBytes( stream_.userFormat );\r
+\r
+    if ( pa_simple_write( pah->s_play, pulse_out, bytes, &pa_error ) < 0 ) {\r
+      errorStream_ << "RtApiPulse::callbackEvent: audio write error, " <<\r
+        pa_strerror( pa_error ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      error( RtError::WARNING );\r
+    }\r
+  }\r
+\r
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX) {\r
+    if ( stream_.doConvertBuffer[INPUT] )\r
+      bytes = stream_.nDeviceChannels[INPUT] * stream_.bufferSize *\r
+        formatBytes( stream_.deviceFormat[INPUT] );\r
+    else\r
+      bytes = stream_.nUserChannels[INPUT] * stream_.bufferSize *\r
+        formatBytes( stream_.userFormat );\r
+            \r
+    if ( pa_simple_read( pah->s_rec, pulse_in, bytes, &pa_error ) < 0 ) {\r
+      errorStream_ << "RtApiPulse::callbackEvent: audio read error, " <<\r
+        pa_strerror( pa_error ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      error( RtError::WARNING );\r
+    }\r
+    if ( stream_.doConvertBuffer[INPUT] ) {\r
+      convertBuffer( stream_.userBuffer[INPUT],\r
+                     stream_.deviceBuffer,\r
+                     stream_.convertInfo[INPUT] );\r
+    }\r
+  }\r
+\r
+ unlock:\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+  RtApi::tickStreamTime();\r
+\r
+  if ( doStopStream == 1 )\r
+    stopStream();\r
+}\r
+\r
+void RtApiPulse::startStream( void )\r
+{\r
+  PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
+\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiPulse::startStream(): the stream is not open!";\r
+    error( RtError::INVALID_USE );\r
+    return;\r
+  }\r
+  if ( stream_.state == STREAM_RUNNING ) {\r
+    errorText_ = "RtApiPulse::startStream(): the stream is already running!";\r
+    error( RtError::WARNING );\r
+    return;\r
+  }\r
+\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  stream_.state = STREAM_RUNNING;\r
+\r
+  pah->runnable = true;\r
+  pthread_cond_signal( &pah->runnable_cv );\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+}\r
+\r
+void RtApiPulse::stopStream( void )\r
+{\r
+  PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
+\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiPulse::stopStream(): the stream is not open!";\r
+    error( RtError::INVALID_USE );\r
+    return;\r
+  }\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiPulse::stopStream(): the stream is already stopped!";\r
+    error( RtError::WARNING );\r
+    return;\r
+  }\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  if ( pah && pah->s_play ) {\r
+    int pa_error;\r
+    if ( pa_simple_drain( pah->s_play, &pa_error ) < 0 ) {\r
+      errorStream_ << "RtApiPulse::stopStream: error draining output device, " <<\r
+        pa_strerror( pa_error ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
+      error( RtError::SYSTEM_ERROR );\r
+    }\r
+  }\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+}\r
+\r
+void RtApiPulse::abortStream( void )\r
+{\r
+  PulseAudioHandle *pah = static_cast<PulseAudioHandle*>( stream_.apiHandle );\r
+\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiPulse::abortStream(): the stream is not open!";\r
+    error( RtError::INVALID_USE );\r
+    return;\r
+  }\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiPulse::abortStream(): the stream is already stopped!";\r
+    error( RtError::WARNING );\r
+    return;\r
+  }\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  if ( pah && pah->s_play ) {\r
+    int pa_error;\r
+    if ( pa_simple_flush( pah->s_play, &pa_error ) < 0 ) {\r
+      errorStream_ << "RtApiPulse::abortStream: error flushing output device, " <<\r
+        pa_strerror( pa_error ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
+      error( RtError::SYSTEM_ERROR );\r
+    }\r
+  }\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+}\r
+\r
+bool RtApiPulse::probeDeviceOpen( unsigned int device, StreamMode mode,\r
+                                  unsigned int channels, unsigned int firstChannel,\r
+                                  unsigned int sampleRate, RtAudioFormat format,\r
+                                  unsigned int *bufferSize, RtAudio::StreamOptions *options )\r
+{\r
+  PulseAudioHandle *pah = 0;\r
+  unsigned long bufferBytes = 0;\r
+  pa_sample_spec ss;\r
+\r
+  if ( device != 0 ) return false;\r
+  if ( mode != INPUT && mode != OUTPUT ) return false;\r
+  if ( channels != 1 && channels != 2 ) {\r
+    errorText_ = "RtApiPulse::probeDeviceOpen: unsupported number of channels.";\r
+    return false;\r
+  }\r
+  ss.channels = channels;\r
+\r
+  if ( firstChannel != 0 ) return false;\r
+\r
+  bool sr_found = false;\r
+  for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr ) {\r
+    if ( sampleRate == *sr ) {\r
+      sr_found = true;\r
+      stream_.sampleRate = sampleRate;\r
+      ss.rate = sampleRate;\r
+      break;\r
+    }\r
+  }\r
+  if ( !sr_found ) {\r
+    errorText_ = "RtApiPulse::probeDeviceOpen: unsupported sample rate.";\r
+    return false;\r
+  }\r
+\r
+  bool sf_found = 0;\r
+  for ( const rtaudio_pa_format_mapping_t *sf = supported_sampleformats;\r
+        sf->rtaudio_format && sf->pa_format != PA_SAMPLE_INVALID; ++sf ) {\r
+    if ( format == sf->rtaudio_format ) {\r
+      sf_found = true;\r
+      stream_.userFormat = sf->rtaudio_format;\r
+      ss.format = sf->pa_format;\r
+      break;\r
+    }\r
+  }\r
+  if ( !sf_found ) {\r
+    errorText_ = "RtApiPulse::probeDeviceOpen: unsupported sample format.";\r
+    return false;\r
+  }\r
+\r
+  // Set interleaving parameters.\r
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;\r
+  else stream_.userInterleaved = true;\r
+  stream_.deviceInterleaved[mode] = true;\r
+  stream_.nBuffers = 1;\r
+  stream_.doByteSwap[mode] = false;\r
+  stream_.doConvertBuffer[mode] = channels > 1 && !stream_.userInterleaved;\r
+  stream_.deviceFormat[mode] = stream_.userFormat;\r
+  stream_.nUserChannels[mode] = channels;\r
+  stream_.nDeviceChannels[mode] = channels + firstChannel;\r
+  stream_.channelOffset[mode] = 0;\r
+\r
+  // Allocate necessary internal buffers.\r
+  bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );\r
+  stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );\r
+  if ( stream_.userBuffer[mode] == NULL ) {\r
+    errorText_ = "RtApiPulse::probeDeviceOpen: error allocating user buffer memory.";\r
+    goto error;\r
+  }\r
+  stream_.bufferSize = *bufferSize;\r
+\r
+  if ( stream_.doConvertBuffer[mode] ) {\r
+\r
+    bool makeBuffer = true;\r
+    bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );\r
+    if ( mode == INPUT ) {\r
+      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {\r
+        unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
+        if ( bufferBytes <= bytesOut ) makeBuffer = false;\r
+      }\r
+    }\r
+\r
+    if ( makeBuffer ) {\r
+      bufferBytes *= *bufferSize;\r
+      if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );\r
+      stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );\r
+      if ( stream_.deviceBuffer == NULL ) {\r
+        errorText_ = "RtApiPulse::probeDeviceOpen: error allocating device buffer memory.";\r
+        goto error;\r
+      }\r
+    }\r
+  }\r
+  \r
+  stream_.device[mode] = device;\r
+  stream_.state = STREAM_STOPPED;\r
+\r
+  // Setup the buffer conversion information structure.\r
+  if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );\r
+\r
+  if ( !stream_.apiHandle ) {\r
+    PulseAudioHandle *pah = new PulseAudioHandle;\r
+    if ( !pah ) {\r
+      errorText_ = "RtApiPulse::probeDeviceOpen: error allocating memory for handle.";\r
+      goto error;\r
+    }\r
+\r
+    stream_.apiHandle = pah;\r
+    if ( pthread_cond_init( &pah->runnable_cv, NULL ) != 0 ) {\r
+      errorText_ = "RtApiPulse::probeDeviceOpen: error creating condition variable.";\r
+      goto error;\r
+    }\r
+  }\r
+  pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
+\r
+  int error;\r
+  switch ( mode ) {\r
+  case INPUT:\r
+    pah->s_rec = pa_simple_new( NULL, "RtAudio", PA_STREAM_RECORD, NULL, "Record", &ss, NULL, NULL, &error );\r
+    if ( !pah->s_rec ) {\r
+      errorText_ = "RtApiPulse::probeDeviceOpen: error connecting input to PulseAudio server.";\r
+      goto error;\r
+    }\r
+    break;\r
+  case OUTPUT:\r
+    pah->s_play = pa_simple_new( NULL, "RtAudio", PA_STREAM_PLAYBACK, NULL, "Playback", &ss, NULL, NULL, &error );\r
+    if ( !pah->s_play ) {\r
+      errorText_ = "RtApiPulse::probeDeviceOpen: error connecting output to PulseAudio server.";\r
+      goto error;\r
+    }\r
+    break;\r
+  default:\r
+    goto error;\r
+  }\r
+\r
+  if ( stream_.mode == UNINITIALIZED )\r
+    stream_.mode = mode;\r
+  else if ( stream_.mode == mode )\r
+    goto error;\r
+  else\r
+    stream_.mode = DUPLEX;\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+\r
+  if ( !stream_.callbackInfo.isRunning ) {\r
+    stream_.callbackInfo.object = this;\r
+    stream_.callbackInfo.isRunning = true;\r
+    if ( pthread_create( &pah->thread, NULL, pulseaudio_callback, (void *)&stream_.callbackInfo) != 0 ) {\r
+      errorText_ = "RtApiPulse::probeDeviceOpen: error creating thread.";\r
+      goto error;\r
+    }\r
+  }\r
+  return true;\r
\r
+ error:\r
+  closeStream();\r
+  return false;\r
+}\r
+\r
+//******************** End of __LINUX_PULSE__ *********************//\r
+#endif\r
 \r
 #if defined(__LINUX_OSS__)\r
 \r
@@ -7378,11 +7817,12 @@ unsigned int RtApi :: formatBytes( RtAudioFormat format )
 {\r
   if ( format == RTAUDIO_SINT16 )\r
     return 2;\r
-  else if ( format == RTAUDIO_SINT24 || format == RTAUDIO_SINT32 ||\r
-            format == RTAUDIO_FLOAT32 )\r
+  else if ( format == RTAUDIO_SINT32 || format == RTAUDIO_FLOAT32 )\r
     return 4;\r
   else if ( format == RTAUDIO_FLOAT64 )\r
     return 8;\r
+  else if ( format == RTAUDIO_SINT24 )\r
+    return 3;\r
   else if ( format == RTAUDIO_SINT8 )\r
     return 1;\r
 \r
@@ -7515,11 +7955,11 @@ void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info
       }\r
     }\r
     else if (info.inFormat == RTAUDIO_SINT24) {\r
-      Int32 *in = (Int32 *)inBuffer;\r
+      Int24 *in = (Int24 *)inBuffer;\r
       scale = 1.0 / 8388607.5;\r
       for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
         for (j=0; j<info.channels; j++) {\r
-          out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]] & 0x00ffffff);\r
+          out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]].asInt());\r
           out[info.outOffset[j]] += 0.5;\r
           out[info.outOffset[j]] *= scale;\r
         }\r
@@ -7593,11 +8033,11 @@ void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info
       }\r
     }\r
     else if (info.inFormat == RTAUDIO_SINT24) {\r
-      Int32 *in = (Int32 *)inBuffer;\r
+      Int24 *in = (Int24 *)inBuffer;\r
       scale = (Float32) ( 1.0 / 8388607.5 );\r
       for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
         for (j=0; j<info.channels; j++) {\r
-          out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]] & 0x00ffffff);\r
+          out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]].asInt());\r
           out[info.outOffset[j]] += 0.5;\r
           out[info.outOffset[j]] *= scale;\r
         }\r
@@ -7664,11 +8104,11 @@ void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info
         out += info.outJump;\r
       }\r
     }\r
-    else if (info.inFormat == RTAUDIO_SINT24) { // Hmmm ... we could just leave it in the lower 3 bytes\r
-      Int32 *in = (Int32 *)inBuffer;\r
+    else if (info.inFormat == RTAUDIO_SINT24) {\r
+      Int24 *in = (Int24 *)inBuffer;\r
       for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
         for (j=0; j<info.channels; j++) {\r
-          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];\r
+          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]].asInt();\r
           out[info.outOffset[j]] <<= 8;\r
         }\r
         in += info.inJump;\r
@@ -7708,13 +8148,13 @@ void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info
     }\r
   }\r
   else if (info.outFormat == RTAUDIO_SINT24) {\r
-    Int32 *out = (Int32 *)outBuffer;\r
+    Int24 *out = (Int24 *)outBuffer;\r
     if (info.inFormat == RTAUDIO_SINT8) {\r
       signed char *in = (signed char *)inBuffer;\r
       for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
         for (j=0; j<info.channels; j++) {\r
-          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];\r
-          out[info.outOffset[j]] <<= 16;\r
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 16);\r
+          //out[info.outOffset[j]] <<= 16;\r
         }\r
         in += info.inJump;\r
         out += info.outJump;\r
@@ -7724,8 +8164,8 @@ void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info
       Int16 *in = (Int16 *)inBuffer;\r
       for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
         for (j=0; j<info.channels; j++) {\r
-          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];\r
-          out[info.outOffset[j]] <<= 8;\r
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 8);\r
+          //out[info.outOffset[j]] <<= 8;\r
         }\r
         in += info.inJump;\r
         out += info.outJump;\r
@@ -7733,7 +8173,7 @@ void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info
     }\r
     else if (info.inFormat == RTAUDIO_SINT24) {\r
       // Channel compensation and/or (de)interleaving only.\r
-      Int32 *in = (Int32 *)inBuffer;\r
+      Int24 *in = (Int24 *)inBuffer;\r
       for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
         for (j=0; j<info.channels; j++) {\r
           out[info.outOffset[j]] = in[info.inOffset[j]];\r
@@ -7746,8 +8186,8 @@ void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info
       Int32 *in = (Int32 *)inBuffer;\r
       for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
         for (j=0; j<info.channels; j++) {\r
-          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];\r
-          out[info.outOffset[j]] >>= 8;\r
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] >> 8);\r
+          //out[info.outOffset[j]] >>= 8;\r
         }\r
         in += info.inJump;\r
         out += info.outJump;\r
@@ -7799,10 +8239,10 @@ void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info
       }\r
     }\r
     else if (info.inFormat == RTAUDIO_SINT24) {\r
-      Int32 *in = (Int32 *)inBuffer;\r
+      Int24 *in = (Int24 *)inBuffer;\r
       for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
         for (j=0; j<info.channels; j++) {\r
-          out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 8) & 0x0000ffff);\r
+          out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]].asInt() >> 8);\r
         }\r
         in += info.inJump;\r
         out += info.outJump;\r
@@ -7863,10 +8303,10 @@ void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info
       }\r
     }\r
     else if (info.inFormat == RTAUDIO_SINT24) {\r
-      Int32 *in = (Int32 *)inBuffer;\r
+      Int24 *in = (Int24 *)inBuffer;\r
       for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
         for (j=0; j<info.channels; j++) {\r
-          out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 16) & 0x000000ff);\r
+          out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]].asInt() >> 16);\r
         }\r
         in += info.inJump;\r
         out += info.outJump;\r
@@ -7905,9 +8345,9 @@ void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info
   }\r
 }\r
 \r
-  //static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }\r
-  //static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }\r
-  //static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }\r
+//static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }\r
+//static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }\r
+//static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }\r
 \r
 void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format )\r
 {\r
@@ -7926,8 +8366,7 @@ void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat
       ptr += 2;\r
     }\r
   }\r
-  else if ( format == RTAUDIO_SINT24 ||\r
-            format == RTAUDIO_SINT32 ||\r
+  else if ( format == RTAUDIO_SINT32 ||\r
             format == RTAUDIO_FLOAT32 ) {\r
     for ( unsigned int i=0; i<samples; i++ ) {\r
       // Swap 1st and 4th bytes.\r
@@ -7945,6 +8384,17 @@ void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat
       ptr += 3;\r
     }\r
   }\r
+  else if ( format == RTAUDIO_SINT24 ) {\r
+    for ( unsigned int i=0; i<samples; i++ ) {\r
+      // Swap 1st and 3rd bytes.\r
+      val = *(ptr);\r
+      *(ptr) = *(ptr+2);\r
+      *(ptr+2) = val;\r
+\r
+      // Increment 2 more bytes.\r
+      ptr += 2;\r
+    }\r
+  }\r
   else if ( format == RTAUDIO_FLOAT64 ) {\r
     for ( unsigned int i=0; i<samples; i++ ) {\r
       // Swap 1st and 8th bytes\r