Fix typo in previous.
[rtaudio-cdist.git] / RtAudio.cpp
index 778cbf248557b879dc8b194c29d756c5e002afb1..9b527ef6e085b0fb0cc4602922d56f4132512291 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-2014 Gary P. Scavone\r
+    Copyright (c) 2001-2016 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.1.1\r
+// RtAudio: Version 4.1.2\r
 \r
 #include "RtAudio.h"\r
 #include <iostream>\r
@@ -46,6 +46,7 @@
 #include <cstring>\r
 #include <climits>\r
 #include <algorithm>\r
+#include <cmath>\r
 \r
 // Static variable definitions.\r
 const unsigned int RtApi::MAX_SAMPLE_RATES = 14;\r
@@ -59,6 +60,22 @@ 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
+\r
+  #include "tchar.h"\r
+\r
+  static std::string convertCharPointerToStdString(const char *text)\r
+  {\r
+    return std::string(text);\r
+  }\r
+\r
+  static std::string convertCharPointerToStdString(const wchar_t *text)\r
+  {\r
+    int length = WideCharToMultiByte(CP_UTF8, 0, text, -1, NULL, 0, NULL, NULL);\r
+    std::string s( length-1, '\0' );\r
+    WideCharToMultiByte(CP_UTF8, 0, text, -1, &s[0], length, NULL, NULL);\r
+    return s;\r
+  }\r
+\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
@@ -180,7 +197,7 @@ RtAudio :: RtAudio( RtAudio::Api api )
   getCompiledApi( apis );\r
   for ( unsigned int i=0; i<apis.size(); i++ ) {\r
     openRtApi( apis[i] );\r
-    if ( rtapi_->getDeviceCount() ) break;\r
+    if ( rtapi_ && rtapi_->getDeviceCount() ) break;\r
   }\r
 \r
   if ( rtapi_ ) return;\r
@@ -392,14 +409,16 @@ double RtApi :: getStreamTime( void )
   struct timeval then;\r
   struct timeval now;\r
 \r
-  if ( stream_.state != STREAM_RUNNING || stream_.streamTime == 0.0 )\r
+  // If lastTickTimestamp is 0 it means we haven't had a "last tick" since\r
+  // we started the stream.\r
+  if ( stream_.state != STREAM_RUNNING || (stream_.lastTickTimestamp.tv_sec == 0 && stream_.lastTickTimestamp.tv_usec == 0) )\r
     return stream_.streamTime;\r
 \r
   gettimeofday( &now, NULL );\r
   then = stream_.lastTickTimestamp;\r
   return stream_.streamTime +\r
     ((now.tv_sec + 0.000001 * now.tv_usec) -\r
-     (then.tv_sec + 0.000001 * then.tv_usec));     \r
+     (then.tv_sec + 0.000001 * then.tv_usec));\r
 #else\r
   return stream_.streamTime;\r
 #endif\r
@@ -420,6 +439,14 @@ unsigned int RtApi :: getStreamSampleRate( void )
  return stream_.sampleRate;\r
 }\r
 \r
+void RtApi :: startStream( void )\r
+{\r
+#if defined( HAVE_GETTIMEOFDAY )\r
+  stream_.lastTickTimestamp.tv_sec = 0;\r
+  stream_.lastTickTimestamp.tv_usec = 0;\r
+#endif\r
+}\r
+\r
 \r
 // *************************************************** //\r
 //\r
@@ -762,9 +789,14 @@ RtAudio::DeviceInfo RtApiCore :: getDeviceInfo( unsigned int device )
   bool haveValueRange = false;\r
   info.sampleRates.clear();\r
   for ( UInt32 i=0; i<nRanges; i++ ) {\r
-    if ( rangeList[i].mMinimum == rangeList[i].mMaximum )\r
-      info.sampleRates.push_back( (unsigned int) rangeList[i].mMinimum );\r
-    else {\r
+    if ( rangeList[i].mMinimum == rangeList[i].mMaximum ) {\r
+      unsigned int tmpSr = (unsigned int) rangeList[i].mMinimum;\r
+      info.sampleRates.push_back( tmpSr );\r
+\r
+      if ( !info.preferredSampleRate || ( tmpSr <= 48000 && tmpSr > info.preferredSampleRate ) )\r
+        info.preferredSampleRate = tmpSr;\r
+\r
+    } else {\r
       haveValueRange = true;\r
       if ( rangeList[i].mMinimum > minimumRate ) minimumRate = rangeList[i].mMinimum;\r
       if ( rangeList[i].mMaximum < maximumRate ) maximumRate = rangeList[i].mMaximum;\r
@@ -773,8 +805,12 @@ RtAudio::DeviceInfo RtApiCore :: getDeviceInfo( unsigned int device )
 \r
   if ( haveValueRange ) {\r
     for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
-      if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate )\r
+      if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate ) {\r
         info.sampleRates.push_back( SAMPLE_RATES[k] );\r
+\r
+        if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )\r
+          info.preferredSampleRate = SAMPLE_RATES[k];\r
+      }\r
     }\r
   }\r
 \r
@@ -1381,6 +1417,18 @@ void RtApiCore :: closeStream( void )
 \r
   CoreHandle *handle = (CoreHandle *) stream_.apiHandle;\r
   if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+    if (handle) {\r
+      AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,\r
+        kAudioObjectPropertyScopeGlobal,\r
+        kAudioObjectPropertyElementMaster };\r
+\r
+      property.mSelector = kAudioDeviceProcessorOverload;\r
+      property.mScope = kAudioObjectPropertyScopeGlobal;\r
+      if (AudioObjectRemovePropertyListener( handle->id[0], &property, xrunListener, (void *) handle ) != noErr) {\r
+        errorText_ = "RtApiCore::closeStream(): error removing property listener!";\r
+        error( RtAudioError::WARNING );\r
+      }\r
+    }\r
     if ( stream_.state == STREAM_RUNNING )\r
       AudioDeviceStop( handle->id[0], callbackHandler );\r
 #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )\r
