Various changes in preparation for new 4.0.5 release (GS).
authorGary Scavone <gary@music.mcgill.ca>
Thu, 15 Jan 2009 20:26:42 +0000 (20:26 +0000)
committerStephen Sinclair <sinclair@music.mcgill.ca>
Thu, 10 Oct 2013 23:38:24 +0000 (01:38 +0200)
RtAudio.cpp
RtAudio.h
doc/doxygen/Doxyfile
doc/doxygen/footer.html
doc/doxygen/license.txt
doc/doxygen/tutorial.txt
doc/release.txt
install
readme

index b16535b07cc19aa69db85c1e4cc7afd3b4c47da7..f86ea126525e453baf6f36b530e4afe26f8473e6 100644 (file)
@@ -10,7 +10,7 @@
     RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
 
     RtAudio: realtime audio i/o C++ classes
-    Copyright (c) 2001-2008 Gary P. Scavone
+    Copyright (c) 2001-2009 Gary P. Scavone
 
     Permission is hereby granted, free of charge, to any person
     obtaining a copy of this software and associated documentation files
@@ -38,7 +38,7 @@
 */
 /************************************************************************/
 
-// RtAudio: Version 4.0.4
+// RtAudio: Version 4.0.5
 
 #include "RtAudio.h"
 #include <iostream>
@@ -880,8 +880,6 @@ bool RtApiCore :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
 
   free( bufferList );
 
-  std::cout << "deviceStreams = " << nStreams << ", firstStream = " << firstStream << ", streamCount = " << streamCount << ", channelOffset = " << channelOffset << std::endl;
-
   // Determine the buffer size.
   AudioValueRange      bufferRange;
   dataSize = sizeof( AudioValueRange );
@@ -1097,9 +1095,6 @@ bool RtApiCore :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigne
   else if ( monoMode && stream_.userInterleaved )
     stream_.doConvertBuffer[mode] = true;
 
-  std::cout << "doConvert = " << stream_.doConvertBuffer[mode] << ", userInterleaved = " << stream_.userInterleaved << ", deviceInterleaved = " << stream_.deviceInterleaved[mode] << std::endl;
-  std::cout << "nUserChannels = " << stream_.nUserChannels[mode] << ", nDeviceChannels = " << stream_.nDeviceChannels[mode] << std::endl;
-
   // Allocate our CoreHandle structure for the stream.
   CoreHandle *handle = 0;
   if ( stream_.apiHandle == 0 ) {
@@ -1326,6 +1321,11 @@ void RtApiCore :: stopStream( void )
 
   MUTEX_LOCK( &stream_.mutex );
 
+  if ( stream_.state == STREAM_STOPPED ) {
+    MUTEX_UNLOCK( &stream_.mutex );
+    return;
+  }
+
   OSStatus result = noErr;
   CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
   if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
@@ -1353,10 +1353,11 @@ void RtApiCore :: stopStream( void )
     }
   }
 
+  stream_.state = STREAM_STOPPED;
+
  unlock:
   MUTEX_UNLOCK( &stream_.mutex );
 
-  stream_.state = STREAM_STOPPED;
   if ( result == noErr ) return;
   error( RtError::SYSTEM_ERROR );
 }
@@ -1401,6 +1402,12 @@ bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
 
   MUTEX_LOCK( &stream_.mutex );
 
+  // The state might change while waiting on a mutex.
+  if ( stream_.state == STREAM_STOPPED ) {
+    MUTEX_UNLOCK( &stream_.mutex );
+    return SUCCESS;
+  }
+
   AudioDeviceID outputDevice = handle->id[0];
 
   // Invoke user callback to get fresh output data UNLESS we are
@@ -1630,799 +1637,810 @@ bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
   return SUCCESS;
 }
 
-  const char* RtApiCore :: getErrorCode( OSStatus code )
-  {
-    switch( code ) {
+const char* RtApiCore :: getErrorCode( OSStatus code )
+{
+  switch( code ) {
 
-    case kAudioHardwareNotRunningError:
-      return "kAudioHardwareNotRunningError";
+  case kAudioHardwareNotRunningError:
+    return "kAudioHardwareNotRunningError";
 
-    case kAudioHardwareUnspecifiedError:
-      return "kAudioHardwareUnspecifiedError";
+  case kAudioHardwareUnspecifiedError:
+    return "kAudioHardwareUnspecifiedError";
 
-    case kAudioHardwareUnknownPropertyError:
-      return "kAudioHardwareUnknownPropertyError";
+  case kAudioHardwareUnknownPropertyError:
+    return "kAudioHardwareUnknownPropertyError";
 
-    case kAudioHardwareBadPropertySizeError:
-      return "kAudioHardwareBadPropertySizeError";
+  case kAudioHardwareBadPropertySizeError:
+    return "kAudioHardwareBadPropertySizeError";
 
-    case kAudioHardwareIllegalOperationError:
-      return "kAudioHardwareIllegalOperationError";
+  case kAudioHardwareIllegalOperationError:
+    return "kAudioHardwareIllegalOperationError";
 
-    case kAudioHardwareBadObjectError:
-      return "kAudioHardwareBadObjectError";
+  case kAudioHardwareBadObjectError:
+    return "kAudioHardwareBadObjectError";
 
-    case kAudioHardwareBadDeviceError:
-      return "kAudioHardwareBadDeviceError";
+  case kAudioHardwareBadDeviceError:
+    return "kAudioHardwareBadDeviceError";
 
-    case kAudioHardwareBadStreamError:
-      return "kAudioHardwareBadStreamError";
+  case kAudioHardwareBadStreamError:
+    return "kAudioHardwareBadStreamError";
 
-    case kAudioHardwareUnsupportedOperationError:
-      return "kAudioHardwareUnsupportedOperationError";
+  case kAudioHardwareUnsupportedOperationError:
+    return "kAudioHardwareUnsupportedOperationError";
 
-    case kAudioDeviceUnsupportedFormatError:
-      return "kAudioDeviceUnsupportedFormatError";
+  case kAudioDeviceUnsupportedFormatError:
+    return "kAudioDeviceUnsupportedFormatError";
 
-    case kAudioDevicePermissionsError:
-      return "kAudioDevicePermissionsError";
+  case kAudioDevicePermissionsError:
+    return "kAudioDevicePermissionsError";
 
-    default:
-      return "CoreAudio unknown error";
-    }
+  default:
+    return "CoreAudio unknown error";
   }
+}
 
   //******************** End of __MACOSX_CORE__ *********************//
 #endif
 
 #if defined(__UNIX_JACK__)
 
-  // JACK is a low-latency audio server, originally written for the
-  // GNU/Linux operating system and now also ported to OS-X. It can
-  // connect a number of different applications to an audio device, as
-  // well as allowing them to share audio between themselves.
-  //
-  // When using JACK with RtAudio, "devices" refer to JACK clients that
-  // have ports connected to the server.  The JACK server is typically
-  // started in a terminal as follows:
-  //
-  // .jackd -d alsa -d hw:0
-  //
-  // or through an interface program such as qjackctl.  Many of the
-  // parameters normally set for a stream are fixed by the JACK server
-  // and can be specified when the JACK server is started.  In
-  // particular,
-  //
-  // .jackd -d alsa -d hw:0 -r 44100 -p 512 -n 4
-  //
-  // specifies a sample rate of 44100 Hz, a buffer size of 512 sample
-  // frames, and number of buffers = 4.  Once the server is running, it
-  // is not possible to override these values.  If the values are not
-  // specified in the command-line, the JACK server uses default values.
-  //
-  // The JACK server does not have to be running when an instance of
-  // RtApiJack is created, though the function getDeviceCount() will
-  // report 0 devices found until JACK has been started.  When no
-  // devices are available (i.e., the JACK server is not running), a
-  // stream cannot be opened.
+// JACK is a low-latency audio server, originally written for the
+// GNU/Linux operating system and now also ported to OS-X. It can
+// connect a number of different applications to an audio device, as
+// well as allowing them to share audio between themselves.
+//
+// When using JACK with RtAudio, "devices" refer to JACK clients that
+// have ports connected to the server.  The JACK server is typically
+// started in a terminal as follows:
+//
+// .jackd -d alsa -d hw:0
+//
+// or through an interface program such as qjackctl.  Many of the
+// parameters normally set for a stream are fixed by the JACK server
+// and can be specified when the JACK server is started.  In
+// particular,
+//
+// .jackd -d alsa -d hw:0 -r 44100 -p 512 -n 4
+//
+// specifies a sample rate of 44100 Hz, a buffer size of 512 sample
+// frames, and number of buffers = 4.  Once the server is running, it
+// is not possible to override these values.  If the values are not
+// specified in the command-line, the JACK server uses default values.
+//
+// The JACK server does not have to be running when an instance of
+// RtApiJack is created, though the function getDeviceCount() will
+// report 0 devices found until JACK has been started.  When no
+// devices are available (i.e., the JACK server is not running), a
+// stream cannot be opened.
 
 #include <jack/jack.h>
 #include <unistd.h>
 
-  // A structure to hold various information related to the Jack API
-  // implementation.
-  struct JackHandle {
-    jack_client_t *client;
-    jack_port_t **ports[2];
-    std::string deviceName[2];
-    bool xrun[2];
-    pthread_cond_t condition;
-    int drainCounter;       // Tracks callback counts when draining
-    bool internalDrain;     // Indicates if stop is initiated from callback or not.
-
-    JackHandle()
-      :client(0), drainCounter(0), internalDrain(false) { ports[0] = 0; ports[1] = 0; xrun[0] = false; xrun[1] = false; }
-  };
-
-  RtApiJack :: RtApiJack()
-  {
-    // Nothing to do here.
-  }
-
-  RtApiJack :: ~RtApiJack()
-  {
-    if ( stream_.state != STREAM_CLOSED ) closeStream();
-  }
-
-  unsigned int RtApiJack :: getDeviceCount( void )
-  {
-    // See if we can become a jack client.
-    jack_options_t options = (jack_options_t) ( JackNoStartServer | JackUseExactName ); //JackNullOption;
-    jack_status_t *status = NULL;
-    jack_client_t *client = jack_client_open( "RtApiJackCount", options, status );
-    if ( client == 0 ) return 0;
-
-    const char **ports;
-    std::string port, previousPort;
-    unsigned int nChannels = 0, nDevices = 0;
-    ports = jack_get_ports( client, NULL, NULL, 0 );
-    if ( ports ) {
-      // Parse the port names up to the first colon (:).
-      size_t iColon = 0;
-      do {
-        port = (char *) ports[ nChannels ];
-        iColon = port.find(":");
-        if ( iColon != std::string::npos ) {
-          port = port.substr( 0, iColon + 1 );
-          if ( port != previousPort ) {
-            nDevices++;
-            previousPort = port;
-          }
-        }
-      } while ( ports[++nChannels] );
-      free( ports );
-    }
+// A structure to hold various information related to the Jack API
+// implementation.
+struct JackHandle {
+  jack_client_t *client;
+  jack_port_t **ports[2];
+  std::string deviceName[2];
+  bool xrun[2];
+  pthread_cond_t condition;
+  int drainCounter;       // Tracks callback counts when draining
+  bool internalDrain;     // Indicates if stop is initiated from callback or not.
 
-    jack_client_close( client );
-    return nDevices;
-  }
+  JackHandle()
+    :client(0), drainCounter(0), internalDrain(false) { ports[0] = 0; ports[1] = 0; xrun[0] = false; xrun[1] = false; }
+};
 
-  RtAudio::DeviceInfo RtApiJack :: getDeviceInfo( unsigned int device )
-  {
-    RtAudio::DeviceInfo info;
-    info.probed = false;
+RtApiJack :: RtApiJack()
+{
+  // Nothing to do here.
+}
 
-    jack_options_t options = (jack_options_t) ( JackNoStartServer | JackUseExactName ); //JackNullOption
-    jack_status_t *status = NULL;
-    jack_client_t *client = jack_client_open( "RtApiJackInfo", options, status );
-    if ( client == 0 ) {
-      errorText_ = "RtApiJack::getDeviceInfo: Jack server not found or connection error!";
-      error( RtError::WARNING );
-      return info;
-    }
+RtApiJack :: ~RtApiJack()
+{
+  if ( stream_.state != STREAM_CLOSED ) closeStream();
+}
 
-    const char **ports;
-    std::string port, previousPort;
-    unsigned int nPorts = 0, nDevices = 0;
-    ports = jack_get_ports( client, NULL, NULL, 0 );
-    if ( ports ) {
-      // Parse the port names up to the first colon (:).
-      size_t iColon = 0;
-      do {
-        port = (char *) ports[ nPorts ];
-        iColon = port.find(":");
-        if ( iColon != std::string::npos ) {
-          port = port.substr( 0, iColon );
-          if ( port != previousPort ) {
-            if ( nDevices == device ) info.name = port;
-            nDevices++;
-            previousPort = port;
-          }
+unsigned int RtApiJack :: getDeviceCount( void )
+{
+  // See if we can become a jack client.
+  jack_options_t options = (jack_options_t) ( JackNoStartServer | JackUseExactName ); //JackNullOption;
+  jack_status_t *status = NULL;
+  jack_client_t *client = jack_client_open( "RtApiJackCount", options, status );
+  if ( client == 0 ) return 0;
+
+  const char **ports;
+  std::string port, previousPort;
+  unsigned int nChannels = 0, nDevices = 0;
+  ports = jack_get_ports( client, NULL, NULL, 0 );
+  if ( ports ) {
+    // Parse the port names up to the first colon (:).
+    size_t iColon = 0;
+    do {
+      port = (char *) ports[ nChannels ];
+      iColon = port.find(":");
+      if ( iColon != std::string::npos ) {
+        port = port.substr( 0, iColon + 1 );
+        if ( port != previousPort ) {
+          nDevices++;
+          previousPort = port;
         }
-      } while ( ports[++nPorts] );
-      free( ports );
-    }
-
-    if ( device >= nDevices ) {
-      errorText_ = "RtApiJack::getDeviceInfo: device ID is invalid!";
-      error( RtError::INVALID_USE );
-    }
+      }
+    } while ( ports[++nChannels] );
+    free( ports );
+  }
 
-    // Get the current jack server sample rate.
-    info.sampleRates.clear();
-    info.sampleRates.push_back( jack_get_sample_rate( client ) );
+  jack_client_close( client );
+  return nDevices;
+}
 
-    // Count the available ports containing the client name as device
-    // channels.  Jack "input ports" equal RtAudio output channels.
-    unsigned int nChannels = 0;
-    ports = jack_get_ports( client, info.name.c_str(), NULL, JackPortIsInput );
-    if ( ports ) {
-      while ( ports[ nChannels ] ) nChannels++;
-      free( ports );
-      info.outputChannels = nChannels;
-    }
+RtAudio::DeviceInfo RtApiJack :: getDeviceInfo( unsigned int device )
+{
+  RtAudio::DeviceInfo info;
+  info.probed = false;
 
-    // Jack "output ports" equal RtAudio input channels.
-    nChannels = 0;
-    ports = jack_get_ports( client, info.name.c_str(), NULL, JackPortIsOutput );
-    if ( ports ) {
-      while ( ports[ nChannels ] ) nChannels++;
-      free( ports );
-      info.inputChannels = nChannels;
-    }
+  jack_options_t options = (jack_options_t) ( JackNoStartServer | JackUseExactName ); //JackNullOption
+  jack_status_t *status = NULL;
+  jack_client_t *client = jack_client_open( "RtApiJackInfo", options, status );
+  if ( client == 0 ) {
+    errorText_ = "RtApiJack::getDeviceInfo: Jack server not found or connection error!";
+    error( RtError::WARNING );
+    return info;
+  }
 
-    if ( info.outputChannels == 0 && info.inputChannels == 0 ) {
-      jack_client_close(client);
-      errorText_ = "RtApiJack::getDeviceInfo: error determining Jack input/output channels!";
-      error( RtError::WARNING );
-      return info;
-    }
+  const char **ports;
+  std::string port, previousPort;
+  unsigned int nPorts = 0, nDevices = 0;
+  ports = jack_get_ports( client, NULL, NULL, 0 );
+  if ( ports ) {
+    // Parse the port names up to the first colon (:).
+    size_t iColon = 0;
+    do {
+      port = (char *) ports[ nPorts ];
+      iColon = port.find(":");
+      if ( iColon != std::string::npos ) {
+        port = port.substr( 0, iColon );
+        if ( port != previousPort ) {
+          if ( nDevices == device ) info.name = port;
+          nDevices++;
+          previousPort = port;
+        }
+      }
+    } while ( ports[++nPorts] );
+    free( ports );
+  }
 
-    // If device opens for both playback and capture, we determine the channels.
-    if ( info.outputChannels > 0 && info.inputChannels > 0 )
-      info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
+  if ( device >= nDevices ) {
+    errorText_ = "RtApiJack::getDeviceInfo: device ID is invalid!";
+    error( RtError::INVALID_USE );
+  }
 
-    // Jack always uses 32-bit floats.
-    info.nativeFormats = RTAUDIO_FLOAT32;
+  // Get the current jack server sample rate.
+  info.sampleRates.clear();
+  info.sampleRates.push_back( jack_get_sample_rate( client ) );
+
+  // Count the available ports containing the client name as device
+  // channels.  Jack "input ports" equal RtAudio output channels.
+  unsigned int nChannels = 0;
+  ports = jack_get_ports( client, info.name.c_str(), NULL, JackPortIsInput );
+  if ( ports ) {
+    while ( ports[ nChannels ] ) nChannels++;
+    free( ports );
+    info.outputChannels = nChannels;
+  }
 
-    // Jack doesn't provide default devices so we'll use the first available one.
-    if ( device == 0 && info.outputChannels > 0 )
-      info.isDefaultOutput = true;
-    if ( device == 0 && info.inputChannels > 0 )
-      info.isDefaultInput = true;
+  // Jack "output ports" equal RtAudio input channels.
+  nChannels = 0;
+  ports = jack_get_ports( client, info.name.c_str(), NULL, JackPortIsOutput );
+  if ( ports ) {
+    while ( ports[ nChannels ] ) nChannels++;
+    free( ports );
+    info.inputChannels = nChannels;
+  }
 
+  if ( info.outputChannels == 0 && info.inputChannels == 0 ) {
     jack_client_close(client);
-    info.probed = true;
+    errorText_ = "RtApiJack::getDeviceInfo: error determining Jack input/output channels!";
+    error( RtError::WARNING );
     return info;
   }
 
-  int jackCallbackHandler( jack_nframes_t nframes, void *infoPointer )
-  {
-    CallbackInfo *info = (CallbackInfo *) infoPointer;
+  // If device opens for both playback and capture, we determine the channels.
+  if ( info.outputChannels > 0 && info.inputChannels > 0 )
+    info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
 
-    RtApiJack *object = (RtApiJack *) info->object;
-    if ( object->callbackEvent( (unsigned long) nframes ) == false ) return 1;
+  // Jack always uses 32-bit floats.
+  info.nativeFormats = RTAUDIO_FLOAT32;
 
-    return 0;
-  }
+  // Jack doesn't provide default devices so we'll use the first available one.
+  if ( device == 0 && info.outputChannels > 0 )
+    info.isDefaultOutput = true;
+  if ( device == 0 && info.inputChannels > 0 )
+    info.isDefaultInput = true;
 
-  void jackShutdown( void *infoPointer )
-  {
-    CallbackInfo *info = (CallbackInfo *) infoPointer;
-    RtApiJack *object = (RtApiJack *) info->object;
+  jack_client_close(client);
+  info.probed = true;
+  return info;
+}
 
-    // Check current stream state.  If stopped, then we'll assume this
-    // was called as a result of a call to RtApiJack::stopStream (the
-    // deactivation of a client handle causes this function to be called).
-    // If not, we'll assume the Jack server is shutting down or some
-    // other problem occurred and we should close the stream.
-    if ( object->isStreamRunning() == false ) return;
+int jackCallbackHandler( jack_nframes_t nframes, void *infoPointer )
+{
+  CallbackInfo *info = (CallbackInfo *) infoPointer;
 
-    object->closeStream();
-    std::cerr << "\nRtApiJack: the Jack server is shutting down this client ... stream stopped and closed!!\n" << std::endl;
-  }
+  RtApiJack *object = (RtApiJack *) info->object;
+  if ( object->callbackEvent( (unsigned long) nframes ) == false ) return 1;
 
-  int jackXrun( void *infoPointer )
-  {
-    JackHandle *handle = (JackHandle *) infoPointer;
+  return 0;
+}
 
-    if ( handle->ports[0] ) handle->xrun[0] = true;
-    if ( handle->ports[1] ) handle->xrun[1] = true;
+void jackShutdown( void *infoPointer )
+{
+  CallbackInfo *info = (CallbackInfo *) infoPointer;
+  RtApiJack *object = (RtApiJack *) info->object;
 
-    return 0;
-  }
+  // Check current stream state.  If stopped, then we'll assume this
+  // was called as a result of a call to RtApiJack::stopStream (the
+  // deactivation of a client handle causes this function to be called).
+  // If not, we'll assume the Jack server is shutting down or some
+  // other problem occurred and we should close the stream.
+  if ( object->isStreamRunning() == false ) return;
 
-  bool RtApiJack :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
-                                     unsigned int firstChannel, unsigned int sampleRate,
-                                     RtAudioFormat format, unsigned int *bufferSize,
-                                     RtAudio::StreamOptions *options )
-  {
-    JackHandle *handle = (JackHandle *) stream_.apiHandle;
-
-    // Look for jack server and try to become a client (only do once per stream).
-    jack_client_t *client = 0;
-    if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) {
-      jack_options_t jackoptions = (jack_options_t) ( JackNoStartServer | JackUseExactName ); //JackNullOption;
-      jack_status_t *status = NULL;
-      if ( options && !options->streamName.empty() )
-        client = jack_client_open( options->streamName.c_str(), jackoptions, status );
-      else
-        client = jack_client_open( "RtApiJack", jackoptions, status );
-      if ( client == 0 ) {
-        errorText_ = "RtApiJack::probeDeviceOpen: Jack server not found or connection error!";
-        error( RtError::WARNING );
-        return FAILURE;
-      }
-    }
-    else {
-      // The handle must have been created on an earlier pass.
-      client = handle->client;
-    }
-
-    const char **ports;
-    std::string port, previousPort, deviceName;
-    unsigned int nPorts = 0, nDevices = 0;
-    ports = jack_get_ports( client, NULL, NULL, 0 );
-    if ( ports ) {
-      // Parse the port names up to the first colon (:).
-      size_t iColon = 0;
-      do {
-        port = (char *) ports[ nPorts ];
-        iColon = port.find(":");
-        if ( iColon != std::string::npos ) {
-          port = port.substr( 0, iColon );
-          if ( port != previousPort ) {
-            if ( nDevices == device ) deviceName = port;
-            nDevices++;
-            previousPort = port;
-          }
-        }
-      } while ( ports[++nPorts] );
-      free( ports );
-    }
+  object->closeStream();
+  std::cerr << "\nRtApiJack: the Jack server is shutting down this client ... stream stopped and closed!!\n" << std::endl;
+}
 
-    if ( device >= nDevices ) {
-      errorText_ = "RtApiJack::probeDeviceOpen: device ID is invalid!";
-      return FAILURE;
-    }
+int jackXrun( void *infoPointer )
+{
+  JackHandle *handle = (JackHandle *) infoPointer;
 
-    // Count the available ports containing the client name as device
-    // channels.  Jack "input ports" equal RtAudio output channels.
-    unsigned int nChannels = 0;
-    unsigned long flag = JackPortIsInput;
-    if ( mode == INPUT ) flag = JackPortIsOutput;
-    ports = jack_get_ports( client, deviceName.c_str(), NULL, flag );
-    if ( ports ) {
-      while ( ports[ nChannels ] ) nChannels++;
-      free( ports );
-    }
+  if ( handle->ports[0] ) handle->xrun[0] = true;
+  if ( handle->ports[1] ) handle->xrun[1] = true;
 
-    // Compare the jack ports for specified client to the requested number of channels.
-    if ( nChannels < (channels + firstChannel) ) {
-      errorStream_ << "RtApiJack::probeDeviceOpen: requested number of channels (" << channels << ") + offset (" << firstChannel << ") not found for specified device (" << device << ":" << deviceName << ").";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  return 0;
+}
 
-    // Check the jack server sample rate.
-    unsigned int jackRate = jack_get_sample_rate( client );
-    if ( sampleRate != jackRate ) {
-      jack_client_close( client );
-      errorStream_ << "RtApiJack::probeDeviceOpen: the requested sample rate (" << sampleRate << ") is different than the JACK server rate (" << jackRate << ").";
-      errorText_ = errorStream_.str();
+bool RtApiJack :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
+                                   unsigned int firstChannel, unsigned int sampleRate,
+                                   RtAudioFormat format, unsigned int *bufferSize,
+                                   RtAudio::StreamOptions *options )
+{
+  JackHandle *handle = (JackHandle *) stream_.apiHandle;
+
+  // Look for jack server and try to become a client (only do once per stream).
+  jack_client_t *client = 0;
+  if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) {
+    jack_options_t jackoptions = (jack_options_t) ( JackNoStartServer | JackUseExactName ); //JackNullOption;
+    jack_status_t *status = NULL;
+    if ( options && !options->streamName.empty() )
+      client = jack_client_open( options->streamName.c_str(), jackoptions, status );
+    else
+      client = jack_client_open( "RtApiJack", jackoptions, status );
+    if ( client == 0 ) {
+      errorText_ = "RtApiJack::probeDeviceOpen: Jack server not found or connection error!";
+      error( RtError::WARNING );
       return FAILURE;
     }
-    stream_.sampleRate = jackRate;
-
-    // Get the latency of the JACK port.
-    ports = jack_get_ports( client, deviceName.c_str(), NULL, flag );
-    if ( ports[ firstChannel ] )
-      stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );
+  }
+  else {
+    // The handle must have been created on an earlier pass.
+    client = handle->client;
+  }
+
+  const char **ports;
+  std::string port, previousPort, deviceName;
+  unsigned int nPorts = 0, nDevices = 0;
+  ports = jack_get_ports( client, NULL, NULL, 0 );
+  if ( ports ) {
+    // Parse the port names up to the first colon (:).
+    size_t iColon = 0;
+    do {
+      port = (char *) ports[ nPorts ];
+      iColon = port.find(":");
+      if ( iColon != std::string::npos ) {
+        port = port.substr( 0, iColon );
+        if ( port != previousPort ) {
+          if ( nDevices == device ) deviceName = port;
+          nDevices++;
+          previousPort = port;
+        }
+      }
+    } while ( ports[++nPorts] );
     free( ports );
+  }
 
-    // The jack server always uses 32-bit floating-point data.
-    stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
-    stream_.userFormat = format;
+  if ( device >= nDevices ) {
+    errorText_ = "RtApiJack::probeDeviceOpen: device ID is invalid!";
+    return FAILURE;
+  }
 
-    if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
-    else stream_.userInterleaved = true;
+  // Count the available ports containing the client name as device
+  // channels.  Jack "input ports" equal RtAudio output channels.
+  unsigned int nChannels = 0;
+  unsigned long flag = JackPortIsInput;
+  if ( mode == INPUT ) flag = JackPortIsOutput;
+  ports = jack_get_ports( client, deviceName.c_str(), NULL, flag );
+  if ( ports ) {
+    while ( ports[ nChannels ] ) nChannels++;
+    free( ports );
+  }
 
-    // Jack always uses non-interleaved buffers.
-    stream_.deviceInterleaved[mode] = false;
+  // Compare the jack ports for specified client to the requested number of channels.
+  if ( nChannels < (channels + firstChannel) ) {
+    errorStream_ << "RtApiJack::probeDeviceOpen: requested number of channels (" << channels << ") + offset (" << firstChannel << ") not found for specified device (" << device << ":" << deviceName << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    // Jack always provides host byte-ordered data.
-    stream_.doByteSwap[mode] = false;
+  // Check the jack server sample rate.
+  unsigned int jackRate = jack_get_sample_rate( client );
+  if ( sampleRate != jackRate ) {
+    jack_client_close( client );
+    errorStream_ << "RtApiJack::probeDeviceOpen: the requested sample rate (" << sampleRate << ") is different than the JACK server rate (" << jackRate << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
+  stream_.sampleRate = jackRate;
 
-    // Get the buffer size.  The buffer size and number of buffers
-    // (periods) is set when the jack server is started.
-    stream_.bufferSize = (int) jack_get_buffer_size( client );
-    *bufferSize = stream_.bufferSize;
+  // Get the latency of the JACK port.
+  ports = jack_get_ports( client, deviceName.c_str(), NULL, flag );
+  if ( ports[ firstChannel ] )
+    stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );
+  free( ports );
 
-    stream_.nDeviceChannels[mode] = channels;
-    stream_.nUserChannels[mode] = channels;
+  // The jack server always uses 32-bit floating-point data.
+  stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
+  stream_.userFormat = format;
 
-    // Set flags for buffer conversion.
-    stream_.doConvertBuffer[mode] = false;
-    if ( stream_.userFormat != stream_.deviceFormat[mode] )
-      stream_.doConvertBuffer[mode] = true;
-    if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
-         stream_.nUserChannels[mode] > 1 )
-      stream_.doConvertBuffer[mode] = true;
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
+  else stream_.userInterleaved = true;
 
-    // Allocate our JackHandle structure for the stream.
-    if ( handle == 0 ) {
-      try {
-        handle = new JackHandle;
-      }
-      catch ( std::bad_alloc& ) {
-        errorText_ = "RtApiJack::probeDeviceOpen: error allocating JackHandle memory.";
-        goto error;
-      }
+  // Jack always uses non-interleaved buffers.
+  stream_.deviceInterleaved[mode] = false;
 
-      if ( pthread_cond_init(&handle->condition, NULL) ) {
-        errorText_ = "RtApiJack::probeDeviceOpen: error initializing pthread condition variable.";
-        goto error;
-      }
-      stream_.apiHandle = (void *) handle;
-      handle->client = client;
-    }
-    handle->deviceName[mode] = deviceName;
+  // Jack always provides host byte-ordered data.
+  stream_.doByteSwap[mode] = false;
 
-    // Allocate necessary internal buffers.
-    unsigned long bufferBytes;
-    bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
-    stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
-    if ( stream_.userBuffer[mode] == NULL ) {
-      errorText_ = "RtApiJack::probeDeviceOpen: error allocating user buffer memory.";
-      goto error;
-    }
+  // Get the buffer size.  The buffer size and number of buffers
+  // (periods) is set when the jack server is started.
+  stream_.bufferSize = (int) jack_get_buffer_size( client );
+  *bufferSize = stream_.bufferSize;
 
-    if ( stream_.doConvertBuffer[mode] ) {
+  stream_.nDeviceChannels[mode] = channels;
+  stream_.nUserChannels[mode] = channels;
 
-      bool makeBuffer = true;
-      if ( mode == OUTPUT )
-        bufferBytes = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
-      else { // mode == INPUT
-        bufferBytes = stream_.nDeviceChannels[1] * formatBytes( stream_.deviceFormat[1] );
-        if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
-          unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-          if ( bufferBytes < bytesOut ) makeBuffer = false;
-        }
-      }
+  // Set flags for buffer conversion.
+  stream_.doConvertBuffer[mode] = false;
+  if ( stream_.userFormat != stream_.deviceFormat[mode] )
+    stream_.doConvertBuffer[mode] = true;
+  if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
+       stream_.nUserChannels[mode] > 1 )
+    stream_.doConvertBuffer[mode] = true;
 
-      if ( makeBuffer ) {
-        bufferBytes *= *bufferSize;
-        if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
-        stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
-        if ( stream_.deviceBuffer == NULL ) {
-          errorText_ = "RtApiJack::probeDeviceOpen: error allocating device buffer memory.";
-          goto error;
-        }
-      }
+  // Allocate our JackHandle structure for the stream.
+  if ( handle == 0 ) {
+    try {
+      handle = new JackHandle;
+    }
+    catch ( std::bad_alloc& ) {
+      errorText_ = "RtApiJack::probeDeviceOpen: error allocating JackHandle memory.";
+      goto error;
     }
 
-    // Allocate memory for the Jack ports (channels) identifiers.
-    handle->ports[mode] = (jack_port_t **) malloc ( sizeof (jack_port_t *) * channels );
-    if ( handle->ports[mode] == NULL )  {
-      errorText_ = "RtApiJack::probeDeviceOpen: error allocating port memory.";
+    if ( pthread_cond_init(&handle->condition, NULL) ) {
+      errorText_ = "RtApiJack::probeDeviceOpen: error initializing pthread condition variable.";
       goto error;
     }
+    stream_.apiHandle = (void *) handle;
+    handle->client = client;
+  }
+  handle->deviceName[mode] = deviceName;
 
-    stream_.device[mode] = device;
-    stream_.channelOffset[mode] = firstChannel;
-    stream_.state = STREAM_STOPPED;
-    stream_.callbackInfo.object = (void *) this;
+  // Allocate necessary internal buffers.
+  unsigned long bufferBytes;
+  bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
+  stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
+  if ( stream_.userBuffer[mode] == NULL ) {
+    errorText_ = "RtApiJack::probeDeviceOpen: error allocating user buffer memory.";
+    goto error;
+  }
 
-    if ( stream_.mode == OUTPUT && mode == INPUT )
-      // We had already set up the stream for output.
-      stream_.mode = DUPLEX;
-    else {
-      stream_.mode = mode;
-      jack_set_process_callback( handle->client, jackCallbackHandler, (void *) &stream_.callbackInfo );
-      jack_set_xrun_callback( handle->client, jackXrun, (void *) &handle );
-      jack_on_shutdown( handle->client, jackShutdown, (void *) &stream_.callbackInfo );
-    }
+  if ( stream_.doConvertBuffer[mode] ) {
 
-    // Register our ports.
-    char label[64];
-    if ( mode == OUTPUT ) {
-      for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
-        snprintf( label, 64, "outport %d", i );
-        handle->ports[0][i] = jack_port_register( handle->client, (const char *)label,
-                                                  JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
+    bool makeBuffer = true;
+    if ( mode == OUTPUT )
+      bufferBytes = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
+    else { // mode == INPUT
+      bufferBytes = stream_.nDeviceChannels[1] * formatBytes( stream_.deviceFormat[1] );
+      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
+        unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
+        if ( bufferBytes < bytesOut ) makeBuffer = false;
       }
     }
-    else {
-      for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
-        snprintf( label, 64, "inport %d", i );
-        handle->ports[1][i] = jack_port_register( handle->client, (const char *)label,
-                                                  JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 );
+
+    if ( makeBuffer ) {
+      bufferBytes *= *bufferSize;
+      if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
+      stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
+      if ( stream_.deviceBuffer == NULL ) {
+        errorText_ = "RtApiJack::probeDeviceOpen: error allocating device buffer memory.";
+        goto error;
       }
     }
+  }
 
-    // Setup the buffer conversion information structure.  We don't use
-    // buffers to do channel offsets, so we override that parameter
-    // here.
-    if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
-
-    return SUCCESS;
+  // Allocate memory for the Jack ports (channels) identifiers.
+  handle->ports[mode] = (jack_port_t **) malloc ( sizeof (jack_port_t *) * channels );
+  if ( handle->ports[mode] == NULL )  {
+    errorText_ = "RtApiJack::probeDeviceOpen: error allocating port memory.";
+    goto error;
+  }
 
-  error:
-    if ( handle ) {
-      pthread_cond_destroy( &handle->condition );
-      jack_client_close( handle->client );
+  stream_.device[mode] = device;
+  stream_.channelOffset[mode] = firstChannel;
+  stream_.state = STREAM_STOPPED;
+  stream_.callbackInfo.object = (void *) this;
 
-      if ( handle->ports[0] ) free( handle->ports[0] );
-      if ( handle->ports[1] ) free( handle->ports[1] );
+  if ( stream_.mode == OUTPUT && mode == INPUT )
+    // We had already set up the stream for output.
+    stream_.mode = DUPLEX;
+  else {
+    stream_.mode = mode;
+    jack_set_process_callback( handle->client, jackCallbackHandler, (void *) &stream_.callbackInfo );
+    jack_set_xrun_callback( handle->client, jackXrun, (void *) &handle );
+    jack_on_shutdown( handle->client, jackShutdown, (void *) &stream_.callbackInfo );
+  }
 
-      delete handle;
-      stream_.apiHandle = 0;
+  // Register our ports.
+  char label[64];
+  if ( mode == OUTPUT ) {
+    for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
+      snprintf( label, 64, "outport %d", i );
+      handle->ports[0][i] = jack_port_register( handle->client, (const char *)label,
+                                                JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );
     }
-
-    for ( int i=0; i<2; i++ ) {
-      if ( stream_.userBuffer[i] ) {
-        free( stream_.userBuffer[i] );
-        stream_.userBuffer[i] = 0;
-      }
+  }
+  else {
+    for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
+      snprintf( label, 64, "inport %d", i );
+      handle->ports[1][i] = jack_port_register( handle->client, (const char *)label,
+                                                JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 );
     }
+  }
 
-    if ( stream_.deviceBuffer ) {
-      free( stream_.deviceBuffer );
-      stream_.deviceBuffer = 0;
-    }
+  // Setup the buffer conversion information structure.  We don't use
+  // buffers to do channel offsets, so we override that parameter
+  // here.
+  if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
 
-    return FAILURE;
-  }
+  return SUCCESS;
 
-  void RtApiJack :: closeStream( void )
-  {
-    if ( stream_.state == STREAM_CLOSED ) {
-      errorText_ = "RtApiJack::closeStream(): no open stream to close!";
-      error( RtError::WARNING );
-      return;
-    }
+ error:
+  if ( handle ) {
+    pthread_cond_destroy( &handle->condition );
+    jack_client_close( handle->client );
 
-    JackHandle *handle = (JackHandle *) stream_.apiHandle;
-    if ( handle ) {
+    if ( handle->ports[0] ) free( handle->ports[0] );
+    if ( handle->ports[1] ) free( handle->ports[1] );
 
-      if ( stream_.state == STREAM_RUNNING )
-        jack_deactivate( handle->client );
+    delete handle;
+    stream_.apiHandle = 0;
+  }
 
-      jack_client_close( handle->client );
+  for ( int i=0; i<2; i++ ) {
+    if ( stream_.userBuffer[i] ) {
+      free( stream_.userBuffer[i] );
+      stream_.userBuffer[i] = 0;
     }
+  }
 
-    if ( handle ) {
-      if ( handle->ports[0] ) free( handle->ports[0] );
-      if ( handle->ports[1] ) free( handle->ports[1] );
-      pthread_cond_destroy( &handle->condition );
-      delete handle;
-      stream_.apiHandle = 0;
-    }
+  if ( stream_.deviceBuffer ) {
+    free( stream_.deviceBuffer );
+    stream_.deviceBuffer = 0;
+  }
 
-    for ( int i=0; i<2; i++ ) {
-      if ( stream_.userBuffer[i] ) {
-        free( stream_.userBuffer[i] );
-        stream_.userBuffer[i] = 0;
-      }
-    }
+  return FAILURE;
+}
 
-    if ( stream_.deviceBuffer ) {
-      free( stream_.deviceBuffer );
-      stream_.deviceBuffer = 0;
-    }
+void RtApiJack :: closeStream( void )
+{
+  if ( stream_.state == STREAM_CLOSED ) {
+    errorText_ = "RtApiJack::closeStream(): no open stream to close!";
+    error( RtError::WARNING );
+    return;
+  }
+
+  JackHandle *handle = (JackHandle *) stream_.apiHandle;
+  if ( handle ) {
+
+    if ( stream_.state == STREAM_RUNNING )
+      jack_deactivate( handle->client );
 
-    stream_.mode = UNINITIALIZED;
-    stream_.state = STREAM_CLOSED;
+    jack_client_close( handle->client );
   }
 
-  void RtApiJack :: startStream( void )
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_RUNNING ) {
-      errorText_ = "RtApiJack::startStream(): the stream is already running!";
-      error( RtError::WARNING );
-      return;
+  if ( handle ) {
+    if ( handle->ports[0] ) free( handle->ports[0] );
+    if ( handle->ports[1] ) free( handle->ports[1] );
+    pthread_cond_destroy( &handle->condition );
+    delete handle;
+    stream_.apiHandle = 0;
+  }
+
+  for ( int i=0; i<2; i++ ) {
+    if ( stream_.userBuffer[i] ) {
+      free( stream_.userBuffer[i] );
+      stream_.userBuffer[i] = 0;
     }
+  }
+
+  if ( stream_.deviceBuffer ) {
+    free( stream_.deviceBuffer );
+    stream_.deviceBuffer = 0;
+  }
 
-    MUTEX_LOCK(&stream_.mutex);
+  stream_.mode = UNINITIALIZED;
+  stream_.state = STREAM_CLOSED;
+}
 
-    JackHandle *handle = (JackHandle *) stream_.apiHandle;
-    int result = jack_activate( handle->client );
-    if ( result ) {
-      errorText_ = "RtApiJack::startStream(): unable to activate JACK client!";
+void RtApiJack :: startStream( void )
+{
+  verifyStream();
+  if ( stream_.state == STREAM_RUNNING ) {
+    errorText_ = "RtApiJack::startStream(): the stream is already running!";
+    error( RtError::WARNING );
+    return;
+  }
+
+  MUTEX_LOCK(&stream_.mutex);
+
+  JackHandle *handle = (JackHandle *) stream_.apiHandle;
+  int result = jack_activate( handle->client );
+  if ( result ) {
+    errorText_ = "RtApiJack::startStream(): unable to activate JACK client!";
+    goto unlock;
+  }
+
+  const char **ports;
+
+  // Get the list of available ports.
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+    result = 1;
+    ports = jack_get_ports( handle->client, handle->deviceName[0].c_str(), NULL, JackPortIsInput);
+    if ( ports == NULL) {
+      errorText_ = "RtApiJack::startStream(): error determining available JACK input ports!";
       goto unlock;
     }
 
-    const char **ports;
-
-    // Get the list of available ports.
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+    // Now make the port connections.  Since RtAudio wasn't designed to
+    // allow the user to select particular channels of a device, we'll
+    // just open the first "nChannels" ports with offset.
+    for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
       result = 1;
-      ports = jack_get_ports( handle->client, handle->deviceName[0].c_str(), NULL, JackPortIsInput);
-      if ( ports == NULL) {
-        errorText_ = "RtApiJack::startStream(): error determining available JACK input ports!";
+      if ( ports[ stream_.channelOffset[0] + i ] )
+        result = jack_connect( handle->client, jack_port_name( handle->ports[0][i] ), ports[ stream_.channelOffset[0] + i ] );
+      if ( result ) {
+        free( ports );
+        errorText_ = "RtApiJack::startStream(): error connecting output ports!";
         goto unlock;
       }
+    }
+    free(ports);
+  }
 
-      // Now make the port connections.  Since RtAudio wasn't designed to
-      // allow the user to select particular channels of a device, we'll
-      // just open the first "nChannels" ports with offset.
-      for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
-        result = 1;
-        if ( ports[ stream_.channelOffset[0] + i ] )
-          result = jack_connect( handle->client, jack_port_name( handle->ports[0][i] ), ports[ stream_.channelOffset[0] + i ] );
-        if ( result ) {
-          free( ports );
-          errorText_ = "RtApiJack::startStream(): error connecting output ports!";
-          goto unlock;
-        }
-      }
-      free(ports);
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
+    result = 1;
+    ports = jack_get_ports( handle->client, handle->deviceName[1].c_str(), NULL, JackPortIsOutput );
+    if ( ports == NULL) {
+      errorText_ = "RtApiJack::startStream(): error determining available JACK output ports!";
+      goto unlock;
     }
 
-    if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
+    // Now make the port connections.  See note above.
+    for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
       result = 1;
-      ports = jack_get_ports( handle->client, handle->deviceName[1].c_str(), NULL, JackPortIsOutput );
-      if ( ports == NULL) {
-        errorText_ = "RtApiJack::startStream(): error determining available JACK output ports!";
+      if ( ports[ stream_.channelOffset[1] + i ] )
+        result = jack_connect( handle->client, ports[ stream_.channelOffset[1] + i ], jack_port_name( handle->ports[1][i] ) );
+      if ( result ) {
+        free( ports );
+        errorText_ = "RtApiJack::startStream(): error connecting input ports!";
         goto unlock;
       }
-
-      // Now make the port connections.  See note above.
-      for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
-        result = 1;
-        if ( ports[ stream_.channelOffset[1] + i ] )
-          result = jack_connect( handle->client, ports[ stream_.channelOffset[1] + i ], jack_port_name( handle->ports[1][i] ) );
-        if ( result ) {
-          free( ports );
-          errorText_ = "RtApiJack::startStream(): error connecting input ports!";
-          goto unlock;
-        }
-      }
-      free(ports);
     }
+    free(ports);
+  }
+
+  handle->drainCounter = 0;
+  handle->internalDrain = false;
+  stream_.state = STREAM_RUNNING;
 
-    handle->drainCounter = 0;
-    handle->internalDrain = false;
-    stream_.state = STREAM_RUNNING;
+ unlock:
+  MUTEX_UNLOCK(&stream_.mutex);
 
-  unlock:
-    MUTEX_UNLOCK(&stream_.mutex);
+  if ( result == 0 ) return;
+  error( RtError::SYSTEM_ERROR );
+}
 
-    if ( result == 0 ) return;
-    error( RtError::SYSTEM_ERROR );
+void RtApiJack :: stopStream( void )
+{
+  verifyStream();
+  if ( stream_.state == STREAM_STOPPED ) {
+    errorText_ = "RtApiJack::stopStream(): the stream is already stopped!";
+    error( RtError::WARNING );
+    return;
   }
 
-  void RtApiJack :: stopStream( void )
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_STOPPED ) {
-      errorText_ = "RtApiJack::stopStream(): the stream is already stopped!";
-      error( RtError::WARNING );
-      return;
-    }
+  MUTEX_LOCK( &stream_.mutex );
 
-    MUTEX_LOCK( &stream_.mutex );
+  if ( stream_.state == STREAM_STOPPED ) {
+    MUTEX_UNLOCK( &stream_.mutex );
+    return;
+  }
 
-    JackHandle *handle = (JackHandle *) stream_.apiHandle;
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+  JackHandle *handle = (JackHandle *) stream_.apiHandle;
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
 
-      if ( handle->drainCounter == 0 ) {
-        handle->drainCounter = 1;
-        pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
-      }
+    if ( handle->drainCounter == 0 ) {
+      handle->drainCounter = 1;
+      pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled
     }
+  }
 
-    jack_deactivate( handle->client );
-    stream_.state = STREAM_STOPPED;
+  jack_deactivate( handle->client );
+  stream_.state = STREAM_STOPPED;
 
-    MUTEX_UNLOCK( &stream_.mutex );
+  MUTEX_UNLOCK( &stream_.mutex );
+}
+
+void RtApiJack :: abortStream( void )
+{
+  verifyStream();
+  if ( stream_.state == STREAM_STOPPED ) {
+    errorText_ = "RtApiJack::abortStream(): the stream is already stopped!";
+    error( RtError::WARNING );
+    return;
   }
 
-  void RtApiJack :: abortStream( void )
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_STOPPED ) {
-      errorText_ = "RtApiJack::abortStream(): the stream is already stopped!";
-      error( RtError::WARNING );
-      return;
-    }
+  JackHandle *handle = (JackHandle *) stream_.apiHandle;
+  handle->drainCounter = 1;
 
-    JackHandle *handle = (JackHandle *) stream_.apiHandle;
-    handle->drainCounter = 1;
+  stopStream();
+}
 
-    stopStream();
+bool RtApiJack :: callbackEvent( unsigned long nframes )
+{
+  if ( stream_.state == STREAM_STOPPED ) return SUCCESS;
+  if ( stream_.state == STREAM_CLOSED ) {
+    errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
+    error( RtError::WARNING );
+    return FAILURE;
+  }
+  if ( stream_.bufferSize != nframes ) {
+    errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size has changed ... cannot process!";
+    error( RtError::WARNING );
+    return FAILURE;
   }
 
-  bool RtApiJack :: callbackEvent( unsigned long nframes )
-  {
-    if ( stream_.state == STREAM_STOPPED ) return SUCCESS;
-    if ( stream_.state == STREAM_CLOSED ) {
-      errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";
-      error( RtError::WARNING );
-      return FAILURE;
-    }
-    if ( stream_.bufferSize != nframes ) {
-      errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size has changed ... cannot process!";
-      error( RtError::WARNING );
-      return FAILURE;
-    }
+  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
+  JackHandle *handle = (JackHandle *) stream_.apiHandle;
 
-    CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
-    JackHandle *handle = (JackHandle *) stream_.apiHandle;
+  // Check if we were draining the stream and signal is finished.
+  if ( handle->drainCounter > 3 ) {
+    if ( handle->internalDrain == false )
+      pthread_cond_signal( &handle->condition );
+    else
+      stopStream();
+    return SUCCESS;
+  }
 
-    // Check if we were draining the stream and signal is finished.
-    if ( handle->drainCounter > 3 ) {
-      if ( handle->internalDrain == false )
-        pthread_cond_signal( &handle->condition );
-      else
-        stopStream();
-      return SUCCESS;
-    }
+  MUTEX_LOCK( &stream_.mutex );
 
-    MUTEX_LOCK( &stream_.mutex );
+  // The state might change while waiting on a mutex.
+  if ( stream_.state == STREAM_STOPPED ) {
+    MUTEX_UNLOCK( &stream_.mutex );
+    return SUCCESS;
+  }
 
-    // Invoke user callback first, to get fresh output data.
-    if ( handle->drainCounter == 0 ) {
-      RtAudioCallback callback = (RtAudioCallback) info->callback;
-      double streamTime = getStreamTime();
-      RtAudioStreamStatus status = 0;
-      if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
-        status |= RTAUDIO_OUTPUT_UNDERFLOW;
-        handle->xrun[0] = false;
-      }
-      if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
-        status |= RTAUDIO_INPUT_OVERFLOW;
-        handle->xrun[1] = false;
-      }
-      handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],
-                                       stream_.bufferSize, streamTime, status, info->userData );
-      if ( handle->drainCounter == 2 ) {
-        MUTEX_UNLOCK( &stream_.mutex );
-        abortStream();
-        return SUCCESS;
-      }
-      else if ( handle->drainCounter == 1 )
-        handle->internalDrain = true;
+  // Invoke user callback first, to get fresh output data.
+  if ( handle->drainCounter == 0 ) {
+    RtAudioCallback callback = (RtAudioCallback) info->callback;
+    double streamTime = getStreamTime();
+    RtAudioStreamStatus status = 0;
+    if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
+      status |= RTAUDIO_OUTPUT_UNDERFLOW;
+      handle->xrun[0] = false;
     }
+    if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
+      status |= RTAUDIO_INPUT_OVERFLOW;
+      handle->xrun[1] = false;
+    }
+    handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],
+                                     stream_.bufferSize, streamTime, status, info->userData );
+    if ( handle->drainCounter == 2 ) {
+      MUTEX_UNLOCK( &stream_.mutex );
+      abortStream();
+      return SUCCESS;
+    }
+    else if ( handle->drainCounter == 1 )
+      handle->internalDrain = true;
+  }
 
-    jack_default_audio_sample_t *jackbuffer;
-    unsigned long bufferBytes = nframes * sizeof( jack_default_audio_sample_t );
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
-
-      if ( handle->drainCounter > 0 ) { // write zeros to the output stream
+  jack_default_audio_sample_t *jackbuffer;
+  unsigned long bufferBytes = nframes * sizeof( jack_default_audio_sample_t );
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
 
-        for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
-          jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
-          memset( jackbuffer, 0, bufferBytes );
-        }
+    if ( handle->drainCounter > 0 ) { // write zeros to the output stream
 
+      for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
+        jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
+        memset( jackbuffer, 0, bufferBytes );
       }
-      else if ( stream_.doConvertBuffer[0] ) {
 
-        convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
+    }
+    else if ( stream_.doConvertBuffer[0] ) {
 
-        for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
-          jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
-          memcpy( jackbuffer, &stream_.deviceBuffer[i*bufferBytes], bufferBytes );
-        }
+      convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
+
+      for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
+        jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
+        memcpy( jackbuffer, &stream_.deviceBuffer[i*bufferBytes], bufferBytes );
       }
-      else { // no buffer conversion
-        for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
-          jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
-          memcpy( jackbuffer, &stream_.userBuffer[0][i*bufferBytes], bufferBytes );
-        }
+    }
+    else { // no buffer conversion
+      for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {
+        jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );
+        memcpy( jackbuffer, &stream_.userBuffer[0][i*bufferBytes], bufferBytes );
       }
+    }
 
-      if ( handle->drainCounter ) {
-        handle->drainCounter++;
-        goto unlock;
-      }
+    if ( handle->drainCounter ) {
+      handle->drainCounter++;
+      goto unlock;
     }
+  }
 
-    if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
 
-      if ( stream_.doConvertBuffer[1] ) {
-        for ( unsigned int i=0; i<stream_.nDeviceChannels[1]; i++ ) {
-          jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
-          memcpy( &stream_.deviceBuffer[i*bufferBytes], jackbuffer, bufferBytes );
-        }
-        convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
+    if ( stream_.doConvertBuffer[1] ) {
+      for ( unsigned int i=0; i<stream_.nDeviceChannels[1]; i++ ) {
+        jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
+        memcpy( &stream_.deviceBuffer[i*bufferBytes], jackbuffer, bufferBytes );
       }
-      else { // no buffer conversion
-        for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
-          jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
-          memcpy( &stream_.userBuffer[1][i*bufferBytes], jackbuffer, bufferBytes );
-        }
+      convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
+    }
+    else { // no buffer conversion
+      for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {
+        jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );
+        memcpy( &stream_.userBuffer[1][i*bufferBytes], jackbuffer, bufferBytes );
       }
     }
+  }
 
 unlock:
-    MUTEX_UNLOCK(&stream_.mutex);
+ unlock:
+  MUTEX_UNLOCK(&stream_.mutex);
 
-    RtApi::tickStreamTime();
-    return SUCCESS;
-  }
+  RtApi::tickStreamTime();
+  return SUCCESS;
+}
   //******************** End of __UNIX_JACK__ *********************//
 #endif
 
 #if defined(__WINDOWS_ASIO__) // ASIO API on Windows
 
-  // The ASIO API is designed around a callback scheme, so this
-  // implementation is similar to that used for OS-X CoreAudio and Linux
-  // Jack.  The primary constraint with ASIO is that it only allows
-  // access to a single driver at a time.  Thus, it is not possible to
-  // have more than one simultaneous RtAudio stream.
-  //
-  // This implementation also requires a number of external ASIO files
-  // and a few global variables.  The ASIO callback scheme does not
-  // allow for the passing of user data, so we must create a global
-  // pointer to our callbackInfo structure.
-  //
-  // On unix systems, we make use of a pthread condition variable.
-  // Since there is no equivalent in Windows, I hacked something based
-  // on information found in
-  // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html.
+// The ASIO API is designed around a callback scheme, so this
+// implementation is similar to that used for OS-X CoreAudio and Linux
+// Jack.  The primary constraint with ASIO is that it only allows
+// access to a single driver at a time.  Thus, it is not possible to
+// have more than one simultaneous RtAudio stream.
+//
+// This implementation also requires a number of external ASIO files
+// and a few global variables.  The ASIO callback scheme does not
+// allow for the passing of user data, so we must create a global
+// pointer to our callbackInfo structure.
+//
+// On unix systems, we make use of a pthread condition variable.
+// Since there is no equivalent in Windows, I hacked something based
+// on information found in
+// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html.
 
 #include "asiosys.h"
 #include "asio.h"
@@ -2430,941 +2448,946 @@ bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
 #include "asiodrivers.h"
 #include <cmath>
 
-  AsioDrivers drivers;
-  ASIOCallbacks asioCallbacks;
-  ASIODriverInfo driverInfo;
-  CallbackInfo *asioCallbackInfo;
-  bool asioXRun;
-
-  struct AsioHandle {
-    int drainCounter;       // Tracks callback counts when draining
-    bool internalDrain;     // Indicates if stop is initiated from callback or not.
-    ASIOBufferInfo *bufferInfos;
-    HANDLE condition;
-
-    AsioHandle()
-      :drainCounter(0), internalDrain(false), bufferInfos(0) {}
-  };
+AsioDrivers drivers;
+ASIOCallbacks asioCallbacks;
+ASIODriverInfo driverInfo;
+CallbackInfo *asioCallbackInfo;
+bool asioXRun;
 
-  // Function declarations (definitions at end of section)
-  static const char* getAsioErrorString( ASIOError result );
-  void sampleRateChanged( ASIOSampleRate sRate );
-  long asioMessages( long selector, long value, void* message, double* opt );
+struct AsioHandle {
+  int drainCounter;       // Tracks callback counts when draining
+  bool internalDrain;     // Indicates if stop is initiated from callback or not.
+  ASIOBufferInfo *bufferInfos;
+  HANDLE condition;
 
-  RtApiAsio :: RtApiAsio()
-  {
-    // ASIO cannot run on a multi-threaded appartment. You can call
-    // CoInitialize beforehand, but it must be for appartment threading
-    // (in which case, CoInitilialize will return S_FALSE here).
-    coInitialized_ = false;
-    HRESULT hr = CoInitialize( NULL ); 
-    if ( FAILED(hr) ) {
-      errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";
-      error( RtError::WARNING );
-    }
-    coInitialized_ = true;
+  AsioHandle()
+    :drainCounter(0), internalDrain(false), bufferInfos(0) {}
+};
 
-    drivers.removeCurrentDriver();
-    driverInfo.asioVersion = 2;
+// Function declarations (definitions at end of section)
+static const char* getAsioErrorString( ASIOError result );
+void sampleRateChanged( ASIOSampleRate sRate );
+long asioMessages( long selector, long value, void* message, double* opt );
 
-    // See note in DirectSound implementation about GetDesktopWindow().
-    driverInfo.sysRef = GetForegroundWindow();
+RtApiAsio :: RtApiAsio()
+{
+  // ASIO cannot run on a multi-threaded appartment. You can call
+  // CoInitialize beforehand, but it must be for appartment threading
+  // (in which case, CoInitilialize will return S_FALSE here).
+  coInitialized_ = false;
+  HRESULT hr = CoInitialize( NULL ); 
+  if ( FAILED(hr) ) {
+    errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";
+    error( RtError::WARNING );
   }
+  coInitialized_ = true;
 
-  RtApiAsio :: ~RtApiAsio()
-  {
-    if ( stream_.state != STREAM_CLOSED ) closeStream();
-    if ( coInitialized_ ) CoUninitialize();
-  }
+  drivers.removeCurrentDriver();
+  driverInfo.asioVersion = 2;
 
-  unsigned int RtApiAsio :: getDeviceCount( void )
-  {
-    return (unsigned int) drivers.asioGetNumDev();
-  }
+  // See note in DirectSound implementation about GetDesktopWindow().
+  driverInfo.sysRef = GetForegroundWindow();
+}
 
-  RtAudio::DeviceInfo RtApiAsio :: getDeviceInfo( unsigned int device )
-  {
-    RtAudio::DeviceInfo info;
-    info.probed = false;
+RtApiAsio :: ~RtApiAsio()
+{
+  if ( stream_.state != STREAM_CLOSED ) closeStream();
+  if ( coInitialized_ ) CoUninitialize();
+}
 
-    // Get device ID
-    unsigned int nDevices = getDeviceCount();
-    if ( nDevices == 0 ) {
-      errorText_ = "RtApiAsio::getDeviceInfo: no devices found!";
-      error( RtError::INVALID_USE );
-    }
+unsigned int RtApiAsio :: getDeviceCount( void )
+{
+  return (unsigned int) drivers.asioGetNumDev();
+}
 
-    if ( device >= nDevices ) {
-      errorText_ = "RtApiAsio::getDeviceInfo: device ID is invalid!";
-      error( RtError::INVALID_USE );
-    }
+RtAudio::DeviceInfo RtApiAsio :: getDeviceInfo( unsigned int device )
+{
+  RtAudio::DeviceInfo info;
+  info.probed = false;
 
-    // If a stream is already open, we cannot probe other devices.  Thus, use the saved results.
-    if ( stream_.state != STREAM_CLOSED ) {
-      if ( device >= devices_.size() ) {
-        errorText_ = "RtApiAsio::getDeviceInfo: device ID was not present before stream was opened.";
-        error( RtError::WARNING );
-        return info;
-      }
-      return devices_[ device ];
-    }
+  // Get device ID
+  unsigned int nDevices = getDeviceCount();
+  if ( nDevices == 0 ) {
+    errorText_ = "RtApiAsio::getDeviceInfo: no devices found!";
+    error( RtError::INVALID_USE );
+  }
 
-    char driverName[32];
-    ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
-    if ( result != ASE_OK ) {
-      errorStream_ << "RtApiAsio::getDeviceInfo: unable to get driver name (" << getAsioErrorString( result ) << ").";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
-    }
-
-    info.name = driverName;
-
-    if ( !drivers.loadDriver( driverName ) ) {
-      errorStream_ << "RtApiAsio::getDeviceInfo: unable to load driver (" << driverName << ").";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
-    }
+  if ( device >= nDevices ) {
+    errorText_ = "RtApiAsio::getDeviceInfo: device ID is invalid!";
+    error( RtError::INVALID_USE );
+  }
 
-    result = ASIOInit( &driverInfo );
-    if ( result != ASE_OK ) {
-      errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
-      errorText_ = errorStream_.str();
+  // If a stream is already open, we cannot probe other devices.  Thus, use the saved results.
+  if ( stream_.state != STREAM_CLOSED ) {
+    if ( device >= devices_.size() ) {
+      errorText_ = "RtApiAsio::getDeviceInfo: device ID was not present before stream was opened.";
       error( RtError::WARNING );
       return info;
     }
+    return devices_[ device ];
+  }
 
-    // Determine the device channel information.
-    long inputChannels, outputChannels;
-    result = ASIOGetChannels( &inputChannels, &outputChannels );
-    if ( result != ASE_OK ) {
-      drivers.removeCurrentDriver();
-      errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
-    }
+  char driverName[32];
+  ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
+  if ( result != ASE_OK ) {
+    errorStream_ << "RtApiAsio::getDeviceInfo: unable to get driver name (" << getAsioErrorString( result ) << ").";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return info;
+  }
 
-    info.outputChannels = outputChannels;
-    info.inputChannels = inputChannels;
-    if ( info.outputChannels > 0 && info.inputChannels > 0 )
-      info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
+  info.name = driverName;
 
-    // Determine the supported sample rates.
-    info.sampleRates.clear();
-    for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
-      result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );
-      if ( result == ASE_OK )
-        info.sampleRates.push_back( SAMPLE_RATES[i] );
-    }
+  if ( !drivers.loadDriver( driverName ) ) {
+    errorStream_ << "RtApiAsio::getDeviceInfo: unable to load driver (" << driverName << ").";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return info;
+  }
 
-    // Determine supported data types ... just check first channel and assume rest are the same.
-    ASIOChannelInfo channelInfo;
-    channelInfo.channel = 0;
-    channelInfo.isInput = true;
-    if ( info.inputChannels <= 0 ) channelInfo.isInput = false;
-    result = ASIOGetChannelInfo( &channelInfo );
-    if ( result != ASE_OK ) {
-      drivers.removeCurrentDriver();
-      errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting driver channel info (" << driverName << ").";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
-    }
+  result = ASIOInit( &driverInfo );
+  if ( result != ASE_OK ) {
+    errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return info;
+  }
 
-    info.nativeFormats = 0;
-    if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB )
-      info.nativeFormats |= RTAUDIO_SINT16;
-    else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB )
-      info.nativeFormats |= RTAUDIO_SINT32;
-    else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB )
-      info.nativeFormats |= RTAUDIO_FLOAT32;
-    else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )
-      info.nativeFormats |= RTAUDIO_FLOAT64;
+  // Determine the device channel information.
+  long inputChannels, outputChannels;
+  result = ASIOGetChannels( &inputChannels, &outputChannels );
+  if ( result != ASE_OK ) {
+    drivers.removeCurrentDriver();
+    errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return info;
+  }
 
-    if ( getDefaultOutputDevice() == device )
-      info.isDefaultOutput = true;
-    if ( getDefaultInputDevice() == device )
-      info.isDefaultInput = true;
+  info.outputChannels = outputChannels;
+  info.inputChannels = inputChannels;
+  if ( info.outputChannels > 0 && info.inputChannels > 0 )
+    info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
 
-    info.probed = true;
+  // Determine the supported sample rates.
+  info.sampleRates.clear();
+  for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
+    result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );
+    if ( result == ASE_OK )
+      info.sampleRates.push_back( SAMPLE_RATES[i] );
+  }
+
+  // Determine supported data types ... just check first channel and assume rest are the same.
+  ASIOChannelInfo channelInfo;
+  channelInfo.channel = 0;
+  channelInfo.isInput = true;
+  if ( info.inputChannels <= 0 ) channelInfo.isInput = false;
+  result = ASIOGetChannelInfo( &channelInfo );
+  if ( result != ASE_OK ) {
     drivers.removeCurrentDriver();
+    errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting driver channel info (" << driverName << ").";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
     return info;
   }
 
-  void bufferSwitch( long index, ASIOBool processNow )
-  {
-    RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object;
-    object->callbackEvent( index );
-  }
+  info.nativeFormats = 0;
+  if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB )
+    info.nativeFormats |= RTAUDIO_SINT16;
+  else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB )
+    info.nativeFormats |= RTAUDIO_SINT32;
+  else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB )
+    info.nativeFormats |= RTAUDIO_FLOAT32;
+  else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )
+    info.nativeFormats |= RTAUDIO_FLOAT64;
 
-  void RtApiAsio :: saveDeviceInfo( void )
-  {
-    devices_.clear();
+  if ( getDefaultOutputDevice() == device )
+    info.isDefaultOutput = true;
+  if ( getDefaultInputDevice() == device )
+    info.isDefaultInput = true;
 
-    unsigned int nDevices = getDeviceCount();
-    devices_.resize( nDevices );
-    for ( unsigned int i=0; i<nDevices; i++ )
-      devices_[i] = getDeviceInfo( i );
-  }
+  info.probed = true;
+  drivers.removeCurrentDriver();
+  return info;
+}
 
-  bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
-                                     unsigned int firstChannel, unsigned int sampleRate,
-                                     RtAudioFormat format, unsigned int *bufferSize,
-                                     RtAudio::StreamOptions *options )
-  {
-    // For ASIO, a duplex stream MUST use the same driver.
-    if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] != device ) {
-      errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";
-      return FAILURE;
-    }
+void bufferSwitch( long index, ASIOBool processNow )
+{
+  RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object;
+  object->callbackEvent( index );
+}
 
-    char driverName[32];
-    ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
-    if ( result != ASE_OK ) {
-      errorStream_ << "RtApiAsio::probeDeviceOpen: unable to get driver name (" << getAsioErrorString( result ) << ").";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+void RtApiAsio :: saveDeviceInfo( void )
+{
+  devices_.clear();
 
-    // The getDeviceInfo() function will not work when a stream is open
-    // because ASIO does not allow multiple devices to run at the same
-    // time.  Thus, we'll probe the system before opening a stream and
-    // save the results for use by getDeviceInfo().
-    this->saveDeviceInfo();
+  unsigned int nDevices = getDeviceCount();
+  devices_.resize( nDevices );
+  for ( unsigned int i=0; i<nDevices; i++ )
+    devices_[i] = getDeviceInfo( i );
+}
 
-    // Only load the driver once for duplex stream.
-    if ( mode != INPUT || stream_.mode != OUTPUT ) {
-      if ( !drivers.loadDriver( driverName ) ) {
-        errorStream_ << "RtApiAsio::probeDeviceOpen: unable to load driver (" << driverName << ").";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
+bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
+                                   unsigned int firstChannel, unsigned int sampleRate,
+                                   RtAudioFormat format, unsigned int *bufferSize,
+                                   RtAudio::StreamOptions *options )
+{
+  // For ASIO, a duplex stream MUST use the same driver.
+  if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] != device ) {
+    errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";
+    return FAILURE;
+  }
 
-      result = ASIOInit( &driverInfo );
-      if ( result != ASE_OK ) {
-        errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
-    }
+  char driverName[32];
+  ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );
+  if ( result != ASE_OK ) {
+    errorStream_ << "RtApiAsio::probeDeviceOpen: unable to get driver name (" << getAsioErrorString( result ) << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    // Check the device channel count.
-    long inputChannels, outputChannels;
-    result = ASIOGetChannels( &inputChannels, &outputChannels );
-    if ( result != ASE_OK ) {
-      drivers.removeCurrentDriver();
-      errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  // The getDeviceInfo() function will not work when a stream is open
+  // because ASIO does not allow multiple devices to run at the same
+  // time.  Thus, we'll probe the system before opening a stream and
+  // save the results for use by getDeviceInfo().
+  this->saveDeviceInfo();
 
-    if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) ||
-         ( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) {
-      drivers.removeCurrentDriver();
-      errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";
+  // Only load the driver once for duplex stream.
+  if ( mode != INPUT || stream_.mode != OUTPUT ) {
+    if ( !drivers.loadDriver( driverName ) ) {
+      errorStream_ << "RtApiAsio::probeDeviceOpen: unable to load driver (" << driverName << ").";
       errorText_ = errorStream_.str();
       return FAILURE;
     }
-    stream_.nDeviceChannels[mode] = channels;
-    stream_.nUserChannels[mode] = channels;
-    stream_.channelOffset[mode] = firstChannel;
 
-    // Verify the sample rate is supported.
-    result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );
+    result = ASIOInit( &driverInfo );
     if ( result != ASE_OK ) {
-      drivers.removeCurrentDriver();
-      errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";
+      errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";
       errorText_ = errorStream_.str();
       return FAILURE;
     }
+  }
 
-    // Get the current sample rate
-    ASIOSampleRate currentRate;
-    result = ASIOGetSampleRate( &currentRate );
-    if ( result != ASE_OK ) {
-      drivers.removeCurrentDriver();
-      errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  // Check the device channel count.
+  long inputChannels, outputChannels;
+  result = ASIOGetChannels( &inputChannels, &outputChannels );
+  if ( result != ASE_OK ) {
+    drivers.removeCurrentDriver();
+    errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    // Set the sample rate only if necessary
-    if ( currentRate != sampleRate ) {
-      result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );
-      if ( result != ASE_OK ) {
-        drivers.removeCurrentDriver();
-        errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
-    }
+  if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) ||
+       ( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) {
+    drivers.removeCurrentDriver();
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
+  stream_.nDeviceChannels[mode] = channels;
+  stream_.nUserChannels[mode] = channels;
+  stream_.channelOffset[mode] = firstChannel;
 
-    // Determine the driver data type.
-    ASIOChannelInfo channelInfo;
-    channelInfo.channel = 0;
-    if ( mode == OUTPUT ) channelInfo.isInput = false;
-    else channelInfo.isInput = true;
-    result = ASIOGetChannelInfo( &channelInfo );
+  // Verify the sample rate is supported.
+  result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );
+  if ( result != ASE_OK ) {
+    drivers.removeCurrentDriver();
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
+
+  // Get the current sample rate
+  ASIOSampleRate currentRate;
+  result = ASIOGetSampleRate( &currentRate );
+  if ( result != ASE_OK ) {
+    drivers.removeCurrentDriver();
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
+
+  // Set the sample rate only if necessary
+  if ( currentRate != sampleRate ) {
+    result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );
     if ( result != ASE_OK ) {
       drivers.removeCurrentDriver();
-      errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format.";
+      errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";
       errorText_ = errorStream_.str();
       return FAILURE;
     }
+  }
 
-    // Assuming WINDOWS host is always little-endian.
-    stream_.doByteSwap[mode] = false;
-    stream_.userFormat = format;
-    stream_.deviceFormat[mode] = 0;
-    if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) {
-      stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-      if ( channelInfo.type == ASIOSTInt16MSB ) stream_.doByteSwap[mode] = true;
-    }
-    else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) {
-      stream_.deviceFormat[mode] = RTAUDIO_SINT32;
-      if ( channelInfo.type == ASIOSTInt32MSB ) stream_.doByteSwap[mode] = true;
-    }
-    else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) {
-      stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
-      if ( channelInfo.type == ASIOSTFloat32MSB ) stream_.doByteSwap[mode] = true;
-    }
-    else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) {
-      stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
-      if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true;
-    }
+  // Determine the driver data type.
+  ASIOChannelInfo channelInfo;
+  channelInfo.channel = 0;
+  if ( mode == OUTPUT ) channelInfo.isInput = false;
+  else channelInfo.isInput = true;
+  result = ASIOGetChannelInfo( &channelInfo );
+  if ( result != ASE_OK ) {
+    drivers.removeCurrentDriver();
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format.";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    if ( stream_.deviceFormat[mode] == 0 ) {
-      drivers.removeCurrentDriver();
-      errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";
-      errorText_ = errorStream_.str();
-      return FAILURE;
+  // Assuming WINDOWS host is always little-endian.
+  stream_.doByteSwap[mode] = false;
+  stream_.userFormat = format;
+  stream_.deviceFormat[mode] = 0;
+  if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) {
+    stream_.deviceFormat[mode] = RTAUDIO_SINT16;
+    if ( channelInfo.type == ASIOSTInt16MSB ) stream_.doByteSwap[mode] = true;
+  }
+  else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) {
+    stream_.deviceFormat[mode] = RTAUDIO_SINT32;
+    if ( channelInfo.type == ASIOSTInt32MSB ) stream_.doByteSwap[mode] = true;
+  }
+  else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) {
+    stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
+    if ( channelInfo.type == ASIOSTFloat32MSB ) stream_.doByteSwap[mode] = true;
+  }
+  else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) {
+    stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
+    if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true;
+  }
+
+  if ( stream_.deviceFormat[mode] == 0 ) {
+    drivers.removeCurrentDriver();
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
+
+  // Set the buffer size.  For a duplex stream, this will end up
+  // setting the buffer size based on the input constraints, which
+  // should be ok.
+  long minSize, maxSize, preferSize, granularity;
+  result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );
+  if ( result != ASE_OK ) {
+    drivers.removeCurrentDriver();
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size.";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
+
+  if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
+  else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
+  else if ( granularity == -1 ) {
+    // Make sure bufferSize is a power of two.
+    int log2_of_min_size = 0;
+    int log2_of_max_size = 0;
+
+    for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {
+      if ( minSize & ((long)1 << i) ) log2_of_min_size = i;
+      if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;
     }
 
-    // Set the buffer size.  For a duplex stream, this will end up
-    // setting the buffer size based on the input constraints, which
-    // should be ok.
-    long minSize, maxSize, preferSize, granularity;
-    result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );
-    if ( result != ASE_OK ) {
-      drivers.removeCurrentDriver();
-      errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size.";
-      errorText_ = errorStream_.str();
-      return FAILURE;
+    long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );
+    int min_delta_num = log2_of_min_size;
+
+    for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {
+      long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );
+      if (current_delta < min_delta) {
+        min_delta = current_delta;
+        min_delta_num = i;
+      }
     }
 
+    *bufferSize = ( (unsigned int)1 << min_delta_num );
     if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
     else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
-    else if ( granularity == -1 ) {
-      // Make sure bufferSize is a power of two.
-      int log2_of_min_size = 0;
-      int log2_of_max_size = 0;
-
-      for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {
-        if ( minSize & ((long)1 << i) ) log2_of_min_size = i;
-        if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;
-      }
+  }
+  else if ( granularity != 0 ) {
+    // Set to an even multiple of granularity, rounding up.
+    *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;
+  }
+
+  if ( mode == INPUT && stream_.mode == OUTPUT && stream_.bufferSize != *bufferSize ) {
+    drivers.removeCurrentDriver();
+    errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";
+    return FAILURE;
+  }
 
-      long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );
-      int min_delta_num = log2_of_min_size;
+  stream_.bufferSize = *bufferSize;
+  stream_.nBuffers = 2;
 
-      for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {
-        long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );
-        if (current_delta < min_delta) {
-          min_delta = current_delta;
-          min_delta_num = i;
-        }
-      }
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
+  else stream_.userInterleaved = true;
 
-      *bufferSize = ( (unsigned int)1 << min_delta_num );
-      if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;
-      else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;
-    }
-    else if ( granularity != 0 ) {
-      // Set to an even multiple of granularity, rounding up.
-      *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;
-    }
+  // ASIO always uses non-interleaved buffers.
+  stream_.deviceInterleaved[mode] = false;
 
-    if ( mode == INPUT && stream_.mode == OUTPUT && stream_.bufferSize != *bufferSize ) {
+  // Allocate, if necessary, our AsioHandle structure for the stream.
+  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
+  if ( handle == 0 ) {
+    try {
+      handle = new AsioHandle;
+    }
+    catch ( std::bad_alloc& ) {
+      //if ( handle == NULL ) {    
       drivers.removeCurrentDriver();
-      errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";
+      errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";
       return FAILURE;
     }
+    handle->bufferInfos = 0;
 
-    stream_.bufferSize = *bufferSize;
-    stream_.nBuffers = 2;
-
-    if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
-    else stream_.userInterleaved = true;
+    // Create a manual-reset event.
+    handle->condition = CreateEvent( NULL,   // no security
+                                     TRUE,   // manual-reset
+                                     FALSE,  // non-signaled initially
+                                     NULL ); // unnamed
+    stream_.apiHandle = (void *) handle;
+  }
 
-    // ASIO always uses non-interleaved buffers.
-    stream_.deviceInterleaved[mode] = false;
+  // Create the ASIO internal buffers.  Since RtAudio sets up input
+  // and output separately, we'll have to dispose of previously
+  // created output buffers for a duplex stream.
+  long inputLatency, outputLatency;
+  if ( mode == INPUT && stream_.mode == OUTPUT ) {
+    ASIODisposeBuffers();
+    if ( handle->bufferInfos ) free( handle->bufferInfos );
+  }
 
-    // Allocate, if necessary, our AsioHandle structure for the stream.
-    AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
-    if ( handle == 0 ) {
-      try {
-        handle = new AsioHandle;
-      }
-      catch ( std::bad_alloc& ) {
-        //if ( handle == NULL ) {    
-        drivers.removeCurrentDriver();
-        errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";
-        return FAILURE;
-      }
-      handle->bufferInfos = 0;
-
-      // Create a manual-reset event.
-      handle->condition = CreateEvent( NULL,   // no security
-                                       TRUE,   // manual-reset
-                                       FALSE,  // non-signaled initially
-                                       NULL ); // unnamed
-      stream_.apiHandle = (void *) handle;
-    }
-
-    // Create the ASIO internal buffers.  Since RtAudio sets up input
-    // and output separately, we'll have to dispose of previously
-    // created output buffers for a duplex stream.
-    long inputLatency, outputLatency;
-    if ( mode == INPUT && stream_.mode == OUTPUT ) {
-      ASIODisposeBuffers();
-      if ( handle->bufferInfos ) free( handle->bufferInfos );
-    }
-
-    // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.
-    bool buffersAllocated = false;
-    unsigned int i, nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
-    handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );
-    if ( handle->bufferInfos == NULL ) {
-      errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";
-      errorText_ = errorStream_.str();
-      goto error;
-    }
+  // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.
+  bool buffersAllocated = false;
+  unsigned int i, nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
+  handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );
+  if ( handle->bufferInfos == NULL ) {
+    errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";
+    errorText_ = errorStream_.str();
+    goto error;
+  }
 
-    ASIOBufferInfo *infos;
-    infos = handle->bufferInfos;
-    for ( i=0; i<stream_.nDeviceChannels[0]; i++, infos++ ) {
-      infos->isInput = ASIOFalse;
-      infos->channelNum = i + stream_.channelOffset[0];
-      infos->buffers[0] = infos->buffers[1] = 0;
-    }
-    for ( i=0; i<stream_.nDeviceChannels[1]; i++, infos++ ) {
-      infos->isInput = ASIOTrue;
-      infos->channelNum = i + stream_.channelOffset[1];
-      infos->buffers[0] = infos->buffers[1] = 0;
-    }
+  ASIOBufferInfo *infos;
+  infos = handle->bufferInfos;
+  for ( i=0; i<stream_.nDeviceChannels[0]; i++, infos++ ) {
+    infos->isInput = ASIOFalse;
+    infos->channelNum = i + stream_.channelOffset[0];
+    infos->buffers[0] = infos->buffers[1] = 0;
+  }
+  for ( i=0; i<stream_.nDeviceChannels[1]; i++, infos++ ) {
+    infos->isInput = ASIOTrue;
+    infos->channelNum = i + stream_.channelOffset[1];
+    infos->buffers[0] = infos->buffers[1] = 0;
+  }
 
-    // Set up the ASIO callback structure and create the ASIO data buffers.
-    asioCallbacks.bufferSwitch = &bufferSwitch;
-    asioCallbacks.sampleRateDidChange = &sampleRateChanged;
-    asioCallbacks.asioMessage = &asioMessages;
-    asioCallbacks.bufferSwitchTimeInfo = NULL;
-    result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
-    if ( result != ASE_OK ) {
-      errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers.";
-      errorText_ = errorStream_.str();
-      goto error;
-    }
-    buffersAllocated = true;
+  // Set up the ASIO callback structure and create the ASIO data buffers.
+  asioCallbacks.bufferSwitch = &bufferSwitch;
+  asioCallbacks.sampleRateDidChange = &sampleRateChanged;
+  asioCallbacks.asioMessage = &asioMessages;
+  asioCallbacks.bufferSwitchTimeInfo = NULL;
+  result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );
+  if ( result != ASE_OK ) {
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers.";
+    errorText_ = errorStream_.str();
+    goto error;
+  }
+  buffersAllocated = true;
 
-    // Set flags for buffer conversion.
-    stream_.doConvertBuffer[mode] = false;
-    if ( stream_.userFormat != stream_.deviceFormat[mode] )
-      stream_.doConvertBuffer[mode] = true;
-    if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
-         stream_.nUserChannels[mode] > 1 )
-      stream_.doConvertBuffer[mode] = true;
+  // Set flags for buffer conversion.
+  stream_.doConvertBuffer[mode] = false;
+  if ( stream_.userFormat != stream_.deviceFormat[mode] )
+    stream_.doConvertBuffer[mode] = true;
+  if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
+       stream_.nUserChannels[mode] > 1 )
+    stream_.doConvertBuffer[mode] = true;
 
-    // Allocate necessary internal buffers
-    unsigned long bufferBytes;
-    bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
-    stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
-    if ( stream_.userBuffer[mode] == NULL ) {
-      errorText_ = "RtApiAsio::probeDeviceOpen: error allocating user buffer memory.";
-      goto error;
-    }
+  // Allocate necessary internal buffers
+  unsigned long bufferBytes;
+  bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
+  stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
+  if ( stream_.userBuffer[mode] == NULL ) {
+    errorText_ = "RtApiAsio::probeDeviceOpen: error allocating user buffer memory.";
+    goto error;
+  }
 
-    if ( stream_.doConvertBuffer[mode] ) {
+  if ( stream_.doConvertBuffer[mode] ) {
 
-      bool makeBuffer = true;
-      bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
-      if ( mode == INPUT ) {
-        if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
-          unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
-          if ( bufferBytes <= bytesOut ) makeBuffer = false;
-        }
+    bool makeBuffer = true;
+    bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
+    if ( mode == INPUT ) {
+      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
+        unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
+        if ( bufferBytes <= bytesOut ) makeBuffer = false;
       }
+    }
 
-      if ( makeBuffer ) {
-        bufferBytes *= *bufferSize;
-        if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
-        stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
-        if ( stream_.deviceBuffer == NULL ) {
-          errorText_ = "RtApiAsio::probeDeviceOpen: error allocating device buffer memory.";
-          goto error;
-        }
+    if ( makeBuffer ) {
+      bufferBytes *= *bufferSize;
+      if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
+      stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
+      if ( stream_.deviceBuffer == NULL ) {
+        errorText_ = "RtApiAsio::probeDeviceOpen: error allocating device buffer memory.";
+        goto error;
       }
     }
+  }
 
-    stream_.sampleRate = sampleRate;
-    stream_.device[mode] = device;
-    stream_.state = STREAM_STOPPED;
-    asioCallbackInfo = &stream_.callbackInfo;
-    stream_.callbackInfo.object = (void *) this;
-    if ( stream_.mode == OUTPUT && mode == INPUT )
-      // We had already set up an output stream.
-      stream_.mode = DUPLEX;
-    else
-      stream_.mode = mode;
+  stream_.sampleRate = sampleRate;
+  stream_.device[mode] = device;
+  stream_.state = STREAM_STOPPED;
+  asioCallbackInfo = &stream_.callbackInfo;
+  stream_.callbackInfo.object = (void *) this;
+  if ( stream_.mode == OUTPUT && mode == INPUT )
+    // We had already set up an output stream.
+    stream_.mode = DUPLEX;
+  else
+    stream_.mode = mode;
 
-    // Determine device latencies
-    result = ASIOGetLatencies( &inputLatency, &outputLatency );
-    if ( result != ASE_OK ) {
-      errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency.";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING); // warn but don't fail
-    }
-    else {
-      stream_.latency[0] = outputLatency;
-      stream_.latency[1] = inputLatency;
-    }
+  // Determine device latencies
+  result = ASIOGetLatencies( &inputLatency, &outputLatency );
+  if ( result != ASE_OK ) {
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency.";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING); // warn but don't fail
+  }
+  else {
+    stream_.latency[0] = outputLatency;
+    stream_.latency[1] = inputLatency;
+  }
 
-    // Setup the buffer conversion information structure.  We don't use
-    // buffers to do channel offsets, so we override that parameter
-    // here.
-    if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
+  // Setup the buffer conversion information structure.  We don't use
+  // buffers to do channel offsets, so we override that parameter
+  // here.
+  if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );
 
-    return SUCCESS;
+  return SUCCESS;
 
 error:
-    if ( buffersAllocated )
-      ASIODisposeBuffers();
-    drivers.removeCurrentDriver();
+ error:
+  if ( buffersAllocated )
+    ASIODisposeBuffers();
+  drivers.removeCurrentDriver();
 
-    if ( handle ) {
-      CloseHandle( handle->condition );
-      if ( handle->bufferInfos )
-        free( handle->bufferInfos );
-      delete handle;
-      stream_.apiHandle = 0;
-    }
+  if ( handle ) {
+    CloseHandle( handle->condition );
+    if ( handle->bufferInfos )
+      free( handle->bufferInfos );
+    delete handle;
+    stream_.apiHandle = 0;
+  }
 
-    for ( int i=0; i<2; i++ ) {
-      if ( stream_.userBuffer[i] ) {
-        free( stream_.userBuffer[i] );
-        stream_.userBuffer[i] = 0;
-      }
+  for ( int i=0; i<2; i++ ) {
+    if ( stream_.userBuffer[i] ) {
+      free( stream_.userBuffer[i] );
+      stream_.userBuffer[i] = 0;
     }
+  }
 
-    if ( stream_.deviceBuffer ) {
-      free( stream_.deviceBuffer );
-      stream_.deviceBuffer = 0;
-    }
+  if ( stream_.deviceBuffer ) {
+    free( stream_.deviceBuffer );
+    stream_.deviceBuffer = 0;
+  }
 
-    return FAILURE;
+  return FAILURE;
+}
+
+void RtApiAsio :: closeStream()
+{
+  if ( stream_.state == STREAM_CLOSED ) {
+    errorText_ = "RtApiAsio::closeStream(): no open stream to close!";
+    error( RtError::WARNING );
+    return;
   }
 
-  void RtApiAsio :: closeStream()
-  {
-    if ( stream_.state == STREAM_CLOSED ) {
-      errorText_ = "RtApiAsio::closeStream(): no open stream to close!";
-      error( RtError::WARNING );
-      return;
-    }
+  if ( stream_.state == STREAM_RUNNING ) {
+    stream_.state = STREAM_STOPPED;
+    ASIOStop();
+  }
+  ASIODisposeBuffers();
+  drivers.removeCurrentDriver();
 
-    if ( stream_.state == STREAM_RUNNING ) {
-      stream_.state = STREAM_STOPPED;
-      ASIOStop();
-    }
-    ASIODisposeBuffers();
-    drivers.removeCurrentDriver();
+  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
+  if ( handle ) {
+    CloseHandle( handle->condition );
+    if ( handle->bufferInfos )
+      free( handle->bufferInfos );
+    delete handle;
+    stream_.apiHandle = 0;
+  }
 
-    AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
-    if ( handle ) {
-      CloseHandle( handle->condition );
-      if ( handle->bufferInfos )
-        free( handle->bufferInfos );
-      delete handle;
-      stream_.apiHandle = 0;
+  for ( int i=0; i<2; i++ ) {
+    if ( stream_.userBuffer[i] ) {
+      free( stream_.userBuffer[i] );
+      stream_.userBuffer[i] = 0;
     }
+  }
 
-    for ( int i=0; i<2; i++ ) {
-      if ( stream_.userBuffer[i] ) {
-        free( stream_.userBuffer[i] );
-        stream_.userBuffer[i] = 0;
-      }
-    }
+  if ( stream_.deviceBuffer ) {
+    free( stream_.deviceBuffer );
+    stream_.deviceBuffer = 0;
+  }
 
-    if ( stream_.deviceBuffer ) {
-      free( stream_.deviceBuffer );
-      stream_.deviceBuffer = 0;
-    }
+  stream_.mode = UNINITIALIZED;
+  stream_.state = STREAM_CLOSED;
+}
 
-    stream_.mode = UNINITIALIZED;
-    stream_.state = STREAM_CLOSED;
+void RtApiAsio :: startStream()
+{
+  verifyStream();
+  if ( stream_.state == STREAM_RUNNING ) {
+    errorText_ = "RtApiAsio::startStream(): the stream is already running!";
+    error( RtError::WARNING );
+    return;
   }
 
-  void RtApiAsio :: startStream()
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_RUNNING ) {
-      errorText_ = "RtApiAsio::startStream(): the stream is already running!";
-      error( RtError::WARNING );
-      return;
-    }
+  MUTEX_LOCK( &stream_.mutex );
 
-    MUTEX_LOCK( &stream_.mutex );
+  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
+  ASIOError result = ASIOStart();
+  if ( result != ASE_OK ) {
+    errorStream_ << "RtApiAsio::startStream: error (" << getAsioErrorString( result ) << ") starting device.";
+    errorText_ = errorStream_.str();
+    goto unlock;
+  }
 
-    AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
-    ASIOError result = ASIOStart();
-    if ( result != ASE_OK ) {
-      errorStream_ << "RtApiAsio::startStream: error (" << getAsioErrorString( result ) << ") starting device.";
-      errorText_ = errorStream_.str();
-      goto unlock;
-    }
+  handle->drainCounter = 0;
+  handle->internalDrain = false;
+  stream_.state = STREAM_RUNNING;
+  asioXRun = false;
 
-    handle->drainCounter = 0;
-    handle->internalDrain = false;
-    stream_.state = STREAM_RUNNING;
-    asioXRun = false;
+ unlock:
+  MUTEX_UNLOCK( &stream_.mutex );
 
-  unlock:
-    MUTEX_UNLOCK( &stream_.mutex );
+  if ( result == ASE_OK ) return;
+  error( RtError::SYSTEM_ERROR );
+}
 
-    if ( result == ASE_OK ) return;
-    error( RtError::SYSTEM_ERROR );
+void RtApiAsio :: stopStream()
+{
+  verifyStream();
+  if ( stream_.state == STREAM_STOPPED ) {
+    errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!";
+    error( RtError::WARNING );
+    return;
   }
 
-  void RtApiAsio :: stopStream()
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_STOPPED ) {
-      errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!";
-      error( RtError::WARNING );
-      return;
-    }
+  MUTEX_LOCK( &stream_.mutex );
 
-    MUTEX_LOCK( &stream_.mutex );
+  if ( stream_.state == STREAM_STOPPED ) {
+    MUTEX_UNLOCK( &stream_.mutex );
+    return;
+  }
 
-    AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
-      if ( handle->drainCounter == 0 ) {
-        handle->drainCounter = 1;
-        MUTEX_UNLOCK( &stream_.mutex );
-        WaitForMultipleObjects( 1, &handle->condition, FALSE, INFINITE );  // block until signaled
-        ResetEvent( handle->condition );
-        MUTEX_LOCK( &stream_.mutex );
-      }
+  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+    if ( handle->drainCounter == 0 ) {
+      handle->drainCounter = 1;
+      MUTEX_UNLOCK( &stream_.mutex );
+      WaitForMultipleObjects( 1, &handle->condition, FALSE, INFINITE );  // block until signaled
+      ResetEvent( handle->condition );
+      MUTEX_LOCK( &stream_.mutex );
     }
+  }
 
-    ASIOError result = ASIOStop();
-    if ( result != ASE_OK ) {
-      errorStream_ << "RtApiAsio::stopStream: error (" << getAsioErrorString( result ) << ") stopping device.";
-      errorText_ = errorStream_.str();
-    }
+  ASIOError result = ASIOStop();
+  if ( result != ASE_OK ) {
+    errorStream_ << "RtApiAsio::stopStream: error (" << getAsioErrorString( result ) << ") stopping device.";
+    errorText_ = errorStream_.str();
+  }
 
-    stream_.state = STREAM_STOPPED;
-    MUTEX_UNLOCK( &stream_.mutex );
+  stream_.state = STREAM_STOPPED;
+  MUTEX_UNLOCK( &stream_.mutex );
+
+  if ( result == ASE_OK ) return;
+  error( RtError::SYSTEM_ERROR );
+}
 
-    if ( result == ASE_OK ) return;
-    error( RtError::SYSTEM_ERROR );
+void RtApiAsio :: abortStream()
+{
+  verifyStream();
+  if ( stream_.state == STREAM_STOPPED ) {
+    errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!";
+    error( RtError::WARNING );
+    return;
   }
 
-  void RtApiAsio :: abortStream()
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_STOPPED ) {
-      errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!";
-      error( RtError::WARNING );
-      return;
-    }
+  // The following lines were commented-out because some behavior was
+  // noted where the device buffers need to be zeroed to avoid
+  // continuing sound, even when the device buffers are completely
+  // disposed.  So now, calling abort is the same as calling stop.
+  // AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
+  // handle->drainCounter = 1;
+  stopStream();
+}
 
-    // The following lines were commented-out because some behavior was
-    // noted where the device buffers need to be zeroed to avoid
-    // continuing sound, even when the device buffers are completed
-    // disposed.  So now, calling abort is the same as calling stop.
-    //AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
-    //handle->drainCounter = 1;
-    stopStream();
+bool RtApiAsio :: callbackEvent( long bufferIndex )
+{
+  if ( stream_.state == STREAM_STOPPED ) return SUCCESS;
+  if ( stream_.state == STREAM_CLOSED ) {
+    errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";
+    error( RtError::WARNING );
+    return FAILURE;
   }
 
-  bool RtApiAsio :: callbackEvent( long bufferIndex )
-  {
-    if ( stream_.state == STREAM_STOPPED ) return SUCCESS;
-    if ( stream_.state == STREAM_CLOSED ) {
-      errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";
-      error( RtError::WARNING );
-      return FAILURE;
-    }
+  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
+  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
+
+  // Check if we were draining the stream and signal is finished.
+  if ( handle->drainCounter > 3 ) {
+    if ( handle->internalDrain == false )
+      SetEvent( handle->condition );
+    else
+      stopStream();
+    return SUCCESS;
+  }
+
+  MUTEX_LOCK( &stream_.mutex );
 
-    CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
-    AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
+  // The state might change while waiting on a mutex.
+  if ( stream_.state == STREAM_STOPPED ) goto unlock;
 
-    // Check if we were draining the stream and signal is finished.
-    if ( handle->drainCounter > 3 ) {
-      if ( handle->internalDrain == false )
-        SetEvent( handle->condition );
-      else
-        stopStream();
+  // Invoke user callback to get fresh output data UNLESS we are
+  // draining stream.
+  if ( handle->drainCounter == 0 ) {
+    RtAudioCallback callback = (RtAudioCallback) info->callback;
+    double streamTime = getStreamTime();
+    RtAudioStreamStatus status = 0;
+    if ( stream_.mode != INPUT && asioXRun == true ) {
+      status |= RTAUDIO_OUTPUT_UNDERFLOW;
+      asioXRun = false;
+    }
+    if ( stream_.mode != OUTPUT && asioXRun == true ) {
+      status |= RTAUDIO_INPUT_OVERFLOW;
+      asioXRun = false;
+    }
+    handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],
+                                     stream_.bufferSize, streamTime, status, info->userData );
+    if ( handle->drainCounter == 2 ) {
+      MUTEX_UNLOCK( &stream_.mutex );
+      abortStream();
       return SUCCESS;
     }
+    else if ( handle->drainCounter == 1 )
+      handle->internalDrain = true;
+  }
 
-    MUTEX_LOCK( &stream_.mutex );
+  unsigned int nChannels, bufferBytes, i, j;
+  nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
 
-    // The state might change while waiting on a mutex.
-    if ( stream_.state == STREAM_STOPPED ) goto unlock;
+    bufferBytes = stream_.bufferSize * formatBytes( stream_.deviceFormat[0] );
 
-    // Invoke user callback to get fresh output data UNLESS we are
-    // draining stream.
-    if ( handle->drainCounter == 0 ) {
-      RtAudioCallback callback = (RtAudioCallback) info->callback;
-      double streamTime = getStreamTime();
-      RtAudioStreamStatus status = 0;
-      if ( stream_.mode != INPUT && asioXRun == true ) {
-        status |= RTAUDIO_OUTPUT_UNDERFLOW;
-        asioXRun = false;
-      }
-      if ( stream_.mode != OUTPUT && asioXRun == true ) {
-        status |= RTAUDIO_INPUT_OVERFLOW;
-        asioXRun = false;
-      }
-      handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],
-                                       stream_.bufferSize, streamTime, status, info->userData );
-      if ( handle->drainCounter == 2 ) {
-        MUTEX_UNLOCK( &stream_.mutex );
-        abortStream();
-        return SUCCESS;
+    if ( handle->drainCounter > 1 ) { // write zeros to the output stream
+
+      for ( i=0, j=0; i<nChannels; i++ ) {
+        if ( handle->bufferInfos[i].isInput != ASIOTrue )
+          memset( handle->bufferInfos[i].buffers[bufferIndex], 0, bufferBytes );
       }
-      else if ( handle->drainCounter == 1 )
-        handle->internalDrain = true;
+
     }
+    else if ( stream_.doConvertBuffer[0] ) {
 
-    unsigned int nChannels, bufferBytes, i, j;
-    nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+      convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
+      if ( stream_.doByteSwap[0] )
+        byteSwapBuffer( stream_.deviceBuffer,
+                        stream_.bufferSize * stream_.nDeviceChannels[0],
+                        stream_.deviceFormat[0] );
 
-      bufferBytes = stream_.bufferSize * formatBytes( stream_.deviceFormat[0] );
+      for ( i=0, j=0; i<nChannels; i++ ) {
+        if ( handle->bufferInfos[i].isInput != ASIOTrue )
+          memcpy( handle->bufferInfos[i].buffers[bufferIndex],
+                  &stream_.deviceBuffer[j++*bufferBytes], bufferBytes );
+      }
 
-      if ( handle->drainCounter > 1 ) { // write zeros to the output stream
+    }
+    else {
 
-        for ( i=0, j=0; i<nChannels; i++ ) {
-          if ( handle->bufferInfos[i].isInput != ASIOTrue )
-            memset( handle->bufferInfos[i].buffers[bufferIndex], 0, bufferBytes );
-        }
+      if ( stream_.doByteSwap[0] )
+        byteSwapBuffer( stream_.userBuffer[0],
+                        stream_.bufferSize * stream_.nUserChannels[0],
+                        stream_.userFormat );
 
+      for ( i=0, j=0; i<nChannels; i++ ) {
+        if ( handle->bufferInfos[i].isInput != ASIOTrue )
+          memcpy( handle->bufferInfos[i].buffers[bufferIndex],
+                  &stream_.userBuffer[0][bufferBytes*j++], bufferBytes );
       }
-      else if ( stream_.doConvertBuffer[0] ) {
 
-        convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );
-        if ( stream_.doByteSwap[0] )
-          byteSwapBuffer( stream_.deviceBuffer,
-                          stream_.bufferSize * stream_.nDeviceChannels[0],
-                          stream_.deviceFormat[0] );
-
-        for ( i=0, j=0; i<nChannels; i++ ) {
-          if ( handle->bufferInfos[i].isInput != ASIOTrue )
-            memcpy( handle->bufferInfos[i].buffers[bufferIndex],
-                    &stream_.deviceBuffer[j++*bufferBytes], bufferBytes );
-        }
+    }
 
-      }
-      else {
+    if ( handle->drainCounter ) {
+      handle->drainCounter++;
+      goto unlock;
+    }
+  }
 
-        if ( stream_.doByteSwap[0] )
-          byteSwapBuffer( stream_.userBuffer[0],
-                          stream_.bufferSize * stream_.nUserChannels[0],
-                          stream_.userFormat );
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
 
-        for ( i=0, j=0; i<nChannels; i++ ) {
-          if ( handle->bufferInfos[i].isInput != ASIOTrue )
-            memcpy( handle->bufferInfos[i].buffers[bufferIndex],
-                    &stream_.userBuffer[0][bufferBytes*j++], bufferBytes );
-        }
+    bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]);
 
+    if (stream_.doConvertBuffer[1]) {
+
+      // Always interleave ASIO input data.
+      for ( i=0, j=0; i<nChannels; i++ ) {
+        if ( handle->bufferInfos[i].isInput == ASIOTrue )
+          memcpy( &stream_.deviceBuffer[j++*bufferBytes],
+                  handle->bufferInfos[i].buffers[bufferIndex],
+                  bufferBytes );
       }
 
-      if ( handle->drainCounter ) {
-        handle->drainCounter++;
-        goto unlock;
+      if ( stream_.doByteSwap[1] )
+        byteSwapBuffer( stream_.deviceBuffer,
+                        stream_.bufferSize * stream_.nDeviceChannels[1],
+                        stream_.deviceFormat[1] );
+      convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
+
+    }
+    else {
+      for ( i=0, j=0; i<nChannels; i++ ) {
+        if ( handle->bufferInfos[i].isInput == ASIOTrue ) {
+          memcpy( &stream_.userBuffer[1][bufferBytes*j++],
+                  handle->bufferInfos[i].buffers[bufferIndex],
+                  bufferBytes );
+        }
       }
+
+      if ( stream_.doByteSwap[1] )
+        byteSwapBuffer( stream_.userBuffer[1],
+                        stream_.bufferSize * stream_.nUserChannels[1],
+                        stream_.userFormat );
     }
+  }
 
-    if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
+ unlock:
+  // The following call was suggested by Malte Clasen.  While the API
+  // documentation indicates it should not be required, some device
+  // drivers apparently do not function correctly without it.
+  ASIOOutputReady();
 
-      bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]);
+  MUTEX_UNLOCK( &stream_.mutex );
 
-      if (stream_.doConvertBuffer[1]) {
+  RtApi::tickStreamTime();
+  return SUCCESS;
+}
 
-        // Always interleave ASIO input data.
-        for ( i=0, j=0; i<nChannels; i++ ) {
-          if ( handle->bufferInfos[i].isInput == ASIOTrue )
-            memcpy( &stream_.deviceBuffer[j++*bufferBytes],
-                    handle->bufferInfos[i].buffers[bufferIndex],
-                    bufferBytes );
-        }
+void sampleRateChanged( ASIOSampleRate sRate )
+{
+  // The ASIO documentation says that this usually only happens during
+  // external sync.  Audio processing is not stopped by the driver,
+  // actual sample rate might not have even changed, maybe only the
+  // sample rate status of an AES/EBU or S/PDIF digital input at the
+  // audio device.
+
+  RtApi *object = (RtApi *) asioCallbackInfo->object;
+  try {
+    object->stopStream();
+  }
+  catch ( RtError &exception ) {
+    std::cerr << "\nRtApiAsio: sampleRateChanged() error (" << exception.getMessage() << ")!\n" << std::endl;
+    return;
+  }
 
-        if ( stream_.doByteSwap[1] )
-          byteSwapBuffer( stream_.deviceBuffer,
-                          stream_.bufferSize * stream_.nDeviceChannels[1],
-                          stream_.deviceFormat[1] );
-        convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
+  std::cerr << "\nRtApiAsio: driver reports sample rate changed to " << sRate << " ... stream stopped!!!\n" << std::endl;
+}
 
-      }
-      else {
-        for ( i=0, j=0; i<nChannels; i++ ) {
-          if ( handle->bufferInfos[i].isInput == ASIOTrue ) {
-            memcpy( &stream_.userBuffer[1][bufferBytes*j++],
-                    handle->bufferInfos[i].buffers[bufferIndex],
-                    bufferBytes );
-          }
-        }
+long asioMessages( long selector, long value, void* message, double* opt )
+{
+  long ret = 0;
+
+  switch( selector ) {
+  case kAsioSelectorSupported:
+    if ( value == kAsioResetRequest
+         || value == kAsioEngineVersion
+         || value == kAsioResyncRequest
+         || value == kAsioLatenciesChanged
+         // The following three were added for ASIO 2.0, you don't
+         // necessarily have to support them.
+         || value == kAsioSupportsTimeInfo
+         || value == kAsioSupportsTimeCode
+         || value == kAsioSupportsInputMonitor)
+      ret = 1L;
+    break;
+  case kAsioResetRequest:
+    // Defer the task and perform the reset of the driver during the
+    // next "safe" situation.  You cannot reset the driver right now,
+    // as this code is called from the driver.  Reset the driver is
+    // done by completely destruct is. I.e. ASIOStop(),
+    // ASIODisposeBuffers(), Destruction Afterwards you initialize the
+    // driver again.
+    std::cerr << "\nRtApiAsio: driver reset requested!!!" << std::endl;
+    ret = 1L;
+    break;
+  case kAsioResyncRequest:
+    // This informs the application that the driver encountered some
+    // non-fatal data loss.  It is used for synchronization purposes
+    // of different media.  Added mainly to work around the Win16Mutex
+    // problems in Windows 95/98 with the Windows Multimedia system,
+    // which could lose data because the Mutex was held too long by
+    // another thread.  However a driver can issue it in other
+    // situations, too.
+    // std::cerr << "\nRtApiAsio: driver resync requested!!!" << std::endl;
+    asioXRun = true;
+    ret = 1L;
+    break;
+  case kAsioLatenciesChanged:
+    // This will inform the host application that the drivers were
+    // latencies changed.  Beware, it this does not mean that the
+    // buffer sizes have changed!  You might need to update internal
+    // delay data.
+    std::cerr << "\nRtApiAsio: driver latency may have changed!!!" << std::endl;
+    ret = 1L;
+    break;
+  case kAsioEngineVersion:
+    // Return the supported ASIO version of the host application.  If
+    // a host application does not implement this selector, ASIO 1.0
+    // is assumed by the driver.
+    ret = 2L;
+    break;
+  case kAsioSupportsTimeInfo:
+    // Informs the driver whether the
+    // asioCallbacks.bufferSwitchTimeInfo() callback is supported.
+    // For compatibility with ASIO 1.0 drivers the host application
+    // should always support the "old" bufferSwitch method, too.
+    ret = 0;
+    break;
+  case kAsioSupportsTimeCode:
+    // Informs the driver whether application is interested in time
+    // code info.  If an application does not need to know about time
+    // code, the driver has less work to do.
+    ret = 0;
+    break;
+  }
+  return ret;
+}
 
-        if ( stream_.doByteSwap[1] )
-          byteSwapBuffer( stream_.userBuffer[1],
-                          stream_.bufferSize * stream_.nUserChannels[1],
-                          stream_.userFormat );
-      }
-    }
+static const char* getAsioErrorString( ASIOError result )
+{
+  struct Messages 
+  {
+    ASIOError value;
+    const char*message;
+  };
 
-  unlock:
-    // The following call was suggested by Malte Clasen.  While the API
-    // documentation indicates it should not be required, some device
-    // drivers apparently do not function correctly without it.
-    ASIOOutputReady();
+  static Messages m[] = 
+    {
+      {   ASE_NotPresent,    "Hardware input or output is not present or available." },
+      {   ASE_HWMalfunction,  "Hardware is malfunctioning." },
+      {   ASE_InvalidParameter, "Invalid input parameter." },
+      {   ASE_InvalidMode,      "Invalid mode." },
+      {   ASE_SPNotAdvancing,     "Sample position not advancing." },
+      {   ASE_NoClock,            "Sample clock or rate cannot be determined or is not present." },
+      {   ASE_NoMemory,           "Not enough memory to complete the request." }
+    };
 
-    MUTEX_UNLOCK( &stream_.mutex );
+  for ( unsigned int i = 0; i < sizeof(m)/sizeof(m[0]); ++i )
+    if ( m[i].value == result ) return m[i].message;
 
-    RtApi::tickStreamTime();
-    return SUCCESS;
-  }
+  return "Unknown error.";
+}
+//******************** End of __WINDOWS_ASIO__ *********************//
+#endif
 
-  void sampleRateChanged( ASIOSampleRate sRate )
-  {
-    // The ASIO documentation says that this usually only happens during
-    // external sync.  Audio processing is not stopped by the driver,
-    // actual sample rate might not have even changed, maybe only the
-    // sample rate status of an AES/EBU or S/PDIF digital input at the
-    // audio device.
 
-    RtApi *object = (RtApi *) asioCallbackInfo->object;
-    try {
-      object->stopStream();
-    }
-    catch ( RtError &exception ) {
-      std::cerr << "\nRtApiAsio: sampleRateChanged() error (" << exception.getMessage() << ")!\n" << std::endl;
-      return;
-    }
+#if defined(__WINDOWS_DS__) // Windows DirectSound API
 
-    std::cerr << "\nRtApiAsio: driver reports sample rate changed to " << sRate << " ... stream stopped!!!\n" << std::endl;
-  }
-
-  long asioMessages( long selector, long value, void* message, double* opt )
-  {
-    long ret = 0;
-
-    switch( selector ) {
-    case kAsioSelectorSupported:
-      if ( value == kAsioResetRequest
-           || value == kAsioEngineVersion
-           || value == kAsioResyncRequest
-           || value == kAsioLatenciesChanged
-           // The following three were added for ASIO 2.0, you don't
-           // necessarily have to support them.
-           || value == kAsioSupportsTimeInfo
-           || value == kAsioSupportsTimeCode
-           || value == kAsioSupportsInputMonitor)
-        ret = 1L;
-      break;
-    case kAsioResetRequest:
-      // Defer the task and perform the reset of the driver during the
-      // next "safe" situation.  You cannot reset the driver right now,
-      // as this code is called from the driver.  Reset the driver is
-      // done by completely destruct is. I.e. ASIOStop(),
-      // ASIODisposeBuffers(), Destruction Afterwards you initialize the
-      // driver again.
-      std::cerr << "\nRtApiAsio: driver reset requested!!!" << std::endl;
-      ret = 1L;
-      break;
-    case kAsioResyncRequest:
-      // This informs the application that the driver encountered some
-      // non-fatal data loss.  It is used for synchronization purposes
-      // of different media.  Added mainly to work around the Win16Mutex
-      // problems in Windows 95/98 with the Windows Multimedia system,
-      // which could lose data because the Mutex was held too long by
-      // another thread.  However a driver can issue it in other
-      // situations, too.
-      // std::cerr << "\nRtApiAsio: driver resync requested!!!" << std::endl;
-      asioXRun = true;
-      ret = 1L;
-      break;
-    case kAsioLatenciesChanged:
-      // This will inform the host application that the drivers were
-      // latencies changed.  Beware, it this does not mean that the
-      // buffer sizes have changed!  You might need to update internal
-      // delay data.
-      std::cerr << "\nRtApiAsio: driver latency may have changed!!!" << std::endl;
-      ret = 1L;
-      break;
-    case kAsioEngineVersion:
-      // Return the supported ASIO version of the host application.  If
-      // a host application does not implement this selector, ASIO 1.0
-      // is assumed by the driver.
-      ret = 2L;
-      break;
-    case kAsioSupportsTimeInfo:
-      // Informs the driver whether the
-      // asioCallbacks.bufferSwitchTimeInfo() callback is supported.
-      // For compatibility with ASIO 1.0 drivers the host application
-      // should always support the "old" bufferSwitch method, too.
-      ret = 0;
-      break;
-    case kAsioSupportsTimeCode:
-      // Informs the driver whether application is interested in time
-      // code info.  If an application does not need to know about time
-      // code, the driver has less work to do.
-      ret = 0;
-      break;
-    }
-    return ret;
-  }
-
-  static const char* getAsioErrorString( ASIOError result )
-  {
-    struct Messages 
-    {
-      ASIOError value;
-      const char*message;
-    };
-
-    static Messages m[] = 
-      {
-        {   ASE_NotPresent,    "Hardware input or output is not present or available." },
-        {   ASE_HWMalfunction,  "Hardware is malfunctioning." },
-        {   ASE_InvalidParameter, "Invalid input parameter." },
-        {   ASE_InvalidMode,      "Invalid mode." },
-        {   ASE_SPNotAdvancing,     "Sample position not advancing." },
-        {   ASE_NoClock,            "Sample clock or rate cannot be determined or is not present." },
-        {   ASE_NoMemory,           "Not enough memory to complete the request." }
-      };
-
-    for ( unsigned int i = 0; i < sizeof(m)/sizeof(m[0]); ++i )
-      if ( m[i].value == result ) return m[i].message;
-
-    return "Unknown error.";
-  }
-  //******************** End of __WINDOWS_ASIO__ *********************//
-#endif
-
-
-#if defined(__WINDOWS_DS__) // Windows DirectSound API
-
-  // Modified by Robin Davies, October 2005
-  // - Improvements to DirectX pointer chasing. 
-  // - Backdoor RtDsStatistics hook provides DirectX performance information.
-  // - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.
-  // - Auto-call CoInitialize for DSOUND and ASIO platforms.
-  // Various revisions for RtAudio 4.0 by Gary Scavone, April 2007
+// Modified by Robin Davies, October 2005
+// - Improvements to DirectX pointer chasing. 
+// - Backdoor RtDsStatistics hook provides DirectX performance information.
+// - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.
+// - Auto-call CoInitialize for DSOUND and ASIO platforms.
+// Various revisions for RtAudio 4.0 by Gary Scavone, April 2007
 
 #include <dsound.h>
 #include <assert.h>
@@ -3383,1587 +3406,1599 @@ bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
 #pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually.
 #endif
 
-  static inline DWORD dsPointerDifference( DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
-  {
-    if ( laterPointer > earlierPointer )
-      return laterPointer - earlierPointer;
-    else
-      return laterPointer - earlierPointer + bufferSize;
-  }
+static inline DWORD dsPointerDifference( DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
+{
+  if ( laterPointer > earlierPointer )
+    return laterPointer - earlierPointer;
+  else
+    return laterPointer - earlierPointer + bufferSize;
+}
 
-  static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
-  {
-    if ( pointer > bufferSize ) pointer -= bufferSize;
-    if ( laterPointer < earlierPointer ) laterPointer += bufferSize;
-    if ( pointer < earlierPointer ) pointer += bufferSize;
-    return pointer >= earlierPointer && pointer < laterPointer;
-  }
-
-  // A structure to hold various information related to the DirectSound
-  // API implementation.
-  struct DsHandle {
-    unsigned int drainCounter; // Tracks callback counts when draining
-    bool internalDrain;        // Indicates if stop is initiated from callback or not.
-    void *id[2];
-    void *buffer[2];
-    bool xrun[2];
-    UINT bufferPointer[2];  
-    DWORD dsBufferSize[2];
-    DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.
-    HANDLE condition;
-
-    DsHandle()
-      :drainCounter(0), internalDrain(false) { id[0] = 0; id[1] = 0; buffer[0] = 0; buffer[1] = 0; xrun[0] = false; xrun[1] = false; bufferPointer[0] = 0; bufferPointer[1] = 0; }
-  };
+static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )
+{
+  if ( pointer > bufferSize ) pointer -= bufferSize;
+  if ( laterPointer < earlierPointer ) laterPointer += bufferSize;
+  if ( pointer < earlierPointer ) pointer += bufferSize;
+  return pointer >= earlierPointer && pointer < laterPointer;
+}
 
-  /*
-    RtApiDs::RtDsStatistics RtApiDs::statistics;
+// A structure to hold various information related to the DirectSound
+// API implementation.
+struct DsHandle {
+  unsigned int drainCounter; // Tracks callback counts when draining
+  bool internalDrain;        // Indicates if stop is initiated from callback or not.
+  void *id[2];
+  void *buffer[2];
+  bool xrun[2];
+  UINT bufferPointer[2];  
+  DWORD dsBufferSize[2];
+  DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.
+  HANDLE condition;
 
-    // Provides a backdoor hook to monitor for DirectSound read overruns and write underruns.
-    RtApiDs::RtDsStatistics RtApiDs::getDsStatistics()
-    {
-    RtDsStatistics s = statistics;
+  DsHandle()
+    :drainCounter(0), internalDrain(false) { id[0] = 0; id[1] = 0; buffer[0] = 0; buffer[1] = 0; xrun[0] = false; xrun[1] = false; bufferPointer[0] = 0; bufferPointer[1] = 0; }
+};
+
+/*
+RtApiDs::RtDsStatistics RtApiDs::statistics;
+
+// Provides a backdoor hook to monitor for DirectSound read overruns and write underruns.
+RtApiDs::RtDsStatistics RtApiDs::getDsStatistics()
+{
+  RtDsStatistics s = statistics;
 
-    // update the calculated fields.
-    if ( s.inputFrameSize != 0 )
+  // update the calculated fields.
+  if ( s.inputFrameSize != 0 )
     s.latency += s.readDeviceSafeLeadBytes * 1.0 / s.inputFrameSize / s.sampleRate;
 
-    if ( s.outputFrameSize != 0 )
+  if ( s.outputFrameSize != 0 )
     s.latency += (s.writeDeviceSafeLeadBytes + s.writeDeviceBufferLeadBytes) * 1.0 / s.outputFrameSize / s.sampleRate;
 
-    return s;
-    }
-  */
+  return s;
+}
+*/
 
-  // Declarations for utility functions, callbacks, and structures
-  // specific to the DirectSound implementation.
-  static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
-                                            LPCTSTR description,
-                                            LPCTSTR module,
-                                            LPVOID lpContext );
+// Declarations for utility functions, callbacks, and structures
+// specific to the DirectSound implementation.
+static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
+                                          LPCTSTR description,
+                                          LPCTSTR module,
+                                          LPVOID lpContext );
 
-  static char* getErrorString( int code );
+static char* getErrorString( int code );
 
-  extern "C" unsigned __stdcall callbackHandler( void *ptr );
+extern "C" unsigned __stdcall callbackHandler( void *ptr );
 
-  struct EnumInfo {
-    bool isInput;
-    bool getDefault;
-    bool findIndex;
-    unsigned int counter;
-    unsigned int index;
-    LPGUID id;
-    std::string name;
+struct EnumInfo {
+  bool isInput;
+  bool getDefault;
+  bool findIndex;
+  unsigned int counter;
+  unsigned int index;
+  LPGUID id;
+  std::string name;
 
-    EnumInfo()
-      : isInput(false), getDefault(false), findIndex(false), counter(0), index(0) {}
-  };
+  EnumInfo()
+    : isInput(false), getDefault(false), findIndex(false), counter(0), index(0) {}
+};
 
-  RtApiDs :: RtApiDs()
-  {
-    // Dsound will run both-threaded. If CoInitialize fails, then just
-    // accept whatever the mainline chose for a threading model.
-    coInitialized_ = false;
-    HRESULT hr = CoInitialize( NULL );
-    if ( !FAILED( hr ) ) coInitialized_ = true;
-  }
+RtApiDs :: RtApiDs()
+{
+  // Dsound will run both-threaded. If CoInitialize fails, then just
+  // accept whatever the mainline chose for a threading model.
+  coInitialized_ = false;
+  HRESULT hr = CoInitialize( NULL );
+  if ( !FAILED( hr ) ) coInitialized_ = true;
+}
 
-  RtApiDs :: ~RtApiDs()
-  {
-    if ( coInitialized_ ) CoUninitialize(); // balanced call.
-    if ( stream_.state != STREAM_CLOSED ) closeStream();
+RtApiDs :: ~RtApiDs()
+{
+  if ( coInitialized_ ) CoUninitialize(); // balanced call.
+  if ( stream_.state != STREAM_CLOSED ) closeStream();
+}
+
+unsigned int RtApiDs :: getDefaultInputDevice( void )
+{
+  // Count output devices.
+  EnumInfo info;
+  HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
+  if ( FAILED( result ) ) {
+    errorStream_ << "RtApiDs::getDefaultOutputDevice: error (" << getErrorString( result ) << ") counting output devices!";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return 0;
   }
 
-  unsigned int RtApiDs :: getDefaultInputDevice( void )
-  {
-    // Count output devices.
-    EnumInfo info;
-    HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
-    if ( FAILED( result ) ) {
-      errorStream_ << "RtApiDs::getDefaultOutputDevice: error (" << getErrorString( result ) << ") counting output devices!";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return 0;
-    }
+  // Now enumerate input devices until we find the id = NULL.
+  info.isInput = true;
+  info.getDefault = true;
+  result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
+  if ( FAILED( result ) ) {
+    errorStream_ << "RtApiDs::getDefaultInputDevice: error (" << getErrorString( result ) << ") enumerating input devices!";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return 0;
+  }
 
-    // Now enumerate input devices until we find the id = NULL.
-    info.isInput = true;
-    info.getDefault = true;
-    result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
-    if ( FAILED( result ) ) {
-      errorStream_ << "RtApiDs::getDefaultInputDevice: error (" << getErrorString( result ) << ") enumerating input devices!";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return 0;
-    }
+  if ( info.counter > 0 ) return info.counter - 1;
+  return 0;
+}
 
-    if ( info.counter > 0 ) return info.counter - 1;
+unsigned int RtApiDs :: getDefaultOutputDevice( void )
+{
+  // Enumerate output devices until we find the id = NULL.
+  EnumInfo info;
+  info.getDefault = true;
+  HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
+  if ( FAILED( result ) ) {
+    errorStream_ << "RtApiDs::getDefaultOutputDevice: error (" << getErrorString( result ) << ") enumerating output devices!";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
     return 0;
   }
 
-  unsigned int RtApiDs :: getDefaultOutputDevice( void )
-  {
-    // Enumerate output devices until we find the id = NULL.
-    EnumInfo info;
-    info.getDefault = true;
-    HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
-    if ( FAILED( result ) ) {
-      errorStream_ << "RtApiDs::getDefaultOutputDevice: error (" << getErrorString( result ) << ") enumerating output devices!";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return 0;
-    }
+  if ( info.counter > 0 ) return info.counter - 1;
+  return 0;
+}
 
-    if ( info.counter > 0 ) return info.counter - 1;
-    return 0;
+unsigned int RtApiDs :: getDeviceCount( void )
+{
+  // Count DirectSound devices.
+  EnumInfo info;
+  HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
+  if ( FAILED( result ) ) {
+    errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
   }
 
-  unsigned int RtApiDs :: getDeviceCount( void )
-  {
-    // Count DirectSound devices.
-    EnumInfo info;
-    HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
-    if ( FAILED( result ) ) {
-      errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-    }
+  // Count DirectSoundCapture devices.
+  info.isInput = true;
+  result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
+  if ( FAILED( result ) ) {
+    errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+  }
 
-    // Count DirectSoundCapture devices.
-    info.isInput = true;
-    result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &info );
-    if ( FAILED( result ) ) {
-      errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-    }
+  return info.counter;
+}
+
+RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )
+{
+  // Because DirectSound always enumerates input and output devices
+  // separately (and because we don't attempt to combine devices
+  // internally), none of our "devices" will ever be duplex.
+
+  RtAudio::DeviceInfo info;
+  info.probed = false;
 
-    return info.counter;
+  // Enumerate through devices to find the id (if it exists).  Note
+  // that we have to do the output enumeration first, even if this is
+  // an input device, in order for the device counter to be correct.
+  EnumInfo dsinfo;
+  dsinfo.findIndex = true;
+  dsinfo.index = device;
+  HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &dsinfo );
+  if ( FAILED( result ) ) {
+    errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") enumerating output devices!";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
   }
 
-  RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )
-  {
-    // Because DirectSound always enumerates input and output devices
-    // separately (and because we don't attempt to combine devices
-    // internally), none of our "devices" will ever be duplex.
-
-    RtAudio::DeviceInfo info;
-    info.probed = false;
-
-    // Enumerate through devices to find the id (if it exists).  Note
-    // that we have to do the output enumeration first, even if this is
-    // an input device, in order for the device counter to be correct.
-    EnumInfo dsinfo;
-    dsinfo.findIndex = true;
-    dsinfo.index = device;
-    HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &dsinfo );
-    if ( FAILED( result ) ) {
-      errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") enumerating output devices!";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-    }
+  if ( dsinfo.name.empty() ) goto probeInput;
 
-    if ( dsinfo.name.empty() ) goto probeInput;
+  LPDIRECTSOUND output;
+  DSCAPS outCaps;
+  result = DirectSoundCreate( dsinfo.id, &output, NULL );
+  if ( FAILED( result ) ) {
+    errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsinfo.name << ")!";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return info;
+  }
 
-    LPDIRECTSOUND output;
-    DSCAPS outCaps;
-    result = DirectSoundCreate( dsinfo.id, &output, NULL );
-    if ( FAILED( result ) ) {
-      errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsinfo.name << ")!";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
-    }
+  outCaps.dwSize = sizeof( outCaps );
+  result = output->GetCaps( &outCaps );
+  if ( FAILED( result ) ) {
+    output->Release();
+    errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return info;
+  }
 
-    outCaps.dwSize = sizeof( outCaps );
-    result = output->GetCaps( &outCaps );
-    if ( FAILED( result ) ) {
-      output->Release();
-      errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
-    }
+  // Get output channel information.
+  info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
 
-    // Get output channel information.
-    info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
+  // Get sample rate information.
+  info.sampleRates.clear();
+  for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
+    if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&
+         SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate )
+      info.sampleRates.push_back( SAMPLE_RATES[k] );
+  }
 
-    // Get sample rate information.
-    info.sampleRates.clear();
-    for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
-      if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&
-           SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate )
-        info.sampleRates.push_back( SAMPLE_RATES[k] );
-    }
+  // Get format information.
+  if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;
+  if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;
 
-    // Get format information.
-    if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;
-    if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;
+  output->Release();
 
-    output->Release();
+  if ( getDefaultOutputDevice() == device )
+    info.isDefaultOutput = true;
 
-    if ( getDefaultOutputDevice() == device )
-      info.isDefaultOutput = true;
+  // Copy name and return.
+  info.name = dsinfo.name;
 
-    // Copy name and return.
-    info.name = dsinfo.name;
+  info.probed = true;
+  return info;
 
-    info.probed = true;
+ probeInput:
+
+  dsinfo.isInput = true;
+  result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &dsinfo );
+  if ( FAILED( result ) ) {
+    errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") enumerating input devices!";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+  }
+
+  if ( dsinfo.name.empty() ) return info;
+
+  LPDIRECTSOUNDCAPTURE input;
+  result = DirectSoundCaptureCreate( dsinfo.id, &input, NULL );
+  if ( FAILED( result ) ) {
+    errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsinfo.name << ")!";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
     return info;
+  }
+
+  DSCCAPS inCaps;
+  inCaps.dwSize = sizeof( inCaps );
+  result = input->GetCaps( &inCaps );
+  if ( FAILED( result ) ) {
+    input->Release();
+    errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsinfo.name << ")!";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return info;
+  }
+
+  // Get input channel information.
+  info.inputChannels = inCaps.dwChannels;
+
+  // Get sample rate and format information.
+  if ( inCaps.dwChannels == 2 ) {
+    if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;
+    if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;
+    if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;
+    if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;
+    if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;
+    if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;
+    if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;
+    if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;
+
+    if ( info.nativeFormats & RTAUDIO_SINT16 ) {
+      if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.sampleRates.push_back( 11025 );
+      if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.sampleRates.push_back( 22050 );
+      if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.sampleRates.push_back( 44100 );
+      if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.sampleRates.push_back( 96000 );
+    }
+    else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
+      if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.sampleRates.push_back( 11025 );
+      if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.sampleRates.push_back( 22050 );
+      if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.sampleRates.push_back( 44100 );
+      if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.sampleRates.push_back( 44100 );
+    }
+  }
+  else if ( inCaps.dwChannels == 1 ) {
+    if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;
+    if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;
+    if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;
+    if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;
+    if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;
+    if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;
+    if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;
+    if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;
+
+    if ( info.nativeFormats & RTAUDIO_SINT16 ) {
+      if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.sampleRates.push_back( 11025 );
+      if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.sampleRates.push_back( 22050 );
+      if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.sampleRates.push_back( 44100 );
+      if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.sampleRates.push_back( 96000 );
+    }
+    else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
+      if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.sampleRates.push_back( 11025 );
+      if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.sampleRates.push_back( 22050 );
+      if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.sampleRates.push_back( 44100 );
+      if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.sampleRates.push_back( 96000 );
+    }
+  }
+  else info.inputChannels = 0; // technically, this would be an error
+
+  input->Release();
+
+  if ( info.inputChannels == 0 ) return info;
+
+  if ( getDefaultInputDevice() == device )
+    info.isDefaultInput = true;
+
+  // Copy name and return.
+  info.name = dsinfo.name;
+  info.probed = true;
+  return info;
+}
 
-  probeInput:
+bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
+                                 unsigned int firstChannel, unsigned int sampleRate,
+                                 RtAudioFormat format, unsigned int *bufferSize,
+                                 RtAudio::StreamOptions *options )
+{
+  if ( channels + firstChannel > 2 ) {
+    errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";
+    return FAILURE;
+  }
+
+  // Enumerate through devices to find the id (if it exists).  Note
+  // that we have to do the output enumeration first, even if this is
+  // an input device, in order for the device counter to be correct.
+  EnumInfo dsinfo;
+  dsinfo.findIndex = true;
+  dsinfo.index = device;
+  HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &dsinfo );
+  if ( FAILED( result ) ) {
+    errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") enumerating output devices!";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
+  if ( mode == OUTPUT ) {
+    if ( dsinfo.name.empty() ) {
+      errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";
+      errorText_ = errorStream_.str();
+      return FAILURE;
+    }
+  }
+  else { // mode == INPUT
     dsinfo.isInput = true;
-    result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &dsinfo );
+    HRESULT result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &dsinfo );
     if ( FAILED( result ) ) {
-      errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") enumerating input devices!";
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") enumerating input devices!";
       errorText_ = errorStream_.str();
-      error( RtError::WARNING );
+      return FAILURE;
+    }
+    if ( dsinfo.name.empty() ) {
+      errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";
+      errorText_ = errorStream_.str();
+      return FAILURE;
     }
+  }
 
-    if ( dsinfo.name.empty() ) return info;
+  // According to a note in PortAudio, using GetDesktopWindow()
+  // instead of GetForegroundWindow() is supposed to avoid problems
+  // that occur when the application's window is not the foreground
+  // window.  Also, if the application window closes before the
+  // DirectSound buffer, DirectSound can crash.  However, for console
+  // applications, no sound was produced when using GetDesktopWindow().
+  HWND hWnd = GetForegroundWindow();
+
+  // Check the numberOfBuffers parameter and limit the lowest value to
+  // two.  This is a judgement call and a value of two is probably too
+  // low for capture, but it should work for playback.
+  int nBuffers = 0;
+  if ( options ) nBuffers = options->numberOfBuffers;
+  if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;
+  if ( nBuffers < 2 ) nBuffers = 3;
+
+  // Create the wave format structure.  The data format setting will
+  // be determined later.
+  WAVEFORMATEX waveFormat;
+  ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );
+  waveFormat.wFormatTag = WAVE_FORMAT_PCM;
+  waveFormat.nChannels = channels + firstChannel;
+  waveFormat.nSamplesPerSec = (unsigned long) sampleRate;
+
+  // Determine the device buffer size. By default, 32k, but we will
+  // grow it to make allowances for very large software buffer sizes.
+  DWORD dsBufferSize = 0;
+  DWORD dsPointerLeadTime = 0;
+  long bufferBytes = MINIMUM_DEVICE_BUFFER_SIZE; // sound cards will always *knock wood* support this
+
+  void *ohandle = 0, *bhandle = 0;
+  if ( mode == OUTPUT ) {
 
-    LPDIRECTSOUNDCAPTURE input;
-    result = DirectSoundCaptureCreate( dsinfo.id, &input, NULL );
+    LPDIRECTSOUND output;
+    result = DirectSoundCreate( dsinfo.id, &output, NULL );
     if ( FAILED( result ) ) {
-      errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsinfo.name << ")!";
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsinfo.name << ")!";
       errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
+      return FAILURE;
     }
 
-    DSCCAPS inCaps;
-    inCaps.dwSize = sizeof( inCaps );
-    result = input->GetCaps( &inCaps );
+    DSCAPS outCaps;
+    outCaps.dwSize = sizeof( outCaps );
+    result = output->GetCaps( &outCaps );
     if ( FAILED( result ) ) {
-      input->Release();
-      errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsinfo.name << ")!";
+      output->Release();
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsinfo.name << ")!";
       errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
+      return FAILURE;
     }
 
-    // Get input channel information.
-    info.inputChannels = inCaps.dwChannels;
-
-    // Get sample rate and format information.
-    if ( inCaps.dwChannels == 2 ) {
-      if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;
-      if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;
-      if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;
-      if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;
-      if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;
-      if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;
-      if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;
-      if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;
-
-      if ( info.nativeFormats & RTAUDIO_SINT16 ) {
-        if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.sampleRates.push_back( 11025 );
-        if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.sampleRates.push_back( 22050 );
-        if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.sampleRates.push_back( 44100 );
-        if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.sampleRates.push_back( 96000 );
-      }
-      else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
-        if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.sampleRates.push_back( 11025 );
-        if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.sampleRates.push_back( 22050 );
-        if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.sampleRates.push_back( 44100 );
-        if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.sampleRates.push_back( 44100 );
-      }
+    // Check channel information.
+    if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {
+      errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsinfo.name << ") does not support stereo playback.";
+      errorText_ = errorStream_.str();
+      return FAILURE;
     }
-    else if ( inCaps.dwChannels == 1 ) {
-      if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;
-      if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;
-      if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;
-      if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;
-      if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;
-      if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;
-      if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;
-      if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;
-
-      if ( info.nativeFormats & RTAUDIO_SINT16 ) {
-        if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.sampleRates.push_back( 11025 );
-        if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.sampleRates.push_back( 22050 );
-        if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.sampleRates.push_back( 44100 );
-        if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.sampleRates.push_back( 96000 );
-      }
-      else if ( info.nativeFormats & RTAUDIO_SINT8 ) {
-        if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.sampleRates.push_back( 11025 );
-        if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.sampleRates.push_back( 22050 );
-        if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.sampleRates.push_back( 44100 );
-        if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.sampleRates.push_back( 96000 );
-      }
+
+    // Check format information.  Use 16-bit format unless not
+    // supported or user requests 8-bit.
+    if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&
+         !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {
+      waveFormat.wBitsPerSample = 16;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT16;
+    }
+    else {
+      waveFormat.wBitsPerSample = 8;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT8;
     }
-    else info.inputChannels = 0; // technically, this would be an error
+    stream_.userFormat = format;
 
-    input->Release();
+    // Update wave format structure and buffer information.
+    waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
+    waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
+    dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
 
-    if ( info.inputChannels == 0 ) return info;
+    // If the user wants an even bigger buffer, increase the device buffer size accordingly.
+    while ( dsPointerLeadTime * 2U > (DWORD) bufferBytes )
+      bufferBytes *= 2;
 
-    if ( getDefaultInputDevice() == device )
-      info.isDefaultInput = true;
+    // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.
+    //result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );
+    // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.
+    result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );
+    if ( FAILED( result ) ) {
+      output->Release();
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsinfo.name << ")!";
+      errorText_ = errorStream_.str();
+      return FAILURE;
+    }
 
-    // Copy name and return.
-    info.name = dsinfo.name;
-    info.probed = true;
-    return info;
-  }
+    // Even though we will write to the secondary buffer, we need to
+    // access the primary buffer to set the correct output format
+    // (since the default is 8-bit, 22 kHz!).  Setup the DS primary
+    // buffer description.
+    DSBUFFERDESC bufferDescription;
+    ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
+    bufferDescription.dwSize = sizeof( DSBUFFERDESC );
+    bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
 
-  bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
-                                   unsigned int firstChannel, unsigned int sampleRate,
-                                   RtAudioFormat format, unsigned int *bufferSize,
-                                   RtAudio::StreamOptions *options )
-  {
-    if ( channels + firstChannel > 2 ) {
-      errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";
+    // Obtain the primary buffer
+    LPDIRECTSOUNDBUFFER buffer;
+    result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
+    if ( FAILED( result ) ) {
+      output->Release();
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsinfo.name << ")!";
+      errorText_ = errorStream_.str();
       return FAILURE;
     }
 
-    // Enumerate through devices to find the id (if it exists).  Note
-    // that we have to do the output enumeration first, even if this is
-    // an input device, in order for the device counter to be correct.
-    EnumInfo dsinfo;
-    dsinfo.findIndex = true;
-    dsinfo.index = device;
-    HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &dsinfo );
+    // Set the primary DS buffer sound format.
+    result = buffer->SetFormat( &waveFormat );
     if ( FAILED( result ) ) {
-      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") enumerating output devices!";
+      output->Release();
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsinfo.name << ")!";
       errorText_ = errorStream_.str();
       return FAILURE;
     }
 
-    if ( mode == OUTPUT ) {
-      if ( dsinfo.name.empty() ) {
-        errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
-    }
-    else { // mode == INPUT
-      dsinfo.isInput = true;
-      HRESULT result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &dsinfo );
+    // Setup the secondary DS buffer description.
+    dsBufferSize = (DWORD) bufferBytes;
+    ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
+    bufferDescription.dwSize = sizeof( DSBUFFERDESC );
+    bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
+                                  DSBCAPS_GLOBALFOCUS |
+                                  DSBCAPS_GETCURRENTPOSITION2 |
+                                  DSBCAPS_LOCHARDWARE );  // Force hardware mixing
+    bufferDescription.dwBufferBytes = bufferBytes;
+    bufferDescription.lpwfxFormat = &waveFormat;
+
+    // Try to create the secondary DS buffer.  If that doesn't work,
+    // try to use software mixing.  Otherwise, there's a problem.
+    result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
+    if ( FAILED( result ) ) {
+      bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
+                                    DSBCAPS_GLOBALFOCUS |
+                                    DSBCAPS_GETCURRENTPOSITION2 |
+                                    DSBCAPS_LOCSOFTWARE );  // Force software mixing
+      result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
       if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") enumerating input devices!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
-      if ( dsinfo.name.empty() ) {
-        errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";
+        output->Release();
+        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsinfo.name << ")!";
         errorText_ = errorStream_.str();
         return FAILURE;
       }
     }
 
-    // According to a note in PortAudio, using GetDesktopWindow()
-    // instead of GetForegroundWindow() is supposed to avoid problems
-    // that occur when the application's window is not the foreground
-    // window.  Also, if the application window closes before the
-    // DirectSound buffer, DirectSound can crash.  However, for console
-    // applications, no sound was produced when using GetDesktopWindow().
-    HWND hWnd = GetForegroundWindow();
-
-    // Check the numberOfBuffers parameter and limit the lowest value to
-    // two.  This is a judgement call and a value of two is probably too
-    // low for capture, but it should work for playback.
-    int nBuffers = 0;
-    if ( options ) nBuffers = options->numberOfBuffers;
-    if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;
-    if ( nBuffers < 2 ) nBuffers = 3;
-
-    // Create the wave format structure.  The data format setting will
-    // be determined later.
-    WAVEFORMATEX waveFormat;
-    ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );
-    waveFormat.wFormatTag = WAVE_FORMAT_PCM;
-    waveFormat.nChannels = channels + firstChannel;
-    waveFormat.nSamplesPerSec = (unsigned long) sampleRate;
-
-    // Determine the device buffer size. By default, 32k, but we will
-    // grow it to make allowances for very large software buffer sizes.
-    DWORD dsBufferSize = 0;
-    DWORD dsPointerLeadTime = 0;
-    long bufferBytes = MINIMUM_DEVICE_BUFFER_SIZE; // sound cards will always *knock wood* support this
-
-    void *ohandle = 0, *bhandle = 0;
-    if ( mode == OUTPUT ) {
-
-      LPDIRECTSOUND output;
-      result = DirectSoundCreate( dsinfo.id, &output, NULL );
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsinfo.name << ")!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
-
-      DSCAPS outCaps;
-      outCaps.dwSize = sizeof( outCaps );
-      result = output->GetCaps( &outCaps );
-      if ( FAILED( result ) ) {
-        output->Release();
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsinfo.name << ")!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
-
-      // Check channel information.
-      if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {
-        errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsinfo.name << ") does not support stereo playback.";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
-
-      // Check format information.  Use 16-bit format unless not
-      // supported or user requests 8-bit.
-      if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&
-           !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {
-        waveFormat.wBitsPerSample = 16;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-      }
-      else {
-        waveFormat.wBitsPerSample = 8;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT8;
-      }
-      stream_.userFormat = format;
-
-      // Update wave format structure and buffer information.
-      waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
-      waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
-      dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
-
-      // If the user wants an even bigger buffer, increase the device buffer size accordingly.
-      while ( dsPointerLeadTime * 2U > (DWORD) bufferBytes )
-        bufferBytes *= 2;
-
-      // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.
-      //result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );
-      // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.
-      result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );
-      if ( FAILED( result ) ) {
-        output->Release();
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsinfo.name << ")!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
-
-      // Even though we will write to the secondary buffer, we need to
-      // access the primary buffer to set the correct output format
-      // (since the default is 8-bit, 22 kHz!).  Setup the DS primary
-      // buffer description.
-      DSBUFFERDESC bufferDescription;
-      ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
-      bufferDescription.dwSize = sizeof( DSBUFFERDESC );
-      bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
-
-      // Obtain the primary buffer
-      LPDIRECTSOUNDBUFFER buffer;
-      result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
-      if ( FAILED( result ) ) {
-        output->Release();
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsinfo.name << ")!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
-
-      // Set the primary DS buffer sound format.
-      result = buffer->SetFormat( &waveFormat );
-      if ( FAILED( result ) ) {
-        output->Release();
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsinfo.name << ")!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
-
-      // Setup the secondary DS buffer description.
-      dsBufferSize = (DWORD) bufferBytes;
-      ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );
-      bufferDescription.dwSize = sizeof( DSBUFFERDESC );
-      bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
-                                    DSBCAPS_GLOBALFOCUS |
-                                    DSBCAPS_GETCURRENTPOSITION2 |
-                                    DSBCAPS_LOCHARDWARE );  // Force hardware mixing
-      bufferDescription.dwBufferBytes = bufferBytes;
-      bufferDescription.lpwfxFormat = &waveFormat;
+    // Get the buffer size ... might be different from what we specified.
+    DSBCAPS dsbcaps;
+    dsbcaps.dwSize = sizeof( DSBCAPS );
+    result = buffer->GetCaps( &dsbcaps );
+    if ( FAILED( result ) ) {
+      output->Release();
+      buffer->Release();
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsinfo.name << ")!";
+      errorText_ = errorStream_.str();
+      return FAILURE;
+    }
 
-      // Try to create the secondary DS buffer.  If that doesn't work,
-      // try to use software mixing.  Otherwise, there's a problem.
-      result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
-      if ( FAILED( result ) ) {
-        bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
-                                      DSBCAPS_GLOBALFOCUS |
-                                      DSBCAPS_GETCURRENTPOSITION2 |
-                                      DSBCAPS_LOCSOFTWARE );  // Force software mixing
-        result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );
-        if ( FAILED( result ) ) {
-          output->Release();
-          errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsinfo.name << ")!";
-          errorText_ = errorStream_.str();
-          return FAILURE;
-        }
-      }
+    bufferBytes = dsbcaps.dwBufferBytes;
 
-      // Get the buffer size ... might be different from what we specified.
-      DSBCAPS dsbcaps;
-      dsbcaps.dwSize = sizeof( DSBCAPS );
-      result = buffer->GetCaps( &dsbcaps );
-      if ( FAILED( result ) ) {
-        output->Release();
-        buffer->Release();
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsinfo.name << ")!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
+    // Lock the DS buffer
+    LPVOID audioPtr;
+    DWORD dataLen;
+    result = buffer->Lock( 0, bufferBytes, &audioPtr, &dataLen, NULL, NULL, 0 );
+    if ( FAILED( result ) ) {
+      output->Release();
+      buffer->Release();
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsinfo.name << ")!";
+      errorText_ = errorStream_.str();
+      return FAILURE;
+    }
 
-      bufferBytes = dsbcaps.dwBufferBytes;
+    // Zero the DS buffer
+    ZeroMemory( audioPtr, dataLen );
 
-      // Lock the DS buffer
-      LPVOID audioPtr;
-      DWORD dataLen;
-      result = buffer->Lock( 0, bufferBytes, &audioPtr, &dataLen, NULL, NULL, 0 );
-      if ( FAILED( result ) ) {
-        output->Release();
-        buffer->Release();
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsinfo.name << ")!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
+    // Unlock the DS buffer
+    result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
+    if ( FAILED( result ) ) {
+      output->Release();
+      buffer->Release();
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsinfo.name << ")!";
+      errorText_ = errorStream_.str();
+      return FAILURE;
+    }
 
-      // Zero the DS buffer
-      ZeroMemory( audioPtr, dataLen );
+    dsBufferSize = bufferBytes;
+    ohandle = (void *) output;
+    bhandle = (void *) buffer;
+  }
 
-      // Unlock the DS buffer
-      result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
-      if ( FAILED( result ) ) {
-        output->Release();
-        buffer->Release();
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsinfo.name << ")!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
+  if ( mode == INPUT ) {
 
-      dsBufferSize = bufferBytes;
-      ohandle = (void *) output;
-      bhandle = (void *) buffer;
+    LPDIRECTSOUNDCAPTURE input;
+    result = DirectSoundCaptureCreate( dsinfo.id, &input, NULL );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsinfo.name << ")!";
+      errorText_ = errorStream_.str();
+      return FAILURE;
     }
 
-    if ( mode == INPUT ) {
-
-      LPDIRECTSOUNDCAPTURE input;
-      result = DirectSoundCaptureCreate( dsinfo.id, &input, NULL );
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsinfo.name << ")!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
+    DSCCAPS inCaps;
+    inCaps.dwSize = sizeof( inCaps );
+    result = input->GetCaps( &inCaps );
+    if ( FAILED( result ) ) {
+      input->Release();
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsinfo.name << ")!";
+      errorText_ = errorStream_.str();
+      return FAILURE;
+    }
 
-      DSCCAPS inCaps;
-      inCaps.dwSize = sizeof( inCaps );
-      result = input->GetCaps( &inCaps );
-      if ( FAILED( result ) ) {
-        input->Release();
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsinfo.name << ")!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
+    // Check channel information.
+    if ( inCaps.dwChannels < channels + firstChannel ) {
+      errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";
+      return FAILURE;
+    }
 
-      // Check channel information.
-      if ( inCaps.dwChannels < channels + firstChannel ) {
-        errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";
-        return FAILURE;
+    // Check format information.  Use 16-bit format unless user
+    // requests 8-bit.
+    DWORD deviceFormats;
+    if ( channels + firstChannel == 2 ) {
+      deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;
+      if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
+        waveFormat.wBitsPerSample = 8;
+        stream_.deviceFormat[mode] = RTAUDIO_SINT8;
       }
-
-      // Check format information.  Use 16-bit format unless user
-      // requests 8-bit.
-      DWORD deviceFormats;
-      if ( channels + firstChannel == 2 ) {
-        deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;
-        if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
-          waveFormat.wBitsPerSample = 8;
-          stream_.deviceFormat[mode] = RTAUDIO_SINT8;
-        }
-        else { // assume 16-bit is supported
-          waveFormat.wBitsPerSample = 16;
-          stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-        }
+      else { // assume 16-bit is supported
+        waveFormat.wBitsPerSample = 16;
+        stream_.deviceFormat[mode] = RTAUDIO_SINT16;
       }
-      else { // channel == 1
-        deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;
-        if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
-          waveFormat.wBitsPerSample = 8;
-          stream_.deviceFormat[mode] = RTAUDIO_SINT8;
-        }
-        else { // assume 16-bit is supported
-          waveFormat.wBitsPerSample = 16;
-          stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-        }
+    }
+    else { // channel == 1
+      deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;
+      if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {
+        waveFormat.wBitsPerSample = 8;
+        stream_.deviceFormat[mode] = RTAUDIO_SINT8;
       }
-      stream_.userFormat = format;
-
-      // Update wave format structure and buffer information.
-      waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
-      waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
-
-      // Setup the secondary DS buffer description.
-      dsBufferSize = bufferBytes;
-      DSCBUFFERDESC bufferDescription;
-      ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );
-      bufferDescription.dwSize = sizeof( DSCBUFFERDESC );
-      bufferDescription.dwFlags = 0;
-      bufferDescription.dwReserved = 0;
-      bufferDescription.dwBufferBytes = bufferBytes;
-      bufferDescription.lpwfxFormat = &waveFormat;
-
-      // Create the capture buffer.
-      LPDIRECTSOUNDCAPTUREBUFFER buffer;
-      result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );
-      if ( FAILED( result ) ) {
-        input->Release();
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsinfo.name << ")!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
+      else { // assume 16-bit is supported
+        waveFormat.wBitsPerSample = 16;
+        stream_.deviceFormat[mode] = RTAUDIO_SINT16;
       }
+    }
+    stream_.userFormat = format;
 
-      // Lock the capture buffer
-      LPVOID audioPtr;
-      DWORD dataLen;
-      result = buffer->Lock( 0, bufferBytes, &audioPtr, &dataLen, NULL, NULL, 0 );
-      if ( FAILED( result ) ) {
-        input->Release();
-        buffer->Release();
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsinfo.name << ")!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
+    // Update wave format structure and buffer information.
+    waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
+    waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
+
+    // Setup the secondary DS buffer description.
+    dsBufferSize = bufferBytes;
+    DSCBUFFERDESC bufferDescription;
+    ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );
+    bufferDescription.dwSize = sizeof( DSCBUFFERDESC );
+    bufferDescription.dwFlags = 0;
+    bufferDescription.dwReserved = 0;
+    bufferDescription.dwBufferBytes = bufferBytes;
+    bufferDescription.lpwfxFormat = &waveFormat;
+
+    // Create the capture buffer.
+    LPDIRECTSOUNDCAPTUREBUFFER buffer;
+    result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );
+    if ( FAILED( result ) ) {
+      input->Release();
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsinfo.name << ")!";
+      errorText_ = errorStream_.str();
+      return FAILURE;
+    }
 
-      // Zero the buffer
-      ZeroMemory( audioPtr, dataLen );
+    // Lock the capture buffer
+    LPVOID audioPtr;
+    DWORD dataLen;
+    result = buffer->Lock( 0, bufferBytes, &audioPtr, &dataLen, NULL, NULL, 0 );
+    if ( FAILED( result ) ) {
+      input->Release();
+      buffer->Release();
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsinfo.name << ")!";
+      errorText_ = errorStream_.str();
+      return FAILURE;
+    }
 
-      // Unlock the buffer
-      result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
-      if ( FAILED( result ) ) {
-        input->Release();
-        buffer->Release();
-        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsinfo.name << ")!";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
+    // Zero the buffer
+    ZeroMemory( audioPtr, dataLen );
 
-      dsBufferSize = bufferBytes;
-      ohandle = (void *) input;
-      bhandle = (void *) buffer;
+    // Unlock the buffer
+    result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
+    if ( FAILED( result ) ) {
+      input->Release();
+      buffer->Release();
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsinfo.name << ")!";
+      errorText_ = errorStream_.str();
+      return FAILURE;
     }
 
-    // Set various stream parameters
-    DsHandle *handle = 0;
-    stream_.nDeviceChannels[mode] = channels + firstChannel;
-    stream_.nUserChannels[mode] = channels;
-    stream_.bufferSize = *bufferSize;
-    stream_.channelOffset[mode] = firstChannel;
-    stream_.deviceInterleaved[mode] = true;
-    if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
-    else stream_.userInterleaved = true;
+    dsBufferSize = bufferBytes;
+    ohandle = (void *) input;
+    bhandle = (void *) buffer;
+  }
 
-    // Set flag for buffer conversion
-    stream_.doConvertBuffer[mode] = false;
-    if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])
-      stream_.doConvertBuffer[mode] = true;
-    if (stream_.userFormat != stream_.deviceFormat[mode])
-      stream_.doConvertBuffer[mode] = true;
-    if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
-         stream_.nUserChannels[mode] > 1 )
-      stream_.doConvertBuffer[mode] = true;
+  // Set various stream parameters
+  DsHandle *handle = 0;
+  stream_.nDeviceChannels[mode] = channels + firstChannel;
+  stream_.nUserChannels[mode] = channels;
+  stream_.bufferSize = *bufferSize;
+  stream_.channelOffset[mode] = firstChannel;
+  stream_.deviceInterleaved[mode] = true;
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;
+  else stream_.userInterleaved = true;
 
-    // Allocate necessary internal buffers
-    bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
-    stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
-    if ( stream_.userBuffer[mode] == NULL ) {
-      errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";
-      goto error;
-    }
+  // Set flag for buffer conversion
+  stream_.doConvertBuffer[mode] = false;
+  if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])
+    stream_.doConvertBuffer[mode] = true;
+  if (stream_.userFormat != stream_.deviceFormat[mode])
+    stream_.doConvertBuffer[mode] = true;
+  if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
+       stream_.nUserChannels[mode] > 1 )
+    stream_.doConvertBuffer[mode] = true;
 
-    if ( stream_.doConvertBuffer[mode] ) {
+  // Allocate necessary internal buffers
+  bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
+  stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
+  if ( stream_.userBuffer[mode] == NULL ) {
+    errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";
+    goto error;
+  }
 
-      bool makeBuffer = true;
-      bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
-      if ( mode == INPUT ) {
-        if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
-          unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
-          if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;
-        }
-      }
+  if ( stream_.doConvertBuffer[mode] ) {
 
-      if ( makeBuffer ) {
-        bufferBytes *= *bufferSize;
-        if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
-        stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
-        if ( stream_.deviceBuffer == NULL ) {
-          errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";
-          goto error;
-        }
+    bool makeBuffer = true;
+    bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
+    if ( mode == INPUT ) {
+      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
+        unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
+        if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;
       }
     }
 
-    // Allocate our DsHandle structures for the stream.
-    if ( stream_.apiHandle == 0 ) {
-      try {
-        handle = new DsHandle;
-      }
-      catch ( std::bad_alloc& ) {
-        errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";
+    if ( makeBuffer ) {
+      bufferBytes *= *bufferSize;
+      if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
+      stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
+      if ( stream_.deviceBuffer == NULL ) {
+        errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";
         goto error;
       }
+    }
+  }
 
-      // Create a manual-reset event.
-      handle->condition = CreateEvent( NULL,   // no security
-                                       TRUE,   // manual-reset
-                                       FALSE,  // non-signaled initially
-                                       NULL ); // unnamed
-      stream_.apiHandle = (void *) handle;
+  // Allocate our DsHandle structures for the stream.
+  if ( stream_.apiHandle == 0 ) {
+    try {
+      handle = new DsHandle;
+    }
+    catch ( std::bad_alloc& ) {
+      errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";
+      goto error;
     }
-    else
-      handle = (DsHandle *) stream_.apiHandle;
-    handle->id[mode] = ohandle;
-    handle->buffer[mode] = bhandle;
-    handle->dsBufferSize[mode] = dsBufferSize;
-    handle->dsPointerLeadTime[mode] = dsPointerLeadTime;
 
-    stream_.device[mode] = device;
-    stream_.state = STREAM_STOPPED;
-    if ( stream_.mode == OUTPUT && mode == INPUT )
-      // We had already set up an output stream.
-      stream_.mode = DUPLEX;
-    else
-      stream_.mode = mode;
-    stream_.nBuffers = nBuffers;
-    stream_.sampleRate = sampleRate;
+    // Create a manual-reset event.
+    handle->condition = CreateEvent( NULL,   // no security
+                                     TRUE,   // manual-reset
+                                     FALSE,  // non-signaled initially
+                                     NULL ); // unnamed
+    stream_.apiHandle = (void *) handle;
+  }
+  else
+    handle = (DsHandle *) stream_.apiHandle;
+  handle->id[mode] = ohandle;
+  handle->buffer[mode] = bhandle;
+  handle->dsBufferSize[mode] = dsBufferSize;
+  handle->dsPointerLeadTime[mode] = dsPointerLeadTime;
+
+  stream_.device[mode] = device;
+  stream_.state = STREAM_STOPPED;
+  if ( stream_.mode == OUTPUT && mode == INPUT )
+    // We had already set up an output stream.
+    stream_.mode = DUPLEX;
+  else
+    stream_.mode = mode;
+  stream_.nBuffers = nBuffers;
+  stream_.sampleRate = sampleRate;
 
-    // Setup the buffer conversion information structure.
-    if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
+  // Setup the buffer conversion information structure.
+  if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
 
-    // Setup the callback thread.
-    unsigned threadId;
-    stream_.callbackInfo.object = (void *) this;
-    stream_.callbackInfo.isRunning = true;
-    stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,
-                                                  &stream_.callbackInfo, 0, &threadId );
-    if ( stream_.callbackInfo.thread == 0 ) {
-      errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";
-      goto error;
-    }
+  // Setup the callback thread.
+  unsigned threadId;
+  stream_.callbackInfo.object = (void *) this;
+  stream_.callbackInfo.isRunning = true;
+  stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,
+                                                &stream_.callbackInfo, 0, &threadId );
+  if ( stream_.callbackInfo.thread == 0 ) {
+    errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";
+    goto error;
+  }
 
-    // Boost DS thread priority
-    SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );
-    return SUCCESS;
+  // Boost DS thread priority
+  SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );
+  return SUCCESS;
 
-  error:
-    if ( handle ) {
-      if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
-        LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
-        LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
-        if ( buffer ) buffer->Release();
-        object->Release();
-      }
-      if ( handle->buffer[1] ) {
-        LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
-        LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
-        if ( buffer ) buffer->Release();
-        object->Release();
-      }
-      CloseHandle( handle->condition );
-      delete handle;
-      stream_.apiHandle = 0;
+ error:
+  if ( handle ) {
+    if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
+      LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
+      LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
+      if ( buffer ) buffer->Release();
+      object->Release();
     }
-
-    for ( int i=0; i<2; i++ ) {
-      if ( stream_.userBuffer[i] ) {
-        free( stream_.userBuffer[i] );
-        stream_.userBuffer[i] = 0;
-      }
+    if ( handle->buffer[1] ) {
+      LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
+      LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
+      if ( buffer ) buffer->Release();
+      object->Release();
     }
+    CloseHandle( handle->condition );
+    delete handle;
+    stream_.apiHandle = 0;
+  }
 
-    if ( stream_.deviceBuffer ) {
-      free( stream_.deviceBuffer );
-      stream_.deviceBuffer = 0;
+  for ( int i=0; i<2; i++ ) {
+    if ( stream_.userBuffer[i] ) {
+      free( stream_.userBuffer[i] );
+      stream_.userBuffer[i] = 0;
     }
+  }
 
-    return FAILURE;
+  if ( stream_.deviceBuffer ) {
+    free( stream_.deviceBuffer );
+    stream_.deviceBuffer = 0;
   }
 
-  void RtApiDs :: closeStream()
-  {
-    if ( stream_.state == STREAM_CLOSED ) {
-      errorText_ = "RtApiDs::closeStream(): no open stream to close!";
-      error( RtError::WARNING );
-      return;
-    }
+  return FAILURE;
+}
 
-    // Stop the callback thread.
-    stream_.callbackInfo.isRunning = false;
-    WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );
-    CloseHandle( (HANDLE) stream_.callbackInfo.thread );
+void RtApiDs :: closeStream()
+{
+  if ( stream_.state == STREAM_CLOSED ) {
+    errorText_ = "RtApiDs::closeStream(): no open stream to close!";
+    error( RtError::WARNING );
+    return;
+  }
 
-    DsHandle *handle = (DsHandle *) stream_.apiHandle;
-    if ( handle ) {
-      if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
-        LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
-        LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
-        if ( buffer ) {
-          buffer->Stop();
-          buffer->Release();
-        }
-        object->Release();
-      }
-      if ( handle->buffer[1] ) {
-        LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
-        LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
-        if ( buffer ) {
-          buffer->Stop();
-          buffer->Release();
-        }
-        object->Release();
+  // Stop the callback thread.
+  stream_.callbackInfo.isRunning = false;
+  WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );
+  CloseHandle( (HANDLE) stream_.callbackInfo.thread );
+
+  DsHandle *handle = (DsHandle *) stream_.apiHandle;
+  if ( handle ) {
+    if ( handle->buffer[0] ) { // the object pointer can be NULL and valid
+      LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];
+      LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
+      if ( buffer ) {
+        buffer->Stop();
+        buffer->Release();
       }
-      CloseHandle( handle->condition );
-      delete handle;
-      stream_.apiHandle = 0;
+      object->Release();
     }
-
-    for ( int i=0; i<2; i++ ) {
-      if ( stream_.userBuffer[i] ) {
-        free( stream_.userBuffer[i] );
-        stream_.userBuffer[i] = 0;
+    if ( handle->buffer[1] ) {
+      LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];
+      LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
+      if ( buffer ) {
+        buffer->Stop();
+        buffer->Release();
       }
+      object->Release();
     }
+    CloseHandle( handle->condition );
+    delete handle;
+    stream_.apiHandle = 0;
+  }
 
-    if ( stream_.deviceBuffer ) {
-      free( stream_.deviceBuffer );
-      stream_.deviceBuffer = 0;
+  for ( int i=0; i<2; i++ ) {
+    if ( stream_.userBuffer[i] ) {
+      free( stream_.userBuffer[i] );
+      stream_.userBuffer[i] = 0;
     }
+  }
 
-    stream_.mode = UNINITIALIZED;
-    stream_.state = STREAM_CLOSED;
+  if ( stream_.deviceBuffer ) {
+    free( stream_.deviceBuffer );
+    stream_.deviceBuffer = 0;
   }
 
-  void RtApiDs :: startStream()
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_RUNNING ) {
-      errorText_ = "RtApiDs::startStream(): the stream is already running!";
-      error( RtError::WARNING );
-      return;
-    }
+  stream_.mode = UNINITIALIZED;
+  stream_.state = STREAM_CLOSED;
+}
+
+void RtApiDs :: startStream()
+{
+  verifyStream();
+  if ( stream_.state == STREAM_RUNNING ) {
+    errorText_ = "RtApiDs::startStream(): the stream is already running!";
+    error( RtError::WARNING );
+    return;
+  }
 
-    // Increase scheduler frequency on lesser windows (a side-effect of
-    // increasing timer accuracy).  On greater windows (Win2K or later),
-    // this is already in effect.
+  // Increase scheduler frequency on lesser windows (a side-effect of
+  // increasing timer accuracy).  On greater windows (Win2K or later),
+  // this is already in effect.
 
-    MUTEX_LOCK( &stream_.mutex );
+  MUTEX_LOCK( &stream_.mutex );
   
-    DsHandle *handle = (DsHandle *) stream_.apiHandle;
+  DsHandle *handle = (DsHandle *) stream_.apiHandle;
 
-    timeBeginPeriod( 1 ); 
+  timeBeginPeriod( 1 ); 
 
-    /*
-      memset( &statistics, 0, sizeof( statistics ) );
-      statistics.sampleRate = stream_.sampleRate;
-      statistics.writeDeviceBufferLeadBytes = handle->dsPointerLeadTime[0];
-    */
+  /*
+    memset( &statistics, 0, sizeof( statistics ) );
+    statistics.sampleRate = stream_.sampleRate;
+    statistics.writeDeviceBufferLeadBytes = handle->dsPointerLeadTime[0];
+  */
 
-    buffersRolling = false;
-    duplexPrerollBytes = 0;
+  buffersRolling = false;
+  duplexPrerollBytes = 0;
 
-    if ( stream_.mode == DUPLEX ) {
-      // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.
-      duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );
-    }
+  if ( stream_.mode == DUPLEX ) {
+    // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.
+    duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );
+  }
 
-    HRESULT result = 0;
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
-      //statistics.outputFrameSize = formatBytes( stream_.deviceFormat[0] ) * stream_.nDeviceChannels[0];
+  HRESULT result = 0;
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+    //statistics.outputFrameSize = formatBytes( stream_.deviceFormat[0] ) * stream_.nDeviceChannels[0];
 
-      LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
-      result = buffer->Play( 0, 0, DSBPLAY_LOOPING );
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";
-        errorText_ = errorStream_.str();
-        goto unlock;
-      }
+    LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
+    result = buffer->Play( 0, 0, DSBPLAY_LOOPING );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";
+      errorText_ = errorStream_.str();
+      goto unlock;
     }
+  }
 
-    if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
-      //statistics.inputFrameSize = formatBytes( stream_.deviceFormat[1]) * stream_.nDeviceChannels[1];
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
+    //statistics.inputFrameSize = formatBytes( stream_.deviceFormat[1]) * stream_.nDeviceChannels[1];
 
-      LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
-      result = buffer->Start( DSCBSTART_LOOPING );
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";
-        errorText_ = errorStream_.str();
-        goto unlock;
-      }
+    LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
+    result = buffer->Start( DSCBSTART_LOOPING );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";
+      errorText_ = errorStream_.str();
+      goto unlock;
     }
+  }
+
+  handle->drainCounter = 0;
+  handle->internalDrain = false;
+  stream_.state = STREAM_RUNNING;
+
+ unlock:
+  MUTEX_UNLOCK( &stream_.mutex );
+
+  if ( FAILED( result ) ) error( RtError::SYSTEM_ERROR );
+}
+
+void RtApiDs :: stopStream()
+{
+  verifyStream();
+  if ( stream_.state == STREAM_STOPPED ) {
+    errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";
+    error( RtError::WARNING );
+    return;
+  }
 
-    handle->drainCounter = 0;
-    handle->internalDrain = false;
-    stream_.state = STREAM_RUNNING;
+  MUTEX_LOCK( &stream_.mutex );
 
-  unlock:
+  if ( stream_.state == STREAM_STOPPED ) {
     MUTEX_UNLOCK( &stream_.mutex );
-
-    if ( FAILED( result ) ) error( RtError::SYSTEM_ERROR );
+    return;
   }
 
-  void RtApiDs :: stopStream()
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_STOPPED ) {
-      errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";
-      error( RtError::WARNING );
-      return;
+  HRESULT result = 0;
+  LPVOID audioPtr;
+  DWORD dataLen;
+  DsHandle *handle = (DsHandle *) stream_.apiHandle;
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+    if ( handle->drainCounter == 0 ) {
+      handle->drainCounter = 1;
+      MUTEX_UNLOCK( &stream_.mutex );
+      WaitForMultipleObjects( 1, &handle->condition, FALSE, INFINITE );  // block until signaled
+      ResetEvent( handle->condition );
+      MUTEX_LOCK( &stream_.mutex );
     }
 
-    MUTEX_LOCK( &stream_.mutex );
+    // Stop the buffer and clear memory
+    LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
+    result = buffer->Stop();
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") stopping output buffer!";
+      errorText_ = errorStream_.str();
+      goto unlock;
+    }
 
-    HRESULT result = 0;
-    LPVOID audioPtr;
-    DWORD dataLen;
-    DsHandle *handle = (DsHandle *) stream_.apiHandle;
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
-      if ( handle->drainCounter == 0 ) {
-        handle->drainCounter = 1;
-        MUTEX_UNLOCK( &stream_.mutex );
-        WaitForMultipleObjects( 1, &handle->condition, FALSE, INFINITE );  // block until signaled
-        ResetEvent( handle->condition );
-        MUTEX_LOCK( &stream_.mutex );
-      }
+    // Lock the buffer and clear it so that if we start to play again,
+    // we won't have old data playing.
+    result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") locking output buffer!";
+      errorText_ = errorStream_.str();
+      goto unlock;
+    }
 
-      // Stop the buffer and clear memory
-      LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
-      result = buffer->Stop();
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") stopping output buffer!";
-        errorText_ = errorStream_.str();
-        goto unlock;
-      }
+    // Zero the DS buffer
+    ZeroMemory( audioPtr, dataLen );
 
-      // Lock the buffer and clear it so that if we start to play again,
-      // we won't have old data playing.
-      result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") locking output buffer!";
-        errorText_ = errorStream_.str();
-        goto unlock;
-      }
+    // Unlock the DS buffer
+    result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") unlocking output buffer!";
+      errorText_ = errorStream_.str();
+      goto unlock;
+    }
 
-      // Zero the DS buffer
-      ZeroMemory( audioPtr, dataLen );
+    // If we start playing again, we must begin at beginning of buffer.
+    handle->bufferPointer[0] = 0;
+  }
 
-      // Unlock the DS buffer
-      result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") unlocking output buffer!";
-        errorText_ = errorStream_.str();
-        goto unlock;
-      }
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
+    LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
+    audioPtr = NULL;
+    dataLen = 0;
 
-      // If we start playing again, we must begin at beginning of buffer.
-      handle->bufferPointer[0] = 0;
+    result = buffer->Stop();
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") stopping input buffer!";
+      errorText_ = errorStream_.str();
+      goto unlock;
     }
 
-    if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
-      LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
-      audioPtr = NULL;
-      dataLen = 0;
+    // Lock the buffer and clear it so that if we start to play again,
+    // we won't have old data playing.
+    result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") locking input buffer!";
+      errorText_ = errorStream_.str();
+      goto unlock;
+    }
 
-      result = buffer->Stop();
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") stopping input buffer!";
-        errorText_ = errorStream_.str();
-        goto unlock;
-      }
+    // Zero the DS buffer
+    ZeroMemory( audioPtr, dataLen );
 
-      // Lock the buffer and clear it so that if we start to play again,
-      // we won't have old data playing.
-      result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") locking input buffer!";
-        errorText_ = errorStream_.str();
-        goto unlock;
-      }
+    // Unlock the DS buffer
+    result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") unlocking input buffer!";
+      errorText_ = errorStream_.str();
+      goto unlock;
+    }
 
-      // Zero the DS buffer
-      ZeroMemory( audioPtr, dataLen );
+    // If we start recording again, we must begin at beginning of buffer.
+    handle->bufferPointer[1] = 0;
+  }
 
-      // Unlock the DS buffer
-      result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::abortStream: error (" << getErrorString( result ) << ") unlocking input buffer!";
-        errorText_ = errorStream_.str();
-        goto unlock;
-      }
+ unlock:
+  timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.
+  stream_.state = STREAM_STOPPED;
+  MUTEX_UNLOCK( &stream_.mutex );
 
-      // If we start recording again, we must begin at beginning of buffer.
-      handle->bufferPointer[1] = 0;
-    }
+  if ( FAILED( result ) ) error( RtError::SYSTEM_ERROR );
+}
 
-  unlock:
-    timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.
-    stream_.state = STREAM_STOPPED;
-    MUTEX_UNLOCK( &stream_.mutex );
-    if ( FAILED( result ) ) error( RtError::SYSTEM_ERROR );
+void RtApiDs :: abortStream()
+{
+  verifyStream();
+  if ( stream_.state == STREAM_STOPPED ) {
+    errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";
+    error( RtError::WARNING );
+    return;
   }
 
-  void RtApiDs :: abortStream()
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_STOPPED ) {
-      errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";
-      error( RtError::WARNING );
-      return;
-    }
+  DsHandle *handle = (DsHandle *) stream_.apiHandle;
+  handle->drainCounter = 1;
 
-    DsHandle *handle = (DsHandle *) stream_.apiHandle;
-    handle->drainCounter = 1;
+  stopStream();
+}
 
-    stopStream();
+void RtApiDs :: callbackEvent()
+{
+  if ( stream_.state == STREAM_STOPPED ) {
+    Sleep(50); // sleep 50 milliseconds
+    return;
   }
 
-  void RtApiDs :: callbackEvent()
-  {
-    if ( stream_.state == STREAM_STOPPED ) {
-      Sleep(50); // sleep 50 milliseconds
-      return;
-    }
+  if ( stream_.state == STREAM_CLOSED ) {
+    errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";
+    error( RtError::WARNING );
+    return;
+  }
 
-    if ( stream_.state == STREAM_CLOSED ) {
-      errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";
-      error( RtError::WARNING );
-      return;
-    }
+  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
+  DsHandle *handle = (DsHandle *) stream_.apiHandle;
 
-    CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
-    DsHandle *handle = (DsHandle *) stream_.apiHandle;
+  // Check if we were draining the stream and signal is finished.
+  if ( handle->drainCounter > stream_.nBuffers + 2 ) {
+    if ( handle->internalDrain == false )
+      SetEvent( handle->condition );
+    else
+      stopStream();
+    return;
+  }
 
-    // Check if we were draining the stream and signal is finished.
-    if ( handle->drainCounter > stream_.nBuffers + 2 ) {
-      if ( handle->internalDrain == false )
-        SetEvent( handle->condition );
-      else
-        stopStream();
-      return;
-    }
+  MUTEX_LOCK( &stream_.mutex );
 
-    MUTEX_LOCK( &stream_.mutex );
+  // The state might change while waiting on a mutex.
+  if ( stream_.state == STREAM_STOPPED ) {
+    MUTEX_UNLOCK( &stream_.mutex );
+    return SUCCESS;
+  }
 
-    // Invoke user callback to get fresh output data UNLESS we are
-    // draining stream.
-    if ( handle->drainCounter == 0 ) {
-      RtAudioCallback callback = (RtAudioCallback) info->callback;
-      double streamTime = getStreamTime();
-      RtAudioStreamStatus status = 0;
-      if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
-        status |= RTAUDIO_OUTPUT_UNDERFLOW;
-        handle->xrun[0] = false;
-      }
-      if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
-        status |= RTAUDIO_INPUT_OVERFLOW;
-        handle->xrun[1] = false;
-      }
-      handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],
-                                       stream_.bufferSize, streamTime, status, info->userData );
-      if ( handle->drainCounter == 2 ) {
-        MUTEX_UNLOCK( &stream_.mutex );
-        abortStream();
-        return;
-      }
-      else if ( handle->drainCounter == 1 )
-        handle->internalDrain = true;
+  // Invoke user callback to get fresh output data UNLESS we are
+  // draining stream.
+  if ( handle->drainCounter == 0 ) {
+    RtAudioCallback callback = (RtAudioCallback) info->callback;
+    double streamTime = getStreamTime();
+    RtAudioStreamStatus status = 0;
+    if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
+      status |= RTAUDIO_OUTPUT_UNDERFLOW;
+      handle->xrun[0] = false;
+    }
+    if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
+      status |= RTAUDIO_INPUT_OVERFLOW;
+      handle->xrun[1] = false;
+    }
+    handle->drainCounter = callback( stream_.userBuffer[0], stream_.userBuffer[1],
+                                     stream_.bufferSize, streamTime, status, info->userData );
+    if ( handle->drainCounter == 2 ) {
+      MUTEX_UNLOCK( &stream_.mutex );
+      abortStream();
+      return;
     }
+    else if ( handle->drainCounter == 1 )
+      handle->internalDrain = true;
+  }
 
-    HRESULT result;
-    DWORD currentWritePos, safeWritePos;
-    DWORD currentReadPos, safeReadPos;
-    DWORD leadPos;
-    UINT nextWritePos;
+  HRESULT result;
+  DWORD currentWritePos, safeWritePos;
+  DWORD currentReadPos, safeReadPos;
+  DWORD leadPos;
+  UINT nextWritePos;
 
 #ifdef GENERATE_DEBUG_LOG
-    DWORD writeTime, readTime;
+  DWORD writeTime, readTime;
 #endif
 
-    LPVOID buffer1 = NULL;
-    LPVOID buffer2 = NULL;
-    DWORD bufferSize1 = 0;
-    DWORD bufferSize2 = 0;
+  LPVOID buffer1 = NULL;
+  LPVOID buffer2 = NULL;
+  DWORD bufferSize1 = 0;
+  DWORD bufferSize2 = 0;
 
-    char *buffer;
-    long bufferBytes;
+  char *buffer;
+  long bufferBytes;
 
-    if ( stream_.mode == DUPLEX && !buffersRolling ) {
-      assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
+  if ( stream_.mode == DUPLEX && !buffersRolling ) {
+    assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
 
-      // It takes a while for the devices to get rolling. As a result,
-      // there's no guarantee that the capture and write device pointers
-      // will move in lockstep.  Wait here for both devices to start
-      // rolling, and then set our buffer pointers accordingly.
-      // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600
-      // bytes later than the write buffer.
+    // It takes a while for the devices to get rolling. As a result,
+    // there's no guarantee that the capture and write device pointers
+    // will move in lockstep.  Wait here for both devices to start
+    // rolling, and then set our buffer pointers accordingly.
+    // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600
+    // bytes later than the write buffer.
 
-      // Stub: a serious risk of having a pre-emptive scheduling round
-      // take place between the two GetCurrentPosition calls... but I'm
-      // really not sure how to solve the problem.  Temporarily boost to
-      // Realtime priority, maybe; but I'm not sure what priority the
-      // DirectSound service threads run at. We *should* be roughly
-      // within a ms or so of correct.
+    // Stub: a serious risk of having a pre-emptive scheduling round
+    // take place between the two GetCurrentPosition calls... but I'm
+    // really not sure how to solve the problem.  Temporarily boost to
+    // Realtime priority, maybe; but I'm not sure what priority the
+    // DirectSound service threads run at. We *should* be roughly
+    // within a ms or so of correct.
 
-      LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
-      LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
+    LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
+    LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
 
-      DWORD initialWritePos, initialSafeWritePos;
-      DWORD initialReadPos, initialSafeReadPos;
+    DWORD initialWritePos, initialSafeWritePos;
+    DWORD initialReadPos, initialSafeReadPos;
 
-      result = dsWriteBuffer->GetCurrentPosition( &initialWritePos, &initialSafeWritePos );
+    result = dsWriteBuffer->GetCurrentPosition( &initialWritePos, &initialSafeWritePos );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
+      errorText_ = errorStream_.str();
+      error( RtError::SYSTEM_ERROR );
+    }
+    result = dsCaptureBuffer->GetCurrentPosition( &initialReadPos, &initialSafeReadPos );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
+      errorText_ = errorStream_.str();
+      error( RtError::SYSTEM_ERROR );
+    }
+    while ( true ) {
+      result = dsWriteBuffer->GetCurrentPosition( &currentWritePos, &safeWritePos );
       if ( FAILED( result ) ) {
         errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
         errorText_ = errorStream_.str();
         error( RtError::SYSTEM_ERROR );
       }
-      result = dsCaptureBuffer->GetCurrentPosition( &initialReadPos, &initialSafeReadPos );
+      result = dsCaptureBuffer->GetCurrentPosition( &currentReadPos, &safeReadPos );
       if ( FAILED( result ) ) {
         errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
         errorText_ = errorStream_.str();
         error( RtError::SYSTEM_ERROR );
       }
-      while ( true ) {
-        result = dsWriteBuffer->GetCurrentPosition( &currentWritePos, &safeWritePos );
-        if ( FAILED( result ) ) {
-          errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
-          errorText_ = errorStream_.str();
-          error( RtError::SYSTEM_ERROR );
-        }
-        result = dsCaptureBuffer->GetCurrentPosition( &currentReadPos, &safeReadPos );
-        if ( FAILED( result ) ) {
-          errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
-          errorText_ = errorStream_.str();
-          error( RtError::SYSTEM_ERROR );
-        }
-        if ( safeWritePos != initialSafeWritePos && safeReadPos != initialSafeReadPos ) break;
-        Sleep( 1 );
-      }
-
-      assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
-
-      buffersRolling = true;
-      handle->bufferPointer[0] = ( safeWritePos + handle->dsPointerLeadTime[0] );
-      handle->bufferPointer[1] = safeReadPos;
+      if ( safeWritePos != initialSafeWritePos && safeReadPos != initialSafeReadPos ) break;
+      Sleep( 1 );
     }
 
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
-    
-      LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
-
-      if ( handle->drainCounter > 1 ) { // write zeros to the output stream
-        bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
-        bufferBytes *= formatBytes( stream_.userFormat );
-        memset( stream_.userBuffer[0], 0, bufferBytes );
-      }
+    assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );
 
-      // Setup parameters and do buffer conversion if necessary.
-      if ( stream_.doConvertBuffer[0] ) {
-        buffer = stream_.deviceBuffer;
-        convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
-        bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];
-        bufferBytes *= formatBytes( stream_.deviceFormat[0] );
-      }
-      else {
-        buffer = stream_.userBuffer[0];
-        bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
-        bufferBytes *= formatBytes( stream_.userFormat );
-      }
+    buffersRolling = true;
+    handle->bufferPointer[0] = ( safeWritePos + handle->dsPointerLeadTime[0] );
+    handle->bufferPointer[1] = safeReadPos;
+  }
 
-      // No byte swapping necessary in DirectSound implementation.
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+    
+    LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];
 
-      // Ahhh ... windoze.  16-bit data is signed but 8-bit data is
-      // unsigned.  So, we need to convert our signed 8-bit data here to
-      // unsigned.
-      if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )
-        for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );
+    if ( handle->drainCounter > 1 ) { // write zeros to the output stream
+      bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
+      bufferBytes *= formatBytes( stream_.userFormat );
+      memset( stream_.userBuffer[0], 0, bufferBytes );
+    }
 
-      DWORD dsBufferSize = handle->dsBufferSize[0];
-      nextWritePos = handle->bufferPointer[0];
+    // Setup parameters and do buffer conversion if necessary.
+    if ( stream_.doConvertBuffer[0] ) {
+      buffer = stream_.deviceBuffer;
+      convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
+      bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];
+      bufferBytes *= formatBytes( stream_.deviceFormat[0] );
+    }
+    else {
+      buffer = stream_.userBuffer[0];
+      bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];
+      bufferBytes *= formatBytes( stream_.userFormat );
+    }
 
-      DWORD endWrite;
-      while ( true ) {
-        // Find out where the read and "safe write" pointers are.
-        result = dsBuffer->GetCurrentPosition( &currentWritePos, &safeWritePos );
-        if ( FAILED( result ) ) {
-          errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
-          errorText_ = errorStream_.str();
-          error( RtError::SYSTEM_ERROR );
-        }
+    // No byte swapping necessary in DirectSound implementation.
 
-        leadPos = safeWritePos + handle->dsPointerLeadTime[0];
-        if ( leadPos > dsBufferSize ) leadPos -= dsBufferSize;
-        if ( leadPos < nextWritePos ) leadPos += dsBufferSize; // unwrap offset
-        endWrite = nextWritePos + bufferBytes;
-
-        // Check whether the entire write region is behind the play pointer.
-        if ( leadPos >= endWrite ) break;
-
-        // If we are here, then we must wait until the play pointer gets
-        // beyond the write region.  The approach here is to use the
-        // Sleep() function to suspend operation until safePos catches
-        // up. Calculate number of milliseconds to wait as:
-        //   time = distance * (milliseconds/second) * fudgefactor /
-        //          ((bytes/sample) * (samples/second))
-        // A "fudgefactor" less than 1 is used because it was found
-        // that sleeping too long was MUCH worse than sleeping for
-        // several shorter periods.
-        double millis = ( endWrite - leadPos ) * 900.0;
-        millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);
-        if ( millis < 1.0 ) millis = 1.0;
-        if ( millis > 50.0 ) {
-          static int nOverruns = 0;
-          ++nOverruns;
-        }
-        Sleep( (DWORD) millis );
-      }
+    // Ahhh ... windoze.  16-bit data is signed but 8-bit data is
+    // unsigned.  So, we need to convert our signed 8-bit data here to
+    // unsigned.
+    if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )
+      for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );
 
-      //if ( statistics.writeDeviceSafeLeadBytes < dsPointerDifference( safeWritePos, currentWritePos, handle->dsBufferSize[0] ) ) {
-      //  statistics.writeDeviceSafeLeadBytes = dsPointerDifference( safeWritePos, currentWritePos, handle->dsBufferSize[0] );
-      //}
-
-      if ( dsPointerBetween( nextWritePos, safeWritePos, currentWritePos, dsBufferSize )
-           || dsPointerBetween( endWrite, safeWritePos, currentWritePos, dsBufferSize ) ) { 
-        // We've strayed into the forbidden zone ... resync the read pointer.
-        //++statistics.numberOfWriteUnderruns;
-        handle->xrun[0] = true;
-        nextWritePos = safeWritePos + handle->dsPointerLeadTime[0] - bufferBytes + dsBufferSize;
-        while ( nextWritePos >= dsBufferSize ) nextWritePos -= dsBufferSize;
-        handle->bufferPointer[0] = nextWritePos;
-        endWrite = nextWritePos + bufferBytes;
-      }
+    DWORD dsBufferSize = handle->dsBufferSize[0];
+    nextWritePos = handle->bufferPointer[0];
 
-      // Lock free space in the buffer
-      result = dsBuffer->Lock( nextWritePos, bufferBytes, &buffer1,
-                               &bufferSize1, &buffer2, &bufferSize2, 0 );
+    DWORD endWrite;
+    while ( true ) {
+      // Find out where the read and "safe write" pointers are.
+      result = dsBuffer->GetCurrentPosition( &currentWritePos, &safeWritePos );
       if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";
+        errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";
         errorText_ = errorStream_.str();
         error( RtError::SYSTEM_ERROR );
       }
 
-      // Copy our buffer into the DS buffer
-      CopyMemory( buffer1, buffer, bufferSize1 );
-      if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );
-
-      // Update our buffer offset and unlock sound buffer
-      dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";
-        errorText_ = errorStream_.str();
-        error( RtError::SYSTEM_ERROR );
-      }
-      nextWritePos = ( nextWritePos + bufferSize1 + bufferSize2 ) % dsBufferSize;
+      leadPos = safeWritePos + handle->dsPointerLeadTime[0];
+      if ( leadPos > dsBufferSize ) leadPos -= dsBufferSize;
+      if ( leadPos < nextWritePos ) leadPos += dsBufferSize; // unwrap offset
+      endWrite = nextWritePos + bufferBytes;
+
+      // Check whether the entire write region is behind the play pointer.
+      if ( leadPos >= endWrite ) break;
+
+      // If we are here, then we must wait until the play pointer gets
+      // beyond the write region.  The approach here is to use the
+      // Sleep() function to suspend operation until safePos catches
+      // up. Calculate number of milliseconds to wait as:
+      //   time = distance * (milliseconds/second) * fudgefactor /
+      //          ((bytes/sample) * (samples/second))
+      // A "fudgefactor" less than 1 is used because it was found
+      // that sleeping too long was MUCH worse than sleeping for
+      // several shorter periods.
+      double millis = ( endWrite - leadPos ) * 900.0;
+      millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);
+      if ( millis < 1.0 ) millis = 1.0;
+      if ( millis > 50.0 ) {
+        static int nOverruns = 0;
+        ++nOverruns;
+      }
+      Sleep( (DWORD) millis );
+    }
+
+    //if ( statistics.writeDeviceSafeLeadBytes < dsPointerDifference( safeWritePos, currentWritePos, handle->dsBufferSize[0] ) ) {
+    //  statistics.writeDeviceSafeLeadBytes = dsPointerDifference( safeWritePos, currentWritePos, handle->dsBufferSize[0] );
+    //}
+
+    if ( dsPointerBetween( nextWritePos, safeWritePos, currentWritePos, dsBufferSize )
+         || dsPointerBetween( endWrite, safeWritePos, currentWritePos, dsBufferSize ) ) { 
+      // We've strayed into the forbidden zone ... resync the read pointer.
+      //++statistics.numberOfWriteUnderruns;
+      handle->xrun[0] = true;
+      nextWritePos = safeWritePos + handle->dsPointerLeadTime[0] - bufferBytes + dsBufferSize;
+      while ( nextWritePos >= dsBufferSize ) nextWritePos -= dsBufferSize;
       handle->bufferPointer[0] = nextWritePos;
+      endWrite = nextWritePos + bufferBytes;
+    }
 
-      if ( handle->drainCounter ) {
-        handle->drainCounter++;
-        goto unlock;
-      }
+    // Lock free space in the buffer
+    result = dsBuffer->Lock( nextWritePos, bufferBytes, &buffer1,
+                             &bufferSize1, &buffer2, &bufferSize2, 0 );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";
+      errorText_ = errorStream_.str();
+      error( RtError::SYSTEM_ERROR );
     }
 
-    if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
+    // Copy our buffer into the DS buffer
+    CopyMemory( buffer1, buffer, bufferSize1 );
+    if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );
 
-      // Setup parameters.
-      if ( stream_.doConvertBuffer[1] ) {
-        buffer = stream_.deviceBuffer;
-        bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];
-        bufferBytes *= formatBytes( stream_.deviceFormat[1] );
-      }
-      else {
-        buffer = stream_.userBuffer[1];
-        bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];
-        bufferBytes *= formatBytes( stream_.userFormat );
-      }
+    // Update our buffer offset and unlock sound buffer
+    dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";
+      errorText_ = errorStream_.str();
+      error( RtError::SYSTEM_ERROR );
+    }
+    nextWritePos = ( nextWritePos + bufferSize1 + bufferSize2 ) % dsBufferSize;
+    handle->bufferPointer[0] = nextWritePos;
 
-      LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
-      long nextReadPos = handle->bufferPointer[1];
-      DWORD dsBufferSize = handle->dsBufferSize[1];
+    if ( handle->drainCounter ) {
+      handle->drainCounter++;
+      goto unlock;
+    }
+  }
 
-      // Find out where the write and "safe read" pointers are.
-      result = dsBuffer->GetCurrentPosition( &currentReadPos, &safeReadPos );
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
-        errorText_ = errorStream_.str();
-        error( RtError::SYSTEM_ERROR );
-      }
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
 
-      if ( safeReadPos < (DWORD)nextReadPos ) safeReadPos += dsBufferSize; // unwrap offset
-      DWORD endRead = nextReadPos + bufferBytes;
-
-      // Handling depends on whether we are INPUT or DUPLEX. 
-      // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,
-      // then a wait here will drag the write pointers into the forbidden zone.
-      // 
-      // In DUPLEX mode, rather than wait, we will back off the read pointer until 
-      // it's in a safe position. This causes dropouts, but it seems to be the only 
-      // practical way to sync up the read and write pointers reliably, given the 
-      // the very complex relationship between phase and increment of the read and write 
-      // pointers.
-      //
-      // In order to minimize audible dropouts in DUPLEX mode, we will
-      // provide a pre-roll period of 0.5 seconds in which we return
-      // zeros from the read buffer while the pointers sync up.
-
-      if ( stream_.mode == DUPLEX ) {
-        if ( safeReadPos < endRead ) {
-          if ( duplexPrerollBytes <= 0 ) {
-            // Pre-roll time over. Be more agressive.
-            int adjustment = endRead-safeReadPos;
-
-            handle->xrun[1] = true;
-            //++statistics.numberOfReadOverruns;
-            // Two cases:
-            //   - large adjustments: we've probably run out of CPU cycles, so just resync exactly,
-            //     and perform fine adjustments later.
-            //   - small adjustments: back off by twice as much.
-            if ( adjustment >= 2*bufferBytes )
-              nextReadPos = safeReadPos-2*bufferBytes;
-            else
-              nextReadPos = safeReadPos-bufferBytes-adjustment;
-
-            //statistics.readDeviceSafeLeadBytes = currentReadPos-nextReadPos;
-            //if ( statistics.readDeviceSafeLeadBytes < 0) statistics.readDeviceSafeLeadBytes += dsBufferSize;
-            if ( nextReadPos < 0 ) nextReadPos += dsBufferSize;
+    // Setup parameters.
+    if ( stream_.doConvertBuffer[1] ) {
+      buffer = stream_.deviceBuffer;
+      bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];
+      bufferBytes *= formatBytes( stream_.deviceFormat[1] );
+    }
+    else {
+      buffer = stream_.userBuffer[1];
+      bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];
+      bufferBytes *= formatBytes( stream_.userFormat );
+    }
 
-          }
-          else {
-            // In pre=roll time. Just do it.
-            nextReadPos = safeReadPos-bufferBytes;
-            while ( nextReadPos < 0 ) nextReadPos += dsBufferSize;
-          }
-          endRead = nextReadPos + bufferBytes;
-        }
-      }
-      else { // mode == INPUT
-        while ( safeReadPos < endRead ) {
-          // See comments for playback.
-          double millis = (endRead - safeReadPos) * 900.0;
-          millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);
-          if ( millis < 1.0 ) millis = 1.0;
-          Sleep( (DWORD) millis );
-
-          // Wake up, find out where we are now
-          result = dsBuffer->GetCurrentPosition( &currentReadPos, &safeReadPos );
-          if ( FAILED( result ) ) {
-            errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
-            errorText_ = errorStream_.str();
-            error( RtError::SYSTEM_ERROR );
-          }
-      
-          if ( safeReadPos < (DWORD)nextReadPos ) safeReadPos += dsBufferSize; // unwrap offset
-        }
-      }
+    LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];
+    long nextReadPos = handle->bufferPointer[1];
+    DWORD dsBufferSize = handle->dsBufferSize[1];
+
+    // Find out where the write and "safe read" pointers are.
+    result = dsBuffer->GetCurrentPosition( &currentReadPos, &safeReadPos );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
+      errorText_ = errorStream_.str();
+      error( RtError::SYSTEM_ERROR );
+    }
 
-      //if (statistics.readDeviceSafeLeadBytes < dsPointerDifference( currentReadPos, nextReadPos, dsBufferSize ) )
-      //  statistics.readDeviceSafeLeadBytes = dsPointerDifference( currentReadPos, nextReadPos, dsBufferSize );
+    if ( safeReadPos < (DWORD)nextReadPos ) safeReadPos += dsBufferSize; // unwrap offset
+    DWORD endRead = nextReadPos + bufferBytes;
 
-      // Lock free space in the buffer
-      result = dsBuffer->Lock( nextReadPos, bufferBytes, &buffer1,
-                               &bufferSize1, &buffer2, &bufferSize2, 0 );
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";
-        errorText_ = errorStream_.str();
-        error( RtError::SYSTEM_ERROR );
-      }
+    // Handling depends on whether we are INPUT or DUPLEX. 
+    // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,
+    // then a wait here will drag the write pointers into the forbidden zone.
+    // 
+    // In DUPLEX mode, rather than wait, we will back off the read pointer until 
+    // it's in a safe position. This causes dropouts, but it seems to be the only 
+    // practical way to sync up the read and write pointers reliably, given the 
+    // the very complex relationship between phase and increment of the read and write 
+    // pointers.
+    //
+    // In order to minimize audible dropouts in DUPLEX mode, we will
+    // provide a pre-roll period of 0.5 seconds in which we return
+    // zeros from the read buffer while the pointers sync up.
 
-      if ( duplexPrerollBytes <= 0 ) {
-        // Copy our buffer into the DS buffer
-        CopyMemory( buffer, buffer1, bufferSize1 );
-        if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );
-      }
-      else {
-        memset( buffer, 0, bufferSize1 );
-        if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );
-        duplexPrerollBytes -= bufferSize1 + bufferSize2;
+    if ( stream_.mode == DUPLEX ) {
+      if ( safeReadPos < endRead ) {
+        if ( duplexPrerollBytes <= 0 ) {
+          // Pre-roll time over. Be more agressive.
+          int adjustment = endRead-safeReadPos;
+
+          handle->xrun[1] = true;
+          //++statistics.numberOfReadOverruns;
+          // Two cases:
+          //   - large adjustments: we've probably run out of CPU cycles, so just resync exactly,
+          //     and perform fine adjustments later.
+          //   - small adjustments: back off by twice as much.
+          if ( adjustment >= 2*bufferBytes )
+            nextReadPos = safeReadPos-2*bufferBytes;
+          else
+            nextReadPos = safeReadPos-bufferBytes-adjustment;
+
+          //statistics.readDeviceSafeLeadBytes = currentReadPos-nextReadPos;
+          //if ( statistics.readDeviceSafeLeadBytes < 0) statistics.readDeviceSafeLeadBytes += dsBufferSize;
+          if ( nextReadPos < 0 ) nextReadPos += dsBufferSize;
+
+        }
+        else {
+          // In pre=roll time. Just do it.
+          nextReadPos = safeReadPos-bufferBytes;
+          while ( nextReadPos < 0 ) nextReadPos += dsBufferSize;
+        }
+        endRead = nextReadPos + bufferBytes;
       }
+    }
+    else { // mode == INPUT
+      while ( safeReadPos < endRead ) {
+        // See comments for playback.
+        double millis = (endRead - safeReadPos) * 900.0;
+        millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);
+        if ( millis < 1.0 ) millis = 1.0;
+        Sleep( (DWORD) millis );
 
-      // Update our buffer offset and unlock sound buffer
-      nextReadPos = ( nextReadPos + bufferSize1 + bufferSize2 ) % dsBufferSize;
-      dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
-      if ( FAILED( result ) ) {
-        errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";
-        errorText_ = errorStream_.str();
-        error( RtError::SYSTEM_ERROR );
+        // Wake up, find out where we are now
+        result = dsBuffer->GetCurrentPosition( &currentReadPos, &safeReadPos );
+        if ( FAILED( result ) ) {
+          errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";
+          errorText_ = errorStream_.str();
+          error( RtError::SYSTEM_ERROR );
+        }
+      
+        if ( safeReadPos < (DWORD)nextReadPos ) safeReadPos += dsBufferSize; // unwrap offset
       }
-      handle->bufferPointer[1] = nextReadPos;
+    }
 
-      // No byte swapping necessary in DirectSound implementation.
+    //if (statistics.readDeviceSafeLeadBytes < dsPointerDifference( currentReadPos, nextReadPos, dsBufferSize ) )
+    //  statistics.readDeviceSafeLeadBytes = dsPointerDifference( currentReadPos, nextReadPos, dsBufferSize );
 
-      // If necessary, convert 8-bit data from unsigned to signed.
-      if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )
-        for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );
+    // Lock free space in the buffer
+    result = dsBuffer->Lock( nextReadPos, bufferBytes, &buffer1,
+                             &bufferSize1, &buffer2, &bufferSize2, 0 );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";
+      errorText_ = errorStream_.str();
+      error( RtError::SYSTEM_ERROR );
+    }
 
-      // Do buffer conversion if necessary.
-      if ( stream_.doConvertBuffer[1] )
-        convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
+    if ( duplexPrerollBytes <= 0 ) {
+      // Copy our buffer into the DS buffer
+      CopyMemory( buffer, buffer1, bufferSize1 );
+      if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );
+    }
+    else {
+      memset( buffer, 0, bufferSize1 );
+      if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );
+      duplexPrerollBytes -= bufferSize1 + bufferSize2;
     }
-#ifdef GENERATE_DEBUG_LOG
-    if ( currentDebugLogEntry < debugLog.size() )
-      {
-        TTickRecord &r = debugLog[currentDebugLogEntry++];
-        r.currentReadPointer = currentReadPos;
-        r.safeReadPointer = safeReadPos;
-        r.currentWritePointer = currentWritePos;
-        r.safeWritePointer = safeWritePos;
-        r.readTime = readTime;
-        r.writeTime = writeTime;
-        r.nextReadPointer = handles[1].bufferPointer;
-        r.nextWritePointer = handles[0].bufferPointer;
-      }
-#endif
 
-  unlock:
-    MUTEX_UNLOCK( &stream_.mutex );
+    // Update our buffer offset and unlock sound buffer
+    nextReadPos = ( nextReadPos + bufferSize1 + bufferSize2 ) % dsBufferSize;
+    dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
+    if ( FAILED( result ) ) {
+      errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";
+      errorText_ = errorStream_.str();
+      error( RtError::SYSTEM_ERROR );
+    }
+    handle->bufferPointer[1] = nextReadPos;
+
+    // No byte swapping necessary in DirectSound implementation.
+
+    // If necessary, convert 8-bit data from unsigned to signed.
+    if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )
+      for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );
 
-    RtApi::tickStreamTime();
+    // Do buffer conversion if necessary.
+    if ( stream_.doConvertBuffer[1] )
+      convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
   }
+#ifdef GENERATE_DEBUG_LOG
+  if ( currentDebugLogEntry < debugLog.size() )
+    {
+      TTickRecord &r = debugLog[currentDebugLogEntry++];
+      r.currentReadPointer = currentReadPos;
+      r.safeReadPointer = safeReadPos;
+      r.currentWritePointer = currentWritePos;
+      r.safeWritePointer = safeWritePos;
+      r.readTime = readTime;
+      r.writeTime = writeTime;
+      r.nextReadPointer = handles[1].bufferPointer;
+      r.nextWritePointer = handles[0].bufferPointer;
+    }
+#endif
 
-  // Definitions for utility functions and callbacks
-  // specific to the DirectSound implementation.
+ unlock:
+  MUTEX_UNLOCK( &stream_.mutex );
 
-  extern "C" unsigned __stdcall callbackHandler( void *ptr )
-  {
-    CallbackInfo *info = (CallbackInfo *) ptr;
-    RtApiDs *object = (RtApiDs *) info->object;
-    bool* isRunning = &info->isRunning;
+  RtApi::tickStreamTime();
+}
 
-    while ( *isRunning == true ) {
-      object->callbackEvent();
-    }
+// Definitions for utility functions and callbacks
+// specific to the DirectSound implementation.
 
-    _endthreadex( 0 );
-    return 0;
+extern "C" unsigned __stdcall callbackHandler( void *ptr )
+{
+  CallbackInfo *info = (CallbackInfo *) ptr;
+  RtApiDs *object = (RtApiDs *) info->object;
+  bool* isRunning = &info->isRunning;
+
+  while ( *isRunning == true ) {
+    object->callbackEvent();
   }
 
+  _endthreadex( 0 );
+  return 0;
+}
+
 #include "tchar.h"
 
-  std::string convertTChar( LPCTSTR name )
-  {
-    std::string s;
+std::string convertTChar( LPCTSTR name )
+{
+  std::string s;
 
 #if defined( UNICODE ) || defined( _UNICODE )
-    // Yes, this conversion doesn't make sense for two-byte characters
-    // but RtAudio is currently written to return an std::string of
-    // one-byte chars for the device name.
-    for ( unsigned int i=0; i<wcslen( name ); i++ )
-      s.push_back( name[i] );
+  // Yes, this conversion doesn't make sense for two-byte characters
+  // but RtAudio is currently written to return an std::string of
+  // one-byte chars for the device name.
+  for ( unsigned int i=0; i<wcslen( name ); i++ )
+    s.push_back( name[i] );
 #else
-    s.append( std::string( name ) );
+  s.append( std::string( name ) );
 #endif
 
-    return s;
-  }
+  return s;
+}
 
-  static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
-                                            LPCTSTR description,
-                                            LPCTSTR module,
-                                            LPVOID lpContext )
-  {
-    EnumInfo *info = (EnumInfo *) lpContext;
+static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,
+                                          LPCTSTR description,
+                                          LPCTSTR module,
+                                          LPVOID lpContext )
+{
+  EnumInfo *info = (EnumInfo *) lpContext;
 
-    HRESULT hr;
-    if ( info->isInput == true ) {
-      DSCCAPS caps;
-      LPDIRECTSOUNDCAPTURE object;
+  HRESULT hr;
+  if ( info->isInput == true ) {
+    DSCCAPS caps;
+    LPDIRECTSOUNDCAPTURE object;
 
-      hr = DirectSoundCaptureCreate(  lpguid, &object,   NULL );
-      if ( hr != DS_OK ) return TRUE;
+    hr = DirectSoundCaptureCreate(  lpguid, &object,   NULL );
+    if ( hr != DS_OK ) return TRUE;
 
-      caps.dwSize = sizeof(caps);
-      hr = object->GetCaps( &caps );
-      if ( hr == DS_OK ) {
-        if ( caps.dwChannels > 0 && caps.dwFormats > 0 )
-          info->counter++;
-      }
-      object->Release();
-    }
-    else {
-      DSCAPS caps;
-      LPDIRECTSOUND object;
-      hr = DirectSoundCreate(  lpguid, &object,   NULL );
-      if ( hr != DS_OK ) return TRUE;
-
-      caps.dwSize = sizeof(caps);
-      hr = object->GetCaps( &caps );
-      if ( hr == DS_OK ) {
-        if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )
-          info->counter++;
-      }
-      object->Release();
+    caps.dwSize = sizeof(caps);
+    hr = object->GetCaps( &caps );
+    if ( hr == DS_OK ) {
+      if ( caps.dwChannels > 0 && caps.dwFormats > 0 )
+        info->counter++;
     }
+    object->Release();
+  }
+  else {
+    DSCAPS caps;
+    LPDIRECTSOUND object;
+    hr = DirectSoundCreate(  lpguid, &object,   NULL );
+    if ( hr != DS_OK ) return TRUE;
 
-    if ( info->getDefault && lpguid == NULL ) return FALSE;
-
-    if ( info->findIndex && info->counter > info->index ) {
-      info->id = lpguid;
-      info->name = convertTChar( description );
-      return FALSE;
+    caps.dwSize = sizeof(caps);
+    hr = object->GetCaps( &caps );
+    if ( hr == DS_OK ) {
+      if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )
+        info->counter++;
     }
+    object->Release();
+  }
 
-    return TRUE;
+  if ( info->getDefault && lpguid == NULL ) return FALSE;
+
+  if ( info->findIndex && info->counter > info->index ) {
+    info->id = lpguid;
+    info->name = convertTChar( description );
+    return FALSE;
   }
 
-  static char* getErrorString( int code )
-  {
-    switch ( code ) {
+  return TRUE;
+}
+
+static char* getErrorString( int code )
+{
+  switch ( code ) {
 
-    case DSERR_ALLOCATED:
-      return "Already allocated";
+  case DSERR_ALLOCATED:
+    return "Already allocated";
 
-    case DSERR_CONTROLUNAVAIL:
-      return "Control unavailable";
+  case DSERR_CONTROLUNAVAIL:
+    return "Control unavailable";
 
-    case DSERR_INVALIDPARAM:
-      return "Invalid parameter";
+  case DSERR_INVALIDPARAM:
+    return "Invalid parameter";
 
-    case DSERR_INVALIDCALL:
-      return "Invalid call";
+  case DSERR_INVALIDCALL:
+    return "Invalid call";
 
-    case DSERR_GENERIC:
-      return "Generic error";
+  case DSERR_GENERIC:
+    return "Generic error";
 
-    case DSERR_PRIOLEVELNEEDED:
-      return "Priority level needed";
+  case DSERR_PRIOLEVELNEEDED:
+    return "Priority level needed";
 
-    case DSERR_OUTOFMEMORY:
-      return "Out of memory";
+  case DSERR_OUTOFMEMORY:
+    return "Out of memory";
 
-    case DSERR_BADFORMAT:
-      return "The sample rate or the channel format is not supported";
+  case DSERR_BADFORMAT:
+    return "The sample rate or the channel format is not supported";
 
-    case DSERR_UNSUPPORTED:
-      return "Not supported";
+  case DSERR_UNSUPPORTED:
+    return "Not supported";
 
-    case DSERR_NODRIVER:
-      return "No driver";
+  case DSERR_NODRIVER:
+    return "No driver";
 
-    case DSERR_ALREADYINITIALIZED:
-      return "Already initialized";
+  case DSERR_ALREADYINITIALIZED:
+    return "Already initialized";
 
-    case DSERR_NOAGGREGATION:
-      return "No aggregation";
+  case DSERR_NOAGGREGATION:
+    return "No aggregation";
 
-    case DSERR_BUFFERLOST:
-      return "Buffer lost";
+  case DSERR_BUFFERLOST:
+    return "Buffer lost";
 
-    case DSERR_OTHERAPPHASPRIO:
-      return "Another application already has priority";
+  case DSERR_OTHERAPPHASPRIO:
+    return "Another application already has priority";
 
-    case DSERR_UNINITIALIZED:
-      return "Uninitialized";
+  case DSERR_UNINITIALIZED:
+    return "Uninitialized";
 
-    default:
-      return "DirectSound unknown error";
-    }
+  default:
+    return "DirectSound unknown error";
   }
-  //******************** End of __WINDOWS_DS__ *********************//
+}
+//******************** End of __WINDOWS_DS__ *********************//
 #endif
 
 
@@ -4974,1220 +5009,1228 @@ bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
 
   // A structure to hold various information related to the ALSA API
   // implementation.
-  struct AlsaHandle {
-    snd_pcm_t *handles[2];
-    bool synchronized;
-    bool xrun[2];
-    pthread_cond_t runnable;
-
-    AlsaHandle()
-      :synchronized(false) { xrun[0] = false; xrun[1] = false; }
-  };
+struct AlsaHandle {
+  snd_pcm_t *handles[2];
+  bool synchronized;
+  bool xrun[2];
+  pthread_cond_t runnable;
 
-  extern "C" void *alsaCallbackHandler( void * ptr );
+  AlsaHandle()
+    :synchronized(false) { xrun[0] = false; xrun[1] = false; }
+};
 
-  RtApiAlsa :: RtApiAlsa()
-  {
-    // Nothing to do here.
-  }
+extern "C" void *alsaCallbackHandler( void * ptr );
 
-  RtApiAlsa :: ~RtApiAlsa()
-  {
-    if ( stream_.state != STREAM_CLOSED ) closeStream();
-  }
+RtApiAlsa :: RtApiAlsa()
+{
+  // Nothing to do here.
+}
 
-  unsigned int RtApiAlsa :: getDeviceCount( void )
-  {
-    unsigned nDevices = 0;
-    int result, subdevice, card;
-    char name[64];
-    snd_ctl_t *handle;
+RtApiAlsa :: ~RtApiAlsa()
+{
+  if ( stream_.state != STREAM_CLOSED ) closeStream();
+}
 
-    // Count cards and devices
-    card = -1;
-    snd_card_next( &card );
-    while ( card >= 0 ) {
-      sprintf( name, "hw:%d", card );
-      result = snd_ctl_open( &handle, name, 0 );
+unsigned int RtApiAlsa :: getDeviceCount( void )
+{
+  unsigned nDevices = 0;
+  int result, subdevice, card;
+  char name[64];
+  snd_ctl_t *handle;
+
+  // Count cards and devices
+  card = -1;
+  snd_card_next( &card );
+  while ( card >= 0 ) {
+    sprintf( name, "hw:%d", card );
+    result = snd_ctl_open( &handle, name, 0 );
+    if ( result < 0 ) {
+      errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror( result ) << ".";
+      errorText_ = errorStream_.str();
+      error( RtError::WARNING );
+      goto nextcard;
+    }
+    subdevice = -1;
+    while( 1 ) {
+      result = snd_ctl_pcm_next_device( handle, &subdevice );
       if ( result < 0 ) {
-        errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror( result ) << ".";
+        errorStream_ << "RtApiAlsa::getDeviceCount: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
         errorText_ = errorStream_.str();
         error( RtError::WARNING );
-        goto nextcard;
-      }
-      subdevice = -1;
-      while( 1 ) {
-        result = snd_ctl_pcm_next_device( handle, &subdevice );
-        if ( result < 0 ) {
-          errorStream_ << "RtApiAlsa::getDeviceCount: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
-          errorText_ = errorStream_.str();
-          error( RtError::WARNING );
-          break;
-        }
-        if ( subdevice < 0 )
-          break;
-        nDevices++;
+        break;
       }
-    nextcard:
-      snd_ctl_close( handle );
-      snd_card_next( &card );
+      if ( subdevice < 0 )
+        break;
+      nDevices++;
     }
-
-    return nDevices;
+  nextcard:
+    snd_ctl_close( handle );
+    snd_card_next( &card );
   }
 
-  RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
-  {
-    RtAudio::DeviceInfo info;
-    info.probed = false;
+  return nDevices;
+}
 
-    unsigned nDevices = 0;
-    int result, subdevice, card;
-    char name[64];
-    snd_ctl_t *chandle;
+RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )
+{
+  RtAudio::DeviceInfo info;
+  info.probed = false;
 
-    // Count cards and devices
-    card = -1;
-    snd_card_next( &card );
-    while ( card >= 0 ) {
-      sprintf( name, "hw:%d", card );
-      result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
+  unsigned nDevices = 0;
+  int result, subdevice, card;
+  char name[64];
+  snd_ctl_t *chandle;
+
+  // Count cards and devices
+  card = -1;
+  snd_card_next( &card );
+  while ( card >= 0 ) {
+    sprintf( name, "hw:%d", card );
+    result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
+    if ( result < 0 ) {
+      errorStream_ << "RtApiAlsa::getDeviceInfo: control open, card = " << card << ", " << snd_strerror( result ) << ".";
+      errorText_ = errorStream_.str();
+      error( RtError::WARNING );
+      goto nextcard;
+    }
+    subdevice = -1;
+    while( 1 ) {
+      result = snd_ctl_pcm_next_device( chandle, &subdevice );
       if ( result < 0 ) {
-        errorStream_ << "RtApiAlsa::getDeviceInfo: control open, card = " << card << ", " << snd_strerror( result ) << ".";
+        errorStream_ << "RtApiAlsa::getDeviceInfo: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
         errorText_ = errorStream_.str();
         error( RtError::WARNING );
-        goto nextcard;
+        break;
       }
-      subdevice = -1;
-      while( 1 ) {
-        result = snd_ctl_pcm_next_device( chandle, &subdevice );
-        if ( result < 0 ) {
-          errorStream_ << "RtApiAlsa::getDeviceInfo: control next device, card = " << card << ", " << snd_strerror( result ) << ".";
-          errorText_ = errorStream_.str();
-          error( RtError::WARNING );
-          break;
-        }
-        if ( subdevice < 0 ) break;
-        if ( nDevices == device ) {
-          sprintf( name, "hw:%d,%d", card, subdevice );
-          goto foundDevice;
-        }
-        nDevices++;
+      if ( subdevice < 0 ) break;
+      if ( nDevices == device ) {
+        sprintf( name, "hw:%d,%d", card, subdevice );
+        goto foundDevice;
       }
-    nextcard:
-      snd_ctl_close( chandle );
-      snd_card_next( &card );
+      nDevices++;
     }
+  nextcard:
+    snd_ctl_close( chandle );
+    snd_card_next( &card );
+  }
 
-    if ( nDevices == 0 ) {
-      errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!";
-      error( RtError::INVALID_USE );
-    }
+  if ( nDevices == 0 ) {
+    errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!";
+    error( RtError::INVALID_USE );
+  }
 
-    if ( device >= nDevices ) {
-      errorText_ = "RtApiAlsa::getDeviceInfo: device ID is invalid!";
-      error( RtError::INVALID_USE );
-    }
+  if ( device >= nDevices ) {
+    errorText_ = "RtApiAlsa::getDeviceInfo: device ID is invalid!";
+    error( RtError::INVALID_USE );
+  }
 
 foundDevice:
+ foundDevice:
 
-    // If a stream is already open, we cannot probe the stream devices.
-    // Thus, use the saved results.
-    if ( stream_.state != STREAM_CLOSED &&
-         ( stream_.device[0] == device || stream_.device[1] == device ) ) {
-      if ( device >= devices_.size() ) {
-        errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened.";
-        error( RtError::WARNING );
-        return info;
-      }
-      return devices_[ device ];
+  // If a stream is already open, we cannot probe the stream devices.
+  // Thus, use the saved results.
+  if ( stream_.state != STREAM_CLOSED &&
+       ( stream_.device[0] == device || stream_.device[1] == device ) ) {
+    if ( device >= devices_.size() ) {
+      errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened.";
+      error( RtError::WARNING );
+      return info;
     }
+    return devices_[ device ];
+  }
 
-    int openMode = SND_PCM_ASYNC;
-    snd_pcm_stream_t stream;
-    snd_pcm_info_t *pcminfo;
-    snd_pcm_info_alloca( &pcminfo );
-    snd_pcm_t *phandle;
-    snd_pcm_hw_params_t *params;
-    snd_pcm_hw_params_alloca( &params );
-
-    // First try for playback
-    stream = SND_PCM_STREAM_PLAYBACK;
-    snd_pcm_info_set_device( pcminfo, subdevice );
-    snd_pcm_info_set_subdevice( pcminfo, 0 );
-    snd_pcm_info_set_stream( pcminfo, stream );
+  int openMode = SND_PCM_ASYNC;
+  snd_pcm_stream_t stream;
+  snd_pcm_info_t *pcminfo;
+  snd_pcm_info_alloca( &pcminfo );
+  snd_pcm_t *phandle;
+  snd_pcm_hw_params_t *params;
+  snd_pcm_hw_params_alloca( &params );
 
-    result = snd_ctl_pcm_info( chandle, pcminfo );
-    if ( result < 0 ) {
-      // Device probably doesn't support playback.
-      goto captureProbe;
-    }
+  // First try for playback
+  stream = SND_PCM_STREAM_PLAYBACK;
+  snd_pcm_info_set_device( pcminfo, subdevice );
+  snd_pcm_info_set_subdevice( pcminfo, 0 );
+  snd_pcm_info_set_stream( pcminfo, stream );
 
-    result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK );
-    if ( result < 0 ) {
-      errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      goto captureProbe;
-    }
+  result = snd_ctl_pcm_info( chandle, pcminfo );
+  if ( result < 0 ) {
+    // Device probably doesn't support playback.
+    goto captureProbe;
+  }
 
-    // The device is open ... fill the parameter structure.
-    result = snd_pcm_hw_params_any( phandle, params );
-    if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      goto captureProbe;
-    }
+  result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK );
+  if ( result < 0 ) {
+    errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    goto captureProbe;
+  }
 
-    // Get output channel information.
-    unsigned int value;
-    result = snd_pcm_hw_params_get_channels_max( params, &value );
-    if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      goto captureProbe;
-    }
-    info.outputChannels = value;
+  // The device is open ... fill the parameter structure.
+  result = snd_pcm_hw_params_any( phandle, params );
+  if ( result < 0 ) {
     snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    goto captureProbe;
+  }
 
-  captureProbe:
-    // Now try for capture
-    stream = SND_PCM_STREAM_CAPTURE;
-    snd_pcm_info_set_stream( pcminfo, stream );
+  // Get output channel information.
+  unsigned int value;
+  result = snd_pcm_hw_params_get_channels_max( params, &value );
+  if ( result < 0 ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    goto captureProbe;
+  }
+  info.outputChannels = value;
+  snd_pcm_close( phandle );
 
-    result = snd_ctl_pcm_info( chandle, pcminfo );
-    snd_ctl_close( chandle );
-    if ( result < 0 ) {
-      // Device probably doesn't support capture.
-      if ( info.outputChannels == 0 ) return info;
-      goto probeParameters;
-    }
+ captureProbe:
+  // Now try for capture
+  stream = SND_PCM_STREAM_CAPTURE;
+  snd_pcm_info_set_stream( pcminfo, stream );
 
-    result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
-    if ( result < 0 ) {
-      errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      if ( info.outputChannels == 0 ) return info;
-      goto probeParameters;
-    }
+  result = snd_ctl_pcm_info( chandle, pcminfo );
+  snd_ctl_close( chandle );
+  if ( result < 0 ) {
+    // Device probably doesn't support capture.
+    if ( info.outputChannels == 0 ) return info;
+    goto probeParameters;
+  }
 
-    // The device is open ... fill the parameter structure.
-    result = snd_pcm_hw_params_any( phandle, params );
-    if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      if ( info.outputChannels == 0 ) return info;
-      goto probeParameters;
-    }
+  result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
+  if ( result < 0 ) {
+    errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    if ( info.outputChannels == 0 ) return info;
+    goto probeParameters;
+  }
 
-    result = snd_pcm_hw_params_get_channels_max( params, &value );
-    if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      if ( info.outputChannels == 0 ) return info;
-      goto probeParameters;
-    }
-    info.inputChannels = value;
+  // The device is open ... fill the parameter structure.
+  result = snd_pcm_hw_params_any( phandle, params );
+  if ( result < 0 ) {
     snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    if ( info.outputChannels == 0 ) return info;
+    goto probeParameters;
+  }
 
-    // If device opens for both playback and capture, we determine the channels.
-    if ( info.outputChannels > 0 && info.inputChannels > 0 )
-      info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
-
-    // ALSA doesn't provide default devices so we'll use the first available one.
-    if ( device == 0 && info.outputChannels > 0 )
-      info.isDefaultOutput = true;
-    if ( device == 0 && info.inputChannels > 0 )
-      info.isDefaultInput = true;
-
-  probeParameters:
-    // At this point, we just need to figure out the supported data
-    // formats and sample rates.  We'll proceed by opening the device in
-    // the direction with the maximum number of channels, or playback if
-    // they are equal.  This might limit our sample rate options, but so
-    // be it.
-
-    if ( info.outputChannels >= info.inputChannels )
-      stream = SND_PCM_STREAM_PLAYBACK;
-    else
-      stream = SND_PCM_STREAM_CAPTURE;
-    snd_pcm_info_set_stream( pcminfo, stream );
+  result = snd_pcm_hw_params_get_channels_max( params, &value );
+  if ( result < 0 ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    if ( info.outputChannels == 0 ) return info;
+    goto probeParameters;
+  }
+  info.inputChannels = value;
+  snd_pcm_close( phandle );
 
-    result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
-    if ( result < 0 ) {
-      errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
-    }
+  // If device opens for both playback and capture, we determine the channels.
+  if ( info.outputChannels > 0 && info.inputChannels > 0 )
+    info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
 
-    // The device is open ... fill the parameter structure.
-    result = snd_pcm_hw_params_any( phandle, params );
-    if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
-    }
+  // ALSA doesn't provide default devices so we'll use the first available one.
+  if ( device == 0 && info.outputChannels > 0 )
+    info.isDefaultOutput = true;
+  if ( device == 0 && info.inputChannels > 0 )
+    info.isDefaultInput = true;
 
-    // Test our discrete set of sample rate values.
-    info.sampleRates.clear();
-    for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
-      if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 )
-        info.sampleRates.push_back( SAMPLE_RATES[i] );
-    }
-    if ( info.sampleRates.size() == 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::getDeviceInfo: no supported sample rates found for device (" << name << ").";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
-    }
+ probeParameters:
+  // At this point, we just need to figure out the supported data
+  // formats and sample rates.  We'll proceed by opening the device in
+  // the direction with the maximum number of channels, or playback if
+  // they are equal.  This might limit our sample rate options, but so
+  // be it.
 
-    // Probe the supported data formats ... we don't care about endian-ness just yet
-    snd_pcm_format_t format;
-    info.nativeFormats = 0;
-    format = SND_PCM_FORMAT_S8;
-    if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
-      info.nativeFormats |= RTAUDIO_SINT8;
-    format = SND_PCM_FORMAT_S16;
-    if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
-      info.nativeFormats |= RTAUDIO_SINT16;
-    format = SND_PCM_FORMAT_S24;
-    if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
-      info.nativeFormats |= RTAUDIO_SINT24;
-    format = SND_PCM_FORMAT_S32;
-    if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
-      info.nativeFormats |= RTAUDIO_SINT32;
-    format = SND_PCM_FORMAT_FLOAT;
-    if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
-      info.nativeFormats |= RTAUDIO_FLOAT32;
-    format = SND_PCM_FORMAT_FLOAT64;
-    if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
-      info.nativeFormats |= RTAUDIO_FLOAT64;
-
-    // Check that we have at least one supported format
-    if ( info.nativeFormats == 0 ) {
-      errorStream_ << "RtApiAlsa::getDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio.";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
-    }
+  if ( info.outputChannels >= info.inputChannels )
+    stream = SND_PCM_STREAM_PLAYBACK;
+  else
+    stream = SND_PCM_STREAM_CAPTURE;
+  snd_pcm_info_set_stream( pcminfo, stream );
 
-    // Get the device name
-    char *cardname;
-    result = snd_card_get_name( card, &cardname );
-    if ( result >= 0 )
-      sprintf( name, "hw:%s,%d", cardname, subdevice );
-    info.name = name;
+  result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);
+  if ( result < 0 ) {
+    errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return info;
+  }
 
-    // That's all ... close the device and return
+  // The device is open ... fill the parameter structure.
+  result = snd_pcm_hw_params_any( phandle, params );
+  if ( result < 0 ) {
     snd_pcm_close( phandle );
-    info.probed = true;
+    errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
     return info;
   }
 
-  void RtApiAlsa :: saveDeviceInfo( void )
-  {
-    devices_.clear();
+  // Test our discrete set of sample rate values.
+  info.sampleRates.clear();
+  for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {
+    if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 )
+      info.sampleRates.push_back( SAMPLE_RATES[i] );
+  }
+  if ( info.sampleRates.size() == 0 ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::getDeviceInfo: no supported sample rates found for device (" << name << ").";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return info;
+  }
 
-    unsigned int nDevices = getDeviceCount();
-    devices_.resize( nDevices );
-    for ( unsigned int i=0; i<nDevices; i++ )
-      devices_[i] = getDeviceInfo( i );
+  // Probe the supported data formats ... we don't care about endian-ness just yet
+  snd_pcm_format_t format;
+  info.nativeFormats = 0;
+  format = SND_PCM_FORMAT_S8;
+  if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
+    info.nativeFormats |= RTAUDIO_SINT8;
+  format = SND_PCM_FORMAT_S16;
+  if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
+    info.nativeFormats |= RTAUDIO_SINT16;
+  format = SND_PCM_FORMAT_S24;
+  if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
+    info.nativeFormats |= RTAUDIO_SINT24;
+  format = SND_PCM_FORMAT_S32;
+  if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
+    info.nativeFormats |= RTAUDIO_SINT32;
+  format = SND_PCM_FORMAT_FLOAT;
+  if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
+    info.nativeFormats |= RTAUDIO_FLOAT32;
+  format = SND_PCM_FORMAT_FLOAT64;
+  if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )
+    info.nativeFormats |= RTAUDIO_FLOAT64;
+
+  // Check that we have at least one supported format
+  if ( info.nativeFormats == 0 ) {
+    errorStream_ << "RtApiAlsa::getDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio.";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return info;
   }
 
-  bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
-                                     unsigned int firstChannel, unsigned int sampleRate,
-                                     RtAudioFormat format, unsigned int *bufferSize,
-                                     RtAudio::StreamOptions *options )
+  // Get the device name
+  char *cardname;
+  result = snd_card_get_name( card, &cardname );
+  if ( result >= 0 )
+    sprintf( name, "hw:%s,%d", cardname, subdevice );
+  info.name = name;
 
-  {
+  // That's all ... close the device and return
+  snd_pcm_close( phandle );
+  info.probed = true;
+  return info;
+}
+
+void RtApiAlsa :: saveDeviceInfo( void )
+{
+  devices_.clear();
+
+  unsigned int nDevices = getDeviceCount();
+  devices_.resize( nDevices );
+  for ( unsigned int i=0; i<nDevices; i++ )
+    devices_[i] = getDeviceInfo( i );
+}
+
+bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
+                                   unsigned int firstChannel, unsigned int sampleRate,
+                                   RtAudioFormat format, unsigned int *bufferSize,
+                                   RtAudio::StreamOptions *options )
+
+{
 #if defined(__RTAUDIO_DEBUG__)
-    snd_output_t *out;
-    snd_output_stdio_attach(&out, stderr, 0);
+  snd_output_t *out;
+  snd_output_stdio_attach(&out, stderr, 0);
 #endif
 
-    // I'm not using the "plug" interface ... too much inconsistent behavior.
+  // I'm not using the "plug" interface ... too much inconsistent behavior.
 
-    unsigned nDevices = 0;
-    int result, subdevice, card;
-    char name[64];
-    snd_ctl_t *chandle;
+  unsigned nDevices = 0;
+  int result, subdevice, card;
+  char name[64];
+  snd_ctl_t *chandle;
 
-    // Count cards and devices
-    card = -1;
-    snd_card_next( &card );
-    while ( card >= 0 ) {
-      sprintf( name, "hw:%d", card );
-      result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
-      if ( result < 0 ) {
-        errorStream_ << "RtApiAlsa::probeDeviceOpen: control open, card = " << card << ", " << snd_strerror( result ) << ".";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
-      subdevice = -1;
-      while( 1 ) {
-        result = snd_ctl_pcm_next_device( chandle, &subdevice );
-        if ( result < 0 ) break;
-        if ( subdevice < 0 ) break;
-        if ( nDevices == device ) {
-          sprintf( name, "hw:%d,%d", card, subdevice );
-          snd_ctl_close( chandle );
-          goto foundDevice;
-        }
-        nDevices++;
+  // Count cards and devices
+  card = -1;
+  snd_card_next( &card );
+  while ( card >= 0 ) {
+    sprintf( name, "hw:%d", card );
+    result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );
+    if ( result < 0 ) {
+      errorStream_ << "RtApiAlsa::probeDeviceOpen: control open, card = " << card << ", " << snd_strerror( result ) << ".";
+      errorText_ = errorStream_.str();
+      return FAILURE;
+    }
+    subdevice = -1;
+    while( 1 ) {
+      result = snd_ctl_pcm_next_device( chandle, &subdevice );
+      if ( result < 0 ) break;
+      if ( subdevice < 0 ) break;
+      if ( nDevices == device ) {
+        sprintf( name, "hw:%d,%d", card, subdevice );
+        snd_ctl_close( chandle );
+        goto foundDevice;
       }
-      snd_ctl_close( chandle );
-      snd_card_next( &card );
+      nDevices++;
     }
+    snd_ctl_close( chandle );
+    snd_card_next( &card );
+  }
 
-    if ( nDevices == 0 ) {
-      // This should not happen because a check is made before this function is called.
-      errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!";
-      return FAILURE;
-    }
+  if ( nDevices == 0 ) {
+    // This should not happen because a check is made before this function is called.
+    errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!";
+    return FAILURE;
+  }
 
-    if ( device >= nDevices ) {
-      // This should not happen because a check is made before this function is called.
-      errorText_ = "RtApiAlsa::probeDeviceOpen: device ID is invalid!";
-      return FAILURE;
-    }
+  if ( device >= nDevices ) {
+    // This should not happen because a check is made before this function is called.
+    errorText_ = "RtApiAlsa::probeDeviceOpen: device ID is invalid!";
+    return FAILURE;
+  }
+
+ foundDevice:
 
-  foundDevice:
+  // The getDeviceInfo() function will not work for a device that is
+  // already open.  Thus, we'll probe the system before opening a
+  // stream and save the results for use by getDeviceInfo().
+  if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) // only do once
+    this->saveDeviceInfo();
 
-    // The getDeviceInfo() function will not work for a device that is
-    // already open.  Thus, we'll probe the system before opening a
-    // stream and save the results for use by getDeviceInfo().
-    if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) // only do once
-      this->saveDeviceInfo();
+  snd_pcm_stream_t stream;
+  if ( mode == OUTPUT )
+    stream = SND_PCM_STREAM_PLAYBACK;
+  else
+    stream = SND_PCM_STREAM_CAPTURE;
 
-    snd_pcm_stream_t stream;
+  snd_pcm_t *phandle;
+  int openMode = SND_PCM_ASYNC;
+  result = snd_pcm_open( &phandle, name, stream, openMode );
+  if ( result < 0 ) {
     if ( mode == OUTPUT )
-      stream = SND_PCM_STREAM_PLAYBACK;
+      errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output.";
     else
-      stream = SND_PCM_STREAM_CAPTURE;
-
-    snd_pcm_t *phandle;
-    int openMode = SND_PCM_ASYNC;
-    result = snd_pcm_open( &phandle, name, stream, openMode );
-    if ( result < 0 ) {
-      if ( mode == OUTPUT )
-        errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output.";
-      else
-        errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input.";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+      errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input.";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    // Fill the parameter structure.
-    snd_pcm_hw_params_t *hw_params;
-    snd_pcm_hw_params_alloca( &hw_params );
-    result = snd_pcm_hw_params_any( phandle, hw_params );
-    if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  // Fill the parameter structure.
+  snd_pcm_hw_params_t *hw_params;
+  snd_pcm_hw_params_alloca( &hw_params );
+  result = snd_pcm_hw_params_any( phandle, hw_params );
+  if ( result < 0 ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
 #if defined(__RTAUDIO_DEBUG__)
-    fprintf( stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n" );
-    snd_pcm_hw_params_dump( hw_params, out );
+  fprintf( stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n" );
+  snd_pcm_hw_params_dump( hw_params, out );
 #endif
 
-    // Set access ... check user preference.
-    if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) {
-      stream_.userInterleaved = false;
-      result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
-      if ( result < 0 ) {
-        result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
-        stream_.deviceInterleaved[mode] =  true;
-      }
-      else
-        stream_.deviceInterleaved[mode] = false;
-    }
-    else {
-      stream_.userInterleaved = true;
+  // Set access ... check user preference.
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) {
+    stream_.userInterleaved = false;
+    result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
+    if ( result < 0 ) {
       result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
-      if ( result < 0 ) {
-        result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
-        stream_.deviceInterleaved[mode] =  false;
-      }
-      else
-        stream_.deviceInterleaved[mode] =  true;
+      stream_.deviceInterleaved[mode] =  true;
     }
-
+    else
+      stream_.deviceInterleaved[mode] = false;
+  }
+  else {
+    stream_.userInterleaved = true;
+    result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );
     if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      return FAILURE;
+      result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );
+      stream_.deviceInterleaved[mode] =  false;
     }
+    else
+      stream_.deviceInterleaved[mode] =  true;
+  }
 
-    // Determine how to set the device format.
-    stream_.userFormat = format;
-    snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN;
-
-    if ( format == RTAUDIO_SINT8 )
-      deviceFormat = SND_PCM_FORMAT_S8;
-    else if ( format == RTAUDIO_SINT16 )
-      deviceFormat = SND_PCM_FORMAT_S16;
-    else if ( format == RTAUDIO_SINT24 )
-      deviceFormat = SND_PCM_FORMAT_S24;
-    else if ( format == RTAUDIO_SINT32 )
-      deviceFormat = SND_PCM_FORMAT_S32;
-    else if ( format == RTAUDIO_FLOAT32 )
-      deviceFormat = SND_PCM_FORMAT_FLOAT;
-    else if ( format == RTAUDIO_FLOAT64 )
-      deviceFormat = SND_PCM_FORMAT_FLOAT64;
-
-    if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0) {
-      stream_.deviceFormat[mode] = format;
-      goto setFormat;
-    }
+  if ( result < 0 ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    // The user requested format is not natively supported by the device.
-    deviceFormat = SND_PCM_FORMAT_FLOAT64;
-    if ( snd_pcm_hw_params_test_format( phandle, hw_params, deviceFormat ) == 0 ) {
-      stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
-      goto setFormat;
-    }
+  // Determine how to set the device format.
+  stream_.userFormat = format;
+  snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN;
 
+  if ( format == RTAUDIO_SINT8 )
+    deviceFormat = SND_PCM_FORMAT_S8;
+  else if ( format == RTAUDIO_SINT16 )
+    deviceFormat = SND_PCM_FORMAT_S16;
+  else if ( format == RTAUDIO_SINT24 )
+    deviceFormat = SND_PCM_FORMAT_S24;
+  else if ( format == RTAUDIO_SINT32 )
+    deviceFormat = SND_PCM_FORMAT_S32;
+  else if ( format == RTAUDIO_FLOAT32 )
     deviceFormat = SND_PCM_FORMAT_FLOAT;
-    if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
-      stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
-      goto setFormat;
-    }
+  else if ( format == RTAUDIO_FLOAT64 )
+    deviceFormat = SND_PCM_FORMAT_FLOAT64;
 
-    deviceFormat = SND_PCM_FORMAT_S32;
-    if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
-      stream_.deviceFormat[mode] = RTAUDIO_SINT32;
-      goto setFormat;
-    }
+  if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0) {
+    stream_.deviceFormat[mode] = format;
+    goto setFormat;
+  }
 
-    deviceFormat = SND_PCM_FORMAT_S24;
-    if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
-      stream_.deviceFormat[mode] = RTAUDIO_SINT24;
-      goto setFormat;
-    }
+  // The user requested format is not natively supported by the device.
+  deviceFormat = SND_PCM_FORMAT_FLOAT64;
+  if ( snd_pcm_hw_params_test_format( phandle, hw_params, deviceFormat ) == 0 ) {
+    stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
+    goto setFormat;
+  }
 
-    deviceFormat = SND_PCM_FORMAT_S16;
-    if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
-      stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-      goto setFormat;
-    }
+  deviceFormat = SND_PCM_FORMAT_FLOAT;
+  if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
+    stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
+    goto setFormat;
+  }
 
-    deviceFormat = SND_PCM_FORMAT_S8;
-    if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
-      stream_.deviceFormat[mode] = RTAUDIO_SINT8;
-      goto setFormat;
-    }
+  deviceFormat = SND_PCM_FORMAT_S32;
+  if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
+    stream_.deviceFormat[mode] = RTAUDIO_SINT32;
+    goto setFormat;
+  }
+
+  deviceFormat = SND_PCM_FORMAT_S24;
+  if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
+    stream_.deviceFormat[mode] = RTAUDIO_SINT24;
+    goto setFormat;
+  }
+
+  deviceFormat = SND_PCM_FORMAT_S16;
+  if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
+    stream_.deviceFormat[mode] = RTAUDIO_SINT16;
+    goto setFormat;
+  }
+
+  deviceFormat = SND_PCM_FORMAT_S8;
+  if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {
+    stream_.deviceFormat[mode] = RTAUDIO_SINT8;
+    goto setFormat;
+  }
+
+  // If we get here, no supported format was found.
+  errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio.";
+  errorText_ = errorStream_.str();
+  return FAILURE;
 
-    // If we get here, no supported format was found.
-    errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio.";
+ setFormat:
+  result = snd_pcm_hw_params_set_format( phandle, hw_params, deviceFormat );
+  if ( result < 0 ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror( result ) << ".";
     errorText_ = errorStream_.str();
     return FAILURE;
+  }
 
-  setFormat:
-    result = snd_pcm_hw_params_set_format( phandle, hw_params, deviceFormat );
-    if ( result < 0 ) {
+  // Determine whether byte-swaping is necessary.
+  stream_.doByteSwap[mode] = false;
+  if ( deviceFormat != SND_PCM_FORMAT_S8 ) {
+    result = snd_pcm_format_cpu_endian( deviceFormat );
+    if ( result == 0 )
+      stream_.doByteSwap[mode] = true;
+    else if (result < 0) {
       snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror( result ) << ".";
+      errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror( result ) << ".";
       errorText_ = errorStream_.str();
       return FAILURE;
     }
+  }
 
-    // Determine whether byte-swaping is necessary.
-    stream_.doByteSwap[mode] = false;
-    if ( deviceFormat != SND_PCM_FORMAT_S8 ) {
-      result = snd_pcm_format_cpu_endian( deviceFormat );
-      if ( result == 0 )
-        stream_.doByteSwap[mode] = true;
-      else if (result < 0) {
-        snd_pcm_close( phandle );
-        errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror( result ) << ".";
-        errorText_ = errorStream_.str();
-        return FAILURE;
-      }
-    }
-
-    // Set the sample rate.
-    result = snd_pcm_hw_params_set_rate_near( phandle, hw_params, (unsigned int*) &sampleRate, 0 );
-    if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  // Set the sample rate.
+  result = snd_pcm_hw_params_set_rate_near( phandle, hw_params, (unsigned int*) &sampleRate, 0 );
+  if ( result < 0 ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    // Determine the number of channels for this device.  We support a possible
-    // minimum device channel number > than the value requested by the user.
-    stream_.nUserChannels[mode] = channels;
-    unsigned int value;
-    result = snd_pcm_hw_params_get_channels_max( hw_params, &value );
-    unsigned int deviceChannels = value;
-    if ( result < 0 || deviceChannels < channels + firstChannel ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  // Determine the number of channels for this device.  We support a possible
+  // minimum device channel number > than the value requested by the user.
+  stream_.nUserChannels[mode] = channels;
+  unsigned int value;
+  result = snd_pcm_hw_params_get_channels_max( hw_params, &value );
+  unsigned int deviceChannels = value;
+  if ( result < 0 || deviceChannels < channels + firstChannel ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    result = snd_pcm_hw_params_get_channels_min( hw_params, &value );
-    if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
-    deviceChannels = value;
-    if ( deviceChannels < channels + firstChannel ) deviceChannels = channels + firstChannel;
-    stream_.nDeviceChannels[mode] = deviceChannels;
+  result = snd_pcm_hw_params_get_channels_min( hw_params, &value );
+  if ( result < 0 ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
+  deviceChannels = value;
+  if ( deviceChannels < channels + firstChannel ) deviceChannels = channels + firstChannel;
+  stream_.nDeviceChannels[mode] = deviceChannels;
 
-    // Set the device channels.
-    result = snd_pcm_hw_params_set_channels( phandle, hw_params, deviceChannels );
-    if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  // Set the device channels.
+  result = snd_pcm_hw_params_set_channels( phandle, hw_params, deviceChannels );
+  if ( result < 0 ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    // Set the buffer number, which in ALSA is referred to as the "period".
-    int totalSize, dir;
-    unsigned int periods = 0;
-    if ( options ) periods = options->numberOfBuffers;
-    totalSize = *bufferSize * periods;
+  // Set the buffer number, which in ALSA is referred to as the "period".
+  int totalSize, dir;
+  unsigned int periods = 0;
+  if ( options ) periods = options->numberOfBuffers;
+  totalSize = *bufferSize * periods;
 
-    // Set the buffer (or period) size.
-    snd_pcm_uframes_t periodSize = *bufferSize;
-    result = snd_pcm_hw_params_set_period_size_near( phandle, hw_params, &periodSize, &dir );
-    if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
-    *bufferSize = periodSize;
+  // Set the buffer (or period) size.
+  snd_pcm_uframes_t periodSize = *bufferSize;
+  result = snd_pcm_hw_params_set_period_size_near( phandle, hw_params, &periodSize, &dir );
+  if ( result < 0 ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
+  *bufferSize = periodSize;
 
-    if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) periods = 2;
-    else periods = totalSize / *bufferSize;
-    // Even though the hardware might allow 1 buffer, it won't work reliably.
-    if ( periods < 2 ) periods = 2;
-    result = snd_pcm_hw_params_set_periods_near( phandle, hw_params, &periods, &dir );
-    if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) periods = 2;
+  else periods = totalSize / *bufferSize;
+  // Even though the hardware might allow 1 buffer, it won't work reliably.
+  if ( periods < 2 ) periods = 2;
+  result = snd_pcm_hw_params_set_periods_near( phandle, hw_params, &periods, &dir );
+  if ( result < 0 ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    // If attempting to setup a duplex stream, the bufferSize parameter
-    // MUST be the same in both directions!
-    if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
-      errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  // If attempting to setup a duplex stream, the bufferSize parameter
+  // MUST be the same in both directions!
+  if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    stream_.bufferSize = *bufferSize;
+  stream_.bufferSize = *bufferSize;
 
-    // Install the hardware configuration
-    result = snd_pcm_hw_params( phandle, hw_params );
-    if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  // Install the hardware configuration
+  result = snd_pcm_hw_params( phandle, hw_params );
+  if ( result < 0 ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
 #if defined(__RTAUDIO_DEBUG__)
-    fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n");
-    snd_pcm_hw_params_dump( hw_params, out );
+  fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n");
+  snd_pcm_hw_params_dump( hw_params, out );
 #endif
 
-    // Set the software configuration to fill buffers with zeros and prevent device stopping on xruns.
-    snd_pcm_sw_params_t *sw_params = NULL;
-    snd_pcm_sw_params_alloca( &sw_params );
-    snd_pcm_sw_params_current( phandle, sw_params );
-    snd_pcm_sw_params_set_start_threshold( phandle, sw_params, *bufferSize );
-    snd_pcm_sw_params_set_stop_threshold( phandle, sw_params, ULONG_MAX );
-    snd_pcm_sw_params_set_silence_threshold( phandle, sw_params, 0 );
-
-    // The following two settings were suggested by Theo Veenker
-    //snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize );
-    //snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 );
-
-    // here are two options for a fix
-    //snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX );
-    snd_pcm_uframes_t val;
-    snd_pcm_sw_params_get_boundary( sw_params, &val );
-    snd_pcm_sw_params_set_silence_size( phandle, sw_params, val );
-
-    result = snd_pcm_sw_params( phandle, sw_params );
-    if ( result < 0 ) {
-      snd_pcm_close( phandle );
-      errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror( result ) << ".";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  // Set the software configuration to fill buffers with zeros and prevent device stopping on xruns.
+  snd_pcm_sw_params_t *sw_params = NULL;
+  snd_pcm_sw_params_alloca( &sw_params );
+  snd_pcm_sw_params_current( phandle, sw_params );
+  snd_pcm_sw_params_set_start_threshold( phandle, sw_params, *bufferSize );
+  snd_pcm_sw_params_set_stop_threshold( phandle, sw_params, ULONG_MAX );
+  snd_pcm_sw_params_set_silence_threshold( phandle, sw_params, 0 );
+
+  // The following two settings were suggested by Theo Veenker
+  //snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize );
+  //snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 );
+
+  // here are two options for a fix
+  //snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX );
+  snd_pcm_uframes_t val;
+  snd_pcm_sw_params_get_boundary( sw_params, &val );
+  snd_pcm_sw_params_set_silence_size( phandle, sw_params, val );
+
+  result = snd_pcm_sw_params( phandle, sw_params );
+  if ( result < 0 ) {
+    snd_pcm_close( phandle );
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror( result ) << ".";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
 #if defined(__RTAUDIO_DEBUG__)
-    fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");
-    snd_pcm_sw_params_dump( sw_params, out );
+  fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");
+  snd_pcm_sw_params_dump( sw_params, out );
 #endif
 
-    // Set flags for buffer conversion
-    stream_.doConvertBuffer[mode] = false;
-    if ( stream_.userFormat != stream_.deviceFormat[mode] )
-      stream_.doConvertBuffer[mode] = true;
-    if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
-      stream_.doConvertBuffer[mode] = true;
-    if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
-         stream_.nUserChannels[mode] > 1 )
-      stream_.doConvertBuffer[mode] = true;
-
-    // Allocate the ApiHandle if necessary and then save.
-    AlsaHandle *apiInfo = 0;
-    if ( stream_.apiHandle == 0 ) {
-      try {
-        apiInfo = (AlsaHandle *) new AlsaHandle;
-      }
-      catch ( std::bad_alloc& ) {
-        errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory.";
-        goto error;
-      }
-
-      if ( pthread_cond_init( &apiInfo->runnable, NULL ) ) {
-        errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable.";
-        goto error;
-      }
+  // Set flags for buffer conversion
+  stream_.doConvertBuffer[mode] = false;
+  if ( stream_.userFormat != stream_.deviceFormat[mode] )
+    stream_.doConvertBuffer[mode] = true;
+  if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
+    stream_.doConvertBuffer[mode] = true;
+  if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
+       stream_.nUserChannels[mode] > 1 )
+    stream_.doConvertBuffer[mode] = true;
 
-      stream_.apiHandle = (void *) apiInfo;
-      apiInfo->handles[0] = 0;
-      apiInfo->handles[1] = 0;
-    }
-    else {
-      apiInfo = (AlsaHandle *) stream_.apiHandle;
+  // Allocate the ApiHandle if necessary and then save.
+  AlsaHandle *apiInfo = 0;
+  if ( stream_.apiHandle == 0 ) {
+    try {
+      apiInfo = (AlsaHandle *) new AlsaHandle;
     }
-    apiInfo->handles[mode] = phandle;
-
-    // Allocate necessary internal buffers.
-    unsigned long bufferBytes;
-    bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
-    stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
-    if ( stream_.userBuffer[mode] == NULL ) {
-      errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory.";
+    catch ( std::bad_alloc& ) {
+      errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory.";
       goto error;
     }
 
-    if ( stream_.doConvertBuffer[mode] ) {
-
-      bool makeBuffer = true;
-      bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
-      if ( mode == INPUT ) {
-        if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
-          unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
-          if ( bufferBytes <= bytesOut ) makeBuffer = false;
-        }
-      }
-
-      if ( makeBuffer ) {
-        bufferBytes *= *bufferSize;
-        if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
-        stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
-        if ( stream_.deviceBuffer == NULL ) {
-          errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory.";
-          goto error;
-        }
-      }
+    if ( pthread_cond_init( &apiInfo->runnable, NULL ) ) {
+      errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable.";
+      goto error;
     }
 
-    stream_.sampleRate = sampleRate;
-    stream_.nBuffers = periods;
-    stream_.device[mode] = device;
-    stream_.state = STREAM_STOPPED;
-
-    // Setup the buffer conversion information structure.
-    if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
+    stream_.apiHandle = (void *) apiInfo;
+    apiInfo->handles[0] = 0;
+    apiInfo->handles[1] = 0;
+  }
+  else {
+    apiInfo = (AlsaHandle *) stream_.apiHandle;
+  }
+  apiInfo->handles[mode] = phandle;
 
-    // Setup thread if necessary.
-    if ( stream_.mode == OUTPUT && mode == INPUT ) {
-      // We had already set up an output stream.
-      stream_.mode = DUPLEX;
-      // Link the streams if possible.
-      apiInfo->synchronized = false;
-      if ( snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0 )
-        apiInfo->synchronized = true;
-      else {
-        errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices.";
-        error( RtError::WARNING );
-      }
-    }
-    else {
-      stream_.mode = mode;
+  // Allocate necessary internal buffers.
+  unsigned long bufferBytes;
+  bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
+  stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
+  if ( stream_.userBuffer[mode] == NULL ) {
+    errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory.";
+    goto error;
+  }
 
-      // Setup callback thread.
-      stream_.callbackInfo.object = (void *) this;
-
-      // Set the thread attributes for joinable and realtime scheduling
-      // priority (optional).  The higher priority will only take affect
-      // if the program is run as root or suid. Note, under Linux
-      // processes with CAP_SYS_NICE privilege, a user can change
-      // scheduling policy and priority (thus need not be root). See
-      // POSIX "capabilities".
-      pthread_attr_t attr;
-      pthread_attr_init( &attr );
-      pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
-#ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
-      if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
-        struct sched_param param;
-        int priority = options->priority;
-        int min = sched_get_priority_min( SCHED_RR );
-        int max = sched_get_priority_max( SCHED_RR );
-        if ( priority < min ) priority = min;
-        else if ( priority > max ) priority = max;
-        param.sched_priority = priority;
-        pthread_attr_setschedparam( &attr, &param );
-        pthread_attr_setschedpolicy( &attr, SCHED_RR );
-      }
-      else
-        pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
-#else
-      pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
-#endif
+  if ( stream_.doConvertBuffer[mode] ) {
 
-      stream_.callbackInfo.isRunning = true;
-      result = pthread_create( &stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo );
-      pthread_attr_destroy( &attr );
-      if ( result ) {
-        stream_.callbackInfo.isRunning = false;
-        errorText_ = "RtApiAlsa::error creating callback thread!";
-        goto error;
+    bool makeBuffer = true;
+    bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
+    if ( mode == INPUT ) {
+      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
+        unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
+        if ( bufferBytes <= bytesOut ) makeBuffer = false;
       }
     }
 
-    return SUCCESS;
-
-  error:
-    if ( apiInfo ) {
-      pthread_cond_destroy( &apiInfo->runnable );
-      if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
-      if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
-      delete apiInfo;
-      stream_.apiHandle = 0;
-    }
-
-    for ( int i=0; i<2; i++ ) {
-      if ( stream_.userBuffer[i] ) {
-        free( stream_.userBuffer[i] );
-        stream_.userBuffer[i] = 0;
+    if ( makeBuffer ) {
+      bufferBytes *= *bufferSize;
+      if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
+      stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
+      if ( stream_.deviceBuffer == NULL ) {
+        errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory.";
+        goto error;
       }
     }
+  }
 
-    if ( stream_.deviceBuffer ) {
-      free( stream_.deviceBuffer );
-      stream_.deviceBuffer = 0;
-    }
+  stream_.sampleRate = sampleRate;
+  stream_.nBuffers = periods;
+  stream_.device[mode] = device;
+  stream_.state = STREAM_STOPPED;
 
-    return FAILURE;
-  }
+  // Setup the buffer conversion information structure.
+  if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
 
-  void RtApiAlsa :: closeStream()
-  {
-    if ( stream_.state == STREAM_CLOSED ) {
-      errorText_ = "RtApiAlsa::closeStream(): no open stream to close!";
+  // Setup thread if necessary.
+  if ( stream_.mode == OUTPUT && mode == INPUT ) {
+    // We had already set up an output stream.
+    stream_.mode = DUPLEX;
+    // Link the streams if possible.
+    apiInfo->synchronized = false;
+    if ( snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0 )
+      apiInfo->synchronized = true;
+    else {
+      errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices.";
       error( RtError::WARNING );
-      return;
     }
+  }
+  else {
+    stream_.mode = mode;
 
-    AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
-    stream_.callbackInfo.isRunning = false;
-    MUTEX_LOCK( &stream_.mutex );
-    if ( stream_.state == STREAM_STOPPED )
-      pthread_cond_signal( &apiInfo->runnable );
-    MUTEX_UNLOCK( &stream_.mutex );
-    pthread_join( stream_.callbackInfo.thread, NULL );
+    // Setup callback thread.
+    stream_.callbackInfo.object = (void *) this;
 
-    if ( stream_.state == STREAM_RUNNING ) {
-      stream_.state = STREAM_STOPPED;
-      if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
-        snd_pcm_drop( apiInfo->handles[0] );
-      if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
-        snd_pcm_drop( apiInfo->handles[1] );
+    // Set the thread attributes for joinable and realtime scheduling
+    // priority (optional).  The higher priority will only take affect
+    // if the program is run as root or suid. Note, under Linux
+    // processes with CAP_SYS_NICE privilege, a user can change
+    // scheduling policy and priority (thus need not be root). See
+    // POSIX "capabilities".
+    pthread_attr_t attr;
+    pthread_attr_init( &attr );
+    pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
+#ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
+    if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
+      struct sched_param param;
+      int priority = options->priority;
+      int min = sched_get_priority_min( SCHED_RR );
+      int max = sched_get_priority_max( SCHED_RR );
+      if ( priority < min ) priority = min;
+      else if ( priority > max ) priority = max;
+      param.sched_priority = priority;
+      pthread_attr_setschedparam( &attr, &param );
+      pthread_attr_setschedpolicy( &attr, SCHED_RR );
     }
+    else
+      pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
+#else
+    pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
+#endif
 
-    if ( apiInfo ) {
-      pthread_cond_destroy( &apiInfo->runnable );
-      if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
-      if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
-      delete apiInfo;
-      stream_.apiHandle = 0;
+    stream_.callbackInfo.isRunning = true;
+    result = pthread_create( &stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo );
+    pthread_attr_destroy( &attr );
+    if ( result ) {
+      stream_.callbackInfo.isRunning = false;
+      errorText_ = "RtApiAlsa::error creating callback thread!";
+      goto error;
     }
+  }
 
-    for ( int i=0; i<2; i++ ) {
-      if ( stream_.userBuffer[i] ) {
-        free( stream_.userBuffer[i] );
-        stream_.userBuffer[i] = 0;
-      }
-    }
+  return SUCCESS;
 
-    if ( stream_.deviceBuffer ) {
-      free( stream_.deviceBuffer );
-      stream_.deviceBuffer = 0;
+ error:
+  if ( apiInfo ) {
+    pthread_cond_destroy( &apiInfo->runnable );
+    if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
+    if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
+    delete apiInfo;
+    stream_.apiHandle = 0;
+  }
+
+  for ( int i=0; i<2; i++ ) {
+    if ( stream_.userBuffer[i] ) {
+      free( stream_.userBuffer[i] );
+      stream_.userBuffer[i] = 0;
     }
+  }
 
-    stream_.mode = UNINITIALIZED;
-    stream_.state = STREAM_CLOSED;
+  if ( stream_.deviceBuffer ) {
+    free( stream_.deviceBuffer );
+    stream_.deviceBuffer = 0;
   }
 
-  void RtApiAlsa :: startStream()
-  {
-    // This method calls snd_pcm_prepare if the device isn't already in that state.
+  return FAILURE;
+}
 
-    verifyStream();
-    if ( stream_.state == STREAM_RUNNING ) {
-      errorText_ = "RtApiAlsa::startStream(): the stream is already running!";
-      error( RtError::WARNING );
-      return;
-    }
+void RtApiAlsa :: closeStream()
+{
+  if ( stream_.state == STREAM_CLOSED ) {
+    errorText_ = "RtApiAlsa::closeStream(): no open stream to close!";
+    error( RtError::WARNING );
+    return;
+  }
 
-    MUTEX_LOCK( &stream_.mutex );
+  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
+  stream_.callbackInfo.isRunning = false;
+  MUTEX_LOCK( &stream_.mutex );
+  if ( stream_.state == STREAM_STOPPED )
+    pthread_cond_signal( &apiInfo->runnable );
+  MUTEX_UNLOCK( &stream_.mutex );
+  pthread_join( stream_.callbackInfo.thread, NULL );
 
-    int result = 0;
-    snd_pcm_state_t state;
-    AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
-    snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
-      state = snd_pcm_state( handle[0] );
-      if ( state != SND_PCM_STATE_PREPARED ) {
-        result = snd_pcm_prepare( handle[0] );
-        if ( result < 0 ) {
-          errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror( result ) << ".";
-          errorText_ = errorStream_.str();
-          goto unlock;
-        }
-      }
-    }
+  if ( stream_.state == STREAM_RUNNING ) {
+    stream_.state = STREAM_STOPPED;
+    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
+      snd_pcm_drop( apiInfo->handles[0] );
+    if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
+      snd_pcm_drop( apiInfo->handles[1] );
+  }
 
-    if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
-      state = snd_pcm_state( handle[1] );
-      if ( state != SND_PCM_STATE_PREPARED ) {
-        result = snd_pcm_prepare( handle[1] );
-        if ( result < 0 ) {
-          errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror( result ) << ".";
-          errorText_ = errorStream_.str();
-          goto unlock;
-        }
-      }
+  if ( apiInfo ) {
+    pthread_cond_destroy( &apiInfo->runnable );
+    if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );
+    if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );
+    delete apiInfo;
+    stream_.apiHandle = 0;
+  }
+
+  for ( int i=0; i<2; i++ ) {
+    if ( stream_.userBuffer[i] ) {
+      free( stream_.userBuffer[i] );
+      stream_.userBuffer[i] = 0;
     }
+  }
 
-    stream_.state = STREAM_RUNNING;
+  if ( stream_.deviceBuffer ) {
+    free( stream_.deviceBuffer );
+    stream_.deviceBuffer = 0;
+  }
 
-  unlock:
-    MUTEX_UNLOCK( &stream_.mutex );
+  stream_.mode = UNINITIALIZED;
+  stream_.state = STREAM_CLOSED;
+}
 
-    pthread_cond_signal( &apiInfo->runnable );
+void RtApiAlsa :: startStream()
+{
+  // This method calls snd_pcm_prepare if the device isn't already in that state.
 
-    if ( result >= 0 ) return;
-    error( RtError::SYSTEM_ERROR );
+  verifyStream();
+  if ( stream_.state == STREAM_RUNNING ) {
+    errorText_ = "RtApiAlsa::startStream(): the stream is already running!";
+    error( RtError::WARNING );
+    return;
   }
 
-  void RtApiAlsa :: stopStream()
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_STOPPED ) {
-      errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!";
-      error( RtError::WARNING );
-      return;
-    }
-
-    // Change the state before the lock to improve shutdown response.
-    stream_.state = STREAM_STOPPED;
-    MUTEX_LOCK( &stream_.mutex );
+  MUTEX_LOCK( &stream_.mutex );
 
-    int result = 0;
-    AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
-    snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
-      if ( apiInfo->synchronized ) 
-        result = snd_pcm_drop( handle[0] );
-      else
-        result = snd_pcm_drain( handle[0] );
+  int result = 0;
+  snd_pcm_state_t state;
+  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
+  snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+    state = snd_pcm_state( handle[0] );
+    if ( state != SND_PCM_STATE_PREPARED ) {
+      result = snd_pcm_prepare( handle[0] );
       if ( result < 0 ) {
-        errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror( result ) << ".";
+        errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror( result ) << ".";
         errorText_ = errorStream_.str();
         goto unlock;
       }
     }
+  }
 
-    if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
-      result = snd_pcm_drop( handle[1] );
+  if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
+    state = snd_pcm_state( handle[1] );
+    if ( state != SND_PCM_STATE_PREPARED ) {
+      result = snd_pcm_prepare( handle[1] );
       if ( result < 0 ) {
-        errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror( result ) << ".";
+        errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror( result ) << ".";
         errorText_ = errorStream_.str();
         goto unlock;
       }
     }
+  }
 
-  unlock:
-    MUTEX_UNLOCK( &stream_.mutex );
+  stream_.state = STREAM_RUNNING;
 
-    if ( result >= 0 ) return;
-    error( RtError::SYSTEM_ERROR );
+ unlock:
+  MUTEX_UNLOCK( &stream_.mutex );
+
+  pthread_cond_signal( &apiInfo->runnable );
+
+  if ( result >= 0 ) return;
+  error( RtError::SYSTEM_ERROR );
+}
+
+void RtApiAlsa :: stopStream()
+{
+  verifyStream();
+  if ( stream_.state == STREAM_STOPPED ) {
+    errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!";
+    error( RtError::WARNING );
+    return;
   }
 
-  void RtApiAlsa :: abortStream()
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_STOPPED ) {
-      errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!";
-      error( RtError::WARNING );
-      return;
-    }
+  MUTEX_LOCK( &stream_.mutex );
 
-    // Change the state before the lock to improve shutdown response.
-    stream_.state = STREAM_STOPPED;
-    MUTEX_LOCK( &stream_.mutex );
+  if ( stream_.state == STREAM_STOPPED ) {
+    MUTEX_UNLOCK( &stream_.mutex );
+    return;
+  }
 
-    int result = 0;
-    AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
-    snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+  int result = 0;
+  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
+  snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+    if ( apiInfo->synchronized ) 
       result = snd_pcm_drop( handle[0] );
-      if ( result < 0 ) {
-        errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror( result ) << ".";
-        errorText_ = errorStream_.str();
-        goto unlock;
-      }
+    else
+      result = snd_pcm_drain( handle[0] );
+    if ( result < 0 ) {
+      errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror( result ) << ".";
+      errorText_ = errorStream_.str();
+      goto unlock;
     }
+  }
 
-    if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
-      result = snd_pcm_drop( handle[1] );
-      if ( result < 0 ) {
-        errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror( result ) << ".";
-        errorText_ = errorStream_.str();
-        goto unlock;
-      }
+  if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
+    result = snd_pcm_drop( handle[1] );
+    if ( result < 0 ) {
+      errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror( result ) << ".";
+      errorText_ = errorStream_.str();
+      goto unlock;
     }
+  }
 
-  unlock:
-    MUTEX_UNLOCK( &stream_.mutex );
+ unlock:
+  stream_.state = STREAM_STOPPED;
+  MUTEX_UNLOCK( &stream_.mutex );
+
+  if ( result >= 0 ) return;
+  error( RtError::SYSTEM_ERROR );
+}
 
-    if ( result >= 0 ) return;
-    error( RtError::SYSTEM_ERROR );
+void RtApiAlsa :: abortStream()
+{
+  verifyStream();
+  if ( stream_.state == STREAM_STOPPED ) {
+    errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!";
+    error( RtError::WARNING );
+    return;
   }
 
-  void RtApiAlsa :: callbackEvent()
-  {
-    AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
-    if ( stream_.state == STREAM_STOPPED ) {
-      MUTEX_LOCK( &stream_.mutex );
-      pthread_cond_wait( &apiInfo->runnable, &stream_.mutex );
-      if ( stream_.state != STREAM_RUNNING ) {
-        MUTEX_UNLOCK( &stream_.mutex );
-        return;
-      }
-      MUTEX_UNLOCK( &stream_.mutex );
-    }
+  MUTEX_LOCK( &stream_.mutex );
 
-    if ( stream_.state == STREAM_CLOSED ) {
-      errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!";
-      error( RtError::WARNING );
-      return;
-    }
+  if ( stream_.state == STREAM_STOPPED ) {
+    MUTEX_UNLOCK( &stream_.mutex );
+    return;
+  }
 
-    int doStopStream = 0;
-    RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
-    double streamTime = getStreamTime();
-    RtAudioStreamStatus status = 0;
-    if ( stream_.mode != INPUT && apiInfo->xrun[0] == true ) {
-      status |= RTAUDIO_OUTPUT_UNDERFLOW;
-      apiInfo->xrun[0] = false;
+  int result = 0;
+  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
+  snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+    result = snd_pcm_drop( handle[0] );
+    if ( result < 0 ) {
+      errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror( result ) << ".";
+      errorText_ = errorStream_.str();
+      goto unlock;
     }
-    if ( stream_.mode != OUTPUT && apiInfo->xrun[1] == true ) {
-      status |= RTAUDIO_INPUT_OVERFLOW;
-      apiInfo->xrun[1] = false;
+  }
+
+  if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {
+    result = snd_pcm_drop( handle[1] );
+    if ( result < 0 ) {
+      errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror( result ) << ".";
+      errorText_ = errorStream_.str();
+      goto unlock;
     }
-    doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
-                             stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
+  }
 
-    if ( doStopStream == 2 ) {
-      abortStream();
+ unlock:
+  stream_.state = STREAM_STOPPED;
+  MUTEX_UNLOCK( &stream_.mutex );
+
+  if ( result >= 0 ) return;
+  error( RtError::SYSTEM_ERROR );
+}
+
+void RtApiAlsa :: callbackEvent()
+{
+  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
+  if ( stream_.state == STREAM_STOPPED ) {
+    MUTEX_LOCK( &stream_.mutex );
+    pthread_cond_wait( &apiInfo->runnable, &stream_.mutex );
+    if ( stream_.state != STREAM_RUNNING ) {
+      MUTEX_UNLOCK( &stream_.mutex );
       return;
     }
+    MUTEX_UNLOCK( &stream_.mutex );
+  }
 
-    MUTEX_LOCK( &stream_.mutex );
+  if ( stream_.state == STREAM_CLOSED ) {
+    errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!";
+    error( RtError::WARNING );
+    return;
+  }
 
-    // The state might change while waiting on a mutex.
-    if ( stream_.state == STREAM_STOPPED ) goto unlock;
+  int doStopStream = 0;
+  RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
+  double streamTime = getStreamTime();
+  RtAudioStreamStatus status = 0;
+  if ( stream_.mode != INPUT && apiInfo->xrun[0] == true ) {
+    status |= RTAUDIO_OUTPUT_UNDERFLOW;
+    apiInfo->xrun[0] = false;
+  }
+  if ( stream_.mode != OUTPUT && apiInfo->xrun[1] == true ) {
+    status |= RTAUDIO_INPUT_OVERFLOW;
+    apiInfo->xrun[1] = false;
+  }
+  doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
+                           stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
 
-    int result;
-    char *buffer;
-    int channels;
-    snd_pcm_t **handle;
-    snd_pcm_sframes_t frames;
-    RtAudioFormat format;
-    handle = (snd_pcm_t **) apiInfo->handles;
+  if ( doStopStream == 2 ) {
+    abortStream();
+    return;
+  }
 
-    if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
+  MUTEX_LOCK( &stream_.mutex );
 
-      // Setup parameters.
-      if ( stream_.doConvertBuffer[1] ) {
-        buffer = stream_.deviceBuffer;
-        channels = stream_.nDeviceChannels[1];
-        format = stream_.deviceFormat[1];
-      }
-      else {
-        buffer = stream_.userBuffer[1];
-        channels = stream_.nUserChannels[1];
-        format = stream_.userFormat;
-      }
+  // The state might change while waiting on a mutex.
+  if ( stream_.state == STREAM_STOPPED ) goto unlock;
 
-      // Read samples from device in interleaved/non-interleaved format.
-      if ( stream_.deviceInterleaved[1] )
-        result = snd_pcm_readi( handle[1], buffer, stream_.bufferSize );
-      else {
-        void *bufs[channels];
-        size_t offset = stream_.bufferSize * formatBytes( format );
-        for ( int i=0; i<channels; i++ )
-          bufs[i] = (void *) (buffer + (i * offset));
-        result = snd_pcm_readn( handle[1], bufs, stream_.bufferSize );
-      }
+  int result;
+  char *buffer;
+  int channels;
+  snd_pcm_t **handle;
+  snd_pcm_sframes_t frames;
+  RtAudioFormat format;
+  handle = (snd_pcm_t **) apiInfo->handles;
 
-      if ( result < (int) stream_.bufferSize ) {
-        // Either an error or overrun occured.
-        if ( result == -EPIPE ) {
-          snd_pcm_state_t state = snd_pcm_state( handle[1] );
-          if ( state == SND_PCM_STATE_XRUN ) {
-            apiInfo->xrun[1] = true;
-            result = snd_pcm_prepare( handle[1] );
-            if ( result < 0 ) {
-              errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror( result ) << ".";
-              errorText_ = errorStream_.str();
-            }
-          }
-          else {
-            errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
+
+    // Setup parameters.
+    if ( stream_.doConvertBuffer[1] ) {
+      buffer = stream_.deviceBuffer;
+      channels = stream_.nDeviceChannels[1];
+      format = stream_.deviceFormat[1];
+    }
+    else {
+      buffer = stream_.userBuffer[1];
+      channels = stream_.nUserChannels[1];
+      format = stream_.userFormat;
+    }
+
+    // Read samples from device in interleaved/non-interleaved format.
+    if ( stream_.deviceInterleaved[1] )
+      result = snd_pcm_readi( handle[1], buffer, stream_.bufferSize );
+    else {
+      void *bufs[channels];
+      size_t offset = stream_.bufferSize * formatBytes( format );
+      for ( int i=0; i<channels; i++ )
+        bufs[i] = (void *) (buffer + (i * offset));
+      result = snd_pcm_readn( handle[1], bufs, stream_.bufferSize );
+    }
+
+    if ( result < (int) stream_.bufferSize ) {
+      // Either an error or overrun occured.
+      if ( result == -EPIPE ) {
+        snd_pcm_state_t state = snd_pcm_state( handle[1] );
+        if ( state == SND_PCM_STATE_XRUN ) {
+          apiInfo->xrun[1] = true;
+          result = snd_pcm_prepare( handle[1] );
+          if ( result < 0 ) {
+            errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror( result ) << ".";
             errorText_ = errorStream_.str();
           }
         }
         else {
-          errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror( result ) << ".";
+          errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
           errorText_ = errorStream_.str();
         }
-        error( RtError::WARNING );
-        goto tryOutput;
       }
+      else {
+        errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror( result ) << ".";
+        errorText_ = errorStream_.str();
+      }
+      error( RtError::WARNING );
+      goto tryOutput;
+    }
 
-      // Do byte swapping if necessary.
-      if ( stream_.doByteSwap[1] )
-        byteSwapBuffer( buffer, stream_.bufferSize * channels, format );
-
-      // Do buffer conversion if necessary.
-      if ( stream_.doConvertBuffer[1] )
-        convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
+    // Do byte swapping if necessary.
+    if ( stream_.doByteSwap[1] )
+      byteSwapBuffer( buffer, stream_.bufferSize * channels, format );
 
-      // Check stream latency
-      result = snd_pcm_delay( handle[1], &frames );
-      if ( result == 0 && frames > 0 ) stream_.latency[1] = frames;
-    }
+    // Do buffer conversion if necessary.
+    if ( stream_.doConvertBuffer[1] )
+      convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
 
-  tryOutput:
+    // Check stream latency
+    result = snd_pcm_delay( handle[1], &frames );
+    if ( result == 0 && frames > 0 ) stream_.latency[1] = frames;
+  }
 
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+ tryOutput:
 
-      // Setup parameters and do buffer conversion if necessary.
-      if ( stream_.doConvertBuffer[0] ) {
-        buffer = stream_.deviceBuffer;
-        convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
-        channels = stream_.nDeviceChannels[0];
-        format = stream_.deviceFormat[0];
-      }
-      else {
-        buffer = stream_.userBuffer[0];
-        channels = stream_.nUserChannels[0];
-        format = stream_.userFormat;
-      }
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
 
-      // Do byte swapping if necessary.
-      if ( stream_.doByteSwap[0] )
-        byteSwapBuffer(buffer, stream_.bufferSize * channels, format);
+    // Setup parameters and do buffer conversion if necessary.
+    if ( stream_.doConvertBuffer[0] ) {
+      buffer = stream_.deviceBuffer;
+      convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
+      channels = stream_.nDeviceChannels[0];
+      format = stream_.deviceFormat[0];
+    }
+    else {
+      buffer = stream_.userBuffer[0];
+      channels = stream_.nUserChannels[0];
+      format = stream_.userFormat;
+    }
 
-      // Write samples to device in interleaved/non-interleaved format.
-      if ( stream_.deviceInterleaved[0] )
-        result = snd_pcm_writei( handle[0], buffer, stream_.bufferSize );
-      else {
-        void *bufs[channels];
-        size_t offset = stream_.bufferSize * formatBytes( format );
-        for ( int i=0; i<channels; i++ )
-          bufs[i] = (void *) (buffer + (i * offset));
-        result = snd_pcm_writen( handle[0], bufs, stream_.bufferSize );
-      }
+    // Do byte swapping if necessary.
+    if ( stream_.doByteSwap[0] )
+      byteSwapBuffer(buffer, stream_.bufferSize * channels, format);
 
-      if ( result < (int) stream_.bufferSize ) {
-        // Either an error or underrun occured.
-        if ( result == -EPIPE ) {
-          snd_pcm_state_t state = snd_pcm_state( handle[0] );
-          if ( state == SND_PCM_STATE_XRUN ) {
-            apiInfo->xrun[0] = true;
-            result = snd_pcm_prepare( handle[0] );
-            if ( result < 0 ) {
-              errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << ".";
-              errorText_ = errorStream_.str();
-            }
-          }
-          else {
-            errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
+    // Write samples to device in interleaved/non-interleaved format.
+    if ( stream_.deviceInterleaved[0] )
+      result = snd_pcm_writei( handle[0], buffer, stream_.bufferSize );
+    else {
+      void *bufs[channels];
+      size_t offset = stream_.bufferSize * formatBytes( format );
+      for ( int i=0; i<channels; i++ )
+        bufs[i] = (void *) (buffer + (i * offset));
+      result = snd_pcm_writen( handle[0], bufs, stream_.bufferSize );
+    }
+
+    if ( result < (int) stream_.bufferSize ) {
+      // Either an error or underrun occured.
+      if ( result == -EPIPE ) {
+        snd_pcm_state_t state = snd_pcm_state( handle[0] );
+        if ( state == SND_PCM_STATE_XRUN ) {
+          apiInfo->xrun[0] = true;
+          result = snd_pcm_prepare( handle[0] );
+          if ( result < 0 ) {
+            errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << ".";
             errorText_ = errorStream_.str();
           }
         }
         else {
-          errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror( result ) << ".";
+          errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";
           errorText_ = errorStream_.str();
         }
-        error( RtError::WARNING );
-        goto unlock;
       }
-
-      // Check stream latency
-      result = snd_pcm_delay( handle[0], &frames );
-      if ( result == 0 && frames > 0 ) stream_.latency[0] = frames;
+      else {
+        errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror( result ) << ".";
+        errorText_ = errorStream_.str();
+      }
+      error( RtError::WARNING );
+      goto unlock;
     }
 
-  unlock:
-    MUTEX_UNLOCK( &stream_.mutex );
-
-    RtApi::tickStreamTime();
-    if ( doStopStream == 1 ) this->stopStream();
+    // Check stream latency
+    result = snd_pcm_delay( handle[0], &frames );
+    if ( result == 0 && frames > 0 ) stream_.latency[0] = frames;
   }
 
-  extern "C" void *alsaCallbackHandler( void *ptr )
-  {
-    CallbackInfo *info = (CallbackInfo *) ptr;
-    RtApiAlsa *object = (RtApiAlsa *) info->object;
-    bool *isRunning = &info->isRunning;
+ unlock:
+  MUTEX_UNLOCK( &stream_.mutex );
 
-    while ( *isRunning == true ) {
-      pthread_testcancel();
-      object->callbackEvent();
-    }
+  RtApi::tickStreamTime();
+  if ( doStopStream == 1 ) this->stopStream();
+}
+
+extern "C" void *alsaCallbackHandler( void *ptr )
+{
+  CallbackInfo *info = (CallbackInfo *) ptr;
+  RtApiAlsa *object = (RtApiAlsa *) info->object;
+  bool *isRunning = &info->isRunning;
 
-    pthread_exit( NULL );
+  while ( *isRunning == true ) {
+    pthread_testcancel();
+    object->callbackEvent();
   }
 
-  //******************** End of __LINUX_ALSA__ *********************//
+  pthread_exit( NULL );
+}
+
+//******************** End of __LINUX_ALSA__ *********************//
 #endif
 
 
@@ -6201,1587 +6244,1593 @@ bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,
 #include <errno.h>
 #include <math.h>
 
-  extern "C" void *ossCallbackHandler(void * ptr);
+extern "C" void *ossCallbackHandler(void * ptr);
 
-  // A structure to hold various information related to the OSS API
-  // implementation.
-  struct OssHandle {
-    int id[2];    // device ids
-    bool xrun[2];
-    bool triggered;
-    pthread_cond_t runnable;
-
-    OssHandle()
-      :triggered(false) { id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
-  };
+// A structure to hold various information related to the OSS API
+// implementation.
+struct OssHandle {
+  int id[2];    // device ids
+  bool xrun[2];
+  bool triggered;
+  pthread_cond_t runnable;
 
-  RtApiOss :: RtApiOss()
-  {
-    // Nothing to do here.
-  }
+  OssHandle()
+    :triggered(false) { id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
+};
 
-  RtApiOss :: ~RtApiOss()
-  {
-    if ( stream_.state != STREAM_CLOSED ) closeStream();
-  }
+RtApiOss :: RtApiOss()
+{
+  // Nothing to do here.
+}
 
-  unsigned int RtApiOss :: getDeviceCount( void )
-  {
-    int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
-    if ( mixerfd == -1 ) {
-      errorText_ = "RtApiOss::getDeviceCount: error opening '/dev/mixer'.";
-      error( RtError::WARNING );
-      return 0;
-    }
+RtApiOss :: ~RtApiOss()
+{
+  if ( stream_.state != STREAM_CLOSED ) closeStream();
+}
 
-    oss_sysinfo sysinfo;
-    if ( ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ) == -1 ) {
-      close( mixerfd );
-      errorText_ = "RtApiOss::getDeviceCount: error getting sysinfo, OSS version >= 4.0 is required.";
-      error( RtError::WARNING );
-      return 0;
-    }
+unsigned int RtApiOss :: getDeviceCount( void )
+{
+  int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
+  if ( mixerfd == -1 ) {
+    errorText_ = "RtApiOss::getDeviceCount: error opening '/dev/mixer'.";
+    error( RtError::WARNING );
+    return 0;
+  }
 
+  oss_sysinfo sysinfo;
+  if ( ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ) == -1 ) {
     close( mixerfd );
-    return sysinfo.numaudios;
+    errorText_ = "RtApiOss::getDeviceCount: error getting sysinfo, OSS version >= 4.0 is required.";
+    error( RtError::WARNING );
+    return 0;
   }
 
-  RtAudio::DeviceInfo RtApiOss :: getDeviceInfo( unsigned int device )
-  {
-    RtAudio::DeviceInfo info;
-    info.probed = false;
+  close( mixerfd );
+  return sysinfo.numaudios;
+}
 
-    int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
-    if ( mixerfd == -1 ) {
-      errorText_ = "RtApiOss::getDeviceInfo: error opening '/dev/mixer'.";
-      error( RtError::WARNING );
-      return info;
-    }
+RtAudio::DeviceInfo RtApiOss :: getDeviceInfo( unsigned int device )
+{
+  RtAudio::DeviceInfo info;
+  info.probed = false;
 
-    oss_sysinfo sysinfo;
-    int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
-    if ( result == -1 ) {
-      close( mixerfd );
-      errorText_ = "RtApiOss::getDeviceInfo: error getting sysinfo, OSS version >= 4.0 is required.";
-      error( RtError::WARNING );
-      return info;
-    }
+  int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
+  if ( mixerfd == -1 ) {
+    errorText_ = "RtApiOss::getDeviceInfo: error opening '/dev/mixer'.";
+    error( RtError::WARNING );
+    return info;
+  }
 
-    unsigned nDevices = sysinfo.numaudios;
-    if ( nDevices == 0 ) {
-      close( mixerfd );
-      errorText_ = "RtApiOss::getDeviceInfo: no devices found!";
-      error( RtError::INVALID_USE );
-    }
+  oss_sysinfo sysinfo;
+  int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
+  if ( result == -1 ) {
+    close( mixerfd );
+    errorText_ = "RtApiOss::getDeviceInfo: error getting sysinfo, OSS version >= 4.0 is required.";
+    error( RtError::WARNING );
+    return info;
+  }
 
-    if ( device >= nDevices ) {
-      close( mixerfd );
-      errorText_ = "RtApiOss::getDeviceInfo: device ID is invalid!";
-      error( RtError::INVALID_USE );
-    }
+  unsigned nDevices = sysinfo.numaudios;
+  if ( nDevices == 0 ) {
+    close( mixerfd );
+    errorText_ = "RtApiOss::getDeviceInfo: no devices found!";
+    error( RtError::INVALID_USE );
+  }
 
-    oss_audioinfo ainfo;
-    ainfo.dev = device;
-    result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
+  if ( device >= nDevices ) {
     close( mixerfd );
-    if ( result == -1 ) {
-      errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
-    }
+    errorText_ = "RtApiOss::getDeviceInfo: device ID is invalid!";
+    error( RtError::INVALID_USE );
+  }
 
-    // Probe channels
-    if ( ainfo.caps & PCM_CAP_OUTPUT ) info.outputChannels = ainfo.max_channels;
-    if ( ainfo.caps & PCM_CAP_INPUT ) info.inputChannels = ainfo.max_channels;
-    if ( ainfo.caps & PCM_CAP_DUPLEX ) {
-      if ( info.outputChannels > 0 && info.inputChannels > 0 && ainfo.caps & PCM_CAP_DUPLEX )
-        info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
-    }
-
-    // Probe data formats ... do for input
-    unsigned long mask = ainfo.iformats;
-    if ( mask & AFMT_S16_LE || mask & AFMT_S16_BE )
-      info.nativeFormats |= RTAUDIO_SINT16;
-    if ( mask & AFMT_S8 )
-      info.nativeFormats |= RTAUDIO_SINT8;
-    if ( mask & AFMT_S32_LE || mask & AFMT_S32_BE )
-      info.nativeFormats |= RTAUDIO_SINT32;
-    if ( mask & AFMT_FLOAT )
-      info.nativeFormats |= RTAUDIO_FLOAT32;
-    if ( mask & AFMT_S24_LE || mask & AFMT_S24_BE )
-      info.nativeFormats |= RTAUDIO_SINT24;
-
-    // Check that we have at least one supported format
-    if ( info.nativeFormats == 0 ) {
-      errorStream_ << "RtApiOss::getDeviceInfo: device (" << ainfo.name << ") data format not supported by RtAudio.";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-      return info;
-    }
+  oss_audioinfo ainfo;
+  ainfo.dev = device;
+  result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
+  close( mixerfd );
+  if ( result == -1 ) {
+    errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return info;
+  }
 
-    // Probe the supported sample rates.
-    info.sampleRates.clear();
-    if ( ainfo.nrates ) {
-      for ( unsigned int i=0; i<ainfo.nrates; i++ ) {
-        for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
-          if ( ainfo.rates[i] == SAMPLE_RATES[k] ) {
-            info.sampleRates.push_back( SAMPLE_RATES[k] );
-            break;
-          }
-        }
-      }
-    }
-    else {
-      // Check min and max rate values;
+  // Probe channels
+  if ( ainfo.caps & PCM_CAP_OUTPUT ) info.outputChannels = ainfo.max_channels;
+  if ( ainfo.caps & PCM_CAP_INPUT ) info.inputChannels = ainfo.max_channels;
+  if ( ainfo.caps & PCM_CAP_DUPLEX ) {
+    if ( info.outputChannels > 0 && info.inputChannels > 0 && ainfo.caps & PCM_CAP_DUPLEX )
+      info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
+  }
+
+  // Probe data formats ... do for input
+  unsigned long mask = ainfo.iformats;
+  if ( mask & AFMT_S16_LE || mask & AFMT_S16_BE )
+    info.nativeFormats |= RTAUDIO_SINT16;
+  if ( mask & AFMT_S8 )
+    info.nativeFormats |= RTAUDIO_SINT8;
+  if ( mask & AFMT_S32_LE || mask & AFMT_S32_BE )
+    info.nativeFormats |= RTAUDIO_SINT32;
+  if ( mask & AFMT_FLOAT )
+    info.nativeFormats |= RTAUDIO_FLOAT32;
+  if ( mask & AFMT_S24_LE || mask & AFMT_S24_BE )
+    info.nativeFormats |= RTAUDIO_SINT24;
+
+  // Check that we have at least one supported format
+  if ( info.nativeFormats == 0 ) {
+    errorStream_ << "RtApiOss::getDeviceInfo: device (" << ainfo.name << ") data format not supported by RtAudio.";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+    return info;
+  }
+
+  // Probe the supported sample rates.
+  info.sampleRates.clear();
+  if ( ainfo.nrates ) {
+    for ( unsigned int i=0; i<ainfo.nrates; i++ ) {
       for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
-        if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] )
+        if ( ainfo.rates[i] == SAMPLE_RATES[k] ) {
           info.sampleRates.push_back( SAMPLE_RATES[k] );
+          break;
+        }
       }
     }
-
-    if ( info.sampleRates.size() == 0 ) {
-      errorStream_ << "RtApiOss::getDeviceInfo: no supported sample rates found for device (" << ainfo.name << ").";
-      errorText_ = errorStream_.str();
-      error( RtError::WARNING );
-    }
-    else {
-      info.probed = true;
-      info.name = ainfo.name;
+  }
+  else {
+    // Check min and max rate values;
+    for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
+      if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] )
+        info.sampleRates.push_back( SAMPLE_RATES[k] );
     }
+  }
 
-    return info;
+  if ( info.sampleRates.size() == 0 ) {
+    errorStream_ << "RtApiOss::getDeviceInfo: no supported sample rates found for device (" << ainfo.name << ").";
+    errorText_ = errorStream_.str();
+    error( RtError::WARNING );
+  }
+  else {
+    info.probed = true;
+    info.name = ainfo.name;
   }
 
+  return info;
+}
 
-  bool RtApiOss :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
-                                    unsigned int firstChannel, unsigned int sampleRate,
-                                    RtAudioFormat format, unsigned int *bufferSize,
-                                    RtAudio::StreamOptions *options )
-  {
-    int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
-    if ( mixerfd == -1 ) {
-      errorText_ = "RtApiOss::probeDeviceOpen: error opening '/dev/mixer'.";
-      return FAILURE;
-    }
 
-    oss_sysinfo sysinfo;
-    int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
-    if ( result == -1 ) {
-      close( mixerfd );
-      errorText_ = "RtApiOss::probeDeviceOpen: error getting sysinfo, OSS version >= 4.0 is required.";
-      return FAILURE;
-    }
+bool RtApiOss :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
+                                  unsigned int firstChannel, unsigned int sampleRate,
+                                  RtAudioFormat format, unsigned int *bufferSize,
+                                  RtAudio::StreamOptions *options )
+{
+  int mixerfd = open( "/dev/mixer", O_RDWR, 0 );
+  if ( mixerfd == -1 ) {
+    errorText_ = "RtApiOss::probeDeviceOpen: error opening '/dev/mixer'.";
+    return FAILURE;
+  }
 
-    unsigned nDevices = sysinfo.numaudios;
-    if ( nDevices == 0 ) {
-      // This should not happen because a check is made before this function is called.
-      close( mixerfd );
-      errorText_ = "RtApiOss::probeDeviceOpen: no devices found!";
-      return FAILURE;
-    }
+  oss_sysinfo sysinfo;
+  int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );
+  if ( result == -1 ) {
+    close( mixerfd );
+    errorText_ = "RtApiOss::probeDeviceOpen: error getting sysinfo, OSS version >= 4.0 is required.";
+    return FAILURE;
+  }
 
-    if ( device >= nDevices ) {
-      // This should not happen because a check is made before this function is called.
-      close( mixerfd );
-      errorText_ = "RtApiOss::probeDeviceOpen: device ID is invalid!";
-      return FAILURE;
-    }
+  unsigned nDevices = sysinfo.numaudios;
+  if ( nDevices == 0 ) {
+    // This should not happen because a check is made before this function is called.
+    close( mixerfd );
+    errorText_ = "RtApiOss::probeDeviceOpen: no devices found!";
+    return FAILURE;
+  }
 
-    oss_audioinfo ainfo;
-    ainfo.dev = device;
-    result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
+  if ( device >= nDevices ) {
+    // This should not happen because a check is made before this function is called.
     close( mixerfd );
-    if ( result == -1 ) {
-      errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+    errorText_ = "RtApiOss::probeDeviceOpen: device ID is invalid!";
+    return FAILURE;
+  }
 
-    // Check if device supports input or output
-    if ( ( mode == OUTPUT && !( ainfo.caps & PCM_CAP_OUTPUT ) ) ||
-         ( mode == INPUT && !( ainfo.caps & PCM_CAP_INPUT ) ) ) {
-      if ( mode == OUTPUT )
-        errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support output.";
-      else
-        errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support input.";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  oss_audioinfo ainfo;
+  ainfo.dev = device;
+  result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );
+  close( mixerfd );
+  if ( result == -1 ) {
+    errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    int flags = 0;
-    OssHandle *handle = (OssHandle *) stream_.apiHandle;
+  // Check if device supports input or output
+  if ( ( mode == OUTPUT && !( ainfo.caps & PCM_CAP_OUTPUT ) ) ||
+       ( mode == INPUT && !( ainfo.caps & PCM_CAP_INPUT ) ) ) {
     if ( mode == OUTPUT )
-      flags |= O_WRONLY;
-    else { // mode == INPUT
-      if (stream_.mode == OUTPUT && stream_.device[0] == device) {
-        // We just set the same device for playback ... close and reopen for duplex (OSS only).
-        close( handle->id[0] );
-        handle->id[0] = 0;
-        if ( !( ainfo.caps & PCM_CAP_DUPLEX ) ) {
-          errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support duplex mode.";
-          errorText_ = errorStream_.str();
-          return FAILURE;
-        }
-        // Check that the number previously set channels is the same.
-        if ( stream_.nUserChannels[0] != channels ) {
-          errorStream_ << "RtApiOss::probeDeviceOpen: input/output channels must be equal for OSS duplex device (" << ainfo.name << ").";
-          errorText_ = errorStream_.str();
-          return FAILURE;
-        }
-        flags |= O_RDWR;
+      errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support output.";
+    else
+      errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support input.";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
+
+  int flags = 0;
+  OssHandle *handle = (OssHandle *) stream_.apiHandle;
+  if ( mode == OUTPUT )
+    flags |= O_WRONLY;
+  else { // mode == INPUT
+    if (stream_.mode == OUTPUT && stream_.device[0] == device) {
+      // We just set the same device for playback ... close and reopen for duplex (OSS only).
+      close( handle->id[0] );
+      handle->id[0] = 0;
+      if ( !( ainfo.caps & PCM_CAP_DUPLEX ) ) {
+        errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support duplex mode.";
+        errorText_ = errorStream_.str();
+        return FAILURE;
       }
-      else
-        flags |= O_RDONLY;
+      // Check that the number previously set channels is the same.
+      if ( stream_.nUserChannels[0] != channels ) {
+        errorStream_ << "RtApiOss::probeDeviceOpen: input/output channels must be equal for OSS duplex device (" << ainfo.name << ").";
+        errorText_ = errorStream_.str();
+        return FAILURE;
+      }
+      flags |= O_RDWR;
     }
+    else
+      flags |= O_RDONLY;
+  }
 
-    // Set exclusive access if specified.
-    if ( options && options->flags & RTAUDIO_HOG_DEVICE ) flags |= O_EXCL;
+  // Set exclusive access if specified.
+  if ( options && options->flags & RTAUDIO_HOG_DEVICE ) flags |= O_EXCL;
 
-    // Try to open the device.
-    int fd;
-    fd = open( ainfo.devnode, flags, 0 );
-    if ( fd == -1 ) {
-      if ( errno == EBUSY )
-        errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") is busy.";
-      else
-        errorStream_ << "RtApiOss::probeDeviceOpen: error opening device (" << ainfo.name << ").";
-      errorText_ = errorStream_.str();
-      return FAILURE;
+  // Try to open the device.
+  int fd;
+  fd = open( ainfo.devnode, flags, 0 );
+  if ( fd == -1 ) {
+    if ( errno == EBUSY )
+      errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") is busy.";
+    else
+      errorStream_ << "RtApiOss::probeDeviceOpen: error opening device (" << ainfo.name << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
+
+  // For duplex operation, specifically set this mode (this doesn't seem to work).
+  /*
+    if ( flags | O_RDWR ) {
+    result = ioctl( fd, SNDCTL_DSP_SETDUPLEX, NULL );
+    if ( result == -1) {
+    errorStream_ << "RtApiOss::probeDeviceOpen: error setting duplex mode for device (" << ainfo.name << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+    }
     }
+  */
 
-    // For duplex operation, specifically set this mode (this doesn't seem to work).
-    /*
-      if ( flags | O_RDWR ) {
-      result = ioctl( fd, SNDCTL_DSP_SETDUPLEX, NULL );
-      if ( result == -1) {
-      errorStream_ << "RtApiOss::probeDeviceOpen: error setting duplex mode for device (" << ainfo.name << ").";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-      }
-      }
-    */
+  // Check the device channel support.
+  stream_.nUserChannels[mode] = channels;
+  if ( ainfo.max_channels < (int)(channels + firstChannel) ) {
+    close( fd );
+    errorStream_ << "RtApiOss::probeDeviceOpen: the device (" << ainfo.name << ") does not support requested channel parameters.";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    // Check the device channel support.
-    stream_.nUserChannels[mode] = channels;
-    if ( ainfo.max_channels < (int)(channels + firstChannel) ) {
-      close( fd );
-      errorStream_ << "RtApiOss::probeDeviceOpen: the device (" << ainfo.name << ") does not support requested channel parameters.";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  // Set the number of channels.
+  int deviceChannels = channels + firstChannel;
+  result = ioctl( fd, SNDCTL_DSP_CHANNELS, &deviceChannels );
+  if ( result == -1 || deviceChannels < (int)(channels + firstChannel) ) {
+    close( fd );
+    errorStream_ << "RtApiOss::probeDeviceOpen: error setting channel parameters on device (" << ainfo.name << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
+  stream_.nDeviceChannels[mode] = deviceChannels;
 
-    // Set the number of channels.
-    int deviceChannels = channels + firstChannel;
-    result = ioctl( fd, SNDCTL_DSP_CHANNELS, &deviceChannels );
-    if ( result == -1 || deviceChannels < (int)(channels + firstChannel) ) {
-      close( fd );
-      errorStream_ << "RtApiOss::probeDeviceOpen: error setting channel parameters on device (" << ainfo.name << ").";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
-    stream_.nDeviceChannels[mode] = deviceChannels;
+  // Get the data format mask
+  int mask;
+  result = ioctl( fd, SNDCTL_DSP_GETFMTS, &mask );
+  if ( result == -1 ) {
+    close( fd );
+    errorStream_ << "RtApiOss::probeDeviceOpen: error getting device (" << ainfo.name << ") data formats.";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    // Get the data format mask
-    int mask;
-    result = ioctl( fd, SNDCTL_DSP_GETFMTS, &mask );
-    if ( result == -1 ) {
-      close( fd );
-      errorStream_ << "RtApiOss::probeDeviceOpen: error getting device (" << ainfo.name << ") data formats.";
-      errorText_ = errorStream_.str();
-      return FAILURE;
+  // Determine how to set the device format.
+  stream_.userFormat = format;
+  int deviceFormat = -1;
+  stream_.doByteSwap[mode] = false;
+  if ( format == RTAUDIO_SINT8 ) {
+    if ( mask & AFMT_S8 ) {
+      deviceFormat = AFMT_S8;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT8;
     }
-
-    // Determine how to set the device format.
-    stream_.userFormat = format;
-    int deviceFormat = -1;
-    stream_.doByteSwap[mode] = false;
-    if ( format == RTAUDIO_SINT8 ) {
-      if ( mask & AFMT_S8 ) {
-        deviceFormat = AFMT_S8;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT8;
-      }
+  }
+  else if ( format == RTAUDIO_SINT16 ) {
+    if ( mask & AFMT_S16_NE ) {
+      deviceFormat = AFMT_S16_NE;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT16;
     }
-    else if ( format == RTAUDIO_SINT16 ) {
-      if ( mask & AFMT_S16_NE ) {
-        deviceFormat = AFMT_S16_NE;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-      }
-      else if ( mask & AFMT_S16_OE ) {
-        deviceFormat = AFMT_S16_OE;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-        stream_.doByteSwap[mode] = true;
-      }
+    else if ( mask & AFMT_S16_OE ) {
+      deviceFormat = AFMT_S16_OE;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT16;
+      stream_.doByteSwap[mode] = true;
     }
-    else if ( format == RTAUDIO_SINT24 ) {
-      if ( mask & AFMT_S24_NE ) {
-        deviceFormat = AFMT_S24_NE;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT24;
-      }
-      else if ( mask & AFMT_S24_OE ) {
-        deviceFormat = AFMT_S24_OE;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT24;
-        stream_.doByteSwap[mode] = true;
-      }
+  }
+  else if ( format == RTAUDIO_SINT24 ) {
+    if ( mask & AFMT_S24_NE ) {
+      deviceFormat = AFMT_S24_NE;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT24;
     }
-    else if ( format == RTAUDIO_SINT32 ) {
-      if ( mask & AFMT_S32_NE ) {
-        deviceFormat = AFMT_S32_NE;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT32;
-      }
-      else if ( mask & AFMT_S32_OE ) {
-        deviceFormat = AFMT_S32_OE;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT32;
-        stream_.doByteSwap[mode] = true;
-      }
+    else if ( mask & AFMT_S24_OE ) {
+      deviceFormat = AFMT_S24_OE;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT24;
+      stream_.doByteSwap[mode] = true;
     }
-
-    if ( deviceFormat == -1 ) {
-      // The user requested format is not natively supported by the device.
-      if ( mask & AFMT_S16_NE ) {
-        deviceFormat = AFMT_S16_NE;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-      }
-      else if ( mask & AFMT_S32_NE ) {
-        deviceFormat = AFMT_S32_NE;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT32;
-      }
-      else if ( mask & AFMT_S24_NE ) {
-        deviceFormat = AFMT_S24_NE;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT24;
-      }
-      else if ( mask & AFMT_S16_OE ) {
-        deviceFormat = AFMT_S16_OE;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-        stream_.doByteSwap[mode] = true;
-      }
-      else if ( mask & AFMT_S32_OE ) {
-        deviceFormat = AFMT_S32_OE;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT32;
-        stream_.doByteSwap[mode] = true;
-      }
-      else if ( mask & AFMT_S24_OE ) {
-        deviceFormat = AFMT_S24_OE;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT24;
-        stream_.doByteSwap[mode] = true;
-      }
-      else if ( mask & AFMT_S8) {
-        deviceFormat = AFMT_S8;
-        stream_.deviceFormat[mode] = RTAUDIO_SINT8;
-      }
+  }
+  else if ( format == RTAUDIO_SINT32 ) {
+    if ( mask & AFMT_S32_NE ) {
+      deviceFormat = AFMT_S32_NE;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT32;
     }
-
-    if ( stream_.deviceFormat[mode] == 0 ) {
-      // This really shouldn't happen ...
-      close( fd );
-      errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") data format not supported by RtAudio.";
-      errorText_ = errorStream_.str();
-      return FAILURE;
+    else if ( mask & AFMT_S32_OE ) {
+      deviceFormat = AFMT_S32_OE;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT32;
+      stream_.doByteSwap[mode] = true;
     }
+  }
 
-    // Set the data format.
-    int temp = deviceFormat;
-    result = ioctl( fd, SNDCTL_DSP_SETFMT, &deviceFormat );
-    if ( result == -1 || deviceFormat != temp ) {
-      close( fd );
-      errorStream_ << "RtApiOss::probeDeviceOpen: error setting data format on device (" << ainfo.name << ").";
-      errorText_ = errorStream_.str();
-      return FAILURE;
+  if ( deviceFormat == -1 ) {
+    // The user requested format is not natively supported by the device.
+    if ( mask & AFMT_S16_NE ) {
+      deviceFormat = AFMT_S16_NE;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT16;
+    }
+    else if ( mask & AFMT_S32_NE ) {
+      deviceFormat = AFMT_S32_NE;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT32;
+    }
+    else if ( mask & AFMT_S24_NE ) {
+      deviceFormat = AFMT_S24_NE;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT24;
+    }
+    else if ( mask & AFMT_S16_OE ) {
+      deviceFormat = AFMT_S16_OE;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT16;
+      stream_.doByteSwap[mode] = true;
+    }
+    else if ( mask & AFMT_S32_OE ) {
+      deviceFormat = AFMT_S32_OE;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT32;
+      stream_.doByteSwap[mode] = true;
+    }
+    else if ( mask & AFMT_S24_OE ) {
+      deviceFormat = AFMT_S24_OE;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT24;
+      stream_.doByteSwap[mode] = true;
     }
-
-    // Attempt to set the buffer size.  According to OSS, the minimum
-    // number of buffers is two.  The supposed minimum buffer size is 16
-    // bytes, so that will be our lower bound.  The argument to this
-    // call is in the form 0xMMMMSSSS (hex), where the buffer size (in
-    // bytes) is given as 2^SSSS and the number of buffers as 2^MMMM.
-    // We'll check the actual value used near the end of the setup
-    // procedure.
-    int ossBufferBytes = *bufferSize * formatBytes( stream_.deviceFormat[mode] ) * deviceChannels;
-    if ( ossBufferBytes < 16 ) ossBufferBytes = 16;
-    int buffers = 0;
-    if ( options ) buffers = options->numberOfBuffers;
-    if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) buffers = 2;
-    if ( buffers < 2 ) buffers = 3;
-    temp = ((int) buffers << 16) + (int)( log10( (double)ossBufferBytes ) / log10( 2.0 ) );
-    result = ioctl( fd, SNDCTL_DSP_SETFRAGMENT, &temp );
-    if ( result == -1 ) {
-      close( fd );
-      errorStream_ << "RtApiOss::probeDeviceOpen: error setting buffer size on device (" << ainfo.name << ").";
-      errorText_ = errorStream_.str();
-      return FAILURE;
+    else if ( mask & AFMT_S8) {
+      deviceFormat = AFMT_S8;
+      stream_.deviceFormat[mode] = RTAUDIO_SINT8;
     }
-    stream_.nBuffers = buffers;
+  }
 
-    // Save buffer size (in sample frames).
-    *bufferSize = ossBufferBytes / ( formatBytes(stream_.deviceFormat[mode]) * deviceChannels );
-    stream_.bufferSize = *bufferSize;
+  if ( stream_.deviceFormat[mode] == 0 ) {
+    // This really shouldn't happen ...
+    close( fd );
+    errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") data format not supported by RtAudio.";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    // Set the sample rate.
-    int srate = sampleRate;
-    result = ioctl( fd, SNDCTL_DSP_SPEED, &srate );
-    if ( result == -1 ) {
-      close( fd );
-      errorStream_ << "RtApiOss::probeDeviceOpen: error setting sample rate (" << sampleRate << ") on device (" << ainfo.name << ").";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
+  // Set the data format.
+  int temp = deviceFormat;
+  result = ioctl( fd, SNDCTL_DSP_SETFMT, &deviceFormat );
+  if ( result == -1 || deviceFormat != temp ) {
+    close( fd );
+    errorStream_ << "RtApiOss::probeDeviceOpen: error setting data format on device (" << ainfo.name << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    // Verify the sample rate setup worked.
-    if ( abs( srate - sampleRate ) > 100 ) {
-      close( fd );
-      errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support sample rate (" << sampleRate << ").";
-      errorText_ = errorStream_.str();
-      return FAILURE;
-    }
-    stream_.sampleRate = sampleRate;
+  // Attempt to set the buffer size.  According to OSS, the minimum
+  // number of buffers is two.  The supposed minimum buffer size is 16
+  // bytes, so that will be our lower bound.  The argument to this
+  // call is in the form 0xMMMMSSSS (hex), where the buffer size (in
+  // bytes) is given as 2^SSSS and the number of buffers as 2^MMMM.
+  // We'll check the actual value used near the end of the setup
+  // procedure.
+  int ossBufferBytes = *bufferSize * formatBytes( stream_.deviceFormat[mode] ) * deviceChannels;
+  if ( ossBufferBytes < 16 ) ossBufferBytes = 16;
+  int buffers = 0;
+  if ( options ) buffers = options->numberOfBuffers;
+  if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) buffers = 2;
+  if ( buffers < 2 ) buffers = 3;
+  temp = ((int) buffers << 16) + (int)( log10( (double)ossBufferBytes ) / log10( 2.0 ) );
+  result = ioctl( fd, SNDCTL_DSP_SETFRAGMENT, &temp );
+  if ( result == -1 ) {
+    close( fd );
+    errorStream_ << "RtApiOss::probeDeviceOpen: error setting buffer size on device (" << ainfo.name << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
+  stream_.nBuffers = buffers;
 
-    if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device) {
-      // We're doing duplex setup here.
-      stream_.deviceFormat[0] = stream_.deviceFormat[1];
-      stream_.nDeviceChannels[0] = deviceChannels;
-    }
+  // Save buffer size (in sample frames).
+  *bufferSize = ossBufferBytes / ( formatBytes(stream_.deviceFormat[mode]) * deviceChannels );
+  stream_.bufferSize = *bufferSize;
 
-    // Set interleaving parameters.
-    stream_.userInterleaved = true;
-    stream_.deviceInterleaved[mode] =  true;
-    if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
-      stream_.userInterleaved = false;
+  // Set the sample rate.
+  int srate = sampleRate;
+  result = ioctl( fd, SNDCTL_DSP_SPEED, &srate );
+  if ( result == -1 ) {
+    close( fd );
+    errorStream_ << "RtApiOss::probeDeviceOpen: error setting sample rate (" << sampleRate << ") on device (" << ainfo.name << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
 
-    // Set flags for buffer conversion
-    stream_.doConvertBuffer[mode] = false;
-    if ( stream_.userFormat != stream_.deviceFormat[mode] )
-      stream_.doConvertBuffer[mode] = true;
-    if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
-      stream_.doConvertBuffer[mode] = true;
-    if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
-         stream_.nUserChannels[mode] > 1 )
-      stream_.doConvertBuffer[mode] = true;
+  // Verify the sample rate setup worked.
+  if ( abs( srate - sampleRate ) > 100 ) {
+    close( fd );
+    errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support sample rate (" << sampleRate << ").";
+    errorText_ = errorStream_.str();
+    return FAILURE;
+  }
+  stream_.sampleRate = sampleRate;
 
-    // Allocate the stream handles if necessary and then save.
-    if ( stream_.apiHandle == 0 ) {
-      try {
-        handle = new OssHandle;
-      }
-      catch ( std::bad_alloc& ) {
-        errorText_ = "RtApiOss::probeDeviceOpen: error allocating OssHandle memory.";
-        goto error;
-      }
+  if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device) {
+    // We're doing duplex setup here.
+    stream_.deviceFormat[0] = stream_.deviceFormat[1];
+    stream_.nDeviceChannels[0] = deviceChannels;
+  }
 
-      if ( pthread_cond_init( &handle->runnable, NULL ) ) {
-        errorText_ = "RtApiOss::probeDeviceOpen: error initializing pthread condition variable.";
-        goto error;
-      }
+  // Set interleaving parameters.
+  stream_.userInterleaved = true;
+  stream_.deviceInterleaved[mode] =  true;
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED )
+    stream_.userInterleaved = false;
+
+  // Set flags for buffer conversion
+  stream_.doConvertBuffer[mode] = false;
+  if ( stream_.userFormat != stream_.deviceFormat[mode] )
+    stream_.doConvertBuffer[mode] = true;
+  if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )
+    stream_.doConvertBuffer[mode] = true;
+  if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&
+       stream_.nUserChannels[mode] > 1 )
+    stream_.doConvertBuffer[mode] = true;
 
-      stream_.apiHandle = (void *) handle;
+  // Allocate the stream handles if necessary and then save.
+  if ( stream_.apiHandle == 0 ) {
+    try {
+      handle = new OssHandle;
     }
-    else {
-      handle = (OssHandle *) stream_.apiHandle;
+    catch ( std::bad_alloc& ) {
+      errorText_ = "RtApiOss::probeDeviceOpen: error allocating OssHandle memory.";
+      goto error;
     }
-    handle->id[mode] = fd;
 
-    // Allocate necessary internal buffers.
-    unsigned long bufferBytes;
-    bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
-    stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
-    if ( stream_.userBuffer[mode] == NULL ) {
-      errorText_ = "RtApiOss::probeDeviceOpen: error allocating user buffer memory.";
+    if ( pthread_cond_init( &handle->runnable, NULL ) ) {
+      errorText_ = "RtApiOss::probeDeviceOpen: error initializing pthread condition variable.";
       goto error;
     }
 
-    if ( stream_.doConvertBuffer[mode] ) {
+    stream_.apiHandle = (void *) handle;
+  }
+  else {
+    handle = (OssHandle *) stream_.apiHandle;
+  }
+  handle->id[mode] = fd;
 
-      bool makeBuffer = true;
-      bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
-      if ( mode == INPUT ) {
-        if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
-          unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
-          if ( bufferBytes <= bytesOut ) makeBuffer = false;
-        }
+  // Allocate necessary internal buffers.
+  unsigned long bufferBytes;
+  bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );
+  stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );
+  if ( stream_.userBuffer[mode] == NULL ) {
+    errorText_ = "RtApiOss::probeDeviceOpen: error allocating user buffer memory.";
+    goto error;
+  }
+
+  if ( stream_.doConvertBuffer[mode] ) {
+
+    bool makeBuffer = true;
+    bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );
+    if ( mode == INPUT ) {
+      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
+        unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );
+        if ( bufferBytes <= bytesOut ) makeBuffer = false;
       }
+    }
 
-      if ( makeBuffer ) {
-        bufferBytes *= *bufferSize;
-        if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
-        stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
-        if ( stream_.deviceBuffer == NULL ) {
-          errorText_ = "RtApiOss::probeDeviceOpen: error allocating device buffer memory.";
-          goto error;
-        }
+    if ( makeBuffer ) {
+      bufferBytes *= *bufferSize;
+      if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );
+      stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );
+      if ( stream_.deviceBuffer == NULL ) {
+        errorText_ = "RtApiOss::probeDeviceOpen: error allocating device buffer memory.";
+        goto error;
       }
     }
+  }
 
-    stream_.device[mode] = device;
-    stream_.state = STREAM_STOPPED;
+  stream_.device[mode] = device;
+  stream_.state = STREAM_STOPPED;
 
-    // Setup the buffer conversion information structure.
-    if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
+  // Setup the buffer conversion information structure.
+  if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );
 
-    // Setup thread if necessary.
-    if ( stream_.mode == OUTPUT && mode == INPUT ) {
-      // We had already set up an output stream.
-      stream_.mode = DUPLEX;
-      if ( stream_.device[0] == device ) handle->id[0] = fd;
-    }
-    else {
-      stream_.mode = mode;
+  // Setup thread if necessary.
+  if ( stream_.mode == OUTPUT && mode == INPUT ) {
+    // We had already set up an output stream.
+    stream_.mode = DUPLEX;
+    if ( stream_.device[0] == device ) handle->id[0] = fd;
+  }
+  else {
+    stream_.mode = mode;
 
-      // Setup callback thread.
-      stream_.callbackInfo.object = (void *) this;
+    // Setup callback thread.
+    stream_.callbackInfo.object = (void *) this;
 
-      // Set the thread attributes for joinable and realtime scheduling
-      // priority.  The higher priority will only take affect if the
-      // program is run as root or suid.
-      pthread_attr_t attr;
-      pthread_attr_init( &attr );
-      pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
+    // Set the thread attributes for joinable and realtime scheduling
+    // priority.  The higher priority will only take affect if the
+    // program is run as root or suid.
+    pthread_attr_t attr;
+    pthread_attr_init( &attr );
+    pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
 #ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)
-      if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
-        struct sched_param param;
-        int priority = options->priority;
-        int min = sched_get_priority_min( SCHED_RR );
-        int max = sched_get_priority_max( SCHED_RR );
-        if ( priority < min ) priority = min;
-        else if ( priority > max ) priority = max;
-        param.sched_priority = priority;
-        pthread_attr_setschedparam( &attr, &param );
-        pthread_attr_setschedpolicy( &attr, SCHED_RR );
-      }
-      else
-        pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
-#else
+    if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {
+      struct sched_param param;
+      int priority = options->priority;
+      int min = sched_get_priority_min( SCHED_RR );
+      int max = sched_get_priority_max( SCHED_RR );
+      if ( priority < min ) priority = min;
+      else if ( priority > max ) priority = max;
+      param.sched_priority = priority;
+      pthread_attr_setschedparam( &attr, &param );
+      pthread_attr_setschedpolicy( &attr, SCHED_RR );
+    }
+    else
       pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
+#else
+    pthread_attr_setschedpolicy( &attr, SCHED_OTHER );
 #endif
 
-      stream_.callbackInfo.isRunning = true;
-      result = pthread_create( &stream_.callbackInfo.thread, &attr, ossCallbackHandler, &stream_.callbackInfo );
-      pthread_attr_destroy( &attr );
-      if ( result ) {
-        stream_.callbackInfo.isRunning = false;
-        errorText_ = "RtApiOss::error creating callback thread!";
-        goto error;
-      }
+    stream_.callbackInfo.isRunning = true;
+    result = pthread_create( &stream_.callbackInfo.thread, &attr, ossCallbackHandler, &stream_.callbackInfo );
+    pthread_attr_destroy( &attr );
+    if ( result ) {
+      stream_.callbackInfo.isRunning = false;
+      errorText_ = "RtApiOss::error creating callback thread!";
+      goto error;
     }
+  }
 
-    return SUCCESS;
-
-  error:
-    if ( handle ) {
-      pthread_cond_destroy( &handle->runnable );
-      if ( handle->id[0] ) close( handle->id[0] );
-      if ( handle->id[1] ) close( handle->id[1] );
-      delete handle;
-      stream_.apiHandle = 0;
-    }
+  return SUCCESS;
 
-    for ( int i=0; i<2; i++ ) {
-      if ( stream_.userBuffer[i] ) {
-        free( stream_.userBuffer[i] );
-        stream_.userBuffer[i] = 0;
-      }
-    }
+ error:
+  if ( handle ) {
+    pthread_cond_destroy( &handle->runnable );
+    if ( handle->id[0] ) close( handle->id[0] );
+    if ( handle->id[1] ) close( handle->id[1] );
+    delete handle;
+    stream_.apiHandle = 0;
+  }
 
-    if ( stream_.deviceBuffer ) {
-      free( stream_.deviceBuffer );
-      stream_.deviceBuffer = 0;
+  for ( int i=0; i<2; i++ ) {
+    if ( stream_.userBuffer[i] ) {
+      free( stream_.userBuffer[i] );
+      stream_.userBuffer[i] = 0;
     }
+  }
 
-    return FAILURE;
+  if ( stream_.deviceBuffer ) {
+    free( stream_.deviceBuffer );
+    stream_.deviceBuffer = 0;
   }
 
-  void RtApiOss :: closeStream()
-  {
-    if ( stream_.state == STREAM_CLOSED ) {
-      errorText_ = "RtApiOss::closeStream(): no open stream to close!";
-      error( RtError::WARNING );
-      return;
-    }
+  return FAILURE;
+}
 
-    OssHandle *handle = (OssHandle *) stream_.apiHandle;
-    stream_.callbackInfo.isRunning = false;
-    MUTEX_LOCK( &stream_.mutex );
-    if ( stream_.state == STREAM_STOPPED )
-      pthread_cond_signal( &handle->runnable );
-    MUTEX_UNLOCK( &stream_.mutex );
-    pthread_join( stream_.callbackInfo.thread, NULL );
+void RtApiOss :: closeStream()
+{
+  if ( stream_.state == STREAM_CLOSED ) {
+    errorText_ = "RtApiOss::closeStream(): no open stream to close!";
+    error( RtError::WARNING );
+    return;
+  }
 
-    if ( stream_.state == STREAM_RUNNING ) {
-      if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
-        ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
-      else
-        ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
-      stream_.state = STREAM_STOPPED;
-    }
+  OssHandle *handle = (OssHandle *) stream_.apiHandle;
+  stream_.callbackInfo.isRunning = false;
+  MUTEX_LOCK( &stream_.mutex );
+  if ( stream_.state == STREAM_STOPPED )
+    pthread_cond_signal( &handle->runnable );
+  MUTEX_UNLOCK( &stream_.mutex );
+  pthread_join( stream_.callbackInfo.thread, NULL );
 
-    if ( handle ) {
-      pthread_cond_destroy( &handle->runnable );
-      if ( handle->id[0] ) close( handle->id[0] );
-      if ( handle->id[1] ) close( handle->id[1] );
-      delete handle;
-      stream_.apiHandle = 0;
-    }
+  if ( stream_.state == STREAM_RUNNING ) {
+    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
+      ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
+    else
+      ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
+    stream_.state = STREAM_STOPPED;
+  }
 
-    for ( int i=0; i<2; i++ ) {
-      if ( stream_.userBuffer[i] ) {
-        free( stream_.userBuffer[i] );
-        stream_.userBuffer[i] = 0;
-      }
-    }
+  if ( handle ) {
+    pthread_cond_destroy( &handle->runnable );
+    if ( handle->id[0] ) close( handle->id[0] );
+    if ( handle->id[1] ) close( handle->id[1] );
+    delete handle;
+    stream_.apiHandle = 0;
+  }
 
-    if ( stream_.deviceBuffer ) {
-      free( stream_.deviceBuffer );
-      stream_.deviceBuffer = 0;
+  for ( int i=0; i<2; i++ ) {
+    if ( stream_.userBuffer[i] ) {
+      free( stream_.userBuffer[i] );
+      stream_.userBuffer[i] = 0;
     }
+  }
 
-    stream_.mode = UNINITIALIZED;
-    stream_.state = STREAM_CLOSED;
+  if ( stream_.deviceBuffer ) {
+    free( stream_.deviceBuffer );
+    stream_.deviceBuffer = 0;
   }
 
-  void RtApiOss :: startStream()
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_RUNNING ) {
-      errorText_ = "RtApiOss::startStream(): the stream is already running!";
-      error( RtError::WARNING );
-      return;
-    }
+  stream_.mode = UNINITIALIZED;
+  stream_.state = STREAM_CLOSED;
+}
 
-    MUTEX_LOCK( &stream_.mutex );
+void RtApiOss :: startStream()
+{
+  verifyStream();
+  if ( stream_.state == STREAM_RUNNING ) {
+    errorText_ = "RtApiOss::startStream(): the stream is already running!";
+    error( RtError::WARNING );
+    return;
+  }
 
-    stream_.state = STREAM_RUNNING;
+  MUTEX_LOCK( &stream_.mutex );
 
-    // No need to do anything else here ... OSS automatically starts
-    // when fed samples.
+  stream_.state = STREAM_RUNNING;
 
-    MUTEX_UNLOCK( &stream_.mutex );
+  // No need to do anything else here ... OSS automatically starts
+  // when fed samples.
 
-    OssHandle *handle = (OssHandle *) stream_.apiHandle;
-    pthread_cond_signal( &handle->runnable );
-  }
+  MUTEX_UNLOCK( &stream_.mutex );
 
-  void RtApiOss :: stopStream()
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_STOPPED ) {
-      errorText_ = "RtApiOss::stopStream(): the stream is already stopped!";
-      error( RtError::WARNING );
-      return;
-    }
+  OssHandle *handle = (OssHandle *) stream_.apiHandle;
+  pthread_cond_signal( &handle->runnable );
+}
 
-    // Change the state before the lock to improve shutdown response
-    // when using a callback.
-    stream_.state = STREAM_STOPPED;
-    MUTEX_LOCK( &stream_.mutex );
+void RtApiOss :: stopStream()
+{
+  verifyStream();
+  if ( stream_.state == STREAM_STOPPED ) {
+    errorText_ = "RtApiOss::stopStream(): the stream is already stopped!";
+    error( RtError::WARNING );
+    return;
+  }
 
-    int result = 0;
-    OssHandle *handle = (OssHandle *) stream_.apiHandle;
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+  MUTEX_LOCK( &stream_.mutex );
 
-      // Flush the output with zeros a few times.
-      char *buffer;
-      int samples;
-      RtAudioFormat format;
+  // The state might change while waiting on a mutex.
+  if ( stream_.state == STREAM_STOPPED ) {
+    MUTEX_UNLOCK( &stream_.mutex );
+    return;
+  }
 
-      if ( stream_.doConvertBuffer[0] ) {
-        buffer = stream_.deviceBuffer;
-        samples = stream_.bufferSize * stream_.nDeviceChannels[0];
-        format = stream_.deviceFormat[0];
-      }
-      else {
-        buffer = stream_.userBuffer[0];
-        samples = stream_.bufferSize * stream_.nUserChannels[0];
-        format = stream_.userFormat;
-      }
+  int result = 0;
+  OssHandle *handle = (OssHandle *) stream_.apiHandle;
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
 
-      memset( buffer, 0, samples * formatBytes(format) );
-      for ( unsigned int i=0; i<stream_.nBuffers+1; i++ ) {
-        result = write( handle->id[0], buffer, samples * formatBytes(format) );
-        if ( result == -1 ) {
-          errorText_ = "RtApiOss::stopStream: audio write error.";
-          error( RtError::WARNING );
-        }
-      }
+    // Flush the output with zeros a few times.
+    char *buffer;
+    int samples;
+    RtAudioFormat format;
 
-      result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
-      if ( result == -1 ) {
-        errorStream_ << "RtApiOss::stopStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
-        errorText_ = errorStream_.str();
-        goto unlock;
-      }
-      handle->triggered = false;
+    if ( stream_.doConvertBuffer[0] ) {
+      buffer = stream_.deviceBuffer;
+      samples = stream_.bufferSize * stream_.nDeviceChannels[0];
+      format = stream_.deviceFormat[0];
+    }
+    else {
+      buffer = stream_.userBuffer[0];
+      samples = stream_.bufferSize * stream_.nUserChannels[0];
+      format = stream_.userFormat;
     }
 
-    if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
-      result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
+    memset( buffer, 0, samples * formatBytes(format) );
+    for ( unsigned int i=0; i<stream_.nBuffers+1; i++ ) {
+      result = write( handle->id[0], buffer, samples * formatBytes(format) );
       if ( result == -1 ) {
-        errorStream_ << "RtApiOss::stopStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
-        errorText_ = errorStream_.str();
-        goto unlock;
+        errorText_ = "RtApiOss::stopStream: audio write error.";
+        error( RtError::WARNING );
       }
     }
 
-  unlock:
-    MUTEX_UNLOCK( &stream_.mutex );
-
-    stream_.state = STREAM_STOPPED;
-    if ( result != -1 ) return;
-    error( RtError::SYSTEM_ERROR );
+    result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
+    if ( result == -1 ) {
+      errorStream_ << "RtApiOss::stopStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
+      errorText_ = errorStream_.str();
+      goto unlock;
+    }
+    handle->triggered = false;
   }
 
-  void RtApiOss :: abortStream()
-  {
-    verifyStream();
-    if ( stream_.state == STREAM_STOPPED ) {
-      errorText_ = "RtApiOss::abortStream(): the stream is already stopped!";
-      error( RtError::WARNING );
-      return;
+  if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
+    result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
+    if ( result == -1 ) {
+      errorStream_ << "RtApiOss::stopStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
+      errorText_ = errorStream_.str();
+      goto unlock;
     }
+  }
 
-    // Change the state before the lock to improve shutdown response
-    // when using a callback.
-    stream_.state = STREAM_STOPPED;
-    MUTEX_LOCK( &stream_.mutex );
+ unlock:
+  stream_.state = STREAM_STOPPED;
+  MUTEX_UNLOCK( &stream_.mutex );
 
-    int result = 0;
-    OssHandle *handle = (OssHandle *) stream_.apiHandle;
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
-      result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
-      if ( result == -1 ) {
-        errorStream_ << "RtApiOss::abortStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
-        errorText_ = errorStream_.str();
-        goto unlock;
-      }
-      handle->triggered = false;
-    }
+  if ( result != -1 ) return;
+  error( RtError::SYSTEM_ERROR );
+}
 
-    if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
-      result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
-      if ( result == -1 ) {
-        errorStream_ << "RtApiOss::abortStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
-        errorText_ = errorStream_.str();
-        goto unlock;
-      }
-    }
+void RtApiOss :: abortStream()
+{
+  verifyStream();
+  if ( stream_.state == STREAM_STOPPED ) {
+    errorText_ = "RtApiOss::abortStream(): the stream is already stopped!";
+    error( RtError::WARNING );
+    return;
+  }
 
-  unlock:
-    MUTEX_UNLOCK( &stream_.mutex );
+  MUTEX_LOCK( &stream_.mutex );
 
-    stream_.state = STREAM_STOPPED;
-    if ( result != -1 ) return;
-    error( RtError::SYSTEM_ERROR );
+  // The state might change while waiting on a mutex.
+  if ( stream_.state == STREAM_STOPPED ) {
+    MUTEX_UNLOCK( &stream_.mutex );
+    return;
   }
 
-  void RtApiOss :: callbackEvent()
-  {
-    OssHandle *handle = (OssHandle *) stream_.apiHandle;
-    if ( stream_.state == STREAM_STOPPED ) {
-      MUTEX_LOCK( &stream_.mutex );
-      pthread_cond_wait( &handle->runnable, &stream_.mutex );
-      if ( stream_.state != STREAM_RUNNING ) {
-        MUTEX_UNLOCK( &stream_.mutex );
-        return;
-      }
-      MUTEX_UNLOCK( &stream_.mutex );
+  int result = 0;
+  OssHandle *handle = (OssHandle *) stream_.apiHandle;
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+    result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );
+    if ( result == -1 ) {
+      errorStream_ << "RtApiOss::abortStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";
+      errorText_ = errorStream_.str();
+      goto unlock;
     }
+    handle->triggered = false;
+  }
 
-    if ( stream_.state == STREAM_CLOSED ) {
-      errorText_ = "RtApiOss::callbackEvent(): the stream is closed ... this shouldn't happen!";
-      error( RtError::WARNING );
-      return;
+  if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {
+    result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );
+    if ( result == -1 ) {
+      errorStream_ << "RtApiOss::abortStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";
+      errorText_ = errorStream_.str();
+      goto unlock;
     }
+  }
 
-    // Invoke user callback to get fresh output data.
-    int doStopStream = 0;
-    RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
-    double streamTime = getStreamTime();
-    RtAudioStreamStatus status = 0;
-    if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
-      status |= RTAUDIO_OUTPUT_UNDERFLOW;
-      handle->xrun[0] = false;
-    }
-    if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
-      status |= RTAUDIO_INPUT_OVERFLOW;
-      handle->xrun[1] = false;
-    }
-    doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
-                             stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
-    if ( doStopStream == 2 ) {
-      this->abortStream();
+ unlock:
+  stream_.state = STREAM_STOPPED;
+  MUTEX_UNLOCK( &stream_.mutex );
+
+  if ( result != -1 ) return;
+  error( RtError::SYSTEM_ERROR );
+}
+
+void RtApiOss :: callbackEvent()
+{
+  OssHandle *handle = (OssHandle *) stream_.apiHandle;
+  if ( stream_.state == STREAM_STOPPED ) {
+    MUTEX_LOCK( &stream_.mutex );
+    pthread_cond_wait( &handle->runnable, &stream_.mutex );
+    if ( stream_.state != STREAM_RUNNING ) {
+      MUTEX_UNLOCK( &stream_.mutex );
       return;
     }
+    MUTEX_UNLOCK( &stream_.mutex );
+  }
 
-    MUTEX_LOCK( &stream_.mutex );
+  if ( stream_.state == STREAM_CLOSED ) {
+    errorText_ = "RtApiOss::callbackEvent(): the stream is closed ... this shouldn't happen!";
+    error( RtError::WARNING );
+    return;
+  }
 
-    // The state might change while waiting on a mutex.
-    if ( stream_.state == STREAM_STOPPED ) goto unlock;
+  // Invoke user callback to get fresh output data.
+  int doStopStream = 0;
+  RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
+  double streamTime = getStreamTime();
+  RtAudioStreamStatus status = 0;
+  if ( stream_.mode != INPUT && handle->xrun[0] == true ) {
+    status |= RTAUDIO_OUTPUT_UNDERFLOW;
+    handle->xrun[0] = false;
+  }
+  if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {
+    status |= RTAUDIO_INPUT_OVERFLOW;
+    handle->xrun[1] = false;
+  }
+  doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],
+                           stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );
+  if ( doStopStream == 2 ) {
+    this->abortStream();
+    return;
+  }
 
-    int result;
-    char *buffer;
-    int samples;
-    RtAudioFormat format;
+  MUTEX_LOCK( &stream_.mutex );
 
-    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
+  // The state might change while waiting on a mutex.
+  if ( stream_.state == STREAM_STOPPED ) goto unlock;
 
-      // Setup parameters and do buffer conversion if necessary.
-      if ( stream_.doConvertBuffer[0] ) {
-        buffer = stream_.deviceBuffer;
-        convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
-        samples = stream_.bufferSize * stream_.nDeviceChannels[0];
-        format = stream_.deviceFormat[0];
-      }
-      else {
-        buffer = stream_.userBuffer[0];
-        samples = stream_.bufferSize * stream_.nUserChannels[0];
-        format = stream_.userFormat;
-      }
+  int result;
+  char *buffer;
+  int samples;
+  RtAudioFormat format;
 
-      // Do byte swapping if necessary.
-      if ( stream_.doByteSwap[0] )
-        byteSwapBuffer( buffer, samples, format );
-
-      if ( stream_.mode == DUPLEX && handle->triggered == false ) {
-        int trig = 0;
-        ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
-        result = write( handle->id[0], buffer, samples * formatBytes(format) );
-        trig = PCM_ENABLE_INPUT|PCM_ENABLE_OUTPUT;
-        ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
-        handle->triggered = true;
-      }
-      else
-        // Write samples to device.
-        result = write( handle->id[0], buffer, samples * formatBytes(format) );
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
 
-      if ( result == -1 ) {
-        // We'll assume this is an underrun, though there isn't a
-        // specific means for determining that.
-        handle->xrun[0] = true;
-        errorText_ = "RtApiOss::callbackEvent: audio write error.";
-        error( RtError::WARNING );
-        // Continue on to input section.
-      }
+    // Setup parameters and do buffer conversion if necessary.
+    if ( stream_.doConvertBuffer[0] ) {
+      buffer = stream_.deviceBuffer;
+      convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );
+      samples = stream_.bufferSize * stream_.nDeviceChannels[0];
+      format = stream_.deviceFormat[0];
+    }
+    else {
+      buffer = stream_.userBuffer[0];
+      samples = stream_.bufferSize * stream_.nUserChannels[0];
+      format = stream_.userFormat;
     }
 
-    if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
+    // Do byte swapping if necessary.
+    if ( stream_.doByteSwap[0] )
+      byteSwapBuffer( buffer, samples, format );
 
-      // Setup parameters.
-      if ( stream_.doConvertBuffer[1] ) {
-        buffer = stream_.deviceBuffer;
-        samples = stream_.bufferSize * stream_.nDeviceChannels[1];
-        format = stream_.deviceFormat[1];
-      }
-      else {
-        buffer = stream_.userBuffer[1];
-        samples = stream_.bufferSize * stream_.nUserChannels[1];
-        format = stream_.userFormat;
-      }
+    if ( stream_.mode == DUPLEX && handle->triggered == false ) {
+      int trig = 0;
+      ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
+      result = write( handle->id[0], buffer, samples * formatBytes(format) );
+      trig = PCM_ENABLE_INPUT|PCM_ENABLE_OUTPUT;
+      ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );
+      handle->triggered = true;
+    }
+    else
+      // Write samples to device.
+      result = write( handle->id[0], buffer, samples * formatBytes(format) );
+
+    if ( result == -1 ) {
+      // We'll assume this is an underrun, though there isn't a
+      // specific means for determining that.
+      handle->xrun[0] = true;
+      errorText_ = "RtApiOss::callbackEvent: audio write error.";
+      error( RtError::WARNING );
+      // Continue on to input section.
+    }
+  }
 
-      // Read samples from device.
-      result = read( handle->id[1], buffer, samples * formatBytes(format) );
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
 
-      if ( result == -1 ) {
-        // We'll assume this is an overrun, though there isn't a
-        // specific means for determining that.
-        handle->xrun[1] = true;
-        errorText_ = "RtApiOss::callbackEvent: audio read error.";
-        error( RtError::WARNING );
-        goto unlock;
-      }
+    // Setup parameters.
+    if ( stream_.doConvertBuffer[1] ) {
+      buffer = stream_.deviceBuffer;
+      samples = stream_.bufferSize * stream_.nDeviceChannels[1];
+      format = stream_.deviceFormat[1];
+    }
+    else {
+      buffer = stream_.userBuffer[1];
+      samples = stream_.bufferSize * stream_.nUserChannels[1];
+      format = stream_.userFormat;
+    }
 
-      // Do byte swapping if necessary.
-      if ( stream_.doByteSwap[1] )
-        byteSwapBuffer( buffer, samples, format );
+    // Read samples from device.
+    result = read( handle->id[1], buffer, samples * formatBytes(format) );
 
-      // Do buffer conversion if necessary.
-      if ( stream_.doConvertBuffer[1] )
-        convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
+    if ( result == -1 ) {
+      // We'll assume this is an overrun, though there isn't a
+      // specific means for determining that.
+      handle->xrun[1] = true;
+      errorText_ = "RtApiOss::callbackEvent: audio read error.";
+      error( RtError::WARNING );
+      goto unlock;
     }
 
-  unlock:
-    MUTEX_UNLOCK( &stream_.mutex );
+    // Do byte swapping if necessary.
+    if ( stream_.doByteSwap[1] )
+      byteSwapBuffer( buffer, samples, format );
 
-    RtApi::tickStreamTime();
-    if ( doStopStream == 1 ) this->stopStream();
+    // Do buffer conversion if necessary.
+    if ( stream_.doConvertBuffer[1] )
+      convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );
   }
 
-  extern "C" void *ossCallbackHandler( void *ptr )
-  {
-    CallbackInfo *info = (CallbackInfo *) ptr;
-    RtApiOss *object = (RtApiOss *) info->object;
-    bool *isRunning = &info->isRunning;
+ unlock:
+  MUTEX_UNLOCK( &stream_.mutex );
 
-    while ( *isRunning == true ) {
-      pthread_testcancel();
-      object->callbackEvent();
-    }
+  RtApi::tickStreamTime();
+  if ( doStopStream == 1 ) this->stopStream();
+}
+
+extern "C" void *ossCallbackHandler( void *ptr )
+{
+  CallbackInfo *info = (CallbackInfo *) ptr;
+  RtApiOss *object = (RtApiOss *) info->object;
+  bool *isRunning = &info->isRunning;
 
-    pthread_exit( NULL );
+  while ( *isRunning == true ) {
+    pthread_testcancel();
+    object->callbackEvent();
   }
 
-  //******************** End of __LINUX_OSS__ *********************//
+  pthread_exit( NULL );
+}
+
+//******************** End of __LINUX_OSS__ *********************//
 #endif
 
 
-  // *************************************************** //
-  //
-  // Protected common (OS-independent) RtAudio methods.
-  //
-  // *************************************************** //
+// *************************************************** //
+//
+// Protected common (OS-independent) RtAudio methods.
+//
+// *************************************************** //
 
-  // This method can be modified to control the behavior of error
-  // message printing.
-  void RtApi :: error( RtError::Type type )
-  {
-    errorStream_.str(""); // clear the ostringstream
-    if ( type == RtError::WARNING && showWarnings_ == true )
-      std::cerr << '\n' << errorText_ << "\n\n";
-    else
-      throw( RtError( errorText_, type ) );
-  }
+// This method can be modified to control the behavior of error
+// message printing.
+void RtApi :: error( RtError::Type type )
+{
+  errorStream_.str(""); // clear the ostringstream
+  if ( type == RtError::WARNING && showWarnings_ == true )
+    std::cerr << '\n' << errorText_ << "\n\n";
+  else
+    throw( RtError( errorText_, type ) );
+}
 
-  void RtApi :: verifyStream()
-  {
-    if ( stream_.state == STREAM_CLOSED ) {
-      errorText_ = "RtApi:: a stream is not open!";
-      error( RtError::INVALID_USE );
-    }
+void RtApi :: verifyStream()
+{
+  if ( stream_.state == STREAM_CLOSED ) {
+    errorText_ = "RtApi:: a stream is not open!";
+    error( RtError::INVALID_USE );
   }
+}
 
-  void RtApi :: clearStreamInfo()
-  {
-    stream_.mode = UNINITIALIZED;
-    stream_.state = STREAM_CLOSED;
-    stream_.sampleRate = 0;
-    stream_.bufferSize = 0;
-    stream_.nBuffers = 0;
-    stream_.userFormat = 0;
-    stream_.userInterleaved = true;
-    stream_.streamTime = 0.0;
-    stream_.apiHandle = 0;
-    stream_.deviceBuffer = 0;
-    stream_.callbackInfo.callback = 0;
-    stream_.callbackInfo.userData = 0;
-    stream_.callbackInfo.isRunning = false;
-    for ( int i=0; i<2; i++ ) {
-      stream_.device[i] = 11111;
-      stream_.doConvertBuffer[i] = false;
-      stream_.deviceInterleaved[i] = true;
-      stream_.doByteSwap[i] = false;
-      stream_.nUserChannels[i] = 0;
-      stream_.nDeviceChannels[i] = 0;
-      stream_.channelOffset[i] = 0;
-      stream_.deviceFormat[i] = 0;
-      stream_.latency[i] = 0;
-      stream_.userBuffer[i] = 0;
-      stream_.convertInfo[i].channels = 0;
-      stream_.convertInfo[i].inJump = 0;
-      stream_.convertInfo[i].outJump = 0;
-      stream_.convertInfo[i].inFormat = 0;
-      stream_.convertInfo[i].outFormat = 0;
-      stream_.convertInfo[i].inOffset.clear();
-      stream_.convertInfo[i].outOffset.clear();
-    }
+void RtApi :: clearStreamInfo()
+{
+  stream_.mode = UNINITIALIZED;
+  stream_.state = STREAM_CLOSED;
+  stream_.sampleRate = 0;
+  stream_.bufferSize = 0;
+  stream_.nBuffers = 0;
+  stream_.userFormat = 0;
+  stream_.userInterleaved = true;
+  stream_.streamTime = 0.0;
+  stream_.apiHandle = 0;
+  stream_.deviceBuffer = 0;
+  stream_.callbackInfo.callback = 0;
+  stream_.callbackInfo.userData = 0;
+  stream_.callbackInfo.isRunning = false;
+  for ( int i=0; i<2; i++ ) {
+    stream_.device[i] = 11111;
+    stream_.doConvertBuffer[i] = false;
+    stream_.deviceInterleaved[i] = true;
+    stream_.doByteSwap[i] = false;
+    stream_.nUserChannels[i] = 0;
+    stream_.nDeviceChannels[i] = 0;
+    stream_.channelOffset[i] = 0;
+    stream_.deviceFormat[i] = 0;
+    stream_.latency[i] = 0;
+    stream_.userBuffer[i] = 0;
+    stream_.convertInfo[i].channels = 0;
+    stream_.convertInfo[i].inJump = 0;
+    stream_.convertInfo[i].outJump = 0;
+    stream_.convertInfo[i].inFormat = 0;
+    stream_.convertInfo[i].outFormat = 0;
+    stream_.convertInfo[i].inOffset.clear();
+    stream_.convertInfo[i].outOffset.clear();
   }
+}
 
-  unsigned int RtApi :: formatBytes( RtAudioFormat format )
-  {
-    if ( format == RTAUDIO_SINT16 )
-      return 2;
-    else if ( format == RTAUDIO_SINT24 || format == RTAUDIO_SINT32 ||
-              format == RTAUDIO_FLOAT32 )
-      return 4;
-    else if ( format == RTAUDIO_FLOAT64 )
-      return 8;
-    else if ( format == RTAUDIO_SINT8 )
-      return 1;
-
-    errorText_ = "RtApi::formatBytes: undefined format.";
-    error( RtError::WARNING );
+unsigned int RtApi :: formatBytes( RtAudioFormat format )
+{
+  if ( format == RTAUDIO_SINT16 )
+    return 2;
+  else if ( format == RTAUDIO_SINT24 || format == RTAUDIO_SINT32 ||
+            format == RTAUDIO_FLOAT32 )
+    return 4;
+  else if ( format == RTAUDIO_FLOAT64 )
+    return 8;
+  else if ( format == RTAUDIO_SINT8 )
+    return 1;
+
+  errorText_ = "RtApi::formatBytes: undefined format.";
+  error( RtError::WARNING );
 
-    return 0;
+  return 0;
+}
+
+void RtApi :: setConvertInfo( StreamMode mode, unsigned int firstChannel )
+{
+  if ( mode == INPUT ) { // convert device to user buffer
+    stream_.convertInfo[mode].inJump = stream_.nDeviceChannels[1];
+    stream_.convertInfo[mode].outJump = stream_.nUserChannels[1];
+    stream_.convertInfo[mode].inFormat = stream_.deviceFormat[1];
+    stream_.convertInfo[mode].outFormat = stream_.userFormat;
+  }
+  else { // convert user to device buffer
+    stream_.convertInfo[mode].inJump = stream_.nUserChannels[0];
+    stream_.convertInfo[mode].outJump = stream_.nDeviceChannels[0];
+    stream_.convertInfo[mode].inFormat = stream_.userFormat;
+    stream_.convertInfo[mode].outFormat = stream_.deviceFormat[0];
   }
 
-  void RtApi :: setConvertInfo( StreamMode mode, unsigned int firstChannel )
-  {
-    if ( mode == INPUT ) { // convert device to user buffer
-      stream_.convertInfo[mode].inJump = stream_.nDeviceChannels[1];
-      stream_.convertInfo[mode].outJump = stream_.nUserChannels[1];
-      stream_.convertInfo[mode].inFormat = stream_.deviceFormat[1];
-      stream_.convertInfo[mode].outFormat = stream_.userFormat;
+  if ( stream_.convertInfo[mode].inJump < stream_.convertInfo[mode].outJump )
+    stream_.convertInfo[mode].channels = stream_.convertInfo[mode].inJump;
+  else
+    stream_.convertInfo[mode].channels = stream_.convertInfo[mode].outJump;
+
+  // Set up the interleave/deinterleave offsets.
+  if ( stream_.deviceInterleaved[mode] != stream_.userInterleaved ) {
+    if ( ( mode == OUTPUT && stream_.deviceInterleaved[mode] ) ||
+         ( mode == INPUT && stream_.userInterleaved ) ) {
+      for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
+        stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
+        stream_.convertInfo[mode].outOffset.push_back( k );
+        stream_.convertInfo[mode].inJump = 1;
+      }
     }
-    else { // convert user to device buffer
-      stream_.convertInfo[mode].inJump = stream_.nUserChannels[0];
-      stream_.convertInfo[mode].outJump = stream_.nDeviceChannels[0];
-      stream_.convertInfo[mode].inFormat = stream_.userFormat;
-      stream_.convertInfo[mode].outFormat = stream_.deviceFormat[0];
+    else {
+      for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
+        stream_.convertInfo[mode].inOffset.push_back( k );
+        stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
+        stream_.convertInfo[mode].outJump = 1;
+      }
     }
-
-    if ( stream_.convertInfo[mode].inJump < stream_.convertInfo[mode].outJump )
-      stream_.convertInfo[mode].channels = stream_.convertInfo[mode].inJump;
-    else
-      stream_.convertInfo[mode].channels = stream_.convertInfo[mode].outJump;
-
-    // Set up the interleave/deinterleave offsets.
-    if ( stream_.deviceInterleaved[mode] != stream_.userInterleaved ) {
-      if ( ( mode == OUTPUT && stream_.deviceInterleaved[mode] ) ||
-           ( mode == INPUT && stream_.userInterleaved ) ) {
-        for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
-          stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
-          stream_.convertInfo[mode].outOffset.push_back( k );
-          stream_.convertInfo[mode].inJump = 1;
-        }
+  }
+  else { // no (de)interleaving
+    if ( stream_.userInterleaved ) {
+      for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
+        stream_.convertInfo[mode].inOffset.push_back( k );
+        stream_.convertInfo[mode].outOffset.push_back( k );
       }
-      else {
-        for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
-          stream_.convertInfo[mode].inOffset.push_back( k );
-          stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
-          stream_.convertInfo[mode].outJump = 1;
-        }
+    }
+    else {
+      for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
+        stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
+        stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
+        stream_.convertInfo[mode].inJump = 1;
+        stream_.convertInfo[mode].outJump = 1;
       }
     }
-    else { // no (de)interleaving
-      if ( stream_.userInterleaved ) {
-        for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
-          stream_.convertInfo[mode].inOffset.push_back( k );
-          stream_.convertInfo[mode].outOffset.push_back( k );
-        }
+  }
+
+  // Add channel offset.
+  if ( firstChannel > 0 ) {
+    if ( stream_.deviceInterleaved[mode] ) {
+      if ( mode == OUTPUT ) {
+        for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
+          stream_.convertInfo[mode].outOffset[k] += firstChannel;
       }
       else {
-        for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {
-          stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );
-          stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );
-          stream_.convertInfo[mode].inJump = 1;
-          stream_.convertInfo[mode].outJump = 1;
-        }
+        for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
+          stream_.convertInfo[mode].inOffset[k] += firstChannel;
       }
     }
-
-    // Add channel offset.
-    if ( firstChannel > 0 ) {
-      if ( stream_.deviceInterleaved[mode] ) {
-        if ( mode == OUTPUT ) {
-          for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
-            stream_.convertInfo[mode].outOffset[k] += firstChannel;
-        }
-        else {
-          for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
-            stream_.convertInfo[mode].inOffset[k] += firstChannel;
-        }
+    else {
+      if ( mode == OUTPUT ) {
+        for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
+          stream_.convertInfo[mode].outOffset[k] += ( firstChannel * stream_.bufferSize );
       }
       else {
-        if ( mode == OUTPUT ) {
-          for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
-            stream_.convertInfo[mode].outOffset[k] += ( firstChannel * stream_.bufferSize );
-        }
-        else {
-          for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
-            stream_.convertInfo[mode].inOffset[k] += ( firstChannel  * stream_.bufferSize );
-        }
+        for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )
+          stream_.convertInfo[mode].inOffset[k] += ( firstChannel  * stream_.bufferSize );
       }
     }
   }
+}
 
-  void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info )
-  {
-    // This function does format conversion, input/output channel compensation, and
-    // data interleaving/deinterleaving.  24-bit integers are assumed to occupy
-    // the upper three bytes of a 32-bit integer.
-
-    // Clear our device buffer when in/out duplex device channels are different
-    if ( outBuffer == stream_.deviceBuffer && stream_.mode == DUPLEX &&
-         ( stream_.nDeviceChannels[0] < stream_.nDeviceChannels[1] ) )
-      memset( outBuffer, 0, stream_.bufferSize * info.outJump * formatBytes( info.outFormat ) );
-
-    int j;
-    if (info.outFormat == RTAUDIO_FLOAT64) {
-      Float64 scale;
-      Float64 *out = (Float64 *)outBuffer;
-
-      if (info.inFormat == RTAUDIO_SINT8) {
-        signed char *in = (signed char *)inBuffer;
-        scale = 1.0 / 127.5;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
-            out[info.outOffset[j]] += 0.5;
-            out[info.outOffset[j]] *= scale;
-          }
-          in += info.inJump;
-          out += info.outJump;
+void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info )
+{
+  // This function does format conversion, input/output channel compensation, and
+  // data interleaving/deinterleaving.  24-bit integers are assumed to occupy
+  // the upper three bytes of a 32-bit integer.
+
+  // Clear our device buffer when in/out duplex device channels are different
+  if ( outBuffer == stream_.deviceBuffer && stream_.mode == DUPLEX &&
+       ( stream_.nDeviceChannels[0] < stream_.nDeviceChannels[1] ) )
+    memset( outBuffer, 0, stream_.bufferSize * info.outJump * formatBytes( info.outFormat ) );
+
+  int j;
+  if (info.outFormat == RTAUDIO_FLOAT64) {
+    Float64 scale;
+    Float64 *out = (Float64 *)outBuffer;
+
+    if (info.inFormat == RTAUDIO_SINT8) {
+      signed char *in = (signed char *)inBuffer;
+      scale = 1.0 / 127.5;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
+          out[info.outOffset[j]] += 0.5;
+          out[info.outOffset[j]] *= scale;
         }
-      }
-      else if (info.inFormat == RTAUDIO_SINT16) {
-        Int16 *in = (Int16 *)inBuffer;
-        scale = 1.0 / 32767.5;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
-            out[info.outOffset[j]] += 0.5;
-            out[info.outOffset[j]] *= scale;
-          }
-          in += info.inJump;
-          out += info.outJump;
+        in += info.inJump;
+        out += info.outJump;
+      }
+    }
+    else if (info.inFormat == RTAUDIO_SINT16) {
+      Int16 *in = (Int16 *)inBuffer;
+      scale = 1.0 / 32767.5;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
+          out[info.outOffset[j]] += 0.5;
+          out[info.outOffset[j]] *= scale;
         }
-      }
-      else if (info.inFormat == RTAUDIO_SINT24) {
-        Int32 *in = (Int32 *)inBuffer;
-        scale = 1.0 / 8388607.5;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]] & 0x00ffffff);
-            out[info.outOffset[j]] += 0.5;
-            out[info.outOffset[j]] *= scale;
-          }
-          in += info.inJump;
-          out += info.outJump;
+        in += info.inJump;
+        out += info.outJump;
+      }
+    }
+    else if (info.inFormat == RTAUDIO_SINT24) {
+      Int32 *in = (Int32 *)inBuffer;
+      scale = 1.0 / 8388607.5;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]] & 0x00ffffff);
+          out[info.outOffset[j]] += 0.5;
+          out[info.outOffset[j]] *= scale;
         }
-      }
-      else if (info.inFormat == RTAUDIO_SINT32) {
-        Int32 *in = (Int32 *)inBuffer;
-        scale = 1.0 / 2147483647.5;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
-            out[info.outOffset[j]] += 0.5;
-            out[info.outOffset[j]] *= scale;
-          }
-          in += info.inJump;
-          out += info.outJump;
+        in += info.inJump;
+        out += info.outJump;
+      }
+    }
+    else if (info.inFormat == RTAUDIO_SINT32) {
+      Int32 *in = (Int32 *)inBuffer;
+      scale = 1.0 / 2147483647.5;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
+          out[info.outOffset[j]] += 0.5;
+          out[info.outOffset[j]] *= scale;
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_FLOAT32) {
-        Float32 *in = (Float32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_FLOAT32) {
+      Float32 *in = (Float32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_FLOAT64) {
-        // Channel compensation and/or (de)interleaving only.
-        Float64 *in = (Float64 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = in[info.inOffset[j]];
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_FLOAT64) {
+      // Channel compensation and/or (de)interleaving only.
+      Float64 *in = (Float64 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = in[info.inOffset[j]];
         }
+        in += info.inJump;
+        out += info.outJump;
       }
     }
-    else if (info.outFormat == RTAUDIO_FLOAT32) {
-      Float32 scale;
-      Float32 *out = (Float32 *)outBuffer;
-
-      if (info.inFormat == RTAUDIO_SINT8) {
-        signed char *in = (signed char *)inBuffer;
-        scale = (Float32) ( 1.0 / 127.5 );
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
-            out[info.outOffset[j]] += 0.5;
-            out[info.outOffset[j]] *= scale;
-          }
-          in += info.inJump;
-          out += info.outJump;
+  }
+  else if (info.outFormat == RTAUDIO_FLOAT32) {
+    Float32 scale;
+    Float32 *out = (Float32 *)outBuffer;
+
+    if (info.inFormat == RTAUDIO_SINT8) {
+      signed char *in = (signed char *)inBuffer;
+      scale = (Float32) ( 1.0 / 127.5 );
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
+          out[info.outOffset[j]] += 0.5;
+          out[info.outOffset[j]] *= scale;
         }
-      }
-      else if (info.inFormat == RTAUDIO_SINT16) {
-        Int16 *in = (Int16 *)inBuffer;
-        scale = (Float32) ( 1.0 / 32767.5 );
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
-            out[info.outOffset[j]] += 0.5;
-            out[info.outOffset[j]] *= scale;
-          }
-          in += info.inJump;
-          out += info.outJump;
+        in += info.inJump;
+        out += info.outJump;
+      }
+    }
+    else if (info.inFormat == RTAUDIO_SINT16) {
+      Int16 *in = (Int16 *)inBuffer;
+      scale = (Float32) ( 1.0 / 32767.5 );
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
+          out[info.outOffset[j]] += 0.5;
+          out[info.outOffset[j]] *= scale;
         }
-      }
-      else if (info.inFormat == RTAUDIO_SINT24) {
-        Int32 *in = (Int32 *)inBuffer;
-        scale = (Float32) ( 1.0 / 8388607.5 );
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]] & 0x00ffffff);
-            out[info.outOffset[j]] += 0.5;
-            out[info.outOffset[j]] *= scale;
-          }
-          in += info.inJump;
-          out += info.outJump;
+        in += info.inJump;
+        out += info.outJump;
+      }
+    }
+    else if (info.inFormat == RTAUDIO_SINT24) {
+      Int32 *in = (Int32 *)inBuffer;
+      scale = (Float32) ( 1.0 / 8388607.5 );
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]] & 0x00ffffff);
+          out[info.outOffset[j]] += 0.5;
+          out[info.outOffset[j]] *= scale;
         }
-      }
-      else if (info.inFormat == RTAUDIO_SINT32) {
-        Int32 *in = (Int32 *)inBuffer;
-        scale = (Float32) ( 1.0 / 2147483647.5 );
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
-            out[info.outOffset[j]] += 0.5;
-            out[info.outOffset[j]] *= scale;
-          }
-          in += info.inJump;
-          out += info.outJump;
+        in += info.inJump;
+        out += info.outJump;
+      }
+    }
+    else if (info.inFormat == RTAUDIO_SINT32) {
+      Int32 *in = (Int32 *)inBuffer;
+      scale = (Float32) ( 1.0 / 2147483647.5 );
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
+          out[info.outOffset[j]] += 0.5;
+          out[info.outOffset[j]] *= scale;
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_FLOAT32) {
-        // Channel compensation and/or (de)interleaving only.
-        Float32 *in = (Float32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = in[info.inOffset[j]];
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_FLOAT32) {
+      // Channel compensation and/or (de)interleaving only.
+      Float32 *in = (Float32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = in[info.inOffset[j]];
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_FLOAT64) {
-        Float64 *in = (Float64 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_FLOAT64) {
+      Float64 *in = (Float64 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];
         }
+        in += info.inJump;
+        out += info.outJump;
       }
     }
-    else if (info.outFormat == RTAUDIO_SINT32) {
-      Int32 *out = (Int32 *)outBuffer;
-      if (info.inFormat == RTAUDIO_SINT8) {
-        signed char *in = (signed char *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
-            out[info.outOffset[j]] <<= 24;
-          }
-          in += info.inJump;
-          out += info.outJump;
+  }
+  else if (info.outFormat == RTAUDIO_SINT32) {
+    Int32 *out = (Int32 *)outBuffer;
+    if (info.inFormat == RTAUDIO_SINT8) {
+      signed char *in = (signed char *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
+          out[info.outOffset[j]] <<= 24;
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_SINT16) {
-        Int16 *in = (Int16 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
-            out[info.outOffset[j]] <<= 16;
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_SINT16) {
+      Int16 *in = (Int16 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
+          out[info.outOffset[j]] <<= 16;
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_SINT24) {
-        Int32 *in = (Int32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
-            out[info.outOffset[j]] <<= 8;
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_SINT24) {
+      Int32 *in = (Int32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
+          out[info.outOffset[j]] <<= 8;
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_SINT32) {
-        // Channel compensation and/or (de)interleaving only.
-        Int32 *in = (Int32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = in[info.inOffset[j]];
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_SINT32) {
+      // Channel compensation and/or (de)interleaving only.
+      Int32 *in = (Int32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = in[info.inOffset[j]];
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_FLOAT32) {
-        Float32 *in = (Float32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_FLOAT32) {
+      Float32 *in = (Float32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_FLOAT64) {
-        Float64 *in = (Float64 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_FLOAT64) {
+      Float64 *in = (Float64 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);
         }
+        in += info.inJump;
+        out += info.outJump;
       }
     }
-    else if (info.outFormat == RTAUDIO_SINT24) {
-      Int32 *out = (Int32 *)outBuffer;
-      if (info.inFormat == RTAUDIO_SINT8) {
-        signed char *in = (signed char *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
-            out[info.outOffset[j]] <<= 16;
-          }
-          in += info.inJump;
-          out += info.outJump;
+  }
+  else if (info.outFormat == RTAUDIO_SINT24) {
+    Int32 *out = (Int32 *)outBuffer;
+    if (info.inFormat == RTAUDIO_SINT8) {
+      signed char *in = (signed char *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
+          out[info.outOffset[j]] <<= 16;
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_SINT16) {
-        Int16 *in = (Int16 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
-            out[info.outOffset[j]] <<= 8;
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_SINT16) {
+      Int16 *in = (Int16 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
+          out[info.outOffset[j]] <<= 8;
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_SINT24) {
-        // Channel compensation and/or (de)interleaving only.
-        Int32 *in = (Int32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = in[info.inOffset[j]];
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_SINT24) {
+      // Channel compensation and/or (de)interleaving only.
+      Int32 *in = (Int32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = in[info.inOffset[j]];
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_SINT32) {
-        Int32 *in = (Int32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
-            out[info.outOffset[j]] >>= 8;
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_SINT32) {
+      Int32 *in = (Int32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];
+          out[info.outOffset[j]] >>= 8;
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_FLOAT32) {
-        Float32 *in = (Float32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_FLOAT32) {
+      Float32 *in = (Float32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_FLOAT64) {
-        Float64 *in = (Float64 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_FLOAT64) {
+      Float64 *in = (Float64 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);
         }
+        in += info.inJump;
+        out += info.outJump;
       }
     }
-    else if (info.outFormat == RTAUDIO_SINT16) {
-      Int16 *out = (Int16 *)outBuffer;
-      if (info.inFormat == RTAUDIO_SINT8) {
-        signed char *in = (signed char *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int16) in[info.inOffset[j]];
-            out[info.outOffset[j]] <<= 8;
-          }
-          in += info.inJump;
-          out += info.outJump;
+  }
+  else if (info.outFormat == RTAUDIO_SINT16) {
+    Int16 *out = (Int16 *)outBuffer;
+    if (info.inFormat == RTAUDIO_SINT8) {
+      signed char *in = (signed char *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int16) in[info.inOffset[j]];
+          out[info.outOffset[j]] <<= 8;
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_SINT16) {
-        // Channel compensation and/or (de)interleaving only.
-        Int16 *in = (Int16 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = in[info.inOffset[j]];
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_SINT16) {
+      // Channel compensation and/or (de)interleaving only.
+      Int16 *in = (Int16 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = in[info.inOffset[j]];
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_SINT24) {
-        Int32 *in = (Int32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 8) & 0x0000ffff);
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_SINT24) {
+      Int32 *in = (Int32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 8) & 0x0000ffff);
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_SINT32) {
-        Int32 *in = (Int32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 16) & 0x0000ffff);
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_SINT32) {
+      Int32 *in = (Int32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 16) & 0x0000ffff);
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_FLOAT32) {
-        Float32 *in = (Float32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_FLOAT32) {
+      Float32 *in = (Float32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_FLOAT64) {
-        Float64 *in = (Float64 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_FLOAT64) {
+      Float64 *in = (Float64 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);
         }
+        in += info.inJump;
+        out += info.outJump;
       }
     }
-    else if (info.outFormat == RTAUDIO_SINT8) {
-      signed char *out = (signed char *)outBuffer;
-      if (info.inFormat == RTAUDIO_SINT8) {
-        // Channel compensation and/or (de)interleaving only.
-        signed char *in = (signed char *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = in[info.inOffset[j]];
-          }
-          in += info.inJump;
-          out += info.outJump;
+  }
+  else if (info.outFormat == RTAUDIO_SINT8) {
+    signed char *out = (signed char *)outBuffer;
+    if (info.inFormat == RTAUDIO_SINT8) {
+      // Channel compensation and/or (de)interleaving only.
+      signed char *in = (signed char *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = in[info.inOffset[j]];
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      if (info.inFormat == RTAUDIO_SINT16) {
-        Int16 *in = (Int16 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 8) & 0x00ff);
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    if (info.inFormat == RTAUDIO_SINT16) {
+      Int16 *in = (Int16 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 8) & 0x00ff);
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_SINT24) {
-        Int32 *in = (Int32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 16) & 0x000000ff);
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_SINT24) {
+      Int32 *in = (Int32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 16) & 0x000000ff);
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_SINT32) {
-        Int32 *in = (Int32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 24) & 0x000000ff);
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_SINT32) {
+      Int32 *in = (Int32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 24) & 0x000000ff);
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_FLOAT32) {
-        Float32 *in = (Float32 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_FLOAT32) {
+      Float32 *in = (Float32 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
         }
+        in += info.inJump;
+        out += info.outJump;
       }
-      else if (info.inFormat == RTAUDIO_FLOAT64) {
-        Float64 *in = (Float64 *)inBuffer;
-        for (unsigned int i=0; i<stream_.bufferSize; i++) {
-          for (j=0; j<info.channels; j++) {
-            out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
-          }
-          in += info.inJump;
-          out += info.outJump;
+    }
+    else if (info.inFormat == RTAUDIO_FLOAT64) {
+      Float64 *in = (Float64 *)inBuffer;
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {
+        for (j=0; j<info.channels; j++) {
+          out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);
         }
+        in += info.inJump;
+        out += info.outJump;
       }
     }
   }
+}
 
   //static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }
   //static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }
   //static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }
 
-  void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format )
-  {
-    register char val;
-    register char *ptr;
-
-    ptr = buffer;
-    if ( format == RTAUDIO_SINT16 ) {
-      for ( unsigned int i=0; i<samples; i++ ) {
-        // Swap 1st and 2nd bytes.
-        val = *(ptr);
-        *(ptr) = *(ptr+1);
-        *(ptr+1) = val;
-
-        // Increment 2 bytes.
-        ptr += 2;
-      }
-    }
-    else if ( format == RTAUDIO_SINT24 ||
-              format == RTAUDIO_SINT32 ||
-              format == RTAUDIO_FLOAT32 ) {
-      for ( unsigned int i=0; i<samples; i++ ) {
-        // Swap 1st and 4th bytes.
-        val = *(ptr);
-        *(ptr) = *(ptr+3);
-        *(ptr+3) = val;
-
-        // Swap 2nd and 3rd bytes.
-        ptr += 1;
-        val = *(ptr);
-        *(ptr) = *(ptr+1);
-        *(ptr+1) = val;
-
-        // Increment 3 more bytes.
-        ptr += 3;
-      }
-    }
-    else if ( format == RTAUDIO_FLOAT64 ) {
-      for ( unsigned int i=0; i<samples; i++ ) {
-        // Swap 1st and 8th bytes
-        val = *(ptr);
-        *(ptr) = *(ptr+7);
-        *(ptr+7) = val;
-
-        // Swap 2nd and 7th bytes
-        ptr += 1;
-        val = *(ptr);
-        *(ptr) = *(ptr+5);
-        *(ptr+5) = val;
-
-        // Swap 3rd and 6th bytes
-        ptr += 1;
-        val = *(ptr);
-        *(ptr) = *(ptr+3);
-        *(ptr+3) = val;
-
-        // Swap 4th and 5th bytes
-        ptr += 1;
-        val = *(ptr);
-        *(ptr) = *(ptr+1);
-        *(ptr+1) = val;
-
-        // Increment 5 more bytes.
-        ptr += 5;
-      }
+void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format )
+{
+  register char val;
+  register char *ptr;
+
+  ptr = buffer;
+  if ( format == RTAUDIO_SINT16 ) {
+    for ( unsigned int i=0; i<samples; i++ ) {
+      // Swap 1st and 2nd bytes.
+      val = *(ptr);
+      *(ptr) = *(ptr+1);
+      *(ptr+1) = val;
+
+      // Increment 2 bytes.
+      ptr += 2;
+    }
+  }
+  else if ( format == RTAUDIO_SINT24 ||
+            format == RTAUDIO_SINT32 ||
+            format == RTAUDIO_FLOAT32 ) {
+    for ( unsigned int i=0; i<samples; i++ ) {
+      // Swap 1st and 4th bytes.
+      val = *(ptr);
+      *(ptr) = *(ptr+3);
+      *(ptr+3) = val;
+
+      // Swap 2nd and 3rd bytes.
+      ptr += 1;
+      val = *(ptr);
+      *(ptr) = *(ptr+1);
+      *(ptr+1) = val;
+
+      // Increment 3 more bytes.
+      ptr += 3;
+    }
+  }
+  else if ( format == RTAUDIO_FLOAT64 ) {
+    for ( unsigned int i=0; i<samples; i++ ) {
+      // Swap 1st and 8th bytes
+      val = *(ptr);
+      *(ptr) = *(ptr+7);
+      *(ptr+7) = val;
+
+      // Swap 2nd and 7th bytes
+      ptr += 1;
+      val = *(ptr);
+      *(ptr) = *(ptr+5);
+      *(ptr+5) = val;
+
+      // Swap 3rd and 6th bytes
+      ptr += 1;
+      val = *(ptr);
+      *(ptr) = *(ptr+3);
+      *(ptr+3) = val;
+
+      // Swap 4th and 5th bytes
+      ptr += 1;
+      val = *(ptr);
+      *(ptr) = *(ptr+1);
+      *(ptr+1) = val;
+
+      // Increment 5 more bytes.
+      ptr += 5;
     }
   }
+}
 
   // Indentation settings for Vim and Emacs
   //
index 3cb544c17ac8b91dd33e1b0811358268a83662ed..5c5fd6f9a4f34af46d23e8bd8d593bd10bc27e38 100644 (file)
--- a/RtAudio.h
+++ b/RtAudio.h
@@ -10,7 +10,7 @@
     RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
 
     RtAudio: realtime audio i/o C++ classes
-    Copyright (c) 2001-2008 Gary P. Scavone
+    Copyright (c) 2001-2009 Gary P. Scavone
 
     Permission is hereby granted, free of charge, to any person
     obtaining a copy of this software and associated documentation files
@@ -42,7 +42,7 @@
   \file RtAudio.h
  */
 
-// RtAudio: Version 4.0.4
+// RtAudio: Version 4.0.5
 
 #ifndef __RTAUDIO_H
 #define __RTAUDIO_H
index be6e89cf2118aeca84a3728cca92434b163517f9..74ae894c42074f4c204d1576125dc65502bf0c46 100644 (file)
-# Doxyfile 1.3.4
-
-# This file describes the settings to be used by the documentation system
-# doxygen (www.doxygen.org) for a project
-#
-# All text after a hash (#) is considered a comment and will be ignored
-# The format is:
-#       TAG = value [value, ...]
-# For lists items can also be appended using:
-#       TAG += value [value, ...]
-# Values that contain spaces should be placed between quotes (" ")
+# Doxyfile 1.5.6
 
 #---------------------------------------------------------------------------
 # Project related configuration options
 #---------------------------------------------------------------------------
-
-# The PROJECT_NAME tag is a single word (or a sequence of words surrounded 
-# by quotes) that should identify the project.
-
+DOXYFILE_ENCODING      = UTF-8
 PROJECT_NAME           = RtAudio
-
-# The PROJECT_NUMBER tag can be used to enter a project or revision number. 
-# This could be handy for archiving the generated documentation or 
-# if some version control system is used.
-
-PROJECT_NUMBER         = 4.0.4
-
-# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) 
-# base path where the generated documentation will be put. 
-# If a relative path is entered, it will be relative to the location 
-# where doxygen was started. If left blank the current directory will be used.
-
+PROJECT_NUMBER         = 4.0.5
 OUTPUT_DIRECTORY       = .
-
-# The OUTPUT_LANGUAGE tag is used to specify the language in which all 
-# documentation generated by doxygen is written. Doxygen will use this 
-# information to generate all constant output in the proper language. 
-# The default language is English, other supported languages are: 
-# Brazilian, Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, Dutch, 
-# Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en 
-# (Japanese with English messages), Korean, Norwegian, Polish, Portuguese, 
-# Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish, and Ukrainian.
-
+CREATE_SUBDIRS         = NO
 OUTPUT_LANGUAGE        = English
-
-# This tag can be used to specify the encoding used in the generated output. 
-# The encoding is not always determined by the language that is chosen, 
-# but also whether or not the output is meant for Windows or non-Windows users. 
-# In case there is a difference, setting the USE_WINDOWS_ENCODING tag to YES 
-# forces the Windows encoding (this is the default for the Windows binary), 
-# whereas setting the tag to NO uses a Unix-style encoding (the default for 
-# all platforms other than Windows).
-
-USE_WINDOWS_ENCODING   = NO
-
-# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will 
-# include brief member descriptions after the members that are listed in 
-# the file and class documentation (similar to JavaDoc). 
-# Set to NO to disable this.
-
 BRIEF_MEMBER_DESC      = YES
-
-# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend 
-# the brief description of a member or function before the detailed description. 
-# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the 
-# brief descriptions will be completely suppressed.
-
 REPEAT_BRIEF           = YES
-
-# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then 
-# Doxygen will generate a detailed section even if there is only a brief 
-# description.
-
+ABBREVIATE_BRIEF       = "The $name class" \
+                         "The $name widget" \
+                         "The $name file" \
+                         is \
+                         provides \
+                         specifies \
+                         contains \
+                         represents \
+                         a \
+                         an \
+                         the
 ALWAYS_DETAILED_SEC    = NO
-
-# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all inherited 
-# members of a class in the documentation of that class as if those members were 
-# ordinary class members. Constructors, destructors and assignment operators of 
-# the base classes will not be shown.
-
 INLINE_INHERITED_MEMB  = NO
-
-# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full 
-# path before files name in the file list and in the header files. If set 
-# to NO the shortest path that makes the file name unique will be used.
-
 FULL_PATH_NAMES        = NO
-
-# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag 
-# can be used to strip a user-defined part of the path. Stripping is 
-# only done if one of the specified strings matches the left-hand part of 
-# the path. It is allowed to use relative paths in the argument list.
-
 STRIP_FROM_PATH        = 
-
-# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter 
-# (but less readable) file names. This can be useful is your file systems 
-# doesn't support long names like on DOS, Mac, or CD-ROM.
-
+STRIP_FROM_INC_PATH    = 
 SHORT_NAMES            = NO
-
-# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen 
-# will interpret the first line (until the first dot) of a JavaDoc-style 
-# comment as the brief description. If set to NO, the JavaDoc 
-# comments will behave just like the Qt-style comments (thus requiring an 
-# explict @brief command for a brief description.
-
 JAVADOC_AUTOBRIEF      = NO
-
-# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen 
-# treat a multi-line C++ special comment block (i.e. a block of //! or /// 
-# comments) as a brief description. This used to be the default behaviour. 
-# The new default is to treat a multi-line C++ comment block as a detailed 
-# description. Set this tag to YES if you prefer the old behaviour instead.
-
+QT_AUTOBRIEF           = NO
 MULTILINE_CPP_IS_BRIEF = NO
-
-# If the DETAILS_AT_TOP tag is set to YES then Doxygen 
-# will output the detailed description near the top, like JavaDoc.
-# If set to NO, the detailed description appears after the member 
-# documentation.
-
 DETAILS_AT_TOP         = NO
-
-# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented 
-# member inherits the documentation from any documented member that it 
-# reimplements.
-
 INHERIT_DOCS           = YES
-
-# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC 
-# tag is set to YES, then doxygen will reuse the documentation of the first 
-# member in the group (if any) for the other members of the group. By default 
-# all members of a group must be documented explicitly.
-
-DISTRIBUTE_GROUP_DOC   = NO
-
-# The TAB_SIZE tag can be used to set the number of spaces in a tab. 
-# Doxygen uses this value to replace tabs by spaces in code fragments.
-
+SEPARATE_MEMBER_PAGES  = NO
 TAB_SIZE               = 8
-
-# This tag can be used to specify a number of aliases that acts 
-# as commands in the documentation. An alias has the form "name=value". 
-# For example adding "sideeffect=\par Side Effects:\n" will allow you to 
-# put the command \sideeffect (or @sideeffect) in the documentation, which 
-# will result in a user-defined paragraph with heading "Side Effects:". 
-# You can put \n's in the value part of an alias to insert newlines.
-
 ALIASES                = 
-
-# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources 
-# only. Doxygen will then generate output that is more tailored for C. 
-# For instance, some of the names that are used will be different. The list 
-# of all members will be omitted, etc.
-
 OPTIMIZE_OUTPUT_FOR_C  = NO
-
-# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java sources 
-# only. Doxygen will then generate output that is more tailored for Java. 
-# For instance, namespaces will be presented as packages, qualified scopes 
-# will look different, etc.
-
 OPTIMIZE_OUTPUT_JAVA   = NO
-
-# Set the SUBGROUPING tag to YES (the default) to allow class member groups of 
-# the same type (for instance a group of public functions) to be put as a 
-# subgroup of that type (e.g. under the Public Functions section). Set it to 
-# NO to prevent subgrouping. Alternatively, this can be done per class using 
-# the \nosubgrouping command.
-
+OPTIMIZE_FOR_FORTRAN   = NO
+OPTIMIZE_OUTPUT_VHDL   = NO
+BUILTIN_STL_SUPPORT    = NO
+CPP_CLI_SUPPORT        = NO
+SIP_SUPPORT            = NO
+IDL_PROPERTY_SUPPORT   = YES
+DISTRIBUTE_GROUP_DOC   = NO
 SUBGROUPING            = YES
-
+TYPEDEF_HIDES_STRUCT   = NO
 #---------------------------------------------------------------------------
 # Build related configuration options
 #---------------------------------------------------------------------------
-
-# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in 
-# documentation are documented, even if no documentation was available. 
-# Private class members and static file members will be hidden unless 
-# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
-
 EXTRACT_ALL            = NO
-
-# If the EXTRACT_PRIVATE tag is set to YES all private members of a class 
-# will be included in the documentation.
-
 EXTRACT_PRIVATE        = NO
-
-# If the EXTRACT_STATIC tag is set to YES all static members of a file 
-# will be included in the documentation.
-
 EXTRACT_STATIC         = NO
-
-# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) 
-# defined locally in source files will be included in the documentation. 
-# If set to NO only classes defined in header files are included.
-
 EXTRACT_LOCAL_CLASSES  = YES
-
-# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all 
-# undocumented members of documented classes, files or namespaces. 
-# If set to NO (the default) these members will be included in the 
-# various overviews, but no documentation section is generated. 
-# This option has no effect if EXTRACT_ALL is enabled.
-
+EXTRACT_LOCAL_METHODS  = NO
+EXTRACT_ANON_NSPACES   = NO
 HIDE_UNDOC_MEMBERS     = YES
-
-# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all 
-# undocumented classes that are normally visible in the class hierarchy. 
-# If set to NO (the default) these classes will be included in the various 
-# overviews. This option has no effect if EXTRACT_ALL is enabled.
-
 HIDE_UNDOC_CLASSES     = YES
-
-# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all 
-# friend (class|struct|union) declarations. 
-# If set to NO (the default) these declarations will be included in the 
-# documentation.
-
 HIDE_FRIEND_COMPOUNDS  = NO
-
-# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any 
-# documentation blocks found inside the body of a function. 
-# If set to NO (the default) these blocks will be appended to the 
-# function's detailed documentation block.
-
 HIDE_IN_BODY_DOCS      = NO
-
-# The INTERNAL_DOCS tag determines if documentation 
-# that is typed after a \internal command is included. If the tag is set 
-# to NO (the default) then the documentation will be excluded. 
-# Set it to YES to include the internal documentation.
-
 INTERNAL_DOCS          = NO
-
-# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate 
-# file names in lower-case letters. If set to YES upper-case letters are also 
-# allowed. This is useful if you have classes or files whose names only differ 
-# in case and if your file system supports case sensitive file names. Windows 
-# users are advised to set this option to NO.
-
 CASE_SENSE_NAMES       = YES
-
-# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen 
-# will show members with their full class and namespace scopes in the 
-# documentation. If set to YES the scope will be hidden.
-
 HIDE_SCOPE_NAMES       = NO
-
-# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen 
-# will put a list of the files that are included by a file in the documentation 
-# of that file.
-
 SHOW_INCLUDE_FILES     = YES
-
-# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] 
-# is inserted in the documentation for inline members.
-
 INLINE_INFO            = YES
-
-# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen 
-# will sort the (detailed) documentation of file and class members 
-# alphabetically by member name. If set to NO the members will appear in 
-# declaration order.
-
 SORT_MEMBER_DOCS       = NO
-
-# The GENERATE_TODOLIST tag can be used to enable (YES) or 
-# disable (NO) the todo list. This list is created by putting \todo 
-# commands in the documentation.
-
+SORT_BRIEF_DOCS        = NO
+SORT_GROUP_NAMES       = NO
+SORT_BY_SCOPE_NAME     = NO
 GENERATE_TODOLIST      = YES
-
-# The GENERATE_TESTLIST tag can be used to enable (YES) or 
-# disable (NO) the test list. This list is created by putting \test 
-# commands in the documentation.
-
 GENERATE_TESTLIST      = YES
-
-# The GENERATE_BUGLIST tag can be used to enable (YES) or 
-# disable (NO) the bug list. This list is created by putting \bug 
-# commands in the documentation.
-
 GENERATE_BUGLIST       = YES
-
-# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or 
-# disable (NO) the deprecated list. This list is created by putting 
-# \deprecated commands in the documentation.
-
 GENERATE_DEPRECATEDLIST= YES
-
-# The ENABLED_SECTIONS tag can be used to enable conditional 
-# documentation sections, marked by \if sectionname ... \endif.
-
 ENABLED_SECTIONS       = 
-
-# The MAX_INITIALIZER_LINES tag determines the maximum number of lines 
-# the initial value of a variable or define consists of for it to appear in 
-# the documentation. If the initializer consists of more lines than specified 
-# here it will be hidden. Use a value of 0 to hide initializers completely. 
-# The appearance of the initializer of individual variables and defines in the 
-# documentation can be controlled using \showinitializer or \hideinitializer 
-# command in the documentation regardless of this setting.
-
 MAX_INITIALIZER_LINES  = 30
-
-# Set the SHOW_USED_FILES tag to NO to disable the list of files generated 
-# at the bottom of the documentation of classes and structs. If set to YES the 
-# list will mention the files that were used to generate the documentation.
-
 SHOW_USED_FILES        = YES
-
+SHOW_DIRECTORIES       = NO
+SHOW_FILES             = YES
+SHOW_NAMESPACES        = YES
+FILE_VERSION_FILTER    = 
 #---------------------------------------------------------------------------
 # configuration options related to warning and progress messages
 #---------------------------------------------------------------------------
-
-# The QUIET tag can be used to turn on/off the messages that are generated 
-# by doxygen. Possible values are YES and NO. If left blank NO is used.
-
 QUIET                  = NO
-
-# The WARNINGS tag can be used to turn on/off the warning messages that are 
-# generated by doxygen. Possible values are YES and NO. If left blank 
-# NO is used.
-
 WARNINGS               = YES
-
-# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings 
-# for undocumented members. If EXTRACT_ALL is set to YES then this flag will 
-# automatically be disabled.
-
 WARN_IF_UNDOCUMENTED   = YES
-
-# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for 
-# potential errors in the documentation, such as not documenting some 
-# parameters in a documented function, or documenting parameters that 
-# don't exist or using markup commands wrongly.
-
 WARN_IF_DOC_ERROR      = YES
-
-# The WARN_FORMAT tag determines the format of the warning messages that 
-# doxygen can produce. The string should contain the $file, $line, and $text 
-# tags, which will be replaced by the file and line number from which the 
-# warning originated and the warning text.
-
+WARN_NO_PARAMDOC       = NO
 WARN_FORMAT            = "$file:$line: $text"
-
-# The WARN_LOGFILE tag can be used to specify a file to which warning 
-# and error messages should be written. If left blank the output is written 
-# to stderr.
-
 WARN_LOGFILE           = 
-
 #---------------------------------------------------------------------------
 # configuration options related to the input files
 #---------------------------------------------------------------------------
-
-# The INPUT tag can be used to specify the files and/or directories that contain 
-# documented source files. You may enter file names like "myfile.cpp" or 
-# directories like "/usr/src/myproject". Separate the files or directories 
-# with spaces.
-
 INPUT                  = . \
                          ../../RtAudio.h \
                          ../../RtError.h
-
-# If the value of the INPUT tag contains directories, you can use the 
-# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp 
-# and *.h) to filter out the source-files in the directories. If left 
-# blank the following patterns are tested: 
-# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx *.hpp 
-# *.h++ *.idl *.odl *.cs *.php *.php3 *.inc
-
+INPUT_ENCODING         = UTF-8
 FILE_PATTERNS          = *.txt
-
-# The RECURSIVE tag can be used to turn specify whether or not subdirectories 
-# should be searched for input files as well. Possible values are YES and NO. 
-# If left blank NO is used.
-
 RECURSIVE              = NO
-
-# The EXCLUDE tag can be used to specify files and/or directories that should 
-# excluded from the INPUT source files. This way you can easily exclude a 
-# subdirectory from a directory tree whose root is specified with the INPUT tag.
-
 EXCLUDE                = 
-
-# The EXCLUDE_SYMLINKS tag can be used select whether or not files or directories 
-# that are symbolic links (a Unix filesystem feature) are excluded from the input.
-
 EXCLUDE_SYMLINKS       = NO
-
-# If the value of the INPUT tag contains directories, you can use the 
-# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude 
-# certain files from those directories.
-
 EXCLUDE_PATTERNS       = 
-
-# The EXAMPLE_PATH tag can be used to specify one or more files or 
-# directories that contain example code fragments that are included (see 
-# the \include command).
-
+EXCLUDE_SYMBOLS        = 
 EXAMPLE_PATH           = ../../tests/
-
-# If the value of the EXAMPLE_PATH tag contains directories, you can use the 
-# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp 
-# and *.h) to filter out the source-files in the directories. If left 
-# blank all files are included.
-
 EXAMPLE_PATTERNS       = 
-
-# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be 
-# searched for input files to be used with the \include or \dontinclude 
-# commands irrespective of the value of the RECURSIVE tag. 
-# Possible values are YES and NO. If left blank NO is used.
-
 EXAMPLE_RECURSIVE      = NO
-
-# The IMAGE_PATH tag can be used to specify one or more files or 
-# directories that contain image that are included in the documentation (see 
-# the \image command).
-
 IMAGE_PATH             = 
-
-# The INPUT_FILTER tag can be used to specify a program that doxygen should 
-# invoke to filter for each input file. Doxygen will invoke the filter program 
-# by executing (via popen()) the command <filter> <input-file>, where <filter> 
-# is the value of the INPUT_FILTER tag, and <input-file> is the name of an 
-# input file. Doxygen will then use the output that the filter program writes 
-# to standard output.
-
 INPUT_FILTER           = 
-
-# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using 
-# INPUT_FILTER) will be used to filter the input files when producing source 
-# files to browse (i.e. when SOURCE_BROWSER is set to YES).
-
+FILTER_PATTERNS        = 
 FILTER_SOURCE_FILES    = NO
-
 #---------------------------------------------------------------------------
 # configuration options related to source browsing
 #---------------------------------------------------------------------------
-
-# If the SOURCE_BROWSER tag is set to YES then a list of source files will 
-# be generated. Documented entities will be cross-referenced with these sources.
-
 SOURCE_BROWSER         = NO
-
-# Setting the INLINE_SOURCES tag to YES will include the body 
-# of functions and classes directly in the documentation.
-
 INLINE_SOURCES         = NO
-
-# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct 
-# doxygen to hide any special comment blocks from generated source code 
-# fragments. Normal C and C++ comments will always remain visible.
-
 STRIP_CODE_COMMENTS    = YES
-
-# If the REFERENCED_BY_RELATION tag is set to YES (the default) 
-# then for each documented function all documented 
-# functions referencing it will be listed.
-
 REFERENCED_BY_RELATION = YES
-
-# If the REFERENCES_RELATION tag is set to YES (the default) 
-# then for each documented function all documented entities 
-# called/used by that function will be listed.
-
 REFERENCES_RELATION    = YES
-
-# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen 
-# will generate a verbatim copy of the header file for each class for 
-# which an include is specified. Set to NO to disable this.
-
+REFERENCES_LINK_SOURCE = YES
+USE_HTAGS              = NO
 VERBATIM_HEADERS       = YES
-
 #---------------------------------------------------------------------------
 # configuration options related to the alphabetical class index
 #---------------------------------------------------------------------------
-
-# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index 
-# of all compounds will be generated. Enable this if the project 
-# contains a lot of classes, structs, unions or interfaces.
-
 ALPHABETICAL_INDEX     = NO
-
-# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then 
-# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns 
-# in which this list will be split (can be a number in the range [1..20])
-
 COLS_IN_ALPHA_INDEX    = 5
-
-# In case all classes in a project start with a common prefix, all 
-# classes will be put under the same header in the alphabetical index. 
-# The IGNORE_PREFIX tag can be used to specify one or more prefixes that 
-# should be ignored while generating the index headers.
-
 IGNORE_PREFIX          = 
-
 #---------------------------------------------------------------------------
 # configuration options related to the HTML output
 #---------------------------------------------------------------------------
-
-# If the GENERATE_HTML tag is set to YES (the default) Doxygen will 
-# generate HTML output.
-
 GENERATE_HTML          = YES
-
-# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. 
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
-# put in front of it. If left blank `html' will be used as the default path.
-
 HTML_OUTPUT            = ../html
-
-# The HTML_FILE_EXTENSION tag can be used to specify the file extension for 
-# each generated HTML page (for example: .htm,.php,.asp). If it is left blank 
-# doxygen will generate files with .html extension.
-
 HTML_FILE_EXTENSION    = .html
-
-# The HTML_HEADER tag can be used to specify a personal HTML header for 
-# each generated HTML page. If it is left blank doxygen will generate a 
-# standard header.
-
 HTML_HEADER            = header.html
-
-# The HTML_FOOTER tag can be used to specify a personal HTML footer for 
-# each generated HTML page. If it is left blank doxygen will generate a 
-# standard footer.
-
 HTML_FOOTER            = footer.html
-
-# The HTML_STYLESHEET tag can be used to specify a user-defined cascading 
-# style sheet that is used by each HTML page. It can be used to 
-# fine-tune the look of the HTML output. If the tag is left blank doxygen 
-# will generate a default style sheet
-
 HTML_STYLESHEET        = 
-
-# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, 
-# files or namespaces will be aligned in HTML using tables. If set to 
-# NO a bullet list will be used.
-
 HTML_ALIGN_MEMBERS     = YES
-
-# If the GENERATE_HTMLHELP tag is set to YES, additional index files 
-# will be generated that can be used as input for tools like the 
-# Microsoft HTML help workshop to generate a compressed HTML help file (.chm) 
-# of the generated HTML documentation.
-
 GENERATE_HTMLHELP      = NO
-
-# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can 
-# be used to specify the file name of the resulting .chm file. You 
-# can add a path in front of the file if the result should not be 
-# written to the html output dir.
-
+GENERATE_DOCSET        = NO
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+HTML_DYNAMIC_SECTIONS  = NO
 CHM_FILE               = 
-
-# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can 
-# be used to specify the location (absolute path including file name) of 
-# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run 
-# the HTML help compiler on the generated index.hhp.
-
 HHC_LOCATION           = 
-
-# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag 
-# controls if a separate .chi index file is generated (YES) or that 
-# it should be included in the master .chm file (NO).
-
 GENERATE_CHI           = NO
-
-# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag 
-# controls whether a binary table of contents is generated (YES) or a 
-# normal table of contents (NO) in the .chm file.
-
+CHM_INDEX_ENCODING     = 
 BINARY_TOC             = NO
-
-# The TOC_EXPAND flag can be set to YES to add extra items for group members 
-# to the contents of the HTML help documentation and to the tree view.
-
 TOC_EXPAND             = NO
-
-# The DISABLE_INDEX tag can be used to turn on/off the condensed index at 
-# top of each HTML page. The value NO (the default) enables the index and 
-# the value YES disables it.
-
 DISABLE_INDEX          = YES
-
-# This tag can be used to set the number of enum values (range [1..20]) 
-# that doxygen will group on one line in the generated HTML documentation.
-
 ENUM_VALUES_PER_LINE   = 4
-
-# If the GENERATE_TREEVIEW tag is set to YES, a side panel will be
-# generated containing a tree-like index structure (just like the one that 
-# is generated for HTML Help). For this to work a browser that supports 
-# JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, 
-# Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are 
-# probably better off using the HTML help feature.
-
 GENERATE_TREEVIEW      = NO
-
-# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be 
-# used to set the initial width (in pixels) of the frame in which the tree 
-# is shown.
-
 TREEVIEW_WIDTH         = 250
-
+FORMULA_FONTSIZE       = 10
 #---------------------------------------------------------------------------
 # configuration options related to the LaTeX output
 #---------------------------------------------------------------------------
-
-# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will 
-# generate Latex output.
-
 GENERATE_LATEX         = NO
-
-# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. 
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
-# put in front of it. If left blank `latex' will be used as the default path.
-
 LATEX_OUTPUT           = latex
-
-# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be 
-# invoked. If left blank `latex' will be used as the default command name.
-
 LATEX_CMD_NAME         = latex
-
-# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to 
-# generate index for LaTeX. If left blank `makeindex' will be used as the 
-# default command name.
-
 MAKEINDEX_CMD_NAME     = makeindex
-
-# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact 
-# LaTeX documents. This may be useful for small projects and may help to 
-# save some trees in general.
-
 COMPACT_LATEX          = NO
-
-# The PAPER_TYPE tag can be used to set the paper type that is used 
-# by the printer. Possible values are: a4, a4wide, letter, legal and 
-# executive. If left blank a4wide will be used.
-
 PAPER_TYPE             = letter
-
-# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX 
-# packages that should be included in the LaTeX output.
-
 EXTRA_PACKAGES         = 
-
-# The LATEX_HEADER tag can be used to specify a personal LaTeX header for 
-# the generated latex document. The header should contain everything until 
-# the first chapter. If it is left blank doxygen will generate a 
-# standard header. Notice: only use this tag if you know what you are doing!
-
 LATEX_HEADER           = 
-
-# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated 
-# is prepared for conversion to pdf (using ps2pdf). The pdf file will 
-# contain links (just like the HTML output) instead of page references 
-# This makes the output suitable for online browsing using a pdf viewer.
-
 PDF_HYPERLINKS         = NO
-
-# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of 
-# plain latex in the generated Makefile. Set this option to YES to get a 
-# higher quality PDF documentation.
-
 USE_PDFLATEX           = YES
-
-# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. 
-# command to the generated LaTeX files. This will instruct LaTeX to keep 
-# running if errors occur, instead of asking the user for help. 
-# This option is also used when generating formulas in HTML.
-
 LATEX_BATCHMODE        = NO
-
-# If LATEX_HIDE_INDICES is set to YES then doxygen will not 
-# include the index chapters (such as File Index, Compound Index, etc.) 
-# in the output.
-
 LATEX_HIDE_INDICES     = NO
-
 #---------------------------------------------------------------------------
 # configuration options related to the RTF output
 #---------------------------------------------------------------------------
-
-# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output 
-# The RTF output is optimised for Word 97 and may not look very pretty with 
-# other RTF readers or editors.
-
 GENERATE_RTF           = NO
-
-# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. 
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
-# put in front of it. If left blank `rtf' will be used as the default path.
-
 RTF_OUTPUT             = rtf
-
-# If the COMPACT_RTF tag is set to YES Doxygen generates more compact 
-# RTF documents. This may be useful for small projects and may help to 
-# save some trees in general.
-
 COMPACT_RTF            = NO
-
-# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated 
-# will contain hyperlink fields. The RTF file will 
-# contain links (just like the HTML output) instead of page references. 
-# This makes the output suitable for online browsing using WORD or other 
-# programs which support those fields. 
-# Note: wordpad (write) and others do not support links.
-
 RTF_HYPERLINKS         = NO
-
-# Load stylesheet definitions from file. Syntax is similar to doxygen's 
-# config file, i.e. a series of assigments. You only have to provide 
-# replacements, missing definitions are set to their default value.
-
 RTF_STYLESHEET_FILE    = 
-
-# Set optional variables used in the generation of an rtf document. 
-# Syntax is similar to doxygen's config file.
-
 RTF_EXTENSIONS_FILE    = 
-
 #---------------------------------------------------------------------------
 # configuration options related to the man page output
 #---------------------------------------------------------------------------
-
-# If the GENERATE_MAN tag is set to YES (the default) Doxygen will 
-# generate man pages
-
 GENERATE_MAN           = NO
-
-# The MAN_OUTPUT tag is used to specify where the man pages will be put. 
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
-# put in front of it. If left blank `man' will be used as the default path.
-
 MAN_OUTPUT             = man
-
-# The MAN_EXTENSION tag determines the extension that is added to 
-# the generated man pages (default is the subroutine's section .3)
-
 MAN_EXTENSION          = .3
-
-# If the MAN_LINKS tag is set to YES and Doxygen generates man output, 
-# then it will generate one additional man file for each entity 
-# documented in the real man page(s). These additional files 
-# only source the real man page, but without them the man command 
-# would be unable to find the correct page. The default is NO.
-
 MAN_LINKS              = NO
-
 #---------------------------------------------------------------------------
 # configuration options related to the XML output
 #---------------------------------------------------------------------------
-
-# If the GENERATE_XML tag is set to YES Doxygen will 
-# generate an XML file that captures the structure of 
-# the code including all documentation. Note that this 
-# feature is still experimental and incomplete at the 
-# moment.
-
 GENERATE_XML           = NO
-
-# The XML_OUTPUT tag is used to specify where the XML pages will be put. 
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be 
-# put in front of it. If left blank `xml' will be used as the default path.
-
 XML_OUTPUT             = xml
-
-# The XML_SCHEMA tag can be used to specify an XML schema, 
-# which can be used by a validating XML parser to check the 
-# syntax of the XML files.
-
 XML_SCHEMA             = 
-
-# The XML_DTD tag can be used to specify an XML DTD, 
-# which can be used by a validating XML parser to check the 
-# syntax of the XML files.
-
 XML_DTD                = 
-
+XML_PROGRAMLISTING     = YES
 #---------------------------------------------------------------------------
 # configuration options for the AutoGen Definitions output
 #---------------------------------------------------------------------------
-
-# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will 
-# generate an AutoGen Definitions (see autogen.sf.net) file 
-# that captures the structure of the code including all 
-# documentation. Note that this feature is still experimental 
-# and incomplete at the moment.
-
 GENERATE_AUTOGEN_DEF   = NO
-
 #---------------------------------------------------------------------------
 # configuration options related to the Perl module output
 #---------------------------------------------------------------------------
-
-# If the GENERATE_PERLMOD tag is set to YES Doxygen will 
-# generate a Perl module file that captures the structure of 
-# the code including all documentation. Note that this 
-# feature is still experimental and incomplete at the 
-# moment.
-
 GENERATE_PERLMOD       = NO
-
-# If the PERLMOD_LATEX tag is set to YES Doxygen will generate 
-# the necessary Makefile rules, Perl scripts and LaTeX code to be able 
-# to generate PDF and DVI output from the Perl module output.
-
 PERLMOD_LATEX          = NO
-
-# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be 
-# nicely formatted so it can be parsed by a human reader.  This is useful 
-# if you want to understand what is going on.  On the other hand, if this 
-# tag is set to NO the size of the Perl module output will be much smaller 
-# and Perl will parse it just the same.
-
 PERLMOD_PRETTY         = YES
-
-# The names of the make variables in the generated doxyrules.make file 
-# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. 
-# This is useful so different doxyrules.make files included by the same 
-# Makefile don't overwrite each other's variables.
-
 PERLMOD_MAKEVAR_PREFIX = 
-
 #---------------------------------------------------------------------------
 # Configuration options related to the preprocessor   
 #---------------------------------------------------------------------------
-
-# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will 
-# evaluate all C-preprocessor directives found in the sources and include 
-# files.
-
 ENABLE_PREPROCESSING   = YES
-
-# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro 
-# names in the source code. If set to NO (the default) only conditional 
-# compilation will be performed. Macro expansion can be done in a controlled 
-# way by setting EXPAND_ONLY_PREDEF to YES.
-
 MACRO_EXPANSION        = NO
-
-# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES 
-# then the macro expansion is limited to the macros specified with the 
-# PREDEFINED and EXPAND_AS_PREDEFINED tags.
-
 EXPAND_ONLY_PREDEF     = NO
-
-# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files 
-# in the INCLUDE_PATH (see below) will be search if a #include is found.
-
 SEARCH_INCLUDES        = YES
-
-# The INCLUDE_PATH tag can be used to specify one or more directories that 
-# contain include files that are not input files but should be processed by 
-# the preprocessor.
-
 INCLUDE_PATH           = 
-
-# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard 
-# patterns (like *.h and *.hpp) to filter out the header-files in the 
-# directories. If left blank, the patterns specified with FILE_PATTERNS will 
-# be used.
-
 INCLUDE_FILE_PATTERNS  = 
-
-# The PREDEFINED tag can be used to specify one or more macro names that 
-# are defined before the preprocessor is started (similar to the -D option of 
-# gcc). The argument of the tag is a list of macros of the form: name 
-# or name=definition (no spaces). If the definition and the = are 
-# omitted =1 is assumed.
-
 PREDEFINED             = 
-
-# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then 
-# this tag can be used to specify a list of macro names that should be expanded. 
-# The macro definition that is found in the sources will be used. 
-# Use the PREDEFINED tag if you want to use a different macro definition.
-
 EXPAND_AS_DEFINED      = 
-
-# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then 
-# doxygen's preprocessor will remove all function-like macros that are alone 
-# on a line, have an all uppercase name, and do not end with a semicolon. Such 
-# function macros are typically used for boiler-plate code, and will confuse the 
-# parser if not removed.
-
 SKIP_FUNCTION_MACROS   = YES
-
 #---------------------------------------------------------------------------
-# Configuration::addtions related to external references   
+# Configuration::additions related to external references   
 #---------------------------------------------------------------------------
-
-# The TAGFILES option can be used to specify one or more tagfiles. 
-# Optionally an initial location of the external documentation 
-# can be added for each tagfile. The format of a tag file without 
-# this location is as follows: 
-#   TAGFILES = file1 file2 ... 
-# Adding location for the tag files is done as follows: 
-#   TAGFILES = file1=loc1 "file2 = loc2" ... 
-# where "loc1" and "loc2" can be relative or absolute paths or 
-# URLs. If a location is present for each tag, the installdox tool 
-# does not have to be run to correct the links.
-# Note that each tag file must have a unique name
-# (where the name does NOT include the path)
-# If a tag file is not located in the directory in which doxygen 
-# is run, you must also specify the path to the tagfile here.
-
 TAGFILES               = 
-
-# When a file name is specified after GENERATE_TAGFILE, doxygen will create 
-# a tag file that is based on the input files it reads.
-
 GENERATE_TAGFILE       = 
-
-# If the ALLEXTERNALS tag is set to YES all external classes will be listed 
-# in the class index. If set to NO only the inherited external classes 
-# will be listed.
-
 ALLEXTERNALS           = NO
-
-# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed 
-# in the modules index. If set to NO, only the current project's groups will 
-# be listed.
-
 EXTERNAL_GROUPS        = YES
-
-# The PERL_PATH should be the absolute path and name of the perl script 
-# interpreter (i.e. the result of `which perl').
-
 PERL_PATH              = /usr/bin/perl
-
 #---------------------------------------------------------------------------
 # Configuration options related to the dot tool   
 #---------------------------------------------------------------------------
-
-# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will 
-# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base or 
-# super classes. Setting the tag to NO turns the diagrams off. Note that this 
-# option is superceded by the HAVE_DOT option below. This is only a fallback. It is 
-# recommended to install and use dot, since it yields more powerful graphs.
-
 CLASS_DIAGRAMS         = YES
-
-# If set to YES, the inheritance and collaboration graphs will hide 
-# inheritance and usage relations if the target is undocumented 
-# or is not a class.
-
+MSCGEN_PATH            = /Applications/Doxygen.app/Contents/Resources/
 HIDE_UNDOC_RELATIONS   = YES
-
-# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is 
-# available from the path. This tool is part of Graphviz, a graph visualization 
-# toolkit from AT&T and Lucent Bell Labs. The other options in this section 
-# have no effect if this option is set to NO (the default)
-
 HAVE_DOT               = NO
-
-# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen 
-# will generate a graph for each documented class showing the direct and 
-# indirect inheritance relations. Setting this tag to YES will force the 
-# the CLASS_DIAGRAMS tag to NO.
-
+DOT_FONTNAME           = FreeSans
+DOT_FONTPATH           = 
 CLASS_GRAPH            = YES
-
-# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen 
-# will generate a graph for each documented class showing the direct and 
-# indirect implementation dependencies (inheritance, containment, and 
-# class references variables) of the class with other documented classes.
-
 COLLABORATION_GRAPH    = YES
-
-# If the UML_LOOK tag is set to YES doxygen will generate inheritance and 
-# collaboration diagrams in a style similiar to the OMG's Unified Modeling 
-# Language.
-
+GROUP_GRAPHS           = YES
 UML_LOOK               = NO
-
-# If set to YES, the inheritance and collaboration graphs will show the 
-# relations between templates and their instances.
-
 TEMPLATE_RELATIONS     = NO
-
-# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT 
-# tags are set to YES then doxygen will generate a graph for each documented 
-# file showing the direct and indirect include dependencies of the file with 
-# other documented files.
-
 INCLUDE_GRAPH          = YES
-
-# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and 
-# HAVE_DOT tags are set to YES then doxygen will generate a graph for each 
-# documented header file showing the documented files that directly or 
-# indirectly include this file.
-
 INCLUDED_BY_GRAPH      = YES
-
-# If the CALL_GRAPH and HAVE_DOT tags are set to YES then doxygen will 
-# generate a call dependency graph for every global function or class method. 
-# Note that enabling this option will significantly increase the time of a run. 
-# So in most cases it will be better to enable call graphs for selected 
-# functions only using the \callgraph command.
-
 CALL_GRAPH             = NO
-
-# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen 
-# will graphical hierarchy of all classes instead of a textual one.
-
+CALLER_GRAPH           = NO
 GRAPHICAL_HIERARCHY    = YES
-
-# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images 
-# generated by dot. Possible values are png, jpg, or gif
-# If left blank png will be used.
-
+DIRECTORY_GRAPH        = YES
 DOT_IMAGE_FORMAT       = png
-
-# The tag DOT_PATH can be used to specify the path where the dot tool can be 
-# found. If left blank, it is assumed the dot tool can be found on the path.
-
-DOT_PATH               = 
-
-# The DOTFILE_DIRS tag can be used to specify one or more directories that 
-# contain dot files that are included in the documentation (see the 
-# \dotfile command).
-
+DOT_PATH               = /Applications/Doxygen.app/Contents/Resources/
 DOTFILE_DIRS           = 
-
-# The MAX_DOT_GRAPH_WIDTH tag can be used to set the maximum allowed width 
-# (in pixels) of the graphs generated by dot. If a graph becomes larger than 
-# this value, doxygen will try to truncate the graph, so that it fits within 
-# the specified constraint. Beware that most browsers cannot cope with very 
-# large images.
-
-MAX_DOT_GRAPH_WIDTH    = 1024
-
-# The MAX_DOT_GRAPH_HEIGHT tag can be used to set the maximum allows height 
-# (in pixels) of the graphs generated by dot. If a graph becomes larger than 
-# this value, doxygen will try to truncate the graph, so that it fits within 
-# the specified constraint. Beware that most browsers cannot cope with very 
-# large images.
-
-MAX_DOT_GRAPH_HEIGHT   = 1024
-
-# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the 
-# graphs generated by dot. A depth value of 3 means that only nodes reachable 
-# from the root by following a path via at most 3 edges will be shown. Nodes that 
-# lay further from the root node will be omitted. Note that setting this option to 
-# 1 or 2 may greatly reduce the computation time needed for large code bases. Also 
-# note that a graph may be further truncated if the graph's image dimensions are 
-# not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH and MAX_DOT_GRAPH_HEIGHT). 
-# If 0 is used for the depth value (the default), the graph is not depth-constrained.
-
+DOT_GRAPH_MAX_NODES    = 50
 MAX_DOT_GRAPH_DEPTH    = 0
-
-# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will 
-# generate a legend page explaining the meaning of the various boxes and 
-# arrows in the dot generated graphs.
-
+DOT_TRANSPARENT        = YES
+DOT_MULTI_TARGETS      = NO
 GENERATE_LEGEND        = YES
-
-# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will 
-# remove the intermediate dot files that are used to generate 
-# the various graphs.
-
 DOT_CLEANUP            = YES
-
 #---------------------------------------------------------------------------
-# Configuration::addtions related to the search engine   
+# Configuration::additions related to the search engine   
 #---------------------------------------------------------------------------
-
-# The SEARCHENGINE tag specifies whether or not a search engine should be 
-# used. If set to NO the values of all tags below this one will be ignored.
-
 SEARCHENGINE           = NO
index 6d2718d0b456886061cc59de44b3b7918a718001..fd6004bd2f50440df6a085c85ef82a6d26255f55 100644 (file)
@@ -1,7 +1,7 @@
 <HR>
 
 <table><tr><td><img src="../images/mcgill.gif" width=165></td>
-  <td>&copy;2001-2008 Gary P. Scavone, McGill University. All Rights Reserved.<br>Maintained by <a href="http://www.music.mcgill.ca/~gary/">Gary P. Scavone</a>.</td></tr>
+  <td>&copy;2001-2009 Gary P. Scavone, McGill University. All Rights Reserved.<br>Maintained by <a href="http://www.music.mcgill.ca/~gary/">Gary P. Scavone</a>.</td></tr>
 </table>
 
 </BODY>
index abcdc2695a0e894a035b4c9dcd19ae3894fe94ae..f7a2f89c75af826abad6954e0343a5b33a585729 100644 (file)
@@ -1,7 +1,7 @@
 /*! \page license License
 
     RtAudio: a set of realtime audio i/o C++ classes<BR>
-    Copyright (c) 2001-2007 Gary P. Scavone
+    Copyright (c) 2001-2009 Gary P. Scavone
 
     Permission is hereby granted, free of charge, to any person
     obtaining a copy of this software and associated documentation files
index c8fd9cfc8509925c58ca3707c1f0f449c562aa43..b42a945a7f728b3f4232545542f8603c82bbac33 100644 (file)
@@ -32,7 +32,7 @@ Devices are now re-enumerated every time the RtAudio::getDeviceCount(), RtAudio:
 
 \section download Download
 
-Latest Release (24 January 2008): <A href="http://www.music.mcgill.ca/~gary/rtaudio/release/rtaudio-4.0.4.tar.gz">Version 4.0.4</A>
+Latest Release (?? January 2009): <A href="http://www.music.mcgill.ca/~gary/rtaudio/release/rtaudio-4.0.5.tar.gz">Version 4.0.5</A>
 
 \section documentation Documentation Links
 
index 4bccff856aa32f9f15489940702ab40f8e4ea9ea..70f82c732a2adf701812e781be8cfbaef7f0ece5 100644 (file)
@@ -1,6 +1,20 @@
 RtAudio - a set of C++ classes that provide a common API for realtime audio input/output across Linux (native ALSA, JACK, and OSS), Macintosh OS X (CoreAudio and JACK), and Windows (DirectSound and ASIO) operating systems.
 
-By Gary P. Scavone, 2001-2008.
+By Gary P. Scavone, 2001-2009.
+
+v4.0.5: (?? January 2009)
+- added support in CoreAudio for arbitrary stream channel configurations
+- added getStreamSampleRate() function because the actual sample rate can sometimes vary slightly from the specified one (thanks to Theo Veenker)
+- added new StreamOptions flag "RTAUDIO_SCHEDULE_REALTIME" and attribute "priority" to StreamOptions (thanks to Theo Veenker)
+- replaced usleep(50000) in callbackEvent() by a wait on condition variable which gets signaled in startStream() (thanks to Theo Veenker)
+- fix to way stream state is changed to avoid infinite loop problem
+- fix to int<->float conversion in convertBuffer() (thanks to Theo Veenker)
+- bug fix in byteSwapBuffer() (thanks to Stefan Muller Arisona and Theo Veenker)
+- fixed a few gcc 4.4 errors in OS-X
+- fixed bug in rtaudio-config script
+- revised configure script and Makefile structures
+- 64-bit fixes in ALSA API (thanks to Stefan Muller Arisona)
+- fixed ASIO sample rate selection bug (thanks to Sasha Zheligovsky)
 
 v4.0.4: (24 January 2008)
 - added functionality to allow getDeviceInfo() to work in ALSA for an open device (like ASIO)
diff --git a/install b/install
index 8bdd0ca53720ead9811ed0e5953d0be3e84a5c5b..70c795fefafe2202f5ea3d79480d8b7ce4bd2395 100644 (file)
--- a/install
+++ b/install
@@ -1,6 +1,6 @@
 RtAudio - a set of C++ classes which provide a common API for realtime audio input/output across Linux (native ALSA, JACK, and OSS), Macintosh OS X (CoreAudio and JACK), and Windows (DirectSound and ASIO) operating systems.
 
-By Gary P. Scavone, 2001-2008.
+By Gary P. Scavone, 2001-2009.
 
 To configure and compile (on Unix systems and MinGW):
 
diff --git a/readme b/readme
index 7c2c7b98f81ea05cb1438b99b2e3872f05a14849..d73ff9108b2691732460399e5c8f6856daf6ad98 100644 (file)
--- a/readme
+++ b/readme
@@ -1,6 +1,6 @@
 RtAudio - a set of C++ classes that provide a common API for realtime audio input/output across Linux (native ALSA, JACK, and OSS), Macintosh OS X (CoreAudio and JACK), and Windows (DirectSound and ASIO) operating systems.
 
-By Gary P. Scavone, 2001-2008.
+By Gary P. Scavone, 2001-2009.
 
 This distribution of RtAudio contains the following:
 
@@ -34,7 +34,7 @@ LEGAL AND ETHICAL:
 The RtAudio license is similar to the MIT License.
 
     RtAudio: a set of realtime audio i/o C++ classes
-    Copyright (c) 2001-2008 Gary P. Scavone
+    Copyright (c) 2001-2009 Gary P. Scavone
 
     Permission is hereby granted, free of charge, to any person
     obtaining a copy of this software and associated documentation files