@@ -1392,6 +1440,18 @@ void RtApiCore :: closeStream( void )
   }\r
 \r
   if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {\r
+    if (handle) {\r
+      AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,\r
+        kAudioObjectPropertyScopeGlobal,\r
+        kAudioObjectPropertyElementMaster };\r
+\r
+      property.mSelector = kAudioDeviceProcessorOverload;\r
+      property.mScope = kAudioObjectPropertyScopeGlobal;\r
+      if (AudioObjectRemovePropertyListener( handle->id[1], &property, xrunListener, (void *) handle ) != noErr) {\r
+        errorText_ = "RtApiCore::closeStream(): error removing property listener!";\r
+        error( RtAudioError::WARNING );\r
+      }\r
+    }\r
     if ( stream_.state == STREAM_RUNNING )\r
       AudioDeviceStop( handle->id[1], callbackHandler );\r
 #if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )\r
@@ -1426,6 +1486,7 @@ void RtApiCore :: closeStream( void )
 void RtApiCore :: startStream( void )\r
 {\r
   verifyStream();\r
+  RtApi::startStream();\r
   if ( stream_.state == STREAM_RUNNING ) {\r
     errorText_ = "RtApiCore::startStream(): the stream is already running!";\r
     error( RtAudioError::WARNING );\r
@@ -1780,7 +1841,7 @@ bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
           channelsLeft -= streamChannels;\r
         }\r
       }\r
-      \r
+\r
       if ( stream_.doConvertBuffer[1] ) { // convert from our internal "device" buffer\r
         convertBuffer( stream_.userBuffer[1],\r
                        stream_.deviceBuffer,\r
@@ -1985,7 +2046,9 @@ RtAudio::DeviceInfo RtApiJack :: getDeviceInfo( unsigned int device )
 \r
   // Get the current jack server sample rate.\r
   info.sampleRates.clear();\r
-  info.sampleRates.push_back( jack_get_sample_rate( client ) );\r
+\r
+  info.preferredSampleRate = jack_get_sample_rate( client );\r
+  info.sampleRates.push_back( info.preferredSampleRate );\r
 \r
   // Count the available ports containing the client name as device\r
   // channels.  Jack "input ports" equal RtAudio output channels.\r
@@ -2376,6 +2439,7 @@ void RtApiJack :: closeStream( void )
 void RtApiJack :: startStream( void )\r
 {\r
   verifyStream();\r
+  RtApi::startStream();\r
   if ( stream_.state == STREAM_RUNNING ) {\r
     errorText_ = "RtApiJack::startStream(): the stream is already running!";\r
     error( RtAudioError::WARNING );\r
@@ -2665,7 +2729,7 @@ RtApiAsio :: RtApiAsio()
   // CoInitialize beforehand, but it must be for appartment threading\r
   // (in which case, CoInitilialize will return S_FALSE here).\r
   coInitialized_ = false;\r
-  HRESULT hr = CoInitialize( NULL ); \r
+  HRESULT hr = CoInitialize( NULL );\r
   if ( FAILED(hr) ) {\r
     errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";\r
     error( RtAudioError::WARNING );\r
@@ -2765,8 +2829,12 @@ RtAudio::DeviceInfo RtApiAsio :: getDeviceInfo( unsigned int device )
   info.sampleRates.clear();\r
   for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {\r
     result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );\r
-    if ( result == ASE_OK )\r
+    if ( result == ASE_OK ) {\r
       info.sampleRates.push_back( SAMPLE_RATES[i] );\r
+\r
+      if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )\r
+        info.preferredSampleRate = SAMPLE_RATES[i];\r
+    }\r
   }\r
 \r
   // Determine supported data types ... just check first channel and assume rest are the same.\r
@@ -2825,9 +2893,12 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
                                    unsigned int firstChannel, unsigned int sampleRate,\r
                                    RtAudioFormat format, unsigned int *bufferSize,\r
                                    RtAudio::StreamOptions *options )\r
-{\r
+{////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r
+\r
+  bool isDuplexInput =  mode == INPUT && stream_.mode == OUTPUT;\r
+\r
   // For ASIO, a duplex stream MUST use the same driver.\r
-  if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] != device ) {\r
+  if ( isDuplexInput && stream_.device[0] != device ) {\r
     errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";\r
     return FAILURE;\r
   }\r
@@ -2841,7 +2912,7 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
   }\r
 \r
   // Only load the driver once for duplex stream.\r
-  if ( mode != INPUT || stream_.mode != OUTPUT ) {\r
+  if ( !isDuplexInput ) {\r
     // The getDeviceInfo() function will not work when a stream is open\r
     // because ASIO does not allow multiple devices to run at the same\r
     // time.  Thus, we'll probe the system before opening a stream and\r
@@ -2862,22 +2933,26 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
     }\r
   }\r
 \r
+  // keep them before any "goto error", they are used for error cleanup + goto device boundary checks\r
+  bool buffersAllocated = false;\r
+  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
+  unsigned int nChannels;\r
+\r
+\r
   // Check the device channel count.\r
   long inputChannels, outputChannels;\r
   result = ASIOGetChannels( &inputChannels, &outputChannels );\r
   if ( result != ASE_OK ) {\r
-    drivers.removeCurrentDriver();\r
     errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";\r
     errorText_ = errorStream_.str();\r
-    return FAILURE;\r
+    goto error;\r
   }\r
 \r
   if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) ||\r
        ( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) {\r
-    drivers.removeCurrentDriver();\r
     errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";\r
     errorText_ = errorStream_.str();\r
-    return FAILURE;\r
+    goto error;\r
   }\r
   stream_.nDeviceChannels[mode] = channels;\r
   stream_.nUserChannels[mode] = channels;\r
@@ -2886,30 +2961,27 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
   // Verify the sample rate is supported.\r
   result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );\r
   if ( result != ASE_OK ) {\r
-    drivers.removeCurrentDriver();\r
     errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";\r
     errorText_ = errorStream_.str();\r
-    return FAILURE;\r
+    goto error;\r
   }\r
 \r
   // Get the current sample rate\r
   ASIOSampleRate currentRate;\r
   result = ASIOGetSampleRate( &currentRate );\r
   if ( result != ASE_OK ) {\r
-    drivers.removeCurrentDriver();\r
     errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";\r
     errorText_ = errorStream_.str();\r
-    return FAILURE;\r
+    goto error;\r
   }\r
 \r
   // Set the sample rate only if necessary\r
   if ( currentRate != sampleRate ) {\r
     result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );\r
     if ( result != ASE_OK ) {\r
-      drivers.removeCurrentDriver();\r
       errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";\r
       errorText_ = errorStream_.str();\r
-      return FAILURE;\r
+      goto error;\r
     }\r
   }\r
 \r
@@ -2920,10 +2992,9 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
   else channelInfo.isInput = true;\r
   result = ASIOGetChannelInfo( &channelInfo );\r
   if ( result != ASE_OK ) {\r
-    drivers.removeCurrentDriver();\r
     errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format.";\r
     errorText_ = errorStream_.str();\r
-    return FAILURE;\r
+    goto error;\r
   }\r
 \r
   // Assuming WINDOWS host is always little-endian.\r
@@ -2952,10 +3023,9 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
   }\r
 \r
   if ( stream_.deviceFormat[mode] == 0 ) {\r
-    drivers.removeCurrentDriver();\r
     errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";\r
     errorText_ = errorStream_.str();\r
-    return FAILURE;\r
+    goto error;\r
   }\r
 \r
   // Set the buffer size.  For a duplex stream, this will end up\r
@@ -2964,49 +3034,63 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
   long minSize, maxSize, preferSize, granularity;\r
   result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );\r
   if ( result != ASE_OK ) {\r
-    drivers.removeCurrentDriver();\r
     errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size.";\r
     errorText_ = errorStream_.str();\r
-    return FAILURE;\r
+    goto error;\r
   }\r
 \r
-  if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;\r
-  else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;\r
-  else if ( granularity == -1 ) {\r
-    // Make sure bufferSize is a power of two.\r
-    int log2_of_min_size = 0;\r
-    int log2_of_max_size = 0;\r
+  if ( isDuplexInput ) {\r
+    // When this is the duplex input (output was opened before), then we have to use the same\r
+    // buffersize as the output, because it might use the preferred buffer size, which most\r
+    // likely wasn't passed as input to this. The buffer sizes have to be identically anyway,\r
+    // So instead of throwing an error, make them equal. The caller uses the reference\r
+    // to the "bufferSize" param as usual to set up processing buffers.\r
 \r
-    for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {\r
-      if ( minSize & ((long)1 << i) ) log2_of_min_size = i;\r
-      if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;\r
-    }\r
+    *bufferSize = stream_.bufferSize;\r
 \r
-    long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );\r
-    int min_delta_num = log2_of_min_size;\r
+  } else {\r
+    if ( *bufferSize == 0 ) *bufferSize = preferSize;\r
+    else if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;\r
+    else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;\r
+    else if ( granularity == -1 ) {\r
+      // Make sure bufferSize is a power of two.\r
+      int log2_of_min_size = 0;\r
+      int log2_of_max_size = 0;\r
 \r
-    for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {\r
-      long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );\r
-      if (current_delta < min_delta) {\r
-        min_delta = current_delta;\r
-        min_delta_num = i;\r
+      for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {\r
+        if ( minSize & ((long)1 << i) ) log2_of_min_size = i;\r
+        if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;\r
       }\r
-    }\r
 \r
-    *bufferSize = ( (unsigned int)1 << min_delta_num );\r
-    if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;\r
-    else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;\r
-  }\r
-  else if ( granularity != 0 ) {\r
-    // Set to an even multiple of granularity, rounding up.\r
-    *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;\r
+      long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );\r
+      int min_delta_num = log2_of_min_size;\r
+\r
+      for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {\r
+        long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );\r
+        if (current_delta < min_delta) {\r
+          min_delta = current_delta;\r
+          min_delta_num = i;\r
+        }\r
+      }\r
+\r
+      *bufferSize = ( (unsigned int)1 << min_delta_num );\r
+      if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;\r
+      else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;\r
+    }\r
+    else if ( granularity != 0 ) {\r
+      // Set to an even multiple of granularity, rounding up.\r
+      *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;\r
+    }\r
   }\r
 \r
-  if ( mode == INPUT && stream_.mode == OUTPUT && stream_.bufferSize != *bufferSize ) {\r
-    drivers.removeCurrentDriver();\r
+  /*\r
+  // we don't use it anymore, see above!\r
+  // Just left it here for the case...\r
+  if ( isDuplexInput && stream_.bufferSize != *bufferSize ) {\r
     errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";\r
-    return FAILURE;\r
+    goto error;\r
   }\r
+  */\r
 \r
   stream_.bufferSize = *bufferSize;\r
   stream_.nBuffers = 2;\r
@@ -3018,16 +3102,13 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
   stream_.deviceInterleaved[mode] = false;\r
 \r
   // Allocate, if necessary, our AsioHandle structure for the stream.\r
-  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
   if ( handle == 0 ) {\r
     try {\r
       handle = new AsioHandle;\r
     }\r
     catch ( std::bad_alloc& ) {\r
-      //if ( handle == NULL ) {    \r
-      drivers.removeCurrentDriver();\r
       errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";\r
-      return FAILURE;\r
+      goto error;\r
     }\r
     handle->bufferInfos = 0;\r
 \r
@@ -3042,15 +3123,14 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
   // Create the ASIO internal buffers.  Since RtAudio sets up input\r
   // and output separately, we'll have to dispose of previously\r
   // created output buffers for a duplex stream.\r
-  long inputLatency, outputLatency;\r
   if ( mode == INPUT && stream_.mode == OUTPUT ) {\r
     ASIODisposeBuffers();\r
     if ( handle->bufferInfos ) free( handle->bufferInfos );\r
   }\r
 \r
   // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.\r
-  bool buffersAllocated = false;\r
-  unsigned int i, nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];\r
+  unsigned int i;\r
+  nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];\r
   handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );\r
   if ( handle->bufferInfos == NULL ) {\r
     errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";\r
@@ -3071,18 +3151,37 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
     infos->buffers[0] = infos->buffers[1] = 0;\r
   }\r
 \r
+  // prepare for callbacks\r
+  stream_.sampleRate = sampleRate;\r
+  stream_.device[mode] = device;\r
+  stream_.mode = isDuplexInput ? DUPLEX : mode;\r
+\r
+  // store this class instance before registering callbacks, that are going to use it\r
+  asioCallbackInfo = &stream_.callbackInfo;\r
+  stream_.callbackInfo.object = (void *) this;\r
+\r
   // Set up the ASIO callback structure and create the ASIO data buffers.\r
   asioCallbacks.bufferSwitch = &bufferSwitch;\r
   asioCallbacks.sampleRateDidChange = &sampleRateChanged;\r
   asioCallbacks.asioMessage = &asioMessages;\r
   asioCallbacks.bufferSwitchTimeInfo = NULL;\r
   result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );\r
+  if ( result != ASE_OK ) {\r
+    // Standard method failed. This can happen with strict/misbehaving drivers that return valid buffer size ranges\r
+    // but only accept the preferred buffer size as parameter for ASIOCreateBuffers. eg. Creatives ASIO driver\r
+    // in that case, let's be naïve and try that instead\r
+    *bufferSize = preferSize;\r
+    stream_.bufferSize = *bufferSize;\r
+    result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );\r
+  }\r
+\r
   if ( result != ASE_OK ) {\r
     errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers.";\r
     errorText_ = errorStream_.str();\r
     goto error;\r
   }\r
   buffersAllocated = true;\r
+  stream_.state = STREAM_STOPPED;\r
 \r
   // Set flags for buffer conversion.\r
   stream_.doConvertBuffer[mode] = false;\r
@@ -3105,11 +3204,9 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
 \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
+    if ( isDuplexInput && stream_.deviceBuffer ) {\r
+      unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
+      if ( bufferBytes <= bytesOut ) makeBuffer = false;\r
     }\r
 \r
     if ( makeBuffer ) {\r
@@ -3123,18 +3220,8 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
     }\r
   }\r
 \r
-  stream_.sampleRate = sampleRate;\r
-  stream_.device[mode] = device;\r
-  stream_.state = STREAM_STOPPED;\r
-  asioCallbackInfo = &stream_.callbackInfo;\r
-  stream_.callbackInfo.object = (void *) this;\r
-  if ( stream_.mode == OUTPUT && mode == INPUT )\r
-    // We had already set up an output stream.\r
-    stream_.mode = DUPLEX;\r
-  else\r
-    stream_.mode = mode;\r
-\r
   // Determine device latencies\r
+  long inputLatency, outputLatency;\r
   result = ASIOGetLatencies( &inputLatency, &outputLatency );\r
   if ( result != ASE_OK ) {\r
     errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency.";\r
@@ -3154,32 +3241,38 @@ bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
   return SUCCESS;\r
 \r
  error:\r
-  if ( buffersAllocated )\r
-    ASIODisposeBuffers();\r
-  drivers.removeCurrentDriver();\r
+  if ( !isDuplexInput ) {\r
+    // the cleanup for error in the duplex input, is done by RtApi::openStream\r
+    // So we clean up for single channel only\r
 \r
-  if ( handle ) {\r
-    CloseHandle( handle->condition );\r
-    if ( handle->bufferInfos )\r
-      free( handle->bufferInfos );\r
-    delete handle;\r
-    stream_.apiHandle = 0;\r
-  }\r
+    if ( buffersAllocated )\r
+      ASIODisposeBuffers();\r
 \r
-  for ( int i=0; i<2; i++ ) {\r
-    if ( stream_.userBuffer[i] ) {\r
-      free( stream_.userBuffer[i] );\r
-      stream_.userBuffer[i] = 0;\r
+    drivers.removeCurrentDriver();\r
+\r
+    if ( handle ) {\r
+      CloseHandle( handle->condition );\r
+      if ( handle->bufferInfos )\r
+        free( handle->bufferInfos );\r
+\r
+      delete handle;\r
+      stream_.apiHandle = 0;\r
     }\r
-  }\r
 \r
-  if ( stream_.deviceBuffer ) {\r
-    free( stream_.deviceBuffer );\r
-    stream_.deviceBuffer = 0;\r
+\r
+    if ( stream_.userBuffer[mode] ) {\r
+      free( stream_.userBuffer[mode] );\r
+      stream_.userBuffer[mode] = 0;\r
+    }\r
+\r
+    if ( stream_.deviceBuffer ) {\r
+      free( stream_.deviceBuffer );\r
+      stream_.deviceBuffer = 0;\r
+    }\r
   }\r
 \r
   return FAILURE;\r
-}\r
+}////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r
 \r
 void RtApiAsio :: closeStream()\r
 {\r
@@ -3226,6 +3319,7 @@ bool stopThreadCalled = false;
 void RtApiAsio :: startStream()\r
 {\r
   verifyStream();\r
+  RtApi::startStream();\r
   if ( stream_.state == STREAM_RUNNING ) {\r
     errorText_ = "RtApiAsio::startStream(): the stream is already running!";\r
     error( RtAudioError::WARNING );\r
@@ -3561,13 +3655,13 @@ static long asioMessages( long selector, long value, void* /*message*/, double*
 \r
 static const char* getAsioErrorString( ASIOError result )\r
 {\r
-  struct Messages \r
+  struct Messages\r
   {\r
     ASIOError value;\r
     const char*message;\r
   };\r
 \r
-  static const Messages m[] = \r
+  static const Messages m[] =\r
     {\r
       {   ASE_NotPresent,    "Hardware input or output is not present or available." },\r
       {   ASE_HWMalfunction,  "Hardware is malfunctioning." },\r
@@ -3602,7 +3696,7 @@ static const char* getAsioErrorString( ASIOError result )
 #include <audioclient.h>\r
 #include <avrt.h>\r
 #include <mmdeviceapi.h>\r
-#include <functiondiscoverykeys_devpkey.h>\r
+#include <FunctionDiscoveryKeys_devpkey.h>\r
 \r
 //=============================================================================\r
 \r
@@ -3631,12 +3725,12 @@ public:
       outIndex_( 0 ) {}\r
 \r
   ~WasapiBuffer() {\r
-    delete buffer_;\r
+    free( buffer_ );\r
   }\r
 \r
   // sets the length of the internal ring buffer\r
   void setBufferSize( unsigned int bufferSize, unsigned int formatBytes ) {\r
-    delete buffer_;\r
+    free( buffer_ );\r
 \r
     buffer_ = ( char* ) calloc( bufferSize, formatBytes );\r
 \r
@@ -3795,7 +3889,7 @@ void convertBufferWasapi( char* outBuffer,
   float sampleStep = 1.0f / sampleRatio;\r
   float inSampleFraction = 0.0f;\r
 \r
-  outSampleCount = ( unsigned int ) ( inSampleCount * sampleRatio );\r
+  outSampleCount = ( unsigned int ) roundf( inSampleCount * sampleRatio );\r
 \r
   // frame-by-frame, copy each relative input sample into it's corresponding output sample\r
   for ( unsigned int outSample = 0; outSample < outSampleCount; outSample++ )\r
@@ -3941,7 +4035,6 @@ RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device )
   RtAudio::DeviceInfo info;\r
   unsigned int captureDeviceCount = 0;\r
   unsigned int renderDeviceCount = 0;\r
-  std::wstring deviceName;\r
   std::string defaultDeviceName;\r
   bool isCaptureDevice = false;\r
 \r
@@ -4044,8 +4137,7 @@ RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device )
     goto Exit;\r
   }\r
 \r
-  deviceName = defaultDeviceNameProp.pwszVal;\r
-  defaultDeviceName = std::string( deviceName.begin(), deviceName.end() );\r
+  defaultDeviceName = convertCharPointerToStdString(defaultDeviceNameProp.pwszVal);\r
 \r
   // name\r
   hr = devicePtr->OpenPropertyStore( STGM_READ, &devicePropStore );\r
@@ -4062,8 +4154,7 @@ RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device )
     goto Exit;\r
   }\r
 \r
-  deviceName = deviceNameProp.pwszVal;\r
-  info.name = std::string( deviceName.begin(), deviceName.end() );\r
+  info.name =convertCharPointerToStdString(deviceNameProp.pwszVal);\r
 \r
   // is default\r
   if ( isCaptureDevice ) {\r
@@ -4106,6 +4197,7 @@ RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device )
   for ( unsigned int i = 0; i < MAX_SAMPLE_RATES; i++ ) {\r
     info.sampleRates.push_back( SAMPLE_RATES[i] );\r
   }\r
+  info.preferredSampleRate = deviceFormat->nSamplesPerSec;\r
 \r
   // native format\r
   info.nativeFormats = 0;\r
@@ -4239,6 +4331,7 @@ void RtApiWasapi::closeStream( void )
 void RtApiWasapi::startStream( void )\r
 {\r
   verifyStream();\r
+  RtApi::startStream();\r
 \r
   if ( stream_.state == STREAM_RUNNING ) {\r
     errorText_ = "RtApiWasapi::startStream: The stream is already running.";\r
@@ -5080,10 +5173,10 @@ void RtApiWasapi::wasapiThread()
     // if the callback buffer was pushed renderBuffer reset callbackPulled flag\r
     if ( callbackPushed ) {\r
       callbackPulled = false;\r
+      // tick stream time\r
+      RtApi::tickStreamTime();\r
     }\r
 \r
-    // tick stream time\r
-    RtApi::tickStreamTime();\r
   }\r
 \r
 Exit:\r
@@ -5111,7 +5204,7 @@ Exit:
 #if defined(__WINDOWS_DS__) // Windows DirectSound API\r
 \r
 // Modified by Robin Davies, October 2005\r
-// - Improvements to DirectX pointer chasing. \r
+// - Improvements to DirectX pointer chasing.\r
 // - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.\r
 // - Auto-call CoInitialize for DSOUND and ASIO platforms.\r
 // Various revisions for RtAudio 4.0 by Gary Scavone, April 2007\r
@@ -5151,7 +5244,7 @@ struct DsHandle {
   void *id[2];\r
   void *buffer[2];\r
   bool xrun[2];\r
-  UINT bufferPointer[2];  \r
+  UINT bufferPointer[2];\r
   DWORD dsBufferSize[2];\r
   DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.\r
   HANDLE condition;\r
@@ -5241,14 +5334,11 @@ unsigned int RtApiDs :: getDeviceCount( void )
     error( RtAudioError::WARNING );\r
   }\r
 \r
-  // Clean out any devices that may have disappeared.\r
-  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
-  //unsigned int nErased = 0;\r
-  for ( unsigned int i=0; i<indices.size(); i++ )\r
-    dsDevices.erase( dsDevices.begin()+indices[i] );\r
-  //dsDevices.erase( dsDevices.begin()-nErased++ );\r
+  // Clean out any devices that may have disappeared (code update submitted by Eli Zehngut).\r
+  for ( unsigned int i=0; i<dsDevices.size(); ) {\r
+    if ( dsDevices[i].found == false ) dsDevices.erase( dsDevices.begin() + i );\r
+    else i++;\r
+  }\r
 \r
   return static_cast<unsigned int>(dsDevices.size());\r
 }\r
@@ -5304,8 +5394,12 @@ RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )
   info.sampleRates.clear();\r
   for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
     if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&\r
-         SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate )\r
+         SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate ) {\r
       info.sampleRates.push_back( SAMPLE_RATES[k] );\r
+\r
+      if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )\r
+        info.preferredSampleRate = SAMPLE_RATES[k];\r
+    }\r
   }\r
 \r
   // Get format information.\r
@@ -5987,6 +6081,8 @@ void RtApiDs :: closeStream()
 void RtApiDs :: startStream()\r
 {\r
   verifyStream();\r
+  RtApi::startStream();\r
+\r
   if ( stream_.state == STREAM_RUNNING ) {\r
     errorText_ = "RtApiDs::startStream(): the stream is already running!";\r
     error( RtAudioError::WARNING );\r
@@ -5998,7 +6094,7 @@ void RtApiDs :: startStream()
   // Increase scheduler frequency on lesser windows (a side-effect of\r
   // increasing timer accuracy).  On greater windows (Win2K or later),\r
   // this is already in effect.\r
-  timeBeginPeriod( 1 ); \r
+  timeBeginPeriod( 1 );\r
 \r
   buffersRolling = false;\r
   duplexPrerollBytes = 0;\r
@@ -6260,6 +6356,7 @@ void RtApiDs :: callbackEvent()
       if ( FAILED( result ) ) {\r
         errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
         errorText_ = errorStream_.str();\r
+        MUTEX_UNLOCK( &stream_.mutex );\r
         error( RtAudioError::SYSTEM_ERROR );\r
         return;\r
       }\r
@@ -6267,6 +6364,7 @@ void RtApiDs :: callbackEvent()
       if ( FAILED( result ) ) {\r
         errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
         errorText_ = errorStream_.str();\r
+        MUTEX_UNLOCK( &stream_.mutex );\r
         error( RtAudioError::SYSTEM_ERROR );\r
         return;\r
       }\r
@@ -6275,6 +6373,7 @@ void RtApiDs :: callbackEvent()
         if ( FAILED( result ) ) {\r
           errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
           errorText_ = errorStream_.str();\r
+          MUTEX_UNLOCK( &stream_.mutex );\r
           error( RtAudioError::SYSTEM_ERROR );\r
           return;\r
         }\r
@@ -6282,6 +6381,7 @@ void RtApiDs :: callbackEvent()
         if ( FAILED( result ) ) {\r
           errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
           errorText_ = errorStream_.str();\r
+          MUTEX_UNLOCK( &stream_.mutex );\r
           error( RtAudioError::SYSTEM_ERROR );\r
           return;\r
         }\r
@@ -6303,6 +6403,7 @@ void RtApiDs :: callbackEvent()
       if ( FAILED( result ) ) {\r
         errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
         errorText_ = errorStream_.str();\r
+        MUTEX_UNLOCK( &stream_.mutex );\r
         error( RtAudioError::SYSTEM_ERROR );\r
         return;\r
       }\r
@@ -6314,7 +6415,7 @@ void RtApiDs :: callbackEvent()
   }\r
 \r
   if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
-    \r
+\r
     LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
 \r
     if ( handle->drainCounter > 1 ) { // write zeros to the output stream\r
@@ -6354,6 +6455,7 @@ void RtApiDs :: callbackEvent()
       if ( FAILED( result ) ) {\r
         errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
         errorText_ = errorStream_.str();\r
+        MUTEX_UNLOCK( &stream_.mutex );\r
         error( RtAudioError::SYSTEM_ERROR );\r
         return;\r
       }\r
@@ -6380,7 +6482,7 @@ void RtApiDs :: callbackEvent()
     }\r
 \r
     if ( dsPointerBetween( nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize )\r
-         || dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) { \r
+         || dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) {\r
       // We've strayed into the forbidden zone ... resync the read pointer.\r
       handle->xrun[0] = true;\r
       nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes;\r
@@ -6395,6 +6497,7 @@ void RtApiDs :: callbackEvent()
     if ( FAILED( result ) ) {\r
       errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";\r
       errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
       error( RtAudioError::SYSTEM_ERROR );\r
       return;\r
     }\r
@@ -6408,6 +6511,7 @@ void RtApiDs :: callbackEvent()
     if ( FAILED( result ) ) {\r
       errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";\r
       errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
       error( RtAudioError::SYSTEM_ERROR );\r
       return;\r
     }\r
@@ -6444,6 +6548,7 @@ void RtApiDs :: callbackEvent()
     if ( FAILED( result ) ) {\r
       errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
       errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
       error( RtAudioError::SYSTEM_ERROR );\r
       return;\r
     }\r
@@ -6451,14 +6556,14 @@ void RtApiDs :: callbackEvent()
     if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset\r
     DWORD endRead = nextReadPointer + bufferBytes;\r
 \r
-    // Handling depends on whether we are INPUT or DUPLEX. \r
+    // Handling depends on whether we are INPUT or DUPLEX.\r
     // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,\r
     // then a wait here will drag the write pointers into the forbidden zone.\r
-    // \r
-    // In DUPLEX mode, rather than wait, we will back off the read pointer until \r
-    // it's in a safe position. This causes dropouts, but it seems to be the only \r
-    // practical way to sync up the read and write pointers reliably, given the \r
-    // the very complex relationship between phase and increment of the read and write \r
+    //\r
+    // In DUPLEX mode, rather than wait, we will back off the read pointer until\r
+    // it's in a safe position. This causes dropouts, but it seems to be the only\r
+    // practical way to sync up the read and write pointers reliably, given the\r
+    // the very complex relationship between phase and increment of the read and write\r
     // pointers.\r
     //\r
     // In order to minimize audible dropouts in DUPLEX mode, we will\r
@@ -6505,10 +6610,11 @@ void RtApiDs :: callbackEvent()
         if ( FAILED( result ) ) {\r
           errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
           errorText_ = errorStream_.str();\r
+          MUTEX_UNLOCK( &stream_.mutex );\r
           error( RtAudioError::SYSTEM_ERROR );\r
           return;\r
         }\r
-      \r
+\r
         if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset\r
       }\r
     }\r
@@ -6519,6 +6625,7 @@ void RtApiDs :: callbackEvent()
     if ( FAILED( result ) ) {\r
       errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";\r
       errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
       error( RtAudioError::SYSTEM_ERROR );\r
       return;\r
     }\r
@@ -6540,6 +6647,7 @@ void RtApiDs :: callbackEvent()
     if ( FAILED( result ) ) {\r
       errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";\r
       errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
       error( RtAudioError::SYSTEM_ERROR );\r
       return;\r
     }\r
@@ -6578,21 +6686,6 @@ static unsigned __stdcall callbackHandler( void *ptr )
   return 0;\r
 }\r
 \r
-#include "tchar.h"\r
-\r
-static std::string convertTChar( LPCTSTR name )\r
-{\r
-#if defined( UNICODE ) || defined( _UNICODE )\r
-  int length = WideCharToMultiByte(CP_UTF8, 0, name, -1, NULL, 0, NULL, NULL);\r
-  std::string s( length-1, '\0' );\r
-  WideCharToMultiByte(CP_UTF8, 0, name, -1, &s[0], length, NULL, NULL);\r
-#else\r
-  std::string s( name );\r
-#endif\r
-\r
-  return s;\r
-}\r
-\r
 static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,\r
                                           LPCTSTR description,\r
                                           LPCTSTR /*module*/,\r
@@ -6634,7 +6727,7 @@ static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
   }\r
 \r
   // If good device, then save its name and guid.\r
-  std::string name = convertTChar( description );\r
+  std::string name = convertCharPointerToStdString( description );\r
   //if ( name == "Primary Sound Driver" || name == "Primary Sound Capture Driver" )\r
   if ( lpguid == NULL )\r
     name = "Default Device";\r
@@ -6816,6 +6909,7 @@ RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
 \r
   // Count cards and devices\r
   card = -1;\r
+  subdevice = -1;\r
   snd_card_next( &card );\r
   while ( card >= 0 ) {\r
     sprintf( name, "hw:%d", card );\r
@@ -7029,8 +7123,12 @@ RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
   // Test our discrete set of sample rate values.\r
   info.sampleRates.clear();\r
   for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {\r
-    if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 )\r
+    if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 ) {\r
       info.sampleRates.push_back( SAMPLE_RATES[i] );\r
+\r
+      if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )\r
+        info.preferredSampleRate = SAMPLE_RATES[i];\r
+    }\r
   }\r
   if ( info.sampleRates.size() == 0 ) {\r
     snd_pcm_close( phandle );\r
@@ -7662,6 +7760,7 @@ void RtApiAlsa :: startStream()
   // This method calls snd_pcm_prepare if the device isn't already in that state.\r
 \r
   verifyStream();\r
+  RtApi::startStream();\r
   if ( stream_.state == STREAM_RUNNING ) {\r
     errorText_ = "RtApiAlsa::startStream(): the stream is already running!";\r
     error( RtAudioError::WARNING );\r
@@ -7726,7 +7825,7 @@ void RtApiAlsa :: stopStream()
   AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
   snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;\r
   if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
-    if ( apiInfo->synchronized ) \r
+    if ( apiInfo->synchronized )\r
       result = snd_pcm_drop( handle[0] );\r
     else\r
       result = snd_pcm_drain( handle[0] );\r
@@ -7955,6 +8054,8 @@ void RtApiAlsa :: callbackEvent()
             errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << ".";\r
             errorText_ = errorStream_.str();\r
           }\r
+          else\r
+            errorText_ =  "RtApiAlsa::callbackEvent: audio write error, underrun.";\r
         }\r
         else {\r
           errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";\r
@@ -7988,7 +8089,7 @@ static void *alsaCallbackHandler( void *ptr )
   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
+  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
@@ -8013,6 +8114,7 @@ static void *alsaCallbackHandler( void *ptr )
 \r
 #include <pulse/error.h>\r
 #include <pulse/simple.h>\r
+#include <pulse/pulseaudio.h>\r
 #include <cstdio>\r
 \r
 static const unsigned int SUPPORTED_SAMPLERATES[] = { 8000, 16000, 22050, 32000,\r
@@ -8049,8 +8151,33 @@ unsigned int RtApiPulse::getDeviceCount( void )
   return 1;\r
 }\r
 \r
+void RtApiPulse::sinkInfoCallback(pa_context*, const pa_sink_info* info, int, void* arg)\r
+{\r
+  RtApiPulse* api = (RtApiPulse *) arg;\r
+  if (info) {\r
+    api->channels_ = info->sample_spec.channels;\r
+  }\r
+  pa_threaded_mainloop_signal(api->mainloop_, 0);\r
+}\r
+\r
+void RtApiPulse::contextStateCallback(pa_context* c, void* arg)\r
+{\r
+  pa_threaded_mainloop* mainloop = (pa_threaded_mainloop*) arg;\r
+\r
+  switch (pa_context_get_state(c)) {\r
+  case PA_CONTEXT_READY:\r
+  case PA_CONTEXT_TERMINATED:\r
+  case PA_CONTEXT_FAILED:\r
+    pa_threaded_mainloop_signal(mainloop, 0);\r
+    break;\r
+  default:\r
+    break;\r
+  }\r
+}\r
+\r
 RtAudio::DeviceInfo RtApiPulse::getDeviceInfo( unsigned int /*device*/ )\r
 {\r
+  /* Set up some defaults in case we crash and burn */\r
   RtAudio::DeviceInfo info;\r
   info.probed = true;\r
   info.name = "PulseAudio";\r
@@ -8063,8 +8190,75 @@ RtAudio::DeviceInfo RtApiPulse::getDeviceInfo( unsigned int /*device*/ )
   for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr )\r
     info.sampleRates.push_back( *sr );\r
 \r
+  info.preferredSampleRate = 48000;\r
   info.nativeFormats = RTAUDIO_SINT16 | RTAUDIO_SINT32 | RTAUDIO_FLOAT32;\r
 \r
+  /* Get the number of output channels from pulseaudio.  A simple task, you say?\r
+     "What is your mainloop?" */\r
+  mainloop_ = pa_threaded_mainloop_new();\r
+  if (!mainloop_) {\r
+    return info;\r
+  }\r
+\r
+  pa_threaded_mainloop_start(mainloop_);\r
+  pa_threaded_mainloop_lock(mainloop_);\r
+\r
+  /* "And what is your context?" */\r
+  pa_context* context = pa_context_new(pa_threaded_mainloop_get_api(mainloop_), "RtAudio");\r
+  if (!context) {\r
+    pa_threaded_mainloop_unlock(mainloop_);\r
+    pa_threaded_mainloop_stop(mainloop_);\r
+    pa_threaded_mainloop_free(mainloop_);\r
+    mainloop_ = 0;\r
+    return info;\r
+  }\r
+\r
+  pa_context_set_state_callback(context, contextStateCallback, mainloop_);\r
+\r
+  pa_context_connect(context, 0, (pa_context_flags_t) 0, 0);\r
+\r
+  /* "And what is your favourite colour?" */\r
+  int connected = 0;\r
+  pa_context_state_t state = pa_context_get_state(context);\r
+  for (; !connected; state = pa_context_get_state(context)) {\r
+    switch (state) {\r
+    case PA_CONTEXT_READY:\r
+      connected = 1;\r
+      continue;\r
+    case PA_CONTEXT_FAILED:\r
+    case PA_CONTEXT_TERMINATED:\r
+      /* Blue! No, I mean red! */\r
+      pa_threaded_mainloop_unlock(mainloop_);\r
+      pa_context_disconnect(context);\r
+      pa_context_unref(context);\r
+      pa_threaded_mainloop_stop(mainloop_);\r
+      pa_threaded_mainloop_free(mainloop_);\r
+      mainloop_ = 0;\r
+      return info;\r
+    default:\r
+      pa_threaded_mainloop_wait(mainloop_);\r
+      break;\r
+    }\r
+  }\r
+\r
+  pa_operation* op = pa_context_get_sink_info_by_index(context, 0, sinkInfoCallback, this);\r
+\r
+  if (op) {\r
+    pa_operation_unref(op);\r
+  }\r
+\r
+  pa_threaded_mainloop_wait(mainloop_);\r
+  pa_threaded_mainloop_unlock(mainloop_);\r
+\r
+  pa_context_disconnect(context);\r
+  pa_context_unref(context);\r
+\r
+  pa_threaded_mainloop_stop(mainloop_);\r
+  pa_threaded_mainloop_free(mainloop_);\r
+  mainloop_ = 0;\r
+\r
+  info.outputChannels = channels_;\r
+\r
   return info;\r
 }\r
 \r
@@ -8191,7 +8385,7 @@ void RtApiPulse::callbackEvent( void )
     else\r
       bytes = stream_.nUserChannels[INPUT] * stream_.bufferSize *\r
         formatBytes( stream_.userFormat );\r
-            \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
@@ -8209,12 +8403,22 @@ void RtApiPulse::callbackEvent( void )
   MUTEX_UNLOCK( &stream_.mutex );\r
   RtApi::tickStreamTime();\r
 \r
+  if (pah->s_play) {\r
+    int e = 0;\r
+    pa_usec_t const lat = pa_simple_get_latency(pah->s_play, &e);\r
+    if (e == 0) {\r
+      stream_.latency[0] = lat * stream_.sampleRate / 1000000;\r
+    }\r
+  }\r
+\r
   if ( doStopStream == 1 )\r
     stopStream();\r
 }\r
 \r
 void RtApiPulse::startStream( void )\r
 {\r
+  RtApi::startStream();\r
+\r
   PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
 \r
   if ( stream_.state == STREAM_CLOSED ) {\r
@@ -8253,6 +8457,7 @@ void RtApiPulse::stopStream( void )
   }\r
 \r
   stream_.state = STREAM_STOPPED;\r
+  pah->runnable = false;\r
   MUTEX_LOCK( &stream_.mutex );\r
 \r
   if ( pah && pah->s_play ) {\r
@@ -8287,6 +8492,7 @@ void RtApiPulse::abortStream( void )
   }\r
 \r
   stream_.state = STREAM_STOPPED;\r
+  pah->runnable = false;\r
   MUTEX_LOCK( &stream_.mutex );\r
 \r
   if ( pah && pah->s_play ) {\r
@@ -8316,10 +8522,6 @@ bool RtApiPulse::probeDeviceOpen( unsigned int device, StreamMode mode,
 \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
@@ -8425,13 +8627,12 @@ bool RtApiPulse::probeDeviceOpen( unsigned int device, StreamMode mode,
   pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
 \r
   int error;\r
-  if ( !options->streamName.empty() ) streamName = options->streamName;\r
+  if ( options && !options->streamName.empty() ) streamName = options->streamName;\r
   switch ( mode ) {\r
   case INPUT:\r
     pa_buffer_attr buffer_attr;\r
     buffer_attr.fragsize = bufferBytes;\r
     buffer_attr.maxlength = -1;\r
-\r
     pah->s_rec = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_RECORD, NULL, "Record", &ss, NULL, &buffer_attr, &error );\r
     if ( !pah->s_rec ) {\r
       errorText_ = "RtApiPulse::probeDeviceOpen: error connecting input to PulseAudio server.";\r
@@ -8439,7 +8640,38 @@ bool RtApiPulse::probeDeviceOpen( unsigned int device, StreamMode mode,
     }\r
     break;\r
   case OUTPUT:\r
-    pah->s_play = pa_simple_new( NULL, "RtAudio", PA_STREAM_PLAYBACK, NULL, "Playback", &ss, NULL, NULL, &error );\r
+    /* XXX: hard-coded for DCP-o-matic */\r
+    pa_channel_map map;\r
+    pa_channel_map_init(&map);\r
+    /* XXX: need to check 7.1 */\r
+    map.channels = channels;\r
+\r
+    if (channels > 0) {\r
+      map.map[0] = PA_CHANNEL_POSITION_FRONT_LEFT;\r
+    }\r
+    if (channels > 1) {\r
+      map.map[1] = PA_CHANNEL_POSITION_FRONT_RIGHT;\r
+    }\r
+    if (channels > 2) {\r
+      map.map[2] = PA_CHANNEL_POSITION_FRONT_CENTER;\r
+    }\r
+    if (channels > 3) {\r
+      map.map[3] = PA_CHANNEL_POSITION_LFE;\r
+    }\r
+    if (channels > 4) {\r
+      map.map[4] = PA_CHANNEL_POSITION_REAR_LEFT;\r
+    }\r
+    if (channels > 5) {\r
+      map.map[5] = PA_CHANNEL_POSITION_REAR_RIGHT;\r
+    }\r
+    if (channels > 6) {\r
+      map.map[6] = PA_CHANNEL_POSITION_SIDE_LEFT;\r
+    }\r
+    if (channels > 7) {\r
+      map.map[7] = PA_CHANNEL_POSITION_SIDE_RIGHT;\r
+    }\r
+\r
+    pah->s_play = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_PLAYBACK, NULL, "Playback", &ss, &map, NULL, &error );\r
     if ( !pah->s_play ) {\r
       errorText_ = "RtApiPulse::probeDeviceOpen: error connecting output to PulseAudio server.";\r
       goto error;\r
@@ -8467,7 +8699,7 @@ bool RtApiPulse::probeDeviceOpen( unsigned int device, StreamMode mode,
 \r
   stream_.state = STREAM_STOPPED;\r
   return true;\r
\r
+\r
  error:\r
   if ( pah && stream_.callbackInfo.isRunning ) {\r
     pthread_cond_destroy( &pah->runnable_cv );\r
@@ -8631,6 +8863,10 @@ RtAudio::DeviceInfo RtApiOss :: getDeviceInfo( unsigned int device )
       for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
         if ( ainfo.rates[i] == SAMPLE_RATES[k] ) {\r
           info.sampleRates.push_back( SAMPLE_RATES[k] );\r
+\r
+          if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )\r
+            info.preferredSampleRate = SAMPLE_RATES[k];\r
+\r
           break;\r
         }\r
       }\r
@@ -8639,8 +8875,12 @@ RtAudio::DeviceInfo RtApiOss :: getDeviceInfo( unsigned int device )
   else {\r
     // Check min and max rate values;\r
     for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
-      if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] )\r
+      if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] ) {\r
         info.sampleRates.push_back( SAMPLE_RATES[k] );\r
+\r
+        if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )\r
+          info.preferredSampleRate = SAMPLE_RATES[k];\r
+      }\r
     }\r
   }\r
 \r
@@ -9143,6 +9383,7 @@ void RtApiOss :: closeStream()
 void RtApiOss :: startStream()\r
 {\r
   verifyStream();\r
+  RtApi::startStream();\r
   if ( stream_.state == STREAM_RUNNING ) {\r
     errorText_ = "RtApiOss::startStream(): the stream is already running!";\r
     error( RtAudioError::WARNING );\r
@@ -10051,8 +10292,8 @@ void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info
 \r
 void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format )\r
 {\r
-  register char val;\r
-  register char *ptr;\r
+  char val;\r
+  char *ptr;\r
 \r
   ptr = buffer;\r
   if ( format == RTAUDIO_SINT16 ) {\r
@@ -10134,4 +10375,3 @@ void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat
   // End:\r
   //\r
   // vim: et sts=2 sw=2\r
-\r