Merge pull request #47 from radarsat1/fix-version
[rtaudio-cdist.git] / RtAudio.cpp
index f7c918de7b8dbea0f11f12d0ac1b293344cd3cbf..882fa0e2830202407c2f17814c8a4e372947993d 100644 (file)
-/************************************************************************/
-/*! \class RtAudio
-    \brief Realtime audio i/o C++ classes.
-
-    RtAudio provides a common API (Application Programming Interface)
-    for realtime audio input/output across Linux (native ALSA, Jack,
-    and OSS), SGI, Macintosh OS X (CoreAudio), and Windows
-    (DirectSound and ASIO) operating systems.
-
-    RtAudio WWW site: http://music.mcgill.ca/~gary/rtaudio/
-
-    RtAudio: realtime audio i/o C++ classes
-    Copyright (c) 2001-2005 Gary P. Scavone
-
-    Permission is hereby granted, free of charge, to any person
-    obtaining a copy of this software and associated documentation files
-    (the "Software"), to deal in the Software without restriction,
-    including without limitation the rights to use, copy, modify, merge,
-    publish, distribute, sublicense, and/or sell copies of the Software,
-    and to permit persons to whom the Software is furnished to do so,
-    subject to the following conditions:
-
-    The above copyright notice and this permission notice shall be
-    included in all copies or substantial portions of the Software.
-
-    Any person wishing to distribute modifications to the Software is
-    requested to send the modifications to the original developer so that
-    they can be incorporated into the canonical version.
-
-    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
-    ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
-    CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-*/
-/************************************************************************/
-
-// RtAudio: Version 3.0.3 (18 November 2005)
-
-#include "RtAudio.h"
-#include <iostream>
-#include <stdio.h>
-
-// Static variable definitions.
-const unsigned int RtApi::MAX_SAMPLE_RATES = 14;
-const unsigned int RtApi::SAMPLE_RATES[] = {
-  4000, 5512, 8000, 9600, 11025, 16000, 22050,
-  32000, 44100, 48000, 88200, 96000, 176400, 192000
-};
-
-#if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__)
-  #define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)
-  #define MUTEX_DESTROY(A)    DeleteCriticalSection(A);
-  #define MUTEX_LOCK(A)      EnterCriticalSection(A)
-  #define MUTEX_UNLOCK(A)     LeaveCriticalSection(A)
-#else // pthread API
-  #define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)
-  #define MUTEX_DESTROY(A)    pthread_mutex_destroy(A);
-  #define MUTEX_LOCK(A)       pthread_mutex_lock(A)
-  #define MUTEX_UNLOCK(A)     pthread_mutex_unlock(A)
-#endif
-
-// *************************************************** //
-//
-// Public common (OS-independent) methods.
-//
-// *************************************************** //
-
-RtAudio :: RtAudio( RtAudioApi api )
-{
-  initialize( api );
-}
-
-RtAudio :: RtAudio( int outputDevice, int outputChannels,
-                    int inputDevice, int inputChannels,
-                    RtAudioFormat format, int sampleRate,
-                    int *bufferSize, int numberOfBuffers, RtAudioApi api )
-{
-  initialize( api );
-
-  try {
-    rtapi_->openStream( outputDevice, outputChannels,
-                        inputDevice, inputChannels,
-                        format, sampleRate,
-                        bufferSize, numberOfBuffers );
-  }
-  catch (RtError &exception) {
-    // Deallocate the RtApi instance.
-    delete rtapi_;
-    throw exception;
-  }
-}
-
-RtAudio :: RtAudio( int outputDevice, int outputChannels,
-                    int inputDevice, int inputChannels,
-                    RtAudioFormat format, int sampleRate,
-                    int *bufferSize, int *numberOfBuffers, RtAudioApi api )
-{
-  initialize( api );
-
-  try {
-    rtapi_->openStream( outputDevice, outputChannels,
-                        inputDevice, inputChannels,
-                        format, sampleRate,
-                        bufferSize, numberOfBuffers );
-  }
-  catch (RtError &exception) {
-    // Deallocate the RtApi instance.
-    delete rtapi_;
-    throw exception;
-  }
-}
-
-RtAudio :: ~RtAudio()
-{
-  delete rtapi_;
-}
-
-void RtAudio :: openStream( int outputDevice, int outputChannels,
-                            int inputDevice, int inputChannels,
-                            RtAudioFormat format, int sampleRate,
-                            int *bufferSize, int numberOfBuffers )
-{
-  rtapi_->openStream( outputDevice, outputChannels, inputDevice,
-                      inputChannels, format, sampleRate,
-                      bufferSize, numberOfBuffers );
-}
-
-void RtAudio :: openStream( int outputDevice, int outputChannels,
-                            int inputDevice, int inputChannels,
-                            RtAudioFormat format, int sampleRate,
-                            int *bufferSize, int *numberOfBuffers )
-{
-  rtapi_->openStream( outputDevice, outputChannels, inputDevice,
-                      inputChannels, format, sampleRate,
-                      bufferSize, *numberOfBuffers );
-}
-
-void RtAudio::initialize( RtAudioApi api )
-{
-  rtapi_ = 0;
-
-  // First look for a compiled match to a specified API value. If one
-  // of these constructors throws an error, it will be passed up the
-  // inheritance chain.
-#if defined(__LINUX_JACK__)
-  if ( api == LINUX_JACK )
-    rtapi_ = new RtApiJack();
-#endif
-#if defined(__LINUX_ALSA__)
-  if ( api == LINUX_ALSA )
-    rtapi_ = new RtApiAlsa();
-#endif
-#if defined(__LINUX_OSS__)
-  if ( api == LINUX_OSS )
-    rtapi_ = new RtApiOss();
-#endif
-#if defined(__WINDOWS_ASIO__)
-  if ( api == WINDOWS_ASIO )
-    rtapi_ = new RtApiAsio();
-#endif
-#if defined(__WINDOWS_DS__)
-  if ( api == WINDOWS_DS )
-    rtapi_ = new RtApiDs();
-#endif
-#if defined(__IRIX_AL__)
-  if ( api == IRIX_AL )
-    rtapi_ = new RtApiAl();
-#endif
-#if defined(__MACOSX_CORE__)
-  if ( api == MACOSX_CORE )
-    rtapi_ = new RtApiCore();
-#endif
-
-  if ( rtapi_ ) return;
-  if ( api > 0 ) {
-    // No compiled support for specified API value.
-    throw RtError( "RtAudio: no compiled support for specified API argument!", RtError::INVALID_PARAMETER );
-  }
-
-  // No specified API ... search for "best" option.
-  try {
-#if defined(__LINUX_JACK__)
-    rtapi_ = new RtApiJack();
-#elif defined(__WINDOWS_ASIO__)
-    rtapi_ = new RtApiAsio();
-#elif defined(__IRIX_AL__)
-    rtapi_ = new RtApiAl();
-#elif defined(__MACOSX_CORE__)
-    rtapi_ = new RtApiCore();
-#else
-    ;
-#endif
-  }
-  catch (RtError &) {
-#if defined(__RTAUDIO_DEBUG__)
-    fprintf(stderr, "\nRtAudio: no devices found for first api option (JACK, ASIO, Al, or CoreAudio).\n\n");
-#endif
-    rtapi_ = 0;
-  }
-
-  if ( rtapi_ ) return;
-
-// Try second API support
-  if ( rtapi_ == 0 ) {
-    try {
-#if defined(__LINUX_ALSA__)
-      rtapi_ = new RtApiAlsa();
-#elif defined(__WINDOWS_DS__)
-      rtapi_ = new RtApiDs();
-#else
-      ;
-#endif
-    }
-    catch (RtError &) {
-#if defined(__RTAUDIO_DEBUG__)
-      fprintf(stderr, "\nRtAudio: no devices found for second api option (Alsa or DirectSound).\n\n");
-#endif
-      rtapi_ = 0;
-    }
-  }
-
-  if ( rtapi_ ) return;
-
-  // Try third API support
-  if ( rtapi_ == 0 ) {
-#if defined(__LINUX_OSS__)
-    try {
-      rtapi_ = new RtApiOss();
-    }
-    catch (RtError &error) {
-      rtapi_ = 0;
-    }
-#else
-    ;
-#endif
-  }
-
-  if ( rtapi_ == 0 ) {
-    // No devices found.
-    throw RtError( "RtAudio: no devices found for compiled audio APIs!", RtError::NO_DEVICES_FOUND );
-  }
-}
-
-RtApi :: RtApi()
-{
-  stream_.mode = UNINITIALIZED;
-  stream_.state = STREAM_STOPPED;
-  stream_.apiHandle = 0;
-  MUTEX_INITIALIZE(&stream_.mutex);
-}
-
-RtApi :: ~RtApi()
-{
-  MUTEX_DESTROY(&stream_.mutex);
-}
-
-void RtApi :: openStream( int outputDevice, int outputChannels,
-                         int inputDevice, int inputChannels,
-                         RtAudioFormat format, int sampleRate,
-                         int *bufferSize, int *numberOfBuffers )
-{
-  this->openStream( outputDevice, outputChannels, inputDevice,
-                    inputChannels, format, sampleRate,
-                    bufferSize, *numberOfBuffers );
-  *numberOfBuffers = stream_.nBuffers;
-}
-
-void RtApi :: openStream( int outputDevice, int outputChannels,
-                         int inputDevice, int inputChannels,
-                         RtAudioFormat format, int sampleRate,
-                         int *bufferSize, int numberOfBuffers )
-{
-  if ( stream_.mode != UNINITIALIZED ) {
-    sprintf(message_, "RtApi: only one open stream allowed per class instance.");
-    error(RtError::INVALID_STREAM);
-  }
-
-  if (outputChannels < 1 && inputChannels < 1) {
-    sprintf(message_,"RtApi: one or both 'channel' parameters must be greater than zero.");
-    error(RtError::INVALID_PARAMETER);
-  }
-
-  if ( formatBytes(format) == 0 ) {
-    sprintf(message_,"RtApi: 'format' parameter value is undefined.");
-    error(RtError::INVALID_PARAMETER);
-  }
-
-  if ( outputChannels > 0 ) {
-    if (outputDevice > nDevices_ || outputDevice < 0) {
-      sprintf(message_,"RtApi: 'outputDevice' parameter value (%d) is invalid.", outputDevice);
-      error(RtError::INVALID_PARAMETER);
-    }
-  }
-
-  if ( inputChannels > 0 ) {
-    if (inputDevice > nDevices_ || inputDevice < 0) {
-      sprintf(message_,"RtApi: 'inputDevice' parameter value (%d) is invalid.", inputDevice);
-      error(RtError::INVALID_PARAMETER);
-    }
-  }
-
-  std::string errorMessages;
-  clearStreamInfo();
-  bool result = FAILURE;
-  int device, defaultDevice = 0;
-  StreamMode mode;
-  int channels;
-  if ( outputChannels > 0 ) {
-
-    mode = OUTPUT;
-    channels = outputChannels;
-
-    if ( outputDevice == 0 ) { // Try default device first.
-      defaultDevice = getDefaultOutputDevice();
-      device = defaultDevice;
-    }
-    else
-      device = outputDevice - 1;
-
-    for ( int i=-1; i<nDevices_; i++ ) {
-      if ( i >= 0 ) { 
-        if ( i == defaultDevice ) continue;
-        device = i;
-      }
-      if ( devices_[device].probed == false ) {
-        // If the device wasn't successfully probed before, try it
-        // (again) now.
-        clearDeviceInfo(&devices_[device]);
-        probeDeviceInfo(&devices_[device]);
-      }
-      if ( devices_[device].probed )
-        result = probeDeviceOpen(device, mode, channels, sampleRate,
-                                 format, bufferSize, numberOfBuffers);
-      if ( result == SUCCESS ) break;
-      errorMessages.append( "    " );
-      errorMessages.append( message_ );
-      errorMessages.append( "\n" );
-      if ( outputDevice > 0 ) break;
-      clearStreamInfo();
-    }
-  }
-
-  if ( inputChannels > 0 && ( result == SUCCESS || outputChannels <= 0 ) ) {
-
-    mode = INPUT;
-    channels = inputChannels;
-
-    if ( inputDevice == 0 ) { // Try default device first.
-      defaultDevice = getDefaultInputDevice();
-      device = defaultDevice;
-    }
-    else
-      device = inputDevice - 1;
-
-    for ( int i=-1; i<nDevices_; i++ ) {
-      if (i >= 0 ) { 
-        if ( i == defaultDevice ) continue;
-        device = i;
-      }
-      if ( devices_[device].probed == false ) {
-        // If the device wasn't successfully probed before, try it
-        // (again) now.
-        clearDeviceInfo(&devices_[device]);
-        probeDeviceInfo(&devices_[device]);
-      }
-      if ( devices_[device].probed )
-        result = probeDeviceOpen( device, mode, channels, sampleRate,
-                                  format, bufferSize, numberOfBuffers );
-      if ( result == SUCCESS ) break;
-      errorMessages.append( "    " );
-      errorMessages.append( message_ );
-      errorMessages.append( "\n" );
-      if ( inputDevice > 0 ) break;
-    }
-  }
-
-  if ( result == SUCCESS )
-    return;
-
-  // If we get here, all attempted probes failed.  Close any opened
-  // devices and clear the stream structure.
-  if ( stream_.mode != UNINITIALIZED ) closeStream();
-  clearStreamInfo();
-  if ( ( outputDevice == 0 && outputChannels > 0 )
-       || ( inputDevice == 0 && inputChannels > 0 ) )
-    sprintf(message_,"RtApi: no devices found for given stream parameters: \n%s",
-            errorMessages.c_str());
-  else
-    sprintf(message_,"RtApi: unable to open specified device(s) with given stream parameters: \n%s",
-            errorMessages.c_str());
-  error(RtError::INVALID_PARAMETER);
-
-  return;
-}
-
-int RtApi :: getDeviceCount(void)
-{
-  return devices_.size();
-}
-
-RtApi::StreamState RtApi :: getStreamState( void ) const
-{
-  return stream_.state;
-}
-
-RtAudioDeviceInfo RtApi :: getDeviceInfo( int device )
-{
-  if (device > (int) devices_.size() || device < 1) {
-    sprintf(message_, "RtApi: invalid device specifier (%d)!", device);
-    error(RtError::INVALID_DEVICE);
-  }
-
-  RtAudioDeviceInfo info;
-  int deviceIndex = device - 1;
-
-  // If the device wasn't successfully probed before, try it now (or again).
-  if (devices_[deviceIndex].probed == false) {
-    clearDeviceInfo(&devices_[deviceIndex]);
-    probeDeviceInfo(&devices_[deviceIndex]);
-  }
-
-  info.name.append( devices_[deviceIndex].name );
-  info.probed = devices_[deviceIndex].probed;
-  if ( info.probed == true ) {
-    info.outputChannels = devices_[deviceIndex].maxOutputChannels;
-    info.inputChannels = devices_[deviceIndex].maxInputChannels;
-    info.duplexChannels = devices_[deviceIndex].maxDuplexChannels;
-    for (unsigned int i=0; i<devices_[deviceIndex].sampleRates.size(); i++)
-      info.sampleRates.push_back( devices_[deviceIndex].sampleRates[i] );
-    info.nativeFormats = devices_[deviceIndex].nativeFormats;
-    if ( (deviceIndex == getDefaultOutputDevice()) ||
-         (deviceIndex == getDefaultInputDevice()) )
-      info.isDefault = true;
-  }
-
-  return info;
-}
-
-char * const RtApi :: getStreamBuffer(void)
-{
-  verifyStream();
-  return stream_.userBuffer;
-}
-
-int RtApi :: getDefaultInputDevice(void)
-{
-  // Should be implemented in subclasses if appropriate.
-  return 0;
-}
-
-int RtApi :: getDefaultOutputDevice(void)
-{
-  // Should be implemented in subclasses if appropriate.
-  return 0;
-}
-
-void RtApi :: closeStream(void)
-{
-  // MUST be implemented in subclasses!
-}
-
-void RtApi :: probeDeviceInfo( RtApiDevice *info )
-{
-  // MUST be implemented in subclasses!
-}
-
-bool RtApi :: probeDeviceOpen( int device, StreamMode mode, int channels, 
-                               int sampleRate, RtAudioFormat format,
-                               int *bufferSize, int numberOfBuffers )
-{
-  // MUST be implemented in subclasses!
-  return FAILURE;
-}
-
-
-// *************************************************** //
-//
-// OS/API-specific methods.
-//
-// *************************************************** //
-
-#if defined(__LINUX_OSS__)
-
-#include <unistd.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <sys/soundcard.h>
-#include <errno.h>
-#include <math.h>
-
-#define DAC_NAME "/dev/dsp"
-#define MAX_DEVICES 16
-#define MAX_CHANNELS 16
-
-extern "C" void *ossCallbackHandler(void * ptr);
-
-RtApiOss :: RtApiOss()
-{
-  this->initialize();
-
-  if (nDevices_ <= 0) {
-    sprintf(message_, "RtApiOss: no Linux OSS audio devices found!");
-    error(RtError::NO_DEVICES_FOUND);
- }
-}
-
-RtApiOss :: ~RtApiOss()
-{
-  if ( stream_.mode != UNINITIALIZED )
-    closeStream();
-}
-
-void RtApiOss :: initialize(void)
-{
-  // Count cards and devices
-  nDevices_ = 0;
-
-  // We check /dev/dsp before probing devices.  /dev/dsp is supposed to
-  // be a link to the "default" audio device, of the form /dev/dsp0,
-  // /dev/dsp1, etc...  However, I've seen many cases where /dev/dsp was a
-  // real device, so we need to check for that.  Also, sometimes the
-  // link is to /dev/dspx and other times just dspx.  I'm not sure how
-  // the latter works, but it does.
-  char device_name[16];
-  struct stat dspstat;
-  int dsplink = -1;
-  int i = 0;
-  if (lstat(DAC_NAME, &dspstat) == 0) {
-    if (S_ISLNK(dspstat.st_mode)) {
-      i = readlink(DAC_NAME, device_name, sizeof(device_name));
-      if (i > 0) {
-        device_name[i] = '\0';
-        if (i > 8) { // check for "/dev/dspx"
-          if (!strncmp(DAC_NAME, device_name, 8))
-            dsplink = atoi(&device_name[8]);
-        }
-        else if (i > 3) { // check for "dspx"
-          if (!strncmp("dsp", device_name, 3))
-            dsplink = atoi(&device_name[3]);
-        }
-      }
-      else {
-        sprintf(message_, "RtApiOss: cannot read value of symbolic link %s.", DAC_NAME);
-        error(RtError::SYSTEM_ERROR);
-      }
-    }
-  }
-  else {
-    sprintf(message_, "RtApiOss: cannot stat %s.", DAC_NAME);
-    error(RtError::SYSTEM_ERROR);
-  }
-
-  // The OSS API doesn't provide a routine for determining the number
-  // of devices.  Thus, we'll just pursue a brute force method.  The
-  // idea is to start with /dev/dsp(0) and continue with higher device
-  // numbers until we reach MAX_DSP_DEVICES.  This should tell us how
-  // many devices we have ... it is not a fullproof scheme, but hopefully
-  // it will work most of the time.
-  int fd = 0;
-  RtApiDevice device;
-  for (i=-1; i<MAX_DEVICES; i++) {
-
-    // Probe /dev/dsp first, since it is supposed to be the default device.
-    if (i == -1)
-      sprintf(device_name, "%s", DAC_NAME);
-    else if (i == dsplink)
-      continue; // We've aready probed this device via /dev/dsp link ... try next device.
-    else
-      sprintf(device_name, "%s%d", DAC_NAME, i);
-
-    // First try to open the device for playback, then record mode.
-    fd = open(device_name, O_WRONLY | O_NONBLOCK);
-    if (fd == -1) {
-      // Open device for playback failed ... either busy or doesn't exist.
-      if (errno != EBUSY && errno != EAGAIN) {
-        // Try to open for capture
-        fd = open(device_name, O_RDONLY | O_NONBLOCK);
-        if (fd == -1) {
-          // Open device for record failed.
-          if (errno != EBUSY && errno != EAGAIN)
-            continue;
-          else {
-            sprintf(message_, "RtApiOss: OSS record device (%s) is busy.", device_name);
-            error(RtError::WARNING);
-            // still count it for now
-          }
-        }
-      }
-      else {
-        sprintf(message_, "RtApiOss: OSS playback device (%s) is busy.", device_name);
-        error(RtError::WARNING);
-        // still count it for now
-      }
-    }
-
-    if (fd >= 0) close(fd);
-    device.name.erase();
-    device.name.append( (const char *)device_name, strlen(device_name)+1);
-    devices_.push_back(device);
-    nDevices_++;
-  }
-}
-
-void RtApiOss :: probeDeviceInfo(RtApiDevice *info)
-{
-  int i, fd, channels, mask;
-
-  // The OSS API doesn't provide a means for probing the capabilities
-  // of devices.  Thus, we'll just pursue a brute force method.
-
-  // First try for playback
-  fd = open(info->name.c_str(), O_WRONLY | O_NONBLOCK);
-  if (fd == -1) {
-    // Open device failed ... either busy or doesn't exist
-    if (errno == EBUSY || errno == EAGAIN)
-      sprintf(message_, "RtApiOss: OSS playback device (%s) is busy and cannot be probed.",
-              info->name.c_str());
-    else
-      sprintf(message_, "RtApiOss: OSS playback device (%s) open error.", info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    goto capture_probe;
-  }
-
-  // We have an open device ... see how many channels it can handle
-  for (i=MAX_CHANNELS; i>0; i--) {
-    channels = i;
-    if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1) {
-      // This would normally indicate some sort of hardware error, but under ALSA's
-      // OSS emulation, it sometimes indicates an invalid channel value.  Further,
-      // the returned channel value is not changed. So, we'll ignore the possible
-      // hardware error.
-      continue; // try next channel number
-    }
-    // Check to see whether the device supports the requested number of channels
-    if (channels != i ) continue; // try next channel number
-    // If here, we found the largest working channel value
-    break;
-  }
-  info->maxOutputChannels = i;
-
-  // Now find the minimum number of channels it can handle
-  for (i=1; i<=info->maxOutputChannels; i++) {
-    channels = i;
-    if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i)
-      continue; // try next channel number
-    // If here, we found the smallest working channel value
-    break;
-  }
-  info->minOutputChannels = i;
-  close(fd);
-
- capture_probe:
-  // Now try for capture
-  fd = open(info->name.c_str(), O_RDONLY | O_NONBLOCK);
-  if (fd == -1) {
-    // Open device for capture failed ... either busy or doesn't exist
-    if (errno == EBUSY || errno == EAGAIN)
-      sprintf(message_, "RtApiOss: OSS capture device (%s) is busy and cannot be probed.",
-              info->name.c_str());
-    else
-      sprintf(message_, "RtApiOss: OSS capture device (%s) open error.", info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    if (info->maxOutputChannels == 0)
-      // didn't open for playback either ... device invalid
-      return;
-    goto probe_parameters;
-  }
-
-  // We have the device open for capture ... see how many channels it can handle
-  for (i=MAX_CHANNELS; i>0; i--) {
-    channels = i;
-    if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) {
-      continue; // as above
-    }
-    // If here, we found a working channel value
-    break;
-  }
-  info->maxInputChannels = i;
-
-  // Now find the minimum number of channels it can handle
-  for (i=1; i<=info->maxInputChannels; i++) {
-    channels = i;
-    if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i)
-      continue; // try next channel number
-    // If here, we found the smallest working channel value
-    break;
-  }
-  info->minInputChannels = i;
-  close(fd);
-
-  if (info->maxOutputChannels == 0 && info->maxInputChannels == 0) {
-    sprintf(message_, "RtApiOss: device (%s) reports zero channels for input and output.",
-            info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // If device opens for both playback and capture, we determine the channels.
-  if (info->maxOutputChannels == 0 || info->maxInputChannels == 0)
-    goto probe_parameters;
-
-  fd = open(info->name.c_str(), O_RDWR | O_NONBLOCK);
-  if (fd == -1)
-    goto probe_parameters;
-
-  ioctl(fd, SNDCTL_DSP_SETDUPLEX, 0);
-  ioctl(fd, SNDCTL_DSP_GETCAPS, &mask);
-  if (mask & DSP_CAP_DUPLEX) {
-    info->hasDuplexSupport = true;
-    // We have the device open for duplex ... see how many channels it can handle
-    for (i=MAX_CHANNELS; i>0; i--) {
-      channels = i;
-      if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i)
-        continue; // as above
-      // If here, we found a working channel value
-      break;
-    }
-    info->maxDuplexChannels = i;
-
-    // Now find the minimum number of channels it can handle
-    for (i=1; i<=info->maxDuplexChannels; i++) {
-      channels = i;
-      if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i)
-        continue; // try next channel number
-      // If here, we found the smallest working channel value
-      break;
-    }
-    info->minDuplexChannels = i;
-  }
-  close(fd);
-
- probe_parameters:
-  // At this point, we need to figure out the supported data formats
-  // and sample rates.  We'll proceed by openning 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->maxOutputChannels >= info->maxInputChannels) {
-    fd = open(info->name.c_str(), O_WRONLY | O_NONBLOCK);
-    channels = info->maxOutputChannels;
-  }
-  else {
-    fd = open(info->name.c_str(), O_RDONLY | O_NONBLOCK);
-    channels = info->maxInputChannels;
-  }
-
-  if (fd == -1) {
-    // We've got some sort of conflict ... abort
-    sprintf(message_, "RtApiOss: device (%s) won't reopen during probe.",
-            info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // We have an open device ... set to maximum channels.
-  i = channels;
-  if (ioctl(fd, SNDCTL_DSP_CHANNELS, &channels) == -1 || channels != i) {
-    // We've got some sort of conflict ... abort
-    close(fd);
-    sprintf(message_, "RtApiOss: device (%s) won't revert to previous channel setting.",
-            info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  if (ioctl(fd, SNDCTL_DSP_GETFMTS, &mask) == -1) {
-    close(fd);
-    sprintf(message_, "RtApiOss: device (%s) can't get supported audio formats.",
-            info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // Probe the supported data formats ... we don't care about endian-ness just yet.
-  int format;
-  info->nativeFormats = 0;
-#if defined (AFMT_S32_BE)
-  // This format does not seem to be in the 2.4 kernel version of OSS soundcard.h
-  if (mask & AFMT_S32_BE) {
-    format = AFMT_S32_BE;
-    info->nativeFormats |= RTAUDIO_SINT32;
-  }
-#endif
-#if defined (AFMT_S32_LE)
-  /* This format is not in the 2.4.4 kernel version of OSS soundcard.h */
-  if (mask & AFMT_S32_LE) {
-    format = AFMT_S32_LE;
-    info->nativeFormats |= RTAUDIO_SINT32;
-  }
-#endif
-  if (mask & AFMT_S8) {
-    format = AFMT_S8;
-    info->nativeFormats |= RTAUDIO_SINT8;
-  }
-  if (mask & AFMT_S16_BE) {
-    format = AFMT_S16_BE;
-    info->nativeFormats |= RTAUDIO_SINT16;
-  }
-  if (mask & AFMT_S16_LE) {
-    format = AFMT_S16_LE;
-    info->nativeFormats |= RTAUDIO_SINT16;
-  }
-
-  // Check that we have at least one supported format
-  if (info->nativeFormats == 0) {
-    close(fd);
-    sprintf(message_, "RtApiOss: device (%s) data format not supported by RtAudio.",
-            info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // Set the format
-  i = format;
-  if (ioctl(fd, SNDCTL_DSP_SETFMT, &format) == -1 || format != i) {
-    close(fd);
-    sprintf(message_, "RtApiOss: device (%s) error setting data format.",
-            info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // Probe the supported sample rates.
-  info->sampleRates.clear();
-  for (unsigned int k=0; k<MAX_SAMPLE_RATES; k++) {
-    int speed = SAMPLE_RATES[k];
-    if (ioctl(fd, SNDCTL_DSP_SPEED, &speed) != -1 && speed == (int)SAMPLE_RATES[k])
-      info->sampleRates.push_back(speed);
-  }
-
-  if (info->sampleRates.size() == 0) {
-    close(fd);
-    sprintf(message_, "RtApiOss: no supported sample rates found for device (%s).",
-            info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // That's all ... close the device and return
-  close(fd);
-  info->probed = true;
-  return;
-}
-
-bool RtApiOss :: probeDeviceOpen(int device, StreamMode mode, int channels, 
-                                int sampleRate, RtAudioFormat format,
-                                int *bufferSize, int numberOfBuffers)
-{
-  int buffers, buffer_bytes, device_channels, device_format;
-  int srate, temp, fd;
-  int *handle = (int *) stream_.apiHandle;
-
-  const char *name = devices_[device].name.c_str();
-
-  if (mode == OUTPUT)
-    fd = open(name, O_WRONLY | O_NONBLOCK);
-  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[0]);
-      handle[0] = 0;
-      // First check that the number previously set channels is the same.
-      if (stream_.nUserChannels[0] != channels) {
-        sprintf(message_, "RtApiOss: input/output channels must be equal for OSS duplex device (%s).", name);
-        goto error;
-      }
-      fd = open(name, O_RDWR | O_NONBLOCK);
-    }
-    else
-      fd = open(name, O_RDONLY | O_NONBLOCK);
-  }
-
-  if (fd == -1) {
-    if (errno == EBUSY || errno == EAGAIN)
-      sprintf(message_, "RtApiOss: device (%s) is busy and cannot be opened.",
-              name);
-    else
-      sprintf(message_, "RtApiOss: device (%s) cannot be opened.", name);
-    goto error;
-  }
-
-  // Now reopen in blocking mode.
-  close(fd);
-  if (mode == OUTPUT)
-    fd = open(name, O_WRONLY | O_SYNC);
-  else { // mode == INPUT
-    if (stream_.mode == OUTPUT && stream_.device[0] == device)
-      fd = open(name, O_RDWR | O_SYNC);
-    else
-      fd = open(name, O_RDONLY | O_SYNC);
-  }
-
-  if (fd == -1) {
-    sprintf(message_, "RtApiOss: device (%s) cannot be opened.", name);
-    goto error;
-  }
-
-  // Get the sample format mask
-  int mask;
-  if (ioctl(fd, SNDCTL_DSP_GETFMTS, &mask) == -1) {
-    close(fd);
-    sprintf(message_, "RtApiOss: device (%s) can't get supported audio formats.",
-            name);
-    goto error;
-  }
-
-  // Determine how to set the device format.
-  stream_.userFormat = format;
-  device_format = -1;
-  stream_.doByteSwap[mode] = false;
-  if (format == RTAUDIO_SINT8) {
-    if (mask & AFMT_S8) {
-      device_format = AFMT_S8;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT8;
-    }
-  }
-  else if (format == RTAUDIO_SINT16) {
-    if (mask & AFMT_S16_NE) {
-      device_format = AFMT_S16_NE;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-    }
-#if BYTE_ORDER == LITTLE_ENDIAN
-    else if (mask & AFMT_S16_BE) {
-      device_format = AFMT_S16_BE;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-      stream_.doByteSwap[mode] = true;
-    }
-#else
-    else if (mask & AFMT_S16_LE) {
-      device_format = AFMT_S16_LE;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-      stream_.doByteSwap[mode] = true;
-    }
-#endif
-  }
-#if defined (AFMT_S32_NE) && defined (AFMT_S32_LE) && defined (AFMT_S32_BE)
-  else if (format == RTAUDIO_SINT32) {
-    if (mask & AFMT_S32_NE) {
-      device_format = AFMT_S32_NE;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT32;
-    }
-#if BYTE_ORDER == LITTLE_ENDIAN
-    else if (mask & AFMT_S32_BE) {
-      device_format = AFMT_S32_BE;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT32;
-      stream_.doByteSwap[mode] = true;
-    }
-#else
-    else if (mask & AFMT_S32_LE) {
-      device_format = AFMT_S32_LE;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT32;
-      stream_.doByteSwap[mode] = true;
-    }
-#endif
-  }
-#endif
-
-  if (device_format == -1) {
-    // The user requested format is not natively supported by the device.
-    if (mask & AFMT_S16_NE) {
-      device_format = AFMT_S16_NE;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-    }
-#if BYTE_ORDER == LITTLE_ENDIAN
-    else if (mask & AFMT_S16_BE) {
-      device_format = AFMT_S16_BE;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-      stream_.doByteSwap[mode] = true;
-    }
-#else
-    else if (mask & AFMT_S16_LE) {
-      device_format = AFMT_S16_LE;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-      stream_.doByteSwap[mode] = true;
-    }
-#endif
-#if defined (AFMT_S32_NE) && defined (AFMT_S32_LE) && defined (AFMT_S32_BE)
-    else if (mask & AFMT_S32_NE) {
-      device_format = AFMT_S32_NE;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT32;
-    }
-#if BYTE_ORDER == LITTLE_ENDIAN
-    else if (mask & AFMT_S32_BE) {
-      device_format = AFMT_S32_BE;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT32;
-      stream_.doByteSwap[mode] = true;
-    }
-#else
-    else if (mask & AFMT_S32_LE) {
-      device_format = AFMT_S32_LE;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT32;
-      stream_.doByteSwap[mode] = true;
-    }
-#endif
-#endif
-    else if (mask & AFMT_S8) {
-      device_format = AFMT_S8;
-      stream_.deviceFormat[mode] = RTAUDIO_SINT8;
-    }
-  }
-
-  if (stream_.deviceFormat[mode] == 0) {
-    // This really shouldn't happen ...
-    close(fd);
-    sprintf(message_, "RtApiOss: device (%s) data format not supported by RtAudio.",
-            name);
-    goto error;
-  }
-
-  // Determine the number of channels for this device.  Note that the
-  // channel value requested by the user might be < min_X_Channels.
-  stream_.nUserChannels[mode] = channels;
-  device_channels = channels;
-  if (mode == OUTPUT) {
-    if (channels < devices_[device].minOutputChannels)
-      device_channels = devices_[device].minOutputChannels;
-  }
-  else { // mode == INPUT
-    if (stream_.mode == OUTPUT && stream_.device[0] == device) {
-      // We're doing duplex setup here.
-      if (channels < devices_[device].minDuplexChannels)
-        device_channels = devices_[device].minDuplexChannels;
-    }
-    else {
-      if (channels < devices_[device].minInputChannels)
-        device_channels = devices_[device].minInputChannels;
-    }
-  }
-  stream_.nDeviceChannels[mode] = device_channels;
-
-  // 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.
-  buffer_bytes = *bufferSize * formatBytes(stream_.deviceFormat[mode]) * device_channels;
-  if (buffer_bytes < 16) buffer_bytes = 16;
-  buffers = numberOfBuffers;
-  if (buffers < 2) buffers = 2;
-  temp = ((int) buffers << 16) + (int)(log10((double)buffer_bytes)/log10(2.0));
-  if (ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &temp)) {
-    close(fd);
-    sprintf(message_, "RtApiOss: error setting fragment size for device (%s).",
-            name);
-    goto error;
-  }
-  stream_.nBuffers = buffers;
-
-  // Set the data format.
-  temp = device_format;
-  if (ioctl(fd, SNDCTL_DSP_SETFMT, &device_format) == -1 || device_format != temp) {
-    close(fd);
-    sprintf(message_, "RtApiOss: error setting data format for device (%s).",
-            name);
-    goto error;
-  }
-
-  // Set the number of channels.
-  temp = device_channels;
-  if (ioctl(fd, SNDCTL_DSP_CHANNELS, &device_channels) == -1 || device_channels != temp) {
-    close(fd);
-    sprintf(message_, "RtApiOss: error setting %d channels on device (%s).",
-            temp, name);
-    goto error;
-  }
-
-  // Set the sample rate.
-  srate = sampleRate;
-  temp = srate;
-  if (ioctl(fd, SNDCTL_DSP_SPEED, &srate) == -1) {
-    close(fd);
-    sprintf(message_, "RtApiOss: error setting sample rate = %d on device (%s).",
-            temp, name);
-    goto error;
-  }
-
-  // Verify the sample rate setup worked.
-  if (abs(srate - temp) > 100) {
-    close(fd);
-    sprintf(message_, "RtApiOss: error ... audio device (%s) doesn't support sample rate of %d.",
-            name, temp);
-    goto error;
-  }
-  stream_.sampleRate = sampleRate;
-
-  if (ioctl(fd, SNDCTL_DSP_GETBLKSIZE, &buffer_bytes) == -1) {
-    close(fd);
-    sprintf(message_, "RtApiOss: error getting buffer size for device (%s).",
-            name);
-    goto error;
-  }
-
-  // Save buffer size (in sample frames).
-  *bufferSize = buffer_bytes / (formatBytes(stream_.deviceFormat[mode]) * device_channels);
-  stream_.bufferSize = *bufferSize;
-
-  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] = device_channels;
-  }
-
-  // Allocate the stream handles if necessary and then save.
-  if ( stream_.apiHandle == 0 ) {
-    handle = (int *) calloc(2, sizeof(int));
-    stream_.apiHandle = (void *) handle;
-    handle[0] = 0;
-    handle[1] = 0;
-  }
-  else {
-    handle = (int *) stream_.apiHandle;
-  }
-  handle[mode] = fd;
-
-  // 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;
-
-  // Allocate necessary internal buffers
-  if ( stream_.nUserChannels[0] != stream_.nUserChannels[1] ) {
-
-    long buffer_bytes;
-    if (stream_.nUserChannels[0] >= stream_.nUserChannels[1])
-      buffer_bytes = stream_.nUserChannels[0];
-    else
-      buffer_bytes = stream_.nUserChannels[1];
-
-    buffer_bytes *= *bufferSize * formatBytes(stream_.userFormat);
-    if (stream_.userBuffer) free(stream_.userBuffer);
-    stream_.userBuffer = (char *) calloc(buffer_bytes, 1);
-    if (stream_.userBuffer == NULL) {
-      close(fd);
-      sprintf(message_, "RtApiOss: error allocating user buffer memory (%s).",
-              name);
-      goto error;
-    }
-  }
-
-  if ( stream_.doConvertBuffer[mode] ) {
-
-    long buffer_bytes;
-    bool makeBuffer = true;
-    if ( mode == OUTPUT )
-      buffer_bytes = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-    else { // mode == INPUT
-      buffer_bytes = stream_.nDeviceChannels[1] * formatBytes(stream_.deviceFormat[1]);
-      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
-        long bytes_out = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-        if ( buffer_bytes < bytes_out ) makeBuffer = false;
-      }
-    }
-
-    if ( makeBuffer ) {
-      buffer_bytes *= *bufferSize;
-      if (stream_.deviceBuffer) free(stream_.deviceBuffer);
-      stream_.deviceBuffer = (char *) calloc(buffer_bytes, 1);
-      if (stream_.deviceBuffer == NULL) {
-        close(fd);
-        sprintf(message_, "RtApiOss: error allocating device buffer memory (%s).",
-                name);
-        goto error;
-      }
-    }
-  }
-
-  stream_.device[mode] = device;
-  stream_.state = STREAM_STOPPED;
-
-  if ( stream_.mode == OUTPUT && mode == INPUT ) {
-    stream_.mode = DUPLEX;
-    if (stream_.device[0] == device)
-      handle[0] = fd;
-  }
-  else
-    stream_.mode = mode;
-
-  // Setup the buffer conversion information structure.
-  if ( stream_.doConvertBuffer[mode] ) {
-    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];
-    }
-
-    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 ( mode == INPUT && stream_.deInterleave[1] ) {
-      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 if (mode == OUTPUT && stream_.deInterleave[0]) {
-      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_.convertInfo[mode].outOffset.push_back( k );
-      }
-    }
-  }
-
-  return SUCCESS;
-
- error:
-  if (handle) {
-    if (handle[0])
-      close(handle[0]);
-    free(handle);
-    stream_.apiHandle = 0;
-  }
-
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  error(RtError::DEBUG_WARNING);
-  return FAILURE;
-}
-
-void RtApiOss :: closeStream()
-{
-  // We don't want an exception to be thrown here because this
-  // function is called by our class destructor.  So, do our own
-  // stream check.
-  if ( stream_.mode == UNINITIALIZED ) {
-    sprintf(message_, "RtApiOss::closeStream(): no open stream to close!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  int *handle = (int *) stream_.apiHandle;
-  if (stream_.state == STREAM_RUNNING) {
-    if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
-      ioctl(handle[0], SNDCTL_DSP_RESET, 0);
-    else
-      ioctl(handle[1], SNDCTL_DSP_RESET, 0);
-    stream_.state = STREAM_STOPPED;
-  }
-
-  if (stream_.callbackInfo.usingCallback) {
-    stream_.callbackInfo.usingCallback = false;
-    pthread_join(stream_.callbackInfo.thread, NULL);
-  }
-
-  if (handle) {
-    if (handle[0]) close(handle[0]);
-    if (handle[1]) close(handle[1]);
-    free(handle);
-    stream_.apiHandle = 0;
-  }
-
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  if (stream_.deviceBuffer) {
-    free(stream_.deviceBuffer);
-    stream_.deviceBuffer = 0;
-  }
-
-  stream_.mode = UNINITIALIZED;
-}
-
-void RtApiOss :: startStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_RUNNING) return;
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  stream_.state = STREAM_RUNNING;
-
-  // No need to do anything else here ... OSS automatically starts
-  // when fed samples.
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiOss :: stopStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_STOPPED) return;
-
-  // Change the state before the lock to improve shutdown response
-  // when using a callback.
-  stream_.state = STREAM_STOPPED;
-  MUTEX_LOCK(&stream_.mutex);
-
-  int err;
-  int *handle = (int *) stream_.apiHandle;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-    err = ioctl(handle[0], SNDCTL_DSP_POST, 0);
-    //err = ioctl(handle[0], SNDCTL_DSP_SYNC, 0);
-    if (err < -1) {
-      sprintf(message_, "RtApiOss: error stopping device (%s).",
-              devices_[stream_.device[0]].name.c_str());
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-  else {
-    err = ioctl(handle[1], SNDCTL_DSP_POST, 0);
-    //err = ioctl(handle[1], SNDCTL_DSP_SYNC, 0);
-    if (err < -1) {
-      sprintf(message_, "RtApiOss: error stopping device (%s).",
-              devices_[stream_.device[1]].name.c_str());
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiOss :: abortStream()
-{
-  stopStream();
-}
-
-int RtApiOss :: streamWillBlock()
-{
-  verifyStream();
-  if (stream_.state == STREAM_STOPPED) return 0;
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  int bytes = 0, channels = 0, frames = 0;
-  audio_buf_info info;
-  int *handle = (int *) stream_.apiHandle;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-    ioctl(handle[0], SNDCTL_DSP_GETOSPACE, &info);
-    bytes = info.bytes;
-    channels = stream_.nDeviceChannels[0];
-  }
-
-  if (stream_.mode == INPUT || stream_.mode == DUPLEX) {
-    ioctl(handle[1], SNDCTL_DSP_GETISPACE, &info);
-    if (stream_.mode == DUPLEX ) {
-      bytes = (bytes < info.bytes) ? bytes : info.bytes;
-      channels = stream_.nDeviceChannels[0];
-    }
-    else {
-      bytes = info.bytes;
-      channels = stream_.nDeviceChannels[1];
-    }
-  }
-
-  frames = (int) (bytes / (channels * formatBytes(stream_.deviceFormat[0])));
-  frames -= stream_.bufferSize;
-  if (frames < 0) frames = 0;
-
-  MUTEX_UNLOCK(&stream_.mutex);
-  return frames;
-}
-
-void RtApiOss :: tickStream()
-{
-  verifyStream();
-
-  int stopStream = 0;
-  if (stream_.state == STREAM_STOPPED) {
-    if (stream_.callbackInfo.usingCallback) usleep(50000); // sleep 50 milliseconds
-    return;
-  }
-  else if (stream_.callbackInfo.usingCallback) {
-    RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
-    stopStream = callback(stream_.userBuffer, stream_.bufferSize, stream_.callbackInfo.userData);
-  }
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  // The state might change while waiting on a mutex.
-  if (stream_.state == STREAM_STOPPED)
-    goto unlock;
-
-  int result, *handle;
-  char *buffer;
-  int samples;
-  RtAudioFormat format;
-  handle = (int *) stream_.apiHandle;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-
-    // Setup parameters and do buffer conversion if necessary.
-    if (stream_.doConvertBuffer[0]) {
-      buffer = stream_.deviceBuffer;
-      convertBuffer( buffer, stream_.userBuffer, stream_.convertInfo[0] );
-      samples = stream_.bufferSize * stream_.nDeviceChannels[0];
-      format = stream_.deviceFormat[0];
-    }
-    else {
-      buffer = stream_.userBuffer;
-      samples = stream_.bufferSize * stream_.nUserChannels[0];
-      format = stream_.userFormat;
-    }
-
-    // Do byte swapping if necessary.
-    if (stream_.doByteSwap[0])
-      byteSwapBuffer(buffer, samples, format);
-
-    // Write samples to device.
-    result = write(handle[0], buffer, samples * formatBytes(format));
-
-    if (result == -1) {
-      // This could be an underrun, but the basic OSS API doesn't provide a means for determining that.
-      sprintf(message_, "RtApiOss: audio write error for device (%s).",
-              devices_[stream_.device[0]].name.c_str());
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  if (stream_.mode == INPUT || stream_.mode == DUPLEX) {
-
-    // Setup parameters.
-    if (stream_.doConvertBuffer[1]) {
-      buffer = stream_.deviceBuffer;
-      samples = stream_.bufferSize * stream_.nDeviceChannels[1];
-      format = stream_.deviceFormat[1];
-    }
-    else {
-      buffer = stream_.userBuffer;
-      samples = stream_.bufferSize * stream_.nUserChannels[1];
-      format = stream_.userFormat;
-    }
-
-    // Read samples from device.
-    result = read(handle[1], buffer, samples * formatBytes(format));
-
-    if (result == -1) {
-      // This could be an overrun, but the basic OSS API doesn't provide a means for determining that.
-      sprintf(message_, "RtApiOss: audio read error for device (%s).",
-              devices_[stream_.device[1]].name.c_str());
-      error(RtError::DRIVER_ERROR);
-    }
-
-    // Do byte swapping if necessary.
-    if (stream_.doByteSwap[1])
-      byteSwapBuffer(buffer, samples, format);
-
-    // Do buffer conversion if necessary.
-    if (stream_.doConvertBuffer[1])
-      convertBuffer( stream_.userBuffer, stream_.deviceBuffer, stream_.convertInfo[1] );
-  }
-
- unlock:
-  MUTEX_UNLOCK(&stream_.mutex);
-
-  if (stream_.callbackInfo.usingCallback && stopStream)
-    this->stopStream();
-}
-
-void RtApiOss :: setStreamCallback(RtAudioCallback callback, void *userData)
-{
-  verifyStream();
-
-  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
-  if ( info->usingCallback ) {
-    sprintf(message_, "RtApiOss: A callback is already set for this stream!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  info->callback = (void *) callback;
-  info->userData = userData;
-  info->usingCallback = true;
-  info->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);
-  pthread_attr_setschedpolicy(&attr, SCHED_RR);
-
-  int err = pthread_create(&(info->thread), &attr, ossCallbackHandler, &stream_.callbackInfo);
-  pthread_attr_destroy(&attr);
-  if (err) {
-    info->usingCallback = false;
-    sprintf(message_, "RtApiOss: error starting callback thread!");
-    error(RtError::THREAD_ERROR);
-  }
-}
-
-void RtApiOss :: cancelStreamCallback()
-{
-  verifyStream();
-
-  if (stream_.callbackInfo.usingCallback) {
-
-    if (stream_.state == STREAM_RUNNING)
-      stopStream();
-
-    MUTEX_LOCK(&stream_.mutex);
-
-    stream_.callbackInfo.usingCallback = false;
-    pthread_join(stream_.callbackInfo.thread, NULL);
-    stream_.callbackInfo.thread = 0;
-    stream_.callbackInfo.callback = NULL;
-    stream_.callbackInfo.userData = NULL;
-
-    MUTEX_UNLOCK(&stream_.mutex);
-  }
-}
-
-extern "C" void *ossCallbackHandler(void *ptr)
-{
-  CallbackInfo *info = (CallbackInfo *) ptr;
-  RtApiOss *object = (RtApiOss *) info->object;
-  bool *usingCallback = &info->usingCallback;
-
-  while ( *usingCallback ) {
-    pthread_testcancel();
-    try {
-      object->tickStream();
-    }
-    catch (RtError &exception) {
-      fprintf(stderr, "\nRtApiOss: callback thread error (%s) ... closing thread.\n\n",
-              exception.getMessageString());
-      break;
-    }
-  }
-
-  return 0;
-}
-
-//******************** End of __LINUX_OSS__ *********************//
-#endif
-
-#if defined(__MACOSX_CORE__)
-
-
-// The OS X CoreAudio API is designed to use a separate callback
-// procedure for each of its audio devices.  A single RtAudio duplex
-// stream using two different devices is supported here, though it
-// cannot be guaranteed to always behave correctly because we cannot
-// synchronize these two callbacks.  This same functionality can be
-// achieved with better synchrony by opening two separate streams for
-// the devices and using RtAudio blocking calls (i.e. tickStream()).
-//
-// A property listener is installed for over/underrun information.
-// However, no functionality is currently provided to allow property
-// listeners to trigger user handlers because it is unclear what could
-// be done if a critical stream parameter (buffer size, sample rate,
-// device disconnect) notification arrived.  The listeners entail
-// quite a bit of extra code and most likely, a user program wouldn't
-// be prepared for the result anyway.
-
-// A structure to hold various information related to the CoreAudio API
-// implementation.
-struct CoreHandle {
-  UInt32 index[2];
-  bool stopStream;
-  bool xrun;
-  char *deviceBuffer;
-  pthread_cond_t condition;
-
-  CoreHandle()
-    :stopStream(false), xrun(false), deviceBuffer(0) {}
-};
-
-RtApiCore :: RtApiCore()
-{
-  this->initialize();
-
-  if (nDevices_ <= 0) {
-    sprintf(message_, "RtApiCore: no Macintosh OS-X Core Audio devices found!");
-    error(RtError::NO_DEVICES_FOUND);
- }
-}
-
-RtApiCore :: ~RtApiCore()
-{
-  // The subclass destructor gets called before the base class
-  // destructor, so close an existing stream before deallocating
-  // apiDeviceId memory.
-  if ( stream_.mode != UNINITIALIZED ) closeStream();
-
-  // Free our allocated apiDeviceId memory.
-  AudioDeviceID *id;
-  for ( unsigned int i=0; i<devices_.size(); i++ ) {
-    id = (AudioDeviceID *) devices_[i].apiDeviceId;
-    if (id) free(id);
-  }
-}
-
-void RtApiCore :: initialize(void)
-{
-  OSStatus err = noErr;
-  UInt32 dataSize;
-  AudioDeviceID        *deviceList = NULL;
-  nDevices_ = 0;
-
-  // Find out how many audio devices there are, if any.
-  err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &dataSize, NULL);
-  if (err != noErr) {
-    sprintf(message_, "RtApiCore: OS-X error getting device info!");
-    error(RtError::SYSTEM_ERROR);
-  }
-
-  nDevices_ = dataSize / sizeof(AudioDeviceID);
-  if (nDevices_ == 0) return;
-
-  // Make space for the devices we are about to get.
-  deviceList = (AudioDeviceID  *) malloc( dataSize );
-  if (deviceList == NULL) {
-    sprintf(message_, "RtApiCore: memory allocation error during initialization!");
-    error(RtError::MEMORY_ERROR);
-  }
-
-  // Get the array of AudioDeviceIDs.
-  err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &dataSize, (void *) deviceList);
-  if (err != noErr) {
-    free(deviceList);
-    sprintf(message_, "RtApiCore: OS-X error getting device properties!");
-    error(RtError::SYSTEM_ERROR);
-  }
-
-  // Create list of device structures and write device identifiers.
-  RtApiDevice device;
-  AudioDeviceID *id;
-  for (int i=0; i<nDevices_; i++) {
-    devices_.push_back(device);
-    id = (AudioDeviceID *) malloc( sizeof(AudioDeviceID) );
-    *id = deviceList[i];
-    devices_[i].apiDeviceId = (void *) id;
-  }
-
-  free(deviceList);
-}
-
-int RtApiCore :: getDefaultInputDevice(void)
-{
-  AudioDeviceID id, *deviceId;
-  UInt32 dataSize = sizeof( AudioDeviceID );
-
-  OSStatus result = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultInputDevice,
-                                              &dataSize, &id );
-
-  if (result != noErr) {
-    sprintf( message_, "RtApiCore: OS-X error getting default input device." );
-    error(RtError::WARNING);
-    return 0;
-  }
-
-  for ( int i=0; i<nDevices_; i++ ) {
-    deviceId = (AudioDeviceID *) devices_[i].apiDeviceId;
-    if ( id == *deviceId ) return i;
-  }
-
-  return 0;
-}
-
-int RtApiCore :: getDefaultOutputDevice(void)
-{
-  AudioDeviceID id, *deviceId;
-  UInt32 dataSize = sizeof( AudioDeviceID );
-
-  OSStatus result = AudioHardwareGetProperty( kAudioHardwarePropertyDefaultOutputDevice,
-                                              &dataSize, &id );
-
-  if (result != noErr) {
-    sprintf( message_, "RtApiCore: OS-X error getting default output device." );
-    error(RtError::WARNING);
-    return 0;
-  }
-
-  for ( int i=0; i<nDevices_; i++ ) {
-    deviceId = (AudioDeviceID *) devices_[i].apiDeviceId;
-    if ( id == *deviceId ) return i;
-  }
-
-  return 0;
-}
-
-static bool deviceSupportsFormat( AudioDeviceID id, bool isInput,
-                                  AudioStreamBasicDescription  *desc, bool isDuplex )
-{
-  OSStatus result = noErr;
-  UInt32 dataSize = sizeof( AudioStreamBasicDescription );
-
-  result = AudioDeviceGetProperty( id, 0, isInput,
-                                   kAudioDevicePropertyStreamFormatSupported,
-                                   &dataSize, desc );
-
-  if (result == kAudioHardwareNoError) {
-    if ( isDuplex ) {
-      result = AudioDeviceGetProperty( id, 0, true,
-                                       kAudioDevicePropertyStreamFormatSupported,
-                                       &dataSize, desc );
-
-
-      if (result != kAudioHardwareNoError)
-        return false;
-    }
-    return true;
-  }
-
-  return false;
-}
-
-void RtApiCore :: probeDeviceInfo( RtApiDevice *info )
-{
-  OSStatus err = noErr;
-
-  // Get the device manufacturer and name.
-  char name[256];
-  char fullname[512];
-  UInt32 dataSize = 256;
-  AudioDeviceID *id = (AudioDeviceID *) info->apiDeviceId;
-  err = AudioDeviceGetProperty( *id, 0, false,
-                                kAudioDevicePropertyDeviceManufacturer,
-                                &dataSize, name );
-  if (err != noErr) {
-    sprintf( message_, "RtApiCore: OS-X error getting device manufacturer." );
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-  strncpy(fullname, name, 256);
-  strcat(fullname, ": " );
-
-  dataSize = 256;
-  err = AudioDeviceGetProperty( *id, 0, false,
-                                kAudioDevicePropertyDeviceName,
-                                &dataSize, name );
-  if (err != noErr) {
-    sprintf( message_, "RtApiCore: OS-X error getting device name." );
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-  strncat(fullname, name, 254);
-  info->name.erase();
-  info->name.append( (const char *)fullname, strlen(fullname)+1);
-
-  // Get output channel information.
-  unsigned int i, minChannels = 0, maxChannels = 0, nStreams = 0;
-  AudioBufferList      *bufferList = nil;
-  err = AudioDeviceGetPropertyInfo( *id, 0, false,
-                                    kAudioDevicePropertyStreamConfiguration,
-                                    &dataSize, NULL );
-  if (err == noErr && dataSize > 0) {
-    bufferList = (AudioBufferList *) malloc( dataSize );
-    if (bufferList == NULL) {
-      sprintf(message_, "RtApiCore: memory allocation error!");
-      error(RtError::DEBUG_WARNING);
-      return;
-    }
-
-    err = AudioDeviceGetProperty( *id, 0, false,
-                                  kAudioDevicePropertyStreamConfiguration,
-                                  &dataSize, bufferList );
-    if (err == noErr) {
-      maxChannels = 0;
-      minChannels = 1000;
-      nStreams = bufferList->mNumberBuffers;
-      for ( i=0; i<nStreams; i++ ) {
-        maxChannels += bufferList->mBuffers[i].mNumberChannels;
-        if ( bufferList->mBuffers[i].mNumberChannels < minChannels )
-          minChannels = bufferList->mBuffers[i].mNumberChannels;
-      }
-    }
-  }
-  free (bufferList);
-
-  if (err != noErr || dataSize <= 0) {
-    sprintf( message_, "RtApiCore: OS-X error getting output channels for device (%s).",
-             info->name.c_str() );
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  if ( nStreams ) {
-    if ( maxChannels > 0 )
-      info->maxOutputChannels = maxChannels;
-    if ( minChannels > 0 )
-      info->minOutputChannels = minChannels;
-  }
-
-  // Get input channel information.
-  bufferList = nil;
-  err = AudioDeviceGetPropertyInfo( *id, 0, true,
-                                    kAudioDevicePropertyStreamConfiguration,
-                                    &dataSize, NULL );
-  if (err == noErr && dataSize > 0) {
-    bufferList = (AudioBufferList *) malloc( dataSize );
-    if (bufferList == NULL) {
-      sprintf(message_, "RtApiCore: memory allocation error!");
-      error(RtError::DEBUG_WARNING);
-      return;
-    }
-    err = AudioDeviceGetProperty( *id, 0, true,
-                                  kAudioDevicePropertyStreamConfiguration,
-                                  &dataSize, bufferList );
-    if (err == noErr) {
-      maxChannels = 0;
-      minChannels = 1000;
-      nStreams = bufferList->mNumberBuffers;
-      for ( i=0; i<nStreams; i++ ) {
-        if ( bufferList->mBuffers[i].mNumberChannels < minChannels )
-          minChannels = bufferList->mBuffers[i].mNumberChannels;
-        maxChannels += bufferList->mBuffers[i].mNumberChannels;
-      }
-    }
-  }
-  free (bufferList);
-
-  if (err != noErr || dataSize <= 0) {
-    sprintf( message_, "RtApiCore: OS-X error getting input channels for device (%s).",
-             info->name.c_str() );
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  if ( nStreams ) {
-    if ( maxChannels > 0 )
-      info->maxInputChannels = maxChannels;
-    if ( minChannels > 0 )
-      info->minInputChannels = minChannels;
-  }
-
-  // If device opens for both playback and capture, we determine the channels.
-  if (info->maxOutputChannels > 0 && info->maxInputChannels > 0) {
-    info->hasDuplexSupport = true;
-    info->maxDuplexChannels = (info->maxOutputChannels > info->maxInputChannels) ?
-      info->maxInputChannels : info->maxOutputChannels;
-    info->minDuplexChannels = (info->minOutputChannels > info->minInputChannels) ?
-      info->minInputChannels : info->minOutputChannels;
-  }
-
-  // Probe the device sample rate and data format parameters.  The
-  // core audio query mechanism is performed on a "stream"
-  // description, which can have a variable number of channels and
-  // apply to input or output only.
-
-  // Create a stream description structure.
-  AudioStreamBasicDescription  description;
-  dataSize = sizeof( AudioStreamBasicDescription );
-  memset(&description, 0, sizeof(AudioStreamBasicDescription));
-  bool isInput = false;
-  if ( info->maxOutputChannels == 0 ) isInput = true;
-  bool isDuplex = false;
-  if ( info->maxDuplexChannels > 0 ) isDuplex = true;
-
-  // Determine the supported sample rates.
-  info->sampleRates.clear();
-  for (unsigned int k=0; k<MAX_SAMPLE_RATES; k++) {
-    description.mSampleRate = (double) SAMPLE_RATES[k];
-    if ( deviceSupportsFormat( *id, isInput, &description, isDuplex ) )
-      info->sampleRates.push_back( SAMPLE_RATES[k] );
-  }
-
-  if (info->sampleRates.size() == 0) {
-    sprintf( message_, "RtApiCore: No supported sample rates found for OS-X device (%s).",
-             info->name.c_str() );
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // Determine the supported data formats.
-  info->nativeFormats = 0;
-  description.mFormatID = kAudioFormatLinearPCM;
-  description.mBitsPerChannel = 8;
-  description.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsBigEndian;
-  if ( deviceSupportsFormat( *id, isInput, &description, isDuplex ) )
-    info->nativeFormats |= RTAUDIO_SINT8;
-  else {
-    description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian;
-    if ( deviceSupportsFormat( *id, isInput, &description, isDuplex ) )
-      info->nativeFormats |= RTAUDIO_SINT8;
-  }
-
-  description.mBitsPerChannel = 16;
-  description.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian;
-  if ( deviceSupportsFormat( *id, isInput, &description, isDuplex ) )
-    info->nativeFormats |= RTAUDIO_SINT16;
-  else {
-    description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian;
-    if ( deviceSupportsFormat( *id, isInput, &description, isDuplex ) )
-      info->nativeFormats |= RTAUDIO_SINT16;
-  }
-
-  description.mBitsPerChannel = 32;
-  description.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian;
-  if ( deviceSupportsFormat( *id, isInput, &description, isDuplex ) )
-    info->nativeFormats |= RTAUDIO_SINT32;
-  else {
-    description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian;
-    if ( deviceSupportsFormat( *id, isInput, &description, isDuplex ) )
-      info->nativeFormats |= RTAUDIO_SINT32;
-  }
-
-  description.mBitsPerChannel = 24;
-  description.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsAlignedHigh | kLinearPCMFormatFlagIsBigEndian;
-  if ( deviceSupportsFormat( *id, isInput, &description, isDuplex ) )
-    info->nativeFormats |= RTAUDIO_SINT24;
-  else {
-    description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian;
-    if ( deviceSupportsFormat( *id, isInput, &description, isDuplex ) )
-      info->nativeFormats |= RTAUDIO_SINT24;
-  }
-
-  description.mBitsPerChannel = 32;
-  description.mFormatFlags = kLinearPCMFormatFlagIsFloat | kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsBigEndian;
-  if ( deviceSupportsFormat( *id, isInput, &description, isDuplex ) )
-    info->nativeFormats |= RTAUDIO_FLOAT32;
-  else {
-    description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian;
-    if ( deviceSupportsFormat( *id, isInput, &description, isDuplex ) )
-      info->nativeFormats |= RTAUDIO_FLOAT32;
-  }
-
-  description.mBitsPerChannel = 64;
-  description.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian;
-  if ( deviceSupportsFormat( *id, isInput, &description, isDuplex ) )
-    info->nativeFormats |= RTAUDIO_FLOAT64;
-  else {
-    description.mFormatFlags &= ~kLinearPCMFormatFlagIsBigEndian;
-    if ( deviceSupportsFormat( *id, isInput, &description, isDuplex ) )
-      info->nativeFormats |= RTAUDIO_FLOAT64;
-  }
-
-  // Check that we have at least one supported format.
-  if (info->nativeFormats == 0) {
-    sprintf(message_, "RtApiCore: OS-X device (%s) data format not supported by RtAudio.",
-            info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  info->probed = true;
-}
-
-OSStatus callbackHandler( AudioDeviceID inDevice,
-                          const AudioTimeStamp* inNow,
-                          const AudioBufferList* inInputData,
-                          const AudioTimeStamp* inInputTime,
-                          AudioBufferList* outOutputData,
-                          const AudioTimeStamp* inOutputTime, 
-                          void* infoPointer )
-{
-  CallbackInfo *info = (CallbackInfo *) infoPointer;
-
-  RtApiCore *object = (RtApiCore *) info->object;
-  try {
-    object->callbackEvent( inDevice, (void *)inInputData, (void *)outOutputData );
-  }
-  catch (RtError &exception) {
-    fprintf(stderr, "\nRtApiCore: callback handler error (%s)!\n\n", exception.getMessageString());
-    return kAudioHardwareUnspecifiedError;
-  }
-
-  return kAudioHardwareNoError;
-}
-
-OSStatus deviceListener( AudioDeviceID inDevice,
-                         UInt32 channel,
-                         Boolean isInput,
-                         AudioDevicePropertyID propertyID,
-                         void* handlePointer )
-{
-  CoreHandle *handle = (CoreHandle *) handlePointer;
-  if ( propertyID == kAudioDeviceProcessorOverload ) {
-    if ( isInput )
-      fprintf(stderr, "\nRtApiCore: OS-X audio input overrun detected!\n");
-    else
-      fprintf(stderr, "\nRtApiCore: OS-X audio output underrun detected!\n");
-    handle->xrun = true;
-  }
-
-  return kAudioHardwareNoError;
-}
-
-bool RtApiCore :: probeDeviceOpen( int device, StreamMode mode, int channels, 
-                                   int sampleRate, RtAudioFormat format,
-                                   int *bufferSize, int numberOfBuffers )
-{
-  // Setup for stream mode.
-  bool isInput = false;
-  AudioDeviceID id = *((AudioDeviceID *) devices_[device].apiDeviceId);
-  if ( mode == INPUT ) isInput = true;
-
-  // Search for a stream which contains the desired number of channels.
-  OSStatus err = noErr;
-  UInt32 dataSize;
-  unsigned int deviceChannels, nStreams = 0;
-  UInt32 iChannel = 0, iStream = 0;
-  AudioBufferList      *bufferList = nil;
-  err = AudioDeviceGetPropertyInfo( id, 0, isInput,
-                                    kAudioDevicePropertyStreamConfiguration,
-                                    &dataSize, NULL );
-
-  if (err == noErr && dataSize > 0) {
-    bufferList = (AudioBufferList *) malloc( dataSize );
-    if (bufferList == NULL) {
-      sprintf(message_, "RtApiCore: memory allocation error in probeDeviceOpen()!");
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-    err = AudioDeviceGetProperty( id, 0, isInput,
-                                  kAudioDevicePropertyStreamConfiguration,
-                                  &dataSize, bufferList );
-
-    if (err == noErr) {
-      stream_.deInterleave[mode] = false;
-      nStreams = bufferList->mNumberBuffers;
-      for ( iStream=0; iStream<nStreams; iStream++ ) {
-        if ( bufferList->mBuffers[iStream].mNumberChannels >= (unsigned int) channels ) break;
-        iChannel += bufferList->mBuffers[iStream].mNumberChannels;
-      }
-      // If we didn't find a single stream above, see if we can meet
-      // the channel specification in mono mode (i.e. using separate
-      // non-interleaved buffers).  This can only work if there are N
-      // consecutive one-channel streams, where N is the number of
-      // desired channels.
-      iChannel = 0;
-      if ( iStream >= nStreams && nStreams >= (unsigned int) channels ) {
-        int counter = 0;
-        for ( iStream=0; iStream<nStreams; iStream++ ) {
-          if ( bufferList->mBuffers[iStream].mNumberChannels == 1 )
-            counter++;
-          else
-            counter = 0;
-          if ( counter == channels ) {
-            iStream -= channels - 1;
-            iChannel -= channels - 1;
-            stream_.deInterleave[mode] = true;
-            break;
-          }
-          iChannel += bufferList->mBuffers[iStream].mNumberChannels;
-        }
-      }
-    }
-  }
-  if (err != noErr || dataSize <= 0) {
-    if ( bufferList ) free( bufferList );
-    sprintf( message_, "RtApiCore: OS-X error getting channels for device (%s).",
-             devices_[device].name.c_str() );
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  if (iStream >= nStreams) {
-    free (bufferList);
-    sprintf( message_, "RtApiCore: unable to find OS-X audio stream on device (%s) for requested channels (%d).",
-             devices_[device].name.c_str(), channels );
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  // This is ok even for mono mode ... it gets updated later.
-  deviceChannels = bufferList->mBuffers[iStream].mNumberChannels;
-  free (bufferList);
-
-  // Determine the buffer size.
-  AudioValueRange      bufferRange;
-  dataSize = sizeof(AudioValueRange);
-  err = AudioDeviceGetProperty( id, 0, isInput,
-                                kAudioDevicePropertyBufferSizeRange,
-                                &dataSize, &bufferRange);
-  if (err != noErr) {
-    sprintf( message_, "RtApiCore: OS-X error getting buffer size range for device (%s).",
-             devices_[device].name.c_str() );
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  long bufferBytes = *bufferSize * deviceChannels * formatBytes(RTAUDIO_FLOAT32);
-  if (bufferRange.mMinimum > bufferBytes) bufferBytes = (int) bufferRange.mMinimum;
-  else if (bufferRange.mMaximum < bufferBytes) bufferBytes = (int) bufferRange.mMaximum;
-
-  // Set the buffer size.  For mono mode, I'm assuming we only need to
-  // make this setting for the first channel.
-  UInt32 theSize = (UInt32) bufferBytes;
-  dataSize = sizeof( UInt32);
-  err = AudioDeviceSetProperty(id, NULL, 0, isInput,
-                               kAudioDevicePropertyBufferSize,
-                               dataSize, &theSize);
-  if (err != noErr) {
-    sprintf( message_, "RtApiCore: OS-X error setting the buffer size for device (%s).",
-             devices_[device].name.c_str() );
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  // If attempting to setup a duplex stream, the bufferSize parameter
-  // MUST be the same in both directions!
-  *bufferSize = bufferBytes / ( deviceChannels * formatBytes(RTAUDIO_FLOAT32) );
-  if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {
-    sprintf( message_, "RtApiCore: OS-X error setting buffer size for duplex stream on device (%s).",
-             devices_[device].name.c_str() );
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  stream_.bufferSize = *bufferSize;
-  stream_.nBuffers = 1;
-
-  // Set the stream format description.  Do for each channel in mono mode.
-  AudioStreamBasicDescription  description;
-  dataSize = sizeof( AudioStreamBasicDescription );
-  if ( stream_.deInterleave[mode] ) nStreams = channels;
-  else nStreams = 1;
-  for ( unsigned int i=0; i<nStreams; i++, iChannel++ ) {
-
-    err = AudioDeviceGetProperty( id, iChannel, isInput,
-                                  kAudioDevicePropertyStreamFormat,
-                                  &dataSize, &description );
-    if (err != noErr) {
-      sprintf( message_, "RtApiCore: OS-X error getting stream format for device (%s).",
-               devices_[device].name.c_str() );
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Set the sample rate and data format id.
-    description.mSampleRate = (double) sampleRate;
-    description.mFormatID = kAudioFormatLinearPCM;
-    err = AudioDeviceSetProperty( id, NULL, iChannel, isInput,
-                                  kAudioDevicePropertyStreamFormat,
-                                  dataSize, &description );
-    if (err != noErr) {
-      sprintf( message_, "RtApiCore: OS-X error setting sample rate or data format for device (%s).",
-               devices_[device].name.c_str() );
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-  }
-
-  // Check whether we need byte-swapping (assuming OS-X host is big-endian).
-  iChannel -= nStreams;
-  err = AudioDeviceGetProperty( id, iChannel, isInput,
-                                kAudioDevicePropertyStreamFormat,
-                                &dataSize, &description );
-  if (err != noErr) {
-    sprintf( message_, "RtApiCore: OS-X error getting stream format for device (%s).", devices_[device].name.c_str() );
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  stream_.doByteSwap[mode] = false;
-  if ( !description.mFormatFlags & kLinearPCMFormatFlagIsBigEndian )
-    stream_.doByteSwap[mode] = true;
-
-  // From the CoreAudio documentation, PCM data must be supplied as
-  // 32-bit floats.
-  stream_.userFormat = format;
-  stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
-
-  if ( stream_.deInterleave[mode] ) // mono mode
-    stream_.nDeviceChannels[mode] = channels;
-  else
-    stream_.nDeviceChannels[mode] = description.mChannelsPerFrame;
-  stream_.nUserChannels[mode] = channels;
-
-  // 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_.nUserChannels[mode] > 1 && stream_.deInterleave[mode])
-    stream_.doConvertBuffer[mode] = true;
-
-  // Allocate our CoreHandle structure for the stream.
-  CoreHandle *handle;
-  if ( stream_.apiHandle == 0 ) {
-    handle = (CoreHandle *) calloc(1, sizeof(CoreHandle));
-    if ( handle == NULL ) {
-      sprintf(message_, "RtApiCore: OS-X error allocating coreHandle memory (%s).",
-              devices_[device].name.c_str());
-      goto error;
-    }
-    handle->index[0] = 0;
-    handle->index[1] = 0;
-    if ( pthread_cond_init(&handle->condition, NULL) ) {
-      sprintf(message_, "RtApiCore: error initializing pthread condition variable (%s).",
-              devices_[device].name.c_str());
-      goto error;
-    }
-    stream_.apiHandle = (void *) handle;
-  }
-  else
-    handle = (CoreHandle *) stream_.apiHandle;
-  handle->index[mode] = iStream;
-
-  // Allocate necessary internal buffers.
-  if ( stream_.nUserChannels[0] != stream_.nUserChannels[1] ) {
-
-    long buffer_bytes;
-    if (stream_.nUserChannels[0] >= stream_.nUserChannels[1])
-      buffer_bytes = stream_.nUserChannels[0];
-    else
-      buffer_bytes = stream_.nUserChannels[1];
-
-    buffer_bytes *= *bufferSize * formatBytes(stream_.userFormat);
-    if (stream_.userBuffer) free(stream_.userBuffer);
-    stream_.userBuffer = (char *) calloc(buffer_bytes, 1);
-    if (stream_.userBuffer == NULL) {
-      sprintf(message_, "RtApiCore: OS-X error allocating user buffer memory (%s).",
-              devices_[device].name.c_str());
-      goto error;
-    }
-  }
-
-  if ( stream_.deInterleave[mode] ) {
-
-    long buffer_bytes;
-    bool makeBuffer = true;
-    if ( mode == OUTPUT )
-      buffer_bytes = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-    else { // mode == INPUT
-      buffer_bytes = stream_.nDeviceChannels[1] * formatBytes(stream_.deviceFormat[1]);
-      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
-        long bytes_out = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-        if ( buffer_bytes < bytes_out ) makeBuffer = false;
-      }
-    }
-
-    if ( makeBuffer ) {
-      buffer_bytes *= *bufferSize;
-      if (stream_.deviceBuffer) free(stream_.deviceBuffer);
-      stream_.deviceBuffer = (char *) calloc(buffer_bytes, 1);
-      if (stream_.deviceBuffer == NULL) {
-        sprintf(message_, "RtApiCore: error allocating device buffer memory (%s).",
-                devices_[device].name.c_str());
-        goto error;
-      }
-
-      // If not de-interleaving, we point stream_.deviceBuffer to the
-      // OS X supplied device buffer before doing any necessary data
-      // conversions.  This presents a problem if we have a duplex
-      // stream using one device which needs de-interleaving and
-      // another device which doesn't.  So, save a pointer to our own
-      // device buffer in the CallbackInfo structure.
-      handle->deviceBuffer = stream_.deviceBuffer;
-    }
-  }
-
-  stream_.sampleRate = sampleRate;
-  stream_.device[mode] = device;
-  stream_.state = STREAM_STOPPED;
-  stream_.callbackInfo.object = (void *) this;
-
-  // Setup the buffer conversion information structure.
-  if ( stream_.doConvertBuffer[mode] ) {
-    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];
-    }
-
-    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 ( mode == INPUT && stream_.deInterleave[1] ) {
-      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 if (mode == OUTPUT && stream_.deInterleave[0]) {
-      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_.convertInfo[mode].outOffset.push_back( k );
-      }
-    }
-  }
-
-  if ( stream_.mode == OUTPUT && mode == INPUT && stream_.device[0] == device )
-    // Only one callback procedure per device.
-    stream_.mode = DUPLEX;
-  else {
-    err = AudioDeviceAddIOProc( id, callbackHandler, (void *) &stream_.callbackInfo );
-    if (err != noErr) {
-      sprintf( message_, "RtApiCore: OS-X error setting callback for device (%s).", devices_[device].name.c_str() );
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-    if ( stream_.mode == OUTPUT && mode == INPUT )
-      stream_.mode = DUPLEX;
-    else
-      stream_.mode = mode;
-  }
-
-  // Setup the device property listener for over/underload.
-  err = AudioDeviceAddPropertyListener( id, iChannel, isInput,
-                                        kAudioDeviceProcessorOverload,
-                                        deviceListener, (void *) handle );
-
-  return SUCCESS;
-
- error:
-  if ( handle ) {
-    pthread_cond_destroy(&handle->condition);
-    free(handle);
-    stream_.apiHandle = 0;
-  }
-
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  error(RtError::DEBUG_WARNING);
-  return FAILURE;
-}
-
-void RtApiCore :: closeStream()
-{
-  // We don't want an exception to be thrown here because this
-  // function is called by our class destructor.  So, do our own
-  // stream check.
-  if ( stream_.mode == UNINITIALIZED ) {
-    sprintf(message_, "RtApiCore::closeStream(): no open stream to close!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  AudioDeviceID id = *( (AudioDeviceID *) devices_[stream_.device[0]].apiDeviceId );
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-    if (stream_.state == STREAM_RUNNING)
-      AudioDeviceStop( id, callbackHandler );
-    AudioDeviceRemoveIOProc( id, callbackHandler );
-  }
-
-  id = *( (AudioDeviceID *) devices_[stream_.device[1]].apiDeviceId );
-  if (stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1]) ) {
-    if (stream_.state == STREAM_RUNNING)
-      AudioDeviceStop( id, callbackHandler );
-    AudioDeviceRemoveIOProc( id, callbackHandler );
-  }
-
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  if ( stream_.deInterleave[0] || stream_.deInterleave[1] ) {
-    free(stream_.deviceBuffer);
-    stream_.deviceBuffer = 0;
-  }
-
-  CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
-
-  // Destroy pthread condition variable and free the CoreHandle structure.
-  if ( handle ) {
-    pthread_cond_destroy(&handle->condition);
-    free( handle );
-    stream_.apiHandle = 0;
-  }
-
-  stream_.mode = UNINITIALIZED;
-}
-
-void RtApiCore :: startStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_RUNNING) return;
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  OSStatus err;
-  AudioDeviceID id;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-
-    id = *( (AudioDeviceID *) devices_[stream_.device[0]].apiDeviceId );
-    err = AudioDeviceStart(id, callbackHandler);
-    if (err != noErr) {
-      sprintf(message_, "RtApiCore: OS-X error starting callback procedure on device (%s).",
-              devices_[stream_.device[0]].name.c_str());
-      MUTEX_UNLOCK(&stream_.mutex);
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  if (stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1]) ) {
-
-    id = *( (AudioDeviceID *) devices_[stream_.device[1]].apiDeviceId );
-    err = AudioDeviceStart(id, callbackHandler);
-    if (err != noErr) {
-      sprintf(message_, "RtApiCore: OS-X error starting input callback procedure on device (%s).",
-              devices_[stream_.device[0]].name.c_str());
-      MUTEX_UNLOCK(&stream_.mutex);
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
-  handle->stopStream = false;
-  stream_.state = STREAM_RUNNING;
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiCore :: stopStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_STOPPED) return;
-
-  // Change the state before the lock to improve shutdown response
-  // when using a callback.
-  stream_.state = STREAM_STOPPED;
-  MUTEX_LOCK(&stream_.mutex);
-
-  OSStatus err;
-  AudioDeviceID id;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-
-    id = *( (AudioDeviceID *) devices_[stream_.device[0]].apiDeviceId );
-    err = AudioDeviceStop(id, callbackHandler);
-    if (err != noErr) {
-      sprintf(message_, "RtApiCore: OS-X error stopping callback procedure on device (%s).",
-              devices_[stream_.device[0]].name.c_str());
-      MUTEX_UNLOCK(&stream_.mutex);
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  if (stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1]) ) {
-
-    id = *( (AudioDeviceID *) devices_[stream_.device[1]].apiDeviceId );
-    err = AudioDeviceStop(id, callbackHandler);
-    if (err != noErr) {
-      sprintf(message_, "RtApiCore: OS-X error stopping input callback procedure on device (%s).",
-              devices_[stream_.device[0]].name.c_str());
-      MUTEX_UNLOCK(&stream_.mutex);
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiCore :: abortStream()
-{
-  stopStream();
-}
-
-void RtApiCore :: tickStream()
-{
-  verifyStream();
-
-  if (stream_.state == STREAM_STOPPED) return;
-
-  if (stream_.callbackInfo.usingCallback) {
-    sprintf(message_, "RtApiCore: tickStream() should not be used when a callback function is set!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  pthread_cond_wait(&handle->condition, &stream_.mutex);
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiCore :: callbackEvent( AudioDeviceID deviceId, void *inData, void *outData )
-{
-  verifyStream();
-
-  if (stream_.state == STREAM_STOPPED) return;
-
-  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
-  CoreHandle *handle = (CoreHandle *) stream_.apiHandle;
-  AudioBufferList *inBufferList = (AudioBufferList *) inData;
-  AudioBufferList *outBufferList = (AudioBufferList *) outData;
-
-  if ( info->usingCallback && handle->stopStream ) {
-    // Check if the stream should be stopped (via the previous user
-    // callback return value).  We stop the stream here, rather than
-    // after the function call, so that output data can first be
-    // processed.
-    this->stopStream();
-    return;
-  }
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  // Invoke user callback first, to get fresh output data.  Don't
-  // invoke the user callback if duplex mode AND the input/output devices
-  // are different AND this function is called for the input device.
-  AudioDeviceID id = *( (AudioDeviceID *) devices_[stream_.device[0]].apiDeviceId );
-  if ( info->usingCallback && (stream_.mode != DUPLEX || deviceId == id ) ) {
-    RtAudioCallback callback = (RtAudioCallback) info->callback;
-    handle->stopStream = callback(stream_.userBuffer, stream_.bufferSize, info->userData);
-    if ( handle->xrun == true ) {
-      handle->xrun = false;
-      MUTEX_UNLOCK(&stream_.mutex);
-      return;
-    }
-  }
-
-  if ( stream_.mode == OUTPUT || ( stream_.mode == DUPLEX && deviceId == id ) ) {
-
-    if (stream_.doConvertBuffer[0]) {
-
-      if ( !stream_.deInterleave[0] )
-        stream_.deviceBuffer = (char *) outBufferList->mBuffers[handle->index[0]].mData;
-      else
-        stream_.deviceBuffer = handle->deviceBuffer;
-
-      convertBuffer( stream_.deviceBuffer, stream_.userBuffer, stream_.convertInfo[0] );
-      if ( stream_.doByteSwap[0] )
-        byteSwapBuffer(stream_.deviceBuffer,
-                       stream_.bufferSize * stream_.nDeviceChannels[0],
-                       stream_.deviceFormat[0]);
-
-      if ( stream_.deInterleave[0] ) {
-        int bufferBytes = outBufferList->mBuffers[handle->index[0]].mDataByteSize;
-        for ( int i=0; i<stream_.nDeviceChannels[0]; i++ ) {
-          memcpy(outBufferList->mBuffers[handle->index[0]+i].mData,
-                 &stream_.deviceBuffer[i*bufferBytes], bufferBytes );
-        }
-      }
-
-    }
-    else {
-      if (stream_.doByteSwap[0])
-        byteSwapBuffer(stream_.userBuffer,
-                       stream_.bufferSize * stream_.nUserChannels[0],
-                       stream_.userFormat);
-
-      memcpy(outBufferList->mBuffers[handle->index[0]].mData,
-             stream_.userBuffer,
-             outBufferList->mBuffers[handle->index[0]].mDataByteSize );
-    }
-  }
-
-  id = *( (AudioDeviceID *) devices_[stream_.device[1]].apiDeviceId );
-  if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && deviceId == id ) ) {
-
-    if (stream_.doConvertBuffer[1]) {
-
-      if ( stream_.deInterleave[1] ) {
-        stream_.deviceBuffer = (char *) handle->deviceBuffer;
-        int bufferBytes = inBufferList->mBuffers[handle->index[1]].mDataByteSize;
-        for ( int i=0; i<stream_.nDeviceChannels[1]; i++ ) {
-          memcpy(&stream_.deviceBuffer[i*bufferBytes],
-                 inBufferList->mBuffers[handle->index[1]+i].mData, bufferBytes );
-        }
-      }
-      else
-        stream_.deviceBuffer = (char *) inBufferList->mBuffers[handle->index[1]].mData;
-
-      if ( stream_.doByteSwap[1] )
-        byteSwapBuffer(stream_.deviceBuffer,
-                       stream_.bufferSize * stream_.nDeviceChannels[1],
-                       stream_.deviceFormat[1]);
-      convertBuffer( stream_.userBuffer, stream_.deviceBuffer, stream_.convertInfo[1] );
-
-    }
-    else {
-      memcpy(stream_.userBuffer,
-             inBufferList->mBuffers[handle->index[1]].mData,
-             inBufferList->mBuffers[handle->index[1]].mDataByteSize );
-
-      if (stream_.doByteSwap[1])
-        byteSwapBuffer(stream_.userBuffer,
-                       stream_.bufferSize * stream_.nUserChannels[1],
-                       stream_.userFormat);
-    }
-  }
-
-  if ( !info->usingCallback && (stream_.mode != DUPLEX || deviceId == id ) )
-    pthread_cond_signal(&handle->condition);
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiCore :: setStreamCallback(RtAudioCallback callback, void *userData)
-{
-  verifyStream();
-
-  if ( stream_.callbackInfo.usingCallback ) {
-    sprintf(message_, "RtApiCore: A callback is already set for this stream!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  stream_.callbackInfo.callback = (void *) callback;
-  stream_.callbackInfo.userData = userData;
-  stream_.callbackInfo.usingCallback = true;
-}
-
-void RtApiCore :: cancelStreamCallback()
-{
-  verifyStream();
-
-  if (stream_.callbackInfo.usingCallback) {
-
-    if (stream_.state == STREAM_RUNNING)
-      stopStream();
-
-    MUTEX_LOCK(&stream_.mutex);
-
-    stream_.callbackInfo.usingCallback = false;
-    stream_.callbackInfo.userData = NULL;
-    stream_.state = STREAM_STOPPED;
-    stream_.callbackInfo.callback = NULL;
-
-    MUTEX_UNLOCK(&stream_.mutex);
-  }
-}
-
-
-//******************** End of __MACOSX_CORE__ *********************//
-#endif
-
-#if defined(__LINUX_JACK__)
-
-// JACK is a low-latency audio server, written primarily for the
-// GNU/Linux operating system. It can connect a number of different
-// applications to an audio device, as well as allowing them to share
-// audio between themselves.
-//
-// The JACK server must be running before RtApiJack can be instantiated.
-// RtAudio will report just a single "device", which is the JACK audio
-// 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.
-
-#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];
-  bool clientOpen;
-  bool stopStream;
-  pthread_cond_t condition;
-
-  JackHandle()
-    :client(0), clientOpen(false), stopStream(false) {}
-};
-
-std::string jackmsg;
-
-static void jackerror (const char *desc)
-{
-  jackmsg.erase();
-  jackmsg.append( desc, strlen(desc)+1 );
-}
-
-RtApiJack :: RtApiJack()
-{
-  this->initialize();
-
-  if (nDevices_ <= 0) {
-    sprintf(message_, "RtApiJack: no Linux Jack server found or connection error (jack: %s)!",
-            jackmsg.c_str());
-    error(RtError::NO_DEVICES_FOUND);
-  }
-}
-
-RtApiJack :: ~RtApiJack()
-{
-  if ( stream_.mode != UNINITIALIZED ) closeStream();
-}
-
-void RtApiJack :: initialize(void)
-{
-  nDevices_ = 0;
-
-  // Tell the jack server to call jackerror() when it experiences an
-  // error.  This function saves the error message for subsequent
-  // reporting via the normal RtAudio error function.
-       jack_set_error_function( jackerror );
-
-  // Look for jack server and try to become a client.
-  jack_client_t *client;
-  if ( (client = jack_client_new( "RtApiJack" )) == 0)
-    return;
-
-  /*
-    RtApiDevice device;
-    // Determine the name of the device.
-    device.name = "Jack Server";
-    devices_.push_back(device);
-    nDevices_++;
-  */
-  const char **ports;
-  std::string port, prevPort;
-  unsigned int nChannels = 0;
-  ports = jack_get_ports( client, NULL, NULL, 0 );
-  if ( ports ) {
-    port = (char *) ports[ nChannels ];
-    unsigned int colonPos = 0;
-    do {
-      port = (char *) ports[ nChannels ];
-      if ( (colonPos = port.find(":")) != std::string::npos ) {
-        port = port.substr( 0, colonPos+1 );
-        if ( port != prevPort ) {
-          RtApiDevice device;
-          device.name = port;
-          devices_.push_back( device );
-          nDevices_++;
-          prevPort = port;
-        }
-      }
-    } while ( ports[++nChannels] );
-    free( ports );
-  }
-
-  jack_client_close(client);
-}
-
-void RtApiJack :: probeDeviceInfo(RtApiDevice *info)
-{
-  // Look for jack server and try to become a client.
-  jack_client_t *client;
-  if ( (client = jack_client_new( "RtApiJack_Probe" )) == 0) {
-    sprintf(message_, "RtApiJack: error connecting to Linux Jack server in probeDeviceInfo() (jack: %s)!",
-            jackmsg.c_str());
-    error(RtError::WARNING);
-    return;
-  }
-
-  // Get the current jack server sample rate.
-  info->sampleRates.clear();
-  info->sampleRates.push_back( jack_get_sample_rate(client) );
-
-  // Count the available ports as device channels.  Jack "input ports"
-  // equal RtAudio output channels.
-  const char **ports;
-  char *port;
-  unsigned int nChannels = 0;
-  ports = jack_get_ports( client, info->name.c_str(), NULL, JackPortIsInput );
-  if ( ports ) {
-    port = (char *) ports[nChannels];
-    while ( port )
-      port = (char *) ports[++nChannels];
-    free( ports );
-    info->maxOutputChannels = nChannels;
-    info->minOutputChannels = 1;
-  }
-
-  // Jack "output ports" equal RtAudio input channels.
-  nChannels = 0;
-  ports = jack_get_ports( client, info->name.c_str(), NULL, JackPortIsOutput );
-  if ( ports ) {
-    port = (char *) ports[nChannels];
-    while ( port )
-      port = (char *) ports[++nChannels];
-    free( ports );
-    info->maxInputChannels = nChannels;
-    info->minInputChannels = 1;
-  }
-
-  if (info->maxOutputChannels == 0 && info->maxInputChannels == 0) {
-    jack_client_close(client);
-    sprintf(message_, "RtApiJack: error determining jack input/output channels!");
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  if (info->maxOutputChannels > 0 && info->maxInputChannels > 0) {
-    info->hasDuplexSupport = true;
-    info->maxDuplexChannels = (info->maxOutputChannels > info->maxInputChannels) ?
-      info->maxInputChannels : info->maxOutputChannels;
-    info->minDuplexChannels = (info->minOutputChannels > info->minInputChannels) ?
-      info->minInputChannels : info->minOutputChannels;
-  }
-
-  // Get the jack data format type.  There isn't much documentation
-  // regarding supported data formats in jack.  I'm assuming here that
-  // the default type will always be a floating-point type, of length
-  // equal to either 4 or 8 bytes.
-  int sample_size = sizeof( jack_default_audio_sample_t );
-  if ( sample_size == 4 )
-    info->nativeFormats = RTAUDIO_FLOAT32;
-  else if ( sample_size == 8 )
-    info->nativeFormats = RTAUDIO_FLOAT64;
-
-  // Check that we have a supported format
-  if (info->nativeFormats == 0) {
-    jack_client_close(client);
-    sprintf(message_, "RtApiJack: error determining jack server data format!");
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  jack_client_close(client);
-  info->probed = true;
-}
-
-int jackCallbackHandler(jack_nframes_t nframes, void *infoPointer)
-{
-  CallbackInfo *info = (CallbackInfo *) infoPointer;
-  RtApiJack *object = (RtApiJack *) info->object;
-  try {
-    object->callbackEvent( (unsigned long) nframes );
-  }
-  catch (RtError &exception) {
-    fprintf(stderr, "\nRtApiJack: callback handler error (%s)!\n\n", exception.getMessageString());
-    return 0;
-  }
-
-  return 0;
-}
-
-void jackShutdown(void *infoPointer)
-{
-  CallbackInfo *info = (CallbackInfo *) infoPointer;
-  JackHandle *handle = (JackHandle *) info->apiInfo;
-  handle->clientOpen = false;
-  RtApiJack *object = (RtApiJack *) info->object;
-
-  // 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->getStreamState() == RtApi::STREAM_STOPPED ) return;
-
-  try {
-    object->closeStream();
-  }
-  catch (RtError &exception) {
-    fprintf(stderr, "\nRtApiJack: jackShutdown error (%s)!\n\n", exception.getMessageString());
-    return;
-  }
-
-  fprintf(stderr, "\nRtApiJack: the Jack server is shutting down this client ... stream stopped and closed!!!\n\n");
-}
-
-int jackXrun( void * )
-{
-  fprintf(stderr, "\nRtApiJack: audio overrun/underrun reported!\n");
-  return 0;
-}
-
-bool RtApiJack :: probeDeviceOpen(int device, StreamMode mode, int channels, 
-                                int sampleRate, RtAudioFormat format,
-                                int *bufferSize, int numberOfBuffers)
-{
-  // Compare the jack server channels to the requested number of channels.
-  if ( (mode == OUTPUT && devices_[device].maxOutputChannels < channels ) || 
-       (mode == INPUT && devices_[device].maxInputChannels < channels ) ) {
-    sprintf(message_, "RtApiJack: the Jack server does not support requested channels!");
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  JackHandle *handle = (JackHandle *) stream_.apiHandle;
-
-  // Look for jack server and try to become a client (only do once per stream).
-  char label[32];
-  jack_client_t *client = 0;
-  if ( mode == OUTPUT || (mode == INPUT && stream_.mode != OUTPUT) ) {
-    snprintf(label, 32, "RtApiJack");
-    if ( (client = jack_client_new( (const char *) label )) == 0) {
-      sprintf(message_, "RtApiJack: cannot connect to Linux Jack server in probeDeviceOpen() (jack: %s)!",
-              jackmsg.c_str());
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-  }
-  else {
-    // The handle must have been created on an earlier pass.
-    client = handle->client;
-  }
-
-  // First, check the jack server sample rate.
-  int jack_rate;
-  jack_rate = (int) jack_get_sample_rate(client);
-  if ( sampleRate != jack_rate ) {
-    jack_client_close(client);
-    sprintf( message_, "RtApiJack: the requested sample rate (%d) is different than the JACK server rate (%d).",
-             sampleRate, jack_rate );
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-  stream_.sampleRate = jack_rate;
-
-  // The jack server seems to support just a single floating-point
-  // data type.  Since we already checked it before, just use what we
-  // found then.
-  stream_.deviceFormat[mode] = devices_[device].nativeFormats;
-  stream_.userFormat = format;
-
-  // Jack always uses non-interleaved buffers.  We'll need to
-  // de-interleave if we have more than one channel.
-  stream_.deInterleave[mode] = false;
-  if ( channels > 1 )
-    stream_.deInterleave[mode] = true;
-
-  // Jack always provides host byte-ordered data.
-  stream_.doByteSwap[mode] = false;
-
-  // 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;
-
-  stream_.nDeviceChannels[mode] = channels;
-  stream_.nUserChannels[mode] = channels;
-
-  stream_.doConvertBuffer[mode] = false;
-  if (stream_.userFormat != stream_.deviceFormat[mode])
-    stream_.doConvertBuffer[mode] = true;
-  if (stream_.deInterleave[mode])
-    stream_.doConvertBuffer[mode] = true;
-
-  // Allocate our JackHandle structure for the stream.
-  if ( handle == 0 ) {
-    handle = (JackHandle *) calloc(1, sizeof(JackHandle));
-    if ( handle == NULL ) {
-      sprintf(message_, "RtApiJack: error allocating JackHandle memory (%s).",
-              devices_[device].name.c_str());
-      goto error;
-    }
-    handle->ports[0] = 0;
-    handle->ports[1] = 0;
-    if ( pthread_cond_init(&handle->condition, NULL) ) {
-      sprintf(message_, "RtApiJack: error initializing pthread condition variable!");
-      goto error;
-    }
-    stream_.apiHandle = (void *) handle;
-    handle->client = client;
-    handle->clientOpen = true;
-  }
-
-  // Allocate necessary internal buffers.
-  if ( stream_.nUserChannels[0] != stream_.nUserChannels[1] ) {
-
-    long buffer_bytes;
-    if (stream_.nUserChannels[0] >= stream_.nUserChannels[1])
-      buffer_bytes = stream_.nUserChannels[0];
-    else
-      buffer_bytes = stream_.nUserChannels[1];
-
-    buffer_bytes *= *bufferSize * formatBytes(stream_.userFormat);
-    if (stream_.userBuffer) free(stream_.userBuffer);
-    stream_.userBuffer = (char *) calloc(buffer_bytes, 1);
-    if (stream_.userBuffer == NULL) {
-      sprintf(message_, "RtApiJack: error allocating user buffer memory (%s).",
-              devices_[device].name.c_str());
-      goto error;
-    }
-  }
-
-  if ( stream_.doConvertBuffer[mode] ) {
-
-    long buffer_bytes;
-    bool makeBuffer = true;
-    if ( mode == OUTPUT )
-      buffer_bytes = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-    else { // mode == INPUT
-      buffer_bytes = stream_.nDeviceChannels[1] * formatBytes(stream_.deviceFormat[1]);
-      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
-        long bytes_out = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-        if ( buffer_bytes < bytes_out ) makeBuffer = false;
-      }
-    }
-
-    if ( makeBuffer ) {
-      buffer_bytes *= *bufferSize;
-      if (stream_.deviceBuffer) free(stream_.deviceBuffer);
-      stream_.deviceBuffer = (char *) calloc(buffer_bytes, 1);
-      if (stream_.deviceBuffer == NULL) {
-        sprintf(message_, "RtApiJack: error allocating device buffer memory (%s).",
-                devices_[device].name.c_str());
-        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 )  {
-    sprintf(message_, "RtApiJack: error allocating port handle memory (%s).",
-            devices_[device].name.c_str());
-    goto error;
-  }
-
-  stream_.device[mode] = device;
-  stream_.state = STREAM_STOPPED;
-  stream_.callbackInfo.usingCallback = false;
-  stream_.callbackInfo.object = (void *) this;
-  stream_.callbackInfo.apiInfo = (void *) handle;
-
-  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, NULL );
-    jack_on_shutdown( handle->client, jackShutdown, (void *) &stream_.callbackInfo );
-  }
-
-  // Setup the buffer conversion information structure.
-  if ( stream_.doConvertBuffer[mode] ) {
-    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];
-    }
-
-    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 ( mode == INPUT && stream_.deInterleave[1] ) {
-      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 if (mode == OUTPUT && stream_.deInterleave[0]) {
-      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_.convertInfo[mode].outOffset.push_back( k );
-      }
-    }
-  }
-
-  return SUCCESS;
-
- error:
-  if ( handle ) {
-    pthread_cond_destroy(&handle->condition);
-    if ( handle->clientOpen == true )
-      jack_client_close(handle->client);
-
-    if ( handle->ports[0] ) free(handle->ports[0]);
-    if ( handle->ports[1] ) free(handle->ports[1]);
-
-    free( handle );
-    stream_.apiHandle = 0;
-  }
-
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  error(RtError::DEBUG_WARNING);
-  return FAILURE;
-}
-
-void RtApiJack :: closeStream()
-{
-  // We don't want an exception to be thrown here because this
-  // function is called by our class destructor.  So, do our own
-  // stream check.
-  if ( stream_.mode == UNINITIALIZED ) {
-    sprintf(message_, "RtApiJack::closeStream(): no open stream to close!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  JackHandle *handle = (JackHandle *) stream_.apiHandle;
-  if ( handle && handle->clientOpen == true ) {
-    if (stream_.state == STREAM_RUNNING)
-      jack_deactivate(handle->client);
-
-    jack_client_close(handle->client);
-  }
-
-  if ( handle ) {
-    if ( handle->ports[0] ) free(handle->ports[0]);
-    if ( handle->ports[1] ) free(handle->ports[1]);
-    pthread_cond_destroy(&handle->condition);
-    free( handle );
-    stream_.apiHandle = 0;
-  }
-
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  if (stream_.deviceBuffer) {
-    free(stream_.deviceBuffer);
-    stream_.deviceBuffer = 0;
-  }
-
-  stream_.mode = UNINITIALIZED;
-}
-
-
-void RtApiJack :: startStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_RUNNING) return;
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  char label[64];
-  JackHandle *handle = (JackHandle *) stream_.apiHandle;
-  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
-    for ( 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);
-    }
-  }
-
-  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
-    for ( 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 (jack_activate(handle->client)) {
-    sprintf(message_, "RtApiJack: unable to activate JACK client!");
-    error(RtError::SYSTEM_ERROR);
-  }
-
-  const char **ports;
-  int result;
-  // Get the list of available ports.
-  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
-    ports = jack_get_ports(handle->client, devices_[stream_.device[0]].name.c_str(), NULL, JackPortIsInput);
-    if ( ports == NULL) {
-      sprintf(message_, "RtApiJack: error determining available jack input ports!");
-      error(RtError::SYSTEM_ERROR);
-    }
-
-    // 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.
-    for ( int i=0; i<stream_.nUserChannels[0]; i++ ) {
-      result = 1;
-      if ( ports[i] )
-        result = jack_connect( handle->client, jack_port_name(handle->ports[0][i]), ports[i] );
-      if ( result ) {
-        free(ports);
-        sprintf(message_, "RtApiJack: error connecting output ports!");
-        error(RtError::SYSTEM_ERROR);
-      }
-    }
-    free(ports);
-  }
-
-  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
-    ports = jack_get_ports( handle->client, devices_[stream_.device[1]].name.c_str(), NULL, JackPortIsOutput );
-    if ( ports == NULL) {
-      sprintf(message_, "RtApiJack: error determining available jack output ports!");
-      error(RtError::SYSTEM_ERROR);
-    }
-
-    // Now make the port connections.  See note above.
-    for ( int i=0; i<stream_.nUserChannels[1]; i++ ) {
-      result = 1;
-      if ( ports[i] )
-        result = jack_connect( handle->client, ports[i], jack_port_name(handle->ports[1][i]) );
-      if ( result ) {
-        free(ports);
-        sprintf(message_, "RtApiJack: error connecting input ports!");
-        error(RtError::SYSTEM_ERROR);
-      }
-    }
-    free(ports);
-  }
-
-  handle->stopStream = false;
-  stream_.state = STREAM_RUNNING;
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiJack :: stopStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_STOPPED) return;
-
-  // Change the state before the lock to improve shutdown response
-  // when using a callback.
-  stream_.state = STREAM_STOPPED;
-  MUTEX_LOCK(&stream_.mutex);
-
-  JackHandle *handle = (JackHandle *) stream_.apiHandle;
-  jack_deactivate(handle->client);
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiJack :: abortStream()
-{
-  stopStream();
-}
-
-void RtApiJack :: tickStream()
-{
-  verifyStream();
-
-  if (stream_.state == STREAM_STOPPED) return;
-
-  if (stream_.callbackInfo.usingCallback) {
-    sprintf(message_, "RtApiJack: tickStream() should not be used when a callback function is set!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  JackHandle *handle = (JackHandle *) stream_.apiHandle;
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  pthread_cond_wait(&handle->condition, &stream_.mutex);
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiJack :: callbackEvent( unsigned long nframes )
-{
-  verifyStream();
-
-  if (stream_.state == STREAM_STOPPED) return;
-
-  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
-  JackHandle *handle = (JackHandle *) stream_.apiHandle;
-  if ( info->usingCallback && handle->stopStream ) {
-    // Check if the stream should be stopped (via the previous user
-    // callback return value).  We stop the stream here, rather than
-    // after the function call, so that output data can first be
-    // processed.
-    this->stopStream();
-    return;
-  }
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  // Invoke user callback first, to get fresh output data.
-  if ( info->usingCallback ) {
-    RtAudioCallback callback = (RtAudioCallback) info->callback;
-    handle->stopStream = callback(stream_.userBuffer, stream_.bufferSize, info->userData);
-  }
-
-  jack_default_audio_sample_t *jackbuffer;
-  long bufferBytes = nframes * sizeof(jack_default_audio_sample_t);
-  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
-
-    if (stream_.doConvertBuffer[0]) {
-      convertBuffer( stream_.deviceBuffer, stream_.userBuffer, stream_.convertInfo[0] );
-
-      for ( 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 { // single channel only
-      jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer(handle->ports[0][0],
-                                                                        (jack_nframes_t) nframes);
-      memcpy(jackbuffer, stream_.userBuffer, bufferBytes );
-    }
-  }
-
-  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
-
-    if (stream_.doConvertBuffer[1]) {
-    for ( 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, stream_.deviceBuffer, stream_.convertInfo[1] );
-    }
-    else { // single channel only
-      jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer(handle->ports[1][0],
-                                                                        (jack_nframes_t) nframes);
-      memcpy(stream_.userBuffer, jackbuffer, bufferBytes );
-    }
-  }
-
-  if ( !info->usingCallback )
-    pthread_cond_signal(&handle->condition);
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiJack :: setStreamCallback(RtAudioCallback callback, void *userData)
-{
-  verifyStream();
-
-  if ( stream_.callbackInfo.usingCallback ) {
-    sprintf(message_, "RtApiJack: A callback is already set for this stream!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  stream_.callbackInfo.callback = (void *) callback;
-  stream_.callbackInfo.userData = userData;
-  stream_.callbackInfo.usingCallback = true;
-}
-
-void RtApiJack :: cancelStreamCallback()
-{
-  verifyStream();
-
-  if (stream_.callbackInfo.usingCallback) {
-
-    if (stream_.state == STREAM_RUNNING)
-      stopStream();
-
-    MUTEX_LOCK(&stream_.mutex);
-
-    stream_.callbackInfo.usingCallback = false;
-    stream_.callbackInfo.userData = NULL;
-    stream_.state = STREAM_STOPPED;
-    stream_.callbackInfo.callback = NULL;
-
-    MUTEX_UNLOCK(&stream_.mutex);
-  }
-}
-
-#endif
-
-#if defined(__LINUX_ALSA__)
-
-#include <alsa/asoundlib.h>
-#include <unistd.h>
-#include <ctype.h>
-
-// A structure to hold various information related to the ALSA API
-// implementation.
-struct AlsaHandle {
-  snd_pcm_t *handles[2];
-  bool synchronized;
-  char *tempBuffer;
-
-  AlsaHandle()
-    :synchronized(false), tempBuffer(0) {}
-};
-
-extern "C" void *alsaCallbackHandler(void * ptr);
-
-RtApiAlsa :: RtApiAlsa()
-{
-  this->initialize();
-
-  if (nDevices_ <= 0) {
-    sprintf(message_, "RtApiAlsa: no Linux ALSA audio devices found!");
-    error(RtError::NO_DEVICES_FOUND);
-  }
-}
-
-RtApiAlsa :: ~RtApiAlsa()
-{
-  if ( stream_.mode != UNINITIALIZED )
-    closeStream();
-}
-
-void RtApiAlsa :: initialize(void)
-{
-  int card, subdevice, result;
-  char name[64];
-  const char *cardId;
-  snd_ctl_t *handle;
-  snd_ctl_card_info_t *info;
-  snd_ctl_card_info_alloca(&info);
-  RtApiDevice device;
-
-  // Count cards and devices
-  nDevices_ = 0;
-  card = -1;
-  snd_card_next(&card);
-  while ( card >= 0 ) {
-    sprintf(name, "hw:%d", card);
-    result = snd_ctl_open(&handle, name, 0);
-    if (result < 0) {
-      sprintf(message_, "RtApiAlsa: control open (%i): %s.", card, snd_strerror(result));
-      error(RtError::DEBUG_WARNING);
-      goto next_card;
-               }
-    result = snd_ctl_card_info(handle, info);
-               if (result < 0) {
-      sprintf(message_, "RtApiAlsa: control hardware info (%i): %s.", card, snd_strerror(result));
-      error(RtError::DEBUG_WARNING);
-      goto next_card;
-               }
-    cardId = snd_ctl_card_info_get_id(info);
-               subdevice = -1;
-               while (1) {
-      result = snd_ctl_pcm_next_device(handle, &subdevice);
-                       if (result < 0) {
-        sprintf(message_, "RtApiAlsa: control next device (%i): %s.", card, snd_strerror(result));
-        error(RtError::DEBUG_WARNING);
-        break;
-      }
-                       if (subdevice < 0)
-        break;
-      sprintf( name, "hw:%d,%d", card, subdevice );
-      // If a cardId exists and it contains at least one non-numeric
-      // character, use it to identify the device.  This avoids a bug
-      // in ALSA such that a numeric string is interpreted as a device
-      // number.
-      for ( unsigned int i=0; i<strlen(cardId); i++ ) {
-        if ( !isdigit( cardId[i] ) ) {
-          sprintf( name, "hw:%s,%d", cardId, subdevice );
-          break;
-        }
-      }
-      device.name.erase();
-      device.name.append( (const char *)name, strlen(name)+1 );
-      devices_.push_back(device);
-      nDevices_++;
-    }
-  next_card:
-    snd_ctl_close(handle);
-    snd_card_next(&card);
-  }
-}
-
-void RtApiAlsa :: probeDeviceInfo(RtApiDevice *info)
-{
-  int err;
-  int open_mode = SND_PCM_ASYNC;
-  snd_pcm_t *handle;
-  snd_ctl_t *chandle;
-  snd_pcm_stream_t stream;
-       snd_pcm_info_t *pcminfo;
-       snd_pcm_info_alloca(&pcminfo);
-  snd_pcm_hw_params_t *params;
-  snd_pcm_hw_params_alloca(&params);
-  char name[64];
-  char *card;
-
-  // Open the control interface for this card.
-  strncpy( name, info->name.c_str(), 64 );
-  card = strtok(name, ",");
-  err = snd_ctl_open(&chandle, card, SND_CTL_NONBLOCK);
-  if (err < 0) {
-    sprintf(message_, "RtApiAlsa: control open (%s): %s.", card, snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-  unsigned int dev = (unsigned int) atoi( strtok(NULL, ",") );
-
-  // First try for playback
-  stream = SND_PCM_STREAM_PLAYBACK;
-  snd_pcm_info_set_device(pcminfo, dev);
-  snd_pcm_info_set_subdevice(pcminfo, 0);
-  snd_pcm_info_set_stream(pcminfo, stream);
-
-  if ((err = snd_ctl_pcm_info(chandle, pcminfo)) < 0) {
-    if (err == -ENOENT) {
-      sprintf(message_, "RtApiAlsa: pcm device (%s) doesn't handle output!", info->name.c_str());
-      error(RtError::DEBUG_WARNING);
-    }
-    else {
-      sprintf(message_, "RtApiAlsa: snd_ctl_pcm_info error for device (%s) output: %s",
-              info->name.c_str(), snd_strerror(err));
-      error(RtError::DEBUG_WARNING);
-    }
-    goto capture_probe;
-  }
-
-  err = snd_pcm_open(&handle, info->name.c_str(), stream, open_mode | SND_PCM_NONBLOCK );
-  if (err < 0) {
-    if ( err == EBUSY )
-      sprintf(message_, "RtApiAlsa: pcm playback device (%s) is busy: %s.",
-              info->name.c_str(), snd_strerror(err));
-    else
-      sprintf(message_, "RtApiAlsa: pcm playback open (%s) error: %s.",
-              info->name.c_str(), snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    goto capture_probe;
-  }
-
-  // We have an open device ... allocate the parameter structure.
-  err = snd_pcm_hw_params_any(handle, params);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: hardware probe error (%s): %s.",
-            info->name.c_str(), snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    goto capture_probe;
-  }
-
-  // Get output channel information.
-  unsigned int value;
-  err = snd_pcm_hw_params_get_channels_min(params, &value);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: hardware minimum channel probe error (%s): %s.",
-            info->name.c_str(), snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    goto capture_probe;
-  }
-  info->minOutputChannels = value;
-
-  err = snd_pcm_hw_params_get_channels_max(params, &value);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: hardware maximum channel probe error (%s): %s.",
-            info->name.c_str(), snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    goto capture_probe;
-  }
-  info->maxOutputChannels = value;
-
-  snd_pcm_close(handle);
-
- capture_probe:
-  // Now try for capture
-  stream = SND_PCM_STREAM_CAPTURE;
-  snd_pcm_info_set_stream(pcminfo, stream);
-
-  err = snd_ctl_pcm_info(chandle, pcminfo);
-  snd_ctl_close(chandle);
-  if ( err < 0 ) {
-    if (err == -ENOENT) {
-      sprintf(message_, "RtApiAlsa: pcm device (%s) doesn't handle input!", info->name.c_str());
-      error(RtError::DEBUG_WARNING);
-    }
-    else {
-      sprintf(message_, "RtApiAlsa: snd_ctl_pcm_info error for device (%s) input: %s",
-              info->name.c_str(), snd_strerror(err));
-      error(RtError::DEBUG_WARNING);
-    }
-    if (info->maxOutputChannels == 0)
-      // didn't open for playback either ... device invalid
-      return;
-    goto probe_parameters;
-  }
-
-  err = snd_pcm_open(&handle, info->name.c_str(), stream, open_mode | SND_PCM_NONBLOCK);
-  if (err < 0) {
-    if ( err == EBUSY )
-      sprintf(message_, "RtApiAlsa: pcm capture device (%s) is busy: %s.",
-              info->name.c_str(), snd_strerror(err));
-    else
-      sprintf(message_, "RtApiAlsa: pcm capture open (%s) error: %s.",
-              info->name.c_str(), snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    if (info->maxOutputChannels == 0)
-      // didn't open for playback either ... device invalid
-      return;
-    goto probe_parameters;
-  }
-
-  // We have an open capture device ... allocate the parameter structure.
-  err = snd_pcm_hw_params_any(handle, params);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: hardware probe error (%s): %s.",
-            info->name.c_str(), snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    if (info->maxOutputChannels > 0)
-      goto probe_parameters;
-    else
-      return;
-  }
-
-  // Get input channel information.
-  err = snd_pcm_hw_params_get_channels_min(params, &value);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: hardware minimum in channel probe error (%s): %s.",
-            info->name.c_str(), snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    if (info->maxOutputChannels > 0)
-      goto probe_parameters;
-    else
-      return;
-  }
-  info->minInputChannels = value;
-
-  err = snd_pcm_hw_params_get_channels_max(params, &value);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: hardware maximum in channel probe error (%s): %s.",
-            info->name.c_str(), snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    if (info->maxOutputChannels > 0)
-      goto probe_parameters;
-    else
-      return;
-  }
-  info->maxInputChannels = value;
-
-  snd_pcm_close(handle);
-
-  // If device opens for both playback and capture, we determine the channels.
-  if (info->maxOutputChannels == 0 || info->maxInputChannels == 0)
-    goto probe_parameters;
-
-  info->hasDuplexSupport = true;
-  info->maxDuplexChannels = (info->maxOutputChannels > info->maxInputChannels) ?
-    info->maxInputChannels : info->maxOutputChannels;
-  info->minDuplexChannels = (info->minOutputChannels > info->minInputChannels) ?
-    info->minInputChannels : info->minOutputChannels;
-
- probe_parameters:
-  // 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->maxOutputChannels >= info->maxInputChannels)
-    stream = SND_PCM_STREAM_PLAYBACK;
-  else
-    stream = SND_PCM_STREAM_CAPTURE;
-
-  err = snd_pcm_open(&handle, info->name.c_str(), stream, open_mode);
-  if (err < 0) {
-    sprintf(message_, "RtApiAlsa: pcm (%s) won't reopen during probe: %s.",
-            info->name.c_str(), snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // We have an open device ... allocate the parameter structure.
-  err = snd_pcm_hw_params_any(handle, params);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: hardware reopen probe error (%s): %s.",
-            info->name.c_str(), snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // Test our discrete set of sample rate values.
-  int dir = 0;
-  info->sampleRates.clear();
-  for (unsigned int i=0; i<MAX_SAMPLE_RATES; i++) {
-    if (snd_pcm_hw_params_test_rate(handle, params, SAMPLE_RATES[i], dir) == 0)
-      info->sampleRates.push_back(SAMPLE_RATES[i]);
-  }
-  if (info->sampleRates.size() == 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: no supported sample rates found for device (%s).",
-            info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // 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(handle, params, format) == 0)
-    info->nativeFormats |= RTAUDIO_SINT8;
-  format = SND_PCM_FORMAT_S16;
-  if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
-    info->nativeFormats |= RTAUDIO_SINT16;
-  format = SND_PCM_FORMAT_S24;
-  if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
-    info->nativeFormats |= RTAUDIO_SINT24;
-  format = SND_PCM_FORMAT_S32;
-  if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
-    info->nativeFormats |= RTAUDIO_SINT32;
-  format = SND_PCM_FORMAT_FLOAT;
-  if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
-    info->nativeFormats |= RTAUDIO_FLOAT32;
-  format = SND_PCM_FORMAT_FLOAT64;
-  if (snd_pcm_hw_params_test_format(handle, params, format) == 0)
-    info->nativeFormats |= RTAUDIO_FLOAT64;
-
-  // Check that we have at least one supported format
-  if (info->nativeFormats == 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: pcm device (%s) data format not supported by RtAudio.",
-            info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // That's all ... close the device and return
-  snd_pcm_close(handle);
-  info->probed = true;
-  return;
-}
-
-bool RtApiAlsa :: probeDeviceOpen( int device, StreamMode mode, int channels, 
-                                   int sampleRate, RtAudioFormat format,
-                                   int *bufferSize, int numberOfBuffers )
-{
-#if defined(__RTAUDIO_DEBUG__)
-  snd_output_t *out;
-  snd_output_stdio_attach(&out, stderr, 0);
-#endif
-
-  // I'm not using the "plug" interface ... too much inconsistent behavior.
-  const char *name = devices_[device].name.c_str();
-
-  snd_pcm_stream_t alsa_stream;
-  if (mode == OUTPUT)
-    alsa_stream = SND_PCM_STREAM_PLAYBACK;
-  else
-    alsa_stream = SND_PCM_STREAM_CAPTURE;
-
-  int err;
-  snd_pcm_t *handle;
-  int alsa_open_mode = SND_PCM_ASYNC;
-  err = snd_pcm_open(&handle, name, alsa_stream, alsa_open_mode);
-  if (err < 0) {
-    sprintf(message_,"RtApiAlsa: pcm device (%s) won't open: %s.",
-            name, snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  // Fill the parameter structure.
-  snd_pcm_hw_params_t *hw_params;
-  snd_pcm_hw_params_alloca(&hw_params);
-  err = snd_pcm_hw_params_any(handle, hw_params);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: error getting parameter handle (%s): %s.",
-            name, snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    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);
-#endif
-
-  // Set access ... try interleaved access first, then non-interleaved
-  if ( !snd_pcm_hw_params_test_access( handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED) ) {
-    err = snd_pcm_hw_params_set_access(handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
-  }
-  else if ( !snd_pcm_hw_params_test_access( handle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED) ) {
-               err = snd_pcm_hw_params_set_access(handle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED);
-    stream_.deInterleave[mode] = true;
-  }
-  else {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: device (%s) access not supported by RtAudio.", name);
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: error setting access ( (%s): %s.", name, snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  // Determine how to set the device format.
-  stream_.userFormat = format;
-  snd_pcm_format_t device_format = SND_PCM_FORMAT_UNKNOWN;
-
-  if (format == RTAUDIO_SINT8)
-    device_format = SND_PCM_FORMAT_S8;
-  else if (format == RTAUDIO_SINT16)
-    device_format = SND_PCM_FORMAT_S16;
-  else if (format == RTAUDIO_SINT24)
-    device_format = SND_PCM_FORMAT_S24;
-  else if (format == RTAUDIO_SINT32)
-    device_format = SND_PCM_FORMAT_S32;
-  else if (format == RTAUDIO_FLOAT32)
-    device_format = SND_PCM_FORMAT_FLOAT;
-  else if (format == RTAUDIO_FLOAT64)
-    device_format = SND_PCM_FORMAT_FLOAT64;
-
-  if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
-    stream_.deviceFormat[mode] = format;
-    goto set_format;
-  }
-
-  // The user requested format is not natively supported by the device.
-  device_format = SND_PCM_FORMAT_FLOAT64;
-  if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
-    stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;
-    goto set_format;
-  }
-
-  device_format = SND_PCM_FORMAT_FLOAT;
-  if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
-    stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
-    goto set_format;
-  }
-
-  device_format = SND_PCM_FORMAT_S32;
-  if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
-    stream_.deviceFormat[mode] = RTAUDIO_SINT32;
-    goto set_format;
-  }
-
-  device_format = SND_PCM_FORMAT_S24;
-  if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
-    stream_.deviceFormat[mode] = RTAUDIO_SINT24;
-    goto set_format;
-  }
-
-  device_format = SND_PCM_FORMAT_S16;
-  if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
-    stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-    goto set_format;
-  }
-
-  device_format = SND_PCM_FORMAT_S8;
-  if (snd_pcm_hw_params_test_format(handle, hw_params, device_format) == 0) {
-    stream_.deviceFormat[mode] = RTAUDIO_SINT8;
-    goto set_format;
-  }
-
-  // If we get here, no supported format was found.
-  sprintf(message_,"RtApiAlsa: pcm device (%s) data format not supported by RtAudio.", name);
-  snd_pcm_close(handle);
-  error(RtError::DEBUG_WARNING);
-  return FAILURE;
-
- set_format:
-  err = snd_pcm_hw_params_set_format(handle, hw_params, device_format);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: error setting format (%s): %s.",
-            name, snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  // Determine whether byte-swaping is necessary.
-  stream_.doByteSwap[mode] = false;
-  if (device_format != SND_PCM_FORMAT_S8) {
-    err = snd_pcm_format_cpu_endian(device_format);
-    if (err == 0)
-      stream_.doByteSwap[mode] = true;
-    else if (err < 0) {
-      snd_pcm_close(handle);
-      sprintf(message_, "RtApiAlsa: error getting format endian-ness (%s): %s.",
-              name, snd_strerror(err));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-  }
-
-  // Set the sample rate.
-  err = snd_pcm_hw_params_set_rate(handle, hw_params, (unsigned int)sampleRate, 0);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: error setting sample rate (%d) on device (%s): %s.",
-            sampleRate, name, snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    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;
-  err = snd_pcm_hw_params_get_channels_max(hw_params, &value);
-  int device_channels = value;
-  if (err < 0 || device_channels < channels) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: channels (%d) not supported by device (%s).",
-            channels, name);
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  err = snd_pcm_hw_params_get_channels_min(hw_params, &value);
-  if (err < 0 ) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: error getting min channels count on device (%s).", name);
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-  device_channels = value;
-  if (device_channels < channels) device_channels = channels;
-  stream_.nDeviceChannels[mode] = device_channels;
-
-  // Set the device channels.
-  err = snd_pcm_hw_params_set_channels(handle, hw_params, device_channels);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: error setting channels (%d) on device (%s): %s.",
-            device_channels, name, snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  // Set the buffer number, which in ALSA is referred to as the "period".
-  int dir;
-  unsigned int periods = numberOfBuffers;
-  // Even though the hardware might allow 1 buffer, it won't work reliably.
-  if (periods < 2) periods = 2;
-  err = snd_pcm_hw_params_set_periods_near(handle, hw_params, &periods, &dir);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: error setting periods (%s): %s.",
-            name, snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  // Set the buffer (or period) size.
-  snd_pcm_uframes_t period_size = *bufferSize;
-  err = snd_pcm_hw_params_set_period_size_near(handle, hw_params, &period_size, &dir);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: error setting period size (%s): %s.",
-            name, snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-  *bufferSize = period_size;
-
-  // 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 ) {
-    sprintf( message_, "RtApiAlsa: error setting buffer size for duplex stream on device (%s).",
-             name );
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  stream_.bufferSize = *bufferSize;
-
-  // Install the hardware configuration
-  err = snd_pcm_hw_params(handle, hw_params);
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtApiAlsa: error installing hardware configuration (%s): %s.",
-            name, snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-#if defined(__RTAUDIO_DEBUG__)
-  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( handle, sw_params );
-  snd_pcm_sw_params_set_start_threshold( handle, sw_params, *bufferSize );
-  snd_pcm_sw_params_set_stop_threshold( handle, sw_params, 0x7fffffff );
-  snd_pcm_sw_params_set_silence_threshold( handle, sw_params, 0 );
-  snd_pcm_sw_params_set_silence_size( handle, sw_params, INT_MAX );
-  err = snd_pcm_sw_params( handle, sw_params );
-  if (err < 0) {
-    snd_pcm_close(handle);
-    sprintf(message_, "RtAudio: ALSA error installing software configuration (%s): %s.",
-            name, snd_strerror(err));
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-#if defined(__RTAUDIO_DEBUG__)
-  fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");
-  snd_pcm_sw_params_dump(sw_params, out);
-#endif
-
-  // Allocate the ApiHandle if necessary and then save.
-  AlsaHandle *apiInfo = 0;
-  if ( stream_.apiHandle == 0 ) {
-    apiInfo = (AlsaHandle *) new AlsaHandle;
-    stream_.apiHandle = (void *) apiInfo;
-    apiInfo->handles[0] = 0;
-    apiInfo->handles[1] = 0;
-  }
-  else {
-    apiInfo = (AlsaHandle *) stream_.apiHandle;
-  }
-  apiInfo->handles[mode] = handle;
-
-  // 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_.nUserChannels[mode] > 1 && stream_.deInterleave[mode])
-    stream_.doConvertBuffer[mode] = true;
-
-  // Allocate necessary internal buffers
-  if ( stream_.nUserChannels[0] != stream_.nUserChannels[1] ) {
-
-    long buffer_bytes;
-    if (stream_.nUserChannels[0] >= stream_.nUserChannels[1])
-      buffer_bytes = stream_.nUserChannels[0];
-    else
-      buffer_bytes = stream_.nUserChannels[1];
-
-    buffer_bytes *= *bufferSize * formatBytes(stream_.userFormat);
-    if (stream_.userBuffer) free(stream_.userBuffer);
-    if (apiInfo->tempBuffer) free(apiInfo->tempBuffer);
-    stream_.userBuffer = (char *) calloc(buffer_bytes, 1);
-    apiInfo->tempBuffer = (char *) calloc(buffer_bytes, 1);
-    if ( stream_.userBuffer == NULL || apiInfo->tempBuffer == NULL ) {
-      sprintf(message_, "RtApiAlsa: error allocating user buffer memory (%s).",
-              devices_[device].name.c_str());
-      goto error;
-    }
-  }
-
-  if ( stream_.doConvertBuffer[mode] ) {
-
-    long buffer_bytes;
-    bool makeBuffer = true;
-    if ( mode == OUTPUT )
-      buffer_bytes = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-    else { // mode == INPUT
-      buffer_bytes = stream_.nDeviceChannels[1] * formatBytes(stream_.deviceFormat[1]);
-      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
-        long bytes_out = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-        if ( buffer_bytes < bytes_out ) makeBuffer = false;
-      }
-    }
-
-    if ( makeBuffer ) {
-      buffer_bytes *= *bufferSize;
-      if (stream_.deviceBuffer) free(stream_.deviceBuffer);
-      stream_.deviceBuffer = (char *) calloc(buffer_bytes, 1);
-      if (stream_.deviceBuffer == NULL) {
-        sprintf(message_, "RtApiAlsa: error allocating device buffer memory (%s).",
-                devices_[device].name.c_str());
-        goto error;
-      }
-    }
-  }
-
-  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;
-    // Link the streams if possible.
-    apiInfo->synchronized = false;
-    if (snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0)
-      apiInfo->synchronized = true;
-    else {
-      sprintf(message_, "RtApiAlsa: unable to synchronize input and output streams (%s).",
-              devices_[device].name.c_str());
-      error(RtError::DEBUG_WARNING);
-    }
-  }
-  else
-    stream_.mode = mode;
-  stream_.nBuffers = periods;
-  stream_.sampleRate = sampleRate;
-
-  // Setup the buffer conversion information structure.
-  if ( stream_.doConvertBuffer[mode] ) {
-    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];
-    }
-
-    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 ( mode == INPUT && stream_.deInterleave[1] ) {
-      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 if (mode == OUTPUT && stream_.deInterleave[0]) {
-      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_.convertInfo[mode].outOffset.push_back( k );
-      }
-    }
-  }
-
-  return SUCCESS;
-
- error:
-  if (apiInfo) {
-    if (apiInfo->handles[0])
-      snd_pcm_close(apiInfo->handles[0]);
-    if (apiInfo->handles[1])
-      snd_pcm_close(apiInfo->handles[1]);
-    if ( apiInfo->tempBuffer ) free(apiInfo->tempBuffer);
-    delete apiInfo;
-    stream_.apiHandle = 0;
-  }
-
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  error(RtError::DEBUG_WARNING);
-  return FAILURE;
-}
-
-void RtApiAlsa :: closeStream()
-{
-  // We don't want an exception to be thrown here because this
-  // function is called by our class destructor.  So, do our own
-  // stream check.
-  if ( stream_.mode == UNINITIALIZED ) {
-    sprintf(message_, "RtApiAlsa::closeStream(): no open stream to close!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
-  if (stream_.state == STREAM_RUNNING) {
-    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]);
-    stream_.state = STREAM_STOPPED;
-  }
-
-  if (stream_.callbackInfo.usingCallback) {
-    stream_.callbackInfo.usingCallback = false;
-    pthread_join(stream_.callbackInfo.thread, NULL);
-  }
-
-  if (apiInfo) {
-    if (apiInfo->handles[0]) snd_pcm_close(apiInfo->handles[0]);
-    if (apiInfo->handles[1]) snd_pcm_close(apiInfo->handles[1]);
-    free(apiInfo->tempBuffer);
-    delete apiInfo;
-    stream_.apiHandle = 0;
-  }
-
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  if (stream_.deviceBuffer) {
-    free(stream_.deviceBuffer);
-    stream_.deviceBuffer = 0;
-  }
-
-  stream_.mode = UNINITIALIZED;
-}
-
-// Pump a bunch of zeros into the output buffer.  This is needed only when we
-// are doing duplex operations.
-bool RtApiAlsa :: primeOutputBuffer()
-{
-  int err;
-  char *buffer;
-  int channels;
-  snd_pcm_t **handle;
-  RtAudioFormat format;
-  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
-  handle = (snd_pcm_t **) apiInfo->handles;
-  
-  if (stream_.mode == DUPLEX) {
-
-    // Setup parameters and do buffer conversion if necessary.
-    if ( stream_.doConvertBuffer[0] ) {
-      convertBuffer( stream_.deviceBuffer, apiInfo->tempBuffer, stream_.convertInfo[0] );
-      channels = stream_.nDeviceChannels[0];
-      format = stream_.deviceFormat[0];
-    }
-    else {
-      channels = stream_.nUserChannels[0];
-      format = stream_.userFormat;
-    }
-
-    buffer = new char[stream_.bufferSize * formatBytes(format) * channels];
-    bzero(buffer, stream_.bufferSize * formatBytes(format) * channels);
-    
-    for (int i=0; i<stream_.nBuffers; i++) {
-      // Write samples to device in interleaved/non-interleaved format.
-      if (stream_.deInterleave[0]) {
-        void *bufs[channels];
-        size_t offset = stream_.bufferSize * formatBytes(format);
-        for (int i=0; i<channels; i++)
-          bufs[i] = (void *) (buffer + (i * offset));
-        err = snd_pcm_writen(handle[0], bufs, stream_.bufferSize);
-      }
-      else
-        err = snd_pcm_writei(handle[0], buffer, stream_.bufferSize);
-  
-      if (err < stream_.bufferSize) {
-        // Either an error or underrun occured.
-        if (err == -EPIPE) {
-          snd_pcm_state_t state = snd_pcm_state(handle[0]);
-          if (state == SND_PCM_STATE_XRUN) {
-            sprintf(message_, "RtApiAlsa: underrun detected while priming output buffer.");
-            return false;
-          }
-          else {
-            sprintf(message_, "RtApiAlsa: primeOutputBuffer() error, current state is %s.",
-                    snd_pcm_state_name(state));
-            return false;
-          }
-        }
-        else {
-          sprintf(message_, "RtApiAlsa: audio write error for device (%s): %s.",
-                  devices_[stream_.device[0]].name.c_str(), snd_strerror(err));
-          return false;
-        }
-      }
-    }
-  }
-
-  return true;
-}
-
-void RtApiAlsa :: startStream()
-{
-  // This method calls snd_pcm_prepare if the device isn't already in that state.
-
-  verifyStream();
-  if (stream_.state == STREAM_RUNNING) return;
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  int err;
-  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) {
-      err = snd_pcm_prepare(handle[0]);
-      if (err < 0) {
-        sprintf(message_, "RtApiAlsa: error preparing pcm device (%s): %s.",
-                devices_[stream_.device[0]].name.c_str(), snd_strerror(err));
-        MUTEX_UNLOCK(&stream_.mutex);
-        error(RtError::DRIVER_ERROR);
-      }
-      // Reprime output buffer if needed
-      if ( (stream_.mode == DUPLEX) && ( !primeOutputBuffer() ) ) {
-        MUTEX_UNLOCK(&stream_.mutex);
-        error(RtError::DRIVER_ERROR);
-      }
-    }
-  }
-
-  if ( (stream_.mode == INPUT || stream_.mode == DUPLEX) && !apiInfo->synchronized ) {
-    state = snd_pcm_state(handle[1]);
-    if (state != SND_PCM_STATE_PREPARED) {
-      err = snd_pcm_prepare(handle[1]);
-      if (err < 0) {
-        sprintf(message_, "RtApiAlsa: error preparing pcm device (%s): %s.",
-                devices_[stream_.device[1]].name.c_str(), snd_strerror(err));
-        MUTEX_UNLOCK(&stream_.mutex);
-        error(RtError::DRIVER_ERROR);
-      }
-    }
-  }
-
-  if ( (stream_.mode == DUPLEX) && ( !primeOutputBuffer() ) ) {
-    MUTEX_UNLOCK(&stream_.mutex);
-    error(RtError::DRIVER_ERROR);
-  }
-  stream_.state = STREAM_RUNNING;
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiAlsa :: stopStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_STOPPED) return;
-
-  // Change the state before the lock to improve shutdown response
-  // when using a callback.
-  stream_.state = STREAM_STOPPED;
-  MUTEX_LOCK(&stream_.mutex);
-
-  int err;
-  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
-  snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-    err = snd_pcm_drain(handle[0]);
-    if (err < 0) {
-      sprintf(message_, "RtApiAlsa: error draining pcm device (%s): %s.",
-              devices_[stream_.device[0]].name.c_str(), snd_strerror(err));
-      MUTEX_UNLOCK(&stream_.mutex);
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  if ( (stream_.mode == INPUT || stream_.mode == DUPLEX) && !apiInfo->synchronized ) {
-    err = snd_pcm_drain(handle[1]);
-    if (err < 0) {
-      sprintf(message_, "RtApiAlsa: error draining pcm device (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), snd_strerror(err));
-      MUTEX_UNLOCK(&stream_.mutex);
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiAlsa :: abortStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_STOPPED) return;
-
-  // Change the state before the lock to improve shutdown response
-  // when using a callback.
-  stream_.state = STREAM_STOPPED;
-  MUTEX_LOCK(&stream_.mutex);
-
-  int err;
-  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
-  snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-    err = snd_pcm_drop(handle[0]);
-    if (err < 0) {
-      sprintf(message_, "RtApiAlsa: error draining pcm device (%s): %s.",
-              devices_[stream_.device[0]].name.c_str(), snd_strerror(err));
-      MUTEX_UNLOCK(&stream_.mutex);
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  if ( (stream_.mode == INPUT || stream_.mode == DUPLEX) && !apiInfo->synchronized ) {
-    err = snd_pcm_drop(handle[1]);
-    if (err < 0) {
-      sprintf(message_, "RtApiAlsa: error draining pcm device (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), snd_strerror(err));
-      MUTEX_UNLOCK(&stream_.mutex);
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-int RtApiAlsa :: streamWillBlock()
-{
-  verifyStream();
-  if (stream_.state == STREAM_STOPPED) return 0;
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  int err = 0, frames = 0;
-  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;
-  snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-    err = snd_pcm_avail_update(handle[0]);
-    if (err < 0) {
-      sprintf(message_, "RtApiAlsa: error getting available frames for device (%s): %s.",
-              devices_[stream_.device[0]].name.c_str(), snd_strerror(err));
-      MUTEX_UNLOCK(&stream_.mutex);
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  frames = err;
-
-  if (stream_.mode == INPUT || stream_.mode == DUPLEX) {
-    err = snd_pcm_avail_update(handle[1]);
-    if (err < 0) {
-      sprintf(message_, "RtApiAlsa: error getting available frames for device (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), snd_strerror(err));
-      MUTEX_UNLOCK(&stream_.mutex);
-      error(RtError::DRIVER_ERROR);
-    }
-    if (frames > err) frames = err;
-  }
-
-  frames = stream_.bufferSize - frames;
-  if (frames < 0) frames = 0;
-
-  MUTEX_UNLOCK(&stream_.mutex);
-  return frames;
-}
-
-void RtApiAlsa :: tickStream()
-{
-  verifyStream();
-
-  int stopStream = 0;
-  if (stream_.state == STREAM_STOPPED) {
-    if (stream_.callbackInfo.usingCallback) usleep(50000); // sleep 50 milliseconds
-    return;
-  }
-  else if (stream_.callbackInfo.usingCallback) {
-    RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
-    stopStream = callback(stream_.userBuffer, stream_.bufferSize, stream_.callbackInfo.userData);
-  }
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  // The state might change while waiting on a mutex.
-  if (stream_.state == STREAM_STOPPED)
-    goto unlock;
-
-  int err;
-  char *buffer;
-  int channels;
-  AlsaHandle *apiInfo;
-  snd_pcm_t **handle;
-  RtAudioFormat format;
-  apiInfo = (AlsaHandle *) stream_.apiHandle;
-  handle = (snd_pcm_t **) apiInfo->handles;
-
-  if ( stream_.mode == DUPLEX ) {
-    // In duplex mode, we need to make the snd_pcm_read call before
-    // the snd_pcm_write call in order to avoid under/over runs.  So,
-    // copy the userData to our temporary buffer.
-    int bufferBytes;
-    bufferBytes = stream_.bufferSize * stream_.nUserChannels[0] * formatBytes(stream_.userFormat);
-    memcpy( apiInfo->tempBuffer, stream_.userBuffer, bufferBytes );
-  }
-
-  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;
-      channels = stream_.nUserChannels[1];
-      format = stream_.userFormat;
-    }
-
-    // Read samples from device in interleaved/non-interleaved format.
-    if (stream_.deInterleave[1]) {
-      void *bufs[channels];
-      size_t offset = stream_.bufferSize * formatBytes(format);
-      for (int i=0; i<channels; i++)
-        bufs[i] = (void *) (buffer + (i * offset));
-      err = snd_pcm_readn(handle[1], bufs, stream_.bufferSize);
-    }
-    else
-      err = snd_pcm_readi(handle[1], buffer, stream_.bufferSize);
-
-    if (err < stream_.bufferSize) {
-      // Either an error or underrun occured.
-      if (err == -EPIPE) {
-        snd_pcm_state_t state = snd_pcm_state(handle[1]);
-        if (state == SND_PCM_STATE_XRUN) {
-          sprintf(message_, "RtApiAlsa: overrun detected.");
-          error(RtError::WARNING);
-          err = snd_pcm_prepare(handle[1]);
-          if (err < 0) {
-            sprintf(message_, "RtApiAlsa: error preparing handle after overrun: %s.",
-                    snd_strerror(err));
-            MUTEX_UNLOCK(&stream_.mutex);
-            error(RtError::DRIVER_ERROR);
-          }
-          // Reprime output buffer if needed.
-          if ( (stream_.mode == DUPLEX) && ( !primeOutputBuffer() ) ) {
-            MUTEX_UNLOCK(&stream_.mutex);
-            error(RtError::DRIVER_ERROR);
-          }
-        }
-        else {
-          sprintf(message_, "RtApiAlsa: tickStream() error, current state is %s.",
-                  snd_pcm_state_name(state));
-          MUTEX_UNLOCK(&stream_.mutex);
-          error(RtError::DRIVER_ERROR);
-        }
-        goto unlock;
-      }
-      else {
-        sprintf(message_, "RtApiAlsa: audio read error for device (%s): %s.",
-                devices_[stream_.device[1]].name.c_str(), snd_strerror(err));
-        MUTEX_UNLOCK(&stream_.mutex);
-        error(RtError::DRIVER_ERROR);
-      }
-    }
-
-    // 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, stream_.deviceBuffer, stream_.convertInfo[1] );
-  }
-
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-
-    // Setup parameters and do buffer conversion if necessary.
-    if (stream_.doConvertBuffer[0]) {
-      buffer = stream_.deviceBuffer;
-      if ( stream_.mode == DUPLEX )
-        convertBuffer( buffer, apiInfo->tempBuffer, stream_.convertInfo[0] );
-      else
-        convertBuffer( buffer, stream_.userBuffer, stream_.convertInfo[0] );
-      channels = stream_.nDeviceChannels[0];
-      format = stream_.deviceFormat[0];
-    }
-    else {
-      if ( stream_.mode == DUPLEX )
-        buffer = apiInfo->tempBuffer;
-      else
-        buffer = stream_.userBuffer;
-      channels = stream_.nUserChannels[0];
-      format = stream_.userFormat;
-    }
-
-    // Do byte swapping if necessary.
-    if (stream_.doByteSwap[0])
-      byteSwapBuffer(buffer, stream_.bufferSize * channels, format);
-
-    // Write samples to device in interleaved/non-interleaved format.
-    if (stream_.deInterleave[0]) {
-      void *bufs[channels];
-      size_t offset = stream_.bufferSize * formatBytes(format);
-      for (int i=0; i<channels; i++)
-        bufs[i] = (void *) (buffer + (i * offset));
-      err = snd_pcm_writen(handle[0], bufs, stream_.bufferSize);
-    }
-    else
-      err = snd_pcm_writei(handle[0], buffer, stream_.bufferSize);
-
-    if (err < stream_.bufferSize) {
-      // Either an error or underrun occured.
-      if (err == -EPIPE) {
-        snd_pcm_state_t state = snd_pcm_state(handle[0]);
-        if (state == SND_PCM_STATE_XRUN) {
-          sprintf(message_, "RtApiAlsa: underrun detected.");
-          error(RtError::WARNING);
-          err = snd_pcm_prepare(handle[0]);
-          if (err < 0) {
-            sprintf(message_, "RtApiAlsa: error preparing handle after underrun: %s.",
-                    snd_strerror(err));
-            MUTEX_UNLOCK(&stream_.mutex);
-            error(RtError::DRIVER_ERROR);
-          }
-        }
-        else {
-          sprintf(message_, "RtApiAlsa: tickStream() error, current state is %s.",
-                  snd_pcm_state_name(state));
-          MUTEX_UNLOCK(&stream_.mutex);
-          error(RtError::DRIVER_ERROR);
-        }
-        goto unlock;
-      }
-      else {
-        sprintf(message_, "RtApiAlsa: audio write error for device (%s): %s.",
-                devices_[stream_.device[0]].name.c_str(), snd_strerror(err));
-        MUTEX_UNLOCK(&stream_.mutex);
-        error(RtError::DRIVER_ERROR);
-      }
-    }
-  }
-
- unlock:
-  MUTEX_UNLOCK(&stream_.mutex);
-
-  if (stream_.callbackInfo.usingCallback && stopStream)
-    this->stopStream();
-}
-
-void RtApiAlsa :: setStreamCallback(RtAudioCallback callback, void *userData)
-{
-  verifyStream();
-
-  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
-  if ( info->usingCallback ) {
-    sprintf(message_, "RtApiAlsa: A callback is already set for this stream!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  info->callback = (void *) callback;
-  info->userData = userData;
-  info->usingCallback = true;
-  info->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);
-  pthread_attr_setschedpolicy(&attr, SCHED_RR);
-
-  int err = pthread_create(&info->thread, &attr, alsaCallbackHandler, &stream_.callbackInfo);
-  pthread_attr_destroy(&attr);
-  if (err) {
-    info->usingCallback = false;
-    sprintf(message_, "RtApiAlsa: error starting callback thread!");
-    error(RtError::THREAD_ERROR);
-  }
-}
-
-void RtApiAlsa :: cancelStreamCallback()
-{
-  verifyStream();
-
-  if (stream_.callbackInfo.usingCallback) {
-
-    if (stream_.state == STREAM_RUNNING)
-      stopStream();
-
-    MUTEX_LOCK(&stream_.mutex);
-
-    stream_.callbackInfo.usingCallback = false;
-    pthread_join(stream_.callbackInfo.thread, NULL);
-    stream_.callbackInfo.thread = 0;
-    stream_.callbackInfo.callback = NULL;
-    stream_.callbackInfo.userData = NULL;
-
-    MUTEX_UNLOCK(&stream_.mutex);
-  }
-}
-
-extern "C" void *alsaCallbackHandler(void *ptr)
-{
-  CallbackInfo *info = (CallbackInfo *) ptr;
-  RtApiAlsa *object = (RtApiAlsa *) info->object;
-  bool *usingCallback = &info->usingCallback;
-
-  while ( *usingCallback ) {
-    try {
-      object->tickStream();
-    }
-    catch (RtError &exception) {
-      fprintf(stderr, "\nRtApiAlsa: callback thread error (%s) ... closing thread.\n\n",
-              exception.getMessageString());
-      break;
-    }
-  }
-
-  pthread_exit(NULL);
-}
-
-//******************** End of __LINUX_ALSA__ *********************//
-#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.
-
-#include "asio/asiosys.h"
-#include "asio/asio.h"
-#include "asio/iasiothiscallresolver.h"
-#include "asio/asiodrivers.h"
-#include <math.h>
-
-AsioDrivers drivers;
-ASIOCallbacks asioCallbacks;
-ASIODriverInfo driverInfo;
-CallbackInfo *asioCallbackInfo;
-
-struct AsioHandle {
-  bool stopStream;
-  ASIOBufferInfo *bufferInfos;
-  HANDLE condition;
-
-  AsioHandle()
-    :stopStream(false), bufferInfos(0) {}
-};
-
-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.";
-}
-
-RtApiAsio :: RtApiAsio()
-{
-  this->coInitialized = false;
-  this->initialize();
-
-  if (nDevices_ <= 0) {
-    sprintf(message_, "RtApiAsio: no Windows ASIO audio drivers found!");
-    error(RtError::NO_DEVICES_FOUND);
-  }
-}
-
-RtApiAsio :: ~RtApiAsio()
-{
-  if ( stream_.mode != UNINITIALIZED ) closeStream();
-
-  if ( coInitialized )
-    CoUninitialize();
-}
-
-void RtApiAsio :: initialize(void)
-{
-
-  // 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) ) {
-    sprintf(message_,"RtApiAsio: ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)");
-  }
-  coInitialized = true;
-
-  nDevices_ = drivers.asioGetNumDev();
-  if (nDevices_ <= 0) return;
-
-  // Create device structures and write device driver names to each.
-  RtApiDevice device;
-  char name[128];
-  for (int i=0; i<nDevices_; i++) {
-    if ( drivers.asioGetDriverName( i, name, 128 ) == 0 ) {
-      device.name.erase();
-      device.name.append( (const char *)name, strlen(name)+1);
-      devices_.push_back(device);
-    }
-    else {
-      sprintf(message_, "RtApiAsio: error getting driver name for device index %d!", i);
-      error(RtError::WARNING);
-    }
-  }
-
-  nDevices_ = (int) devices_.size();
-
-  drivers.removeCurrentDriver();
-  driverInfo.asioVersion = 2;
-  // See note in DirectSound implementation about GetDesktopWindow().
-  driverInfo.sysRef = GetForegroundWindow();
-}
-
-void RtApiAsio :: probeDeviceInfo(RtApiDevice *info)
-{
-  // Don't probe if a stream is already open.
-  if ( stream_.mode != UNINITIALIZED ) {
-    sprintf(message_, "RtApiAsio: unable to probe driver while a stream is open.");
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  if ( !drivers.loadDriver( (char *)info->name.c_str() ) ) {
-    sprintf(message_, "RtApiAsio: error loading driver (%s).", info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  ASIOError result = ASIOInit( &driverInfo );
-  if ( result != ASE_OK ) {
-    sprintf(message_, "RtApiAsio: error (%s) initializing driver (%s).", 
-      GetAsioErrorString(result), info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // Determine the device channel information.
-  long inputChannels, outputChannels;
-  result = ASIOGetChannels( &inputChannels, &outputChannels );
-  if ( result != ASE_OK ) {
-    drivers.removeCurrentDriver();
-    sprintf(message_, "RtApiAsio: error (%s) getting input/output channel count (%s).", 
-      GetAsioErrorString(result), 
-      info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  info->maxOutputChannels = outputChannels;
-  if ( outputChannels > 0 ) info->minOutputChannels = 1;
-
-  info->maxInputChannels = inputChannels;
-  if ( inputChannels > 0 ) info->minInputChannels = 1;
-
-  // If device opens for both playback and capture, we determine the channels.
-  if (info->maxOutputChannels > 0 && info->maxInputChannels > 0) {
-    info->hasDuplexSupport = true;
-    info->maxDuplexChannels = (info->maxOutputChannels > info->maxInputChannels) ?
-      info->maxInputChannels : info->maxOutputChannels;
-    info->minDuplexChannels = (info->minOutputChannels > info->minInputChannels) ?
-      info->minInputChannels : info->minOutputChannels;
-  }
-
-  // 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 (info->sampleRates.size() == 0) {
-    drivers.removeCurrentDriver();
-    sprintf( message_, "RtApiAsio: No supported sample rates found for driver (%s).", info->name.c_str() );
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // Determine supported data types ... just check first channel and assume rest are the same.
-  ASIOChannelInfo channelInfo;
-  channelInfo.channel = 0;
-  channelInfo.isInput = true;
-  if ( info->maxInputChannels <= 0 ) channelInfo.isInput = false;
-  result = ASIOGetChannelInfo( &channelInfo );
-  if ( result != ASE_OK ) {
-    drivers.removeCurrentDriver();
-    sprintf(message_, "RtApiAsio: error (%s) getting driver (%s) channel information.", 
-      GetAsioErrorString(result), 
-      info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  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;
-
-       // Check that we have at least one supported format.
-  if (info->nativeFormats == 0) {
-    drivers.removeCurrentDriver();
-    sprintf(message_, "RtApiAsio: driver (%s) data format not supported by RtAudio.",
-            info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  info->probed = true;
-  drivers.removeCurrentDriver();
-}
-
-void bufferSwitch(long index, ASIOBool processNow)
-{
-  RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object;
-  try {
-    object->callbackEvent( index );
-  }
-  catch (RtError &exception) {
-    fprintf(stderr, "\nRtApiAsio: callback handler error (%s)!\n\n", exception.getMessageString());
-    return;
-  }
-
-  return;
-}
-
-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.
-
-  RtAudio *object = (RtAudio *) asioCallbackInfo->object;
-  try {
-    object->stopStream();
-  }
-  catch (RtError &exception) {
-    fprintf(stderr, "\nRtApiAsio: sampleRateChanged() error (%s)!\n\n", exception.getMessageString());
-    return;
-  }
-
-  fprintf(stderr, "\nRtApiAsio: driver reports sample rate changed to %d ... stream stopped!!!", (int) sRate);
-}
-
-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.
-    fprintf(stderr, "\nRtApiAsio: driver reset requested!!!");
-    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.
-    fprintf(stderr, "\nRtApiAsio: driver resync requested!!!");
-    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.
-    fprintf(stderr, "\nRtApiAsio: driver latency may have changed!!!");
-    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 wether 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;
-}
-
-bool RtApiAsio :: probeDeviceOpen(int device, StreamMode mode, int channels, 
-                                  int sampleRate, RtAudioFormat format,
-                                  int *bufferSize, int numberOfBuffers)
-{
-  // For ASIO, a duplex stream MUST use the same driver.
-  if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] != device ) {
-    sprintf(message_, "RtApiAsio: duplex stream must use the same device for input and output.");
-    error(RtError::WARNING);
-    return FAILURE;
-  }
-
-  // Only load the driver once for duplex stream.
-  ASIOError result;
-  if ( mode != INPUT || stream_.mode != OUTPUT ) {
-    if ( !drivers.loadDriver( (char *)devices_[device].name.c_str() ) ) {
-      sprintf(message_, "RtApiAsio: error loading driver (%s).", 
-        devices_[device].name.c_str());
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    result = ASIOInit( &driverInfo );
-    if ( result != ASE_OK ) {
-      sprintf(message_, "RtApiAsio: error (%s) initializing driver (%s).", 
-        GetAsioErrorString(result), devices_[device].name.c_str());
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-  }
-
-  // Check the device channel count.
-  long inputChannels, outputChannels;
-  result = ASIOGetChannels( &inputChannels, &outputChannels );
-  if ( result != ASE_OK ) {
-    drivers.removeCurrentDriver();
-    sprintf(message_, "RtApiAsio: error (%s) getting input/output channel count (%s).",
-      GetAsioErrorString(result), 
-      devices_[device].name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  if ( ( mode == OUTPUT && channels > outputChannels) ||
-       ( mode == INPUT && channels > inputChannels) ) {
-    drivers.removeCurrentDriver();
-    sprintf(message_, "RtApiAsio: driver (%s) does not support requested channel count (%d).",
-            devices_[device].name.c_str(), channels);
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-  stream_.nDeviceChannels[mode] = channels;
-  stream_.nUserChannels[mode] = channels;
-
-  // Verify the sample rate is supported.
-  result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );
-  if ( result != ASE_OK ) {
-    drivers.removeCurrentDriver();
-    sprintf(message_, "RtApiAsio: driver (%s) does not support requested sample rate (%d).",
-            devices_[device].name.c_str(), sampleRate);
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  // Set the sample rate.
-  result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );
-  if ( result != ASE_OK ) {
-    drivers.removeCurrentDriver();
-    sprintf(message_, "RtApiAsio: driver (%s) error setting sample rate (%d).",
-            devices_[device].name.c_str(), sampleRate);
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  // 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();
-    sprintf(message_, "RtApiAsio: driver (%s) error getting data format.",
-            devices_[device].name.c_str());
-    error(RtError::DEBUG_WARNING);
-    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();
-    sprintf(message_, "RtApiAsio: driver (%s) data format not supported by RtAudio.",
-            devices_[device].name.c_str());
-    error(RtError::DEBUG_WARNING);
-    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();
-    sprintf(message_, "RtApiAsio: error (%s) on driver (%s) error getting buffer size.",
-        GetAsioErrorString(result), 
-        devices_[device].name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  if ( *bufferSize < minSize ) *bufferSize = minSize;
-  else if ( *bufferSize > maxSize ) *bufferSize = maxSize;
-  else if ( granularity == -1 ) {
-    // Make sure bufferSize is a power of two.
-    double power = log10( (double) *bufferSize ) / log10( 2.0 );
-    *bufferSize = (int) pow( 2.0, floor(power+0.5) );
-    if ( *bufferSize < minSize ) *bufferSize = minSize;
-    else if ( *bufferSize > maxSize ) *bufferSize = maxSize;
-    else *bufferSize = preferSize;
-  } else if (granularity != 0)
-  {
-    // to an even multiple of granularity, rounding up.
-    *bufferSize = (*bufferSize + granularity-1)/granularity*granularity;
-  }
-
-
-
-  if ( mode == INPUT && stream_.mode == OUTPUT && stream_.bufferSize != *bufferSize )
-    std::cerr << "Possible input/output buffersize discrepancy!" << std::endl;
-
-  stream_.bufferSize = *bufferSize;
-  stream_.nBuffers = 2;
-
-  // ASIO always uses deinterleaved channels.
-  stream_.deInterleave[mode] = true;
-
-  // Allocate, if necessary, our AsioHandle structure for the stream.
-  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
-  if ( handle == 0 ) {
-    handle = (AsioHandle *) calloc(1, sizeof(AsioHandle));
-    if ( handle == NULL ) {
-      drivers.removeCurrentDriver();
-      sprintf(message_, "RtApiAsio: error allocating AsioHandle memory (%s).",
-              devices_[device].name.c_str());
-      error(RtError::DEBUG_WARNING);
-      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.
-  if ( mode == INPUT && stream_.mode == OUTPUT ) {
-    ASIODisposeBuffers();
-    if ( handle->bufferInfos ) free( handle->bufferInfos );
-  }
-
-  // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.
-  int i, nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
-  handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );
-  if (handle->bufferInfos == NULL) {
-    sprintf(message_, "RtApiAsio: error allocating bufferInfo memory (%s).",
-            devices_[device].name.c_str());
-    goto error;
-  }
-  ASIOBufferInfo *infos;
-  infos = handle->bufferInfos;
-  for ( i=0; i<stream_.nDeviceChannels[0]; i++, infos++ ) {
-    infos->isInput = ASIOFalse;
-    infos->channelNum = i;
-    infos->buffers[0] = infos->buffers[1] = 0;
-  }
-  for ( i=0; i<stream_.nDeviceChannels[1]; i++, infos++ ) {
-    infos->isInput = ASIOTrue;
-    infos->channelNum = i;
-    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 ) {
-    sprintf(message_, "RtApiAsio: eror (%s) on driver (%s) error creating buffers.",
-      GetAsioErrorString(result), 
-      devices_[device].name.c_str());
-    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_.nUserChannels[mode] > 1 && stream_.deInterleave[mode])
-    stream_.doConvertBuffer[mode] = true;
-
-  // Allocate necessary internal buffers
-  if ( stream_.nUserChannels[0] != stream_.nUserChannels[1] ) {
-
-    long buffer_bytes;
-    if (stream_.nUserChannels[0] >= stream_.nUserChannels[1])
-      buffer_bytes = stream_.nUserChannels[0];
-    else
-      buffer_bytes = stream_.nUserChannels[1];
-
-    buffer_bytes *= *bufferSize * formatBytes(stream_.userFormat);
-    if (stream_.userBuffer) free(stream_.userBuffer);
-    stream_.userBuffer = (char *) calloc(buffer_bytes, 1);
-    if (stream_.userBuffer == NULL) {
-      sprintf(message_, "RtApiAsio: error (%s) allocating user buffer memory (%s).",
-        GetAsioErrorString(result), 
-        devices_[device].name.c_str());
-      goto error;
-    }
-  }
-
-  if ( stream_.doConvertBuffer[mode] ) {
-
-    long buffer_bytes;
-    bool makeBuffer = true;
-    if ( mode == OUTPUT )
-      buffer_bytes = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-    else { // mode == INPUT
-      buffer_bytes = stream_.nDeviceChannels[1] * formatBytes(stream_.deviceFormat[1]);
-      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
-        long bytes_out = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-        if ( buffer_bytes < bytes_out ) makeBuffer = false;
-      }
-    }
-
-    if ( makeBuffer ) {
-      buffer_bytes *= *bufferSize;
-      if (stream_.deviceBuffer) free(stream_.deviceBuffer);
-      stream_.deviceBuffer = (char *) calloc(buffer_bytes, 1);
-      if (stream_.deviceBuffer == NULL) {
-        sprintf(message_, "RtApiAsio: error (%s) allocating device buffer memory (%s).",
-          GetAsioErrorString(result), 
-                devices_[device].name.c_str());
-        goto error;
-      }
-    }
-  }
-
-  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_.sampleRate = sampleRate;
-  asioCallbackInfo = &stream_.callbackInfo;
-  stream_.callbackInfo.object = (void *) this;
-
-  // Setup the buffer conversion information structure.
-  if ( stream_.doConvertBuffer[mode] ) {
-    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];
-    }
-
-    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 ( mode == INPUT && stream_.deInterleave[1] ) {
-      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 if (mode == OUTPUT && stream_.deInterleave[0]) {
-      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_.convertInfo[mode].outOffset.push_back( k );
-      }
-    }
-  }
-
-  return SUCCESS;
-
- error:
-  ASIODisposeBuffers();
-  drivers.removeCurrentDriver();
-
-  if ( handle ) {
-    CloseHandle( handle->condition );
-    if ( handle->bufferInfos )
-      free( handle->bufferInfos );
-    free( handle );
-    stream_.apiHandle = 0;
-  }
-
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  error(RtError::DEBUG_WARNING);
-  return FAILURE;
-}
-
-void RtApiAsio :: closeStream()
-{
-  // We don't want an exception to be thrown here because this
-  // function is called by our class destructor.  So, do our own
-  // streamId check.
-  if ( stream_.mode == UNINITIALIZED ) {
-    sprintf(message_, "RtApiAsio::closeStream(): no open stream to close!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  if (stream_.state == STREAM_RUNNING)
-    ASIOStop();
-
-  ASIODisposeBuffers();
-  drivers.removeCurrentDriver();
-
-  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
-  if ( handle ) {
-    CloseHandle( handle->condition );
-    if ( handle->bufferInfos )
-      free( handle->bufferInfos );
-    free( handle );
-    stream_.apiHandle = 0;
-  }
-
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  if (stream_.deviceBuffer) {
-    free(stream_.deviceBuffer);
-    stream_.deviceBuffer = 0;
-  }
-
-  stream_.mode = UNINITIALIZED;
-}
-
-void RtApiAsio :: setStreamCallback(RtAudioCallback callback, void *userData)
-{
-  verifyStream();
-
-  if ( stream_.callbackInfo.usingCallback ) {
-    sprintf(message_, "RtApiAsio: A callback is already set for this stream!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  stream_.callbackInfo.callback = (void *) callback;
-  stream_.callbackInfo.userData = userData;
-  stream_.callbackInfo.usingCallback = true;
-}
-
-void RtApiAsio :: cancelStreamCallback()
-{
-  verifyStream();
-
-  if (stream_.callbackInfo.usingCallback) {
-
-    if (stream_.state == STREAM_RUNNING)
-      stopStream();
-
-    MUTEX_LOCK(&stream_.mutex);
-
-    stream_.callbackInfo.usingCallback = false;
-    stream_.callbackInfo.userData = NULL;
-    stream_.state = STREAM_STOPPED;
-    stream_.callbackInfo.callback = NULL;
-
-    MUTEX_UNLOCK(&stream_.mutex);
-  }
-}
-
-void RtApiAsio :: startStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_RUNNING) return;
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  ASIOError result = ASIOStart();
-  if ( result != ASE_OK ) {
-    sprintf(message_, "RtApiAsio: error starting device (%s).",
-              devices_[stream_.device[0]].name.c_str());
-    MUTEX_UNLOCK(&stream_.mutex);
-    error(RtError::DRIVER_ERROR);
-  }
-  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
-  handle->stopStream = false;
-  stream_.state = STREAM_RUNNING;
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiAsio :: stopStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_STOPPED) return;
-
-  // Change the state before the lock to improve shutdown response
-  // when using a callback.
-  stream_.state = STREAM_STOPPED;
-  MUTEX_LOCK(&stream_.mutex);
-
-  ASIOError result = ASIOStop();
-  if ( result != ASE_OK ) {
-    sprintf(message_, "RtApiAsio: error stopping device (%s).",
-              devices_[stream_.device[0]].name.c_str());
-    MUTEX_UNLOCK(&stream_.mutex);
-    error(RtError::DRIVER_ERROR);
-  }
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiAsio :: abortStream()
-{
-  stopStream();
-}
-
-void RtApiAsio :: tickStream()
-{
-  verifyStream();
-
-  if (stream_.state == STREAM_STOPPED)
-    return;
-
-  if (stream_.callbackInfo.usingCallback) {
-    sprintf(message_, "RtApiAsio: tickStream() should not be used when a callback function is set!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  // Release the stream_mutex here and wait for the event
-  // to become signaled by the callback process.
-  MUTEX_UNLOCK(&stream_.mutex);
-  WaitForMultipleObjects(1, &handle->condition, FALSE, INFINITE);
-  ResetEvent( handle->condition );
-}
-
-void RtApiAsio :: callbackEvent(long bufferIndex)
-{
-  verifyStream();
-
-  if (stream_.state == STREAM_STOPPED) return;
-
-  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
-  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;
-  if ( info->usingCallback && handle->stopStream ) {
-    // Check if the stream should be stopped (via the previous user
-    // callback return value).  We stop the stream here, rather than
-    // after the function call, so that output data can first be
-    // processed.
-    this->stopStream();
-    return;
-  }
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  // Invoke user callback first, to get fresh output data.
-  if ( info->usingCallback ) {
-    RtAudioCallback callback = (RtAudioCallback) info->callback;
-    if ( callback(stream_.userBuffer, stream_.bufferSize, info->userData) )
-      handle->stopStream = true;
-  }
-
-  int bufferBytes, j;
-  int nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];
-  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {
-
-    bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[0]);
-    if (stream_.doConvertBuffer[0]) {
-
-      convertBuffer( stream_.deviceBuffer, stream_.userBuffer, stream_.convertInfo[0] );
-      if ( stream_.doByteSwap[0] )
-        byteSwapBuffer(stream_.deviceBuffer,
-                       stream_.bufferSize * stream_.nDeviceChannels[0],
-                       stream_.deviceFormat[0]);
-
-      // Always de-interleave ASIO output data.
-      j = 0;
-      for ( int i=0; i<nChannels; i++ ) {
-        if ( handle->bufferInfos[i].isInput != ASIOTrue )
-          memcpy(handle->bufferInfos[i].buffers[bufferIndex],
-                 &stream_.deviceBuffer[j++*bufferBytes], bufferBytes );
-      }
-    }
-    else { // single channel only
-
-      if (stream_.doByteSwap[0])
-        byteSwapBuffer(stream_.userBuffer,
-                       stream_.bufferSize * stream_.nUserChannels[0],
-                       stream_.userFormat);
-
-      for ( int i=0; i<nChannels; i++ ) {
-        if ( handle->bufferInfos[i].isInput != ASIOTrue ) {
-          memcpy(handle->bufferInfos[i].buffers[bufferIndex], stream_.userBuffer, bufferBytes );
-          break;
-        }
-      }
-    }
-  }
-
-  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {
-
-    bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]);
-    if (stream_.doConvertBuffer[1]) {
-
-      // Always interleave ASIO input data.
-      j = 0;
-      for ( int i=0; i<nChannels; i++ ) {
-        if ( handle->bufferInfos[i].isInput == ASIOTrue )
-          memcpy(&stream_.deviceBuffer[j++*bufferBytes],
-                 handle->bufferInfos[i].buffers[bufferIndex],
-                 bufferBytes );
-      }
-
-      if ( stream_.doByteSwap[1] )
-        byteSwapBuffer(stream_.deviceBuffer,
-                       stream_.bufferSize * stream_.nDeviceChannels[1],
-                       stream_.deviceFormat[1]);
-      convertBuffer( stream_.userBuffer, stream_.deviceBuffer, stream_.convertInfo[1] );
-
-    }
-    else { // single channel only
-      for ( int i=0; i<nChannels; i++ ) {
-        if ( handle->bufferInfos[i].isInput == ASIOTrue ) {
-          memcpy(stream_.userBuffer,
-                 handle->bufferInfos[i].buffers[bufferIndex],
-                 bufferBytes );
-          break;
-        }
-      }
-
-      if (stream_.doByteSwap[1])
-        byteSwapBuffer(stream_.userBuffer,
-                       stream_.bufferSize * stream_.nUserChannels[1],
-                       stream_.userFormat);
-    }
-  }
-
-  if ( !info->usingCallback )
-    SetEvent( handle->condition );
-
-  // 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();
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-//******************** End of __WINDOWS_ASIO__ *********************//
-#endif
-
-#if defined(__WINDOWS_DS__) // Windows DirectSound API
-
-
-#include <dsound.h>
-#include <assert.h>
-
-#define MINIMUM_DEVICE_BUFFER_SIZE 32768
-
-
-#ifdef _MSC_VER // if Microsoft Visual C++
-#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 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;
-}
-
-#undef GENERATE_DEBUG_LOG // Define this to generate a debug timing log file in c:/rtaudiolog.txt"
-#ifdef GENERATE_DEBUG_LOG
-
-#include "mmsystem.h"
-#include "fstream"
-
-struct TTickRecord
-{
-  DWORD currentReadPointer, safeReadPointer;
-  DWORD currentWritePointer, safeWritePointer;
-  DWORD readTime, writeTime;
-  DWORD nextWritePointer, nextReadPointer;
-};
-
-int currentDebugLogEntry = 0;
-std::vector<TTickRecord> debugLog(2000);
-
-
-#endif
-
-// A structure to hold various information related to the DirectSound
-// API implementation.
-struct DsHandle {
-  void *object;
-  void *buffer;
-  UINT bufferPointer;  
-  DWORD dsBufferSize;
-  DWORD dsPointerLeadTime; // the number of bytes ahead of the safe pointer to lead by.
-};
-
-
-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)
-    s.latency += s.readDeviceSafeLeadBytes*1.0/s.inputFrameSize / s.sampleRate;
-
-  if (s.outputFrameSize != 0)
-    s.latency += (s.writeDeviceSafeLeadBytes+ s.writeDeviceBufferLeadBytes)*1.0/s.outputFrameSize / s.sampleRate;
-
-  return s;
-}
-
-// Declarations for utility functions, callbacks, and structures
-// specific to the DirectSound implementation.
-static bool CALLBACK deviceCountCallback(LPGUID lpguid,
-                                         LPCTSTR description,
-                                         LPCTSTR module,
-                                         LPVOID lpContext);
-
-static bool CALLBACK deviceInfoCallback(LPGUID lpguid,
-                                        LPCTSTR description,
-                                        LPCTSTR module,
-                                        LPVOID lpContext);
-
-static bool CALLBACK defaultDeviceCallback(LPGUID lpguid,
-                                           LPCTSTR description,
-                                           LPCTSTR module,
-                                           LPVOID lpContext);
-
-static bool CALLBACK deviceIdCallback(LPGUID lpguid,
-                                      LPCTSTR description,
-                                      LPCTSTR module,
-                                      LPVOID lpContext);
-
-static char* getErrorString(int code);
-
-extern "C" unsigned __stdcall callbackHandler(void *ptr);
-
-struct enum_info {
-  std::string name;
-  LPGUID id;
-  bool isInput;
-  bool isValid;
-};
-
-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;
-
-  this->initialize();
-
-  if (nDevices_ <= 0) {
-    sprintf(message_, "RtApiDs: no Windows DirectSound audio devices found!");
-    error(RtError::NO_DEVICES_FOUND);
- }
-}
-
-RtApiDs :: ~RtApiDs()
-{
-  if (coInitialized)
-    CoUninitialize(); // balanced call.
-
-  if ( stream_.mode != UNINITIALIZED ) closeStream();
-}
-
-int RtApiDs :: getDefaultInputDevice(void)
-{
-  enum_info info;
-
-  // Enumerate through devices to find the default output.
-  HRESULT result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)defaultDeviceCallback, &info);
-  if ( FAILED(result) ) {
-    sprintf(message_, "RtApiDs: Error performing default input device enumeration: %s.",
-            getErrorString(result));
-    error(RtError::WARNING);
-    return 0;
-  }
-
-  for ( int i=0; i<nDevices_; i++ ) {
-    if ( info.name == devices_[i].name ) return i;
-  }
-
-  return 0;
-}
-
-int RtApiDs :: getDefaultOutputDevice(void)
-{
-  enum_info info;
-  info.name[0] = '\0';
-
-  // Enumerate through devices to find the default output.
-  HRESULT result = DirectSoundEnumerate((LPDSENUMCALLBACK)defaultDeviceCallback, &info);
-  if ( FAILED(result) ) {
-    sprintf(message_, "RtApiDs: Error performing default output device enumeration: %s.",
-            getErrorString(result));
-    error(RtError::WARNING);
-    return 0;
-  }
-
-  for ( int i=0; i<nDevices_; i++ )
-    if ( info.name == devices_[i].name ) return i;
-
-  return 0;
-}
-
-void RtApiDs :: initialize(void)
-{
-  int i, ins = 0, outs = 0, count = 0;
-  HRESULT result;
-  nDevices_ = 0;
-
-  // Count DirectSound devices.
-  result = DirectSoundEnumerate((LPDSENUMCALLBACK)deviceCountCallback, &outs);
-  if ( FAILED(result) ) {
-    sprintf(message_, "RtApiDs: Unable to enumerate through sound playback devices: %s.",
-            getErrorString(result));
-    error(RtError::DRIVER_ERROR);
-  }
-
-  // Count DirectSoundCapture devices.
-  result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceCountCallback, &ins);
-  if ( FAILED(result) ) {
-    sprintf(message_, "RtApiDs: Unable to enumerate through sound capture devices: %s.",
-            getErrorString(result));
-    error(RtError::DRIVER_ERROR);
-  }
-
-  count = ins + outs;
-  if (count == 0) return;
-
-  std::vector<enum_info> info(count);
-  for (i=0; i<count; i++) {
-    if (i < outs) info[i].isInput = false;
-    else info[i].isInput = true;
-  }
-
-  // Get playback device info and check capabilities.
-  result = DirectSoundEnumerate((LPDSENUMCALLBACK)deviceInfoCallback, &info[0]);
-  if ( FAILED(result) ) {
-    sprintf(message_, "RtApiDs: Unable to enumerate through sound playback devices: %s.",
-            getErrorString(result));
-    error(RtError::DRIVER_ERROR);
-  }
-
-  // Get capture device info and check capabilities.
-  result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceInfoCallback, &info[0]);
-  if ( FAILED(result) ) {
-    sprintf(message_, "RtApiDs: Unable to enumerate through sound capture devices: %s.",
-            getErrorString(result));
-    error(RtError::DRIVER_ERROR);
-  }
-
-  // Create device structures for valid devices and write device names
-  // to each.  Devices are considered invalid if they cannot be
-  // opened, they report < 1 supported channels, or they report no
-  // supported data (capture only).
-  RtApiDevice device;
-  for (i=0; i<count; i++) {
-    if ( info[i].isValid ) {
-      device.name.erase();
-      device.name = info[i].name;
-      devices_.push_back(device);
-    }
-  }
-
-  nDevices_ = devices_.size();
-  return;
-}
-
-void RtApiDs :: probeDeviceInfo(RtApiDevice *info)
-{
-  enum_info dsinfo;
-  dsinfo.name = info->name;
-  dsinfo.isValid = false;
-
-  // Enumerate through input devices to find the id (if it exists).
-  HRESULT result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceIdCallback, &dsinfo);
-  if ( FAILED(result) ) {
-    sprintf(message_, "RtApiDs: Error performing input device id enumeration: %s.",
-            getErrorString(result));
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // Do capture probe first.
-  if ( dsinfo.isValid == false )
-    goto playback_probe;
-
-  LPDIRECTSOUNDCAPTURE  input;
-  result = DirectSoundCaptureCreate( dsinfo.id, &input, NULL );
-  if ( FAILED(result) ) {
-    sprintf(message_, "RtApiDs: Could not create capture object (%s): %s.",
-            info->name.c_str(), getErrorString(result));
-    error(RtError::DEBUG_WARNING);
-    goto playback_probe;
-  }
-
-  DSCCAPS in_caps;
-  in_caps.dwSize = sizeof(in_caps);
-  result = input->GetCaps( &in_caps );
-  if ( FAILED(result) ) {
-    input->Release();
-    sprintf(message_, "RtApiDs: Could not get capture capabilities (%s): %s.",
-            info->name.c_str(), getErrorString(result));
-    error(RtError::DEBUG_WARNING);
-    goto playback_probe;
-  }
-
-  // Get input channel information.
-  info->minInputChannels = 1;
-  info->maxInputChannels = in_caps.dwChannels;
-
-  // Get sample rate and format information.
-  info->sampleRates.clear();
-  if( in_caps.dwChannels == 2 ) {
-    if( in_caps.dwFormats & WAVE_FORMAT_1S16 ) info->nativeFormats |= RTAUDIO_SINT16;
-    if( in_caps.dwFormats & WAVE_FORMAT_2S16 ) info->nativeFormats |= RTAUDIO_SINT16;
-    if( in_caps.dwFormats & WAVE_FORMAT_4S16 ) info->nativeFormats |= RTAUDIO_SINT16;
-    if( in_caps.dwFormats & WAVE_FORMAT_1S08 ) info->nativeFormats |= RTAUDIO_SINT8;
-    if( in_caps.dwFormats & WAVE_FORMAT_2S08 ) info->nativeFormats |= RTAUDIO_SINT8;
-    if( in_caps.dwFormats & WAVE_FORMAT_4S08 ) info->nativeFormats |= RTAUDIO_SINT8;
-
-    if ( info->nativeFormats & RTAUDIO_SINT16 ) {
-      if( in_caps.dwFormats & WAVE_FORMAT_1S16 ) info->sampleRates.push_back( 11025 );
-      if( in_caps.dwFormats & WAVE_FORMAT_2S16 ) info->sampleRates.push_back( 22050 );
-      if( in_caps.dwFormats & WAVE_FORMAT_4S16 ) info->sampleRates.push_back( 44100 );
-    }
-    else if ( info->nativeFormats & RTAUDIO_SINT8 ) {
-      if( in_caps.dwFormats & WAVE_FORMAT_1S08 ) info->sampleRates.push_back( 11025 );
-      if( in_caps.dwFormats & WAVE_FORMAT_2S08 ) info->sampleRates.push_back( 22050 );
-      if( in_caps.dwFormats & WAVE_FORMAT_4S08 ) info->sampleRates.push_back( 44100 );
-    }
-  }
-  else if ( in_caps.dwChannels == 1 ) {
-    if( in_caps.dwFormats & WAVE_FORMAT_1M16 ) info->nativeFormats |= RTAUDIO_SINT16;
-    if( in_caps.dwFormats & WAVE_FORMAT_2M16 ) info->nativeFormats |= RTAUDIO_SINT16;
-    if( in_caps.dwFormats & WAVE_FORMAT_4M16 ) info->nativeFormats |= RTAUDIO_SINT16;
-    if( in_caps.dwFormats & WAVE_FORMAT_1M08 ) info->nativeFormats |= RTAUDIO_SINT8;
-    if( in_caps.dwFormats & WAVE_FORMAT_2M08 ) info->nativeFormats |= RTAUDIO_SINT8;
-    if( in_caps.dwFormats & WAVE_FORMAT_4M08 ) info->nativeFormats |= RTAUDIO_SINT8;
-
-    if ( info->nativeFormats & RTAUDIO_SINT16 ) {
-      if( in_caps.dwFormats & WAVE_FORMAT_1M16 ) info->sampleRates.push_back( 11025 );
-      if( in_caps.dwFormats & WAVE_FORMAT_2M16 ) info->sampleRates.push_back( 22050 );
-      if( in_caps.dwFormats & WAVE_FORMAT_4M16 ) info->sampleRates.push_back( 44100 );
-    }
-    else if ( info->nativeFormats & RTAUDIO_SINT8 ) {
-      if( in_caps.dwFormats & WAVE_FORMAT_1M08 ) info->sampleRates.push_back( 11025 );
-      if( in_caps.dwFormats & WAVE_FORMAT_2M08 ) info->sampleRates.push_back( 22050 );
-      if( in_caps.dwFormats & WAVE_FORMAT_4M08 ) info->sampleRates.push_back( 44100 );
-    }
-  }
-  else info->minInputChannels = 0; // technically, this would be an error
-
-  input->Release();
-
- playback_probe:
-
-  dsinfo.isValid = false;
-
-  // Enumerate through output devices to find the id (if it exists).
-  result = DirectSoundEnumerate((LPDSENUMCALLBACK)deviceIdCallback, &dsinfo);
-  if ( FAILED(result) ) {
-    sprintf(message_, "RtApiDs: Error performing output device id enumeration: %s.",
-            getErrorString(result));
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // Now do playback probe.
-  if ( dsinfo.isValid == false )
-    goto check_parameters;
-
-  LPDIRECTSOUND  output;
-  DSCAPS out_caps;
-  result = DirectSoundCreate( dsinfo.id, &output, NULL );
-  if ( FAILED(result) ) {
-    sprintf(message_, "RtApiDs: Could not create playback object (%s): %s.",
-            info->name.c_str(), getErrorString(result));
-    error(RtError::DEBUG_WARNING);
-    goto check_parameters;
-  }
-
-  out_caps.dwSize = sizeof(out_caps);
-  result = output->GetCaps( &out_caps );
-  if ( FAILED(result) ) {
-    output->Release();
-    sprintf(message_, "RtApiDs: Could not get playback capabilities (%s): %s.",
-            info->name.c_str(), getErrorString(result));
-    error(RtError::DEBUG_WARNING);
-    goto check_parameters;
-  }
-
-  // Get output channel information.
-  info->minOutputChannels = 1;
-  info->maxOutputChannels = ( out_caps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;
-
-  // Get sample rate information.  Use capture device rate information
-  // if it exists.
-  if ( info->sampleRates.size() == 0 ) {
-    info->sampleRates.push_back( (int) out_caps.dwMinSecondarySampleRate );
-    if ( out_caps.dwMaxSecondarySampleRate > out_caps.dwMinSecondarySampleRate )
-      info->sampleRates.push_back( (int) out_caps.dwMaxSecondarySampleRate );
-  }
-  else {
-    // Check input rates against output rate range.  If there's an
-    // inconsistency (such as a duplex-capable device which reports a
-    // single output rate of 48000 Hz), we'll go with the output
-    // rate(s) since the DirectSoundCapture API is stupid and broken.
-    // Note that the probed sample rate values are NOT used when
-    // opening the device.  Thanks to Tue Andersen for reporting this.
-    if ( info->sampleRates.back() < (int) out_caps.dwMinSecondarySampleRate ) {
-      info->sampleRates.clear();
-      info->sampleRates.push_back( (int) out_caps.dwMinSecondarySampleRate );
-      if ( out_caps.dwMaxSecondarySampleRate > out_caps.dwMinSecondarySampleRate )
-        info->sampleRates.push_back( (int) out_caps.dwMaxSecondarySampleRate );
-    }
-    else {
-      for ( int i=info->sampleRates.size()-1; i>=0; i-- ) {
-        if ( (unsigned int) info->sampleRates[i] > out_caps.dwMaxSecondarySampleRate )
-          info->sampleRates.erase( info->sampleRates.begin() + i );
-      }
-      while ( info->sampleRates.size() > 0 &&
-              ((unsigned int) info->sampleRates[0] < out_caps.dwMinSecondarySampleRate) ) {
-        info->sampleRates.erase( info->sampleRates.begin() );
-      }
-    }
-  }
-
-  // Get format information.
-  if ( out_caps.dwFlags & DSCAPS_PRIMARY16BIT ) info->nativeFormats |= RTAUDIO_SINT16;
-  if ( out_caps.dwFlags & DSCAPS_PRIMARY8BIT ) info->nativeFormats |= RTAUDIO_SINT8;
-
-  output->Release();
-
- check_parameters:
-  if ( info->maxInputChannels == 0 && info->maxOutputChannels == 0 ) {
-    sprintf(message_, "RtApiDs: no reported input or output channels for device (%s).",
-            info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-  if ( info->sampleRates.size() == 0 || info->nativeFormats == 0 ) {
-    sprintf(message_, "RtApiDs: no reported sample rates or data formats for device (%s).",
-            info->name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return;
-  }
-
-  // Determine duplex status.
-  if (info->maxInputChannels < info->maxOutputChannels)
-    info->maxDuplexChannels = info->maxInputChannels;
-  else
-    info->maxDuplexChannels = info->maxOutputChannels;
-  if (info->minInputChannels < info->minOutputChannels)
-    info->minDuplexChannels = info->minInputChannels;
-  else
-    info->minDuplexChannels = info->minOutputChannels;
-
-  if ( info->maxDuplexChannels > 0 ) info->hasDuplexSupport = true;
-  else info->hasDuplexSupport = false;
-
-  info->probed = true;
-
-  return;
-}
-
-bool RtApiDs :: probeDeviceOpen( int device, StreamMode mode, int channels, 
-                                 int sampleRate, RtAudioFormat format,
-                                 int *bufferSize, int numberOfBuffers)
-{
-  HRESULT result;
-  HWND hWnd = GetForegroundWindow();
-
-  // 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().
-  long buffer_size;
-  LPVOID audioPtr;
-  DWORD dataLen;
-  int nBuffers;
-
-  // 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.
-  if (numberOfBuffers < 2)
-    nBuffers = 2;
-  else
-    nBuffers = numberOfBuffers;
-
-  // Define the wave format structure (16-bit PCM, srate, channels)
-  WAVEFORMATEX waveFormat;
-  ZeroMemory(&waveFormat, sizeof(WAVEFORMATEX));
-  waveFormat.wFormatTag = WAVE_FORMAT_PCM;
-  waveFormat.nChannels = channels;
-  waveFormat.nSamplesPerSec = (unsigned long) sampleRate;
-
-  // Determine the data format.
-  if ( devices_[device].nativeFormats ) { // 8-bit and/or 16-bit support
-    if ( format == RTAUDIO_SINT8 ) {
-      if ( devices_[device].nativeFormats & RTAUDIO_SINT8 )
-        waveFormat.wBitsPerSample = 8;
-      else
-        waveFormat.wBitsPerSample = 16;
-    }
-    else {
-      if ( devices_[device].nativeFormats & RTAUDIO_SINT16 )
-        waveFormat.wBitsPerSample = 16;
-      else
-        waveFormat.wBitsPerSample = 8;
-    }
-  }
-  else {
-    sprintf(message_, "RtApiDs: no reported data formats for device (%s).",
-            devices_[device].name.c_str());
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
-  waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
-
-  // 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;
-
-  buffer_size = MINIMUM_DEVICE_BUFFER_SIZE; // sound cards will always *knock wood* support this
-
-  enum_info dsinfo;
-  void *ohandle = 0, *bhandle = 0;
-  //  strncpy( dsinfo.name, devices_[device].name.c_str(), 64 );
-  dsinfo.name = devices_[device].name;
-  dsinfo.isValid = false;
-  if ( mode == OUTPUT ) {
-
-    dsPointerLeadTime = numberOfBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;
-
-    // If the user wants an even bigger buffer, increase the device buffer size accordingly.
-    while ( dsPointerLeadTime * 2U > (DWORD)buffer_size )
-      buffer_size *= 2;
-
-    if ( devices_[device].maxOutputChannels < channels ) {
-      sprintf(message_, "RtApiDs: requested channels (%d) > than supported (%d) by device (%s).",
-              channels, devices_[device].maxOutputChannels, devices_[device].name.c_str());
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Enumerate through output devices to find the id (if it exists).
-    result = DirectSoundEnumerate((LPDSENUMCALLBACK)deviceIdCallback, &dsinfo);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Error performing output device id enumeration: %s.",
-              getErrorString(result));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    if ( dsinfo.isValid == false ) {
-      sprintf(message_, "RtApiDs: output device (%s) id not found!", devices_[device].name.c_str());
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    LPGUID id = dsinfo.id;
-    LPDIRECTSOUND  object;
-    LPDIRECTSOUNDBUFFER buffer;
-    DSBUFFERDESC bufferDescription;
-    
-    result = DirectSoundCreate( id, &object, NULL );
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Could not create playback object (%s): %s.",
-              devices_[device].name.c_str(), getErrorString(result));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Set cooperative level to DSSCL_EXCLUSIVE
-    result = object->SetCooperativeLevel(hWnd, DSSCL_EXCLUSIVE);
-    if ( FAILED(result) ) {
-      object->Release();
-      sprintf(message_, "RtApiDs: Unable to set cooperative level (%s): %s.",
-              devices_[device].name.c_str(), getErrorString(result));
-      error(RtError::DEBUG_WARNING);
-      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.
-    ZeroMemory(&bufferDescription, sizeof(DSBUFFERDESC));
-    bufferDescription.dwSize = sizeof(DSBUFFERDESC);
-    bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
-    // Obtain the primary buffer
-    result = object->CreateSoundBuffer(&bufferDescription, &buffer, NULL);
-    if ( FAILED(result) ) {
-      object->Release();
-      sprintf(message_, "RtApiDs: Unable to access primary buffer (%s): %s.",
-              devices_[device].name.c_str(), getErrorString(result));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Set the primary DS buffer sound format.
-    result = buffer->SetFormat(&waveFormat);
-    if ( FAILED(result) ) {
-      object->Release();
-      sprintf(message_, "RtApiDs: Unable to set primary buffer format (%s): %s.",
-              devices_[device].name.c_str(), getErrorString(result));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Setup the secondary DS buffer description.
-    dsBufferSize = (DWORD)buffer_size;
-    ZeroMemory(&bufferDescription, sizeof(DSBUFFERDESC));
-    bufferDescription.dwSize = sizeof(DSBUFFERDESC);
-    bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
-                                  DSBCAPS_GETCURRENTPOSITION2 |
-                                  DSBCAPS_LOCHARDWARE );  // Force hardware mixing
-    bufferDescription.dwBufferBytes = buffer_size;
-    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 = object->CreateSoundBuffer(&bufferDescription, &buffer, NULL);
-    if ( FAILED(result) ) {
-      bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |
-                                    DSBCAPS_GETCURRENTPOSITION2 |
-                                    DSBCAPS_LOCSOFTWARE );  // Force software mixing
-      result = object->CreateSoundBuffer(&bufferDescription, &buffer, NULL);
-      if ( FAILED(result) ) {
-        object->Release();
-        sprintf(message_, "RtApiDs: Unable to create secondary DS buffer (%s): %s.",
-                devices_[device].name.c_str(), getErrorString(result));
-        error(RtError::DEBUG_WARNING);
-        return FAILURE;
-      }
-    }
-
-    // Get the buffer size ... might be different from what we specified.
-    DSBCAPS dsbcaps;
-    dsbcaps.dwSize = sizeof(DSBCAPS);
-    buffer->GetCaps(&dsbcaps);
-    buffer_size = dsbcaps.dwBufferBytes;
-
-    // Lock the DS buffer
-    result = buffer->Lock(0, buffer_size, &audioPtr, &dataLen, NULL, NULL, 0);
-    if ( FAILED(result) ) {
-      object->Release();
-      buffer->Release();
-      sprintf(message_, "RtApiDs: Unable to lock buffer (%s): %s.",
-              devices_[device].name.c_str(), getErrorString(result));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Zero the DS buffer
-    ZeroMemory(audioPtr, dataLen);
-
-    // Unlock the DS buffer
-    result = buffer->Unlock(audioPtr, dataLen, NULL, 0);
-    if ( FAILED(result) ) {
-      object->Release();
-      buffer->Release();
-      sprintf(message_, "RtApiDs: Unable to unlock buffer(%s): %s.",
-              devices_[device].name.c_str(), getErrorString(result));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    ohandle = (void *) object;
-    bhandle = (void *) buffer;
-    stream_.nDeviceChannels[0] = channels;
-  }
-
-  if ( mode == INPUT ) {
-
-    if ( devices_[device].maxInputChannels < channels ) {
-      sprintf(message_, "RtAudioDS: device (%s) does not support %d channels.", devices_[device].name.c_str(), channels);
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Enumerate through input devices to find the id (if it exists).
-    result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceIdCallback, &dsinfo);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Error performing input device id enumeration: %s.",
-              getErrorString(result));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    if ( dsinfo.isValid == false ) {
-      sprintf(message_, "RtAudioDS: input device (%s) id not found!", devices_[device].name.c_str());
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    LPGUID id = dsinfo.id;
-    LPDIRECTSOUNDCAPTURE  object;
-    LPDIRECTSOUNDCAPTUREBUFFER buffer;
-    DSCBUFFERDESC bufferDescription;
-
-    result = DirectSoundCaptureCreate( id, &object, NULL );
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Could not create capture object (%s): %s.",
-              devices_[device].name.c_str(), getErrorString(result));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Setup the secondary DS buffer description.
-    dsBufferSize = buffer_size;
-    ZeroMemory(&bufferDescription, sizeof(DSCBUFFERDESC));
-    bufferDescription.dwSize = sizeof(DSCBUFFERDESC);
-    bufferDescription.dwFlags = 0;
-    bufferDescription.dwReserved = 0;
-    bufferDescription.dwBufferBytes = buffer_size;
-    bufferDescription.lpwfxFormat = &waveFormat;
-
-    // Create the capture buffer.
-    result = object->CreateCaptureBuffer(&bufferDescription, &buffer, NULL);
-    if ( FAILED(result) ) {
-      object->Release();
-      sprintf(message_, "RtApiDs: Unable to create capture buffer (%s): %s.",
-              devices_[device].name.c_str(), getErrorString(result));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Lock the capture buffer
-    result = buffer->Lock(0, buffer_size, &audioPtr, &dataLen, NULL, NULL, 0);
-    if ( FAILED(result) ) {
-      object->Release();
-      buffer->Release();
-      sprintf(message_, "RtApiDs: Unable to lock capture buffer (%s): %s.",
-              devices_[device].name.c_str(), getErrorString(result));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Zero the buffer
-    ZeroMemory(audioPtr, dataLen);
-
-    // Unlock the buffer
-    result = buffer->Unlock(audioPtr, dataLen, NULL, 0);
-    if ( FAILED(result) ) {
-      object->Release();
-      buffer->Release();
-      sprintf(message_, "RtApiDs: Unable to unlock capture buffer (%s): %s.",
-              devices_[device].name.c_str(), getErrorString(result));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    ohandle = (void *) object;
-    bhandle = (void *) buffer;
-    stream_.nDeviceChannels[1] = channels;
-  }
-
-  stream_.userFormat = format;
-  if ( waveFormat.wBitsPerSample == 8 )
-    stream_.deviceFormat[mode] = RTAUDIO_SINT8;
-  else
-    stream_.deviceFormat[mode] = RTAUDIO_SINT16;
-  stream_.nUserChannels[mode] = channels;
-
-  stream_.bufferSize = *bufferSize;
-
-  // 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;
-
-  // Allocate necessary internal buffers
-  if ( stream_.nUserChannels[0] != stream_.nUserChannels[1] ) {
-
-    long buffer_bytes;
-    if (stream_.nUserChannels[0] >= stream_.nUserChannels[1])
-      buffer_bytes = stream_.nUserChannels[0];
-    else
-      buffer_bytes = stream_.nUserChannels[1];
-
-    buffer_bytes *= *bufferSize * formatBytes(stream_.userFormat);
-    if (stream_.userBuffer) free(stream_.userBuffer);
-    stream_.userBuffer = (char *) calloc(buffer_bytes, 1);
-    if (stream_.userBuffer == NULL) {
-      sprintf(message_, "RtApiDs: error allocating user buffer memory (%s).",
-              devices_[device].name.c_str());
-      goto error;
-    }
-  }
-
-  if ( stream_.doConvertBuffer[mode] ) {
-
-    long buffer_bytes;
-    bool makeBuffer = true;
-    if ( mode == OUTPUT )
-      buffer_bytes = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-    else { // mode == INPUT
-      buffer_bytes = stream_.nDeviceChannels[1] * formatBytes(stream_.deviceFormat[1]);
-      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
-        long bytes_out = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-        if ( buffer_bytes < bytes_out ) makeBuffer = false;
-      }
-    }
-
-    if ( makeBuffer ) {
-      buffer_bytes *= *bufferSize;
-      if (stream_.deviceBuffer) free(stream_.deviceBuffer);
-      stream_.deviceBuffer = (char *) calloc(buffer_bytes, 1);
-      if (stream_.deviceBuffer == NULL) {
-        sprintf(message_, "RtApiDs: error allocating device buffer memory (%s).",
-                devices_[device].name.c_str());
-        goto error;
-      }
-    }
-  }
-
-  // Allocate our DsHandle structures for the stream.
-  DsHandle *handles;
-  if ( stream_.apiHandle == 0 ) {
-    handles = (DsHandle *) calloc(2, sizeof(DsHandle));
-    if ( handles == NULL ) {
-      sprintf(message_, "RtApiDs: Error allocating DsHandle memory (%s).",
-              devices_[device].name.c_str());
-      goto error;
-    }
-    handles[0].object = 0;
-    handles[1].object = 0;
-    stream_.apiHandle = (void *) handles;
-  }
-  else
-    handles = (DsHandle *) stream_.apiHandle;
-  handles[mode].object = ohandle;
-  handles[mode].buffer = bhandle;
-  handles[mode].dsBufferSize = dsBufferSize;
-  handles[mode].dsPointerLeadTime = 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] ) {
-    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];
-    }
-
-    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 ( mode == INPUT && stream_.deInterleave[1] ) {
-      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 if (mode == OUTPUT && stream_.deInterleave[0]) {
-      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_.convertInfo[mode].outOffset.push_back( k );
-      }
-    }
-  }
-
-  return SUCCESS;
-
- error:
-  if (handles) {
-    if (handles[0].object) {
-      LPDIRECTSOUND object = (LPDIRECTSOUND) handles[0].object;
-      LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handles[0].buffer;
-      if (buffer) buffer->Release();
-      object->Release();
-    }
-    if (handles[1].object) {
-      LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handles[1].object;
-      LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handles[1].buffer;
-      if (buffer) buffer->Release();
-      object->Release();
-    }
-    free(handles);
-    stream_.apiHandle = 0;
-  }
-
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  error(RtError::DEBUG_WARNING);
-  return FAILURE;
-}
-
-void RtApiDs :: setStreamCallback(RtAudioCallback callback, void *userData)
-{
-  verifyStream();
-
-  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
-  if ( info->usingCallback ) {
-    sprintf(message_, "RtApiDs: A callback is already set for this stream!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  info->callback = (void *) callback;
-  info->userData = userData;
-  info->usingCallback = true;
-  info->object = (void *) this;
-
-  unsigned thread_id;
-  info->thread = _beginthreadex(NULL, 0, &callbackHandler,
-                                &stream_.callbackInfo, 0, &thread_id);
-  if (info->thread == 0) {
-    info->usingCallback = false;
-    sprintf(message_, "RtApiDs: error starting callback thread!");
-    error(RtError::THREAD_ERROR);
-  }
-
-  // When spawning multiple threads in quick succession, it appears to be
-  // necessary to wait a bit for each to initialize ... another windoism!
-  Sleep(1);
-}
-
-void RtApiDs :: cancelStreamCallback()
-{
-  verifyStream();
-
-  if (stream_.callbackInfo.usingCallback) {
-
-    if (stream_.state == STREAM_RUNNING)
-      stopStream();
-
-    MUTEX_LOCK(&stream_.mutex);
-
-    stream_.callbackInfo.usingCallback = false;
-    WaitForSingleObject( (HANDLE)stream_.callbackInfo.thread, INFINITE );
-    CloseHandle( (HANDLE)stream_.callbackInfo.thread );
-    stream_.callbackInfo.thread = 0;
-    stream_.callbackInfo.callback = NULL;
-    stream_.callbackInfo.userData = NULL;
-
-    MUTEX_UNLOCK(&stream_.mutex);
-  }
-}
-
-void RtApiDs :: closeStream()
-{
-  // We don't want an exception to be thrown here because this
-  // function is called by our class destructor.  So, do our own
-  // streamId check.
-  if ( stream_.mode == UNINITIALIZED ) {
-    sprintf(message_, "RtApiDs::closeStream(): no open stream to close!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  if (stream_.callbackInfo.usingCallback) {
-    stream_.callbackInfo.usingCallback = false;
-    WaitForSingleObject( (HANDLE)stream_.callbackInfo.thread, INFINITE );
-    CloseHandle( (HANDLE)stream_.callbackInfo.thread );
-  }
-
-  DsHandle *handles = (DsHandle *) stream_.apiHandle;
-  if (handles) {
-    if (handles[0].object) {
-      LPDIRECTSOUND object = (LPDIRECTSOUND) handles[0].object;
-      LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handles[0].buffer;
-      if (buffer) {
-        buffer->Stop();
-        buffer->Release();
-      }
-      object->Release();
-    }
-
-    if (handles[1].object) {
-      LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handles[1].object;
-      LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handles[1].buffer;
-      if (buffer) {
-        buffer->Stop();
-        buffer->Release();
-      }
-      object->Release();
-    }
-    free(handles);
-    stream_.apiHandle = 0;
-  }
-    
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  if (stream_.deviceBuffer) {
-    free(stream_.deviceBuffer);
-    stream_.deviceBuffer = 0;
-  }
-
-  stream_.mode = UNINITIALIZED;
-}
-
-void RtApiDs :: startStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_RUNNING) 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.
-
-  MUTEX_LOCK(&stream_.mutex);
-  
-  DsHandle *handles = (DsHandle *) stream_.apiHandle;
-
-  timeBeginPeriod(1); 
-
-  memset(&statistics,0,sizeof(statistics));
-  statistics.sampleRate = stream_.sampleRate;
-  statistics.writeDeviceBufferLeadBytes = handles[0].dsPointerLeadTime ;
-
-  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]);
-  }
-
-#ifdef GENERATE_DEBUG_LOG
-  currentDebugLogEntry = 0;
-#endif  
-
-  HRESULT result;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-      statistics.outputFrameSize = formatBytes( stream_.deviceFormat[0])
-                                  *stream_.nDeviceChannels[0];
-
-    LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handles[0].buffer;
-    result = buffer->Play( 0, 0, DSBPLAY_LOOPING );
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to start buffer (%s): %s.",
-              devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  if (stream_.mode == INPUT || stream_.mode == DUPLEX) {
-    statistics.inputFrameSize = formatBytes( stream_.deviceFormat[1])
-                                  *stream_.nDeviceChannels[1];
-
-    LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handles[1].buffer;
-    result = buffer->Start(DSCBSTART_LOOPING );
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to start capture buffer (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-  stream_.state = STREAM_RUNNING;
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiDs :: stopStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_STOPPED) return;
-
-  // Change the state before the lock to improve shutdown response
-  // when using a callback.
-  stream_.state = STREAM_STOPPED;
-  MUTEX_LOCK(&stream_.mutex);
-
-  timeEndPeriod(1); // revert to normal scheduler frequency on lesser windows.
-
-#ifdef GENERATE_DEBUG_LOG
-  // Write the timing log to a .TSV file for analysis in Excel.
-  unlink("c:/rtaudiolog.txt");
-  std::ofstream os("c:/rtaudiolog.txt");
-  os << "writeTime\treadDelay\tnextWritePointer\tnextReadPointer\tcurrentWritePointer\tsafeWritePointer\tcurrentReadPointer\tsafeReadPointer" << std::endl;
-  for (int i = 0; i < currentDebugLogEntry ; ++i) {
-    TTickRecord &r = debugLog[i];
-    os << r.writeTime-debugLog[0].writeTime << "\t" << (r.readTime-r.writeTime) << "\t"
-       << r.nextWritePointer % BUFFER_SIZE << "\t" << r.nextReadPointer % BUFFER_SIZE 
-       << "\t" << r.currentWritePointer % BUFFER_SIZE << "\t" << r.safeWritePointer % BUFFER_SIZE 
-       << "\t" << r.currentReadPointer % BUFFER_SIZE << "\t" << r.safeReadPointer % BUFFER_SIZE << std::endl;
-  }
-#endif
-
-  // There is no specific DirectSound API call to "drain" a buffer
-  // before stopping.  We can hack this for playback by writing
-  // buffers of zeroes over the entire buffer.  For capture, the
-  // concept is less clear so we'll repeat what we do in the
-  // abortStream() case.
-  HRESULT result;
-  DWORD dsBufferSize;
-  LPVOID buffer1 = NULL;
-  LPVOID buffer2 = NULL;
-  DWORD bufferSize1 = 0;
-  DWORD bufferSize2 = 0;
-  DsHandle *handles = (DsHandle *) stream_.apiHandle;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-
-    DWORD currentPos, safePos;
-    long buffer_bytes = stream_.bufferSize * stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-
-    LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handles[0].buffer;
-    DWORD nextWritePos = handles[0].bufferPointer;
-    dsBufferSize = handles[0].dsBufferSize;
-    DWORD dsBytesWritten = 0;
-
-    // Write zeroes for at least dsBufferSize bytes. 
-    while ( dsBytesWritten < dsBufferSize ) {
-
-      // Find out where the read and "safe write" pointers are.
-      result = dsBuffer->GetCurrentPosition( &currentPos, &safePos );
-      if ( FAILED(result) ) {
-        sprintf(message_, "RtApiDs: Unable to get current position (%s): %s.",
-                devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-        error(RtError::DRIVER_ERROR);
-      }
-
-      // Chase nextWritePosition.
-      if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset
-      DWORD endWrite = nextWritePos + buffer_bytes;
-
-      // Check whether the entire write region is behind the play pointer.
-      while ( currentPos < endWrite ) {
-        double millis = (endWrite - currentPos) * 900.0;
-        millis /= ( formatBytes(stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] *stream_.sampleRate);
-        if ( millis < 1.0 ) millis = 1.0;
-        Sleep( (DWORD) millis );
-
-        // Wake up, find out where we are now
-        result = dsBuffer->GetCurrentPosition( &currentPos, &safePos );
-        if ( FAILED(result) ) {
-          sprintf(message_, "RtApiDs: Unable to get current position (%s): %s.",
-                  devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-          error(RtError::DRIVER_ERROR);
-        }
-
-        if ( currentPos < (DWORD)nextWritePos ) currentPos += dsBufferSize; // unwrap offset
-      }
-
-      // Lock free space in the buffer
-      result = dsBuffer->Lock( nextWritePos, buffer_bytes, &buffer1,
-                               &bufferSize1, &buffer2, &bufferSize2, 0);
-      if ( FAILED(result) ) {
-        sprintf(message_, "RtApiDs: Unable to lock buffer during playback (%s): %s.",
-                devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-        error(RtError::DRIVER_ERROR);
-      }
-
-      // Zero the free space
-      ZeroMemory( buffer1, bufferSize1 );
-      if (buffer2 != NULL) ZeroMemory( buffer2, bufferSize2 );
-
-      // Update our buffer offset and unlock sound buffer
-      dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );
-      if ( FAILED(result) ) {
-        sprintf(message_, "RtApiDs: Unable to unlock buffer during playback (%s): %s.",
-                devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-        error(RtError::DRIVER_ERROR);
-      }
-      nextWritePos = (nextWritePos + bufferSize1 + bufferSize2) % dsBufferSize;
-      handles[0].bufferPointer = nextWritePos;
-      dsBytesWritten += buffer_bytes;
-    }
-
-    // OK, now stop the buffer.
-    result = dsBuffer->Stop();
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to stop buffer (%s): %s",
-              devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    // If we play again, start at the beginning of the buffer.
-    handles[0].bufferPointer = 0;
-  }
-
-  if (stream_.mode == INPUT || stream_.mode == DUPLEX) {
-
-    LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handles[1].buffer;
-    buffer1 = NULL;
-    bufferSize1 = 0;
-
-    result = buffer->Stop();
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to stop capture buffer (%s): %s",
-              devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    dsBufferSize = handles[1].dsBufferSize;
-
-    // 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, dsBufferSize, &buffer1, &bufferSize1, NULL, NULL, 0);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to lock capture buffer (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    // Zero the DS buffer
-    ZeroMemory(buffer1, bufferSize1);
-
-    // Unlock the DS buffer
-    result = buffer->Unlock(buffer1, bufferSize1, NULL, 0);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to unlock capture buffer (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    // If we start recording again, we must begin at beginning of buffer.
-    handles[1].bufferPointer = 0;
-  }
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiDs :: abortStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_STOPPED) return;
-
-  // Change the state before the lock to improve shutdown response
-  // when using a callback.
-  stream_.state = STREAM_STOPPED;
-  MUTEX_LOCK(&stream_.mutex);
-
-  timeEndPeriod(1); // revert to normal scheduler frequency on lesser windows.
-
-  HRESULT result;
-  long dsBufferSize;
-  LPVOID audioPtr;
-  DWORD dataLen;
-  DsHandle *handles = (DsHandle *) stream_.apiHandle;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-    LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handles[0].buffer;
-    result = buffer->Stop();
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to stop buffer (%s): %s",
-              devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    dsBufferSize = handles[0].dsBufferSize;
-
-    // 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, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to lock buffer (%s): %s.",
-              devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    // Zero the DS buffer
-    ZeroMemory(audioPtr, dataLen);
-
-    // Unlock the DS buffer
-    result = buffer->Unlock(audioPtr, dataLen, NULL, 0);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to unlock buffer (%s): %s.",
-              devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    // If we start playing again, we must begin at beginning of buffer.
-    handles[0].bufferPointer = 0;
-  }
-
-  if (stream_.mode == INPUT || stream_.mode == DUPLEX) {
-    LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handles[1].buffer;
-    audioPtr = NULL;
-    dataLen = 0;
-
-    result = buffer->Stop();
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to stop capture buffer (%s): %s",
-              devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    dsBufferSize = handles[1].dsBufferSize;
-
-    // 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, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to lock capture buffer (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    // Zero the DS buffer
-    ZeroMemory(audioPtr, dataLen);
-
-    // Unlock the DS buffer
-    result = buffer->Unlock(audioPtr, dataLen, NULL, 0);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to unlock capture buffer (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    // If we start recording again, we must begin at beginning of buffer.
-    handles[1].bufferPointer = 0;
-  }
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-int RtApiDs :: streamWillBlock()
-{
-  verifyStream();
-  if (stream_.state == STREAM_STOPPED) return 0;
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  int channels;
-  int frames = 0;
-  HRESULT result;
-  DWORD currentPos, safePos;
-  channels = 1;
-  DsHandle *handles = (DsHandle *) stream_.apiHandle;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-
-    LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handles[0].buffer;
-    UINT nextWritePos = handles[0].bufferPointer;
-    channels = stream_.nDeviceChannels[0];
-    DWORD dsBufferSize = handles[0].dsBufferSize;
-
-    // Find out where the read and "safe write" pointers are.
-    result = dsBuffer->GetCurrentPosition(&currentPos, &safePos);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to get current position (%s): %s.",
-              devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    DWORD leadPos = safePos + handles[0].dsPointerLeadTime;
-    if (leadPos > dsBufferSize) {
-      leadPos -= dsBufferSize;
-    }
-    if ( leadPos < nextWritePos ) leadPos += dsBufferSize; // unwrap offset
-
-    frames = (leadPos - nextWritePos);
-    frames /= channels * formatBytes(stream_.deviceFormat[0]);
-  }
-
-  if (stream_.mode == INPUT ) {
-      // note that we don't block on DUPLEX input anymore. We run lockstep with the write pointer instead.
-
-    LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handles[1].buffer;
-    UINT nextReadPos = handles[1].bufferPointer;
-    channels = stream_.nDeviceChannels[1];
-    DWORD dsBufferSize = handles[1].dsBufferSize;
-
-    // Find out where the write and "safe read" pointers are.
-    result = dsBuffer->GetCurrentPosition(&currentPos, &safePos);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to get current capture position (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    if ( safePos < (DWORD)nextReadPos ) safePos += dsBufferSize; // unwrap offset
-
-    frames = (int)(safePos - nextReadPos);
-    frames /= channels * formatBytes(stream_.deviceFormat[1]);
-  }
-
-  frames = stream_.bufferSize - frames;
-  if (frames < 0) frames = 0;
-
-  MUTEX_UNLOCK(&stream_.mutex);
-  return frames;
-}
-
-void RtApiDs :: tickStream()
-{
-  verifyStream();
-
-  int stopStream = 0;
-  if (stream_.state == STREAM_STOPPED) {
-    if (stream_.callbackInfo.usingCallback) Sleep(50); // sleep 50 milliseconds
-    return;
-  }
-  else if (stream_.callbackInfo.usingCallback) {
-    RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
-    stopStream = callback(stream_.userBuffer, stream_.bufferSize, stream_.callbackInfo.userData);
-  }
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  // The state might change while waiting on a mutex.
-  if (stream_.state == STREAM_STOPPED) {
-    MUTEX_UNLOCK(&stream_.mutex);
-    return;
-  }
-
-  HRESULT result;
-  DWORD currentWritePos, safeWritePos;
-  DWORD currentReadPos, safeReadPos;
-  DWORD leadPos;
-  UINT nextWritePos;
-
-#ifdef GENERATE_DEBUG_LOG
-  DWORD writeTime, readTime;
-#endif
-
-  LPVOID buffer1 = NULL;
-  LPVOID buffer2 = NULL;
-  DWORD bufferSize1 = 0;
-  DWORD bufferSize2 = 0;
-
-  char *buffer;
-  long buffer_bytes;
-  DsHandle *handles = (DsHandle *) stream_.apiHandle;
-
-  if (stream_.mode == DUPLEX && !buffersRolling) {
-    assert(handles[0].dsBufferSize == handles[1].dsBufferSize);
-
-    // 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.
-
-    LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handles[0].buffer;
-    LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handles[1].buffer;
-
-    DWORD initialWritePos, initialSafeWritePos;
-    DWORD initialReadPos, initialSafeReadPos;;
-
-    result = dsWriteBuffer->GetCurrentPosition(&initialWritePos, &initialSafeWritePos);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to get current position (%s): %s.",
-              devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-    result = dsCaptureBuffer->GetCurrentPosition(&initialReadPos, &initialSafeReadPos);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to get current capture position (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-    while (true) {
-      result = dsWriteBuffer->GetCurrentPosition(&currentWritePos, &safeWritePos);
-      if ( FAILED(result) ) {
-        sprintf(message_, "RtApiDs: Unable to get current position (%s): %s.",
-                devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-        error(RtError::DRIVER_ERROR);
-      }
-      result = dsCaptureBuffer->GetCurrentPosition(&currentReadPos, &safeReadPos);
-      if ( FAILED(result) ) {
-        sprintf(message_, "RtApiDs: Unable to get current capture position (%s): %s.",
-                devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-        error(RtError::DRIVER_ERROR);
-      }
-      if (safeWritePos != initialSafeWritePos && safeReadPos != initialSafeReadPos) {
-        break;
-      }
-      Sleep(1);
-    }
-
-    assert( handles[0].dsBufferSize == handles[1].dsBufferSize );
-
-    buffersRolling = true;
-    handles[0].bufferPointer = (safeWritePos + handles[0].dsPointerLeadTime);
-    handles[1].bufferPointer = safeReadPos;
-
-  }
-
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-    
-    LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handles[0].buffer;
-
-    // Setup parameters and do buffer conversion if necessary.
-    if (stream_.doConvertBuffer[0]) {
-      buffer = stream_.deviceBuffer;
-      convertBuffer( buffer, stream_.userBuffer, stream_.convertInfo[0] );
-      buffer_bytes = stream_.bufferSize * stream_.nDeviceChannels[0];
-      buffer_bytes *= formatBytes(stream_.deviceFormat[0]);
-    }
-    else {
-      buffer = stream_.userBuffer;
-      buffer_bytes = stream_.bufferSize * stream_.nUserChannels[0];
-      buffer_bytes *= formatBytes(stream_.userFormat);
-    }
-
-    // No byte swapping necessary in DirectSound implementation.
-
-    // 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<buffer_bytes; i++ ) buffer[i] = (unsigned char) (buffer[i] + 128);
-
-    DWORD dsBufferSize = handles[0].dsBufferSize;
-         nextWritePos = handles[0].bufferPointer;
-
-    DWORD endWrite;
-    while ( true ) {
-      // Find out where the read and "safe write" pointers are.
-      result = dsBuffer->GetCurrentPosition(&currentWritePos, &safeWritePos);
-      if ( FAILED(result) ) {
-        sprintf(message_, "RtApiDs: Unable to get current position (%s): %s.",
-                devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-        error(RtError::DRIVER_ERROR);
-      }
-
-      leadPos = safeWritePos + handles[0].dsPointerLeadTime;
-      if ( leadPos > dsBufferSize ) leadPos -= dsBufferSize;
-      if ( leadPos < nextWritePos ) leadPos += dsBufferSize; // unwrap offset
-      endWrite = nextWritePos + buffer_bytes;
-
-      // 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 );
-    }
-
-#ifdef GENERATE_DEBUG_LOG
-    writeTime = timeGetTime();
-#endif
-
-    if (statistics.writeDeviceSafeLeadBytes < dsPointerDifference(safeWritePos,currentWritePos,handles[0].dsBufferSize)) {
-      statistics.writeDeviceSafeLeadBytes = dsPointerDifference(safeWritePos,currentWritePos,handles[0].dsBufferSize);
-    }
-
-    if ( dsPointerBetween( nextWritePos, safeWritePos, currentWritePos, dsBufferSize )
-         || dsPointerBetween( endWrite, safeWritePos, currentWritePos, dsBufferSize ) ) { 
-      // We've strayed into the forbidden zone ... resync the read pointer.
-      ++statistics.numberOfWriteUnderruns;
-      nextWritePos = safeWritePos + handles[0].dsPointerLeadTime-buffer_bytes+dsBufferSize;
-      while (nextWritePos >= dsBufferSize) nextWritePos-= dsBufferSize;
-      handles[0].bufferPointer = nextWritePos;
-      endWrite = nextWritePos + buffer_bytes;
-    }
-    
-    // Lock free space in the buffer
-    result = dsBuffer->Lock( nextWritePos, buffer_bytes, &buffer1,
-                             &bufferSize1, &buffer2, &bufferSize2, 0 );
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to lock buffer during playback (%s): %s.",
-              devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_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) ) {
-      sprintf(message_, "RtApiDs: Unable to unlock buffer during playback (%s): %s.",
-              devices_[stream_.device[0]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-    nextWritePos = (nextWritePos + bufferSize1 + bufferSize2) % dsBufferSize;
-    handles[0].bufferPointer = nextWritePos;
-  }
-
-  if (stream_.mode == INPUT || stream_.mode == DUPLEX) {
-
-    // Setup parameters.
-    if (stream_.doConvertBuffer[1]) {
-      buffer = stream_.deviceBuffer;
-      buffer_bytes = stream_.bufferSize * stream_.nDeviceChannels[1];
-      buffer_bytes *= formatBytes(stream_.deviceFormat[1]);
-    }
-    else {
-      buffer = stream_.userBuffer;
-      buffer_bytes = stream_.bufferSize * stream_.nUserChannels[1];
-      buffer_bytes *= formatBytes(stream_.userFormat);
-    }
-    LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handles[1].buffer;
-    long nextReadPos = handles[1].bufferPointer;
-    DWORD dsBufferSize = handles[1].dsBufferSize;
-
-    // Find out where the write and "safe read" pointers are.
-    result = dsBuffer->GetCurrentPosition(&currentReadPos, &safeReadPos);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to get current capture position (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    if ( safeReadPos < (DWORD)nextReadPos ) safeReadPos += dsBufferSize; // unwrap offset
-    DWORD endRead = nextReadPos + buffer_bytes;
-
-    // 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;
-
-          ++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*buffer_bytes)  
-          {
-            nextReadPos = safeReadPos-2*buffer_bytes;
-          } else 
-          {
-            nextReadPos = safeReadPos-buffer_bytes-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-buffer_bytes;
-          while (nextReadPos < 0) nextReadPos += dsBufferSize;
-        }
-        endRead = nextReadPos + buffer_bytes;
-      }
-    } else {
-      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) ) {
-          sprintf(message_, "RtApiDs: Unable to get current capture position (%s): %s.",
-                  devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-          error(RtError::DRIVER_ERROR);
-        }
-      
-        if ( safeReadPos < (DWORD)nextReadPos ) safeReadPos += dsBufferSize; // unwrap offset
-      }
-    }
-#ifdef GENERATE_DEBUG_LOG
-    readTime = timeGetTime();
-#endif
-    if (statistics.readDeviceSafeLeadBytes < dsPointerDifference(currentReadPos,nextReadPos ,dsBufferSize))
-    {
-      statistics.readDeviceSafeLeadBytes = dsPointerDifference(currentReadPos,nextReadPos ,dsBufferSize);
-    }
-
-    // Lock free space in the buffer
-    result = dsBuffer->Lock (nextReadPos, buffer_bytes, &buffer1,
-                             &bufferSize1, &buffer2, &bufferSize2, 0);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to lock buffer during capture (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-
-    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;
-    }
-
-    // Update our buffer offset and unlock sound buffer
-    nextReadPos = (nextReadPos + bufferSize1 + bufferSize2) % dsBufferSize;
-    dsBuffer->Unlock (buffer1, bufferSize1, buffer2, bufferSize2);
-    if ( FAILED(result) ) {
-      sprintf(message_, "RtApiDs: Unable to unlock buffer during capture (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), getErrorString(result));
-      error(RtError::DRIVER_ERROR);
-    }
-    handles[1].bufferPointer = 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<buffer_bytes; j++ ) buffer[j] = (signed char) (buffer[j] - 128);
-
-    // Do buffer conversion if necessary.
-    if (stream_.doConvertBuffer[1])
-      convertBuffer( stream_.userBuffer, 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
-
-
-  MUTEX_UNLOCK(&stream_.mutex);
-
-  if (stream_.callbackInfo.usingCallback && stopStream)
-    this->stopStream();
-}
-// Definitions for utility functions and callbacks
-// specific to the DirectSound implementation.
-
-extern "C" unsigned __stdcall callbackHandler(void *ptr)
-{
-  CallbackInfo *info = (CallbackInfo *) ptr;
-  RtApiDs *object = (RtApiDs *) info->object;
-  bool *usingCallback = &info->usingCallback;
-
-  while ( *usingCallback ) {
-    try {
-      object->tickStream();
-    }
-    catch (RtError &exception) {
-      fprintf(stderr, "\nRtApiDs: callback thread error (%s) ... closing thread.\n\n",
-              exception.getMessageString());
-      break;
-    }
-  }
-
-  _endthreadex( 0 );
-  return 0;
-}
-
-static bool CALLBACK deviceCountCallback(LPGUID lpguid,
-                                         LPCTSTR description,
-                                         LPCTSTR module,
-                                         LPVOID lpContext)
-{
-  int *pointer = ((int *) lpContext);
-  (*pointer)++;
-
-  return true;
-}
-
-#include "tchar.h"
-
-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] );
-#else
-  s.append( std::string( name ) );
-#endif
-
-  return s;
-}
-
-static bool CALLBACK deviceInfoCallback(LPGUID lpguid,
-                                        LPCTSTR description,
-                                        LPCTSTR module,
-                                        LPVOID lpContext)
-{
-  enum_info *info = ((enum_info *) lpContext);
-  while ( !info->name.empty() ) info++;
-
-  info->name = convertTChar( description );
-  info->id = lpguid;
-
-  HRESULT hr;
-  info->isValid = false;
-  if (info->isInput == true) {
-    DSCCAPS caps;
-    LPDIRECTSOUNDCAPTURE object;
-
-    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->isValid = true;
-    }
-    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->isValid = true;
-    }
-    object->Release();
-  }
-
-  return true;
-}
-
-static bool CALLBACK defaultDeviceCallback(LPGUID lpguid,
-                                           LPCTSTR description,
-                                           LPCTSTR module,
-                                           LPVOID lpContext)
-{
-  enum_info *info = ((enum_info *) lpContext);
-
-  if ( lpguid == NULL ) {
-    info->name = convertTChar( description );
-    return false;
-  }
-
-  return true;
-}
-
-static bool CALLBACK deviceIdCallback(LPGUID lpguid,
-                                      LPCTSTR description,
-                                      LPCTSTR module,
-                                      LPVOID lpContext)
-{
-  enum_info *info = ((enum_info *) lpContext);
-
-  std::string s = convertTChar( description );
-  if ( info->name == s ) {
-    info->id = lpguid;
-    info->isValid = true;
-    return false;
-  }
-
-  return true;
-}
-
-static char* getErrorString(int code)
-{
-       switch (code) {
-
-  case DSERR_ALLOCATED:
-    return "Already allocated.";
-
-  case DSERR_CONTROLUNAVAIL:
-    return "Control unavailable.";
-
-  case DSERR_INVALIDPARAM:
-    return "Invalid parameter.";
-
-  case DSERR_INVALIDCALL:
-    return "Invalid call.";
-
-  case DSERR_GENERIC:
-    return "Generic error.";
-
-  case DSERR_PRIOLEVELNEEDED:
-    return "Priority level needed";
-
-  case DSERR_OUTOFMEMORY:
-    return "Out of memory";
-
-  case DSERR_BADFORMAT:
-    return "The sample rate or the channel format is not supported.";
-
-  case DSERR_UNSUPPORTED:
-    return "Not supported.";
-
-  case DSERR_NODRIVER:
-    return "No driver.";
-
-  case DSERR_ALREADYINITIALIZED:
-    return "Already initialized.";
-
-  case DSERR_NOAGGREGATION:
-    return "No aggregation.";
-
-  case DSERR_BUFFERLOST:
-    return "Buffer lost.";
-
-  case DSERR_OTHERAPPHASPRIO:
-    return "Another application already has priority.";
-
-  case DSERR_UNINITIALIZED:
-    return "Uninitialized.";
-
-  default:
-    return "DirectSound unknown error";
-       }
-}
-
-//******************** End of __WINDOWS_DS__ *********************//
-#endif
-
-#if defined(__IRIX_AL__) // SGI's AL API for IRIX
-
-#include <dmedia/audio.h>
-#include <unistd.h>
-#include <errno.h>
-
-extern "C" void *callbackHandler(void * ptr);
-
-RtApiAl :: RtApiAl()
-{
-  this->initialize();
-
-  if (nDevices_ <= 0) {
-    sprintf(message_, "RtApiAl: no Irix AL audio devices found!");
-    error(RtError::NO_DEVICES_FOUND);
- }
-}
-
-RtApiAl :: ~RtApiAl()
-{
-  // The subclass destructor gets called before the base class
-  // destructor, so close any existing streams before deallocating
-  // apiDeviceId memory.
-  if ( stream_.mode != UNINITIALIZED ) closeStream();
-
-  // Free our allocated apiDeviceId memory.
-  long *id;
-  for ( unsigned int i=0; i<devices_.size(); i++ ) {
-    id = (long *) devices_[i].apiDeviceId;
-    if (id) free(id);
-  }
-}
-
-void RtApiAl :: initialize(void)
-{
-  // Count cards and devices
-  nDevices_ = 0;
-
-  // Determine the total number of input and output devices.
-  nDevices_ = alQueryValues(AL_SYSTEM, AL_DEVICES, 0, 0, 0, 0);
-  if (nDevices_ < 0) {
-    sprintf(message_, "RtApiAl: error counting devices: %s.",
-            alGetErrorString(oserror()));
-    error(RtError::DRIVER_ERROR);
-  }
-
-  if (nDevices_ <= 0) return;
-
-  ALvalue *vls = (ALvalue *) new ALvalue[nDevices_];
-
-  // Create our list of devices and write their ascii identifiers and resource ids.
-  char name[64];
-  int outs, ins, i;
-  ALpv pvs[1];
-  pvs[0].param = AL_NAME;
-  pvs[0].value.ptr = name;
-  pvs[0].sizeIn = 64;
-  RtApiDevice device;
-  long *id;
-
-  outs = alQueryValues(AL_SYSTEM, AL_DEFAULT_OUTPUT, vls, nDevices_, 0, 0);
-  if (outs < 0) {
-    delete [] vls;
-    sprintf(message_, "RtApiAl: error getting output devices: %s.",
-            alGetErrorString(oserror()));
-    error(RtError::DRIVER_ERROR);
-  }
-
-  for (i=0; i<outs; i++) {
-    if (alGetParams(vls[i].i, pvs, 1) < 0) {
-      delete [] vls;
-      sprintf(message_, "RtApiAl: error querying output devices: %s.",
-              alGetErrorString(oserror()));
-      error(RtError::DRIVER_ERROR);
-    }
-    device.name.erase();
-    device.name.append( (const char *)name, strlen(name)+1);
-    devices_.push_back(device);
-    id = (long *) calloc(2, sizeof(long));
-    id[0] = vls[i].i;
-    devices_[i].apiDeviceId = (void *) id;
-  }
-
-  ins = alQueryValues(AL_SYSTEM, AL_DEFAULT_INPUT, &vls[outs], nDevices_-outs, 0, 0);
-  if (ins < 0) {
-    delete [] vls;
-    sprintf(message_, "RtApiAl: error getting input devices: %s.",
-            alGetErrorString(oserror()));
-    error(RtError::DRIVER_ERROR);
-  }
-
-  for (i=outs; i<ins+outs; i++) {
-    if (alGetParams(vls[i].i, pvs, 1) < 0) {
-      delete [] vls;
-      sprintf(message_, "RtApiAl: error querying input devices: %s.",
-              alGetErrorString(oserror()));
-      error(RtError::DRIVER_ERROR);
-    }
-    device.name.erase();
-    device.name.append( (const char *)name, strlen(name)+1);
-    devices_.push_back(device);
-    id = (long *) calloc(2, sizeof(long));
-    id[1] = vls[i].i;
-    devices_[i].apiDeviceId = (void *) id;
-  }
-
-  delete [] vls;
-}
-
-int RtApiAl :: getDefaultInputDevice(void)
-{
-  ALvalue value;
-  long *id;
-  int result = alQueryValues(AL_SYSTEM, AL_DEFAULT_INPUT, &value, 1, 0, 0);
-  if (result < 0) {
-    sprintf(message_, "RtApiAl: error getting default input device id: %s.",
-            alGetErrorString(oserror()));
-    error(RtError::WARNING);
-  }
-  else {
-    for ( unsigned int i=0; i<devices_.size(); i++ ) {
-      id = (long *) devices_[i].apiDeviceId;
-      if ( id[1] == value.i ) return i;
-    }
-  }
-
-  return 0;
-}
-
-int RtApiAl :: getDefaultOutputDevice(void)
-{
-  ALvalue value;
-  long *id;
-  int result = alQueryValues(AL_SYSTEM, AL_DEFAULT_OUTPUT, &value, 1, 0, 0);
-  if (result < 0) {
-    sprintf(message_, "RtApiAl: error getting default output device id: %s.",
-            alGetErrorString(oserror()));
-    error(RtError::WARNING);
-  }
-  else {
-    for ( unsigned int i=0; i<devices_.size(); i++ ) {
-      id = (long *) devices_[i].apiDeviceId;
-      if ( id[0] == value.i ) return i;
-    }
-  }
-
-  return 0;
-}
-
-void RtApiAl :: probeDeviceInfo(RtApiDevice *info)
-{
-  int result;
-  long resource;
-  ALvalue value;
-  ALparamInfo pinfo;
-
-  // Get output resource ID if it exists.
-  long *id = (long *) info->apiDeviceId;
-  resource = id[0];
-  if (resource > 0) {
-
-    // Probe output device parameters.
-    result = alQueryValues(resource, AL_CHANNELS, &value, 1, 0, 0);
-    if (result < 0) {
-      sprintf(message_, "RtApiAl: error getting device (%s) channels: %s.",
-              info->name.c_str(), alGetErrorString(oserror()));
-      error(RtError::DEBUG_WARNING);
-    }
-    else {
-      info->maxOutputChannels = value.i;
-      info->minOutputChannels = 1;
-    }
-
-    result = alGetParamInfo(resource, AL_RATE, &pinfo);
-    if (result < 0) {
-      sprintf(message_, "RtApiAl: error getting device (%s) rates: %s.",
-              info->name.c_str(), alGetErrorString(oserror()));
-      error(RtError::DEBUG_WARNING);
-    }
-    else {
-      info->sampleRates.clear();
-      for (unsigned int k=0; k<MAX_SAMPLE_RATES; k++) {
-        if ( SAMPLE_RATES[k] >= pinfo.min.i && SAMPLE_RATES[k] <= pinfo.max.i )
-          info->sampleRates.push_back( SAMPLE_RATES[k] );
-      }
-    }
-
-    // The AL library supports all our formats, except 24-bit and 32-bit ints.
-    info->nativeFormats = (RtAudioFormat) 51;
-  }
-
-  // Now get input resource ID if it exists.
-  resource = id[1];
-  if (resource > 0) {
-
-    // Probe input device parameters.
-    result = alQueryValues(resource, AL_CHANNELS, &value, 1, 0, 0);
-    if (result < 0) {
-      sprintf(message_, "RtApiAl: error getting device (%s) channels: %s.",
-              info->name.c_str(), alGetErrorString(oserror()));
-      error(RtError::DEBUG_WARNING);
-    }
-    else {
-      info->maxInputChannels = value.i;
-      info->minInputChannels = 1;
-    }
-
-    result = alGetParamInfo(resource, AL_RATE, &pinfo);
-    if (result < 0) {
-      sprintf(message_, "RtApiAl: error getting device (%s) rates: %s.",
-              info->name.c_str(), alGetErrorString(oserror()));
-      error(RtError::DEBUG_WARNING);
-    }
-    else {
-      // In the case of the default device, these values will
-      // overwrite the rates determined for the output device.  Since
-      // the input device is most likely to be more limited than the
-      // output device, this is ok.
-      info->sampleRates.clear();
-      for (unsigned int k=0; k<MAX_SAMPLE_RATES; k++) {
-        if ( SAMPLE_RATES[k] >= pinfo.min.i && SAMPLE_RATES[k] <= pinfo.max.i )
-          info->sampleRates.push_back( SAMPLE_RATES[k] );
-      }
-    }
-
-    // The AL library supports all our formats, except 24-bit and 32-bit ints.
-    info->nativeFormats = (RtAudioFormat) 51;
-  }
-
-  if ( info->maxInputChannels == 0 && info->maxOutputChannels == 0 )
-    return;
-  if ( info->sampleRates.size() == 0 )
-    return;
-
-  // Determine duplex status.
-  if (info->maxInputChannels < info->maxOutputChannels)
-    info->maxDuplexChannels = info->maxInputChannels;
-  else
-    info->maxDuplexChannels = info->maxOutputChannels;
-  if (info->minInputChannels < info->minOutputChannels)
-    info->minDuplexChannels = info->minInputChannels;
-  else
-    info->minDuplexChannels = info->minOutputChannels;
-
-  if ( info->maxDuplexChannels > 0 ) info->hasDuplexSupport = true;
-  else info->hasDuplexSupport = false;
-
-  info->probed = true;
-
-  return;
-}
-
-bool RtApiAl :: probeDeviceOpen(int device, StreamMode mode, int channels, 
-                                int sampleRate, RtAudioFormat format,
-                                int *bufferSize, int numberOfBuffers)
-{
-  int result, nBuffers;
-  long resource;
-  ALconfig al_config;
-  ALport port;
-  ALpv pvs[2];
-  long *id = (long *) devices_[device].apiDeviceId;
-
-  // Get a new ALconfig structure.
-  al_config = alNewConfig();
-  if ( !al_config ) {
-    sprintf(message_,"RtApiAl: can't get AL config: %s.",
-            alGetErrorString(oserror()));
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  // Set the channels.
-  result = alSetChannels(al_config, channels);
-  if ( result < 0 ) {
-    alFreeConfig(al_config);
-    sprintf(message_,"RtApiAl: can't set %d channels in AL config: %s.",
-            channels, alGetErrorString(oserror()));
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  // Attempt to set the queue size.  The al API doesn't provide a
-  // means for querying the minimum/maximum buffer size of a device,
-  // so if the specified size doesn't work, take whatever the
-  // al_config structure returns.
-  if ( numberOfBuffers < 1 )
-    nBuffers = 1;
-  else
-    nBuffers = numberOfBuffers;
-  long buffer_size = *bufferSize * nBuffers;
-  result = alSetQueueSize(al_config, buffer_size); // in sample frames
-  if ( result < 0 ) {
-    // Get the buffer size specified by the al_config and try that.
-    buffer_size = alGetQueueSize(al_config);
-    result = alSetQueueSize(al_config, buffer_size);
-    if ( result < 0 ) {
-      alFreeConfig(al_config);
-      sprintf(message_,"RtApiAl: can't set buffer size (%ld) in AL config: %s.",
-              buffer_size, alGetErrorString(oserror()));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-    *bufferSize = buffer_size / nBuffers;
-  }
-
-  // Set the data format.
-  stream_.userFormat = format;
-  stream_.deviceFormat[mode] = format;
-  if (format == RTAUDIO_SINT8) {
-    result = alSetSampFmt(al_config, AL_SAMPFMT_TWOSCOMP);
-    result = alSetWidth(al_config, AL_SAMPLE_8);
-  }
-  else if (format == RTAUDIO_SINT16) {
-    result = alSetSampFmt(al_config, AL_SAMPFMT_TWOSCOMP);
-    result = alSetWidth(al_config, AL_SAMPLE_16);
-  }
-  else if (format == RTAUDIO_SINT24) {
-    // Our 24-bit format assumes the upper 3 bytes of a 4 byte word.
-    // The AL library uses the lower 3 bytes, so we'll need to do our
-    // own conversion.
-    result = alSetSampFmt(al_config, AL_SAMPFMT_FLOAT);
-    stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
-  }
-  else if (format == RTAUDIO_SINT32) {
-    // The AL library doesn't seem to support the 32-bit integer
-    // format, so we'll need to do our own conversion.
-    result = alSetSampFmt(al_config, AL_SAMPFMT_FLOAT);
-    stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;
-  }
-  else if (format == RTAUDIO_FLOAT32)
-    result = alSetSampFmt(al_config, AL_SAMPFMT_FLOAT);
-  else if (format == RTAUDIO_FLOAT64)
-    result = alSetSampFmt(al_config, AL_SAMPFMT_DOUBLE);
-
-  if ( result == -1 ) {
-    alFreeConfig(al_config);
-    sprintf(message_,"RtApiAl: error setting sample format in AL config: %s.",
-            alGetErrorString(oserror()));
-    error(RtError::DEBUG_WARNING);
-    return FAILURE;
-  }
-
-  if (mode == OUTPUT) {
-
-    // Set our device.
-    if (device == 0)
-      resource = AL_DEFAULT_OUTPUT;
-    else
-      resource = id[0];
-    result = alSetDevice(al_config, resource);
-    if ( result == -1 ) {
-      alFreeConfig(al_config);
-      sprintf(message_,"RtApiAl: error setting device (%s) in AL config: %s.",
-              devices_[device].name.c_str(), alGetErrorString(oserror()));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Open the port.
-    port = alOpenPort("RtApiAl Output Port", "w", al_config);
-    if( !port ) {
-      alFreeConfig(al_config);
-      sprintf(message_,"RtApiAl: error opening output port: %s.",
-              alGetErrorString(oserror()));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Set the sample rate
-    pvs[0].param = AL_MASTER_CLOCK;
-    pvs[0].value.i = AL_CRYSTAL_MCLK_TYPE;
-    pvs[1].param = AL_RATE;
-    pvs[1].value.ll = alDoubleToFixed((double)sampleRate);
-    result = alSetParams(resource, pvs, 2);
-    if ( result < 0 ) {
-      alClosePort(port);
-      alFreeConfig(al_config);
-      sprintf(message_,"RtApiAl: error setting sample rate (%d) for device (%s): %s.",
-              sampleRate, devices_[device].name.c_str(), alGetErrorString(oserror()));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-  }
-  else { // mode == INPUT
-
-    // Set our device.
-    if (device == 0)
-      resource = AL_DEFAULT_INPUT;
-    else
-      resource = id[1];
-    result = alSetDevice(al_config, resource);
-    if ( result == -1 ) {
-      alFreeConfig(al_config);
-      sprintf(message_,"RtApiAl: error setting device (%s) in AL config: %s.",
-              devices_[device].name.c_str(), alGetErrorString(oserror()));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Open the port.
-    port = alOpenPort("RtApiAl Input Port", "r", al_config);
-    if( !port ) {
-      alFreeConfig(al_config);
-      sprintf(message_,"RtApiAl: error opening input port: %s.",
-              alGetErrorString(oserror()));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-
-    // Set the sample rate
-    pvs[0].param = AL_MASTER_CLOCK;
-    pvs[0].value.i = AL_CRYSTAL_MCLK_TYPE;
-    pvs[1].param = AL_RATE;
-    pvs[1].value.ll = alDoubleToFixed((double)sampleRate);
-    result = alSetParams(resource, pvs, 2);
-    if ( result < 0 ) {
-      alClosePort(port);
-      alFreeConfig(al_config);
-      sprintf(message_,"RtApiAl: error setting sample rate (%d) for device (%s): %s.",
-              sampleRate, devices_[device].name.c_str(), alGetErrorString(oserror()));
-      error(RtError::DEBUG_WARNING);
-      return FAILURE;
-    }
-  }
-
-  alFreeConfig(al_config);
-
-  stream_.nUserChannels[mode] = channels;
-  stream_.nDeviceChannels[mode] = channels;
-
-  // Save stream handle.
-  ALport *handle = (ALport *) stream_.apiHandle;
-  if ( handle == 0 ) {
-    handle = (ALport *) calloc(2, sizeof(ALport));
-    if ( handle == NULL ) {
-      sprintf(message_, "RtApiAl: Irix Al error allocating handle memory (%s).",
-              devices_[device].name.c_str());
-      goto error;
-    }
-    stream_.apiHandle = (void *) handle;
-    handle[0] = 0;
-    handle[1] = 0;
-  }
-  handle[mode] = port;
-
-  // Set flags for buffer conversion
-  stream_.doConvertBuffer[mode] = false;
-  if (stream_.userFormat != stream_.deviceFormat[mode])
-    stream_.doConvertBuffer[mode] = true;
-
-  // Allocate necessary internal buffers
-  if ( stream_.nUserChannels[0] != stream_.nUserChannels[1] ) {
-
-    long buffer_bytes;
-    if (stream_.nUserChannels[0] >= stream_.nUserChannels[1])
-      buffer_bytes = stream_.nUserChannels[0];
-    else
-      buffer_bytes = stream_.nUserChannels[1];
-
-    buffer_bytes *= *bufferSize * formatBytes(stream_.userFormat);
-    if (stream_.userBuffer) free(stream_.userBuffer);
-    stream_.userBuffer = (char *) calloc(buffer_bytes, 1);
-    if (stream_.userBuffer == NULL) {
-      sprintf(message_, "RtApiAl: error allocating user buffer memory (%s).",
-              devices_[device].name.c_str());
-      goto error;
-    }
-  }
-
-  if ( stream_.doConvertBuffer[mode] ) {
-
-    long buffer_bytes;
-    bool makeBuffer = true;
-    if ( mode == OUTPUT )
-      buffer_bytes = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-    else { // mode == INPUT
-      buffer_bytes = stream_.nDeviceChannels[1] * formatBytes(stream_.deviceFormat[1]);
-      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {
-        long bytes_out = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);
-        if ( buffer_bytes < bytes_out ) makeBuffer = false;
-      }
-    }
-
-    if ( makeBuffer ) {
-      buffer_bytes *= *bufferSize;
-      if (stream_.deviceBuffer) free(stream_.deviceBuffer);
-      stream_.deviceBuffer = (char *) calloc(buffer_bytes, 1);
-      if (stream_.deviceBuffer == NULL) {
-        sprintf(message_, "RtApiAl: error allocating device buffer memory (%s).",
-                devices_[device].name.c_str());
-        goto error;
-      }
-    }
-  }
-
-  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_.bufferSize = *bufferSize;
-  stream_.sampleRate = sampleRate;
-
-  // Setup the buffer conversion information structure.
-  if ( stream_.doConvertBuffer[mode] ) {
-    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];
-    }
-
-    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 ( mode == INPUT && stream_.deInterleave[1] ) {
-      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 if (mode == OUTPUT && stream_.deInterleave[0]) {
-      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_.convertInfo[mode].outOffset.push_back( k );
-      }
-    }
-  }
-
-  return SUCCESS;
-
- error:
-  if (handle) {
-    if (handle[0])
-      alClosePort(handle[0]);
-    if (handle[1])
-      alClosePort(handle[1]);
-    free(handle);
-    stream_.apiHandle = 0;
-  }
-
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  error(RtError::DEBUG_WARNING);
-  return FAILURE;
-}
-
-void RtApiAl :: closeStream()
-{
-  // We don't want an exception to be thrown here because this
-  // function is called by our class destructor.  So, do our own
-  // streamId check.
-  if ( stream_.mode == UNINITIALIZED ) {
-    sprintf(message_, "RtApiAl::closeStream(): no open stream to close!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  ALport *handle = (ALport *) stream_.apiHandle;
-  if (stream_.state == STREAM_RUNNING) {
-    int buffer_size = stream_.bufferSize * stream_.nBuffers;
-    if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
-      alDiscardFrames(handle[0], buffer_size);
-    if (stream_.mode == INPUT || stream_.mode == DUPLEX)
-      alDiscardFrames(handle[1], buffer_size);
-    stream_.state = STREAM_STOPPED;
-  }
-
-  if (stream_.callbackInfo.usingCallback) {
-    stream_.callbackInfo.usingCallback = false;
-    pthread_join(stream_.callbackInfo.thread, NULL);
-  }
-
-  if (handle) {
-    if (handle[0]) alClosePort(handle[0]);
-    if (handle[1]) alClosePort(handle[1]);
-    free(handle);
-    stream_.apiHandle = 0;
-  }
-
-  if (stream_.userBuffer) {
-    free(stream_.userBuffer);
-    stream_.userBuffer = 0;
-  }
-
-  if (stream_.deviceBuffer) {
-    free(stream_.deviceBuffer);
-    stream_.deviceBuffer = 0;
-  }
-
-  stream_.mode = UNINITIALIZED;
-}
-
-void RtApiAl :: startStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_RUNNING) return;
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  // The AL port is ready as soon as it is opened.
-  stream_.state = STREAM_RUNNING;
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiAl :: stopStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_STOPPED) return;
-
-  // Change the state before the lock to improve shutdown response
-  // when using a callback.
-  stream_.state = STREAM_STOPPED;
-  MUTEX_LOCK(&stream_.mutex);
-
-  int result, buffer_size = stream_.bufferSize * stream_.nBuffers;
-  ALport *handle = (ALport *) stream_.apiHandle;
-
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX)
-    alZeroFrames(handle[0], buffer_size);
-
-  if (stream_.mode == INPUT || stream_.mode == DUPLEX) {
-    result = alDiscardFrames(handle[1], buffer_size);
-    if (result == -1) {
-      sprintf(message_, "RtApiAl: error draining stream device (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), alGetErrorString(oserror()));
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-void RtApiAl :: abortStream()
-{
-  verifyStream();
-  if (stream_.state == STREAM_STOPPED) return;
-
-  // Change the state before the lock to improve shutdown response
-  // when using a callback.
-  stream_.state = STREAM_STOPPED;
-  MUTEX_LOCK(&stream_.mutex);
-
-  ALport *handle = (ALport *) stream_.apiHandle;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-
-    int buffer_size = stream_.bufferSize * stream_.nBuffers;
-    int result = alDiscardFrames(handle[0], buffer_size);
-    if (result == -1) {
-      sprintf(message_, "RtApiAl: error aborting stream device (%s): %s.",
-              devices_[stream_.device[0]].name.c_str(), alGetErrorString(oserror()));
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  // There is no clear action to take on the input stream, since the
-  // port will continue to run in any event.
-
-  MUTEX_UNLOCK(&stream_.mutex);
-}
-
-int RtApiAl :: streamWillBlock()
-{
-  verifyStream();
-
-  if (stream_.state == STREAM_STOPPED) return 0;
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  int frames = 0;
-  int err = 0;
-  ALport *handle = (ALport *) stream_.apiHandle;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-    err = alGetFillable(handle[0]);
-    if (err < 0) {
-      sprintf(message_, "RtApiAl: error getting available frames for stream (%s): %s.",
-              devices_[stream_.device[0]].name.c_str(), alGetErrorString(oserror()));
-      error(RtError::DRIVER_ERROR);
-    }
-  }
-
-  frames = err;
-
-  if (stream_.mode == INPUT || stream_.mode == DUPLEX) {
-    err = alGetFilled(handle[1]);
-    if (err < 0) {
-      sprintf(message_, "RtApiAl: error getting available frames for stream (%s): %s.",
-              devices_[stream_.device[1]].name.c_str(), alGetErrorString(oserror()));
-      error(RtError::DRIVER_ERROR);
-    }
-    if (frames > err) frames = err;
-  }
-
-  frames = stream_.bufferSize - frames;
-  if (frames < 0) frames = 0;
-
-  MUTEX_UNLOCK(&stream_.mutex);
-  return frames;
-}
-
-void RtApiAl :: tickStream()
-{
-  verifyStream();
-
-  int stopStream = 0;
-  if (stream_.state == STREAM_STOPPED) {
-    if (stream_.callbackInfo.usingCallback) usleep(50000); // sleep 50 milliseconds
-    return;
-  }
-  else if (stream_.callbackInfo.usingCallback) {
-    RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;
-    stopStream = callback(stream_.userBuffer, stream_.bufferSize, stream_.callbackInfo.userData);
-  }
-
-  MUTEX_LOCK(&stream_.mutex);
-
-  // The state might change while waiting on a mutex.
-  if (stream_.state == STREAM_STOPPED)
-    goto unlock;
-
-  char *buffer;
-  int channels;
-  RtAudioFormat format;
-  ALport *handle = (ALport *) stream_.apiHandle;
-  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX) {
-
-    // Setup parameters and do buffer conversion if necessary.
-    if (stream_.doConvertBuffer[0]) {
-      buffer = stream_.deviceBuffer;
-      convertBuffer( buffer, stream_.userBuffer, stream_.convertInfo[0] );
-      channels = stream_.nDeviceChannels[0];
-      format = stream_.deviceFormat[0];
-    }
-    else {
-      buffer = stream_.userBuffer;
-      channels = stream_.nUserChannels[0];
-      format = stream_.userFormat;
-    }
-
-    // Do byte swapping if necessary.
-    if (stream_.doByteSwap[0])
-      byteSwapBuffer(buffer, stream_.bufferSize * channels, format);
-
-    // Write interleaved samples to device.
-    alWriteFrames(handle[0], buffer, stream_.bufferSize);
-  }
-
-  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;
-      channels = stream_.nUserChannels[1];
-      format = stream_.userFormat;
-    }
-
-    // Read interleaved samples from device.
-    alReadFrames(handle[1], buffer, stream_.bufferSize);
-
-    // 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, stream_.deviceBuffer, stream_.convertInfo[1] );
-  }
-
- unlock:
-  MUTEX_UNLOCK(&stream_.mutex);
-
-  if (stream_.callbackInfo.usingCallback && stopStream)
-    this->stopStream();
-}
-
-void RtApiAl :: setStreamCallback(RtAudioCallback callback, void *userData)
-{
-  verifyStream();
-
-  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;
-  if ( info->usingCallback ) {
-    sprintf(message_, "RtApiAl: A callback is already set for this stream!");
-    error(RtError::WARNING);
-    return;
-  }
-
-  info->callback = (void *) callback;
-  info->userData = userData;
-  info->usingCallback = true;
-  info->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);
-  pthread_attr_setschedpolicy(&attr, SCHED_RR);
-
-  int err = pthread_create(&info->thread, &attr, callbackHandler, &stream_.callbackInfo);
-  pthread_attr_destroy(&attr);
-  if (err) {
-    info->usingCallback = false;
-    sprintf(message_, "RtApiAl: error starting callback thread!");
-    error(RtError::THREAD_ERROR);
-  }
-}
-
-void RtApiAl :: cancelStreamCallback()
-{
-  verifyStream();
-
-  if (stream_.callbackInfo.usingCallback) {
-
-    if (stream_.state == STREAM_RUNNING)
-      stopStream();
-
-    MUTEX_LOCK(&stream_.mutex);
-
-    stream_.callbackInfo.usingCallback = false;
-    pthread_join(stream_.callbackInfo.thread, NULL);
-    stream_.callbackInfo.thread = 0;
-    stream_.callbackInfo.callback = NULL;
-    stream_.callbackInfo.userData = NULL;
-
-    MUTEX_UNLOCK(&stream_.mutex);
-  }
-}
-
-extern "C" void *callbackHandler(void *ptr)
-{
-  CallbackInfo *info = (CallbackInfo *) ptr;
-  RtApiAl *object = (RtApiAl *) info->object;
-  bool *usingCallback = &info->usingCallback;
-
-  while ( *usingCallback ) {
-    try {
-      object->tickStream();
-    }
-    catch (RtError &exception) {
-      fprintf(stderr, "\nRtApiAl: callback thread error (%s) ... closing thread.\n\n",
-              exception.getMessageString());
-      break;
-    }
-  }
-
-  return 0;
-}
-
-//******************** End of __IRIX_AL__ *********************//
-#endif
-
-
-// *************************************************** //
-//
-// Protected common (OS-independent) RtAudio methods.
-//
-// *************************************************** //
-
-// This method can be modified to control the behavior of error
-// message reporting and throwing.
-void RtApi :: error(RtError::Type type)
-{
-  if (type == RtError::WARNING) {
-    fprintf(stderr, "\n%s\n\n", message_);
-  }
-  else if (type == RtError::DEBUG_WARNING) {
-#if defined(__RTAUDIO_DEBUG__)
-    fprintf(stderr, "\n%s\n\n", message_);
-#endif
-  }
-  else {
-#if defined(__RTAUDIO_DEBUG__)
-    fprintf(stderr, "\n%s\n\n", message_);
-#endif
-    throw RtError(std::string(message_), type);
-  }
-}
-
-void RtApi :: verifyStream()
-{
-  if ( stream_.mode == UNINITIALIZED ) {
-    sprintf(message_, "RtAudio: stream is not open!");
-    error(RtError::INVALID_STREAM);
-  }
-}
-
-void RtApi :: clearDeviceInfo(RtApiDevice *info)
-{
-  // Don't clear the name or DEVICE_ID fields here ... they are
-  // typically set prior to a call of this function.
-  info->probed = false;
-  info->maxOutputChannels = 0;
-  info->maxInputChannels = 0;
-  info->maxDuplexChannels = 0;
-  info->minOutputChannels = 0;
-  info->minInputChannels = 0;
-  info->minDuplexChannels = 0;
-  info->hasDuplexSupport = false;
-  info->sampleRates.clear();
-  info->nativeFormats = 0;
-}
-
-void RtApi :: clearStreamInfo()
-{
-  stream_.mode = UNINITIALIZED;
-  stream_.state = STREAM_STOPPED;
-  stream_.sampleRate = 0;
-  stream_.bufferSize = 0;
-  stream_.nBuffers = 0;
-  stream_.userFormat = 0;
-  for ( int i=0; i<2; i++ ) {
-    stream_.device[i] = 0;
-    stream_.doConvertBuffer[i] = false;
-    stream_.deInterleave[i] = false;
-    stream_.doByteSwap[i] = false;
-    stream_.nUserChannels[i] = 0;
-    stream_.nDeviceChannels[i] = 0;
-    stream_.deviceFormat[i] = 0;
-  }
-}
-
-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;
-
-  sprintf(message_,"RtApi: undefined format in formatBytes().");
-  error(RtError::WARNING);
-
-  return 0;
-}
-
-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 / 128.0;
-      for (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]] *= scale;
-        }
-        in += info.inJump;
-        out += info.outJump;
-      }
-    }
-    else if (info.inFormat == RTAUDIO_SINT16) {
-      Int16 *in = (Int16 *)inBuffer;
-      scale = 1.0 / 32768.0;
-      for (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]] *= scale;
-        }
-        in += info.inJump;
-        out += info.outJump;
-      }
-    }
-    else if (info.inFormat == RTAUDIO_SINT24) {
-      Int32 *in = (Int32 *)inBuffer;
-      scale = 1.0 / 2147483648.0;
-      for (int i=0; i<stream_.bufferSize; i++) {
-        for (j=0; j<info.channels; j++) {
-          out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]] & 0xffffff00);
-          out[info.outOffset[j]] *= scale;
-        }
-        in += info.inJump;
-        out += info.outJump;
-      }
-    }
-    else if (info.inFormat == RTAUDIO_SINT32) {
-      Int32 *in = (Int32 *)inBuffer;
-      scale = 1.0 / 2147483648.0;
-      for (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]] *= scale;
-        }
-        in += info.inJump;
-        out += info.outJump;
-      }
-    }
-    else if (info.inFormat == RTAUDIO_FLOAT32) {
-      Float32 *in = (Float32 *)inBuffer;
-      for (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 (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 = 1.0 / 128.0;
-      for (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]] *= scale;
-        }
-        in += info.inJump;
-        out += info.outJump;
-      }
-    }
-    else if (info.inFormat == RTAUDIO_SINT16) {
-      Int16 *in = (Int16 *)inBuffer;
-      scale = 1.0 / 32768.0;
-      for (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]] *= scale;
-        }
-        in += info.inJump;
-        out += info.outJump;
-      }
-    }
-    else if (info.inFormat == RTAUDIO_SINT24) {
-      Int32 *in = (Int32 *)inBuffer;
-      scale = 1.0 / 2147483648.0;
-      for (int i=0; i<stream_.bufferSize; i++) {
-        for (j=0; j<info.channels; j++) {
-          out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]] & 0xffffff00);
-          out[info.outOffset[j]] *= scale;
-        }
-        in += info.inJump;
-        out += info.outJump;
-      }
-    }
-    else if (info.inFormat == RTAUDIO_SINT32) {
-      Int32 *in = (Int32 *)inBuffer;
-      scale = 1.0 / 2147483648.0;
-      for (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]] *= 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 (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 (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 (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 (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 (int i=0; i<stream_.bufferSize; i++) {
-        for (j=0; j<info.channels; j++) {
-          out[info.outOffset[j]] = (Int32) 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 (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 (int i=0; i<stream_.bufferSize; i++) {
-        for (j=0; j<info.channels; j++) {
-          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.0);
-        }
-        in += info.inJump;
-        out += info.outJump;
-      }
-    }
-    else if (info.inFormat == RTAUDIO_FLOAT64) {
-      Float64 *in = (Float64 *)inBuffer;
-      for (int i=0; i<stream_.bufferSize; i++) {
-        for (j=0; j<info.channels; j++) {
-          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.0);
-        }
-        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 (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 (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) {
-      // Channel compensation and/or (de)interleaving only.
-      Int32 *in = (Int32 *)inBuffer;
-      for (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 (int i=0; i<stream_.bufferSize; i++) {
-        for (j=0; j<info.channels; j++) {
-          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] & 0xffffff00);
-        }
-        in += info.inJump;
-        out += info.outJump;
-      }
-    }
-    else if (info.inFormat == RTAUDIO_FLOAT32) {
-      Float32 *in = (Float32 *)inBuffer;
-      for (int i=0; i<stream_.bufferSize; i++) {
-        for (j=0; j<info.channels; j++) {
-          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.0);
-        }
-        in += info.inJump;
-        out += info.outJump;
-      }
-    }
-    else if (info.inFormat == RTAUDIO_FLOAT64) {
-      Float64 *in = (Float64 *)inBuffer;
-      for (int i=0; i<stream_.bufferSize; i++) {
-        for (j=0; j<info.channels; j++) {
-          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.0);
-        }
-        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 (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 (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 (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 (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 (int i=0; i<stream_.bufferSize; i++) {
-        for (j=0; j<info.channels; j++) {
-          out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.0);
-        }
-        in += info.inJump;
-        out += info.outJump;
-      }
-    }
-    else if (info.inFormat == RTAUDIO_FLOAT64) {
-      Float64 *in = (Float64 *)inBuffer;
-      for (int i=0; i<stream_.bufferSize; i++) {
-        for (j=0; j<info.channels; j++) {
-          out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.0);
-        }
-        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 (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 (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 (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 (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 (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.0);
-        }
-        in += info.inJump;
-        out += info.outJump;
-      }
-    }
-    else if (info.inFormat == RTAUDIO_FLOAT64) {
-      Float64 *in = (Float64 *)inBuffer;
-      for (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.0);
-        }
-        in += info.inJump;
-        out += info.outJump;
-      }
-    }
-  }
-}
-
-void RtApi :: byteSwapBuffer( char *buffer, int samples, RtAudioFormat format )
-{
-  register char val;
-  register char *ptr;
-
-  ptr = buffer;
-  if (format == RTAUDIO_SINT16) {
-    for (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 (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 4 bytes.
-      ptr += 4;
-    }
-  }
-  else if (format == RTAUDIO_FLOAT64) {
-    for (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 8 bytes.
-      ptr += 8;
-    }
-  }
-}
+/************************************************************************/\r
+/*! \class RtAudio\r
+    \brief Realtime audio i/o C++ classes.\r
+\r
+    RtAudio provides a common API (Application Programming Interface)\r
+    for realtime audio input/output across Linux (native ALSA, Jack,\r
+    and OSS), Macintosh OS X (CoreAudio and Jack), and Windows\r
+    (DirectSound, ASIO and WASAPI) operating systems.\r
+\r
+    RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/\r
+\r
+    RtAudio: realtime audio i/o C++ classes\r
+    Copyright (c) 2001-2016 Gary P. Scavone\r
+\r
+    Permission is hereby granted, free of charge, to any person\r
+    obtaining a copy of this software and associated documentation files\r
+    (the "Software"), to deal in the Software without restriction,\r
+    including without limitation the rights to use, copy, modify, merge,\r
+    publish, distribute, sublicense, and/or sell copies of the Software,\r
+    and to permit persons to whom the Software is furnished to do so,\r
+    subject to the following conditions:\r
+\r
+    The above copyright notice and this permission notice shall be\r
+    included in all copies or substantial portions of the Software.\r
+\r
+    Any person wishing to distribute modifications to the Software is\r
+    asked to send the modifications to the original developer so that\r
+    they can be incorporated into the canonical version.  This is,\r
+    however, not a binding provision of this license.\r
+\r
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\r
+    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\r
+    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\r
+    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR\r
+    ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\r
+    CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\r
+    WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\r
+*/\r
+/************************************************************************/\r
+\r
+// RtAudio: Version 4.1.2\r
+\r
+#include "RtAudio.h"\r
+#include <iostream>\r
+#include <cstdlib>\r
+#include <cstring>\r
+#include <climits>\r
+#include <algorithm>\r
+\r
+// Static variable definitions.\r
+const unsigned int RtApi::MAX_SAMPLE_RATES = 14;\r
+const unsigned int RtApi::SAMPLE_RATES[] = {\r
+  4000, 5512, 8000, 9600, 11025, 16000, 22050,\r
+  32000, 44100, 48000, 88200, 96000, 176400, 192000\r
+};\r
+\r
+#if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)\r
+  #define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)\r
+  #define MUTEX_DESTROY(A)    DeleteCriticalSection(A)\r
+  #define MUTEX_LOCK(A)       EnterCriticalSection(A)\r
+  #define MUTEX_UNLOCK(A)     LeaveCriticalSection(A)\r
+\r
+  #include "tchar.h"\r
+\r
+  static std::string convertCharPointerToStdString(const char *text)\r
+  {\r
+    return std::string(text);\r
+  }\r
+\r
+  static std::string convertCharPointerToStdString(const wchar_t *text)\r
+  {\r
+    int length = WideCharToMultiByte(CP_UTF8, 0, text, -1, NULL, 0, NULL, NULL);\r
+    std::string s( length-1, '\0' );\r
+    WideCharToMultiByte(CP_UTF8, 0, text, -1, &s[0], length, NULL, NULL);\r
+    return s;\r
+  }\r
+\r
+#elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)\r
+  // pthread API\r
+  #define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)\r
+  #define MUTEX_DESTROY(A)    pthread_mutex_destroy(A)\r
+  #define MUTEX_LOCK(A)       pthread_mutex_lock(A)\r
+  #define MUTEX_UNLOCK(A)     pthread_mutex_unlock(A)\r
+#else\r
+  #define MUTEX_INITIALIZE(A) abs(*A) // dummy definitions\r
+  #define MUTEX_DESTROY(A)    abs(*A) // dummy definitions\r
+#endif\r
+\r
+// *************************************************** //\r
+//\r
+// RtAudio definitions.\r
+//\r
+// *************************************************** //\r
+\r
+std::string RtAudio :: getVersion( void ) throw()\r
+{\r
+  return RTAUDIO_VERSION;\r
+}\r
+\r
+void RtAudio :: getCompiledApi( std::vector<RtAudio::Api> &apis ) throw()\r
+{\r
+  apis.clear();\r
+\r
+  // The order here will control the order of RtAudio's API search in\r
+  // the constructor.\r
+#if defined(__UNIX_JACK__)\r
+  apis.push_back( UNIX_JACK );\r
+#endif\r
+#if defined(__LINUX_ALSA__)\r
+  apis.push_back( LINUX_ALSA );\r
+#endif\r
+#if defined(__LINUX_PULSE__)\r
+  apis.push_back( LINUX_PULSE );\r
+#endif\r
+#if defined(__LINUX_OSS__)\r
+  apis.push_back( LINUX_OSS );\r
+#endif\r
+#if defined(__WINDOWS_ASIO__)\r
+  apis.push_back( WINDOWS_ASIO );\r
+#endif\r
+#if defined(__WINDOWS_WASAPI__)\r
+  apis.push_back( WINDOWS_WASAPI );\r
+#endif\r
+#if defined(__WINDOWS_DS__)\r
+  apis.push_back( WINDOWS_DS );\r
+#endif\r
+#if defined(__MACOSX_CORE__)\r
+  apis.push_back( MACOSX_CORE );\r
+#endif\r
+#if defined(__RTAUDIO_DUMMY__)\r
+  apis.push_back( RTAUDIO_DUMMY );\r
+#endif\r
+}\r
+\r
+void RtAudio :: openRtApi( RtAudio::Api api )\r
+{\r
+  if ( rtapi_ )\r
+    delete rtapi_;\r
+  rtapi_ = 0;\r
+\r
+#if defined(__UNIX_JACK__)\r
+  if ( api == UNIX_JACK )\r
+    rtapi_ = new RtApiJack();\r
+#endif\r
+#if defined(__LINUX_ALSA__)\r
+  if ( api == LINUX_ALSA )\r
+    rtapi_ = new RtApiAlsa();\r
+#endif\r
+#if defined(__LINUX_PULSE__)\r
+  if ( api == LINUX_PULSE )\r
+    rtapi_ = new RtApiPulse();\r
+#endif\r
+#if defined(__LINUX_OSS__)\r
+  if ( api == LINUX_OSS )\r
+    rtapi_ = new RtApiOss();\r
+#endif\r
+#if defined(__WINDOWS_ASIO__)\r
+  if ( api == WINDOWS_ASIO )\r
+    rtapi_ = new RtApiAsio();\r
+#endif\r
+#if defined(__WINDOWS_WASAPI__)\r
+  if ( api == WINDOWS_WASAPI )\r
+    rtapi_ = new RtApiWasapi();\r
+#endif\r
+#if defined(__WINDOWS_DS__)\r
+  if ( api == WINDOWS_DS )\r
+    rtapi_ = new RtApiDs();\r
+#endif\r
+#if defined(__MACOSX_CORE__)\r
+  if ( api == MACOSX_CORE )\r
+    rtapi_ = new RtApiCore();\r
+#endif\r
+#if defined(__RTAUDIO_DUMMY__)\r
+  if ( api == RTAUDIO_DUMMY )\r
+    rtapi_ = new RtApiDummy();\r
+#endif\r
+}\r
+\r
+RtAudio :: RtAudio( RtAudio::Api api )\r
+{\r
+  rtapi_ = 0;\r
+\r
+  if ( api != UNSPECIFIED ) {\r
+    // Attempt to open the specified API.\r
+    openRtApi( api );\r
+    if ( rtapi_ ) return;\r
+\r
+    // No compiled support for specified API value.  Issue a debug\r
+    // warning and continue as if no API was specified.\r
+    std::cerr << "\nRtAudio: no compiled support for specified API argument!\n" << std::endl;\r
+  }\r
+\r
+  // Iterate through the compiled APIs and return as soon as we find\r
+  // one with at least one device or we reach the end of the list.\r
+  std::vector< RtAudio::Api > apis;\r
+  getCompiledApi( apis );\r
+  for ( unsigned int i=0; i<apis.size(); i++ ) {\r
+    openRtApi( apis[i] );\r
+    if ( rtapi_ && rtapi_->getDeviceCount() ) break;\r
+  }\r
+\r
+  if ( rtapi_ ) return;\r
+\r
+  // It should not be possible to get here because the preprocessor\r
+  // definition __RTAUDIO_DUMMY__ is automatically defined if no\r
+  // API-specific definitions are passed to the compiler. But just in\r
+  // case something weird happens, we'll thow an error.\r
+  std::string errorText = "\nRtAudio: no compiled API support found ... critical error!!\n\n";\r
+  throw( RtAudioError( errorText, RtAudioError::UNSPECIFIED ) );\r
+}\r
+\r
+RtAudio :: ~RtAudio() throw()\r
+{\r
+  if ( rtapi_ )\r
+    delete rtapi_;\r
+}\r
+\r
+void RtAudio :: openStream( RtAudio::StreamParameters *outputParameters,\r
+                            RtAudio::StreamParameters *inputParameters,\r
+                            RtAudioFormat format, unsigned int sampleRate,\r
+                            unsigned int *bufferFrames,\r
+                            RtAudioCallback callback, void *userData,\r
+                            RtAudio::StreamOptions *options,\r
+                            RtAudioErrorCallback errorCallback )\r
+{\r
+  return rtapi_->openStream( outputParameters, inputParameters, format,\r
+                             sampleRate, bufferFrames, callback,\r
+                             userData, options, errorCallback );\r
+}\r
+\r
+// *************************************************** //\r
+//\r
+// Public RtApi definitions (see end of file for\r
+// private or protected utility functions).\r
+//\r
+// *************************************************** //\r
+\r
+RtApi :: RtApi()\r
+{\r
+  stream_.state = STREAM_CLOSED;\r
+  stream_.mode = UNINITIALIZED;\r
+  stream_.apiHandle = 0;\r
+  stream_.userBuffer[0] = 0;\r
+  stream_.userBuffer[1] = 0;\r
+  MUTEX_INITIALIZE( &stream_.mutex );\r
+  showWarnings_ = true;\r
+  firstErrorOccurred_ = false;\r
+}\r
+\r
+RtApi :: ~RtApi()\r
+{\r
+  MUTEX_DESTROY( &stream_.mutex );\r
+}\r
+\r
+void RtApi :: openStream( RtAudio::StreamParameters *oParams,\r
+                          RtAudio::StreamParameters *iParams,\r
+                          RtAudioFormat format, unsigned int sampleRate,\r
+                          unsigned int *bufferFrames,\r
+                          RtAudioCallback callback, void *userData,\r
+                          RtAudio::StreamOptions *options,\r
+                          RtAudioErrorCallback errorCallback )\r
+{\r
+  if ( stream_.state != STREAM_CLOSED ) {\r
+    errorText_ = "RtApi::openStream: a stream is already open!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return;\r
+  }\r
+\r
+  // Clear stream information potentially left from a previously open stream.\r
+  clearStreamInfo();\r
+\r
+  if ( oParams && oParams->nChannels < 1 ) {\r
+    errorText_ = "RtApi::openStream: a non-NULL output StreamParameters structure cannot have an nChannels value less than one.";\r
+    error( RtAudioError::INVALID_USE );\r
+    return;\r
+  }\r
+\r
+  if ( iParams && iParams->nChannels < 1 ) {\r
+    errorText_ = "RtApi::openStream: a non-NULL input StreamParameters structure cannot have an nChannels value less than one.";\r
+    error( RtAudioError::INVALID_USE );\r
+    return;\r
+  }\r
+\r
+  if ( oParams == NULL && iParams == NULL ) {\r
+    errorText_ = "RtApi::openStream: input and output StreamParameters structures are both NULL!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return;\r
+  }\r
+\r
+  if ( formatBytes(format) == 0 ) {\r
+    errorText_ = "RtApi::openStream: 'format' parameter value is undefined.";\r
+    error( RtAudioError::INVALID_USE );\r
+    return;\r
+  }\r
+\r
+  unsigned int nDevices = getDeviceCount();\r
+  unsigned int oChannels = 0;\r
+  if ( oParams ) {\r
+    oChannels = oParams->nChannels;\r
+    if ( oParams->deviceId >= nDevices ) {\r
+      errorText_ = "RtApi::openStream: output device parameter value is invalid.";\r
+      error( RtAudioError::INVALID_USE );\r
+      return;\r
+    }\r
+  }\r
+\r
+  unsigned int iChannels = 0;\r
+  if ( iParams ) {\r
+    iChannels = iParams->nChannels;\r
+    if ( iParams->deviceId >= nDevices ) {\r
+      errorText_ = "RtApi::openStream: input device parameter value is invalid.";\r
+      error( RtAudioError::INVALID_USE );\r
+      return;\r
+    }\r
+  }\r
+\r
+  bool result;\r
+\r
+  if ( oChannels > 0 ) {\r
+\r
+    result = probeDeviceOpen( oParams->deviceId, OUTPUT, oChannels, oParams->firstChannel,\r
+                              sampleRate, format, bufferFrames, options );\r
+    if ( result == false ) {\r
+      error( RtAudioError::SYSTEM_ERROR );\r
+      return;\r
+    }\r
+  }\r
+\r
+  if ( iChannels > 0 ) {\r
+\r
+    result = probeDeviceOpen( iParams->deviceId, INPUT, iChannels, iParams->firstChannel,\r
+                              sampleRate, format, bufferFrames, options );\r
+    if ( result == false ) {\r
+      if ( oChannels > 0 ) closeStream();\r
+      error( RtAudioError::SYSTEM_ERROR );\r
+      return;\r
+    }\r
+  }\r
+\r
+  stream_.callbackInfo.callback = (void *) callback;\r
+  stream_.callbackInfo.userData = userData;\r
+  stream_.callbackInfo.errorCallback = (void *) errorCallback;\r
+\r
+  if ( options ) options->numberOfBuffers = stream_.nBuffers;\r
+  stream_.state = STREAM_STOPPED;\r
+}\r
+\r
+unsigned int RtApi :: getDefaultInputDevice( void )\r
+{\r
+  // Should be implemented in subclasses if possible.\r
+  return 0;\r
+}\r
+\r
+unsigned int RtApi :: getDefaultOutputDevice( void )\r
+{\r
+  // Should be implemented in subclasses if possible.\r
+  return 0;\r
+}\r
+\r
+void RtApi :: closeStream( void )\r
+{\r
+  // MUST be implemented in subclasses!\r
+  return;\r
+}\r
+\r
+bool RtApi :: probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,\r
+                               unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,\r
+                               RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,\r
+                               RtAudio::StreamOptions * /*options*/ )\r
+{\r
+  // MUST be implemented in subclasses!\r
+  return FAILURE;\r
+}\r
+\r
+void RtApi :: tickStreamTime( void )\r
+{\r
+  // Subclasses that do not provide their own implementation of\r
+  // getStreamTime should call this function once per buffer I/O to\r
+  // provide basic stream time support.\r
+\r
+  stream_.streamTime += ( stream_.bufferSize * 1.0 / stream_.sampleRate );\r
+\r
+#if defined( HAVE_GETTIMEOFDAY )\r
+  gettimeofday( &stream_.lastTickTimestamp, NULL );\r
+#endif\r
+}\r
+\r
+long RtApi :: getStreamLatency( void )\r
+{\r
+  verifyStream();\r
+\r
+  long totalLatency = 0;\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )\r
+    totalLatency = stream_.latency[0];\r
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX )\r
+    totalLatency += stream_.latency[1];\r
+\r
+  return totalLatency;\r
+}\r
+\r
+double RtApi :: getStreamTime( void )\r
+{\r
+  verifyStream();\r
+\r
+#if defined( HAVE_GETTIMEOFDAY )\r
+  // Return a very accurate estimate of the stream time by\r
+  // adding in the elapsed time since the last tick.\r
+  struct timeval then;\r
+  struct timeval now;\r
+\r
+  if ( stream_.state != STREAM_RUNNING || stream_.streamTime == 0.0 )\r
+    return stream_.streamTime;\r
+\r
+  gettimeofday( &now, NULL );\r
+  then = stream_.lastTickTimestamp;\r
+  return stream_.streamTime +\r
+    ((now.tv_sec + 0.000001 * now.tv_usec) -\r
+     (then.tv_sec + 0.000001 * then.tv_usec));     \r
+#else\r
+  return stream_.streamTime;\r
+#endif\r
+}\r
+\r
+void RtApi :: setStreamTime( double time )\r
+{\r
+  verifyStream();\r
+\r
+  if ( time >= 0.0 )\r
+    stream_.streamTime = time;\r
+}\r
+\r
+unsigned int RtApi :: getStreamSampleRate( void )\r
+{\r
+ verifyStream();\r
+\r
+ return stream_.sampleRate;\r
+}\r
+\r
+\r
+// *************************************************** //\r
+//\r
+// OS/API-specific methods.\r
+//\r
+// *************************************************** //\r
+\r
+#if defined(__MACOSX_CORE__)\r
+\r
+// The OS X CoreAudio API is designed to use a separate callback\r
+// procedure for each of its audio devices.  A single RtAudio duplex\r
+// stream using two different devices is supported here, though it\r
+// cannot be guaranteed to always behave correctly because we cannot\r
+// synchronize these two callbacks.\r
+//\r
+// A property listener is installed for over/underrun information.\r
+// However, no functionality is currently provided to allow property\r
+// listeners to trigger user handlers because it is unclear what could\r
+// be done if a critical stream parameter (buffer size, sample rate,\r
+// device disconnect) notification arrived.  The listeners entail\r
+// quite a bit of extra code and most likely, a user program wouldn't\r
+// be prepared for the result anyway.  However, we do provide a flag\r
+// to the client callback function to inform of an over/underrun.\r
+\r
+// A structure to hold various information related to the CoreAudio API\r
+// implementation.\r
+struct CoreHandle {\r
+  AudioDeviceID id[2];    // device ids\r
+#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )\r
+  AudioDeviceIOProcID procId[2];\r
+#endif\r
+  UInt32 iStream[2];      // device stream index (or first if using multiple)\r
+  UInt32 nStreams[2];     // number of streams to use\r
+  bool xrun[2];\r
+  char *deviceBuffer;\r
+  pthread_cond_t condition;\r
+  int drainCounter;       // Tracks callback counts when draining\r
+  bool internalDrain;     // Indicates if stop is initiated from callback or not.\r
+\r
+  CoreHandle()\r
+    :deviceBuffer(0), drainCounter(0), internalDrain(false) { nStreams[0] = 1; nStreams[1] = 1; id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }\r
+};\r
+\r
+RtApiCore:: RtApiCore()\r
+{\r
+#if defined( AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER )\r
+  // This is a largely undocumented but absolutely necessary\r
+  // requirement starting with OS-X 10.6.  If not called, queries and\r
+  // updates to various audio device properties are not handled\r
+  // correctly.\r
+  CFRunLoopRef theRunLoop = NULL;\r
+  AudioObjectPropertyAddress property = { kAudioHardwarePropertyRunLoop,\r
+                                          kAudioObjectPropertyScopeGlobal,\r
+                                          kAudioObjectPropertyElementMaster };\r
+  OSStatus result = AudioObjectSetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);\r
+  if ( result != noErr ) {\r
+    errorText_ = "RtApiCore::RtApiCore: error setting run loop property!";\r
+    error( RtAudioError::WARNING );\r
+  }\r
+#endif\r
+}\r
+\r
+RtApiCore :: ~RtApiCore()\r
+{\r
+  // The subclass destructor gets called before the base class\r
+  // destructor, so close an existing stream before deallocating\r
+  // apiDeviceId memory.\r
+  if ( stream_.state != STREAM_CLOSED ) closeStream();\r
+}\r
+\r
+unsigned int RtApiCore :: getDeviceCount( void )\r
+{\r
+  // Find out how many audio devices there are, if any.\r
+  UInt32 dataSize;\r
+  AudioObjectPropertyAddress propertyAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };\r
+  OSStatus result = AudioObjectGetPropertyDataSize( kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize );\r
+  if ( result != noErr ) {\r
+    errorText_ = "RtApiCore::getDeviceCount: OS-X error getting device info!";\r
+    error( RtAudioError::WARNING );\r
+    return 0;\r
+  }\r
+\r
+  return dataSize / sizeof( AudioDeviceID );\r
+}\r
+\r
+unsigned int RtApiCore :: getDefaultInputDevice( void )\r
+{\r
+  unsigned int nDevices = getDeviceCount();\r
+  if ( nDevices <= 1 ) return 0;\r
+\r
+  AudioDeviceID id;\r
+  UInt32 dataSize = sizeof( AudioDeviceID );\r
+  AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };\r
+  OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );\r
+  if ( result != noErr ) {\r
+    errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device.";\r
+    error( RtAudioError::WARNING );\r
+    return 0;\r
+  }\r
+\r
+  dataSize *= nDevices;\r
+  AudioDeviceID deviceList[ nDevices ];\r
+  property.mSelector = kAudioHardwarePropertyDevices;\r
+  result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );\r
+  if ( result != noErr ) {\r
+    errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device IDs.";\r
+    error( RtAudioError::WARNING );\r
+    return 0;\r
+  }\r
+\r
+  for ( unsigned int i=0; i<nDevices; i++ )\r
+    if ( id == deviceList[i] ) return i;\r
+\r
+  errorText_ = "RtApiCore::getDefaultInputDevice: No default device found!";\r
+  error( RtAudioError::WARNING );\r
+  return 0;\r
+}\r
+\r
+unsigned int RtApiCore :: getDefaultOutputDevice( void )\r
+{\r
+  unsigned int nDevices = getDeviceCount();\r
+  if ( nDevices <= 1 ) return 0;\r
+\r
+  AudioDeviceID id;\r
+  UInt32 dataSize = sizeof( AudioDeviceID );\r
+  AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };\r
+  OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );\r
+  if ( result != noErr ) {\r
+    errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device.";\r
+    error( RtAudioError::WARNING );\r
+    return 0;\r
+  }\r
+\r
+  dataSize = sizeof( AudioDeviceID ) * nDevices;\r
+  AudioDeviceID deviceList[ nDevices ];\r
+  property.mSelector = kAudioHardwarePropertyDevices;\r
+  result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );\r
+  if ( result != noErr ) {\r
+    errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device IDs.";\r
+    error( RtAudioError::WARNING );\r
+    return 0;\r
+  }\r
+\r
+  for ( unsigned int i=0; i<nDevices; i++ )\r
+    if ( id == deviceList[i] ) return i;\r
+\r
+  errorText_ = "RtApiCore::getDefaultOutputDevice: No default device found!";\r
+  error( RtAudioError::WARNING );\r
+  return 0;\r
+}\r
+\r
+RtAudio::DeviceInfo RtApiCore :: getDeviceInfo( unsigned int device )\r
+{\r
+  RtAudio::DeviceInfo info;\r
+  info.probed = false;\r
+\r
+  // Get device ID\r
+  unsigned int nDevices = getDeviceCount();\r
+  if ( nDevices == 0 ) {\r
+    errorText_ = "RtApiCore::getDeviceInfo: no devices found!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return info;\r
+  }\r
+\r
+  if ( device >= nDevices ) {\r
+    errorText_ = "RtApiCore::getDeviceInfo: device ID is invalid!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return info;\r
+  }\r
+\r
+  AudioDeviceID deviceList[ nDevices ];\r
+  UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;\r
+  AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,\r
+                                          kAudioObjectPropertyScopeGlobal,\r
+                                          kAudioObjectPropertyElementMaster };\r
+  OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,\r
+                                                0, NULL, &dataSize, (void *) &deviceList );\r
+  if ( result != noErr ) {\r
+    errorText_ = "RtApiCore::getDeviceInfo: OS-X system error getting device IDs.";\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  AudioDeviceID id = deviceList[ device ];\r
+\r
+  // Get the device name.\r
+  info.name.erase();\r
+  CFStringRef cfname;\r
+  dataSize = sizeof( CFStringRef );\r
+  property.mSelector = kAudioObjectPropertyManufacturer;\r
+  result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );\r
+  if ( result != noErr ) {\r
+    errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device manufacturer.";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  //const char *mname = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );\r
+  int length = CFStringGetLength(cfname);\r
+  char *mname = (char *)malloc(length * 3 + 1);\r
+#if defined( UNICODE ) || defined( _UNICODE )\r
+  CFStringGetCString(cfname, mname, length * 3 + 1, kCFStringEncodingUTF8);\r
+#else\r
+  CFStringGetCString(cfname, mname, length * 3 + 1, CFStringGetSystemEncoding());\r
+#endif\r
+  info.name.append( (const char *)mname, strlen(mname) );\r
+  info.name.append( ": " );\r
+  CFRelease( cfname );\r
+  free(mname);\r
+\r
+  property.mSelector = kAudioObjectPropertyName;\r
+  result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );\r
+  if ( result != noErr ) {\r
+    errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device name.";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  //const char *name = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );\r
+  length = CFStringGetLength(cfname);\r
+  char *name = (char *)malloc(length * 3 + 1);\r
+#if defined( UNICODE ) || defined( _UNICODE )\r
+  CFStringGetCString(cfname, name, length * 3 + 1, kCFStringEncodingUTF8);\r
+#else\r
+  CFStringGetCString(cfname, name, length * 3 + 1, CFStringGetSystemEncoding());\r
+#endif\r
+  info.name.append( (const char *)name, strlen(name) );\r
+  CFRelease( cfname );\r
+  free(name);\r
+\r
+  // Get the output stream "configuration".\r
+  AudioBufferList      *bufferList = nil;\r
+  property.mSelector = kAudioDevicePropertyStreamConfiguration;\r
+  property.mScope = kAudioDevicePropertyScopeOutput;\r
+  //  property.mElement = kAudioObjectPropertyElementWildcard;\r
+  dataSize = 0;\r
+  result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );\r
+  if ( result != noErr || dataSize == 0 ) {\r
+    errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration info for device (" << device << ").";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // Allocate the AudioBufferList.\r
+  bufferList = (AudioBufferList *) malloc( dataSize );\r
+  if ( bufferList == NULL ) {\r
+    errorText_ = "RtApiCore::getDeviceInfo: memory error allocating output AudioBufferList.";\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );\r
+  if ( result != noErr || dataSize == 0 ) {\r
+    free( bufferList );\r
+    errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration for device (" << device << ").";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // Get output channel information.\r
+  unsigned int i, nStreams = bufferList->mNumberBuffers;\r
+  for ( i=0; i<nStreams; i++ )\r
+    info.outputChannels += bufferList->mBuffers[i].mNumberChannels;\r
+  free( bufferList );\r
+\r
+  // Get the input stream "configuration".\r
+  property.mScope = kAudioDevicePropertyScopeInput;\r
+  result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );\r
+  if ( result != noErr || dataSize == 0 ) {\r
+    errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration info for device (" << device << ").";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // Allocate the AudioBufferList.\r
+  bufferList = (AudioBufferList *) malloc( dataSize );\r
+  if ( bufferList == NULL ) {\r
+    errorText_ = "RtApiCore::getDeviceInfo: memory error allocating input AudioBufferList.";\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );\r
+  if (result != noErr || dataSize == 0) {\r
+    free( bufferList );\r
+    errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration for device (" << device << ").";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // Get input channel information.\r
+  nStreams = bufferList->mNumberBuffers;\r
+  for ( i=0; i<nStreams; i++ )\r
+    info.inputChannels += bufferList->mBuffers[i].mNumberChannels;\r
+  free( bufferList );\r
+\r
+  // If device opens for both playback and capture, we determine the channels.\r
+  if ( info.outputChannels > 0 && info.inputChannels > 0 )\r
+    info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;\r
+\r
+  // Probe the device sample rates.\r
+  bool isInput = false;\r
+  if ( info.outputChannels == 0 ) isInput = true;\r
+\r
+  // Determine the supported sample rates.\r
+  property.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;\r
+  if ( isInput == false ) property.mScope = kAudioDevicePropertyScopeOutput;\r
+  result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );\r
+  if ( result != kAudioHardwareNoError || dataSize == 0 ) {\r
+    errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rate info.";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  UInt32 nRanges = dataSize / sizeof( AudioValueRange );\r
+  AudioValueRange rangeList[ nRanges ];\r
+  result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &rangeList );\r
+  if ( result != kAudioHardwareNoError ) {\r
+    errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rates.";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // The sample rate reporting mechanism is a bit of a mystery.  It\r
+  // seems that it can either return individual rates or a range of\r
+  // rates.  I assume that if the min / max range values are the same,\r
+  // then that represents a single supported rate and if the min / max\r
+  // range values are different, the device supports an arbitrary\r
+  // range of values (though there might be multiple ranges, so we'll\r
+  // use the most conservative range).\r
+  Float64 minimumRate = 1.0, maximumRate = 10000000000.0;\r
+  bool haveValueRange = false;\r
+  info.sampleRates.clear();\r
+  for ( UInt32 i=0; i<nRanges; i++ ) {\r
+    if ( rangeList[i].mMinimum == rangeList[i].mMaximum ) {\r
+      unsigned int tmpSr = (unsigned int) rangeList[i].mMinimum;\r
+      info.sampleRates.push_back( tmpSr );\r
+\r
+      if ( !info.preferredSampleRate || ( tmpSr <= 48000 && tmpSr > info.preferredSampleRate ) )\r
+        info.preferredSampleRate = tmpSr;\r
+\r
+    } else {\r
+      haveValueRange = true;\r
+      if ( rangeList[i].mMinimum > minimumRate ) minimumRate = rangeList[i].mMinimum;\r
+      if ( rangeList[i].mMaximum < maximumRate ) maximumRate = rangeList[i].mMaximum;\r
+    }\r
+  }\r
+\r
+  if ( haveValueRange ) {\r
+    for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
+      if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate ) {\r
+        info.sampleRates.push_back( SAMPLE_RATES[k] );\r
+\r
+        if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )\r
+          info.preferredSampleRate = SAMPLE_RATES[k];\r
+      }\r
+    }\r
+  }\r
+\r
+  // Sort and remove any redundant values\r
+  std::sort( info.sampleRates.begin(), info.sampleRates.end() );\r
+  info.sampleRates.erase( unique( info.sampleRates.begin(), info.sampleRates.end() ), info.sampleRates.end() );\r
+\r
+  if ( info.sampleRates.size() == 0 ) {\r
+    errorStream_ << "RtApiCore::probeDeviceInfo: No supported sample rates found for device (" << device << ").";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // CoreAudio always uses 32-bit floating point data for PCM streams.\r
+  // Thus, any other "physical" formats supported by the device are of\r
+  // no interest to the client.\r
+  info.nativeFormats = RTAUDIO_FLOAT32;\r
+\r
+  if ( info.outputChannels > 0 )\r
+    if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;\r
+  if ( info.inputChannels > 0 )\r
+    if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;\r
+\r
+  info.probed = true;\r
+  return info;\r
+}\r
+\r
+static OSStatus callbackHandler( AudioDeviceID inDevice,\r
+                                 const AudioTimeStamp* /*inNow*/,\r
+                                 const AudioBufferList* inInputData,\r
+                                 const AudioTimeStamp* /*inInputTime*/,\r
+                                 AudioBufferList* outOutputData,\r
+                                 const AudioTimeStamp* /*inOutputTime*/,\r
+                                 void* infoPointer )\r
+{\r
+  CallbackInfo *info = (CallbackInfo *) infoPointer;\r
+\r
+  RtApiCore *object = (RtApiCore *) info->object;\r
+  if ( object->callbackEvent( inDevice, inInputData, outOutputData ) == false )\r
+    return kAudioHardwareUnspecifiedError;\r
+  else\r
+    return kAudioHardwareNoError;\r
+}\r
+\r
+static OSStatus xrunListener( AudioObjectID /*inDevice*/,\r
+                              UInt32 nAddresses,\r
+                              const AudioObjectPropertyAddress properties[],\r
+                              void* handlePointer )\r
+{\r
+  CoreHandle *handle = (CoreHandle *) handlePointer;\r
+  for ( UInt32 i=0; i<nAddresses; i++ ) {\r
+    if ( properties[i].mSelector == kAudioDeviceProcessorOverload ) {\r
+      if ( properties[i].mScope == kAudioDevicePropertyScopeInput )\r
+        handle->xrun[1] = true;\r
+      else\r
+        handle->xrun[0] = true;\r
+    }\r
+  }\r
+\r
+  return kAudioHardwareNoError;\r
+}\r
+\r
+static OSStatus rateListener( AudioObjectID inDevice,\r
+                              UInt32 /*nAddresses*/,\r
+                              const AudioObjectPropertyAddress /*properties*/[],\r
+                              void* ratePointer )\r
+{\r
+  Float64 *rate = (Float64 *) ratePointer;\r
+  UInt32 dataSize = sizeof( Float64 );\r
+  AudioObjectPropertyAddress property = { kAudioDevicePropertyNominalSampleRate,\r
+                                          kAudioObjectPropertyScopeGlobal,\r
+                                          kAudioObjectPropertyElementMaster };\r
+  AudioObjectGetPropertyData( inDevice, &property, 0, NULL, &dataSize, rate );\r
+  return kAudioHardwareNoError;\r
+}\r
+\r
+bool RtApiCore :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,\r
+                                   unsigned int firstChannel, unsigned int sampleRate,\r
+                                   RtAudioFormat format, unsigned int *bufferSize,\r
+                                   RtAudio::StreamOptions *options )\r
+{\r
+  // Get device ID\r
+  unsigned int nDevices = getDeviceCount();\r
+  if ( nDevices == 0 ) {\r
+    // This should not happen because a check is made before this function is called.\r
+    errorText_ = "RtApiCore::probeDeviceOpen: no devices found!";\r
+    return FAILURE;\r
+  }\r
+\r
+  if ( device >= nDevices ) {\r
+    // This should not happen because a check is made before this function is called.\r
+    errorText_ = "RtApiCore::probeDeviceOpen: device ID is invalid!";\r
+    return FAILURE;\r
+  }\r
+\r
+  AudioDeviceID deviceList[ nDevices ];\r
+  UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;\r
+  AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,\r
+                                          kAudioObjectPropertyScopeGlobal,\r
+                                          kAudioObjectPropertyElementMaster };\r
+  OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,\r
+                                                0, NULL, &dataSize, (void *) &deviceList );\r
+  if ( result != noErr ) {\r
+    errorText_ = "RtApiCore::probeDeviceOpen: OS-X system error getting device IDs.";\r
+    return FAILURE;\r
+  }\r
+\r
+  AudioDeviceID id = deviceList[ device ];\r
+\r
+  // Setup for stream mode.\r
+  bool isInput = false;\r
+  if ( mode == INPUT ) {\r
+    isInput = true;\r
+    property.mScope = kAudioDevicePropertyScopeInput;\r
+  }\r
+  else\r
+    property.mScope = kAudioDevicePropertyScopeOutput;\r
+\r
+  // Get the stream "configuration".\r
+  AudioBufferList      *bufferList = nil;\r
+  dataSize = 0;\r
+  property.mSelector = kAudioDevicePropertyStreamConfiguration;\r
+  result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );\r
+  if ( result != noErr || dataSize == 0 ) {\r
+    errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration info for device (" << device << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Allocate the AudioBufferList.\r
+  bufferList = (AudioBufferList *) malloc( dataSize );\r
+  if ( bufferList == NULL ) {\r
+    errorText_ = "RtApiCore::probeDeviceOpen: memory error allocating AudioBufferList.";\r
+    return FAILURE;\r
+  }\r
+\r
+  result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );\r
+  if (result != noErr || dataSize == 0) {\r
+    free( bufferList );\r
+    errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration for device (" << device << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Search for one or more streams that contain the desired number of\r
+  // channels. CoreAudio devices can have an arbitrary number of\r
+  // streams and each stream can have an arbitrary number of channels.\r
+  // For each stream, a single buffer of interleaved samples is\r
+  // provided.  RtAudio prefers the use of one stream of interleaved\r
+  // data or multiple consecutive single-channel streams.  However, we\r
+  // now support multiple consecutive multi-channel streams of\r
+  // interleaved data as well.\r
+  UInt32 iStream, offsetCounter = firstChannel;\r
+  UInt32 nStreams = bufferList->mNumberBuffers;\r
+  bool monoMode = false;\r
+  bool foundStream = false;\r
+\r
+  // First check that the device supports the requested number of\r
+  // channels.\r
+  UInt32 deviceChannels = 0;\r
+  for ( iStream=0; iStream<nStreams; iStream++ )\r
+    deviceChannels += bufferList->mBuffers[iStream].mNumberChannels;\r
+\r
+  if ( deviceChannels < ( channels + firstChannel ) ) {\r
+    free( bufferList );\r
+    errorStream_ << "RtApiCore::probeDeviceOpen: the device (" << device << ") does not support the requested channel count.";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Look for a single stream meeting our needs.\r
+  UInt32 firstStream, streamCount = 1, streamChannels = 0, channelOffset = 0;\r
+  for ( iStream=0; iStream<nStreams; iStream++ ) {\r
+    streamChannels = bufferList->mBuffers[iStream].mNumberChannels;\r
+    if ( streamChannels >= channels + offsetCounter ) {\r
+      firstStream = iStream;\r
+      channelOffset = offsetCounter;\r
+      foundStream = true;\r
+      break;\r
+    }\r
+    if ( streamChannels > offsetCounter ) break;\r
+    offsetCounter -= streamChannels;\r
+  }\r
+\r
+  // If we didn't find a single stream above, then we should be able\r
+  // to meet the channel specification with multiple streams.\r
+  if ( foundStream == false ) {\r
+    monoMode = true;\r
+    offsetCounter = firstChannel;\r
+    for ( iStream=0; iStream<nStreams; iStream++ ) {\r
+      streamChannels = bufferList->mBuffers[iStream].mNumberChannels;\r
+      if ( streamChannels > offsetCounter ) break;\r
+      offsetCounter -= streamChannels;\r
+    }\r
+\r
+    firstStream = iStream;\r
+    channelOffset = offsetCounter;\r
+    Int32 channelCounter = channels + offsetCounter - streamChannels;\r
+\r
+    if ( streamChannels > 1 ) monoMode = false;\r
+    while ( channelCounter > 0 ) {\r
+      streamChannels = bufferList->mBuffers[++iStream].mNumberChannels;\r
+      if ( streamChannels > 1 ) monoMode = false;\r
+      channelCounter -= streamChannels;\r
+      streamCount++;\r
+    }\r
+  }\r
+\r
+  free( bufferList );\r
+\r
+  // Determine the buffer size.\r
+  AudioValueRange      bufferRange;\r
+  dataSize = sizeof( AudioValueRange );\r
+  property.mSelector = kAudioDevicePropertyBufferFrameSizeRange;\r
+  result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &bufferRange );\r
+\r
+  if ( result != noErr ) {\r
+    errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting buffer size range for device (" << device << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  if ( bufferRange.mMinimum > *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMinimum;\r
+  else if ( bufferRange.mMaximum < *bufferSize ) *bufferSize = (unsigned long) bufferRange.mMaximum;\r
+  if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) *bufferSize = (unsigned long) bufferRange.mMinimum;\r
+\r
+  // Set the buffer size.  For multiple streams, I'm assuming we only\r
+  // need to make this setting for the master channel.\r
+  UInt32 theSize = (UInt32) *bufferSize;\r
+  dataSize = sizeof( UInt32 );\r
+  property.mSelector = kAudioDevicePropertyBufferFrameSize;\r
+  result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &theSize );\r
+\r
+  if ( result != noErr ) {\r
+    errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting the buffer size for device (" << device << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // If attempting to setup a duplex stream, the bufferSize parameter\r
+  // MUST be the same in both directions!\r
+  *bufferSize = theSize;\r
+  if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {\r
+    errorStream_ << "RtApiCore::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << device << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  stream_.bufferSize = *bufferSize;\r
+  stream_.nBuffers = 1;\r
+\r
+  // Try to set "hog" mode ... it's not clear to me this is working.\r
+  if ( options && options->flags & RTAUDIO_HOG_DEVICE ) {\r
+    pid_t hog_pid;\r
+    dataSize = sizeof( hog_pid );\r
+    property.mSelector = kAudioDevicePropertyHogMode;\r
+    result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &hog_pid );\r
+    if ( result != noErr ) {\r
+      errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting 'hog' state!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    if ( hog_pid != getpid() ) {\r
+      hog_pid = getpid();\r
+      result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &hog_pid );\r
+      if ( result != noErr ) {\r
+        errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting 'hog' state!";\r
+        errorText_ = errorStream_.str();\r
+        return FAILURE;\r
+      }\r
+    }\r
+  }\r
+\r
+  // Check and if necessary, change the sample rate for the device.\r
+  Float64 nominalRate;\r
+  dataSize = sizeof( Float64 );\r
+  property.mSelector = kAudioDevicePropertyNominalSampleRate;\r
+  result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &nominalRate );\r
+  if ( result != noErr ) {\r
+    errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting current sample rate.";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Only change the sample rate if off by more than 1 Hz.\r
+  if ( fabs( nominalRate - (double)sampleRate ) > 1.0 ) {\r
+\r
+    // Set a property listener for the sample rate change\r
+    Float64 reportedRate = 0.0;\r
+    AudioObjectPropertyAddress tmp = { kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };\r
+    result = AudioObjectAddPropertyListener( id, &tmp, rateListener, (void *) &reportedRate );\r
+    if ( result != noErr ) {\r
+      errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate property listener for device (" << device << ").";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    nominalRate = (Float64) sampleRate;\r
+    result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &nominalRate );\r
+    if ( result != noErr ) {\r
+      AudioObjectRemovePropertyListener( id, &tmp, rateListener, (void *) &reportedRate );\r
+      errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate for device (" << device << ").";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    // Now wait until the reported nominal rate is what we just set.\r
+    UInt32 microCounter = 0;\r
+    while ( reportedRate != nominalRate ) {\r
+      microCounter += 5000;\r
+      if ( microCounter > 5000000 ) break;\r
+      usleep( 5000 );\r
+    }\r
+\r
+    // Remove the property listener.\r
+    AudioObjectRemovePropertyListener( id, &tmp, rateListener, (void *) &reportedRate );\r
+\r
+    if ( microCounter > 5000000 ) {\r
+      errorStream_ << "RtApiCore::probeDeviceOpen: timeout waiting for sample rate update for device (" << device << ").";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+  }\r
+\r
+  // Now set the stream format for all streams.  Also, check the\r
+  // physical format of the device and change that if necessary.\r
+  AudioStreamBasicDescription  description;\r
+  dataSize = sizeof( AudioStreamBasicDescription );\r
+  property.mSelector = kAudioStreamPropertyVirtualFormat;\r
+  result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &description );\r
+  if ( result != noErr ) {\r
+    errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream format for device (" << device << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Set the sample rate and data format id.  However, only make the\r
+  // change if the sample rate is not within 1.0 of the desired\r
+  // rate and the format is not linear pcm.\r
+  bool updateFormat = false;\r
+  if ( fabs( description.mSampleRate - (Float64)sampleRate ) > 1.0 ) {\r
+    description.mSampleRate = (Float64) sampleRate;\r
+    updateFormat = true;\r
+  }\r
+\r
+  if ( description.mFormatID != kAudioFormatLinearPCM ) {\r
+    description.mFormatID = kAudioFormatLinearPCM;\r
+    updateFormat = true;\r
+  }\r
+\r
+  if ( updateFormat ) {\r
+    result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &description );\r
+    if ( result != noErr ) {\r
+      errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting sample rate or data format for device (" << device << ").";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+  }\r
+\r
+  // Now check the physical format.\r
+  property.mSelector = kAudioStreamPropertyPhysicalFormat;\r
+  result = AudioObjectGetPropertyData( id, &property, 0, NULL,  &dataSize, &description );\r
+  if ( result != noErr ) {\r
+    errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream physical format for device (" << device << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  //std::cout << "Current physical stream format:" << std::endl;\r
+  //std::cout << "   mBitsPerChan = " << description.mBitsPerChannel << std::endl;\r
+  //std::cout << "   aligned high = " << (description.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (description.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;\r
+  //std::cout << "   bytesPerFrame = " << description.mBytesPerFrame << std::endl;\r
+  //std::cout << "   sample rate = " << description.mSampleRate << std::endl;\r
+\r
+  if ( description.mFormatID != kAudioFormatLinearPCM || description.mBitsPerChannel < 16 ) {\r
+    description.mFormatID = kAudioFormatLinearPCM;\r
+    //description.mSampleRate = (Float64) sampleRate;\r
+    AudioStreamBasicDescription        testDescription = description;\r
+    UInt32 formatFlags;\r
+\r
+    // We'll try higher bit rates first and then work our way down.\r
+    std::vector< std::pair<UInt32, UInt32>  > physicalFormats;\r
+    formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsFloat) & ~kLinearPCMFormatFlagIsSignedInteger;\r
+    physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );\r
+    formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;\r
+    physicalFormats.push_back( std::pair<Float32, UInt32>( 32, formatFlags ) );\r
+    physicalFormats.push_back( std::pair<Float32, UInt32>( 24, formatFlags ) );   // 24-bit packed\r
+    formatFlags &= ~( kAudioFormatFlagIsPacked | kAudioFormatFlagIsAlignedHigh );\r
+    physicalFormats.push_back( std::pair<Float32, UInt32>( 24.2, formatFlags ) ); // 24-bit in 4 bytes, aligned low\r
+    formatFlags |= kAudioFormatFlagIsAlignedHigh;\r
+    physicalFormats.push_back( std::pair<Float32, UInt32>( 24.4, formatFlags ) ); // 24-bit in 4 bytes, aligned high\r
+    formatFlags = (description.mFormatFlags | kLinearPCMFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked) & ~kLinearPCMFormatFlagIsFloat;\r
+    physicalFormats.push_back( std::pair<Float32, UInt32>( 16, formatFlags ) );\r
+    physicalFormats.push_back( std::pair<Float32, UInt32>( 8, formatFlags ) );\r
+\r
+    bool setPhysicalFormat = false;\r
+    for( unsigned int i=0; i<physicalFormats.size(); i++ ) {\r
+      testDescription = description;\r
+      testDescription.mBitsPerChannel = (UInt32) physicalFormats[i].first;\r
+      testDescription.mFormatFlags = physicalFormats[i].second;\r
+      if ( (24 == (UInt32)physicalFormats[i].first) && ~( physicalFormats[i].second & kAudioFormatFlagIsPacked ) )\r
+        testDescription.mBytesPerFrame =  4 * testDescription.mChannelsPerFrame;\r
+      else\r
+        testDescription.mBytesPerFrame =  testDescription.mBitsPerChannel/8 * testDescription.mChannelsPerFrame;\r
+      testDescription.mBytesPerPacket = testDescription.mBytesPerFrame * testDescription.mFramesPerPacket;\r
+      result = AudioObjectSetPropertyData( id, &property, 0, NULL, dataSize, &testDescription );\r
+      if ( result == noErr ) {\r
+        setPhysicalFormat = true;\r
+        //std::cout << "Updated physical stream format:" << std::endl;\r
+        //std::cout << "   mBitsPerChan = " << testDescription.mBitsPerChannel << std::endl;\r
+        //std::cout << "   aligned high = " << (testDescription.mFormatFlags & kAudioFormatFlagIsAlignedHigh) << ", isPacked = " << (testDescription.mFormatFlags & kAudioFormatFlagIsPacked) << std::endl;\r
+        //std::cout << "   bytesPerFrame = " << testDescription.mBytesPerFrame << std::endl;\r
+        //std::cout << "   sample rate = " << testDescription.mSampleRate << std::endl;\r
+        break;\r
+      }\r
+    }\r
+\r
+    if ( !setPhysicalFormat ) {\r
+      errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") setting physical data format for device (" << device << ").";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+  } // done setting virtual/physical formats.\r
+\r
+  // Get the stream / device latency.\r
+  UInt32 latency;\r
+  dataSize = sizeof( UInt32 );\r
+  property.mSelector = kAudioDevicePropertyLatency;\r
+  if ( AudioObjectHasProperty( id, &property ) == true ) {\r
+    result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &latency );\r
+    if ( result == kAudioHardwareNoError ) stream_.latency[ mode ] = latency;\r
+    else {\r
+      errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting device latency for device (" << device << ").";\r
+      errorText_ = errorStream_.str();\r
+      error( RtAudioError::WARNING );\r
+    }\r
+  }\r
+\r
+  // Byte-swapping: According to AudioHardware.h, the stream data will\r
+  // always be presented in native-endian format, so we should never\r
+  // need to byte swap.\r
+  stream_.doByteSwap[mode] = false;\r
+\r
+  // From the CoreAudio documentation, PCM data must be supplied as\r
+  // 32-bit floats.\r
+  stream_.userFormat = format;\r
+  stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;\r
+\r
+  if ( streamCount == 1 )\r
+    stream_.nDeviceChannels[mode] = description.mChannelsPerFrame;\r
+  else // multiple streams\r
+    stream_.nDeviceChannels[mode] = channels;\r
+  stream_.nUserChannels[mode] = channels;\r
+  stream_.channelOffset[mode] = channelOffset;  // offset within a CoreAudio stream\r
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;\r
+  else stream_.userInterleaved = true;\r
+  stream_.deviceInterleaved[mode] = true;\r
+  if ( monoMode == true ) stream_.deviceInterleaved[mode] = false;\r
+\r
+  // Set flags for buffer conversion.\r
+  stream_.doConvertBuffer[mode] = false;\r
+  if ( stream_.userFormat != stream_.deviceFormat[mode] )\r
+    stream_.doConvertBuffer[mode] = true;\r
+  if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )\r
+    stream_.doConvertBuffer[mode] = true;\r
+  if ( streamCount == 1 ) {\r
+    if ( stream_.nUserChannels[mode] > 1 &&\r
+         stream_.userInterleaved != stream_.deviceInterleaved[mode] )\r
+      stream_.doConvertBuffer[mode] = true;\r
+  }\r
+  else if ( monoMode && stream_.userInterleaved )\r
+    stream_.doConvertBuffer[mode] = true;\r
+\r
+  // Allocate our CoreHandle structure for the stream.\r
+  CoreHandle *handle = 0;\r
+  if ( stream_.apiHandle == 0 ) {\r
+    try {\r
+      handle = new CoreHandle;\r
+    }\r
+    catch ( std::bad_alloc& ) {\r
+      errorText_ = "RtApiCore::probeDeviceOpen: error allocating CoreHandle memory.";\r
+      goto error;\r
+    }\r
+\r
+    if ( pthread_cond_init( &handle->condition, NULL ) ) {\r
+      errorText_ = "RtApiCore::probeDeviceOpen: error initializing pthread condition variable.";\r
+      goto error;\r
+    }\r
+    stream_.apiHandle = (void *) handle;\r
+  }\r
+  else\r
+    handle = (CoreHandle *) stream_.apiHandle;\r
+  handle->iStream[mode] = firstStream;\r
+  handle->nStreams[mode] = streamCount;\r
+  handle->id[mode] = id;\r
+\r
+  // Allocate necessary internal buffers.\r
+  unsigned long bufferBytes;\r
+  bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );\r
+  //  stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );\r
+  stream_.userBuffer[mode] = (char *) malloc( bufferBytes * sizeof(char) );\r
+  memset( stream_.userBuffer[mode], 0, bufferBytes * sizeof(char) );\r
+  if ( stream_.userBuffer[mode] == NULL ) {\r
+    errorText_ = "RtApiCore::probeDeviceOpen: error allocating user buffer memory.";\r
+    goto error;\r
+  }\r
+\r
+  // If possible, we will make use of the CoreAudio stream buffers as\r
+  // "device buffers".  However, we can't do this if using multiple\r
+  // streams.\r
+  if ( stream_.doConvertBuffer[mode] && handle->nStreams[mode] > 1 ) {\r
+\r
+    bool makeBuffer = true;\r
+    bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );\r
+    if ( mode == INPUT ) {\r
+      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {\r
+        unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
+        if ( bufferBytes <= bytesOut ) makeBuffer = false;\r
+      }\r
+    }\r
+\r
+    if ( makeBuffer ) {\r
+      bufferBytes *= *bufferSize;\r
+      if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );\r
+      stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );\r
+      if ( stream_.deviceBuffer == NULL ) {\r
+        errorText_ = "RtApiCore::probeDeviceOpen: error allocating device buffer memory.";\r
+        goto error;\r
+      }\r
+    }\r
+  }\r
+\r
+  stream_.sampleRate = sampleRate;\r
+  stream_.device[mode] = device;\r
+  stream_.state = STREAM_STOPPED;\r
+  stream_.callbackInfo.object = (void *) this;\r
+\r
+  // Setup the buffer conversion information structure.\r
+  if ( stream_.doConvertBuffer[mode] ) {\r
+    if ( streamCount > 1 ) setConvertInfo( mode, 0 );\r
+    else setConvertInfo( mode, channelOffset );\r
+  }\r
+\r
+  if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device )\r
+    // Only one callback procedure per device.\r
+    stream_.mode = DUPLEX;\r
+  else {\r
+#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )\r
+    result = AudioDeviceCreateIOProcID( id, callbackHandler, (void *) &stream_.callbackInfo, &handle->procId[mode] );\r
+#else\r
+    // deprecated in favor of AudioDeviceCreateIOProcID()\r
+    result = AudioDeviceAddIOProc( id, callbackHandler, (void *) &stream_.callbackInfo );\r
+#endif\r
+    if ( result != noErr ) {\r
+      errorStream_ << "RtApiCore::probeDeviceOpen: system error setting callback for device (" << device << ").";\r
+      errorText_ = errorStream_.str();\r
+      goto error;\r
+    }\r
+    if ( stream_.mode == OUTPUT && mode == INPUT )\r
+      stream_.mode = DUPLEX;\r
+    else\r
+      stream_.mode = mode;\r
+  }\r
+\r
+  // Setup the device property listener for over/underload.\r
+  property.mSelector = kAudioDeviceProcessorOverload;\r
+  property.mScope = kAudioObjectPropertyScopeGlobal;\r
+  result = AudioObjectAddPropertyListener( id, &property, xrunListener, (void *) handle );\r
+\r
+  return SUCCESS;\r
+\r
+ error:\r
+  if ( handle ) {\r
+    pthread_cond_destroy( &handle->condition );\r
+    delete handle;\r
+    stream_.apiHandle = 0;\r
+  }\r
+\r
+  for ( int i=0; i<2; i++ ) {\r
+    if ( stream_.userBuffer[i] ) {\r
+      free( stream_.userBuffer[i] );\r
+      stream_.userBuffer[i] = 0;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceBuffer ) {\r
+    free( stream_.deviceBuffer );\r
+    stream_.deviceBuffer = 0;\r
+  }\r
+\r
+  stream_.state = STREAM_CLOSED;\r
+  return FAILURE;\r
+}\r
+\r
+void RtApiCore :: closeStream( void )\r
+{\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiCore::closeStream(): no open stream to close!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  CoreHandle *handle = (CoreHandle *) stream_.apiHandle;\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+    if (handle) {\r
+      AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,\r
+        kAudioObjectPropertyScopeGlobal,\r
+        kAudioObjectPropertyElementMaster };\r
+\r
+      property.mSelector = kAudioDeviceProcessorOverload;\r
+      property.mScope = kAudioObjectPropertyScopeGlobal;\r
+      if (AudioObjectRemovePropertyListener( handle->id[0], &property, xrunListener, (void *) handle ) != noErr) {\r
+        errorText_ = "RtApiCore::closeStream(): error removing property listener!";\r
+        error( RtAudioError::WARNING );\r
+      }\r
+    }\r
+    if ( stream_.state == STREAM_RUNNING )\r
+      AudioDeviceStop( handle->id[0], callbackHandler );\r
+#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )\r
+    AudioDeviceDestroyIOProcID( handle->id[0], handle->procId[0] );\r
+#else\r
+    // deprecated in favor of AudioDeviceDestroyIOProcID()\r
+    AudioDeviceRemoveIOProc( handle->id[0], callbackHandler );\r
+#endif\r
+  }\r
+\r
+  if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {\r
+    if (handle) {\r
+      AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,\r
+        kAudioObjectPropertyScopeGlobal,\r
+        kAudioObjectPropertyElementMaster };\r
+\r
+      property.mSelector = kAudioDeviceProcessorOverload;\r
+      property.mScope = kAudioObjectPropertyScopeGlobal;\r
+      if (AudioObjectRemovePropertyListener( handle->id[1], &property, xrunListener, (void *) handle ) != noErr) {\r
+        errorText_ = "RtApiCore::closeStream(): error removing property listener!";\r
+        error( RtAudioError::WARNING );\r
+      }\r
+    }\r
+    if ( stream_.state == STREAM_RUNNING )\r
+      AudioDeviceStop( handle->id[1], callbackHandler );\r
+#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )\r
+    AudioDeviceDestroyIOProcID( handle->id[1], handle->procId[1] );\r
+#else\r
+    // deprecated in favor of AudioDeviceDestroyIOProcID()\r
+    AudioDeviceRemoveIOProc( handle->id[1], callbackHandler );\r
+#endif\r
+  }\r
+\r
+  for ( int i=0; i<2; i++ ) {\r
+    if ( stream_.userBuffer[i] ) {\r
+      free( stream_.userBuffer[i] );\r
+      stream_.userBuffer[i] = 0;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceBuffer ) {\r
+    free( stream_.deviceBuffer );\r
+    stream_.deviceBuffer = 0;\r
+  }\r
+\r
+  // Destroy pthread condition variable.\r
+  pthread_cond_destroy( &handle->condition );\r
+  delete handle;\r
+  stream_.apiHandle = 0;\r
+\r
+  stream_.mode = UNINITIALIZED;\r
+  stream_.state = STREAM_CLOSED;\r
+}\r
+\r
+void RtApiCore :: startStream( void )\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_RUNNING ) {\r
+    errorText_ = "RtApiCore::startStream(): the stream is already running!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  OSStatus result = noErr;\r
+  CoreHandle *handle = (CoreHandle *) stream_.apiHandle;\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+\r
+    result = AudioDeviceStart( handle->id[0], callbackHandler );\r
+    if ( result != noErr ) {\r
+      errorStream_ << "RtApiCore::startStream: system error (" << getErrorCode( result ) << ") starting callback procedure on device (" << stream_.device[0] << ").";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+  }\r
+\r
+  if ( stream_.mode == INPUT ||\r
+       ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {\r
+\r
+    result = AudioDeviceStart( handle->id[1], callbackHandler );\r
+    if ( result != noErr ) {\r
+      errorStream_ << "RtApiCore::startStream: system error starting input callback procedure on device (" << stream_.device[1] << ").";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+  }\r
+\r
+  handle->drainCounter = 0;\r
+  handle->internalDrain = false;\r
+  stream_.state = STREAM_RUNNING;\r
+\r
+ unlock:\r
+  if ( result == noErr ) return;\r
+  error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiCore :: stopStream( void )\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiCore::stopStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  OSStatus result = noErr;\r
+  CoreHandle *handle = (CoreHandle *) stream_.apiHandle;\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+\r
+    if ( handle->drainCounter == 0 ) {\r
+      handle->drainCounter = 2;\r
+      pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled\r
+    }\r
+\r
+    result = AudioDeviceStop( handle->id[0], callbackHandler );\r
+    if ( result != noErr ) {\r
+      errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping callback procedure on device (" << stream_.device[0] << ").";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+  }\r
+\r
+  if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && stream_.device[0] != stream_.device[1] ) ) {\r
+\r
+    result = AudioDeviceStop( handle->id[1], callbackHandler );\r
+    if ( result != noErr ) {\r
+      errorStream_ << "RtApiCore::stopStream: system error (" << getErrorCode( result ) << ") stopping input callback procedure on device (" << stream_.device[1] << ").";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+  }\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+\r
+ unlock:\r
+  if ( result == noErr ) return;\r
+  error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiCore :: abortStream( void )\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiCore::abortStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  CoreHandle *handle = (CoreHandle *) stream_.apiHandle;\r
+  handle->drainCounter = 2;\r
+\r
+  stopStream();\r
+}\r
+\r
+// This function will be called by a spawned thread when the user\r
+// callback function signals that the stream should be stopped or\r
+// aborted.  It is better to handle it this way because the\r
+// callbackEvent() function probably should return before the AudioDeviceStop()\r
+// function is called.\r
+static void *coreStopStream( void *ptr )\r
+{\r
+  CallbackInfo *info = (CallbackInfo *) ptr;\r
+  RtApiCore *object = (RtApiCore *) info->object;\r
+\r
+  object->stopStream();\r
+  pthread_exit( NULL );\r
+}\r
+\r
+bool RtApiCore :: callbackEvent( AudioDeviceID deviceId,\r
+                                 const AudioBufferList *inBufferList,\r
+                                 const AudioBufferList *outBufferList )\r
+{\r
+  if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
+    error( RtAudioError::WARNING );\r
+    return FAILURE;\r
+  }\r
+\r
+  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;\r
+  CoreHandle *handle = (CoreHandle *) stream_.apiHandle;\r
+\r
+  // Check if we were draining the stream and signal is finished.\r
+  if ( handle->drainCounter > 3 ) {\r
+    ThreadHandle threadId;\r
+\r
+    stream_.state = STREAM_STOPPING;\r
+    if ( handle->internalDrain == true )\r
+      pthread_create( &threadId, NULL, coreStopStream, info );\r
+    else // external call to stopStream()\r
+      pthread_cond_signal( &handle->condition );\r
+    return SUCCESS;\r
+  }\r
+\r
+  AudioDeviceID outputDevice = handle->id[0];\r
+\r
+  // Invoke user callback to get fresh output data UNLESS we are\r
+  // draining stream or duplex mode AND the input/output devices are\r
+  // different AND this function is called for the input device.\r
+  if ( handle->drainCounter == 0 && ( stream_.mode != DUPLEX || deviceId == outputDevice ) ) {\r
+    RtAudioCallback callback = (RtAudioCallback) info->callback;\r
+    double streamTime = getStreamTime();\r
+    RtAudioStreamStatus status = 0;\r
+    if ( stream_.mode != INPUT && handle->xrun[0] == true ) {\r
+      status |= RTAUDIO_OUTPUT_UNDERFLOW;\r
+      handle->xrun[0] = false;\r
+    }\r
+    if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {\r
+      status |= RTAUDIO_INPUT_OVERFLOW;\r
+      handle->xrun[1] = false;\r
+    }\r
+\r
+    int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
+                                  stream_.bufferSize, streamTime, status, info->userData );\r
+    if ( cbReturnValue == 2 ) {\r
+      stream_.state = STREAM_STOPPING;\r
+      handle->drainCounter = 2;\r
+      abortStream();\r
+      return SUCCESS;\r
+    }\r
+    else if ( cbReturnValue == 1 ) {\r
+      handle->drainCounter = 1;\r
+      handle->internalDrain = true;\r
+    }\r
+  }\r
+\r
+  if ( stream_.mode == OUTPUT || ( stream_.mode == DUPLEX && deviceId == outputDevice ) ) {\r
+\r
+    if ( handle->drainCounter > 1 ) { // write zeros to the output stream\r
+\r
+      if ( handle->nStreams[0] == 1 ) {\r
+        memset( outBufferList->mBuffers[handle->iStream[0]].mData,\r
+                0,\r
+                outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );\r
+      }\r
+      else { // fill multiple streams with zeros\r
+        for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {\r
+          memset( outBufferList->mBuffers[handle->iStream[0]+i].mData,\r
+                  0,\r
+                  outBufferList->mBuffers[handle->iStream[0]+i].mDataByteSize );\r
+        }\r
+      }\r
+    }\r
+    else if ( handle->nStreams[0] == 1 ) {\r
+      if ( stream_.doConvertBuffer[0] ) { // convert directly to CoreAudio stream buffer\r
+        convertBuffer( (char *) outBufferList->mBuffers[handle->iStream[0]].mData,\r
+                       stream_.userBuffer[0], stream_.convertInfo[0] );\r
+      }\r
+      else { // copy from user buffer\r
+        memcpy( outBufferList->mBuffers[handle->iStream[0]].mData,\r
+                stream_.userBuffer[0],\r
+                outBufferList->mBuffers[handle->iStream[0]].mDataByteSize );\r
+      }\r
+    }\r
+    else { // fill multiple streams\r
+      Float32 *inBuffer = (Float32 *) stream_.userBuffer[0];\r
+      if ( stream_.doConvertBuffer[0] ) {\r
+        convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );\r
+        inBuffer = (Float32 *) stream_.deviceBuffer;\r
+      }\r
+\r
+      if ( stream_.deviceInterleaved[0] == false ) { // mono mode\r
+        UInt32 bufferBytes = outBufferList->mBuffers[handle->iStream[0]].mDataByteSize;\r
+        for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {\r
+          memcpy( outBufferList->mBuffers[handle->iStream[0]+i].mData,\r
+                  (void *)&inBuffer[i*stream_.bufferSize], bufferBytes );\r
+        }\r
+      }\r
+      else { // fill multiple multi-channel streams with interleaved data\r
+        UInt32 streamChannels, channelsLeft, inJump, outJump, inOffset;\r
+        Float32 *out, *in;\r
+\r
+        bool inInterleaved = ( stream_.userInterleaved ) ? true : false;\r
+        UInt32 inChannels = stream_.nUserChannels[0];\r
+        if ( stream_.doConvertBuffer[0] ) {\r
+          inInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode\r
+          inChannels = stream_.nDeviceChannels[0];\r
+        }\r
+\r
+        if ( inInterleaved ) inOffset = 1;\r
+        else inOffset = stream_.bufferSize;\r
+\r
+        channelsLeft = inChannels;\r
+        for ( unsigned int i=0; i<handle->nStreams[0]; i++ ) {\r
+          in = inBuffer;\r
+          out = (Float32 *) outBufferList->mBuffers[handle->iStream[0]+i].mData;\r
+          streamChannels = outBufferList->mBuffers[handle->iStream[0]+i].mNumberChannels;\r
+\r
+          outJump = 0;\r
+          // Account for possible channel offset in first stream\r
+          if ( i == 0 && stream_.channelOffset[0] > 0 ) {\r
+            streamChannels -= stream_.channelOffset[0];\r
+            outJump = stream_.channelOffset[0];\r
+            out += outJump;\r
+          }\r
+\r
+          // Account for possible unfilled channels at end of the last stream\r
+          if ( streamChannels > channelsLeft ) {\r
+            outJump = streamChannels - channelsLeft;\r
+            streamChannels = channelsLeft;\r
+          }\r
+\r
+          // Determine input buffer offsets and skips\r
+          if ( inInterleaved ) {\r
+            inJump = inChannels;\r
+            in += inChannels - channelsLeft;\r
+          }\r
+          else {\r
+            inJump = 1;\r
+            in += (inChannels - channelsLeft) * inOffset;\r
+          }\r
+\r
+          for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {\r
+            for ( unsigned int j=0; j<streamChannels; j++ ) {\r
+              *out++ = in[j*inOffset];\r
+            }\r
+            out += outJump;\r
+            in += inJump;\r
+          }\r
+          channelsLeft -= streamChannels;\r
+        }\r
+      }\r
+    }\r
+  }\r
+\r
+  // Don't bother draining input\r
+  if ( handle->drainCounter ) {\r
+    handle->drainCounter++;\r
+    goto unlock;\r
+  }\r
+\r
+  AudioDeviceID inputDevice;\r
+  inputDevice = handle->id[1];\r
+  if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && deviceId == inputDevice ) ) {\r
+\r
+    if ( handle->nStreams[1] == 1 ) {\r
+      if ( stream_.doConvertBuffer[1] ) { // convert directly from CoreAudio stream buffer\r
+        convertBuffer( stream_.userBuffer[1],\r
+                       (char *) inBufferList->mBuffers[handle->iStream[1]].mData,\r
+                       stream_.convertInfo[1] );\r
+      }\r
+      else { // copy to user buffer\r
+        memcpy( stream_.userBuffer[1],\r
+                inBufferList->mBuffers[handle->iStream[1]].mData,\r
+                inBufferList->mBuffers[handle->iStream[1]].mDataByteSize );\r
+      }\r
+    }\r
+    else { // read from multiple streams\r
+      Float32 *outBuffer = (Float32 *) stream_.userBuffer[1];\r
+      if ( stream_.doConvertBuffer[1] ) outBuffer = (Float32 *) stream_.deviceBuffer;\r
+\r
+      if ( stream_.deviceInterleaved[1] == false ) { // mono mode\r
+        UInt32 bufferBytes = inBufferList->mBuffers[handle->iStream[1]].mDataByteSize;\r
+        for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {\r
+          memcpy( (void *)&outBuffer[i*stream_.bufferSize],\r
+                  inBufferList->mBuffers[handle->iStream[1]+i].mData, bufferBytes );\r
+        }\r
+      }\r
+      else { // read from multiple multi-channel streams\r
+        UInt32 streamChannels, channelsLeft, inJump, outJump, outOffset;\r
+        Float32 *out, *in;\r
+\r
+        bool outInterleaved = ( stream_.userInterleaved ) ? true : false;\r
+        UInt32 outChannels = stream_.nUserChannels[1];\r
+        if ( stream_.doConvertBuffer[1] ) {\r
+          outInterleaved = true; // device buffer will always be interleaved for nStreams > 1 and not mono mode\r
+          outChannels = stream_.nDeviceChannels[1];\r
+        }\r
+\r
+        if ( outInterleaved ) outOffset = 1;\r
+        else outOffset = stream_.bufferSize;\r
+\r
+        channelsLeft = outChannels;\r
+        for ( unsigned int i=0; i<handle->nStreams[1]; i++ ) {\r
+          out = outBuffer;\r
+          in = (Float32 *) inBufferList->mBuffers[handle->iStream[1]+i].mData;\r
+          streamChannels = inBufferList->mBuffers[handle->iStream[1]+i].mNumberChannels;\r
+\r
+          inJump = 0;\r
+          // Account for possible channel offset in first stream\r
+          if ( i == 0 && stream_.channelOffset[1] > 0 ) {\r
+            streamChannels -= stream_.channelOffset[1];\r
+            inJump = stream_.channelOffset[1];\r
+            in += inJump;\r
+          }\r
+\r
+          // Account for possible unread channels at end of the last stream\r
+          if ( streamChannels > channelsLeft ) {\r
+            inJump = streamChannels - channelsLeft;\r
+            streamChannels = channelsLeft;\r
+          }\r
+\r
+          // Determine output buffer offsets and skips\r
+          if ( outInterleaved ) {\r
+            outJump = outChannels;\r
+            out += outChannels - channelsLeft;\r
+          }\r
+          else {\r
+            outJump = 1;\r
+            out += (outChannels - channelsLeft) * outOffset;\r
+          }\r
+\r
+          for ( unsigned int i=0; i<stream_.bufferSize; i++ ) {\r
+            for ( unsigned int j=0; j<streamChannels; j++ ) {\r
+              out[j*outOffset] = *in++;\r
+            }\r
+            out += outJump;\r
+            in += inJump;\r
+          }\r
+          channelsLeft -= streamChannels;\r
+        }\r
+      }\r
+      \r
+      if ( stream_.doConvertBuffer[1] ) { // convert from our internal "device" buffer\r
+        convertBuffer( stream_.userBuffer[1],\r
+                       stream_.deviceBuffer,\r
+                       stream_.convertInfo[1] );\r
+      }\r
+    }\r
+  }\r
+\r
+ unlock:\r
+  //MUTEX_UNLOCK( &stream_.mutex );\r
+\r
+  RtApi::tickStreamTime();\r
+  return SUCCESS;\r
+}\r
+\r
+const char* RtApiCore :: getErrorCode( OSStatus code )\r
+{\r
+  switch( code ) {\r
+\r
+  case kAudioHardwareNotRunningError:\r
+    return "kAudioHardwareNotRunningError";\r
+\r
+  case kAudioHardwareUnspecifiedError:\r
+    return "kAudioHardwareUnspecifiedError";\r
+\r
+  case kAudioHardwareUnknownPropertyError:\r
+    return "kAudioHardwareUnknownPropertyError";\r
+\r
+  case kAudioHardwareBadPropertySizeError:\r
+    return "kAudioHardwareBadPropertySizeError";\r
+\r
+  case kAudioHardwareIllegalOperationError:\r
+    return "kAudioHardwareIllegalOperationError";\r
+\r
+  case kAudioHardwareBadObjectError:\r
+    return "kAudioHardwareBadObjectError";\r
+\r
+  case kAudioHardwareBadDeviceError:\r
+    return "kAudioHardwareBadDeviceError";\r
+\r
+  case kAudioHardwareBadStreamError:\r
+    return "kAudioHardwareBadStreamError";\r
+\r
+  case kAudioHardwareUnsupportedOperationError:\r
+    return "kAudioHardwareUnsupportedOperationError";\r
+\r
+  case kAudioDeviceUnsupportedFormatError:\r
+    return "kAudioDeviceUnsupportedFormatError";\r
+\r
+  case kAudioDevicePermissionsError:\r
+    return "kAudioDevicePermissionsError";\r
+\r
+  default:\r
+    return "CoreAudio unknown error";\r
+  }\r
+}\r
+\r
+  //******************** End of __MACOSX_CORE__ *********************//\r
+#endif\r
+\r
+#if defined(__UNIX_JACK__)\r
+\r
+// JACK is a low-latency audio server, originally written for the\r
+// GNU/Linux operating system and now also ported to OS-X. It can\r
+// connect a number of different applications to an audio device, as\r
+// well as allowing them to share audio between themselves.\r
+//\r
+// When using JACK with RtAudio, "devices" refer to JACK clients that\r
+// have ports connected to the server.  The JACK server is typically\r
+// started in a terminal as follows:\r
+//\r
+// .jackd -d alsa -d hw:0\r
+//\r
+// or through an interface program such as qjackctl.  Many of the\r
+// parameters normally set for a stream are fixed by the JACK server\r
+// and can be specified when the JACK server is started.  In\r
+// particular,\r
+//\r
+// .jackd -d alsa -d hw:0 -r 44100 -p 512 -n 4\r
+//\r
+// specifies a sample rate of 44100 Hz, a buffer size of 512 sample\r
+// frames, and number of buffers = 4.  Once the server is running, it\r
+// is not possible to override these values.  If the values are not\r
+// specified in the command-line, the JACK server uses default values.\r
+//\r
+// The JACK server does not have to be running when an instance of\r
+// RtApiJack is created, though the function getDeviceCount() will\r
+// report 0 devices found until JACK has been started.  When no\r
+// devices are available (i.e., the JACK server is not running), a\r
+// stream cannot be opened.\r
+\r
+#include <jack/jack.h>\r
+#include <unistd.h>\r
+#include <cstdio>\r
+\r
+// A structure to hold various information related to the Jack API\r
+// implementation.\r
+struct JackHandle {\r
+  jack_client_t *client;\r
+  jack_port_t **ports[2];\r
+  std::string deviceName[2];\r
+  bool xrun[2];\r
+  pthread_cond_t condition;\r
+  int drainCounter;       // Tracks callback counts when draining\r
+  bool internalDrain;     // Indicates if stop is initiated from callback or not.\r
+\r
+  JackHandle()\r
+    :client(0), drainCounter(0), internalDrain(false) { ports[0] = 0; ports[1] = 0; xrun[0] = false; xrun[1] = false; }\r
+};\r
+\r
+static void jackSilentError( const char * ) {};\r
+\r
+RtApiJack :: RtApiJack()\r
+{\r
+  // Nothing to do here.\r
+#if !defined(__RTAUDIO_DEBUG__)\r
+  // Turn off Jack's internal error reporting.\r
+  jack_set_error_function( &jackSilentError );\r
+#endif\r
+}\r
+\r
+RtApiJack :: ~RtApiJack()\r
+{\r
+  if ( stream_.state != STREAM_CLOSED ) closeStream();\r
+}\r
+\r
+unsigned int RtApiJack :: getDeviceCount( void )\r
+{\r
+  // See if we can become a jack client.\r
+  jack_options_t options = (jack_options_t) ( JackNoStartServer ); //JackNullOption;\r
+  jack_status_t *status = NULL;\r
+  jack_client_t *client = jack_client_open( "RtApiJackCount", options, status );\r
+  if ( client == 0 ) return 0;\r
+\r
+  const char **ports;\r
+  std::string port, previousPort;\r
+  unsigned int nChannels = 0, nDevices = 0;\r
+  ports = jack_get_ports( client, NULL, NULL, 0 );\r
+  if ( ports ) {\r
+    // Parse the port names up to the first colon (:).\r
+    size_t iColon = 0;\r
+    do {\r
+      port = (char *) ports[ nChannels ];\r
+      iColon = port.find(":");\r
+      if ( iColon != std::string::npos ) {\r
+        port = port.substr( 0, iColon + 1 );\r
+        if ( port != previousPort ) {\r
+          nDevices++;\r
+          previousPort = port;\r
+        }\r
+      }\r
+    } while ( ports[++nChannels] );\r
+    free( ports );\r
+  }\r
+\r
+  jack_client_close( client );\r
+  return nDevices;\r
+}\r
+\r
+RtAudio::DeviceInfo RtApiJack :: getDeviceInfo( unsigned int device )\r
+{\r
+  RtAudio::DeviceInfo info;\r
+  info.probed = false;\r
+\r
+  jack_options_t options = (jack_options_t) ( JackNoStartServer ); //JackNullOption\r
+  jack_status_t *status = NULL;\r
+  jack_client_t *client = jack_client_open( "RtApiJackInfo", options, status );\r
+  if ( client == 0 ) {\r
+    errorText_ = "RtApiJack::getDeviceInfo: Jack server not found or connection error!";\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  const char **ports;\r
+  std::string port, previousPort;\r
+  unsigned int nPorts = 0, nDevices = 0;\r
+  ports = jack_get_ports( client, NULL, NULL, 0 );\r
+  if ( ports ) {\r
+    // Parse the port names up to the first colon (:).\r
+    size_t iColon = 0;\r
+    do {\r
+      port = (char *) ports[ nPorts ];\r
+      iColon = port.find(":");\r
+      if ( iColon != std::string::npos ) {\r
+        port = port.substr( 0, iColon );\r
+        if ( port != previousPort ) {\r
+          if ( nDevices == device ) info.name = port;\r
+          nDevices++;\r
+          previousPort = port;\r
+        }\r
+      }\r
+    } while ( ports[++nPorts] );\r
+    free( ports );\r
+  }\r
+\r
+  if ( device >= nDevices ) {\r
+    jack_client_close( client );\r
+    errorText_ = "RtApiJack::getDeviceInfo: device ID is invalid!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return info;\r
+  }\r
+\r
+  // Get the current jack server sample rate.\r
+  info.sampleRates.clear();\r
+\r
+  info.preferredSampleRate = jack_get_sample_rate( client );\r
+  info.sampleRates.push_back( info.preferredSampleRate );\r
+\r
+  // Count the available ports containing the client name as device\r
+  // channels.  Jack "input ports" equal RtAudio output channels.\r
+  unsigned int nChannels = 0;\r
+  ports = jack_get_ports( client, info.name.c_str(), NULL, JackPortIsInput );\r
+  if ( ports ) {\r
+    while ( ports[ nChannels ] ) nChannels++;\r
+    free( ports );\r
+    info.outputChannels = nChannels;\r
+  }\r
+\r
+  // Jack "output ports" equal RtAudio input channels.\r
+  nChannels = 0;\r
+  ports = jack_get_ports( client, info.name.c_str(), NULL, JackPortIsOutput );\r
+  if ( ports ) {\r
+    while ( ports[ nChannels ] ) nChannels++;\r
+    free( ports );\r
+    info.inputChannels = nChannels;\r
+  }\r
+\r
+  if ( info.outputChannels == 0 && info.inputChannels == 0 ) {\r
+    jack_client_close(client);\r
+    errorText_ = "RtApiJack::getDeviceInfo: error determining Jack input/output channels!";\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // If device opens for both playback and capture, we determine the channels.\r
+  if ( info.outputChannels > 0 && info.inputChannels > 0 )\r
+    info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;\r
+\r
+  // Jack always uses 32-bit floats.\r
+  info.nativeFormats = RTAUDIO_FLOAT32;\r
+\r
+  // Jack doesn't provide default devices so we'll use the first available one.\r
+  if ( device == 0 && info.outputChannels > 0 )\r
+    info.isDefaultOutput = true;\r
+  if ( device == 0 && info.inputChannels > 0 )\r
+    info.isDefaultInput = true;\r
+\r
+  jack_client_close(client);\r
+  info.probed = true;\r
+  return info;\r
+}\r
+\r
+static int jackCallbackHandler( jack_nframes_t nframes, void *infoPointer )\r
+{\r
+  CallbackInfo *info = (CallbackInfo *) infoPointer;\r
+\r
+  RtApiJack *object = (RtApiJack *) info->object;\r
+  if ( object->callbackEvent( (unsigned long) nframes ) == false ) return 1;\r
+\r
+  return 0;\r
+}\r
+\r
+// This function will be called by a spawned thread when the Jack\r
+// server signals that it is shutting down.  It is necessary to handle\r
+// it this way because the jackShutdown() function must return before\r
+// the jack_deactivate() function (in closeStream()) will return.\r
+static void *jackCloseStream( void *ptr )\r
+{\r
+  CallbackInfo *info = (CallbackInfo *) ptr;\r
+  RtApiJack *object = (RtApiJack *) info->object;\r
+\r
+  object->closeStream();\r
+\r
+  pthread_exit( NULL );\r
+}\r
+static void jackShutdown( void *infoPointer )\r
+{\r
+  CallbackInfo *info = (CallbackInfo *) infoPointer;\r
+  RtApiJack *object = (RtApiJack *) info->object;\r
+\r
+  // Check current stream state.  If stopped, then we'll assume this\r
+  // was called as a result of a call to RtApiJack::stopStream (the\r
+  // deactivation of a client handle causes this function to be called).\r
+  // If not, we'll assume the Jack server is shutting down or some\r
+  // other problem occurred and we should close the stream.\r
+  if ( object->isStreamRunning() == false ) return;\r
+\r
+  ThreadHandle threadId;\r
+  pthread_create( &threadId, NULL, jackCloseStream, info );\r
+  std::cerr << "\nRtApiJack: the Jack server is shutting down this client ... stream stopped and closed!!\n" << std::endl;\r
+}\r
+\r
+static int jackXrun( void *infoPointer )\r
+{\r
+  JackHandle *handle = (JackHandle *) infoPointer;\r
+\r
+  if ( handle->ports[0] ) handle->xrun[0] = true;\r
+  if ( handle->ports[1] ) handle->xrun[1] = true;\r
+\r
+  return 0;\r
+}\r
+\r
+bool RtApiJack :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,\r
+                                   unsigned int firstChannel, unsigned int sampleRate,\r
+                                   RtAudioFormat format, unsigned int *bufferSize,\r
+                                   RtAudio::StreamOptions *options )\r
+{\r
+  JackHandle *handle = (JackHandle *) stream_.apiHandle;\r
+\r
+  // Look for jack server and try to become a client (only do once per stream).\r
+  jack_client_t *client = 0;\r
+  if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) {\r
+    jack_options_t jackoptions = (jack_options_t) ( JackNoStartServer ); //JackNullOption;\r
+    jack_status_t *status = NULL;\r
+    if ( options && !options->streamName.empty() )\r
+      client = jack_client_open( options->streamName.c_str(), jackoptions, status );\r
+    else\r
+      client = jack_client_open( "RtApiJack", jackoptions, status );\r
+    if ( client == 0 ) {\r
+      errorText_ = "RtApiJack::probeDeviceOpen: Jack server not found or connection error!";\r
+      error( RtAudioError::WARNING );\r
+      return FAILURE;\r
+    }\r
+  }\r
+  else {\r
+    // The handle must have been created on an earlier pass.\r
+    client = handle->client;\r
+  }\r
+\r
+  const char **ports;\r
+  std::string port, previousPort, deviceName;\r
+  unsigned int nPorts = 0, nDevices = 0;\r
+  ports = jack_get_ports( client, NULL, NULL, 0 );\r
+  if ( ports ) {\r
+    // Parse the port names up to the first colon (:).\r
+    size_t iColon = 0;\r
+    do {\r
+      port = (char *) ports[ nPorts ];\r
+      iColon = port.find(":");\r
+      if ( iColon != std::string::npos ) {\r
+        port = port.substr( 0, iColon );\r
+        if ( port != previousPort ) {\r
+          if ( nDevices == device ) deviceName = port;\r
+          nDevices++;\r
+          previousPort = port;\r
+        }\r
+      }\r
+    } while ( ports[++nPorts] );\r
+    free( ports );\r
+  }\r
+\r
+  if ( device >= nDevices ) {\r
+    errorText_ = "RtApiJack::probeDeviceOpen: device ID is invalid!";\r
+    return FAILURE;\r
+  }\r
+\r
+  // Count the available ports containing the client name as device\r
+  // channels.  Jack "input ports" equal RtAudio output channels.\r
+  unsigned int nChannels = 0;\r
+  unsigned long flag = JackPortIsInput;\r
+  if ( mode == INPUT ) flag = JackPortIsOutput;\r
+  ports = jack_get_ports( client, deviceName.c_str(), NULL, flag );\r
+  if ( ports ) {\r
+    while ( ports[ nChannels ] ) nChannels++;\r
+    free( ports );\r
+  }\r
+\r
+  // Compare the jack ports for specified client to the requested number of channels.\r
+  if ( nChannels < (channels + firstChannel) ) {\r
+    errorStream_ << "RtApiJack::probeDeviceOpen: requested number of channels (" << channels << ") + offset (" << firstChannel << ") not found for specified device (" << device << ":" << deviceName << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Check the jack server sample rate.\r
+  unsigned int jackRate = jack_get_sample_rate( client );\r
+  if ( sampleRate != jackRate ) {\r
+    jack_client_close( client );\r
+    errorStream_ << "RtApiJack::probeDeviceOpen: the requested sample rate (" << sampleRate << ") is different than the JACK server rate (" << jackRate << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+  stream_.sampleRate = jackRate;\r
+\r
+  // Get the latency of the JACK port.\r
+  ports = jack_get_ports( client, deviceName.c_str(), NULL, flag );\r
+  if ( ports[ firstChannel ] ) {\r
+    // Added by Ge Wang\r
+    jack_latency_callback_mode_t cbmode = (mode == INPUT ? JackCaptureLatency : JackPlaybackLatency);\r
+    // the range (usually the min and max are equal)\r
+    jack_latency_range_t latrange; latrange.min = latrange.max = 0;\r
+    // get the latency range\r
+    jack_port_get_latency_range( jack_port_by_name( client, ports[firstChannel] ), cbmode, &latrange );\r
+    // be optimistic, use the min!\r
+    stream_.latency[mode] = latrange.min;\r
+    //stream_.latency[mode] = jack_port_get_latency( jack_port_by_name( client, ports[ firstChannel ] ) );\r
+  }\r
+  free( ports );\r
+\r
+  // The jack server always uses 32-bit floating-point data.\r
+  stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;\r
+  stream_.userFormat = format;\r
+\r
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;\r
+  else stream_.userInterleaved = true;\r
+\r
+  // Jack always uses non-interleaved buffers.\r
+  stream_.deviceInterleaved[mode] = false;\r
+\r
+  // Jack always provides host byte-ordered data.\r
+  stream_.doByteSwap[mode] = false;\r
+\r
+  // Get the buffer size.  The buffer size and number of buffers\r
+  // (periods) is set when the jack server is started.\r
+  stream_.bufferSize = (int) jack_get_buffer_size( client );\r
+  *bufferSize = stream_.bufferSize;\r
+\r
+  stream_.nDeviceChannels[mode] = channels;\r
+  stream_.nUserChannels[mode] = channels;\r
+\r
+  // Set flags for buffer conversion.\r
+  stream_.doConvertBuffer[mode] = false;\r
+  if ( stream_.userFormat != stream_.deviceFormat[mode] )\r
+    stream_.doConvertBuffer[mode] = true;\r
+  if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&\r
+       stream_.nUserChannels[mode] > 1 )\r
+    stream_.doConvertBuffer[mode] = true;\r
+\r
+  // Allocate our JackHandle structure for the stream.\r
+  if ( handle == 0 ) {\r
+    try {\r
+      handle = new JackHandle;\r
+    }\r
+    catch ( std::bad_alloc& ) {\r
+      errorText_ = "RtApiJack::probeDeviceOpen: error allocating JackHandle memory.";\r
+      goto error;\r
+    }\r
+\r
+    if ( pthread_cond_init(&handle->condition, NULL) ) {\r
+      errorText_ = "RtApiJack::probeDeviceOpen: error initializing pthread condition variable.";\r
+      goto error;\r
+    }\r
+    stream_.apiHandle = (void *) handle;\r
+    handle->client = client;\r
+  }\r
+  handle->deviceName[mode] = deviceName;\r
+\r
+  // Allocate necessary internal buffers.\r
+  unsigned long bufferBytes;\r
+  bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );\r
+  stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );\r
+  if ( stream_.userBuffer[mode] == NULL ) {\r
+    errorText_ = "RtApiJack::probeDeviceOpen: error allocating user buffer memory.";\r
+    goto error;\r
+  }\r
+\r
+  if ( stream_.doConvertBuffer[mode] ) {\r
+\r
+    bool makeBuffer = true;\r
+    if ( mode == OUTPUT )\r
+      bufferBytes = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
+    else { // mode == INPUT\r
+      bufferBytes = stream_.nDeviceChannels[1] * formatBytes( stream_.deviceFormat[1] );\r
+      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {\r
+        unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes(stream_.deviceFormat[0]);\r
+        if ( bufferBytes < bytesOut ) makeBuffer = false;\r
+      }\r
+    }\r
+\r
+    if ( makeBuffer ) {\r
+      bufferBytes *= *bufferSize;\r
+      if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );\r
+      stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );\r
+      if ( stream_.deviceBuffer == NULL ) {\r
+        errorText_ = "RtApiJack::probeDeviceOpen: error allocating device buffer memory.";\r
+        goto error;\r
+      }\r
+    }\r
+  }\r
+\r
+  // Allocate memory for the Jack ports (channels) identifiers.\r
+  handle->ports[mode] = (jack_port_t **) malloc ( sizeof (jack_port_t *) * channels );\r
+  if ( handle->ports[mode] == NULL )  {\r
+    errorText_ = "RtApiJack::probeDeviceOpen: error allocating port memory.";\r
+    goto error;\r
+  }\r
+\r
+  stream_.device[mode] = device;\r
+  stream_.channelOffset[mode] = firstChannel;\r
+  stream_.state = STREAM_STOPPED;\r
+  stream_.callbackInfo.object = (void *) this;\r
+\r
+  if ( stream_.mode == OUTPUT && mode == INPUT )\r
+    // We had already set up the stream for output.\r
+    stream_.mode = DUPLEX;\r
+  else {\r
+    stream_.mode = mode;\r
+    jack_set_process_callback( handle->client, jackCallbackHandler, (void *) &stream_.callbackInfo );\r
+    jack_set_xrun_callback( handle->client, jackXrun, (void *) &handle );\r
+    jack_on_shutdown( handle->client, jackShutdown, (void *) &stream_.callbackInfo );\r
+  }\r
+\r
+  // Register our ports.\r
+  char label[64];\r
+  if ( mode == OUTPUT ) {\r
+    for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {\r
+      snprintf( label, 64, "outport %d", i );\r
+      handle->ports[0][i] = jack_port_register( handle->client, (const char *)label,\r
+                                                JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 );\r
+    }\r
+  }\r
+  else {\r
+    for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {\r
+      snprintf( label, 64, "inport %d", i );\r
+      handle->ports[1][i] = jack_port_register( handle->client, (const char *)label,\r
+                                                JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 );\r
+    }\r
+  }\r
+\r
+  // Setup the buffer conversion information structure.  We don't use\r
+  // buffers to do channel offsets, so we override that parameter\r
+  // here.\r
+  if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );\r
+\r
+  return SUCCESS;\r
+\r
+ error:\r
+  if ( handle ) {\r
+    pthread_cond_destroy( &handle->condition );\r
+    jack_client_close( handle->client );\r
+\r
+    if ( handle->ports[0] ) free( handle->ports[0] );\r
+    if ( handle->ports[1] ) free( handle->ports[1] );\r
+\r
+    delete handle;\r
+    stream_.apiHandle = 0;\r
+  }\r
+\r
+  for ( int i=0; i<2; i++ ) {\r
+    if ( stream_.userBuffer[i] ) {\r
+      free( stream_.userBuffer[i] );\r
+      stream_.userBuffer[i] = 0;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceBuffer ) {\r
+    free( stream_.deviceBuffer );\r
+    stream_.deviceBuffer = 0;\r
+  }\r
+\r
+  return FAILURE;\r
+}\r
+\r
+void RtApiJack :: closeStream( void )\r
+{\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiJack::closeStream(): no open stream to close!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  JackHandle *handle = (JackHandle *) stream_.apiHandle;\r
+  if ( handle ) {\r
+\r
+    if ( stream_.state == STREAM_RUNNING )\r
+      jack_deactivate( handle->client );\r
+\r
+    jack_client_close( handle->client );\r
+  }\r
+\r
+  if ( handle ) {\r
+    if ( handle->ports[0] ) free( handle->ports[0] );\r
+    if ( handle->ports[1] ) free( handle->ports[1] );\r
+    pthread_cond_destroy( &handle->condition );\r
+    delete handle;\r
+    stream_.apiHandle = 0;\r
+  }\r
+\r
+  for ( int i=0; i<2; i++ ) {\r
+    if ( stream_.userBuffer[i] ) {\r
+      free( stream_.userBuffer[i] );\r
+      stream_.userBuffer[i] = 0;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceBuffer ) {\r
+    free( stream_.deviceBuffer );\r
+    stream_.deviceBuffer = 0;\r
+  }\r
+\r
+  stream_.mode = UNINITIALIZED;\r
+  stream_.state = STREAM_CLOSED;\r
+}\r
+\r
+void RtApiJack :: startStream( void )\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_RUNNING ) {\r
+    errorText_ = "RtApiJack::startStream(): the stream is already running!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  JackHandle *handle = (JackHandle *) stream_.apiHandle;\r
+  int result = jack_activate( handle->client );\r
+  if ( result ) {\r
+    errorText_ = "RtApiJack::startStream(): unable to activate JACK client!";\r
+    goto unlock;\r
+  }\r
+\r
+  const char **ports;\r
+\r
+  // Get the list of available ports.\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+    result = 1;\r
+    ports = jack_get_ports( handle->client, handle->deviceName[0].c_str(), NULL, JackPortIsInput);\r
+    if ( ports == NULL) {\r
+      errorText_ = "RtApiJack::startStream(): error determining available JACK input ports!";\r
+      goto unlock;\r
+    }\r
+\r
+    // Now make the port connections.  Since RtAudio wasn't designed to\r
+    // allow the user to select particular channels of a device, we'll\r
+    // just open the first "nChannels" ports with offset.\r
+    for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {\r
+      result = 1;\r
+      if ( ports[ stream_.channelOffset[0] + i ] )\r
+        result = jack_connect( handle->client, jack_port_name( handle->ports[0][i] ), ports[ stream_.channelOffset[0] + i ] );\r
+      if ( result ) {\r
+        free( ports );\r
+        errorText_ = "RtApiJack::startStream(): error connecting output ports!";\r
+        goto unlock;\r
+      }\r
+    }\r
+    free(ports);\r
+  }\r
+\r
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+    result = 1;\r
+    ports = jack_get_ports( handle->client, handle->deviceName[1].c_str(), NULL, JackPortIsOutput );\r
+    if ( ports == NULL) {\r
+      errorText_ = "RtApiJack::startStream(): error determining available JACK output ports!";\r
+      goto unlock;\r
+    }\r
+\r
+    // Now make the port connections.  See note above.\r
+    for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {\r
+      result = 1;\r
+      if ( ports[ stream_.channelOffset[1] + i ] )\r
+        result = jack_connect( handle->client, ports[ stream_.channelOffset[1] + i ], jack_port_name( handle->ports[1][i] ) );\r
+      if ( result ) {\r
+        free( ports );\r
+        errorText_ = "RtApiJack::startStream(): error connecting input ports!";\r
+        goto unlock;\r
+      }\r
+    }\r
+    free(ports);\r
+  }\r
+\r
+  handle->drainCounter = 0;\r
+  handle->internalDrain = false;\r
+  stream_.state = STREAM_RUNNING;\r
+\r
+ unlock:\r
+  if ( result == 0 ) return;\r
+  error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiJack :: stopStream( void )\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiJack::stopStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  JackHandle *handle = (JackHandle *) stream_.apiHandle;\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+\r
+    if ( handle->drainCounter == 0 ) {\r
+      handle->drainCounter = 2;\r
+      pthread_cond_wait( &handle->condition, &stream_.mutex ); // block until signaled\r
+    }\r
+  }\r
+\r
+  jack_deactivate( handle->client );\r
+  stream_.state = STREAM_STOPPED;\r
+}\r
+\r
+void RtApiJack :: abortStream( void )\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiJack::abortStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  JackHandle *handle = (JackHandle *) stream_.apiHandle;\r
+  handle->drainCounter = 2;\r
+\r
+  stopStream();\r
+}\r
+\r
+// This function will be called by a spawned thread when the user\r
+// callback function signals that the stream should be stopped or\r
+// aborted.  It is necessary to handle it this way because the\r
+// callbackEvent() function must return before the jack_deactivate()\r
+// function will return.\r
+static void *jackStopStream( void *ptr )\r
+{\r
+  CallbackInfo *info = (CallbackInfo *) ptr;\r
+  RtApiJack *object = (RtApiJack *) info->object;\r
+\r
+  object->stopStream();\r
+  pthread_exit( NULL );\r
+}\r
+\r
+bool RtApiJack :: callbackEvent( unsigned long nframes )\r
+{\r
+  if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiCore::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
+    error( RtAudioError::WARNING );\r
+    return FAILURE;\r
+  }\r
+  if ( stream_.bufferSize != nframes ) {\r
+    errorText_ = "RtApiCore::callbackEvent(): the JACK buffer size has changed ... cannot process!";\r
+    error( RtAudioError::WARNING );\r
+    return FAILURE;\r
+  }\r
+\r
+  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;\r
+  JackHandle *handle = (JackHandle *) stream_.apiHandle;\r
+\r
+  // Check if we were draining the stream and signal is finished.\r
+  if ( handle->drainCounter > 3 ) {\r
+    ThreadHandle threadId;\r
+\r
+    stream_.state = STREAM_STOPPING;\r
+    if ( handle->internalDrain == true )\r
+      pthread_create( &threadId, NULL, jackStopStream, info );\r
+    else\r
+      pthread_cond_signal( &handle->condition );\r
+    return SUCCESS;\r
+  }\r
+\r
+  // Invoke user callback first, to get fresh output data.\r
+  if ( handle->drainCounter == 0 ) {\r
+    RtAudioCallback callback = (RtAudioCallback) info->callback;\r
+    double streamTime = getStreamTime();\r
+    RtAudioStreamStatus status = 0;\r
+    if ( stream_.mode != INPUT && handle->xrun[0] == true ) {\r
+      status |= RTAUDIO_OUTPUT_UNDERFLOW;\r
+      handle->xrun[0] = false;\r
+    }\r
+    if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {\r
+      status |= RTAUDIO_INPUT_OVERFLOW;\r
+      handle->xrun[1] = false;\r
+    }\r
+    int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
+                                  stream_.bufferSize, streamTime, status, info->userData );\r
+    if ( cbReturnValue == 2 ) {\r
+      stream_.state = STREAM_STOPPING;\r
+      handle->drainCounter = 2;\r
+      ThreadHandle id;\r
+      pthread_create( &id, NULL, jackStopStream, info );\r
+      return SUCCESS;\r
+    }\r
+    else if ( cbReturnValue == 1 ) {\r
+      handle->drainCounter = 1;\r
+      handle->internalDrain = true;\r
+    }\r
+  }\r
+\r
+  jack_default_audio_sample_t *jackbuffer;\r
+  unsigned long bufferBytes = nframes * sizeof( jack_default_audio_sample_t );\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+\r
+    if ( handle->drainCounter > 1 ) { // write zeros to the output stream\r
+\r
+      for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {\r
+        jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );\r
+        memset( jackbuffer, 0, bufferBytes );\r
+      }\r
+\r
+    }\r
+    else if ( stream_.doConvertBuffer[0] ) {\r
+\r
+      convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );\r
+\r
+      for ( unsigned int i=0; i<stream_.nDeviceChannels[0]; i++ ) {\r
+        jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );\r
+        memcpy( jackbuffer, &stream_.deviceBuffer[i*bufferBytes], bufferBytes );\r
+      }\r
+    }\r
+    else { // no buffer conversion\r
+      for ( unsigned int i=0; i<stream_.nUserChannels[0]; i++ ) {\r
+        jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[0][i], (jack_nframes_t) nframes );\r
+        memcpy( jackbuffer, &stream_.userBuffer[0][i*bufferBytes], bufferBytes );\r
+      }\r
+    }\r
+  }\r
+\r
+  // Don't bother draining input\r
+  if ( handle->drainCounter ) {\r
+    handle->drainCounter++;\r
+    goto unlock;\r
+  }\r
+\r
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+\r
+    if ( stream_.doConvertBuffer[1] ) {\r
+      for ( unsigned int i=0; i<stream_.nDeviceChannels[1]; i++ ) {\r
+        jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );\r
+        memcpy( &stream_.deviceBuffer[i*bufferBytes], jackbuffer, bufferBytes );\r
+      }\r
+      convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );\r
+    }\r
+    else { // no buffer conversion\r
+      for ( unsigned int i=0; i<stream_.nUserChannels[1]; i++ ) {\r
+        jackbuffer = (jack_default_audio_sample_t *) jack_port_get_buffer( handle->ports[1][i], (jack_nframes_t) nframes );\r
+        memcpy( &stream_.userBuffer[1][i*bufferBytes], jackbuffer, bufferBytes );\r
+      }\r
+    }\r
+  }\r
+\r
+ unlock:\r
+  RtApi::tickStreamTime();\r
+  return SUCCESS;\r
+}\r
+  //******************** End of __UNIX_JACK__ *********************//\r
+#endif\r
+\r
+#if defined(__WINDOWS_ASIO__) // ASIO API on Windows\r
+\r
+// The ASIO API is designed around a callback scheme, so this\r
+// implementation is similar to that used for OS-X CoreAudio and Linux\r
+// Jack.  The primary constraint with ASIO is that it only allows\r
+// access to a single driver at a time.  Thus, it is not possible to\r
+// have more than one simultaneous RtAudio stream.\r
+//\r
+// This implementation also requires a number of external ASIO files\r
+// and a few global variables.  The ASIO callback scheme does not\r
+// allow for the passing of user data, so we must create a global\r
+// pointer to our callbackInfo structure.\r
+//\r
+// On unix systems, we make use of a pthread condition variable.\r
+// Since there is no equivalent in Windows, I hacked something based\r
+// on information found in\r
+// http://www.cs.wustl.edu/~schmidt/win32-cv-1.html.\r
+\r
+#include "asiosys.h"\r
+#include "asio.h"\r
+#include "iasiothiscallresolver.h"\r
+#include "asiodrivers.h"\r
+#include <cmath>\r
+\r
+static AsioDrivers drivers;\r
+static ASIOCallbacks asioCallbacks;\r
+static ASIODriverInfo driverInfo;\r
+static CallbackInfo *asioCallbackInfo;\r
+static bool asioXRun;\r
+\r
+struct AsioHandle {\r
+  int drainCounter;       // Tracks callback counts when draining\r
+  bool internalDrain;     // Indicates if stop is initiated from callback or not.\r
+  ASIOBufferInfo *bufferInfos;\r
+  HANDLE condition;\r
+\r
+  AsioHandle()\r
+    :drainCounter(0), internalDrain(false), bufferInfos(0) {}\r
+};\r
+\r
+// Function declarations (definitions at end of section)\r
+static const char* getAsioErrorString( ASIOError result );\r
+static void sampleRateChanged( ASIOSampleRate sRate );\r
+static long asioMessages( long selector, long value, void* message, double* opt );\r
+\r
+RtApiAsio :: RtApiAsio()\r
+{\r
+  // ASIO cannot run on a multi-threaded appartment. You can call\r
+  // CoInitialize beforehand, but it must be for appartment threading\r
+  // (in which case, CoInitilialize will return S_FALSE here).\r
+  coInitialized_ = false;\r
+  HRESULT hr = CoInitialize( NULL ); \r
+  if ( FAILED(hr) ) {\r
+    errorText_ = "RtApiAsio::ASIO requires a single-threaded appartment. Call CoInitializeEx(0,COINIT_APARTMENTTHREADED)";\r
+    error( RtAudioError::WARNING );\r
+  }\r
+  coInitialized_ = true;\r
+\r
+  drivers.removeCurrentDriver();\r
+  driverInfo.asioVersion = 2;\r
+\r
+  // See note in DirectSound implementation about GetDesktopWindow().\r
+  driverInfo.sysRef = GetForegroundWindow();\r
+}\r
+\r
+RtApiAsio :: ~RtApiAsio()\r
+{\r
+  if ( stream_.state != STREAM_CLOSED ) closeStream();\r
+  if ( coInitialized_ ) CoUninitialize();\r
+}\r
+\r
+unsigned int RtApiAsio :: getDeviceCount( void )\r
+{\r
+  return (unsigned int) drivers.asioGetNumDev();\r
+}\r
+\r
+RtAudio::DeviceInfo RtApiAsio :: getDeviceInfo( unsigned int device )\r
+{\r
+  RtAudio::DeviceInfo info;\r
+  info.probed = false;\r
+\r
+  // Get device ID\r
+  unsigned int nDevices = getDeviceCount();\r
+  if ( nDevices == 0 ) {\r
+    errorText_ = "RtApiAsio::getDeviceInfo: no devices found!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return info;\r
+  }\r
+\r
+  if ( device >= nDevices ) {\r
+    errorText_ = "RtApiAsio::getDeviceInfo: device ID is invalid!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return info;\r
+  }\r
+\r
+  // If a stream is already open, we cannot probe other devices.  Thus, use the saved results.\r
+  if ( stream_.state != STREAM_CLOSED ) {\r
+    if ( device >= devices_.size() ) {\r
+      errorText_ = "RtApiAsio::getDeviceInfo: device ID was not present before stream was opened.";\r
+      error( RtAudioError::WARNING );\r
+      return info;\r
+    }\r
+    return devices_[ device ];\r
+  }\r
+\r
+  char driverName[32];\r
+  ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );\r
+  if ( result != ASE_OK ) {\r
+    errorStream_ << "RtApiAsio::getDeviceInfo: unable to get driver name (" << getAsioErrorString( result ) << ").";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  info.name = driverName;\r
+\r
+  if ( !drivers.loadDriver( driverName ) ) {\r
+    errorStream_ << "RtApiAsio::getDeviceInfo: unable to load driver (" << driverName << ").";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  result = ASIOInit( &driverInfo );\r
+  if ( result != ASE_OK ) {\r
+    errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // Determine the device channel information.\r
+  long inputChannels, outputChannels;\r
+  result = ASIOGetChannels( &inputChannels, &outputChannels );\r
+  if ( result != ASE_OK ) {\r
+    drivers.removeCurrentDriver();\r
+    errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  info.outputChannels = outputChannels;\r
+  info.inputChannels = inputChannels;\r
+  if ( info.outputChannels > 0 && info.inputChannels > 0 )\r
+    info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;\r
+\r
+  // Determine the supported sample rates.\r
+  info.sampleRates.clear();\r
+  for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {\r
+    result = ASIOCanSampleRate( (ASIOSampleRate) SAMPLE_RATES[i] );\r
+    if ( result == ASE_OK ) {\r
+      info.sampleRates.push_back( SAMPLE_RATES[i] );\r
+\r
+      if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )\r
+        info.preferredSampleRate = SAMPLE_RATES[i];\r
+    }\r
+  }\r
+\r
+  // Determine supported data types ... just check first channel and assume rest are the same.\r
+  ASIOChannelInfo channelInfo;\r
+  channelInfo.channel = 0;\r
+  channelInfo.isInput = true;\r
+  if ( info.inputChannels <= 0 ) channelInfo.isInput = false;\r
+  result = ASIOGetChannelInfo( &channelInfo );\r
+  if ( result != ASE_OK ) {\r
+    drivers.removeCurrentDriver();\r
+    errorStream_ << "RtApiAsio::getDeviceInfo: error (" << getAsioErrorString( result ) << ") getting driver channel info (" << driverName << ").";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  info.nativeFormats = 0;\r
+  if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB )\r
+    info.nativeFormats |= RTAUDIO_SINT16;\r
+  else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB )\r
+    info.nativeFormats |= RTAUDIO_SINT32;\r
+  else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB )\r
+    info.nativeFormats |= RTAUDIO_FLOAT32;\r
+  else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB )\r
+    info.nativeFormats |= RTAUDIO_FLOAT64;\r
+  else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB )\r
+    info.nativeFormats |= RTAUDIO_SINT24;\r
+\r
+  if ( info.outputChannels > 0 )\r
+    if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;\r
+  if ( info.inputChannels > 0 )\r
+    if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;\r
+\r
+  info.probed = true;\r
+  drivers.removeCurrentDriver();\r
+  return info;\r
+}\r
+\r
+static void bufferSwitch( long index, ASIOBool /*processNow*/ )\r
+{\r
+  RtApiAsio *object = (RtApiAsio *) asioCallbackInfo->object;\r
+  object->callbackEvent( index );\r
+}\r
+\r
+void RtApiAsio :: saveDeviceInfo( void )\r
+{\r
+  devices_.clear();\r
+\r
+  unsigned int nDevices = getDeviceCount();\r
+  devices_.resize( nDevices );\r
+  for ( unsigned int i=0; i<nDevices; i++ )\r
+    devices_[i] = getDeviceInfo( i );\r
+}\r
+\r
+bool RtApiAsio :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,\r
+                                   unsigned int firstChannel, unsigned int sampleRate,\r
+                                   RtAudioFormat format, unsigned int *bufferSize,\r
+                                   RtAudio::StreamOptions *options )\r
+{////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r
+\r
+  bool isDuplexInput =  mode == INPUT && stream_.mode == OUTPUT;\r
+\r
+  // For ASIO, a duplex stream MUST use the same driver.\r
+  if ( isDuplexInput && stream_.device[0] != device ) {\r
+    errorText_ = "RtApiAsio::probeDeviceOpen: an ASIO duplex stream must use the same device for input and output!";\r
+    return FAILURE;\r
+  }\r
+\r
+  char driverName[32];\r
+  ASIOError result = drivers.asioGetDriverName( (int) device, driverName, 32 );\r
+  if ( result != ASE_OK ) {\r
+    errorStream_ << "RtApiAsio::probeDeviceOpen: unable to get driver name (" << getAsioErrorString( result ) << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Only load the driver once for duplex stream.\r
+  if ( !isDuplexInput ) {\r
+    // The getDeviceInfo() function will not work when a stream is open\r
+    // because ASIO does not allow multiple devices to run at the same\r
+    // time.  Thus, we'll probe the system before opening a stream and\r
+    // save the results for use by getDeviceInfo().\r
+    this->saveDeviceInfo();\r
+\r
+    if ( !drivers.loadDriver( driverName ) ) {\r
+      errorStream_ << "RtApiAsio::probeDeviceOpen: unable to load driver (" << driverName << ").";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    result = ASIOInit( &driverInfo );\r
+    if ( result != ASE_OK ) {\r
+      errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") initializing driver (" << driverName << ").";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+  }\r
+\r
+  // keep them before any "goto error", they are used for error cleanup + goto device boundary checks\r
+  bool buffersAllocated = false;\r
+  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
+  unsigned int nChannels;\r
+\r
+\r
+  // Check the device channel count.\r
+  long inputChannels, outputChannels;\r
+  result = ASIOGetChannels( &inputChannels, &outputChannels );\r
+  if ( result != ASE_OK ) {\r
+    errorStream_ << "RtApiAsio::probeDeviceOpen: error (" << getAsioErrorString( result ) << ") getting channel count (" << driverName << ").";\r
+    errorText_ = errorStream_.str();\r
+    goto error;\r
+  }\r
+\r
+  if ( ( mode == OUTPUT && (channels+firstChannel) > (unsigned int) outputChannels) ||\r
+       ( mode == INPUT && (channels+firstChannel) > (unsigned int) inputChannels) ) {\r
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested channel count (" << channels << ") + offset (" << firstChannel << ").";\r
+    errorText_ = errorStream_.str();\r
+    goto error;\r
+  }\r
+  stream_.nDeviceChannels[mode] = channels;\r
+  stream_.nUserChannels[mode] = channels;\r
+  stream_.channelOffset[mode] = firstChannel;\r
+\r
+  // Verify the sample rate is supported.\r
+  result = ASIOCanSampleRate( (ASIOSampleRate) sampleRate );\r
+  if ( result != ASE_OK ) {\r
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") does not support requested sample rate (" << sampleRate << ").";\r
+    errorText_ = errorStream_.str();\r
+    goto error;\r
+  }\r
+\r
+  // Get the current sample rate\r
+  ASIOSampleRate currentRate;\r
+  result = ASIOGetSampleRate( &currentRate );\r
+  if ( result != ASE_OK ) {\r
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error getting sample rate.";\r
+    errorText_ = errorStream_.str();\r
+    goto error;\r
+  }\r
+\r
+  // Set the sample rate only if necessary\r
+  if ( currentRate != sampleRate ) {\r
+    result = ASIOSetSampleRate( (ASIOSampleRate) sampleRate );\r
+    if ( result != ASE_OK ) {\r
+      errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error setting sample rate (" << sampleRate << ").";\r
+      errorText_ = errorStream_.str();\r
+      goto error;\r
+    }\r
+  }\r
+\r
+  // Determine the driver data type.\r
+  ASIOChannelInfo channelInfo;\r
+  channelInfo.channel = 0;\r
+  if ( mode == OUTPUT ) channelInfo.isInput = false;\r
+  else channelInfo.isInput = true;\r
+  result = ASIOGetChannelInfo( &channelInfo );\r
+  if ( result != ASE_OK ) {\r
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting data format.";\r
+    errorText_ = errorStream_.str();\r
+    goto error;\r
+  }\r
+\r
+  // Assuming WINDOWS host is always little-endian.\r
+  stream_.doByteSwap[mode] = false;\r
+  stream_.userFormat = format;\r
+  stream_.deviceFormat[mode] = 0;\r
+  if ( channelInfo.type == ASIOSTInt16MSB || channelInfo.type == ASIOSTInt16LSB ) {\r
+    stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
+    if ( channelInfo.type == ASIOSTInt16MSB ) stream_.doByteSwap[mode] = true;\r
+  }\r
+  else if ( channelInfo.type == ASIOSTInt32MSB || channelInfo.type == ASIOSTInt32LSB ) {\r
+    stream_.deviceFormat[mode] = RTAUDIO_SINT32;\r
+    if ( channelInfo.type == ASIOSTInt32MSB ) stream_.doByteSwap[mode] = true;\r
+  }\r
+  else if ( channelInfo.type == ASIOSTFloat32MSB || channelInfo.type == ASIOSTFloat32LSB ) {\r
+    stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;\r
+    if ( channelInfo.type == ASIOSTFloat32MSB ) stream_.doByteSwap[mode] = true;\r
+  }\r
+  else if ( channelInfo.type == ASIOSTFloat64MSB || channelInfo.type == ASIOSTFloat64LSB ) {\r
+    stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;\r
+    if ( channelInfo.type == ASIOSTFloat64MSB ) stream_.doByteSwap[mode] = true;\r
+  }\r
+  else if ( channelInfo.type == ASIOSTInt24MSB || channelInfo.type == ASIOSTInt24LSB ) {\r
+    stream_.deviceFormat[mode] = RTAUDIO_SINT24;\r
+    if ( channelInfo.type == ASIOSTInt24MSB ) stream_.doByteSwap[mode] = true;\r
+  }\r
+\r
+  if ( stream_.deviceFormat[mode] == 0 ) {\r
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") data format not supported by RtAudio.";\r
+    errorText_ = errorStream_.str();\r
+    goto error;\r
+  }\r
+\r
+  // Set the buffer size.  For a duplex stream, this will end up\r
+  // setting the buffer size based on the input constraints, which\r
+  // should be ok.\r
+  long minSize, maxSize, preferSize, granularity;\r
+  result = ASIOGetBufferSize( &minSize, &maxSize, &preferSize, &granularity );\r
+  if ( result != ASE_OK ) {\r
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting buffer size.";\r
+    errorText_ = errorStream_.str();\r
+    goto error;\r
+  }\r
+\r
+  if ( isDuplexInput ) {\r
+    // When this is the duplex input (output was opened before), then we have to use the same\r
+    // buffersize as the output, because it might use the preferred buffer size, which most\r
+    // likely wasn't passed as input to this. The buffer sizes have to be identically anyway,\r
+    // So instead of throwing an error, make them equal. The caller uses the reference\r
+    // to the "bufferSize" param as usual to set up processing buffers.\r
+\r
+    *bufferSize = stream_.bufferSize;\r
+\r
+  } else {\r
+    if ( *bufferSize == 0 ) *bufferSize = preferSize;\r
+    else if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;\r
+    else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;\r
+    else if ( granularity == -1 ) {\r
+      // Make sure bufferSize is a power of two.\r
+      int log2_of_min_size = 0;\r
+      int log2_of_max_size = 0;\r
+\r
+      for ( unsigned int i = 0; i < sizeof(long) * 8; i++ ) {\r
+        if ( minSize & ((long)1 << i) ) log2_of_min_size = i;\r
+        if ( maxSize & ((long)1 << i) ) log2_of_max_size = i;\r
+      }\r
+\r
+      long min_delta = std::abs( (long)*bufferSize - ((long)1 << log2_of_min_size) );\r
+      int min_delta_num = log2_of_min_size;\r
+\r
+      for (int i = log2_of_min_size + 1; i <= log2_of_max_size; i++) {\r
+        long current_delta = std::abs( (long)*bufferSize - ((long)1 << i) );\r
+        if (current_delta < min_delta) {\r
+          min_delta = current_delta;\r
+          min_delta_num = i;\r
+        }\r
+      }\r
+\r
+      *bufferSize = ( (unsigned int)1 << min_delta_num );\r
+      if ( *bufferSize < (unsigned int) minSize ) *bufferSize = (unsigned int) minSize;\r
+      else if ( *bufferSize > (unsigned int) maxSize ) *bufferSize = (unsigned int) maxSize;\r
+    }\r
+    else if ( granularity != 0 ) {\r
+      // Set to an even multiple of granularity, rounding up.\r
+      *bufferSize = (*bufferSize + granularity-1) / granularity * granularity;\r
+    }\r
+  }\r
+\r
+  /*\r
+  // we don't use it anymore, see above!\r
+  // Just left it here for the case...\r
+  if ( isDuplexInput && stream_.bufferSize != *bufferSize ) {\r
+    errorText_ = "RtApiAsio::probeDeviceOpen: input/output buffersize discrepancy!";\r
+    goto error;\r
+  }\r
+  */\r
+\r
+  stream_.bufferSize = *bufferSize;\r
+  stream_.nBuffers = 2;\r
+\r
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;\r
+  else stream_.userInterleaved = true;\r
+\r
+  // ASIO always uses non-interleaved buffers.\r
+  stream_.deviceInterleaved[mode] = false;\r
+\r
+  // Allocate, if necessary, our AsioHandle structure for the stream.\r
+  if ( handle == 0 ) {\r
+    try {\r
+      handle = new AsioHandle;\r
+    }\r
+    catch ( std::bad_alloc& ) {\r
+      errorText_ = "RtApiAsio::probeDeviceOpen: error allocating AsioHandle memory.";\r
+      goto error;\r
+    }\r
+    handle->bufferInfos = 0;\r
+\r
+    // Create a manual-reset event.\r
+    handle->condition = CreateEvent( NULL,   // no security\r
+                                     TRUE,   // manual-reset\r
+                                     FALSE,  // non-signaled initially\r
+                                     NULL ); // unnamed\r
+    stream_.apiHandle = (void *) handle;\r
+  }\r
+\r
+  // Create the ASIO internal buffers.  Since RtAudio sets up input\r
+  // and output separately, we'll have to dispose of previously\r
+  // created output buffers for a duplex stream.\r
+  if ( mode == INPUT && stream_.mode == OUTPUT ) {\r
+    ASIODisposeBuffers();\r
+    if ( handle->bufferInfos ) free( handle->bufferInfos );\r
+  }\r
+\r
+  // Allocate, initialize, and save the bufferInfos in our stream callbackInfo structure.\r
+  unsigned int i;\r
+  nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];\r
+  handle->bufferInfos = (ASIOBufferInfo *) malloc( nChannels * sizeof(ASIOBufferInfo) );\r
+  if ( handle->bufferInfos == NULL ) {\r
+    errorStream_ << "RtApiAsio::probeDeviceOpen: error allocating bufferInfo memory for driver (" << driverName << ").";\r
+    errorText_ = errorStream_.str();\r
+    goto error;\r
+  }\r
+\r
+  ASIOBufferInfo *infos;\r
+  infos = handle->bufferInfos;\r
+  for ( i=0; i<stream_.nDeviceChannels[0]; i++, infos++ ) {\r
+    infos->isInput = ASIOFalse;\r
+    infos->channelNum = i + stream_.channelOffset[0];\r
+    infos->buffers[0] = infos->buffers[1] = 0;\r
+  }\r
+  for ( i=0; i<stream_.nDeviceChannels[1]; i++, infos++ ) {\r
+    infos->isInput = ASIOTrue;\r
+    infos->channelNum = i + stream_.channelOffset[1];\r
+    infos->buffers[0] = infos->buffers[1] = 0;\r
+  }\r
+\r
+  // prepare for callbacks\r
+  stream_.sampleRate = sampleRate;\r
+  stream_.device[mode] = device;\r
+  stream_.mode = isDuplexInput ? DUPLEX : mode;\r
+\r
+  // store this class instance before registering callbacks, that are going to use it\r
+  asioCallbackInfo = &stream_.callbackInfo;\r
+  stream_.callbackInfo.object = (void *) this;\r
+\r
+  // Set up the ASIO callback structure and create the ASIO data buffers.\r
+  asioCallbacks.bufferSwitch = &bufferSwitch;\r
+  asioCallbacks.sampleRateDidChange = &sampleRateChanged;\r
+  asioCallbacks.asioMessage = &asioMessages;\r
+  asioCallbacks.bufferSwitchTimeInfo = NULL;\r
+  result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );\r
+  if ( result != ASE_OK ) {\r
+    // Standard method failed. This can happen with strict/misbehaving drivers that return valid buffer size ranges\r
+    // but only accept the preferred buffer size as parameter for ASIOCreateBuffers. eg. Creatives ASIO driver\r
+    // in that case, let's be naïve and try that instead\r
+    *bufferSize = preferSize;\r
+    stream_.bufferSize = *bufferSize;\r
+    result = ASIOCreateBuffers( handle->bufferInfos, nChannels, stream_.bufferSize, &asioCallbacks );\r
+  }\r
+\r
+  if ( result != ASE_OK ) {\r
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") creating buffers.";\r
+    errorText_ = errorStream_.str();\r
+    goto error;\r
+  }\r
+  buffersAllocated = true;  \r
+  stream_.state = STREAM_STOPPED;\r
+\r
+  // Set flags for buffer conversion.\r
+  stream_.doConvertBuffer[mode] = false;\r
+  if ( stream_.userFormat != stream_.deviceFormat[mode] )\r
+    stream_.doConvertBuffer[mode] = true;\r
+  if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&\r
+       stream_.nUserChannels[mode] > 1 )\r
+    stream_.doConvertBuffer[mode] = true;\r
+\r
+  // Allocate necessary internal buffers\r
+  unsigned long bufferBytes;\r
+  bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );\r
+  stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );\r
+  if ( stream_.userBuffer[mode] == NULL ) {\r
+    errorText_ = "RtApiAsio::probeDeviceOpen: error allocating user buffer memory.";\r
+    goto error;\r
+  }\r
+\r
+  if ( stream_.doConvertBuffer[mode] ) {\r
+\r
+    bool makeBuffer = true;\r
+    bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );\r
+    if ( isDuplexInput && stream_.deviceBuffer ) {\r
+      unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
+      if ( bufferBytes <= bytesOut ) makeBuffer = false;\r
+    }\r
+\r
+    if ( makeBuffer ) {\r
+      bufferBytes *= *bufferSize;\r
+      if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );\r
+      stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );\r
+      if ( stream_.deviceBuffer == NULL ) {\r
+        errorText_ = "RtApiAsio::probeDeviceOpen: error allocating device buffer memory.";\r
+        goto error;\r
+      }\r
+    }\r
+  }\r
+\r
+  // Determine device latencies\r
+  long inputLatency, outputLatency;\r
+  result = ASIOGetLatencies( &inputLatency, &outputLatency );\r
+  if ( result != ASE_OK ) {\r
+    errorStream_ << "RtApiAsio::probeDeviceOpen: driver (" << driverName << ") error (" << getAsioErrorString( result ) << ") getting latency.";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING); // warn but don't fail\r
+  }\r
+  else {\r
+    stream_.latency[0] = outputLatency;\r
+    stream_.latency[1] = inputLatency;\r
+  }\r
+\r
+  // Setup the buffer conversion information structure.  We don't use\r
+  // buffers to do channel offsets, so we override that parameter\r
+  // here.\r
+  if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, 0 );\r
+\r
+  return SUCCESS;\r
+\r
+ error:\r
+  if ( !isDuplexInput ) {\r
+    // the cleanup for error in the duplex input, is done by RtApi::openStream\r
+    // So we clean up for single channel only\r
+\r
+    if ( buffersAllocated )\r
+      ASIODisposeBuffers();\r
+\r
+    drivers.removeCurrentDriver();\r
+\r
+    if ( handle ) {\r
+      CloseHandle( handle->condition );\r
+      if ( handle->bufferInfos )\r
+        free( handle->bufferInfos );\r
+\r
+      delete handle;\r
+      stream_.apiHandle = 0;\r
+    }\r
+\r
+\r
+    if ( stream_.userBuffer[mode] ) {\r
+      free( stream_.userBuffer[mode] );\r
+      stream_.userBuffer[mode] = 0;\r
+    }\r
+\r
+    if ( stream_.deviceBuffer ) {\r
+      free( stream_.deviceBuffer );\r
+      stream_.deviceBuffer = 0;\r
+    }\r
+  }\r
+\r
+  return FAILURE;\r
+}////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////\r
+\r
+void RtApiAsio :: closeStream()\r
+{\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiAsio::closeStream(): no open stream to close!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  if ( stream_.state == STREAM_RUNNING ) {\r
+    stream_.state = STREAM_STOPPED;\r
+    ASIOStop();\r
+  }\r
+  ASIODisposeBuffers();\r
+  drivers.removeCurrentDriver();\r
+\r
+  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
+  if ( handle ) {\r
+    CloseHandle( handle->condition );\r
+    if ( handle->bufferInfos )\r
+      free( handle->bufferInfos );\r
+    delete handle;\r
+    stream_.apiHandle = 0;\r
+  }\r
+\r
+  for ( int i=0; i<2; i++ ) {\r
+    if ( stream_.userBuffer[i] ) {\r
+      free( stream_.userBuffer[i] );\r
+      stream_.userBuffer[i] = 0;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceBuffer ) {\r
+    free( stream_.deviceBuffer );\r
+    stream_.deviceBuffer = 0;\r
+  }\r
+\r
+  stream_.mode = UNINITIALIZED;\r
+  stream_.state = STREAM_CLOSED;\r
+}\r
+\r
+bool stopThreadCalled = false;\r
+\r
+void RtApiAsio :: startStream()\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_RUNNING ) {\r
+    errorText_ = "RtApiAsio::startStream(): the stream is already running!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
+  ASIOError result = ASIOStart();\r
+  if ( result != ASE_OK ) {\r
+    errorStream_ << "RtApiAsio::startStream: error (" << getAsioErrorString( result ) << ") starting device.";\r
+    errorText_ = errorStream_.str();\r
+    goto unlock;\r
+  }\r
+\r
+  handle->drainCounter = 0;\r
+  handle->internalDrain = false;\r
+  ResetEvent( handle->condition );\r
+  stream_.state = STREAM_RUNNING;\r
+  asioXRun = false;\r
+\r
+ unlock:\r
+  stopThreadCalled = false;\r
+\r
+  if ( result == ASE_OK ) return;\r
+  error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiAsio :: stopStream()\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiAsio::stopStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+    if ( handle->drainCounter == 0 ) {\r
+      handle->drainCounter = 2;\r
+      WaitForSingleObject( handle->condition, INFINITE );  // block until signaled\r
+    }\r
+  }\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+\r
+  ASIOError result = ASIOStop();\r
+  if ( result != ASE_OK ) {\r
+    errorStream_ << "RtApiAsio::stopStream: error (" << getAsioErrorString( result ) << ") stopping device.";\r
+    errorText_ = errorStream_.str();\r
+  }\r
+\r
+  if ( result == ASE_OK ) return;\r
+  error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiAsio :: abortStream()\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiAsio::abortStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  // The following lines were commented-out because some behavior was\r
+  // noted where the device buffers need to be zeroed to avoid\r
+  // continuing sound, even when the device buffers are completely\r
+  // disposed.  So now, calling abort is the same as calling stop.\r
+  // AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
+  // handle->drainCounter = 2;\r
+  stopStream();\r
+}\r
+\r
+// This function will be called by a spawned thread when the user\r
+// callback function signals that the stream should be stopped or\r
+// aborted.  It is necessary to handle it this way because the\r
+// callbackEvent() function must return before the ASIOStop()\r
+// function will return.\r
+static unsigned __stdcall asioStopStream( void *ptr )\r
+{\r
+  CallbackInfo *info = (CallbackInfo *) ptr;\r
+  RtApiAsio *object = (RtApiAsio *) info->object;\r
+\r
+  object->stopStream();\r
+  _endthreadex( 0 );\r
+  return 0;\r
+}\r
+\r
+bool RtApiAsio :: callbackEvent( long bufferIndex )\r
+{\r
+  if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) return SUCCESS;\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiAsio::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
+    error( RtAudioError::WARNING );\r
+    return FAILURE;\r
+  }\r
+\r
+  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;\r
+  AsioHandle *handle = (AsioHandle *) stream_.apiHandle;\r
+\r
+  // Check if we were draining the stream and signal if finished.\r
+  if ( handle->drainCounter > 3 ) {\r
+\r
+    stream_.state = STREAM_STOPPING;\r
+    if ( handle->internalDrain == false )\r
+      SetEvent( handle->condition );\r
+    else { // spawn a thread to stop the stream\r
+      unsigned threadId;\r
+      stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,\r
+                                                    &stream_.callbackInfo, 0, &threadId );\r
+    }\r
+    return SUCCESS;\r
+  }\r
+\r
+  // Invoke user callback to get fresh output data UNLESS we are\r
+  // draining stream.\r
+  if ( handle->drainCounter == 0 ) {\r
+    RtAudioCallback callback = (RtAudioCallback) info->callback;\r
+    double streamTime = getStreamTime();\r
+    RtAudioStreamStatus status = 0;\r
+    if ( stream_.mode != INPUT && asioXRun == true ) {\r
+      status |= RTAUDIO_OUTPUT_UNDERFLOW;\r
+      asioXRun = false;\r
+    }\r
+    if ( stream_.mode != OUTPUT && asioXRun == true ) {\r
+      status |= RTAUDIO_INPUT_OVERFLOW;\r
+      asioXRun = false;\r
+    }\r
+    int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
+                                     stream_.bufferSize, streamTime, status, info->userData );\r
+    if ( cbReturnValue == 2 ) {\r
+      stream_.state = STREAM_STOPPING;\r
+      handle->drainCounter = 2;\r
+      unsigned threadId;\r
+      stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &asioStopStream,\r
+                                                    &stream_.callbackInfo, 0, &threadId );\r
+      return SUCCESS;\r
+    }\r
+    else if ( cbReturnValue == 1 ) {\r
+      handle->drainCounter = 1;\r
+      handle->internalDrain = true;\r
+    }\r
+  }\r
+\r
+  unsigned int nChannels, bufferBytes, i, j;\r
+  nChannels = stream_.nDeviceChannels[0] + stream_.nDeviceChannels[1];\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+\r
+    bufferBytes = stream_.bufferSize * formatBytes( stream_.deviceFormat[0] );\r
+\r
+    if ( handle->drainCounter > 1 ) { // write zeros to the output stream\r
+\r
+      for ( i=0, j=0; i<nChannels; i++ ) {\r
+        if ( handle->bufferInfos[i].isInput != ASIOTrue )\r
+          memset( handle->bufferInfos[i].buffers[bufferIndex], 0, bufferBytes );\r
+      }\r
+\r
+    }\r
+    else if ( stream_.doConvertBuffer[0] ) {\r
+\r
+      convertBuffer( stream_.deviceBuffer, stream_.userBuffer[0], stream_.convertInfo[0] );\r
+      if ( stream_.doByteSwap[0] )\r
+        byteSwapBuffer( stream_.deviceBuffer,\r
+                        stream_.bufferSize * stream_.nDeviceChannels[0],\r
+                        stream_.deviceFormat[0] );\r
+\r
+      for ( i=0, j=0; i<nChannels; i++ ) {\r
+        if ( handle->bufferInfos[i].isInput != ASIOTrue )\r
+          memcpy( handle->bufferInfos[i].buffers[bufferIndex],\r
+                  &stream_.deviceBuffer[j++*bufferBytes], bufferBytes );\r
+      }\r
+\r
+    }\r
+    else {\r
+\r
+      if ( stream_.doByteSwap[0] )\r
+        byteSwapBuffer( stream_.userBuffer[0],\r
+                        stream_.bufferSize * stream_.nUserChannels[0],\r
+                        stream_.userFormat );\r
+\r
+      for ( i=0, j=0; i<nChannels; i++ ) {\r
+        if ( handle->bufferInfos[i].isInput != ASIOTrue )\r
+          memcpy( handle->bufferInfos[i].buffers[bufferIndex],\r
+                  &stream_.userBuffer[0][bufferBytes*j++], bufferBytes );\r
+      }\r
+\r
+    }\r
+  }\r
+\r
+  // Don't bother draining input\r
+  if ( handle->drainCounter ) {\r
+    handle->drainCounter++;\r
+    goto unlock;\r
+  }\r
+\r
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+\r
+    bufferBytes = stream_.bufferSize * formatBytes(stream_.deviceFormat[1]);\r
+\r
+    if (stream_.doConvertBuffer[1]) {\r
+\r
+      // Always interleave ASIO input data.\r
+      for ( i=0, j=0; i<nChannels; i++ ) {\r
+        if ( handle->bufferInfos[i].isInput == ASIOTrue )\r
+          memcpy( &stream_.deviceBuffer[j++*bufferBytes],\r
+                  handle->bufferInfos[i].buffers[bufferIndex],\r
+                  bufferBytes );\r
+      }\r
+\r
+      if ( stream_.doByteSwap[1] )\r
+        byteSwapBuffer( stream_.deviceBuffer,\r
+                        stream_.bufferSize * stream_.nDeviceChannels[1],\r
+                        stream_.deviceFormat[1] );\r
+      convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );\r
+\r
+    }\r
+    else {\r
+      for ( i=0, j=0; i<nChannels; i++ ) {\r
+        if ( handle->bufferInfos[i].isInput == ASIOTrue ) {\r
+          memcpy( &stream_.userBuffer[1][bufferBytes*j++],\r
+                  handle->bufferInfos[i].buffers[bufferIndex],\r
+                  bufferBytes );\r
+        }\r
+      }\r
+\r
+      if ( stream_.doByteSwap[1] )\r
+        byteSwapBuffer( stream_.userBuffer[1],\r
+                        stream_.bufferSize * stream_.nUserChannels[1],\r
+                        stream_.userFormat );\r
+    }\r
+  }\r
+\r
+ unlock:\r
+  // The following call was suggested by Malte Clasen.  While the API\r
+  // documentation indicates it should not be required, some device\r
+  // drivers apparently do not function correctly without it.\r
+  ASIOOutputReady();\r
+\r
+  RtApi::tickStreamTime();\r
+  return SUCCESS;\r
+}\r
+\r
+static void sampleRateChanged( ASIOSampleRate sRate )\r
+{\r
+  // The ASIO documentation says that this usually only happens during\r
+  // external sync.  Audio processing is not stopped by the driver,\r
+  // actual sample rate might not have even changed, maybe only the\r
+  // sample rate status of an AES/EBU or S/PDIF digital input at the\r
+  // audio device.\r
+\r
+  RtApi *object = (RtApi *) asioCallbackInfo->object;\r
+  try {\r
+    object->stopStream();\r
+  }\r
+  catch ( RtAudioError &exception ) {\r
+    std::cerr << "\nRtApiAsio: sampleRateChanged() error (" << exception.getMessage() << ")!\n" << std::endl;\r
+    return;\r
+  }\r
+\r
+  std::cerr << "\nRtApiAsio: driver reports sample rate changed to " << sRate << " ... stream stopped!!!\n" << std::endl;\r
+}\r
+\r
+static long asioMessages( long selector, long value, void* /*message*/, double* /*opt*/ )\r
+{\r
+  long ret = 0;\r
+\r
+  switch( selector ) {\r
+  case kAsioSelectorSupported:\r
+    if ( value == kAsioResetRequest\r
+         || value == kAsioEngineVersion\r
+         || value == kAsioResyncRequest\r
+         || value == kAsioLatenciesChanged\r
+         // The following three were added for ASIO 2.0, you don't\r
+         // necessarily have to support them.\r
+         || value == kAsioSupportsTimeInfo\r
+         || value == kAsioSupportsTimeCode\r
+         || value == kAsioSupportsInputMonitor)\r
+      ret = 1L;\r
+    break;\r
+  case kAsioResetRequest:\r
+    // Defer the task and perform the reset of the driver during the\r
+    // next "safe" situation.  You cannot reset the driver right now,\r
+    // as this code is called from the driver.  Reset the driver is\r
+    // done by completely destruct is. I.e. ASIOStop(),\r
+    // ASIODisposeBuffers(), Destruction Afterwards you initialize the\r
+    // driver again.\r
+    std::cerr << "\nRtApiAsio: driver reset requested!!!" << std::endl;\r
+    ret = 1L;\r
+    break;\r
+  case kAsioResyncRequest:\r
+    // This informs the application that the driver encountered some\r
+    // non-fatal data loss.  It is used for synchronization purposes\r
+    // of different media.  Added mainly to work around the Win16Mutex\r
+    // problems in Windows 95/98 with the Windows Multimedia system,\r
+    // which could lose data because the Mutex was held too long by\r
+    // another thread.  However a driver can issue it in other\r
+    // situations, too.\r
+    // std::cerr << "\nRtApiAsio: driver resync requested!!!" << std::endl;\r
+    asioXRun = true;\r
+    ret = 1L;\r
+    break;\r
+  case kAsioLatenciesChanged:\r
+    // This will inform the host application that the drivers were\r
+    // latencies changed.  Beware, it this does not mean that the\r
+    // buffer sizes have changed!  You might need to update internal\r
+    // delay data.\r
+    std::cerr << "\nRtApiAsio: driver latency may have changed!!!" << std::endl;\r
+    ret = 1L;\r
+    break;\r
+  case kAsioEngineVersion:\r
+    // Return the supported ASIO version of the host application.  If\r
+    // a host application does not implement this selector, ASIO 1.0\r
+    // is assumed by the driver.\r
+    ret = 2L;\r
+    break;\r
+  case kAsioSupportsTimeInfo:\r
+    // Informs the driver whether the\r
+    // asioCallbacks.bufferSwitchTimeInfo() callback is supported.\r
+    // For compatibility with ASIO 1.0 drivers the host application\r
+    // should always support the "old" bufferSwitch method, too.\r
+    ret = 0;\r
+    break;\r
+  case kAsioSupportsTimeCode:\r
+    // Informs the driver whether application is interested in time\r
+    // code info.  If an application does not need to know about time\r
+    // code, the driver has less work to do.\r
+    ret = 0;\r
+    break;\r
+  }\r
+  return ret;\r
+}\r
+\r
+static const char* getAsioErrorString( ASIOError result )\r
+{\r
+  struct Messages \r
+  {\r
+    ASIOError value;\r
+    const char*message;\r
+  };\r
+\r
+  static const Messages m[] = \r
+    {\r
+      {   ASE_NotPresent,    "Hardware input or output is not present or available." },\r
+      {   ASE_HWMalfunction,  "Hardware is malfunctioning." },\r
+      {   ASE_InvalidParameter, "Invalid input parameter." },\r
+      {   ASE_InvalidMode,      "Invalid mode." },\r
+      {   ASE_SPNotAdvancing,     "Sample position not advancing." },\r
+      {   ASE_NoClock,            "Sample clock or rate cannot be determined or is not present." },\r
+      {   ASE_NoMemory,           "Not enough memory to complete the request." }\r
+    };\r
+\r
+  for ( unsigned int i = 0; i < sizeof(m)/sizeof(m[0]); ++i )\r
+    if ( m[i].value == result ) return m[i].message;\r
+\r
+  return "Unknown error.";\r
+}\r
+\r
+//******************** End of __WINDOWS_ASIO__ *********************//\r
+#endif\r
+\r
+\r
+#if defined(__WINDOWS_WASAPI__) // Windows WASAPI API\r
+\r
+// Authored by Marcus Tomlinson <themarcustomlinson@gmail.com>, April 2014\r
+// - Introduces support for the Windows WASAPI API\r
+// - Aims to deliver bit streams to and from hardware at the lowest possible latency, via the absolute minimum buffer sizes required\r
+// - Provides flexible stream configuration to an otherwise strict and inflexible WASAPI interface\r
+// - Includes automatic internal conversion of sample rate and buffer size between hardware and the user\r
+\r
+#ifndef INITGUID\r
+  #define INITGUID\r
+#endif\r
+#include <audioclient.h>\r
+#include <avrt.h>\r
+#include <mmdeviceapi.h>\r
+#include <functiondiscoverykeys_devpkey.h>\r
+\r
+//=============================================================================\r
+\r
+#define SAFE_RELEASE( objectPtr )\\r
+if ( objectPtr )\\r
+{\\r
+  objectPtr->Release();\\r
+  objectPtr = NULL;\\r
+}\r
+\r
+typedef HANDLE ( __stdcall *TAvSetMmThreadCharacteristicsPtr )( LPCWSTR TaskName, LPDWORD TaskIndex );\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+// WASAPI dictates stream sample rate, format, channel count, and in some cases, buffer size.\r
+// Therefore we must perform all necessary conversions to user buffers in order to satisfy these\r
+// requirements. WasapiBuffer ring buffers are used between HwIn->UserIn and UserOut->HwOut to\r
+// provide intermediate storage for read / write synchronization.\r
+class WasapiBuffer\r
+{\r
+public:\r
+  WasapiBuffer()\r
+    : buffer_( NULL ),\r
+      bufferSize_( 0 ),\r
+      inIndex_( 0 ),\r
+      outIndex_( 0 ) {}\r
+\r
+  ~WasapiBuffer() {\r
+    free( buffer_ );\r
+  }\r
+\r
+  // sets the length of the internal ring buffer\r
+  void setBufferSize( unsigned int bufferSize, unsigned int formatBytes ) {\r
+    free( buffer_ );\r
+\r
+    buffer_ = ( char* ) calloc( bufferSize, formatBytes );\r
+\r
+    bufferSize_ = bufferSize;\r
+    inIndex_ = 0;\r
+    outIndex_ = 0;\r
+  }\r
+\r
+  // attempt to push a buffer into the ring buffer at the current "in" index\r
+  bool pushBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )\r
+  {\r
+    if ( !buffer ||                 // incoming buffer is NULL\r
+         bufferSize == 0 ||         // incoming buffer has no data\r
+         bufferSize > bufferSize_ ) // incoming buffer too large\r
+    {\r
+      return false;\r
+    }\r
+\r
+    unsigned int relOutIndex = outIndex_;\r
+    unsigned int inIndexEnd = inIndex_ + bufferSize;\r
+    if ( relOutIndex < inIndex_ && inIndexEnd >= bufferSize_ ) {\r
+      relOutIndex += bufferSize_;\r
+    }\r
+\r
+    // "in" index can end on the "out" index but cannot begin at it\r
+    if ( inIndex_ <= relOutIndex && inIndexEnd > relOutIndex ) {\r
+      return false; // not enough space between "in" index and "out" index\r
+    }\r
+\r
+    // copy buffer from external to internal\r
+    int fromZeroSize = inIndex_ + bufferSize - bufferSize_;\r
+    fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;\r
+    int fromInSize = bufferSize - fromZeroSize;\r
+\r
+    switch( format )\r
+      {\r
+      case RTAUDIO_SINT8:\r
+        memcpy( &( ( char* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( char ) );\r
+        memcpy( buffer_, &( ( char* ) buffer )[fromInSize], fromZeroSize * sizeof( char ) );\r
+        break;\r
+      case RTAUDIO_SINT16:\r
+        memcpy( &( ( short* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( short ) );\r
+        memcpy( buffer_, &( ( short* ) buffer )[fromInSize], fromZeroSize * sizeof( short ) );\r
+        break;\r
+      case RTAUDIO_SINT24:\r
+        memcpy( &( ( S24* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( S24 ) );\r
+        memcpy( buffer_, &( ( S24* ) buffer )[fromInSize], fromZeroSize * sizeof( S24 ) );\r
+        break;\r
+      case RTAUDIO_SINT32:\r
+        memcpy( &( ( int* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( int ) );\r
+        memcpy( buffer_, &( ( int* ) buffer )[fromInSize], fromZeroSize * sizeof( int ) );\r
+        break;\r
+      case RTAUDIO_FLOAT32:\r
+        memcpy( &( ( float* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( float ) );\r
+        memcpy( buffer_, &( ( float* ) buffer )[fromInSize], fromZeroSize * sizeof( float ) );\r
+        break;\r
+      case RTAUDIO_FLOAT64:\r
+        memcpy( &( ( double* ) buffer_ )[inIndex_], buffer, fromInSize * sizeof( double ) );\r
+        memcpy( buffer_, &( ( double* ) buffer )[fromInSize], fromZeroSize * sizeof( double ) );\r
+        break;\r
+    }\r
+\r
+    // update "in" index\r
+    inIndex_ += bufferSize;\r
+    inIndex_ %= bufferSize_;\r
+\r
+    return true;\r
+  }\r
+\r
+  // attempt to pull a buffer from the ring buffer from the current "out" index\r
+  bool pullBuffer( char* buffer, unsigned int bufferSize, RtAudioFormat format )\r
+  {\r
+    if ( !buffer ||                 // incoming buffer is NULL\r
+         bufferSize == 0 ||         // incoming buffer has no data\r
+         bufferSize > bufferSize_ ) // incoming buffer too large\r
+    {\r
+      return false;\r
+    }\r
+\r
+    unsigned int relInIndex = inIndex_;\r
+    unsigned int outIndexEnd = outIndex_ + bufferSize;\r
+    if ( relInIndex < outIndex_ && outIndexEnd >= bufferSize_ ) {\r
+      relInIndex += bufferSize_;\r
+    }\r
+\r
+    // "out" index can begin at and end on the "in" index\r
+    if ( outIndex_ < relInIndex && outIndexEnd > relInIndex ) {\r
+      return false; // not enough space between "out" index and "in" index\r
+    }\r
+\r
+    // copy buffer from internal to external\r
+    int fromZeroSize = outIndex_ + bufferSize - bufferSize_;\r
+    fromZeroSize = fromZeroSize < 0 ? 0 : fromZeroSize;\r
+    int fromOutSize = bufferSize - fromZeroSize;\r
+\r
+    switch( format )\r
+    {\r
+      case RTAUDIO_SINT8:\r
+        memcpy( buffer, &( ( char* ) buffer_ )[outIndex_], fromOutSize * sizeof( char ) );\r
+        memcpy( &( ( char* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( char ) );\r
+        break;\r
+      case RTAUDIO_SINT16:\r
+        memcpy( buffer, &( ( short* ) buffer_ )[outIndex_], fromOutSize * sizeof( short ) );\r
+        memcpy( &( ( short* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( short ) );\r
+        break;\r
+      case RTAUDIO_SINT24:\r
+        memcpy( buffer, &( ( S24* ) buffer_ )[outIndex_], fromOutSize * sizeof( S24 ) );\r
+        memcpy( &( ( S24* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( S24 ) );\r
+        break;\r
+      case RTAUDIO_SINT32:\r
+        memcpy( buffer, &( ( int* ) buffer_ )[outIndex_], fromOutSize * sizeof( int ) );\r
+        memcpy( &( ( int* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( int ) );\r
+        break;\r
+      case RTAUDIO_FLOAT32:\r
+        memcpy( buffer, &( ( float* ) buffer_ )[outIndex_], fromOutSize * sizeof( float ) );\r
+        memcpy( &( ( float* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( float ) );\r
+        break;\r
+      case RTAUDIO_FLOAT64:\r
+        memcpy( buffer, &( ( double* ) buffer_ )[outIndex_], fromOutSize * sizeof( double ) );\r
+        memcpy( &( ( double* ) buffer )[fromOutSize], buffer_, fromZeroSize * sizeof( double ) );\r
+        break;\r
+    }\r
+\r
+    // update "out" index\r
+    outIndex_ += bufferSize;\r
+    outIndex_ %= bufferSize_;\r
+\r
+    return true;\r
+  }\r
+\r
+private:\r
+  char* buffer_;\r
+  unsigned int bufferSize_;\r
+  unsigned int inIndex_;\r
+  unsigned int outIndex_;\r
+};\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+// In order to satisfy WASAPI's buffer requirements, we need a means of converting sample rate\r
+// between HW and the user. The convertBufferWasapi function is used to perform this conversion\r
+// between HwIn->UserIn and UserOut->HwOut during the stream callback loop.\r
+// This sample rate converter favors speed over quality, and works best with conversions between\r
+// one rate and its multiple.\r
+void convertBufferWasapi( char* outBuffer,\r
+                          const char* inBuffer,\r
+                          const unsigned int& channelCount,\r
+                          const unsigned int& inSampleRate,\r
+                          const unsigned int& outSampleRate,\r
+                          const unsigned int& inSampleCount,\r
+                          unsigned int& outSampleCount,\r
+                          const RtAudioFormat& format )\r
+{\r
+  // calculate the new outSampleCount and relative sampleStep\r
+  float sampleRatio = ( float ) outSampleRate / inSampleRate;\r
+  float sampleStep = 1.0f / sampleRatio;\r
+  float inSampleFraction = 0.0f;\r
+\r
+  outSampleCount = ( unsigned int ) roundf( inSampleCount * sampleRatio );\r
+\r
+  // frame-by-frame, copy each relative input sample into it's corresponding output sample\r
+  for ( unsigned int outSample = 0; outSample < outSampleCount; outSample++ )\r
+  {\r
+    unsigned int inSample = ( unsigned int ) inSampleFraction;\r
+\r
+    switch ( format )\r
+    {\r
+      case RTAUDIO_SINT8:\r
+        memcpy( &( ( char* ) outBuffer )[ outSample * channelCount ], &( ( char* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( char ) );\r
+        break;\r
+      case RTAUDIO_SINT16:\r
+        memcpy( &( ( short* ) outBuffer )[ outSample * channelCount ], &( ( short* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( short ) );\r
+        break;\r
+      case RTAUDIO_SINT24:\r
+        memcpy( &( ( S24* ) outBuffer )[ outSample * channelCount ], &( ( S24* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( S24 ) );\r
+        break;\r
+      case RTAUDIO_SINT32:\r
+        memcpy( &( ( int* ) outBuffer )[ outSample * channelCount ], &( ( int* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( int ) );\r
+        break;\r
+      case RTAUDIO_FLOAT32:\r
+        memcpy( &( ( float* ) outBuffer )[ outSample * channelCount ], &( ( float* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( float ) );\r
+        break;\r
+      case RTAUDIO_FLOAT64:\r
+        memcpy( &( ( double* ) outBuffer )[ outSample * channelCount ], &( ( double* ) inBuffer )[ inSample * channelCount ], channelCount * sizeof( double ) );\r
+        break;\r
+    }\r
+\r
+    // jump to next in sample\r
+    inSampleFraction += sampleStep;\r
+  }\r
+}\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+// A structure to hold various information related to the WASAPI implementation.\r
+struct WasapiHandle\r
+{\r
+  IAudioClient* captureAudioClient;\r
+  IAudioClient* renderAudioClient;\r
+  IAudioCaptureClient* captureClient;\r
+  IAudioRenderClient* renderClient;\r
+  HANDLE captureEvent;\r
+  HANDLE renderEvent;\r
+\r
+  WasapiHandle()\r
+  : captureAudioClient( NULL ),\r
+    renderAudioClient( NULL ),\r
+    captureClient( NULL ),\r
+    renderClient( NULL ),\r
+    captureEvent( NULL ),\r
+    renderEvent( NULL ) {}\r
+};\r
+\r
+//=============================================================================\r
+\r
+RtApiWasapi::RtApiWasapi()\r
+  : coInitialized_( false ), deviceEnumerator_( NULL )\r
+{\r
+  // WASAPI can run either apartment or multi-threaded\r
+  HRESULT hr = CoInitialize( NULL );\r
+  if ( !FAILED( hr ) )\r
+    coInitialized_ = true;\r
+\r
+  // Instantiate device enumerator\r
+  hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL,\r
+                         CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ),\r
+                         ( void** ) &deviceEnumerator_ );\r
+\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::RtApiWasapi: Unable to instantiate device enumerator";\r
+    error( RtAudioError::DRIVER_ERROR );\r
+  }\r
+}\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+RtApiWasapi::~RtApiWasapi()\r
+{\r
+  if ( stream_.state != STREAM_CLOSED )\r
+    closeStream();\r
+\r
+  SAFE_RELEASE( deviceEnumerator_ );\r
+\r
+  // If this object previously called CoInitialize()\r
+  if ( coInitialized_ )\r
+    CoUninitialize();\r
+}\r
+\r
+//=============================================================================\r
+\r
+unsigned int RtApiWasapi::getDeviceCount( void )\r
+{\r
+  unsigned int captureDeviceCount = 0;\r
+  unsigned int renderDeviceCount = 0;\r
+\r
+  IMMDeviceCollection* captureDevices = NULL;\r
+  IMMDeviceCollection* renderDevices = NULL;\r
+\r
+  // Count capture devices\r
+  errorText_.clear();\r
+  HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device collection.";\r
+    goto Exit;\r
+  }\r
+\r
+  hr = captureDevices->GetCount( &captureDeviceCount );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve capture device count.";\r
+    goto Exit;\r
+  }\r
+\r
+  // Count render devices\r
+  hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device collection.";\r
+    goto Exit;\r
+  }\r
+\r
+  hr = renderDevices->GetCount( &renderDeviceCount );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceCount: Unable to retrieve render device count.";\r
+    goto Exit;\r
+  }\r
+\r
+Exit:\r
+  // release all references\r
+  SAFE_RELEASE( captureDevices );\r
+  SAFE_RELEASE( renderDevices );\r
+\r
+  if ( errorText_.empty() )\r
+    return captureDeviceCount + renderDeviceCount;\r
+\r
+  error( RtAudioError::DRIVER_ERROR );\r
+  return 0;\r
+}\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+RtAudio::DeviceInfo RtApiWasapi::getDeviceInfo( unsigned int device )\r
+{\r
+  RtAudio::DeviceInfo info;\r
+  unsigned int captureDeviceCount = 0;\r
+  unsigned int renderDeviceCount = 0;\r
+  std::string defaultDeviceName;\r
+  bool isCaptureDevice = false;\r
+\r
+  PROPVARIANT deviceNameProp;\r
+  PROPVARIANT defaultDeviceNameProp;\r
+\r
+  IMMDeviceCollection* captureDevices = NULL;\r
+  IMMDeviceCollection* renderDevices = NULL;\r
+  IMMDevice* devicePtr = NULL;\r
+  IMMDevice* defaultDevicePtr = NULL;\r
+  IAudioClient* audioClient = NULL;\r
+  IPropertyStore* devicePropStore = NULL;\r
+  IPropertyStore* defaultDevicePropStore = NULL;\r
+\r
+  WAVEFORMATEX* deviceFormat = NULL;\r
+  WAVEFORMATEX* closestMatchFormat = NULL;\r
+\r
+  // probed\r
+  info.probed = false;\r
+\r
+  // Count capture devices\r
+  errorText_.clear();\r
+  RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;\r
+  HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device collection.";\r
+    goto Exit;\r
+  }\r
+\r
+  hr = captureDevices->GetCount( &captureDeviceCount );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device count.";\r
+    goto Exit;\r
+  }\r
+\r
+  // Count render devices\r
+  hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device collection.";\r
+    goto Exit;\r
+  }\r
+\r
+  hr = renderDevices->GetCount( &renderDeviceCount );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device count.";\r
+    goto Exit;\r
+  }\r
+\r
+  // validate device index\r
+  if ( device >= captureDeviceCount + renderDeviceCount ) {\r
+    errorText_ = "RtApiWasapi::getDeviceInfo: Invalid device index.";\r
+    errorType = RtAudioError::INVALID_USE;\r
+    goto Exit;\r
+  }\r
+\r
+  // determine whether index falls within capture or render devices\r
+  if ( device >= renderDeviceCount ) {\r
+    hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve capture device handle.";\r
+      goto Exit;\r
+    }\r
+    isCaptureDevice = true;\r
+  }\r
+  else {\r
+    hr = renderDevices->Item( device, &devicePtr );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve render device handle.";\r
+      goto Exit;\r
+    }\r
+    isCaptureDevice = false;\r
+  }\r
+\r
+  // get default device name\r
+  if ( isCaptureDevice ) {\r
+    hr = deviceEnumerator_->GetDefaultAudioEndpoint( eCapture, eConsole, &defaultDevicePtr );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default capture device handle.";\r
+      goto Exit;\r
+    }\r
+  }\r
+  else {\r
+    hr = deviceEnumerator_->GetDefaultAudioEndpoint( eRender, eConsole, &defaultDevicePtr );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default render device handle.";\r
+      goto Exit;\r
+    }\r
+  }\r
+\r
+  hr = defaultDevicePtr->OpenPropertyStore( STGM_READ, &defaultDevicePropStore );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open default device property store.";\r
+    goto Exit;\r
+  }\r
+  PropVariantInit( &defaultDeviceNameProp );\r
+\r
+  hr = defaultDevicePropStore->GetValue( PKEY_Device_FriendlyName, &defaultDeviceNameProp );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve default device property: PKEY_Device_FriendlyName.";\r
+    goto Exit;\r
+  }\r
+\r
+  defaultDeviceName = convertCharPointerToStdString(defaultDeviceNameProp.pwszVal);\r
+\r
+  // name\r
+  hr = devicePtr->OpenPropertyStore( STGM_READ, &devicePropStore );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceInfo: Unable to open device property store.";\r
+    goto Exit;\r
+  }\r
+\r
+  PropVariantInit( &deviceNameProp );\r
+\r
+  hr = devicePropStore->GetValue( PKEY_Device_FriendlyName, &deviceNameProp );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device property: PKEY_Device_FriendlyName.";\r
+    goto Exit;\r
+  }\r
+\r
+  info.name =convertCharPointerToStdString(deviceNameProp.pwszVal);\r
+\r
+  // is default\r
+  if ( isCaptureDevice ) {\r
+    info.isDefaultInput = info.name == defaultDeviceName;\r
+    info.isDefaultOutput = false;\r
+  }\r
+  else {\r
+    info.isDefaultInput = false;\r
+    info.isDefaultOutput = info.name == defaultDeviceName;\r
+  }\r
+\r
+  // channel count\r
+  hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL, NULL, ( void** ) &audioClient );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device audio client.";\r
+    goto Exit;\r
+  }\r
+\r
+  hr = audioClient->GetMixFormat( &deviceFormat );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::getDeviceInfo: Unable to retrieve device mix format.";\r
+    goto Exit;\r
+  }\r
+\r
+  if ( isCaptureDevice ) {\r
+    info.inputChannels = deviceFormat->nChannels;\r
+    info.outputChannels = 0;\r
+    info.duplexChannels = 0;\r
+  }\r
+  else {\r
+    info.inputChannels = 0;\r
+    info.outputChannels = deviceFormat->nChannels;\r
+    info.duplexChannels = 0;\r
+  }\r
+\r
+  // sample rates\r
+  info.sampleRates.clear();\r
+\r
+  // allow support for all sample rates as we have a built-in sample rate converter\r
+  for ( unsigned int i = 0; i < MAX_SAMPLE_RATES; i++ ) {\r
+    info.sampleRates.push_back( SAMPLE_RATES[i] );\r
+  }\r
+  info.preferredSampleRate = deviceFormat->nSamplesPerSec;\r
+\r
+  // native format\r
+  info.nativeFormats = 0;\r
+\r
+  if ( deviceFormat->wFormatTag == WAVE_FORMAT_IEEE_FLOAT ||\r
+       ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&\r
+         ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT ) )\r
+  {\r
+    if ( deviceFormat->wBitsPerSample == 32 ) {\r
+      info.nativeFormats |= RTAUDIO_FLOAT32;\r
+    }\r
+    else if ( deviceFormat->wBitsPerSample == 64 ) {\r
+      info.nativeFormats |= RTAUDIO_FLOAT64;\r
+    }\r
+  }\r
+  else if ( deviceFormat->wFormatTag == WAVE_FORMAT_PCM ||\r
+           ( deviceFormat->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&\r
+             ( ( WAVEFORMATEXTENSIBLE* ) deviceFormat )->SubFormat == KSDATAFORMAT_SUBTYPE_PCM ) )\r
+  {\r
+    if ( deviceFormat->wBitsPerSample == 8 ) {\r
+      info.nativeFormats |= RTAUDIO_SINT8;\r
+    }\r
+    else if ( deviceFormat->wBitsPerSample == 16 ) {\r
+      info.nativeFormats |= RTAUDIO_SINT16;\r
+    }\r
+    else if ( deviceFormat->wBitsPerSample == 24 ) {\r
+      info.nativeFormats |= RTAUDIO_SINT24;\r
+    }\r
+    else if ( deviceFormat->wBitsPerSample == 32 ) {\r
+      info.nativeFormats |= RTAUDIO_SINT32;\r
+    }\r
+  }\r
+\r
+  // probed\r
+  info.probed = true;\r
+\r
+Exit:\r
+  // release all references\r
+  PropVariantClear( &deviceNameProp );\r
+  PropVariantClear( &defaultDeviceNameProp );\r
+\r
+  SAFE_RELEASE( captureDevices );\r
+  SAFE_RELEASE( renderDevices );\r
+  SAFE_RELEASE( devicePtr );\r
+  SAFE_RELEASE( defaultDevicePtr );\r
+  SAFE_RELEASE( audioClient );\r
+  SAFE_RELEASE( devicePropStore );\r
+  SAFE_RELEASE( defaultDevicePropStore );\r
+\r
+  CoTaskMemFree( deviceFormat );\r
+  CoTaskMemFree( closestMatchFormat );\r
+\r
+  if ( !errorText_.empty() )\r
+    error( errorType );\r
+  return info;\r
+}\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+unsigned int RtApiWasapi::getDefaultOutputDevice( void )\r
+{\r
+  for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {\r
+    if ( getDeviceInfo( i ).isDefaultOutput ) {\r
+      return i;\r
+    }\r
+  }\r
+\r
+  return 0;\r
+}\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+unsigned int RtApiWasapi::getDefaultInputDevice( void )\r
+{\r
+  for ( unsigned int i = 0; i < getDeviceCount(); i++ ) {\r
+    if ( getDeviceInfo( i ).isDefaultInput ) {\r
+      return i;\r
+    }\r
+  }\r
+\r
+  return 0;\r
+}\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+void RtApiWasapi::closeStream( void )\r
+{\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiWasapi::closeStream: No open stream to close.";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  if ( stream_.state != STREAM_STOPPED )\r
+    stopStream();\r
+\r
+  // clean up stream memory\r
+  SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient )\r
+  SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient )\r
+\r
+  SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->captureClient )\r
+  SAFE_RELEASE( ( ( WasapiHandle* ) stream_.apiHandle )->renderClient )\r
+\r
+  if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent )\r
+    CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent );\r
+\r
+  if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent )\r
+    CloseHandle( ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent );\r
+\r
+  delete ( WasapiHandle* ) stream_.apiHandle;\r
+  stream_.apiHandle = NULL;\r
+\r
+  for ( int i = 0; i < 2; i++ ) {\r
+    if ( stream_.userBuffer[i] ) {\r
+      free( stream_.userBuffer[i] );\r
+      stream_.userBuffer[i] = 0;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceBuffer ) {\r
+    free( stream_.deviceBuffer );\r
+    stream_.deviceBuffer = 0;\r
+  }\r
+\r
+  // update stream state\r
+  stream_.state = STREAM_CLOSED;\r
+}\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+void RtApiWasapi::startStream( void )\r
+{\r
+  verifyStream();\r
+\r
+  if ( stream_.state == STREAM_RUNNING ) {\r
+    errorText_ = "RtApiWasapi::startStream: The stream is already running.";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  // update stream state\r
+  stream_.state = STREAM_RUNNING;\r
+\r
+  // create WASAPI stream thread\r
+  stream_.callbackInfo.thread = ( ThreadHandle ) CreateThread( NULL, 0, runWasapiThread, this, CREATE_SUSPENDED, NULL );\r
+\r
+  if ( !stream_.callbackInfo.thread ) {\r
+    errorText_ = "RtApiWasapi::startStream: Unable to instantiate callback thread.";\r
+    error( RtAudioError::THREAD_ERROR );\r
+  }\r
+  else {\r
+    SetThreadPriority( ( void* ) stream_.callbackInfo.thread, stream_.callbackInfo.priority );\r
+    ResumeThread( ( void* ) stream_.callbackInfo.thread );\r
+  }\r
+}\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+void RtApiWasapi::stopStream( void )\r
+{\r
+  verifyStream();\r
+\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiWasapi::stopStream: The stream is already stopped.";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  // inform stream thread by setting stream state to STREAM_STOPPING\r
+  stream_.state = STREAM_STOPPING;\r
+\r
+  // wait until stream thread is stopped\r
+  while( stream_.state != STREAM_STOPPED ) {\r
+    Sleep( 1 );\r
+  }\r
+\r
+  // Wait for the last buffer to play before stopping.\r
+  Sleep( 1000 * stream_.bufferSize / stream_.sampleRate );\r
+\r
+  // stop capture client if applicable\r
+  if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient ) {\r
+    HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient->Stop();\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::stopStream: Unable to stop capture stream.";\r
+      error( RtAudioError::DRIVER_ERROR );\r
+      return;\r
+    }\r
+  }\r
+\r
+  // stop render client if applicable\r
+  if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient ) {\r
+    HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient->Stop();\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::stopStream: Unable to stop render stream.";\r
+      error( RtAudioError::DRIVER_ERROR );\r
+      return;\r
+    }\r
+  }\r
+\r
+  // close thread handle\r
+  if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {\r
+    errorText_ = "RtApiWasapi::stopStream: Unable to close callback thread.";\r
+    error( RtAudioError::THREAD_ERROR );\r
+    return;\r
+  }\r
+\r
+  stream_.callbackInfo.thread = (ThreadHandle) NULL;\r
+}\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+void RtApiWasapi::abortStream( void )\r
+{\r
+  verifyStream();\r
+\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiWasapi::abortStream: The stream is already stopped.";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  // inform stream thread by setting stream state to STREAM_STOPPING\r
+  stream_.state = STREAM_STOPPING;\r
+\r
+  // wait until stream thread is stopped\r
+  while ( stream_.state != STREAM_STOPPED ) {\r
+    Sleep( 1 );\r
+  }\r
+\r
+  // stop capture client if applicable\r
+  if ( ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient ) {\r
+    HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient->Stop();\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::abortStream: Unable to stop capture stream.";\r
+      error( RtAudioError::DRIVER_ERROR );\r
+      return;\r
+    }\r
+  }\r
+\r
+  // stop render client if applicable\r
+  if ( ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient ) {\r
+    HRESULT hr = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient->Stop();\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::abortStream: Unable to stop render stream.";\r
+      error( RtAudioError::DRIVER_ERROR );\r
+      return;\r
+    }\r
+  }\r
+\r
+  // close thread handle\r
+  if ( stream_.callbackInfo.thread && !CloseHandle( ( void* ) stream_.callbackInfo.thread ) ) {\r
+    errorText_ = "RtApiWasapi::abortStream: Unable to close callback thread.";\r
+    error( RtAudioError::THREAD_ERROR );\r
+    return;\r
+  }\r
+\r
+  stream_.callbackInfo.thread = (ThreadHandle) NULL;\r
+}\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+bool RtApiWasapi::probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,\r
+                                   unsigned int firstChannel, unsigned int sampleRate,\r
+                                   RtAudioFormat format, unsigned int* bufferSize,\r
+                                   RtAudio::StreamOptions* options )\r
+{\r
+  bool methodResult = FAILURE;\r
+  unsigned int captureDeviceCount = 0;\r
+  unsigned int renderDeviceCount = 0;\r
+\r
+  IMMDeviceCollection* captureDevices = NULL;\r
+  IMMDeviceCollection* renderDevices = NULL;\r
+  IMMDevice* devicePtr = NULL;\r
+  WAVEFORMATEX* deviceFormat = NULL;\r
+  unsigned int bufferBytes;\r
+  stream_.state = STREAM_STOPPED;\r
+\r
+  // create API Handle if not already created\r
+  if ( !stream_.apiHandle )\r
+    stream_.apiHandle = ( void* ) new WasapiHandle();\r
+\r
+  // Count capture devices\r
+  errorText_.clear();\r
+  RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;\r
+  HRESULT hr = deviceEnumerator_->EnumAudioEndpoints( eCapture, DEVICE_STATE_ACTIVE, &captureDevices );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device collection.";\r
+    goto Exit;\r
+  }\r
+\r
+  hr = captureDevices->GetCount( &captureDeviceCount );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device count.";\r
+    goto Exit;\r
+  }\r
+\r
+  // Count render devices\r
+  hr = deviceEnumerator_->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE, &renderDevices );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device collection.";\r
+    goto Exit;\r
+  }\r
+\r
+  hr = renderDevices->GetCount( &renderDeviceCount );\r
+  if ( FAILED( hr ) ) {\r
+    errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device count.";\r
+    goto Exit;\r
+  }\r
+\r
+  // validate device index\r
+  if ( device >= captureDeviceCount + renderDeviceCount ) {\r
+    errorType = RtAudioError::INVALID_USE;\r
+    errorText_ = "RtApiWasapi::probeDeviceOpen: Invalid device index.";\r
+    goto Exit;\r
+  }\r
+\r
+  // determine whether index falls within capture or render devices\r
+  if ( device >= renderDeviceCount ) {\r
+    if ( mode != INPUT ) {\r
+      errorType = RtAudioError::INVALID_USE;\r
+      errorText_ = "RtApiWasapi::probeDeviceOpen: Capture device selected as output device.";\r
+      goto Exit;\r
+    }\r
+\r
+    // retrieve captureAudioClient from devicePtr\r
+    IAudioClient*& captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;\r
+\r
+    hr = captureDevices->Item( device - renderDeviceCount, &devicePtr );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve capture device handle.";\r
+      goto Exit;\r
+    }\r
+\r
+    hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,\r
+                              NULL, ( void** ) &captureAudioClient );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";\r
+      goto Exit;\r
+    }\r
+\r
+    hr = captureAudioClient->GetMixFormat( &deviceFormat );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";\r
+      goto Exit;\r
+    }\r
+\r
+    stream_.nDeviceChannels[mode] = deviceFormat->nChannels;\r
+    captureAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );\r
+  }\r
+  else {\r
+    if ( mode != OUTPUT ) {\r
+      errorType = RtAudioError::INVALID_USE;\r
+      errorText_ = "RtApiWasapi::probeDeviceOpen: Render device selected as input device.";\r
+      goto Exit;\r
+    }\r
+\r
+    // retrieve renderAudioClient from devicePtr\r
+    IAudioClient*& renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;\r
+\r
+    hr = renderDevices->Item( device, &devicePtr );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve render device handle.";\r
+      goto Exit;\r
+    }\r
+\r
+    hr = devicePtr->Activate( __uuidof( IAudioClient ), CLSCTX_ALL,\r
+                              NULL, ( void** ) &renderAudioClient );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device audio client.";\r
+      goto Exit;\r
+    }\r
+\r
+    hr = renderAudioClient->GetMixFormat( &deviceFormat );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::probeDeviceOpen: Unable to retrieve device mix format.";\r
+      goto Exit;\r
+    }\r
+\r
+    stream_.nDeviceChannels[mode] = deviceFormat->nChannels;\r
+    renderAudioClient->GetStreamLatency( ( long long* ) &stream_.latency[mode] );\r
+  }\r
+\r
+  // fill stream data\r
+  if ( ( stream_.mode == OUTPUT && mode == INPUT ) ||\r
+       ( stream_.mode == INPUT && mode == OUTPUT ) ) {\r
+    stream_.mode = DUPLEX;\r
+  }\r
+  else {\r
+    stream_.mode = mode;\r
+  }\r
+\r
+  stream_.device[mode] = device;\r
+  stream_.doByteSwap[mode] = false;\r
+  stream_.sampleRate = sampleRate;\r
+  stream_.bufferSize = *bufferSize;\r
+  stream_.nBuffers = 1;\r
+  stream_.nUserChannels[mode] = channels;\r
+  stream_.channelOffset[mode] = firstChannel;\r
+  stream_.userFormat = format;\r
+  stream_.deviceFormat[mode] = getDeviceInfo( device ).nativeFormats;\r
+\r
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED )\r
+    stream_.userInterleaved = false;\r
+  else\r
+    stream_.userInterleaved = true;\r
+  stream_.deviceInterleaved[mode] = true;\r
+\r
+  // Set flags for buffer conversion.\r
+  stream_.doConvertBuffer[mode] = false;\r
+  if ( stream_.userFormat != stream_.deviceFormat[mode] ||\r
+       stream_.nUserChannels != stream_.nDeviceChannels )\r
+    stream_.doConvertBuffer[mode] = true;\r
+  else if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&\r
+            stream_.nUserChannels[mode] > 1 )\r
+    stream_.doConvertBuffer[mode] = true;\r
+\r
+  if ( stream_.doConvertBuffer[mode] )\r
+    setConvertInfo( mode, 0 );\r
+\r
+  // Allocate necessary internal buffers\r
+  bufferBytes = stream_.nUserChannels[mode] * stream_.bufferSize * formatBytes( stream_.userFormat );\r
+\r
+  stream_.userBuffer[mode] = ( char* ) calloc( bufferBytes, 1 );\r
+  if ( !stream_.userBuffer[mode] ) {\r
+    errorType = RtAudioError::MEMORY_ERROR;\r
+    errorText_ = "RtApiWasapi::probeDeviceOpen: Error allocating user buffer memory.";\r
+    goto Exit;\r
+  }\r
+\r
+  if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME )\r
+    stream_.callbackInfo.priority = 15;\r
+  else\r
+    stream_.callbackInfo.priority = 0;\r
+\r
+  ///! TODO: RTAUDIO_MINIMIZE_LATENCY // Provide stream buffers directly to callback\r
+  ///! TODO: RTAUDIO_HOG_DEVICE       // Exclusive mode\r
+\r
+  methodResult = SUCCESS;\r
+\r
+Exit:\r
+  //clean up\r
+  SAFE_RELEASE( captureDevices );\r
+  SAFE_RELEASE( renderDevices );\r
+  SAFE_RELEASE( devicePtr );\r
+  CoTaskMemFree( deviceFormat );\r
+\r
+  // if method failed, close the stream\r
+  if ( methodResult == FAILURE )\r
+    closeStream();\r
+\r
+  if ( !errorText_.empty() )\r
+    error( errorType );\r
+  return methodResult;\r
+}\r
+\r
+//=============================================================================\r
+\r
+DWORD WINAPI RtApiWasapi::runWasapiThread( void* wasapiPtr )\r
+{\r
+  if ( wasapiPtr )\r
+    ( ( RtApiWasapi* ) wasapiPtr )->wasapiThread();\r
+\r
+  return 0;\r
+}\r
+\r
+DWORD WINAPI RtApiWasapi::stopWasapiThread( void* wasapiPtr )\r
+{\r
+  if ( wasapiPtr )\r
+    ( ( RtApiWasapi* ) wasapiPtr )->stopStream();\r
+\r
+  return 0;\r
+}\r
+\r
+DWORD WINAPI RtApiWasapi::abortWasapiThread( void* wasapiPtr )\r
+{\r
+  if ( wasapiPtr )\r
+    ( ( RtApiWasapi* ) wasapiPtr )->abortStream();\r
+\r
+  return 0;\r
+}\r
+\r
+//-----------------------------------------------------------------------------\r
+\r
+void RtApiWasapi::wasapiThread()\r
+{\r
+  // as this is a new thread, we must CoInitialize it\r
+  CoInitialize( NULL );\r
+\r
+  HRESULT hr;\r
+\r
+  IAudioClient* captureAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureAudioClient;\r
+  IAudioClient* renderAudioClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderAudioClient;\r
+  IAudioCaptureClient* captureClient = ( ( WasapiHandle* ) stream_.apiHandle )->captureClient;\r
+  IAudioRenderClient* renderClient = ( ( WasapiHandle* ) stream_.apiHandle )->renderClient;\r
+  HANDLE captureEvent = ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent;\r
+  HANDLE renderEvent = ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent;\r
+\r
+  WAVEFORMATEX* captureFormat = NULL;\r
+  WAVEFORMATEX* renderFormat = NULL;\r
+  float captureSrRatio = 0.0f;\r
+  float renderSrRatio = 0.0f;\r
+  WasapiBuffer captureBuffer;\r
+  WasapiBuffer renderBuffer;\r
+\r
+  // declare local stream variables\r
+  RtAudioCallback callback = ( RtAudioCallback ) stream_.callbackInfo.callback;\r
+  BYTE* streamBuffer = NULL;\r
+  unsigned long captureFlags = 0;\r
+  unsigned int bufferFrameCount = 0;\r
+  unsigned int numFramesPadding = 0;\r
+  unsigned int convBufferSize = 0;\r
+  bool callbackPushed = false;\r
+  bool callbackPulled = false;\r
+  bool callbackStopped = false;\r
+  int callbackResult = 0;\r
+\r
+  // convBuffer is used to store converted buffers between WASAPI and the user\r
+  char* convBuffer = NULL;\r
+  unsigned int convBuffSize = 0;\r
+  unsigned int deviceBuffSize = 0;\r
+\r
+  errorText_.clear();\r
+  RtAudioError::Type errorType = RtAudioError::DRIVER_ERROR;\r
+\r
+  // Attempt to assign "Pro Audio" characteristic to thread\r
+  HMODULE AvrtDll = LoadLibrary( (LPCTSTR) "AVRT.dll" );\r
+  if ( AvrtDll ) {\r
+    DWORD taskIndex = 0;\r
+    TAvSetMmThreadCharacteristicsPtr AvSetMmThreadCharacteristicsPtr = ( TAvSetMmThreadCharacteristicsPtr ) GetProcAddress( AvrtDll, "AvSetMmThreadCharacteristicsW" );\r
+    AvSetMmThreadCharacteristicsPtr( L"Pro Audio", &taskIndex );\r
+    FreeLibrary( AvrtDll );\r
+  }\r
+\r
+  // start capture stream if applicable\r
+  if ( captureAudioClient ) {\r
+    hr = captureAudioClient->GetMixFormat( &captureFormat );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";\r
+      goto Exit;\r
+    }\r
+\r
+    captureSrRatio = ( ( float ) captureFormat->nSamplesPerSec / stream_.sampleRate );\r
+\r
+    // initialize capture stream according to desire buffer size\r
+    float desiredBufferSize = stream_.bufferSize * captureSrRatio;\r
+    REFERENCE_TIME desiredBufferPeriod = ( REFERENCE_TIME ) ( ( float ) desiredBufferSize * 10000000 / captureFormat->nSamplesPerSec );\r
+\r
+    if ( !captureClient ) {\r
+      hr = captureAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,\r
+                                           AUDCLNT_STREAMFLAGS_EVENTCALLBACK,\r
+                                           desiredBufferPeriod,\r
+                                           desiredBufferPeriod,\r
+                                           captureFormat,\r
+                                           NULL );\r
+      if ( FAILED( hr ) ) {\r
+        errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize capture audio client.";\r
+        goto Exit;\r
+      }\r
+\r
+      hr = captureAudioClient->GetService( __uuidof( IAudioCaptureClient ),\r
+                                           ( void** ) &captureClient );\r
+      if ( FAILED( hr ) ) {\r
+        errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture client handle.";\r
+        goto Exit;\r
+      }\r
+\r
+      // configure captureEvent to trigger on every available capture buffer\r
+      captureEvent = CreateEvent( NULL, FALSE, FALSE, NULL );\r
+      if ( !captureEvent ) {\r
+        errorType = RtAudioError::SYSTEM_ERROR;\r
+        errorText_ = "RtApiWasapi::wasapiThread: Unable to create capture event.";\r
+        goto Exit;\r
+      }\r
+\r
+      hr = captureAudioClient->SetEventHandle( captureEvent );\r
+      if ( FAILED( hr ) ) {\r
+        errorText_ = "RtApiWasapi::wasapiThread: Unable to set capture event handle.";\r
+        goto Exit;\r
+      }\r
+\r
+      ( ( WasapiHandle* ) stream_.apiHandle )->captureClient = captureClient;\r
+      ( ( WasapiHandle* ) stream_.apiHandle )->captureEvent = captureEvent;\r
+    }\r
+\r
+    unsigned int inBufferSize = 0;\r
+    hr = captureAudioClient->GetBufferSize( &inBufferSize );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::wasapiThread: Unable to get capture buffer size.";\r
+      goto Exit;\r
+    }\r
+\r
+    // scale outBufferSize according to stream->user sample rate ratio\r
+    unsigned int outBufferSize = ( unsigned int ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT];\r
+    inBufferSize *= stream_.nDeviceChannels[INPUT];\r
+\r
+    // set captureBuffer size\r
+    captureBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[INPUT] ) );\r
+\r
+    // reset the capture stream\r
+    hr = captureAudioClient->Reset();\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::wasapiThread: Unable to reset capture stream.";\r
+      goto Exit;\r
+    }\r
+\r
+    // start the capture stream\r
+    hr = captureAudioClient->Start();\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::wasapiThread: Unable to start capture stream.";\r
+      goto Exit;\r
+    }\r
+  }\r
+\r
+  // start render stream if applicable\r
+  if ( renderAudioClient ) {\r
+    hr = renderAudioClient->GetMixFormat( &renderFormat );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve device mix format.";\r
+      goto Exit;\r
+    }\r
+\r
+    renderSrRatio = ( ( float ) renderFormat->nSamplesPerSec / stream_.sampleRate );\r
+\r
+    // initialize render stream according to desire buffer size\r
+    float desiredBufferSize = stream_.bufferSize * renderSrRatio;\r
+    REFERENCE_TIME desiredBufferPeriod = ( REFERENCE_TIME ) ( ( float ) desiredBufferSize * 10000000 / renderFormat->nSamplesPerSec );\r
+\r
+    if ( !renderClient ) {\r
+      hr = renderAudioClient->Initialize( AUDCLNT_SHAREMODE_SHARED,\r
+                                          AUDCLNT_STREAMFLAGS_EVENTCALLBACK,\r
+                                          desiredBufferPeriod,\r
+                                          desiredBufferPeriod,\r
+                                          renderFormat,\r
+                                          NULL );\r
+      if ( FAILED( hr ) ) {\r
+        errorText_ = "RtApiWasapi::wasapiThread: Unable to initialize render audio client.";\r
+        goto Exit;\r
+      }\r
+\r
+      hr = renderAudioClient->GetService( __uuidof( IAudioRenderClient ),\r
+                                          ( void** ) &renderClient );\r
+      if ( FAILED( hr ) ) {\r
+        errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render client handle.";\r
+        goto Exit;\r
+      }\r
+\r
+      // configure renderEvent to trigger on every available render buffer\r
+      renderEvent = CreateEvent( NULL, FALSE, FALSE, NULL );\r
+      if ( !renderEvent ) {\r
+        errorType = RtAudioError::SYSTEM_ERROR;\r
+        errorText_ = "RtApiWasapi::wasapiThread: Unable to create render event.";\r
+        goto Exit;\r
+      }\r
+\r
+      hr = renderAudioClient->SetEventHandle( renderEvent );\r
+      if ( FAILED( hr ) ) {\r
+        errorText_ = "RtApiWasapi::wasapiThread: Unable to set render event handle.";\r
+        goto Exit;\r
+      }\r
+\r
+      ( ( WasapiHandle* ) stream_.apiHandle )->renderClient = renderClient;\r
+      ( ( WasapiHandle* ) stream_.apiHandle )->renderEvent = renderEvent;\r
+    }\r
+\r
+    unsigned int outBufferSize = 0;\r
+    hr = renderAudioClient->GetBufferSize( &outBufferSize );\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::wasapiThread: Unable to get render buffer size.";\r
+      goto Exit;\r
+    }\r
+\r
+    // scale inBufferSize according to user->stream sample rate ratio\r
+    unsigned int inBufferSize = ( unsigned int ) ( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT];\r
+    outBufferSize *= stream_.nDeviceChannels[OUTPUT];\r
+\r
+    // set renderBuffer size\r
+    renderBuffer.setBufferSize( inBufferSize + outBufferSize, formatBytes( stream_.deviceFormat[OUTPUT] ) );\r
+\r
+    // reset the render stream\r
+    hr = renderAudioClient->Reset();\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::wasapiThread: Unable to reset render stream.";\r
+      goto Exit;\r
+    }\r
+\r
+    // start the render stream\r
+    hr = renderAudioClient->Start();\r
+    if ( FAILED( hr ) ) {\r
+      errorText_ = "RtApiWasapi::wasapiThread: Unable to start render stream.";\r
+      goto Exit;\r
+    }\r
+  }\r
+\r
+  if ( stream_.mode == INPUT ) {\r
+    convBuffSize = ( size_t ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );\r
+    deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] );\r
+  }\r
+  else if ( stream_.mode == OUTPUT ) {\r
+    convBuffSize = ( size_t ) ( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );\r
+    deviceBuffSize = stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] );\r
+  }\r
+  else if ( stream_.mode == DUPLEX ) {\r
+    convBuffSize = std::max( ( size_t ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),\r
+                             ( size_t ) ( stream_.bufferSize * renderSrRatio ) * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );\r
+    deviceBuffSize = std::max( stream_.bufferSize * stream_.nDeviceChannels[INPUT] * formatBytes( stream_.deviceFormat[INPUT] ),\r
+                               stream_.bufferSize * stream_.nDeviceChannels[OUTPUT] * formatBytes( stream_.deviceFormat[OUTPUT] ) );\r
+  }\r
+\r
+  convBuffer = ( char* ) malloc( convBuffSize );\r
+  stream_.deviceBuffer = ( char* ) malloc( deviceBuffSize );\r
+  if ( !convBuffer || !stream_.deviceBuffer ) {\r
+    errorType = RtAudioError::MEMORY_ERROR;\r
+    errorText_ = "RtApiWasapi::wasapiThread: Error allocating device buffer memory.";\r
+    goto Exit;\r
+  }\r
+\r
+  // stream process loop\r
+  while ( stream_.state != STREAM_STOPPING ) {\r
+    if ( !callbackPulled ) {\r
+      // Callback Input\r
+      // ==============\r
+      // 1. Pull callback buffer from inputBuffer\r
+      // 2. If 1. was successful: Convert callback buffer to user sample rate and channel count\r
+      //                          Convert callback buffer to user format\r
+\r
+      if ( captureAudioClient ) {\r
+        // Pull callback buffer from inputBuffer\r
+        callbackPulled = captureBuffer.pullBuffer( convBuffer,\r
+                                                   ( unsigned int ) ( stream_.bufferSize * captureSrRatio ) * stream_.nDeviceChannels[INPUT],\r
+                                                   stream_.deviceFormat[INPUT] );\r
+\r
+        if ( callbackPulled ) {\r
+          // Convert callback buffer to user sample rate\r
+          convertBufferWasapi( stream_.deviceBuffer,\r
+                               convBuffer,\r
+                               stream_.nDeviceChannels[INPUT],\r
+                               captureFormat->nSamplesPerSec,\r
+                               stream_.sampleRate,\r
+                               ( unsigned int ) ( stream_.bufferSize * captureSrRatio ),\r
+                               convBufferSize,\r
+                               stream_.deviceFormat[INPUT] );\r
+\r
+          if ( stream_.doConvertBuffer[INPUT] ) {\r
+            // Convert callback buffer to user format\r
+            convertBuffer( stream_.userBuffer[INPUT],\r
+                           stream_.deviceBuffer,\r
+                           stream_.convertInfo[INPUT] );\r
+          }\r
+          else {\r
+            // no further conversion, simple copy deviceBuffer to userBuffer\r
+            memcpy( stream_.userBuffer[INPUT],\r
+                    stream_.deviceBuffer,\r
+                    stream_.bufferSize * stream_.nUserChannels[INPUT] * formatBytes( stream_.userFormat ) );\r
+          }\r
+        }\r
+      }\r
+      else {\r
+        // if there is no capture stream, set callbackPulled flag\r
+        callbackPulled = true;\r
+      }\r
+\r
+      // Execute Callback\r
+      // ================\r
+      // 1. Execute user callback method\r
+      // 2. Handle return value from callback\r
+\r
+      // if callback has not requested the stream to stop\r
+      if ( callbackPulled && !callbackStopped ) {\r
+        // Execute user callback method\r
+        callbackResult = callback( stream_.userBuffer[OUTPUT],\r
+                                   stream_.userBuffer[INPUT],\r
+                                   stream_.bufferSize,\r
+                                   getStreamTime(),\r
+                                   captureFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY ? RTAUDIO_INPUT_OVERFLOW : 0,\r
+                                   stream_.callbackInfo.userData );\r
+\r
+        // Handle return value from callback\r
+        if ( callbackResult == 1 ) {\r
+          // instantiate a thread to stop this thread\r
+          HANDLE threadHandle = CreateThread( NULL, 0, stopWasapiThread, this, 0, NULL );\r
+          if ( !threadHandle ) {\r
+            errorType = RtAudioError::THREAD_ERROR;\r
+            errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream stop thread.";\r
+            goto Exit;\r
+          }\r
+          else if ( !CloseHandle( threadHandle ) ) {\r
+            errorType = RtAudioError::THREAD_ERROR;\r
+            errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream stop thread handle.";\r
+            goto Exit;\r
+          }\r
+\r
+          callbackStopped = true;\r
+        }\r
+        else if ( callbackResult == 2 ) {\r
+          // instantiate a thread to stop this thread\r
+          HANDLE threadHandle = CreateThread( NULL, 0, abortWasapiThread, this, 0, NULL );\r
+          if ( !threadHandle ) {\r
+            errorType = RtAudioError::THREAD_ERROR;\r
+            errorText_ = "RtApiWasapi::wasapiThread: Unable to instantiate stream abort thread.";\r
+            goto Exit;\r
+          }\r
+          else if ( !CloseHandle( threadHandle ) ) {\r
+            errorType = RtAudioError::THREAD_ERROR;\r
+            errorText_ = "RtApiWasapi::wasapiThread: Unable to close stream abort thread handle.";\r
+            goto Exit;\r
+          }\r
+\r
+          callbackStopped = true;\r
+        }\r
+      }\r
+    }\r
+\r
+    // Callback Output\r
+    // ===============\r
+    // 1. Convert callback buffer to stream format\r
+    // 2. Convert callback buffer to stream sample rate and channel count\r
+    // 3. Push callback buffer into outputBuffer\r
+\r
+    if ( renderAudioClient && callbackPulled ) {\r
+      if ( stream_.doConvertBuffer[OUTPUT] ) {\r
+        // Convert callback buffer to stream format\r
+        convertBuffer( stream_.deviceBuffer,\r
+                       stream_.userBuffer[OUTPUT],\r
+                       stream_.convertInfo[OUTPUT] );\r
+\r
+      }\r
+\r
+      // Convert callback buffer to stream sample rate\r
+      convertBufferWasapi( convBuffer,\r
+                           stream_.deviceBuffer,\r
+                           stream_.nDeviceChannels[OUTPUT],\r
+                           stream_.sampleRate,\r
+                           renderFormat->nSamplesPerSec,\r
+                           stream_.bufferSize,\r
+                           convBufferSize,\r
+                           stream_.deviceFormat[OUTPUT] );\r
+\r
+      // Push callback buffer into outputBuffer\r
+      callbackPushed = renderBuffer.pushBuffer( convBuffer,\r
+                                                convBufferSize * stream_.nDeviceChannels[OUTPUT],\r
+                                                stream_.deviceFormat[OUTPUT] );\r
+    }\r
+    else {\r
+      // if there is no render stream, set callbackPushed flag\r
+      callbackPushed = true;\r
+    }\r
+\r
+    // Stream Capture\r
+    // ==============\r
+    // 1. Get capture buffer from stream\r
+    // 2. Push capture buffer into inputBuffer\r
+    // 3. If 2. was successful: Release capture buffer\r
+\r
+    if ( captureAudioClient ) {\r
+      // if the callback input buffer was not pulled from captureBuffer, wait for next capture event\r
+      if ( !callbackPulled ) {\r
+        WaitForSingleObject( captureEvent, INFINITE );\r
+      }\r
+\r
+      // Get capture buffer from stream\r
+      hr = captureClient->GetBuffer( &streamBuffer,\r
+                                     &bufferFrameCount,\r
+                                     &captureFlags, NULL, NULL );\r
+      if ( FAILED( hr ) ) {\r
+        errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve capture buffer.";\r
+        goto Exit;\r
+      }\r
+\r
+      if ( bufferFrameCount != 0 ) {\r
+        // Push capture buffer into inputBuffer\r
+        if ( captureBuffer.pushBuffer( ( char* ) streamBuffer,\r
+                                       bufferFrameCount * stream_.nDeviceChannels[INPUT],\r
+                                       stream_.deviceFormat[INPUT] ) )\r
+        {\r
+          // Release capture buffer\r
+          hr = captureClient->ReleaseBuffer( bufferFrameCount );\r
+          if ( FAILED( hr ) ) {\r
+            errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";\r
+            goto Exit;\r
+          }\r
+        }\r
+        else\r
+        {\r
+          // Inform WASAPI that capture was unsuccessful\r
+          hr = captureClient->ReleaseBuffer( 0 );\r
+          if ( FAILED( hr ) ) {\r
+            errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";\r
+            goto Exit;\r
+          }\r
+        }\r
+      }\r
+      else\r
+      {\r
+        // Inform WASAPI that capture was unsuccessful\r
+        hr = captureClient->ReleaseBuffer( 0 );\r
+        if ( FAILED( hr ) ) {\r
+          errorText_ = "RtApiWasapi::wasapiThread: Unable to release capture buffer.";\r
+          goto Exit;\r
+        }\r
+      }\r
+    }\r
+\r
+    // Stream Render\r
+    // =============\r
+    // 1. Get render buffer from stream\r
+    // 2. Pull next buffer from outputBuffer\r
+    // 3. If 2. was successful: Fill render buffer with next buffer\r
+    //                          Release render buffer\r
+\r
+    if ( renderAudioClient ) {\r
+      // if the callback output buffer was not pushed to renderBuffer, wait for next render event\r
+      if ( callbackPulled && !callbackPushed ) {\r
+        WaitForSingleObject( renderEvent, INFINITE );\r
+      }\r
+\r
+      // Get render buffer from stream\r
+      hr = renderAudioClient->GetBufferSize( &bufferFrameCount );\r
+      if ( FAILED( hr ) ) {\r
+        errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer size.";\r
+        goto Exit;\r
+      }\r
+\r
+      hr = renderAudioClient->GetCurrentPadding( &numFramesPadding );\r
+      if ( FAILED( hr ) ) {\r
+        errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer padding.";\r
+        goto Exit;\r
+      }\r
+\r
+      bufferFrameCount -= numFramesPadding;\r
+\r
+      if ( bufferFrameCount != 0 ) {\r
+        hr = renderClient->GetBuffer( bufferFrameCount, &streamBuffer );\r
+        if ( FAILED( hr ) ) {\r
+          errorText_ = "RtApiWasapi::wasapiThread: Unable to retrieve render buffer.";\r
+          goto Exit;\r
+        }\r
+\r
+        // Pull next buffer from outputBuffer\r
+        // Fill render buffer with next buffer\r
+        if ( renderBuffer.pullBuffer( ( char* ) streamBuffer,\r
+                                      bufferFrameCount * stream_.nDeviceChannels[OUTPUT],\r
+                                      stream_.deviceFormat[OUTPUT] ) )\r
+        {\r
+          // Release render buffer\r
+          hr = renderClient->ReleaseBuffer( bufferFrameCount, 0 );\r
+          if ( FAILED( hr ) ) {\r
+            errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";\r
+            goto Exit;\r
+          }\r
+        }\r
+        else\r
+        {\r
+          // Inform WASAPI that render was unsuccessful\r
+          hr = renderClient->ReleaseBuffer( 0, 0 );\r
+          if ( FAILED( hr ) ) {\r
+            errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";\r
+            goto Exit;\r
+          }\r
+        }\r
+      }\r
+      else\r
+      {\r
+        // Inform WASAPI that render was unsuccessful\r
+        hr = renderClient->ReleaseBuffer( 0, 0 );\r
+        if ( FAILED( hr ) ) {\r
+          errorText_ = "RtApiWasapi::wasapiThread: Unable to release render buffer.";\r
+          goto Exit;\r
+        }\r
+      }\r
+    }\r
+\r
+    // if the callback buffer was pushed renderBuffer reset callbackPulled flag\r
+    if ( callbackPushed ) {\r
+      callbackPulled = false;\r
+      // tick stream time\r
+      RtApi::tickStreamTime();\r
+    }\r
+\r
+  }\r
+\r
+Exit:\r
+  // clean up\r
+  CoTaskMemFree( captureFormat );\r
+  CoTaskMemFree( renderFormat );\r
+\r
+  free ( convBuffer );\r
+\r
+  CoUninitialize();\r
+\r
+  // update stream state\r
+  stream_.state = STREAM_STOPPED;\r
+\r
+  if ( errorText_.empty() )\r
+    return;\r
+  else\r
+    error( errorType );\r
+}\r
+\r
+//******************** End of __WINDOWS_WASAPI__ *********************//\r
+#endif\r
+\r
+\r
+#if defined(__WINDOWS_DS__) // Windows DirectSound API\r
+\r
+// Modified by Robin Davies, October 2005\r
+// - Improvements to DirectX pointer chasing. \r
+// - Bug fix for non-power-of-two Asio granularity used by Edirol PCR-A30.\r
+// - Auto-call CoInitialize for DSOUND and ASIO platforms.\r
+// Various revisions for RtAudio 4.0 by Gary Scavone, April 2007\r
+// Changed device query structure for RtAudio 4.0.7, January 2010\r
+\r
+#include <dsound.h>\r
+#include <assert.h>\r
+#include <algorithm>\r
+\r
+#if defined(__MINGW32__)\r
+  // missing from latest mingw winapi\r
+#define WAVE_FORMAT_96M08 0x00010000 /* 96 kHz, Mono, 8-bit */\r
+#define WAVE_FORMAT_96S08 0x00020000 /* 96 kHz, Stereo, 8-bit */\r
+#define WAVE_FORMAT_96M16 0x00040000 /* 96 kHz, Mono, 16-bit */\r
+#define WAVE_FORMAT_96S16 0x00080000 /* 96 kHz, Stereo, 16-bit */\r
+#endif\r
+\r
+#define MINIMUM_DEVICE_BUFFER_SIZE 32768\r
+\r
+#ifdef _MSC_VER // if Microsoft Visual C++\r
+#pragma comment( lib, "winmm.lib" ) // then, auto-link winmm.lib. Otherwise, it has to be added manually.\r
+#endif\r
+\r
+static inline DWORD dsPointerBetween( DWORD pointer, DWORD laterPointer, DWORD earlierPointer, DWORD bufferSize )\r
+{\r
+  if ( pointer > bufferSize ) pointer -= bufferSize;\r
+  if ( laterPointer < earlierPointer ) laterPointer += bufferSize;\r
+  if ( pointer < earlierPointer ) pointer += bufferSize;\r
+  return pointer >= earlierPointer && pointer < laterPointer;\r
+}\r
+\r
+// A structure to hold various information related to the DirectSound\r
+// API implementation.\r
+struct DsHandle {\r
+  unsigned int drainCounter; // Tracks callback counts when draining\r
+  bool internalDrain;        // Indicates if stop is initiated from callback or not.\r
+  void *id[2];\r
+  void *buffer[2];\r
+  bool xrun[2];\r
+  UINT bufferPointer[2];  \r
+  DWORD dsBufferSize[2];\r
+  DWORD dsPointerLeadTime[2]; // the number of bytes ahead of the safe pointer to lead by.\r
+  HANDLE condition;\r
+\r
+  DsHandle()\r
+    :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; }\r
+};\r
+\r
+// Declarations for utility functions, callbacks, and structures\r
+// specific to the DirectSound implementation.\r
+static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,\r
+                                          LPCTSTR description,\r
+                                          LPCTSTR module,\r
+                                          LPVOID lpContext );\r
+\r
+static const char* getErrorString( int code );\r
+\r
+static unsigned __stdcall callbackHandler( void *ptr );\r
+\r
+struct DsDevice {\r
+  LPGUID id[2];\r
+  bool validId[2];\r
+  bool found;\r
+  std::string name;\r
+\r
+  DsDevice()\r
+  : found(false) { validId[0] = false; validId[1] = false; }\r
+};\r
+\r
+struct DsProbeData {\r
+  bool isInput;\r
+  std::vector<struct DsDevice>* dsDevices;\r
+};\r
+\r
+RtApiDs :: RtApiDs()\r
+{\r
+  // Dsound will run both-threaded. If CoInitialize fails, then just\r
+  // accept whatever the mainline chose for a threading model.\r
+  coInitialized_ = false;\r
+  HRESULT hr = CoInitialize( NULL );\r
+  if ( !FAILED( hr ) ) coInitialized_ = true;\r
+}\r
+\r
+RtApiDs :: ~RtApiDs()\r
+{\r
+  if ( coInitialized_ ) CoUninitialize(); // balanced call.\r
+  if ( stream_.state != STREAM_CLOSED ) closeStream();\r
+}\r
+\r
+// The DirectSound default output is always the first device.\r
+unsigned int RtApiDs :: getDefaultOutputDevice( void )\r
+{\r
+  return 0;\r
+}\r
+\r
+// The DirectSound default input is always the first input device,\r
+// which is the first capture device enumerated.\r
+unsigned int RtApiDs :: getDefaultInputDevice( void )\r
+{\r
+  return 0;\r
+}\r
+\r
+unsigned int RtApiDs :: getDeviceCount( void )\r
+{\r
+  // Set query flag for previously found devices to false, so that we\r
+  // can check for any devices that have disappeared.\r
+  for ( unsigned int i=0; i<dsDevices.size(); i++ )\r
+    dsDevices[i].found = false;\r
+\r
+  // Query DirectSound devices.\r
+  struct DsProbeData probeInfo;\r
+  probeInfo.isInput = false;\r
+  probeInfo.dsDevices = &dsDevices;\r
+  HRESULT result = DirectSoundEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );\r
+  if ( FAILED( result ) ) {\r
+    errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating output devices!";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+  }\r
+\r
+  // Query DirectSoundCapture devices.\r
+  probeInfo.isInput = true;\r
+  result = DirectSoundCaptureEnumerate( (LPDSENUMCALLBACK) deviceQueryCallback, &probeInfo );\r
+  if ( FAILED( result ) ) {\r
+    errorStream_ << "RtApiDs::getDeviceCount: error (" << getErrorString( result ) << ") enumerating input devices!";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+  }\r
+\r
+  // Clean out any devices that may have disappeared (code update submitted by Eli Zehngut).\r
+  for ( unsigned int i=0; i<dsDevices.size(); ) {\r
+    if ( dsDevices[i].found == false ) dsDevices.erase( dsDevices.begin() + i );\r
+    else i++;\r
+  }\r
+\r
+  return static_cast<unsigned int>(dsDevices.size());\r
+}\r
+\r
+RtAudio::DeviceInfo RtApiDs :: getDeviceInfo( unsigned int device )\r
+{\r
+  RtAudio::DeviceInfo info;\r
+  info.probed = false;\r
+\r
+  if ( dsDevices.size() == 0 ) {\r
+    // Force a query of all devices\r
+    getDeviceCount();\r
+    if ( dsDevices.size() == 0 ) {\r
+      errorText_ = "RtApiDs::getDeviceInfo: no devices found!";\r
+      error( RtAudioError::INVALID_USE );\r
+      return info;\r
+    }\r
+  }\r
+\r
+  if ( device >= dsDevices.size() ) {\r
+    errorText_ = "RtApiDs::getDeviceInfo: device ID is invalid!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return info;\r
+  }\r
+\r
+  HRESULT result;\r
+  if ( dsDevices[ device ].validId[0] == false ) goto probeInput;\r
+\r
+  LPDIRECTSOUND output;\r
+  DSCAPS outCaps;\r
+  result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );\r
+  if ( FAILED( result ) ) {\r
+    errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    goto probeInput;\r
+  }\r
+\r
+  outCaps.dwSize = sizeof( outCaps );\r
+  result = output->GetCaps( &outCaps );\r
+  if ( FAILED( result ) ) {\r
+    output->Release();\r
+    errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting capabilities!";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    goto probeInput;\r
+  }\r
+\r
+  // Get output channel information.\r
+  info.outputChannels = ( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ? 2 : 1;\r
+\r
+  // Get sample rate information.\r
+  info.sampleRates.clear();\r
+  for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
+    if ( SAMPLE_RATES[k] >= (unsigned int) outCaps.dwMinSecondarySampleRate &&\r
+         SAMPLE_RATES[k] <= (unsigned int) outCaps.dwMaxSecondarySampleRate ) {\r
+      info.sampleRates.push_back( SAMPLE_RATES[k] );\r
+\r
+      if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )\r
+        info.preferredSampleRate = SAMPLE_RATES[k];\r
+    }\r
+  }\r
+\r
+  // Get format information.\r
+  if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT ) info.nativeFormats |= RTAUDIO_SINT16;\r
+  if ( outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) info.nativeFormats |= RTAUDIO_SINT8;\r
+\r
+  output->Release();\r
+\r
+  if ( getDefaultOutputDevice() == device )\r
+    info.isDefaultOutput = true;\r
+\r
+  if ( dsDevices[ device ].validId[1] == false ) {\r
+    info.name = dsDevices[ device ].name;\r
+    info.probed = true;\r
+    return info;\r
+  }\r
+\r
+ probeInput:\r
+\r
+  LPDIRECTSOUNDCAPTURE input;\r
+  result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );\r
+  if ( FAILED( result ) ) {\r
+    errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  DSCCAPS inCaps;\r
+  inCaps.dwSize = sizeof( inCaps );\r
+  result = input->GetCaps( &inCaps );\r
+  if ( FAILED( result ) ) {\r
+    input->Release();\r
+    errorStream_ << "RtApiDs::getDeviceInfo: error (" << getErrorString( result ) << ") getting object capabilities (" << dsDevices[ device ].name << ")!";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // Get input channel information.\r
+  info.inputChannels = inCaps.dwChannels;\r
+\r
+  // Get sample rate and format information.\r
+  std::vector<unsigned int> rates;\r
+  if ( inCaps.dwChannels >= 2 ) {\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+\r
+    if ( info.nativeFormats & RTAUDIO_SINT16 ) {\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_1S16 ) rates.push_back( 11025 );\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_2S16 ) rates.push_back( 22050 );\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_4S16 ) rates.push_back( 44100 );\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_96S16 ) rates.push_back( 96000 );\r
+    }\r
+    else if ( info.nativeFormats & RTAUDIO_SINT8 ) {\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_1S08 ) rates.push_back( 11025 );\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_2S08 ) rates.push_back( 22050 );\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_4S08 ) rates.push_back( 44100 );\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_96S08 ) rates.push_back( 96000 );\r
+    }\r
+  }\r
+  else if ( inCaps.dwChannels == 1 ) {\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) info.nativeFormats |= RTAUDIO_SINT16;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+    if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) info.nativeFormats |= RTAUDIO_SINT8;\r
+\r
+    if ( info.nativeFormats & RTAUDIO_SINT16 ) {\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_1M16 ) rates.push_back( 11025 );\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_2M16 ) rates.push_back( 22050 );\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_4M16 ) rates.push_back( 44100 );\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_96M16 ) rates.push_back( 96000 );\r
+    }\r
+    else if ( info.nativeFormats & RTAUDIO_SINT8 ) {\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_1M08 ) rates.push_back( 11025 );\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_2M08 ) rates.push_back( 22050 );\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_4M08 ) rates.push_back( 44100 );\r
+      if ( inCaps.dwFormats & WAVE_FORMAT_96M08 ) rates.push_back( 96000 );\r
+    }\r
+  }\r
+  else info.inputChannels = 0; // technically, this would be an error\r
+\r
+  input->Release();\r
+\r
+  if ( info.inputChannels == 0 ) return info;\r
+\r
+  // Copy the supported rates to the info structure but avoid duplication.\r
+  bool found;\r
+  for ( unsigned int i=0; i<rates.size(); i++ ) {\r
+    found = false;\r
+    for ( unsigned int j=0; j<info.sampleRates.size(); j++ ) {\r
+      if ( rates[i] == info.sampleRates[j] ) {\r
+        found = true;\r
+        break;\r
+      }\r
+    }\r
+    if ( found == false ) info.sampleRates.push_back( rates[i] );\r
+  }\r
+  std::sort( info.sampleRates.begin(), info.sampleRates.end() );\r
+\r
+  // If device opens for both playback and capture, we determine the channels.\r
+  if ( info.outputChannels > 0 && info.inputChannels > 0 )\r
+    info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;\r
+\r
+  if ( device == 0 ) info.isDefaultInput = true;\r
+\r
+  // Copy name and return.\r
+  info.name = dsDevices[ device ].name;\r
+  info.probed = true;\r
+  return info;\r
+}\r
+\r
+bool RtApiDs :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,\r
+                                 unsigned int firstChannel, unsigned int sampleRate,\r
+                                 RtAudioFormat format, unsigned int *bufferSize,\r
+                                 RtAudio::StreamOptions *options )\r
+{\r
+  if ( channels + firstChannel > 2 ) {\r
+    errorText_ = "RtApiDs::probeDeviceOpen: DirectSound does not support more than 2 channels per device.";\r
+    return FAILURE;\r
+  }\r
+\r
+  size_t nDevices = dsDevices.size();\r
+  if ( nDevices == 0 ) {\r
+    // This should not happen because a check is made before this function is called.\r
+    errorText_ = "RtApiDs::probeDeviceOpen: no devices found!";\r
+    return FAILURE;\r
+  }\r
+\r
+  if ( device >= nDevices ) {\r
+    // This should not happen because a check is made before this function is called.\r
+    errorText_ = "RtApiDs::probeDeviceOpen: device ID is invalid!";\r
+    return FAILURE;\r
+  }\r
+\r
+  if ( mode == OUTPUT ) {\r
+    if ( dsDevices[ device ].validId[0] == false ) {\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support output!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+  }\r
+  else { // mode == INPUT\r
+    if ( dsDevices[ device ].validId[1] == false ) {\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: device (" << device << ") does not support input!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+  }\r
+\r
+  // According to a note in PortAudio, using GetDesktopWindow()\r
+  // instead of GetForegroundWindow() is supposed to avoid problems\r
+  // that occur when the application's window is not the foreground\r
+  // window.  Also, if the application window closes before the\r
+  // DirectSound buffer, DirectSound can crash.  In the past, I had\r
+  // problems when using GetDesktopWindow() but it seems fine now\r
+  // (January 2010).  I'll leave it commented here.\r
+  // HWND hWnd = GetForegroundWindow();\r
+  HWND hWnd = GetDesktopWindow();\r
+\r
+  // Check the numberOfBuffers parameter and limit the lowest value to\r
+  // two.  This is a judgement call and a value of two is probably too\r
+  // low for capture, but it should work for playback.\r
+  int nBuffers = 0;\r
+  if ( options ) nBuffers = options->numberOfBuffers;\r
+  if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) nBuffers = 2;\r
+  if ( nBuffers < 2 ) nBuffers = 3;\r
+\r
+  // Check the lower range of the user-specified buffer size and set\r
+  // (arbitrarily) to a lower bound of 32.\r
+  if ( *bufferSize < 32 ) *bufferSize = 32;\r
+\r
+  // Create the wave format structure.  The data format setting will\r
+  // be determined later.\r
+  WAVEFORMATEX waveFormat;\r
+  ZeroMemory( &waveFormat, sizeof(WAVEFORMATEX) );\r
+  waveFormat.wFormatTag = WAVE_FORMAT_PCM;\r
+  waveFormat.nChannels = channels + firstChannel;\r
+  waveFormat.nSamplesPerSec = (unsigned long) sampleRate;\r
+\r
+  // Determine the device buffer size. By default, we'll use the value\r
+  // defined above (32K), but we will grow it to make allowances for\r
+  // very large software buffer sizes.\r
+  DWORD dsBufferSize = MINIMUM_DEVICE_BUFFER_SIZE;\r
+  DWORD dsPointerLeadTime = 0;\r
+\r
+  void *ohandle = 0, *bhandle = 0;\r
+  HRESULT result;\r
+  if ( mode == OUTPUT ) {\r
+\r
+    LPDIRECTSOUND output;\r
+    result = DirectSoundCreate( dsDevices[ device ].id[0], &output, NULL );\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening output device (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    DSCAPS outCaps;\r
+    outCaps.dwSize = sizeof( outCaps );\r
+    result = output->GetCaps( &outCaps );\r
+    if ( FAILED( result ) ) {\r
+      output->Release();\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting capabilities (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    // Check channel information.\r
+    if ( channels + firstChannel == 2 && !( outCaps.dwFlags & DSCAPS_PRIMARYSTEREO ) ) {\r
+      errorStream_ << "RtApiDs::getDeviceInfo: the output device (" << dsDevices[ device ].name << ") does not support stereo playback.";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    // Check format information.  Use 16-bit format unless not\r
+    // supported or user requests 8-bit.\r
+    if ( outCaps.dwFlags & DSCAPS_PRIMARY16BIT &&\r
+         !( format == RTAUDIO_SINT8 && outCaps.dwFlags & DSCAPS_PRIMARY8BIT ) ) {\r
+      waveFormat.wBitsPerSample = 16;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
+    }\r
+    else {\r
+      waveFormat.wBitsPerSample = 8;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
+    }\r
+    stream_.userFormat = format;\r
+\r
+    // Update wave format structure and buffer information.\r
+    waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;\r
+    waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;\r
+    dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;\r
+\r
+    // If the user wants an even bigger buffer, increase the device buffer size accordingly.\r
+    while ( dsPointerLeadTime * 2U > dsBufferSize )\r
+      dsBufferSize *= 2;\r
+\r
+    // Set cooperative level to DSSCL_EXCLUSIVE ... sound stops when window focus changes.\r
+    // result = output->SetCooperativeLevel( hWnd, DSSCL_EXCLUSIVE );\r
+    // Set cooperative level to DSSCL_PRIORITY ... sound remains when window focus changes.\r
+    result = output->SetCooperativeLevel( hWnd, DSSCL_PRIORITY );\r
+    if ( FAILED( result ) ) {\r
+      output->Release();\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting cooperative level (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    // Even though we will write to the secondary buffer, we need to\r
+    // access the primary buffer to set the correct output format\r
+    // (since the default is 8-bit, 22 kHz!).  Setup the DS primary\r
+    // buffer description.\r
+    DSBUFFERDESC bufferDescription;\r
+    ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );\r
+    bufferDescription.dwSize = sizeof( DSBUFFERDESC );\r
+    bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;\r
+\r
+    // Obtain the primary buffer\r
+    LPDIRECTSOUNDBUFFER buffer;\r
+    result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );\r
+    if ( FAILED( result ) ) {\r
+      output->Release();\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") accessing primary buffer (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    // Set the primary DS buffer sound format.\r
+    result = buffer->SetFormat( &waveFormat );\r
+    if ( FAILED( result ) ) {\r
+      output->Release();\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") setting primary buffer format (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    // Setup the secondary DS buffer description.\r
+    ZeroMemory( &bufferDescription, sizeof( DSBUFFERDESC ) );\r
+    bufferDescription.dwSize = sizeof( DSBUFFERDESC );\r
+    bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |\r
+                                  DSBCAPS_GLOBALFOCUS |\r
+                                  DSBCAPS_GETCURRENTPOSITION2 |\r
+                                  DSBCAPS_LOCHARDWARE );  // Force hardware mixing\r
+    bufferDescription.dwBufferBytes = dsBufferSize;\r
+    bufferDescription.lpwfxFormat = &waveFormat;\r
+\r
+    // Try to create the secondary DS buffer.  If that doesn't work,\r
+    // try to use software mixing.  Otherwise, there's a problem.\r
+    result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );\r
+    if ( FAILED( result ) ) {\r
+      bufferDescription.dwFlags = ( DSBCAPS_STICKYFOCUS |\r
+                                    DSBCAPS_GLOBALFOCUS |\r
+                                    DSBCAPS_GETCURRENTPOSITION2 |\r
+                                    DSBCAPS_LOCSOFTWARE );  // Force software mixing\r
+      result = output->CreateSoundBuffer( &bufferDescription, &buffer, NULL );\r
+      if ( FAILED( result ) ) {\r
+        output->Release();\r
+        errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating secondary buffer (" << dsDevices[ device ].name << ")!";\r
+        errorText_ = errorStream_.str();\r
+        return FAILURE;\r
+      }\r
+    }\r
+\r
+    // Get the buffer size ... might be different from what we specified.\r
+    DSBCAPS dsbcaps;\r
+    dsbcaps.dwSize = sizeof( DSBCAPS );\r
+    result = buffer->GetCaps( &dsbcaps );\r
+    if ( FAILED( result ) ) {\r
+      output->Release();\r
+      buffer->Release();\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    dsBufferSize = dsbcaps.dwBufferBytes;\r
+\r
+    // Lock the DS buffer\r
+    LPVOID audioPtr;\r
+    DWORD dataLen;\r
+    result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );\r
+    if ( FAILED( result ) ) {\r
+      output->Release();\r
+      buffer->Release();\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking buffer (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    // Zero the DS buffer\r
+    ZeroMemory( audioPtr, dataLen );\r
+\r
+    // Unlock the DS buffer\r
+    result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );\r
+    if ( FAILED( result ) ) {\r
+      output->Release();\r
+      buffer->Release();\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking buffer (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    ohandle = (void *) output;\r
+    bhandle = (void *) buffer;\r
+  }\r
+\r
+  if ( mode == INPUT ) {\r
+\r
+    LPDIRECTSOUNDCAPTURE input;\r
+    result = DirectSoundCaptureCreate( dsDevices[ device ].id[1], &input, NULL );\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") opening input device (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    DSCCAPS inCaps;\r
+    inCaps.dwSize = sizeof( inCaps );\r
+    result = input->GetCaps( &inCaps );\r
+    if ( FAILED( result ) ) {\r
+      input->Release();\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting input capabilities (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    // Check channel information.\r
+    if ( inCaps.dwChannels < channels + firstChannel ) {\r
+      errorText_ = "RtApiDs::getDeviceInfo: the input device does not support requested input channels.";\r
+      return FAILURE;\r
+    }\r
+\r
+    // Check format information.  Use 16-bit format unless user\r
+    // requests 8-bit.\r
+    DWORD deviceFormats;\r
+    if ( channels + firstChannel == 2 ) {\r
+      deviceFormats = WAVE_FORMAT_1S08 | WAVE_FORMAT_2S08 | WAVE_FORMAT_4S08 | WAVE_FORMAT_96S08;\r
+      if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {\r
+        waveFormat.wBitsPerSample = 8;\r
+        stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
+      }\r
+      else { // assume 16-bit is supported\r
+        waveFormat.wBitsPerSample = 16;\r
+        stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
+      }\r
+    }\r
+    else { // channel == 1\r
+      deviceFormats = WAVE_FORMAT_1M08 | WAVE_FORMAT_2M08 | WAVE_FORMAT_4M08 | WAVE_FORMAT_96M08;\r
+      if ( format == RTAUDIO_SINT8 && inCaps.dwFormats & deviceFormats ) {\r
+        waveFormat.wBitsPerSample = 8;\r
+        stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
+      }\r
+      else { // assume 16-bit is supported\r
+        waveFormat.wBitsPerSample = 16;\r
+        stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
+      }\r
+    }\r
+    stream_.userFormat = format;\r
+\r
+    // Update wave format structure and buffer information.\r
+    waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;\r
+    waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;\r
+    dsPointerLeadTime = nBuffers * (*bufferSize) * (waveFormat.wBitsPerSample / 8) * channels;\r
+\r
+    // If the user wants an even bigger buffer, increase the device buffer size accordingly.\r
+    while ( dsPointerLeadTime * 2U > dsBufferSize )\r
+      dsBufferSize *= 2;\r
+\r
+    // Setup the secondary DS buffer description.\r
+    DSCBUFFERDESC bufferDescription;\r
+    ZeroMemory( &bufferDescription, sizeof( DSCBUFFERDESC ) );\r
+    bufferDescription.dwSize = sizeof( DSCBUFFERDESC );\r
+    bufferDescription.dwFlags = 0;\r
+    bufferDescription.dwReserved = 0;\r
+    bufferDescription.dwBufferBytes = dsBufferSize;\r
+    bufferDescription.lpwfxFormat = &waveFormat;\r
+\r
+    // Create the capture buffer.\r
+    LPDIRECTSOUNDCAPTUREBUFFER buffer;\r
+    result = input->CreateCaptureBuffer( &bufferDescription, &buffer, NULL );\r
+    if ( FAILED( result ) ) {\r
+      input->Release();\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") creating input buffer (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    // Get the buffer size ... might be different from what we specified.\r
+    DSCBCAPS dscbcaps;\r
+    dscbcaps.dwSize = sizeof( DSCBCAPS );\r
+    result = buffer->GetCaps( &dscbcaps );\r
+    if ( FAILED( result ) ) {\r
+      input->Release();\r
+      buffer->Release();\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") getting buffer settings (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    dsBufferSize = dscbcaps.dwBufferBytes;\r
+\r
+    // NOTE: We could have a problem here if this is a duplex stream\r
+    // and the play and capture hardware buffer sizes are different\r
+    // (I'm actually not sure if that is a problem or not).\r
+    // Currently, we are not verifying that.\r
+\r
+    // Lock the capture buffer\r
+    LPVOID audioPtr;\r
+    DWORD dataLen;\r
+    result = buffer->Lock( 0, dsBufferSize, &audioPtr, &dataLen, NULL, NULL, 0 );\r
+    if ( FAILED( result ) ) {\r
+      input->Release();\r
+      buffer->Release();\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") locking input buffer (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    // Zero the buffer\r
+    ZeroMemory( audioPtr, dataLen );\r
+\r
+    // Unlock the buffer\r
+    result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );\r
+    if ( FAILED( result ) ) {\r
+      input->Release();\r
+      buffer->Release();\r
+      errorStream_ << "RtApiDs::probeDeviceOpen: error (" << getErrorString( result ) << ") unlocking input buffer (" << dsDevices[ device ].name << ")!";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+\r
+    ohandle = (void *) input;\r
+    bhandle = (void *) buffer;\r
+  }\r
+\r
+  // Set various stream parameters\r
+  DsHandle *handle = 0;\r
+  stream_.nDeviceChannels[mode] = channels + firstChannel;\r
+  stream_.nUserChannels[mode] = channels;\r
+  stream_.bufferSize = *bufferSize;\r
+  stream_.channelOffset[mode] = firstChannel;\r
+  stream_.deviceInterleaved[mode] = true;\r
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;\r
+  else stream_.userInterleaved = true;\r
+\r
+  // Set flag for buffer conversion\r
+  stream_.doConvertBuffer[mode] = false;\r
+  if (stream_.nUserChannels[mode] != stream_.nDeviceChannels[mode])\r
+    stream_.doConvertBuffer[mode] = true;\r
+  if (stream_.userFormat != stream_.deviceFormat[mode])\r
+    stream_.doConvertBuffer[mode] = true;\r
+  if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&\r
+       stream_.nUserChannels[mode] > 1 )\r
+    stream_.doConvertBuffer[mode] = true;\r
+\r
+  // Allocate necessary internal buffers\r
+  long bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );\r
+  stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );\r
+  if ( stream_.userBuffer[mode] == NULL ) {\r
+    errorText_ = "RtApiDs::probeDeviceOpen: error allocating user buffer memory.";\r
+    goto error;\r
+  }\r
+\r
+  if ( stream_.doConvertBuffer[mode] ) {\r
+\r
+    bool makeBuffer = true;\r
+    bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );\r
+    if ( mode == INPUT ) {\r
+      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {\r
+        unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
+        if ( bufferBytes <= (long) bytesOut ) makeBuffer = false;\r
+      }\r
+    }\r
+\r
+    if ( makeBuffer ) {\r
+      bufferBytes *= *bufferSize;\r
+      if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );\r
+      stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );\r
+      if ( stream_.deviceBuffer == NULL ) {\r
+        errorText_ = "RtApiDs::probeDeviceOpen: error allocating device buffer memory.";\r
+        goto error;\r
+      }\r
+    }\r
+  }\r
+\r
+  // Allocate our DsHandle structures for the stream.\r
+  if ( stream_.apiHandle == 0 ) {\r
+    try {\r
+      handle = new DsHandle;\r
+    }\r
+    catch ( std::bad_alloc& ) {\r
+      errorText_ = "RtApiDs::probeDeviceOpen: error allocating AsioHandle memory.";\r
+      goto error;\r
+    }\r
+\r
+    // Create a manual-reset event.\r
+    handle->condition = CreateEvent( NULL,   // no security\r
+                                     TRUE,   // manual-reset\r
+                                     FALSE,  // non-signaled initially\r
+                                     NULL ); // unnamed\r
+    stream_.apiHandle = (void *) handle;\r
+  }\r
+  else\r
+    handle = (DsHandle *) stream_.apiHandle;\r
+  handle->id[mode] = ohandle;\r
+  handle->buffer[mode] = bhandle;\r
+  handle->dsBufferSize[mode] = dsBufferSize;\r
+  handle->dsPointerLeadTime[mode] = dsPointerLeadTime;\r
+\r
+  stream_.device[mode] = device;\r
+  stream_.state = STREAM_STOPPED;\r
+  if ( stream_.mode == OUTPUT && mode == INPUT )\r
+    // We had already set up an output stream.\r
+    stream_.mode = DUPLEX;\r
+  else\r
+    stream_.mode = mode;\r
+  stream_.nBuffers = nBuffers;\r
+  stream_.sampleRate = sampleRate;\r
+\r
+  // Setup the buffer conversion information structure.\r
+  if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );\r
+\r
+  // Setup the callback thread.\r
+  if ( stream_.callbackInfo.isRunning == false ) {\r
+    unsigned threadId;\r
+    stream_.callbackInfo.isRunning = true;\r
+    stream_.callbackInfo.object = (void *) this;\r
+    stream_.callbackInfo.thread = _beginthreadex( NULL, 0, &callbackHandler,\r
+                                                  &stream_.callbackInfo, 0, &threadId );\r
+    if ( stream_.callbackInfo.thread == 0 ) {\r
+      errorText_ = "RtApiDs::probeDeviceOpen: error creating callback thread!";\r
+      goto error;\r
+    }\r
+\r
+    // Boost DS thread priority\r
+    SetThreadPriority( (HANDLE) stream_.callbackInfo.thread, THREAD_PRIORITY_HIGHEST );\r
+  }\r
+  return SUCCESS;\r
+\r
+ error:\r
+  if ( handle ) {\r
+    if ( handle->buffer[0] ) { // the object pointer can be NULL and valid\r
+      LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];\r
+      LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+      if ( buffer ) buffer->Release();\r
+      object->Release();\r
+    }\r
+    if ( handle->buffer[1] ) {\r
+      LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];\r
+      LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
+      if ( buffer ) buffer->Release();\r
+      object->Release();\r
+    }\r
+    CloseHandle( handle->condition );\r
+    delete handle;\r
+    stream_.apiHandle = 0;\r
+  }\r
+\r
+  for ( int i=0; i<2; i++ ) {\r
+    if ( stream_.userBuffer[i] ) {\r
+      free( stream_.userBuffer[i] );\r
+      stream_.userBuffer[i] = 0;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceBuffer ) {\r
+    free( stream_.deviceBuffer );\r
+    stream_.deviceBuffer = 0;\r
+  }\r
+\r
+  stream_.state = STREAM_CLOSED;\r
+  return FAILURE;\r
+}\r
+\r
+void RtApiDs :: closeStream()\r
+{\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiDs::closeStream(): no open stream to close!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  // Stop the callback thread.\r
+  stream_.callbackInfo.isRunning = false;\r
+  WaitForSingleObject( (HANDLE) stream_.callbackInfo.thread, INFINITE );\r
+  CloseHandle( (HANDLE) stream_.callbackInfo.thread );\r
+\r
+  DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
+  if ( handle ) {\r
+    if ( handle->buffer[0] ) { // the object pointer can be NULL and valid\r
+      LPDIRECTSOUND object = (LPDIRECTSOUND) handle->id[0];\r
+      LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+      if ( buffer ) {\r
+        buffer->Stop();\r
+        buffer->Release();\r
+      }\r
+      object->Release();\r
+    }\r
+    if ( handle->buffer[1] ) {\r
+      LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) handle->id[1];\r
+      LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
+      if ( buffer ) {\r
+        buffer->Stop();\r
+        buffer->Release();\r
+      }\r
+      object->Release();\r
+    }\r
+    CloseHandle( handle->condition );\r
+    delete handle;\r
+    stream_.apiHandle = 0;\r
+  }\r
+\r
+  for ( int i=0; i<2; i++ ) {\r
+    if ( stream_.userBuffer[i] ) {\r
+      free( stream_.userBuffer[i] );\r
+      stream_.userBuffer[i] = 0;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceBuffer ) {\r
+    free( stream_.deviceBuffer );\r
+    stream_.deviceBuffer = 0;\r
+  }\r
+\r
+  stream_.mode = UNINITIALIZED;\r
+  stream_.state = STREAM_CLOSED;\r
+}\r
+\r
+void RtApiDs :: startStream()\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_RUNNING ) {\r
+    errorText_ = "RtApiDs::startStream(): the stream is already running!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
+\r
+  // Increase scheduler frequency on lesser windows (a side-effect of\r
+  // increasing timer accuracy).  On greater windows (Win2K or later),\r
+  // this is already in effect.\r
+  timeBeginPeriod( 1 ); \r
+\r
+  buffersRolling = false;\r
+  duplexPrerollBytes = 0;\r
+\r
+  if ( stream_.mode == DUPLEX ) {\r
+    // 0.5 seconds of silence in DUPLEX mode while the devices spin up and synchronize.\r
+    duplexPrerollBytes = (int) ( 0.5 * stream_.sampleRate * formatBytes( stream_.deviceFormat[1] ) * stream_.nDeviceChannels[1] );\r
+  }\r
+\r
+  HRESULT result = 0;\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+\r
+    LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+    result = buffer->Play( 0, 0, DSBPLAY_LOOPING );\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting output buffer!";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+  }\r
+\r
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+\r
+    LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
+    result = buffer->Start( DSCBSTART_LOOPING );\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::startStream: error (" << getErrorString( result ) << ") starting input buffer!";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+  }\r
+\r
+  handle->drainCounter = 0;\r
+  handle->internalDrain = false;\r
+  ResetEvent( handle->condition );\r
+  stream_.state = STREAM_RUNNING;\r
+\r
+ unlock:\r
+  if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiDs :: stopStream()\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiDs::stopStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  HRESULT result = 0;\r
+  LPVOID audioPtr;\r
+  DWORD dataLen;\r
+  DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+    if ( handle->drainCounter == 0 ) {\r
+      handle->drainCounter = 2;\r
+      WaitForSingleObject( handle->condition, INFINITE );  // block until signaled\r
+    }\r
+\r
+    stream_.state = STREAM_STOPPED;\r
+\r
+    MUTEX_LOCK( &stream_.mutex );\r
+\r
+    // Stop the buffer and clear memory\r
+    LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+    result = buffer->Stop();\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping output buffer!";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+\r
+    // Lock the buffer and clear it so that if we start to play again,\r
+    // we won't have old data playing.\r
+    result = buffer->Lock( 0, handle->dsBufferSize[0], &audioPtr, &dataLen, NULL, NULL, 0 );\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking output buffer!";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+\r
+    // Zero the DS buffer\r
+    ZeroMemory( audioPtr, dataLen );\r
+\r
+    // Unlock the DS buffer\r
+    result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking output buffer!";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+\r
+    // If we start playing again, we must begin at beginning of buffer.\r
+    handle->bufferPointer[0] = 0;\r
+  }\r
+\r
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+    LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
+    audioPtr = NULL;\r
+    dataLen = 0;\r
+\r
+    stream_.state = STREAM_STOPPED;\r
+\r
+    if ( stream_.mode != DUPLEX )\r
+      MUTEX_LOCK( &stream_.mutex );\r
+\r
+    result = buffer->Stop();\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") stopping input buffer!";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+\r
+    // Lock the buffer and clear it so that if we start to play again,\r
+    // we won't have old data playing.\r
+    result = buffer->Lock( 0, handle->dsBufferSize[1], &audioPtr, &dataLen, NULL, NULL, 0 );\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") locking input buffer!";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+\r
+    // Zero the DS buffer\r
+    ZeroMemory( audioPtr, dataLen );\r
+\r
+    // Unlock the DS buffer\r
+    result = buffer->Unlock( audioPtr, dataLen, NULL, 0 );\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::stopStream: error (" << getErrorString( result ) << ") unlocking input buffer!";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+\r
+    // If we start recording again, we must begin at beginning of buffer.\r
+    handle->bufferPointer[1] = 0;\r
+  }\r
+\r
+ unlock:\r
+  timeEndPeriod( 1 ); // revert to normal scheduler frequency on lesser windows.\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+\r
+  if ( FAILED( result ) ) error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiDs :: abortStream()\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiDs::abortStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
+  handle->drainCounter = 2;\r
+\r
+  stopStream();\r
+}\r
+\r
+void RtApiDs :: callbackEvent()\r
+{\r
+  if ( stream_.state == STREAM_STOPPED || stream_.state == STREAM_STOPPING ) {\r
+    Sleep( 50 ); // sleep 50 milliseconds\r
+    return;\r
+  }\r
+\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiDs::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  CallbackInfo *info = (CallbackInfo *) &stream_.callbackInfo;\r
+  DsHandle *handle = (DsHandle *) stream_.apiHandle;\r
+\r
+  // Check if we were draining the stream and signal is finished.\r
+  if ( handle->drainCounter > stream_.nBuffers + 2 ) {\r
+\r
+    stream_.state = STREAM_STOPPING;\r
+    if ( handle->internalDrain == false )\r
+      SetEvent( handle->condition );\r
+    else\r
+      stopStream();\r
+    return;\r
+  }\r
+\r
+  // Invoke user callback to get fresh output data UNLESS we are\r
+  // draining stream.\r
+  if ( handle->drainCounter == 0 ) {\r
+    RtAudioCallback callback = (RtAudioCallback) info->callback;\r
+    double streamTime = getStreamTime();\r
+    RtAudioStreamStatus status = 0;\r
+    if ( stream_.mode != INPUT && handle->xrun[0] == true ) {\r
+      status |= RTAUDIO_OUTPUT_UNDERFLOW;\r
+      handle->xrun[0] = false;\r
+    }\r
+    if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {\r
+      status |= RTAUDIO_INPUT_OVERFLOW;\r
+      handle->xrun[1] = false;\r
+    }\r
+    int cbReturnValue = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
+                                  stream_.bufferSize, streamTime, status, info->userData );\r
+    if ( cbReturnValue == 2 ) {\r
+      stream_.state = STREAM_STOPPING;\r
+      handle->drainCounter = 2;\r
+      abortStream();\r
+      return;\r
+    }\r
+    else if ( cbReturnValue == 1 ) {\r
+      handle->drainCounter = 1;\r
+      handle->internalDrain = true;\r
+    }\r
+  }\r
+\r
+  HRESULT result;\r
+  DWORD currentWritePointer, safeWritePointer;\r
+  DWORD currentReadPointer, safeReadPointer;\r
+  UINT nextWritePointer;\r
+\r
+  LPVOID buffer1 = NULL;\r
+  LPVOID buffer2 = NULL;\r
+  DWORD bufferSize1 = 0;\r
+  DWORD bufferSize2 = 0;\r
+\r
+  char *buffer;\r
+  long bufferBytes;\r
+\r
+  MUTEX_LOCK( &stream_.mutex );\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    MUTEX_UNLOCK( &stream_.mutex );\r
+    return;\r
+  }\r
+\r
+  if ( buffersRolling == false ) {\r
+    if ( stream_.mode == DUPLEX ) {\r
+      //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );\r
+\r
+      // It takes a while for the devices to get rolling. As a result,\r
+      // there's no guarantee that the capture and write device pointers\r
+      // will move in lockstep.  Wait here for both devices to start\r
+      // rolling, and then set our buffer pointers accordingly.\r
+      // e.g. Crystal Drivers: the capture buffer starts up 5700 to 9600\r
+      // bytes later than the write buffer.\r
+\r
+      // Stub: a serious risk of having a pre-emptive scheduling round\r
+      // take place between the two GetCurrentPosition calls... but I'm\r
+      // really not sure how to solve the problem.  Temporarily boost to\r
+      // Realtime priority, maybe; but I'm not sure what priority the\r
+      // DirectSound service threads run at. We *should* be roughly\r
+      // within a ms or so of correct.\r
+\r
+      LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+      LPDIRECTSOUNDCAPTUREBUFFER dsCaptureBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
+\r
+      DWORD startSafeWritePointer, startSafeReadPointer;\r
+\r
+      result = dsWriteBuffer->GetCurrentPosition( NULL, &startSafeWritePointer );\r
+      if ( FAILED( result ) ) {\r
+        errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
+        errorText_ = errorStream_.str();\r
+        MUTEX_UNLOCK( &stream_.mutex );\r
+        error( RtAudioError::SYSTEM_ERROR );\r
+        return;\r
+      }\r
+      result = dsCaptureBuffer->GetCurrentPosition( NULL, &startSafeReadPointer );\r
+      if ( FAILED( result ) ) {\r
+        errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
+        errorText_ = errorStream_.str();\r
+        MUTEX_UNLOCK( &stream_.mutex );\r
+        error( RtAudioError::SYSTEM_ERROR );\r
+        return;\r
+      }\r
+      while ( true ) {\r
+        result = dsWriteBuffer->GetCurrentPosition( NULL, &safeWritePointer );\r
+        if ( FAILED( result ) ) {\r
+          errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
+          errorText_ = errorStream_.str();\r
+          MUTEX_UNLOCK( &stream_.mutex );\r
+          error( RtAudioError::SYSTEM_ERROR );\r
+          return;\r
+        }\r
+        result = dsCaptureBuffer->GetCurrentPosition( NULL, &safeReadPointer );\r
+        if ( FAILED( result ) ) {\r
+          errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
+          errorText_ = errorStream_.str();\r
+          MUTEX_UNLOCK( &stream_.mutex );\r
+          error( RtAudioError::SYSTEM_ERROR );\r
+          return;\r
+        }\r
+        if ( safeWritePointer != startSafeWritePointer && safeReadPointer != startSafeReadPointer ) break;\r
+        Sleep( 1 );\r
+      }\r
+\r
+      //assert( handle->dsBufferSize[0] == handle->dsBufferSize[1] );\r
+\r
+      handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];\r
+      if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];\r
+      handle->bufferPointer[1] = safeReadPointer;\r
+    }\r
+    else if ( stream_.mode == OUTPUT ) {\r
+\r
+      // Set the proper nextWritePosition after initial startup.\r
+      LPDIRECTSOUNDBUFFER dsWriteBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+      result = dsWriteBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );\r
+      if ( FAILED( result ) ) {\r
+        errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
+        errorText_ = errorStream_.str();\r
+        MUTEX_UNLOCK( &stream_.mutex );\r
+        error( RtAudioError::SYSTEM_ERROR );\r
+        return;\r
+      }\r
+      handle->bufferPointer[0] = safeWritePointer + handle->dsPointerLeadTime[0];\r
+      if ( handle->bufferPointer[0] >= handle->dsBufferSize[0] ) handle->bufferPointer[0] -= handle->dsBufferSize[0];\r
+    }\r
+\r
+    buffersRolling = true;\r
+  }\r
+\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+    \r
+    LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) handle->buffer[0];\r
+\r
+    if ( handle->drainCounter > 1 ) { // write zeros to the output stream\r
+      bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];\r
+      bufferBytes *= formatBytes( stream_.userFormat );\r
+      memset( stream_.userBuffer[0], 0, bufferBytes );\r
+    }\r
+\r
+    // Setup parameters and do buffer conversion if necessary.\r
+    if ( stream_.doConvertBuffer[0] ) {\r
+      buffer = stream_.deviceBuffer;\r
+      convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );\r
+      bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[0];\r
+      bufferBytes *= formatBytes( stream_.deviceFormat[0] );\r
+    }\r
+    else {\r
+      buffer = stream_.userBuffer[0];\r
+      bufferBytes = stream_.bufferSize * stream_.nUserChannels[0];\r
+      bufferBytes *= formatBytes( stream_.userFormat );\r
+    }\r
+\r
+    // No byte swapping necessary in DirectSound implementation.\r
+\r
+    // Ahhh ... windoze.  16-bit data is signed but 8-bit data is\r
+    // unsigned.  So, we need to convert our signed 8-bit data here to\r
+    // unsigned.\r
+    if ( stream_.deviceFormat[0] == RTAUDIO_SINT8 )\r
+      for ( int i=0; i<bufferBytes; i++ ) buffer[i] = (unsigned char) ( buffer[i] + 128 );\r
+\r
+    DWORD dsBufferSize = handle->dsBufferSize[0];\r
+    nextWritePointer = handle->bufferPointer[0];\r
+\r
+    DWORD endWrite, leadPointer;\r
+    while ( true ) {\r
+      // Find out where the read and "safe write" pointers are.\r
+      result = dsBuffer->GetCurrentPosition( &currentWritePointer, &safeWritePointer );\r
+      if ( FAILED( result ) ) {\r
+        errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current write position!";\r
+        errorText_ = errorStream_.str();\r
+        MUTEX_UNLOCK( &stream_.mutex );\r
+        error( RtAudioError::SYSTEM_ERROR );\r
+        return;\r
+      }\r
+\r
+      // We will copy our output buffer into the region between\r
+      // safeWritePointer and leadPointer.  If leadPointer is not\r
+      // beyond the next endWrite position, wait until it is.\r
+      leadPointer = safeWritePointer + handle->dsPointerLeadTime[0];\r
+      //std::cout << "safeWritePointer = " << safeWritePointer << ", leadPointer = " << leadPointer << ", nextWritePointer = " << nextWritePointer << std::endl;\r
+      if ( leadPointer > dsBufferSize ) leadPointer -= dsBufferSize;\r
+      if ( leadPointer < nextWritePointer ) leadPointer += dsBufferSize; // unwrap offset\r
+      endWrite = nextWritePointer + bufferBytes;\r
+\r
+      // Check whether the entire write region is behind the play pointer.\r
+      if ( leadPointer >= endWrite ) break;\r
+\r
+      // If we are here, then we must wait until the leadPointer advances\r
+      // beyond the end of our next write region. We use the\r
+      // Sleep() function to suspend operation until that happens.\r
+      double millis = ( endWrite - leadPointer ) * 1000.0;\r
+      millis /= ( formatBytes( stream_.deviceFormat[0]) * stream_.nDeviceChannels[0] * stream_.sampleRate);\r
+      if ( millis < 1.0 ) millis = 1.0;\r
+      Sleep( (DWORD) millis );\r
+    }\r
+\r
+    if ( dsPointerBetween( nextWritePointer, safeWritePointer, currentWritePointer, dsBufferSize )\r
+         || dsPointerBetween( endWrite, safeWritePointer, currentWritePointer, dsBufferSize ) ) { \r
+      // We've strayed into the forbidden zone ... resync the read pointer.\r
+      handle->xrun[0] = true;\r
+      nextWritePointer = safeWritePointer + handle->dsPointerLeadTime[0] - bufferBytes;\r
+      if ( nextWritePointer >= dsBufferSize ) nextWritePointer -= dsBufferSize;\r
+      handle->bufferPointer[0] = nextWritePointer;\r
+      endWrite = nextWritePointer + bufferBytes;\r
+    }\r
+\r
+    // Lock free space in the buffer\r
+    result = dsBuffer->Lock( nextWritePointer, bufferBytes, &buffer1,\r
+                             &bufferSize1, &buffer2, &bufferSize2, 0 );\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking buffer during playback!";\r
+      errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
+      error( RtAudioError::SYSTEM_ERROR );\r
+      return;\r
+    }\r
+\r
+    // Copy our buffer into the DS buffer\r
+    CopyMemory( buffer1, buffer, bufferSize1 );\r
+    if ( buffer2 != NULL ) CopyMemory( buffer2, buffer+bufferSize1, bufferSize2 );\r
+\r
+    // Update our buffer offset and unlock sound buffer\r
+    dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking buffer during playback!";\r
+      errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
+      error( RtAudioError::SYSTEM_ERROR );\r
+      return;\r
+    }\r
+    nextWritePointer = ( nextWritePointer + bufferSize1 + bufferSize2 ) % dsBufferSize;\r
+    handle->bufferPointer[0] = nextWritePointer;\r
+  }\r
+\r
+  // Don't bother draining input\r
+  if ( handle->drainCounter ) {\r
+    handle->drainCounter++;\r
+    goto unlock;\r
+  }\r
+\r
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+\r
+    // Setup parameters.\r
+    if ( stream_.doConvertBuffer[1] ) {\r
+      buffer = stream_.deviceBuffer;\r
+      bufferBytes = stream_.bufferSize * stream_.nDeviceChannels[1];\r
+      bufferBytes *= formatBytes( stream_.deviceFormat[1] );\r
+    }\r
+    else {\r
+      buffer = stream_.userBuffer[1];\r
+      bufferBytes = stream_.bufferSize * stream_.nUserChannels[1];\r
+      bufferBytes *= formatBytes( stream_.userFormat );\r
+    }\r
+\r
+    LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) handle->buffer[1];\r
+    long nextReadPointer = handle->bufferPointer[1];\r
+    DWORD dsBufferSize = handle->dsBufferSize[1];\r
+\r
+    // Find out where the write and "safe read" pointers are.\r
+    result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
+      errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
+      error( RtAudioError::SYSTEM_ERROR );\r
+      return;\r
+    }\r
+\r
+    if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset\r
+    DWORD endRead = nextReadPointer + bufferBytes;\r
+\r
+    // Handling depends on whether we are INPUT or DUPLEX. \r
+    // If we're in INPUT mode then waiting is a good thing. If we're in DUPLEX mode,\r
+    // then a wait here will drag the write pointers into the forbidden zone.\r
+    // \r
+    // In DUPLEX mode, rather than wait, we will back off the read pointer until \r
+    // it's in a safe position. This causes dropouts, but it seems to be the only \r
+    // practical way to sync up the read and write pointers reliably, given the \r
+    // the very complex relationship between phase and increment of the read and write \r
+    // pointers.\r
+    //\r
+    // In order to minimize audible dropouts in DUPLEX mode, we will\r
+    // provide a pre-roll period of 0.5 seconds in which we return\r
+    // zeros from the read buffer while the pointers sync up.\r
+\r
+    if ( stream_.mode == DUPLEX ) {\r
+      if ( safeReadPointer < endRead ) {\r
+        if ( duplexPrerollBytes <= 0 ) {\r
+          // Pre-roll time over. Be more agressive.\r
+          int adjustment = endRead-safeReadPointer;\r
+\r
+          handle->xrun[1] = true;\r
+          // Two cases:\r
+          //   - large adjustments: we've probably run out of CPU cycles, so just resync exactly,\r
+          //     and perform fine adjustments later.\r
+          //   - small adjustments: back off by twice as much.\r
+          if ( adjustment >= 2*bufferBytes )\r
+            nextReadPointer = safeReadPointer-2*bufferBytes;\r
+          else\r
+            nextReadPointer = safeReadPointer-bufferBytes-adjustment;\r
+\r
+          if ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;\r
+\r
+        }\r
+        else {\r
+          // In pre=roll time. Just do it.\r
+          nextReadPointer = safeReadPointer - bufferBytes;\r
+          while ( nextReadPointer < 0 ) nextReadPointer += dsBufferSize;\r
+        }\r
+        endRead = nextReadPointer + bufferBytes;\r
+      }\r
+    }\r
+    else { // mode == INPUT\r
+      while ( safeReadPointer < endRead && stream_.callbackInfo.isRunning ) {\r
+        // See comments for playback.\r
+        double millis = (endRead - safeReadPointer) * 1000.0;\r
+        millis /= ( formatBytes(stream_.deviceFormat[1]) * stream_.nDeviceChannels[1] * stream_.sampleRate);\r
+        if ( millis < 1.0 ) millis = 1.0;\r
+        Sleep( (DWORD) millis );\r
+\r
+        // Wake up and find out where we are now.\r
+        result = dsBuffer->GetCurrentPosition( &currentReadPointer, &safeReadPointer );\r
+        if ( FAILED( result ) ) {\r
+          errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") getting current read position!";\r
+          errorText_ = errorStream_.str();\r
+          MUTEX_UNLOCK( &stream_.mutex );\r
+          error( RtAudioError::SYSTEM_ERROR );\r
+          return;\r
+        }\r
+      \r
+        if ( safeReadPointer < (DWORD)nextReadPointer ) safeReadPointer += dsBufferSize; // unwrap offset\r
+      }\r
+    }\r
+\r
+    // Lock free space in the buffer\r
+    result = dsBuffer->Lock( nextReadPointer, bufferBytes, &buffer1,\r
+                             &bufferSize1, &buffer2, &bufferSize2, 0 );\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") locking capture buffer!";\r
+      errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
+      error( RtAudioError::SYSTEM_ERROR );\r
+      return;\r
+    }\r
+\r
+    if ( duplexPrerollBytes <= 0 ) {\r
+      // Copy our buffer into the DS buffer\r
+      CopyMemory( buffer, buffer1, bufferSize1 );\r
+      if ( buffer2 != NULL ) CopyMemory( buffer+bufferSize1, buffer2, bufferSize2 );\r
+    }\r
+    else {\r
+      memset( buffer, 0, bufferSize1 );\r
+      if ( buffer2 != NULL ) memset( buffer + bufferSize1, 0, bufferSize2 );\r
+      duplexPrerollBytes -= bufferSize1 + bufferSize2;\r
+    }\r
+\r
+    // Update our buffer offset and unlock sound buffer\r
+    nextReadPointer = ( nextReadPointer + bufferSize1 + bufferSize2 ) % dsBufferSize;\r
+    dsBuffer->Unlock( buffer1, bufferSize1, buffer2, bufferSize2 );\r
+    if ( FAILED( result ) ) {\r
+      errorStream_ << "RtApiDs::callbackEvent: error (" << getErrorString( result ) << ") unlocking capture buffer!";\r
+      errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
+      error( RtAudioError::SYSTEM_ERROR );\r
+      return;\r
+    }\r
+    handle->bufferPointer[1] = nextReadPointer;\r
+\r
+    // No byte swapping necessary in DirectSound implementation.\r
+\r
+    // If necessary, convert 8-bit data from unsigned to signed.\r
+    if ( stream_.deviceFormat[1] == RTAUDIO_SINT8 )\r
+      for ( int j=0; j<bufferBytes; j++ ) buffer[j] = (signed char) ( buffer[j] - 128 );\r
+\r
+    // Do buffer conversion if necessary.\r
+    if ( stream_.doConvertBuffer[1] )\r
+      convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );\r
+  }\r
+\r
+ unlock:\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+  RtApi::tickStreamTime();\r
+}\r
+\r
+// Definitions for utility functions and callbacks\r
+// specific to the DirectSound implementation.\r
+\r
+static unsigned __stdcall callbackHandler( void *ptr )\r
+{\r
+  CallbackInfo *info = (CallbackInfo *) ptr;\r
+  RtApiDs *object = (RtApiDs *) info->object;\r
+  bool* isRunning = &info->isRunning;\r
+\r
+  while ( *isRunning == true ) {\r
+    object->callbackEvent();\r
+  }\r
+\r
+  _endthreadex( 0 );\r
+  return 0;\r
+}\r
+\r
+static BOOL CALLBACK deviceQueryCallback( LPGUID lpguid,\r
+                                          LPCTSTR description,\r
+                                          LPCTSTR /*module*/,\r
+                                          LPVOID lpContext )\r
+{\r
+  struct DsProbeData& probeInfo = *(struct DsProbeData*) lpContext;\r
+  std::vector<struct DsDevice>& dsDevices = *probeInfo.dsDevices;\r
+\r
+  HRESULT hr;\r
+  bool validDevice = false;\r
+  if ( probeInfo.isInput == true ) {\r
+    DSCCAPS caps;\r
+    LPDIRECTSOUNDCAPTURE object;\r
+\r
+    hr = DirectSoundCaptureCreate(  lpguid, &object,   NULL );\r
+    if ( hr != DS_OK ) return TRUE;\r
+\r
+    caps.dwSize = sizeof(caps);\r
+    hr = object->GetCaps( &caps );\r
+    if ( hr == DS_OK ) {\r
+      if ( caps.dwChannels > 0 && caps.dwFormats > 0 )\r
+        validDevice = true;\r
+    }\r
+    object->Release();\r
+  }\r
+  else {\r
+    DSCAPS caps;\r
+    LPDIRECTSOUND object;\r
+    hr = DirectSoundCreate(  lpguid, &object,   NULL );\r
+    if ( hr != DS_OK ) return TRUE;\r
+\r
+    caps.dwSize = sizeof(caps);\r
+    hr = object->GetCaps( &caps );\r
+    if ( hr == DS_OK ) {\r
+      if ( caps.dwFlags & DSCAPS_PRIMARYMONO || caps.dwFlags & DSCAPS_PRIMARYSTEREO )\r
+        validDevice = true;\r
+    }\r
+    object->Release();\r
+  }\r
+\r
+  // If good device, then save its name and guid.\r
+  std::string name = convertCharPointerToStdString( description );\r
+  //if ( name == "Primary Sound Driver" || name == "Primary Sound Capture Driver" )\r
+  if ( lpguid == NULL )\r
+    name = "Default Device";\r
+  if ( validDevice ) {\r
+    for ( unsigned int i=0; i<dsDevices.size(); i++ ) {\r
+      if ( dsDevices[i].name == name ) {\r
+        dsDevices[i].found = true;\r
+        if ( probeInfo.isInput ) {\r
+          dsDevices[i].id[1] = lpguid;\r
+          dsDevices[i].validId[1] = true;\r
+        }\r
+        else {\r
+          dsDevices[i].id[0] = lpguid;\r
+          dsDevices[i].validId[0] = true;\r
+        }\r
+        return TRUE;\r
+      }\r
+    }\r
+\r
+    DsDevice device;\r
+    device.name = name;\r
+    device.found = true;\r
+    if ( probeInfo.isInput ) {\r
+      device.id[1] = lpguid;\r
+      device.validId[1] = true;\r
+    }\r
+    else {\r
+      device.id[0] = lpguid;\r
+      device.validId[0] = true;\r
+    }\r
+    dsDevices.push_back( device );\r
+  }\r
+\r
+  return TRUE;\r
+}\r
+\r
+static const char* getErrorString( int code )\r
+{\r
+  switch ( code ) {\r
+\r
+  case DSERR_ALLOCATED:\r
+    return "Already allocated";\r
+\r
+  case DSERR_CONTROLUNAVAIL:\r
+    return "Control unavailable";\r
+\r
+  case DSERR_INVALIDPARAM:\r
+    return "Invalid parameter";\r
+\r
+  case DSERR_INVALIDCALL:\r
+    return "Invalid call";\r
+\r
+  case DSERR_GENERIC:\r
+    return "Generic error";\r
+\r
+  case DSERR_PRIOLEVELNEEDED:\r
+    return "Priority level needed";\r
+\r
+  case DSERR_OUTOFMEMORY:\r
+    return "Out of memory";\r
+\r
+  case DSERR_BADFORMAT:\r
+    return "The sample rate or the channel format is not supported";\r
+\r
+  case DSERR_UNSUPPORTED:\r
+    return "Not supported";\r
+\r
+  case DSERR_NODRIVER:\r
+    return "No driver";\r
+\r
+  case DSERR_ALREADYINITIALIZED:\r
+    return "Already initialized";\r
+\r
+  case DSERR_NOAGGREGATION:\r
+    return "No aggregation";\r
+\r
+  case DSERR_BUFFERLOST:\r
+    return "Buffer lost";\r
+\r
+  case DSERR_OTHERAPPHASPRIO:\r
+    return "Another application already has priority";\r
+\r
+  case DSERR_UNINITIALIZED:\r
+    return "Uninitialized";\r
+\r
+  default:\r
+    return "DirectSound unknown error";\r
+  }\r
+}\r
+//******************** End of __WINDOWS_DS__ *********************//\r
+#endif\r
+\r
+\r
+#if defined(__LINUX_ALSA__)\r
+\r
+#include <alsa/asoundlib.h>\r
+#include <unistd.h>\r
+\r
+  // A structure to hold various information related to the ALSA API\r
+  // implementation.\r
+struct AlsaHandle {\r
+  snd_pcm_t *handles[2];\r
+  bool synchronized;\r
+  bool xrun[2];\r
+  pthread_cond_t runnable_cv;\r
+  bool runnable;\r
+\r
+  AlsaHandle()\r
+    :synchronized(false), runnable(false) { xrun[0] = false; xrun[1] = false; }\r
+};\r
+\r
+static void *alsaCallbackHandler( void * ptr );\r
+\r
+RtApiAlsa :: RtApiAlsa()\r
+{\r
+  // Nothing to do here.\r
+}\r
+\r
+RtApiAlsa :: ~RtApiAlsa()\r
+{\r
+  if ( stream_.state != STREAM_CLOSED ) closeStream();\r
+}\r
+\r
+unsigned int RtApiAlsa :: getDeviceCount( void )\r
+{\r
+  unsigned nDevices = 0;\r
+  int result, subdevice, card;\r
+  char name[64];\r
+  snd_ctl_t *handle;\r
+\r
+  // Count cards and devices\r
+  card = -1;\r
+  snd_card_next( &card );\r
+  while ( card >= 0 ) {\r
+    sprintf( name, "hw:%d", card );\r
+    result = snd_ctl_open( &handle, name, 0 );\r
+    if ( result < 0 ) {\r
+      errorStream_ << "RtApiAlsa::getDeviceCount: control open, card = " << card << ", " << snd_strerror( result ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      error( RtAudioError::WARNING );\r
+      goto nextcard;\r
+    }\r
+    subdevice = -1;\r
+    while( 1 ) {\r
+      result = snd_ctl_pcm_next_device( handle, &subdevice );\r
+      if ( result < 0 ) {\r
+        errorStream_ << "RtApiAlsa::getDeviceCount: control next device, card = " << card << ", " << snd_strerror( result ) << ".";\r
+        errorText_ = errorStream_.str();\r
+        error( RtAudioError::WARNING );\r
+        break;\r
+      }\r
+      if ( subdevice < 0 )\r
+        break;\r
+      nDevices++;\r
+    }\r
+  nextcard:\r
+    snd_ctl_close( handle );\r
+    snd_card_next( &card );\r
+  }\r
+\r
+  result = snd_ctl_open( &handle, "default", 0 );\r
+  if (result == 0) {\r
+    nDevices++;\r
+    snd_ctl_close( handle );\r
+  }\r
+\r
+  return nDevices;\r
+}\r
+\r
+RtAudio::DeviceInfo RtApiAlsa :: getDeviceInfo( unsigned int device )\r
+{\r
+  RtAudio::DeviceInfo info;\r
+  info.probed = false;\r
+\r
+  unsigned nDevices = 0;\r
+  int result, subdevice, card;\r
+  char name[64];\r
+  snd_ctl_t *chandle;\r
+\r
+  // Count cards and devices\r
+  card = -1;\r
+  subdevice = -1;\r
+  snd_card_next( &card );\r
+  while ( card >= 0 ) {\r
+    sprintf( name, "hw:%d", card );\r
+    result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );\r
+    if ( result < 0 ) {\r
+      errorStream_ << "RtApiAlsa::getDeviceInfo: control open, card = " << card << ", " << snd_strerror( result ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      error( RtAudioError::WARNING );\r
+      goto nextcard;\r
+    }\r
+    subdevice = -1;\r
+    while( 1 ) {\r
+      result = snd_ctl_pcm_next_device( chandle, &subdevice );\r
+      if ( result < 0 ) {\r
+        errorStream_ << "RtApiAlsa::getDeviceInfo: control next device, card = " << card << ", " << snd_strerror( result ) << ".";\r
+        errorText_ = errorStream_.str();\r
+        error( RtAudioError::WARNING );\r
+        break;\r
+      }\r
+      if ( subdevice < 0 ) break;\r
+      if ( nDevices == device ) {\r
+        sprintf( name, "hw:%d,%d", card, subdevice );\r
+        goto foundDevice;\r
+      }\r
+      nDevices++;\r
+    }\r
+  nextcard:\r
+    snd_ctl_close( chandle );\r
+    snd_card_next( &card );\r
+  }\r
+\r
+  result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );\r
+  if ( result == 0 ) {\r
+    if ( nDevices == device ) {\r
+      strcpy( name, "default" );\r
+      goto foundDevice;\r
+    }\r
+    nDevices++;\r
+  }\r
+\r
+  if ( nDevices == 0 ) {\r
+    errorText_ = "RtApiAlsa::getDeviceInfo: no devices found!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return info;\r
+  }\r
+\r
+  if ( device >= nDevices ) {\r
+    errorText_ = "RtApiAlsa::getDeviceInfo: device ID is invalid!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return info;\r
+  }\r
+\r
+ foundDevice:\r
+\r
+  // If a stream is already open, we cannot probe the stream devices.\r
+  // Thus, use the saved results.\r
+  if ( stream_.state != STREAM_CLOSED &&\r
+       ( stream_.device[0] == device || stream_.device[1] == device ) ) {\r
+    snd_ctl_close( chandle );\r
+    if ( device >= devices_.size() ) {\r
+      errorText_ = "RtApiAlsa::getDeviceInfo: device ID was not present before stream was opened.";\r
+      error( RtAudioError::WARNING );\r
+      return info;\r
+    }\r
+    return devices_[ device ];\r
+  }\r
+\r
+  int openMode = SND_PCM_ASYNC;\r
+  snd_pcm_stream_t stream;\r
+  snd_pcm_info_t *pcminfo;\r
+  snd_pcm_info_alloca( &pcminfo );\r
+  snd_pcm_t *phandle;\r
+  snd_pcm_hw_params_t *params;\r
+  snd_pcm_hw_params_alloca( &params );\r
+\r
+  // First try for playback unless default device (which has subdev -1)\r
+  stream = SND_PCM_STREAM_PLAYBACK;\r
+  snd_pcm_info_set_stream( pcminfo, stream );\r
+  if ( subdevice != -1 ) {\r
+    snd_pcm_info_set_device( pcminfo, subdevice );\r
+    snd_pcm_info_set_subdevice( pcminfo, 0 );\r
+\r
+    result = snd_ctl_pcm_info( chandle, pcminfo );\r
+    if ( result < 0 ) {\r
+      // Device probably doesn't support playback.\r
+      goto captureProbe;\r
+    }\r
+  }\r
+\r
+  result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK );\r
+  if ( result < 0 ) {\r
+    errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    goto captureProbe;\r
+  }\r
+\r
+  // The device is open ... fill the parameter structure.\r
+  result = snd_pcm_hw_params_any( phandle, params );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    goto captureProbe;\r
+  }\r
+\r
+  // Get output channel information.\r
+  unsigned int value;\r
+  result = snd_pcm_hw_params_get_channels_max( params, &value );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") output channels, " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    goto captureProbe;\r
+  }\r
+  info.outputChannels = value;\r
+  snd_pcm_close( phandle );\r
+\r
+ captureProbe:\r
+  stream = SND_PCM_STREAM_CAPTURE;\r
+  snd_pcm_info_set_stream( pcminfo, stream );\r
+\r
+  // Now try for capture unless default device (with subdev = -1)\r
+  if ( subdevice != -1 ) {\r
+    result = snd_ctl_pcm_info( chandle, pcminfo );\r
+    snd_ctl_close( chandle );\r
+    if ( result < 0 ) {\r
+      // Device probably doesn't support capture.\r
+      if ( info.outputChannels == 0 ) return info;\r
+      goto probeParameters;\r
+    }\r
+  }\r
+  else\r
+    snd_ctl_close( chandle );\r
+\r
+  result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);\r
+  if ( result < 0 ) {\r
+    errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    if ( info.outputChannels == 0 ) return info;\r
+    goto probeParameters;\r
+  }\r
+\r
+  // The device is open ... fill the parameter structure.\r
+  result = snd_pcm_hw_params_any( phandle, params );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    if ( info.outputChannels == 0 ) return info;\r
+    goto probeParameters;\r
+  }\r
+\r
+  result = snd_pcm_hw_params_get_channels_max( params, &value );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::getDeviceInfo: error getting device (" << name << ") input channels, " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    if ( info.outputChannels == 0 ) return info;\r
+    goto probeParameters;\r
+  }\r
+  info.inputChannels = value;\r
+  snd_pcm_close( phandle );\r
+\r
+  // If device opens for both playback and capture, we determine the channels.\r
+  if ( info.outputChannels > 0 && info.inputChannels > 0 )\r
+    info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;\r
+\r
+  // ALSA doesn't provide default devices so we'll use the first available one.\r
+  if ( device == 0 && info.outputChannels > 0 )\r
+    info.isDefaultOutput = true;\r
+  if ( device == 0 && info.inputChannels > 0 )\r
+    info.isDefaultInput = true;\r
+\r
+ probeParameters:\r
+  // At this point, we just need to figure out the supported data\r
+  // formats and sample rates.  We'll proceed by opening the device in\r
+  // the direction with the maximum number of channels, or playback if\r
+  // they are equal.  This might limit our sample rate options, but so\r
+  // be it.\r
+\r
+  if ( info.outputChannels >= info.inputChannels )\r
+    stream = SND_PCM_STREAM_PLAYBACK;\r
+  else\r
+    stream = SND_PCM_STREAM_CAPTURE;\r
+  snd_pcm_info_set_stream( pcminfo, stream );\r
+\r
+  result = snd_pcm_open( &phandle, name, stream, openMode | SND_PCM_NONBLOCK);\r
+  if ( result < 0 ) {\r
+    errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_open error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // The device is open ... fill the parameter structure.\r
+  result = snd_pcm_hw_params_any( phandle, params );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::getDeviceInfo: snd_pcm_hw_params error for device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // Test our discrete set of sample rate values.\r
+  info.sampleRates.clear();\r
+  for ( unsigned int i=0; i<MAX_SAMPLE_RATES; i++ ) {\r
+    if ( snd_pcm_hw_params_test_rate( phandle, params, SAMPLE_RATES[i], 0 ) == 0 ) {\r
+      info.sampleRates.push_back( SAMPLE_RATES[i] );\r
+\r
+      if ( !info.preferredSampleRate || ( SAMPLE_RATES[i] <= 48000 && SAMPLE_RATES[i] > info.preferredSampleRate ) )\r
+        info.preferredSampleRate = SAMPLE_RATES[i];\r
+    }\r
+  }\r
+  if ( info.sampleRates.size() == 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::getDeviceInfo: no supported sample rates found for device (" << name << ").";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // Probe the supported data formats ... we don't care about endian-ness just yet\r
+  snd_pcm_format_t format;\r
+  info.nativeFormats = 0;\r
+  format = SND_PCM_FORMAT_S8;\r
+  if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
+    info.nativeFormats |= RTAUDIO_SINT8;\r
+  format = SND_PCM_FORMAT_S16;\r
+  if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
+    info.nativeFormats |= RTAUDIO_SINT16;\r
+  format = SND_PCM_FORMAT_S24;\r
+  if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
+    info.nativeFormats |= RTAUDIO_SINT24;\r
+  format = SND_PCM_FORMAT_S32;\r
+  if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
+    info.nativeFormats |= RTAUDIO_SINT32;\r
+  format = SND_PCM_FORMAT_FLOAT;\r
+  if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
+    info.nativeFormats |= RTAUDIO_FLOAT32;\r
+  format = SND_PCM_FORMAT_FLOAT64;\r
+  if ( snd_pcm_hw_params_test_format( phandle, params, format ) == 0 )\r
+    info.nativeFormats |= RTAUDIO_FLOAT64;\r
+\r
+  // Check that we have at least one supported format\r
+  if ( info.nativeFormats == 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::getDeviceInfo: pcm device (" << name << ") data format not supported by RtAudio.";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // Get the device name\r
+  char *cardname;\r
+  result = snd_card_get_name( card, &cardname );\r
+  if ( result >= 0 ) {\r
+    sprintf( name, "hw:%s,%d", cardname, subdevice );\r
+    free( cardname );\r
+  }\r
+  info.name = name;\r
+\r
+  // That's all ... close the device and return\r
+  snd_pcm_close( phandle );\r
+  info.probed = true;\r
+  return info;\r
+}\r
+\r
+void RtApiAlsa :: saveDeviceInfo( void )\r
+{\r
+  devices_.clear();\r
+\r
+  unsigned int nDevices = getDeviceCount();\r
+  devices_.resize( nDevices );\r
+  for ( unsigned int i=0; i<nDevices; i++ )\r
+    devices_[i] = getDeviceInfo( i );\r
+}\r
+\r
+bool RtApiAlsa :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,\r
+                                   unsigned int firstChannel, unsigned int sampleRate,\r
+                                   RtAudioFormat format, unsigned int *bufferSize,\r
+                                   RtAudio::StreamOptions *options )\r
+\r
+{\r
+#if defined(__RTAUDIO_DEBUG__)\r
+  snd_output_t *out;\r
+  snd_output_stdio_attach(&out, stderr, 0);\r
+#endif\r
+\r
+  // I'm not using the "plug" interface ... too much inconsistent behavior.\r
+\r
+  unsigned nDevices = 0;\r
+  int result, subdevice, card;\r
+  char name[64];\r
+  snd_ctl_t *chandle;\r
+\r
+  if ( options && options->flags & RTAUDIO_ALSA_USE_DEFAULT )\r
+    snprintf(name, sizeof(name), "%s", "default");\r
+  else {\r
+    // Count cards and devices\r
+    card = -1;\r
+    snd_card_next( &card );\r
+    while ( card >= 0 ) {\r
+      sprintf( name, "hw:%d", card );\r
+      result = snd_ctl_open( &chandle, name, SND_CTL_NONBLOCK );\r
+      if ( result < 0 ) {\r
+        errorStream_ << "RtApiAlsa::probeDeviceOpen: control open, card = " << card << ", " << snd_strerror( result ) << ".";\r
+        errorText_ = errorStream_.str();\r
+        return FAILURE;\r
+      }\r
+      subdevice = -1;\r
+      while( 1 ) {\r
+        result = snd_ctl_pcm_next_device( chandle, &subdevice );\r
+        if ( result < 0 ) break;\r
+        if ( subdevice < 0 ) break;\r
+        if ( nDevices == device ) {\r
+          sprintf( name, "hw:%d,%d", card, subdevice );\r
+          snd_ctl_close( chandle );\r
+          goto foundDevice;\r
+        }\r
+        nDevices++;\r
+      }\r
+      snd_ctl_close( chandle );\r
+      snd_card_next( &card );\r
+    }\r
+\r
+    result = snd_ctl_open( &chandle, "default", SND_CTL_NONBLOCK );\r
+    if ( result == 0 ) {\r
+      if ( nDevices == device ) {\r
+        strcpy( name, "default" );\r
+        goto foundDevice;\r
+      }\r
+      nDevices++;\r
+    }\r
+\r
+    if ( nDevices == 0 ) {\r
+      // This should not happen because a check is made before this function is called.\r
+      errorText_ = "RtApiAlsa::probeDeviceOpen: no devices found!";\r
+      return FAILURE;\r
+    }\r
+\r
+    if ( device >= nDevices ) {\r
+      // This should not happen because a check is made before this function is called.\r
+      errorText_ = "RtApiAlsa::probeDeviceOpen: device ID is invalid!";\r
+      return FAILURE;\r
+    }\r
+  }\r
+\r
+ foundDevice:\r
+\r
+  // The getDeviceInfo() function will not work for a device that is\r
+  // already open.  Thus, we'll probe the system before opening a\r
+  // stream and save the results for use by getDeviceInfo().\r
+  if ( mode == OUTPUT || ( mode == INPUT && stream_.mode != OUTPUT ) ) // only do once\r
+    this->saveDeviceInfo();\r
+\r
+  snd_pcm_stream_t stream;\r
+  if ( mode == OUTPUT )\r
+    stream = SND_PCM_STREAM_PLAYBACK;\r
+  else\r
+    stream = SND_PCM_STREAM_CAPTURE;\r
+\r
+  snd_pcm_t *phandle;\r
+  int openMode = SND_PCM_ASYNC;\r
+  result = snd_pcm_open( &phandle, name, stream, openMode );\r
+  if ( result < 0 ) {\r
+    if ( mode == OUTPUT )\r
+      errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for output.";\r
+    else\r
+      errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device (" << name << ") won't open for input.";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Fill the parameter structure.\r
+  snd_pcm_hw_params_t *hw_params;\r
+  snd_pcm_hw_params_alloca( &hw_params );\r
+  result = snd_pcm_hw_params_any( phandle, hw_params );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") parameters, " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+#if defined(__RTAUDIO_DEBUG__)\r
+  fprintf( stderr, "\nRtApiAlsa: dump hardware params just after device open:\n\n" );\r
+  snd_pcm_hw_params_dump( hw_params, out );\r
+#endif\r
+\r
+  // Set access ... check user preference.\r
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) {\r
+    stream_.userInterleaved = false;\r
+    result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );\r
+    if ( result < 0 ) {\r
+      result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );\r
+      stream_.deviceInterleaved[mode] =  true;\r
+    }\r
+    else\r
+      stream_.deviceInterleaved[mode] = false;\r
+  }\r
+  else {\r
+    stream_.userInterleaved = true;\r
+    result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED );\r
+    if ( result < 0 ) {\r
+      result = snd_pcm_hw_params_set_access( phandle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED );\r
+      stream_.deviceInterleaved[mode] =  false;\r
+    }\r
+    else\r
+      stream_.deviceInterleaved[mode] =  true;\r
+  }\r
+\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") access, " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Determine how to set the device format.\r
+  stream_.userFormat = format;\r
+  snd_pcm_format_t deviceFormat = SND_PCM_FORMAT_UNKNOWN;\r
+\r
+  if ( format == RTAUDIO_SINT8 )\r
+    deviceFormat = SND_PCM_FORMAT_S8;\r
+  else if ( format == RTAUDIO_SINT16 )\r
+    deviceFormat = SND_PCM_FORMAT_S16;\r
+  else if ( format == RTAUDIO_SINT24 )\r
+    deviceFormat = SND_PCM_FORMAT_S24;\r
+  else if ( format == RTAUDIO_SINT32 )\r
+    deviceFormat = SND_PCM_FORMAT_S32;\r
+  else if ( format == RTAUDIO_FLOAT32 )\r
+    deviceFormat = SND_PCM_FORMAT_FLOAT;\r
+  else if ( format == RTAUDIO_FLOAT64 )\r
+    deviceFormat = SND_PCM_FORMAT_FLOAT64;\r
+\r
+  if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat) == 0) {\r
+    stream_.deviceFormat[mode] = format;\r
+    goto setFormat;\r
+  }\r
+\r
+  // The user requested format is not natively supported by the device.\r
+  deviceFormat = SND_PCM_FORMAT_FLOAT64;\r
+  if ( snd_pcm_hw_params_test_format( phandle, hw_params, deviceFormat ) == 0 ) {\r
+    stream_.deviceFormat[mode] = RTAUDIO_FLOAT64;\r
+    goto setFormat;\r
+  }\r
+\r
+  deviceFormat = SND_PCM_FORMAT_FLOAT;\r
+  if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
+    stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;\r
+    goto setFormat;\r
+  }\r
+\r
+  deviceFormat = SND_PCM_FORMAT_S32;\r
+  if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
+    stream_.deviceFormat[mode] = RTAUDIO_SINT32;\r
+    goto setFormat;\r
+  }\r
+\r
+  deviceFormat = SND_PCM_FORMAT_S24;\r
+  if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
+    stream_.deviceFormat[mode] = RTAUDIO_SINT24;\r
+    goto setFormat;\r
+  }\r
+\r
+  deviceFormat = SND_PCM_FORMAT_S16;\r
+  if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
+    stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
+    goto setFormat;\r
+  }\r
+\r
+  deviceFormat = SND_PCM_FORMAT_S8;\r
+  if ( snd_pcm_hw_params_test_format(phandle, hw_params, deviceFormat ) == 0 ) {\r
+    stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
+    goto setFormat;\r
+  }\r
+\r
+  // If we get here, no supported format was found.\r
+  snd_pcm_close( phandle );\r
+  errorStream_ << "RtApiAlsa::probeDeviceOpen: pcm device " << device << " data format not supported by RtAudio.";\r
+  errorText_ = errorStream_.str();\r
+  return FAILURE;\r
+\r
+ setFormat:\r
+  result = snd_pcm_hw_params_set_format( phandle, hw_params, deviceFormat );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting pcm device (" << name << ") data format, " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Determine whether byte-swaping is necessary.\r
+  stream_.doByteSwap[mode] = false;\r
+  if ( deviceFormat != SND_PCM_FORMAT_S8 ) {\r
+    result = snd_pcm_format_cpu_endian( deviceFormat );\r
+    if ( result == 0 )\r
+      stream_.doByteSwap[mode] = true;\r
+    else if (result < 0) {\r
+      snd_pcm_close( phandle );\r
+      errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting pcm device (" << name << ") endian-ness, " << snd_strerror( result ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      return FAILURE;\r
+    }\r
+  }\r
+\r
+  // Set the sample rate.\r
+  result = snd_pcm_hw_params_set_rate_near( phandle, hw_params, (unsigned int*) &sampleRate, 0 );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting sample rate on device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Determine the number of channels for this device.  We support a possible\r
+  // minimum device channel number > than the value requested by the user.\r
+  stream_.nUserChannels[mode] = channels;\r
+  unsigned int value;\r
+  result = snd_pcm_hw_params_get_channels_max( hw_params, &value );\r
+  unsigned int deviceChannels = value;\r
+  if ( result < 0 || deviceChannels < channels + firstChannel ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: requested channel parameters not supported by device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  result = snd_pcm_hw_params_get_channels_min( hw_params, &value );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error getting minimum channels for device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+  deviceChannels = value;\r
+  if ( deviceChannels < channels + firstChannel ) deviceChannels = channels + firstChannel;\r
+  stream_.nDeviceChannels[mode] = deviceChannels;\r
+\r
+  // Set the device channels.\r
+  result = snd_pcm_hw_params_set_channels( phandle, hw_params, deviceChannels );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting channels for device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Set the buffer (or period) size.\r
+  int dir = 0;\r
+  snd_pcm_uframes_t periodSize = *bufferSize;\r
+  result = snd_pcm_hw_params_set_period_size_near( phandle, hw_params, &periodSize, &dir );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting period size for device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+  *bufferSize = periodSize;\r
+\r
+  // Set the buffer number, which in ALSA is referred to as the "period".\r
+  unsigned int periods = 0;\r
+  if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) periods = 2;\r
+  if ( options && options->numberOfBuffers > 0 ) periods = options->numberOfBuffers;\r
+  if ( periods < 2 ) periods = 4; // a fairly safe default value\r
+  result = snd_pcm_hw_params_set_periods_near( phandle, hw_params, &periods, &dir );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error setting periods for device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // If attempting to setup a duplex stream, the bufferSize parameter\r
+  // MUST be the same in both directions!\r
+  if ( stream_.mode == OUTPUT && mode == INPUT && *bufferSize != stream_.bufferSize ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: system error setting buffer size for duplex stream on device (" << name << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  stream_.bufferSize = *bufferSize;\r
+\r
+  // Install the hardware configuration\r
+  result = snd_pcm_hw_params( phandle, hw_params );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing hardware configuration on device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+#if defined(__RTAUDIO_DEBUG__)\r
+  fprintf(stderr, "\nRtApiAlsa: dump hardware params after installation:\n\n");\r
+  snd_pcm_hw_params_dump( hw_params, out );\r
+#endif\r
+\r
+  // Set the software configuration to fill buffers with zeros and prevent device stopping on xruns.\r
+  snd_pcm_sw_params_t *sw_params = NULL;\r
+  snd_pcm_sw_params_alloca( &sw_params );\r
+  snd_pcm_sw_params_current( phandle, sw_params );\r
+  snd_pcm_sw_params_set_start_threshold( phandle, sw_params, *bufferSize );\r
+  snd_pcm_sw_params_set_stop_threshold( phandle, sw_params, ULONG_MAX );\r
+  snd_pcm_sw_params_set_silence_threshold( phandle, sw_params, 0 );\r
+\r
+  // The following two settings were suggested by Theo Veenker\r
+  //snd_pcm_sw_params_set_avail_min( phandle, sw_params, *bufferSize );\r
+  //snd_pcm_sw_params_set_xfer_align( phandle, sw_params, 1 );\r
+\r
+  // here are two options for a fix\r
+  //snd_pcm_sw_params_set_silence_size( phandle, sw_params, ULONG_MAX );\r
+  snd_pcm_uframes_t val;\r
+  snd_pcm_sw_params_get_boundary( sw_params, &val );\r
+  snd_pcm_sw_params_set_silence_size( phandle, sw_params, val );\r
+\r
+  result = snd_pcm_sw_params( phandle, sw_params );\r
+  if ( result < 0 ) {\r
+    snd_pcm_close( phandle );\r
+    errorStream_ << "RtApiAlsa::probeDeviceOpen: error installing software configuration on device (" << name << "), " << snd_strerror( result ) << ".";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+#if defined(__RTAUDIO_DEBUG__)\r
+  fprintf(stderr, "\nRtApiAlsa: dump software params after installation:\n\n");\r
+  snd_pcm_sw_params_dump( sw_params, out );\r
+#endif\r
+\r
+  // Set flags for buffer conversion\r
+  stream_.doConvertBuffer[mode] = false;\r
+  if ( stream_.userFormat != stream_.deviceFormat[mode] )\r
+    stream_.doConvertBuffer[mode] = true;\r
+  if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )\r
+    stream_.doConvertBuffer[mode] = true;\r
+  if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&\r
+       stream_.nUserChannels[mode] > 1 )\r
+    stream_.doConvertBuffer[mode] = true;\r
+\r
+  // Allocate the ApiHandle if necessary and then save.\r
+  AlsaHandle *apiInfo = 0;\r
+  if ( stream_.apiHandle == 0 ) {\r
+    try {\r
+      apiInfo = (AlsaHandle *) new AlsaHandle;\r
+    }\r
+    catch ( std::bad_alloc& ) {\r
+      errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating AlsaHandle memory.";\r
+      goto error;\r
+    }\r
+\r
+    if ( pthread_cond_init( &apiInfo->runnable_cv, NULL ) ) {\r
+      errorText_ = "RtApiAlsa::probeDeviceOpen: error initializing pthread condition variable.";\r
+      goto error;\r
+    }\r
+\r
+    stream_.apiHandle = (void *) apiInfo;\r
+    apiInfo->handles[0] = 0;\r
+    apiInfo->handles[1] = 0;\r
+  }\r
+  else {\r
+    apiInfo = (AlsaHandle *) stream_.apiHandle;\r
+  }\r
+  apiInfo->handles[mode] = phandle;\r
+  phandle = 0;\r
+\r
+  // Allocate necessary internal buffers.\r
+  unsigned long bufferBytes;\r
+  bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );\r
+  stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );\r
+  if ( stream_.userBuffer[mode] == NULL ) {\r
+    errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating user buffer memory.";\r
+    goto error;\r
+  }\r
+\r
+  if ( stream_.doConvertBuffer[mode] ) {\r
+\r
+    bool makeBuffer = true;\r
+    bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );\r
+    if ( mode == INPUT ) {\r
+      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {\r
+        unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
+        if ( bufferBytes <= bytesOut ) makeBuffer = false;\r
+      }\r
+    }\r
+\r
+    if ( makeBuffer ) {\r
+      bufferBytes *= *bufferSize;\r
+      if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );\r
+      stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );\r
+      if ( stream_.deviceBuffer == NULL ) {\r
+        errorText_ = "RtApiAlsa::probeDeviceOpen: error allocating device buffer memory.";\r
+        goto error;\r
+      }\r
+    }\r
+  }\r
+\r
+  stream_.sampleRate = sampleRate;\r
+  stream_.nBuffers = periods;\r
+  stream_.device[mode] = device;\r
+  stream_.state = STREAM_STOPPED;\r
+\r
+  // Setup the buffer conversion information structure.\r
+  if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );\r
+\r
+  // Setup thread if necessary.\r
+  if ( stream_.mode == OUTPUT && mode == INPUT ) {\r
+    // We had already set up an output stream.\r
+    stream_.mode = DUPLEX;\r
+    // Link the streams if possible.\r
+    apiInfo->synchronized = false;\r
+    if ( snd_pcm_link( apiInfo->handles[0], apiInfo->handles[1] ) == 0 )\r
+      apiInfo->synchronized = true;\r
+    else {\r
+      errorText_ = "RtApiAlsa::probeDeviceOpen: unable to synchronize input and output devices.";\r
+      error( RtAudioError::WARNING );\r
+    }\r
+  }\r
+  else {\r
+    stream_.mode = mode;\r
+\r
+    // Setup callback thread.\r
+    stream_.callbackInfo.object = (void *) this;\r
+\r
+    // Set the thread attributes for joinable and realtime scheduling\r
+    // priority (optional).  The higher priority will only take affect\r
+    // if the program is run as root or suid. Note, under Linux\r
+    // processes with CAP_SYS_NICE privilege, a user can change\r
+    // scheduling policy and priority (thus need not be root). See\r
+    // POSIX "capabilities".\r
+    pthread_attr_t attr;\r
+    pthread_attr_init( &attr );\r
+    pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );\r
+\r
+#ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)\r
+    if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {\r
+      // We previously attempted to increase the audio callback priority\r
+      // to SCHED_RR here via the attributes.  However, while no errors\r
+      // were reported in doing so, it did not work.  So, now this is\r
+      // done in the alsaCallbackHandler function.\r
+      stream_.callbackInfo.doRealtime = true;\r
+      int priority = options->priority;\r
+      int min = sched_get_priority_min( SCHED_RR );\r
+      int max = sched_get_priority_max( SCHED_RR );\r
+      if ( priority < min ) priority = min;\r
+      else if ( priority > max ) priority = max;\r
+      stream_.callbackInfo.priority = priority;\r
+    }\r
+#endif\r
+\r
+    stream_.callbackInfo.isRunning = true;\r
+    result = pthread_create( &stream_.callbackInfo.thread, &attr, alsaCallbackHandler, &stream_.callbackInfo );\r
+    pthread_attr_destroy( &attr );\r
+    if ( result ) {\r
+      stream_.callbackInfo.isRunning = false;\r
+      errorText_ = "RtApiAlsa::error creating callback thread!";\r
+      goto error;\r
+    }\r
+  }\r
+\r
+  return SUCCESS;\r
+\r
+ error:\r
+  if ( apiInfo ) {\r
+    pthread_cond_destroy( &apiInfo->runnable_cv );\r
+    if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );\r
+    if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );\r
+    delete apiInfo;\r
+    stream_.apiHandle = 0;\r
+  }\r
+\r
+  if ( phandle) snd_pcm_close( phandle );\r
+\r
+  for ( int i=0; i<2; i++ ) {\r
+    if ( stream_.userBuffer[i] ) {\r
+      free( stream_.userBuffer[i] );\r
+      stream_.userBuffer[i] = 0;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceBuffer ) {\r
+    free( stream_.deviceBuffer );\r
+    stream_.deviceBuffer = 0;\r
+  }\r
+\r
+  stream_.state = STREAM_CLOSED;\r
+  return FAILURE;\r
+}\r
+\r
+void RtApiAlsa :: closeStream()\r
+{\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiAlsa::closeStream(): no open stream to close!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
+  stream_.callbackInfo.isRunning = false;\r
+  MUTEX_LOCK( &stream_.mutex );\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    apiInfo->runnable = true;\r
+    pthread_cond_signal( &apiInfo->runnable_cv );\r
+  }\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+  pthread_join( stream_.callbackInfo.thread, NULL );\r
+\r
+  if ( stream_.state == STREAM_RUNNING ) {\r
+    stream_.state = STREAM_STOPPED;\r
+    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )\r
+      snd_pcm_drop( apiInfo->handles[0] );\r
+    if ( stream_.mode == INPUT || stream_.mode == DUPLEX )\r
+      snd_pcm_drop( apiInfo->handles[1] );\r
+  }\r
+\r
+  if ( apiInfo ) {\r
+    pthread_cond_destroy( &apiInfo->runnable_cv );\r
+    if ( apiInfo->handles[0] ) snd_pcm_close( apiInfo->handles[0] );\r
+    if ( apiInfo->handles[1] ) snd_pcm_close( apiInfo->handles[1] );\r
+    delete apiInfo;\r
+    stream_.apiHandle = 0;\r
+  }\r
+\r
+  for ( int i=0; i<2; i++ ) {\r
+    if ( stream_.userBuffer[i] ) {\r
+      free( stream_.userBuffer[i] );\r
+      stream_.userBuffer[i] = 0;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceBuffer ) {\r
+    free( stream_.deviceBuffer );\r
+    stream_.deviceBuffer = 0;\r
+  }\r
+\r
+  stream_.mode = UNINITIALIZED;\r
+  stream_.state = STREAM_CLOSED;\r
+}\r
+\r
+void RtApiAlsa :: startStream()\r
+{\r
+  // This method calls snd_pcm_prepare if the device isn't already in that state.\r
+\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_RUNNING ) {\r
+    errorText_ = "RtApiAlsa::startStream(): the stream is already running!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  int result = 0;\r
+  snd_pcm_state_t state;\r
+  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
+  snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+    state = snd_pcm_state( handle[0] );\r
+    if ( state != SND_PCM_STATE_PREPARED ) {\r
+      result = snd_pcm_prepare( handle[0] );\r
+      if ( result < 0 ) {\r
+        errorStream_ << "RtApiAlsa::startStream: error preparing output pcm device, " << snd_strerror( result ) << ".";\r
+        errorText_ = errorStream_.str();\r
+        goto unlock;\r
+      }\r
+    }\r
+  }\r
+\r
+  if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {\r
+    result = snd_pcm_drop(handle[1]); // fix to remove stale data received since device has been open\r
+    state = snd_pcm_state( handle[1] );\r
+    if ( state != SND_PCM_STATE_PREPARED ) {\r
+      result = snd_pcm_prepare( handle[1] );\r
+      if ( result < 0 ) {\r
+        errorStream_ << "RtApiAlsa::startStream: error preparing input pcm device, " << snd_strerror( result ) << ".";\r
+        errorText_ = errorStream_.str();\r
+        goto unlock;\r
+      }\r
+    }\r
+  }\r
+\r
+  stream_.state = STREAM_RUNNING;\r
+\r
+ unlock:\r
+  apiInfo->runnable = true;\r
+  pthread_cond_signal( &apiInfo->runnable_cv );\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+\r
+  if ( result >= 0 ) return;\r
+  error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiAlsa :: stopStream()\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiAlsa::stopStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  int result = 0;\r
+  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
+  snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+    if ( apiInfo->synchronized ) \r
+      result = snd_pcm_drop( handle[0] );\r
+    else\r
+      result = snd_pcm_drain( handle[0] );\r
+    if ( result < 0 ) {\r
+      errorStream_ << "RtApiAlsa::stopStream: error draining output pcm device, " << snd_strerror( result ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+  }\r
+\r
+  if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {\r
+    result = snd_pcm_drop( handle[1] );\r
+    if ( result < 0 ) {\r
+      errorStream_ << "RtApiAlsa::stopStream: error stopping input pcm device, " << snd_strerror( result ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+  }\r
+\r
+ unlock:\r
+  apiInfo->runnable = false; // fixes high CPU usage when stopped\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+\r
+  if ( result >= 0 ) return;\r
+  error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiAlsa :: abortStream()\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiAlsa::abortStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  int result = 0;\r
+  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
+  snd_pcm_t **handle = (snd_pcm_t **) apiInfo->handles;\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+    result = snd_pcm_drop( handle[0] );\r
+    if ( result < 0 ) {\r
+      errorStream_ << "RtApiAlsa::abortStream: error aborting output pcm device, " << snd_strerror( result ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+  }\r
+\r
+  if ( ( stream_.mode == INPUT || stream_.mode == DUPLEX ) && !apiInfo->synchronized ) {\r
+    result = snd_pcm_drop( handle[1] );\r
+    if ( result < 0 ) {\r
+      errorStream_ << "RtApiAlsa::abortStream: error aborting input pcm device, " << snd_strerror( result ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+  }\r
+\r
+ unlock:\r
+  apiInfo->runnable = false; // fixes high CPU usage when stopped\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+\r
+  if ( result >= 0 ) return;\r
+  error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiAlsa :: callbackEvent()\r
+{\r
+  AlsaHandle *apiInfo = (AlsaHandle *) stream_.apiHandle;\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    MUTEX_LOCK( &stream_.mutex );\r
+    while ( !apiInfo->runnable )\r
+      pthread_cond_wait( &apiInfo->runnable_cv, &stream_.mutex );\r
+\r
+    if ( stream_.state != STREAM_RUNNING ) {\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
+      return;\r
+    }\r
+    MUTEX_UNLOCK( &stream_.mutex );\r
+  }\r
+\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiAlsa::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  int doStopStream = 0;\r
+  RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;\r
+  double streamTime = getStreamTime();\r
+  RtAudioStreamStatus status = 0;\r
+  if ( stream_.mode != INPUT && apiInfo->xrun[0] == true ) {\r
+    status |= RTAUDIO_OUTPUT_UNDERFLOW;\r
+    apiInfo->xrun[0] = false;\r
+  }\r
+  if ( stream_.mode != OUTPUT && apiInfo->xrun[1] == true ) {\r
+    status |= RTAUDIO_INPUT_OVERFLOW;\r
+    apiInfo->xrun[1] = false;\r
+  }\r
+  doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
+                           stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );\r
+\r
+  if ( doStopStream == 2 ) {\r
+    abortStream();\r
+    return;\r
+  }\r
+\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  // The state might change while waiting on a mutex.\r
+  if ( stream_.state == STREAM_STOPPED ) goto unlock;\r
+\r
+  int result;\r
+  char *buffer;\r
+  int channels;\r
+  snd_pcm_t **handle;\r
+  snd_pcm_sframes_t frames;\r
+  RtAudioFormat format;\r
+  handle = (snd_pcm_t **) apiInfo->handles;\r
+\r
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+\r
+    // Setup parameters.\r
+    if ( stream_.doConvertBuffer[1] ) {\r
+      buffer = stream_.deviceBuffer;\r
+      channels = stream_.nDeviceChannels[1];\r
+      format = stream_.deviceFormat[1];\r
+    }\r
+    else {\r
+      buffer = stream_.userBuffer[1];\r
+      channels = stream_.nUserChannels[1];\r
+      format = stream_.userFormat;\r
+    }\r
+\r
+    // Read samples from device in interleaved/non-interleaved format.\r
+    if ( stream_.deviceInterleaved[1] )\r
+      result = snd_pcm_readi( handle[1], buffer, stream_.bufferSize );\r
+    else {\r
+      void *bufs[channels];\r
+      size_t offset = stream_.bufferSize * formatBytes( format );\r
+      for ( int i=0; i<channels; i++ )\r
+        bufs[i] = (void *) (buffer + (i * offset));\r
+      result = snd_pcm_readn( handle[1], bufs, stream_.bufferSize );\r
+    }\r
+\r
+    if ( result < (int) stream_.bufferSize ) {\r
+      // Either an error or overrun occured.\r
+      if ( result == -EPIPE ) {\r
+        snd_pcm_state_t state = snd_pcm_state( handle[1] );\r
+        if ( state == SND_PCM_STATE_XRUN ) {\r
+          apiInfo->xrun[1] = true;\r
+          result = snd_pcm_prepare( handle[1] );\r
+          if ( result < 0 ) {\r
+            errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after overrun, " << snd_strerror( result ) << ".";\r
+            errorText_ = errorStream_.str();\r
+          }\r
+        }\r
+        else {\r
+          errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";\r
+          errorText_ = errorStream_.str();\r
+        }\r
+      }\r
+      else {\r
+        errorStream_ << "RtApiAlsa::callbackEvent: audio read error, " << snd_strerror( result ) << ".";\r
+        errorText_ = errorStream_.str();\r
+      }\r
+      error( RtAudioError::WARNING );\r
+      goto tryOutput;\r
+    }\r
+\r
+    // Do byte swapping if necessary.\r
+    if ( stream_.doByteSwap[1] )\r
+      byteSwapBuffer( buffer, stream_.bufferSize * channels, format );\r
+\r
+    // Do buffer conversion if necessary.\r
+    if ( stream_.doConvertBuffer[1] )\r
+      convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );\r
+\r
+    // Check stream latency\r
+    result = snd_pcm_delay( handle[1], &frames );\r
+    if ( result == 0 && frames > 0 ) stream_.latency[1] = frames;\r
+  }\r
+\r
+ tryOutput:\r
+\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+\r
+    // Setup parameters and do buffer conversion if necessary.\r
+    if ( stream_.doConvertBuffer[0] ) {\r
+      buffer = stream_.deviceBuffer;\r
+      convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );\r
+      channels = stream_.nDeviceChannels[0];\r
+      format = stream_.deviceFormat[0];\r
+    }\r
+    else {\r
+      buffer = stream_.userBuffer[0];\r
+      channels = stream_.nUserChannels[0];\r
+      format = stream_.userFormat;\r
+    }\r
+\r
+    // Do byte swapping if necessary.\r
+    if ( stream_.doByteSwap[0] )\r
+      byteSwapBuffer(buffer, stream_.bufferSize * channels, format);\r
+\r
+    // Write samples to device in interleaved/non-interleaved format.\r
+    if ( stream_.deviceInterleaved[0] )\r
+      result = snd_pcm_writei( handle[0], buffer, stream_.bufferSize );\r
+    else {\r
+      void *bufs[channels];\r
+      size_t offset = stream_.bufferSize * formatBytes( format );\r
+      for ( int i=0; i<channels; i++ )\r
+        bufs[i] = (void *) (buffer + (i * offset));\r
+      result = snd_pcm_writen( handle[0], bufs, stream_.bufferSize );\r
+    }\r
+\r
+    if ( result < (int) stream_.bufferSize ) {\r
+      // Either an error or underrun occured.\r
+      if ( result == -EPIPE ) {\r
+        snd_pcm_state_t state = snd_pcm_state( handle[0] );\r
+        if ( state == SND_PCM_STATE_XRUN ) {\r
+          apiInfo->xrun[0] = true;\r
+          result = snd_pcm_prepare( handle[0] );\r
+          if ( result < 0 ) {\r
+            errorStream_ << "RtApiAlsa::callbackEvent: error preparing device after underrun, " << snd_strerror( result ) << ".";\r
+            errorText_ = errorStream_.str();\r
+          }\r
+          else\r
+            errorText_ =  "RtApiAlsa::callbackEvent: audio write error, underrun.";\r
+        }\r
+        else {\r
+          errorStream_ << "RtApiAlsa::callbackEvent: error, current state is " << snd_pcm_state_name( state ) << ", " << snd_strerror( result ) << ".";\r
+          errorText_ = errorStream_.str();\r
+        }\r
+      }\r
+      else {\r
+        errorStream_ << "RtApiAlsa::callbackEvent: audio write error, " << snd_strerror( result ) << ".";\r
+        errorText_ = errorStream_.str();\r
+      }\r
+      error( RtAudioError::WARNING );\r
+      goto unlock;\r
+    }\r
+\r
+    // Check stream latency\r
+    result = snd_pcm_delay( handle[0], &frames );\r
+    if ( result == 0 && frames > 0 ) stream_.latency[0] = frames;\r
+  }\r
+\r
+ unlock:\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+\r
+  RtApi::tickStreamTime();\r
+  if ( doStopStream == 1 ) this->stopStream();\r
+}\r
+\r
+static void *alsaCallbackHandler( void *ptr )\r
+{\r
+  CallbackInfo *info = (CallbackInfo *) ptr;\r
+  RtApiAlsa *object = (RtApiAlsa *) info->object;\r
+  bool *isRunning = &info->isRunning;\r
+\r
+#ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)\r
+  if ( info->doRealtime ) {\r
+    pthread_t tID = pthread_self();     // ID of this thread\r
+    sched_param prio = { info->priority }; // scheduling priority of thread\r
+    pthread_setschedparam( tID, SCHED_RR, &prio );\r
+  }\r
+#endif\r
+\r
+  while ( *isRunning == true ) {\r
+    pthread_testcancel();\r
+    object->callbackEvent();\r
+  }\r
+\r
+  pthread_exit( NULL );\r
+}\r
+\r
+//******************** End of __LINUX_ALSA__ *********************//\r
+#endif\r
+\r
+#if defined(__LINUX_PULSE__)\r
+\r
+// Code written by Peter Meerwald, pmeerw@pmeerw.net\r
+// and Tristan Matthews.\r
+\r
+#include <pulse/error.h>\r
+#include <pulse/simple.h>\r
+#include <cstdio>\r
+\r
+static const unsigned int SUPPORTED_SAMPLERATES[] = { 8000, 16000, 22050, 32000,\r
+                                                      44100, 48000, 96000, 0};\r
+\r
+struct rtaudio_pa_format_mapping_t {\r
+  RtAudioFormat rtaudio_format;\r
+  pa_sample_format_t pa_format;\r
+};\r
+\r
+static const rtaudio_pa_format_mapping_t supported_sampleformats[] = {\r
+  {RTAUDIO_SINT16, PA_SAMPLE_S16LE},\r
+  {RTAUDIO_SINT32, PA_SAMPLE_S32LE},\r
+  {RTAUDIO_FLOAT32, PA_SAMPLE_FLOAT32LE},\r
+  {0, PA_SAMPLE_INVALID}};\r
+\r
+struct PulseAudioHandle {\r
+  pa_simple *s_play;\r
+  pa_simple *s_rec;\r
+  pthread_t thread;\r
+  pthread_cond_t runnable_cv;\r
+  bool runnable;\r
+  PulseAudioHandle() : s_play(0), s_rec(0), runnable(false) { }\r
+};\r
+\r
+RtApiPulse::~RtApiPulse()\r
+{\r
+  if ( stream_.state != STREAM_CLOSED )\r
+    closeStream();\r
+}\r
+\r
+unsigned int RtApiPulse::getDeviceCount( void )\r
+{\r
+  return 1;\r
+}\r
+\r
+RtAudio::DeviceInfo RtApiPulse::getDeviceInfo( unsigned int /*device*/ )\r
+{\r
+  RtAudio::DeviceInfo info;\r
+  info.probed = true;\r
+  info.name = "PulseAudio";\r
+  info.outputChannels = 2;\r
+  info.inputChannels = 2;\r
+  info.duplexChannels = 2;\r
+  info.isDefaultOutput = true;\r
+  info.isDefaultInput = true;\r
+\r
+  for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr )\r
+    info.sampleRates.push_back( *sr );\r
+\r
+  info.preferredSampleRate = 48000;\r
+  info.nativeFormats = RTAUDIO_SINT16 | RTAUDIO_SINT32 | RTAUDIO_FLOAT32;\r
+\r
+  return info;\r
+}\r
+\r
+static void *pulseaudio_callback( void * user )\r
+{\r
+  CallbackInfo *cbi = static_cast<CallbackInfo *>( user );\r
+  RtApiPulse *context = static_cast<RtApiPulse *>( cbi->object );\r
+  volatile bool *isRunning = &cbi->isRunning;\r
+\r
+  while ( *isRunning ) {\r
+    pthread_testcancel();\r
+    context->callbackEvent();\r
+  }\r
+\r
+  pthread_exit( NULL );\r
+}\r
+\r
+void RtApiPulse::closeStream( void )\r
+{\r
+  PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
+\r
+  stream_.callbackInfo.isRunning = false;\r
+  if ( pah ) {\r
+    MUTEX_LOCK( &stream_.mutex );\r
+    if ( stream_.state == STREAM_STOPPED ) {\r
+      pah->runnable = true;\r
+      pthread_cond_signal( &pah->runnable_cv );\r
+    }\r
+    MUTEX_UNLOCK( &stream_.mutex );\r
+\r
+    pthread_join( pah->thread, 0 );\r
+    if ( pah->s_play ) {\r
+      pa_simple_flush( pah->s_play, NULL );\r
+      pa_simple_free( pah->s_play );\r
+    }\r
+    if ( pah->s_rec )\r
+      pa_simple_free( pah->s_rec );\r
+\r
+    pthread_cond_destroy( &pah->runnable_cv );\r
+    delete pah;\r
+    stream_.apiHandle = 0;\r
+  }\r
+\r
+  if ( stream_.userBuffer[0] ) {\r
+    free( stream_.userBuffer[0] );\r
+    stream_.userBuffer[0] = 0;\r
+  }\r
+  if ( stream_.userBuffer[1] ) {\r
+    free( stream_.userBuffer[1] );\r
+    stream_.userBuffer[1] = 0;\r
+  }\r
+\r
+  stream_.state = STREAM_CLOSED;\r
+  stream_.mode = UNINITIALIZED;\r
+}\r
+\r
+void RtApiPulse::callbackEvent( void )\r
+{\r
+  PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
+\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    MUTEX_LOCK( &stream_.mutex );\r
+    while ( !pah->runnable )\r
+      pthread_cond_wait( &pah->runnable_cv, &stream_.mutex );\r
+\r
+    if ( stream_.state != STREAM_RUNNING ) {\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
+      return;\r
+    }\r
+    MUTEX_UNLOCK( &stream_.mutex );\r
+  }\r
+\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiPulse::callbackEvent(): the stream is closed ... "\r
+      "this shouldn't happen!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;\r
+  double streamTime = getStreamTime();\r
+  RtAudioStreamStatus status = 0;\r
+  int doStopStream = callback( stream_.userBuffer[OUTPUT], stream_.userBuffer[INPUT],\r
+                               stream_.bufferSize, streamTime, status,\r
+                               stream_.callbackInfo.userData );\r
+\r
+  if ( doStopStream == 2 ) {\r
+    abortStream();\r
+    return;\r
+  }\r
+\r
+  MUTEX_LOCK( &stream_.mutex );\r
+  void *pulse_in = stream_.doConvertBuffer[INPUT] ? stream_.deviceBuffer : stream_.userBuffer[INPUT];\r
+  void *pulse_out = stream_.doConvertBuffer[OUTPUT] ? stream_.deviceBuffer : stream_.userBuffer[OUTPUT];\r
+\r
+  if ( stream_.state != STREAM_RUNNING )\r
+    goto unlock;\r
+\r
+  int pa_error;\r
+  size_t bytes;\r
+  if (stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+    if ( stream_.doConvertBuffer[OUTPUT] ) {\r
+        convertBuffer( stream_.deviceBuffer,\r
+                       stream_.userBuffer[OUTPUT],\r
+                       stream_.convertInfo[OUTPUT] );\r
+        bytes = stream_.nDeviceChannels[OUTPUT] * stream_.bufferSize *\r
+                formatBytes( stream_.deviceFormat[OUTPUT] );\r
+    } else\r
+        bytes = stream_.nUserChannels[OUTPUT] * stream_.bufferSize *\r
+                formatBytes( stream_.userFormat );\r
+\r
+    if ( pa_simple_write( pah->s_play, pulse_out, bytes, &pa_error ) < 0 ) {\r
+      errorStream_ << "RtApiPulse::callbackEvent: audio write error, " <<\r
+        pa_strerror( pa_error ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      error( RtAudioError::WARNING );\r
+    }\r
+  }\r
+\r
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX) {\r
+    if ( stream_.doConvertBuffer[INPUT] )\r
+      bytes = stream_.nDeviceChannels[INPUT] * stream_.bufferSize *\r
+        formatBytes( stream_.deviceFormat[INPUT] );\r
+    else\r
+      bytes = stream_.nUserChannels[INPUT] * stream_.bufferSize *\r
+        formatBytes( stream_.userFormat );\r
+            \r
+    if ( pa_simple_read( pah->s_rec, pulse_in, bytes, &pa_error ) < 0 ) {\r
+      errorStream_ << "RtApiPulse::callbackEvent: audio read error, " <<\r
+        pa_strerror( pa_error ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      error( RtAudioError::WARNING );\r
+    }\r
+    if ( stream_.doConvertBuffer[INPUT] ) {\r
+      convertBuffer( stream_.userBuffer[INPUT],\r
+                     stream_.deviceBuffer,\r
+                     stream_.convertInfo[INPUT] );\r
+    }\r
+  }\r
+\r
+ unlock:\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+  RtApi::tickStreamTime();\r
+\r
+  if ( doStopStream == 1 )\r
+    stopStream();\r
+}\r
+\r
+void RtApiPulse::startStream( void )\r
+{\r
+  PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
+\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiPulse::startStream(): the stream is not open!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return;\r
+  }\r
+  if ( stream_.state == STREAM_RUNNING ) {\r
+    errorText_ = "RtApiPulse::startStream(): the stream is already running!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  stream_.state = STREAM_RUNNING;\r
+\r
+  pah->runnable = true;\r
+  pthread_cond_signal( &pah->runnable_cv );\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+}\r
+\r
+void RtApiPulse::stopStream( void )\r
+{\r
+  PulseAudioHandle *pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
+\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiPulse::stopStream(): the stream is not open!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return;\r
+  }\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiPulse::stopStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  if ( pah && pah->s_play ) {\r
+    int pa_error;\r
+    if ( pa_simple_drain( pah->s_play, &pa_error ) < 0 ) {\r
+      errorStream_ << "RtApiPulse::stopStream: error draining output device, " <<\r
+        pa_strerror( pa_error ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
+      error( RtAudioError::SYSTEM_ERROR );\r
+      return;\r
+    }\r
+  }\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+}\r
+\r
+void RtApiPulse::abortStream( void )\r
+{\r
+  PulseAudioHandle *pah = static_cast<PulseAudioHandle*>( stream_.apiHandle );\r
+\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiPulse::abortStream(): the stream is not open!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return;\r
+  }\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiPulse::abortStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  if ( pah && pah->s_play ) {\r
+    int pa_error;\r
+    if ( pa_simple_flush( pah->s_play, &pa_error ) < 0 ) {\r
+      errorStream_ << "RtApiPulse::abortStream: error flushing output device, " <<\r
+        pa_strerror( pa_error ) << ".";\r
+      errorText_ = errorStream_.str();\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
+      error( RtAudioError::SYSTEM_ERROR );\r
+      return;\r
+    }\r
+  }\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+}\r
+\r
+bool RtApiPulse::probeDeviceOpen( unsigned int device, StreamMode mode,\r
+                                  unsigned int channels, unsigned int firstChannel,\r
+                                  unsigned int sampleRate, RtAudioFormat format,\r
+                                  unsigned int *bufferSize, RtAudio::StreamOptions *options )\r
+{\r
+  PulseAudioHandle *pah = 0;\r
+  unsigned long bufferBytes = 0;\r
+  pa_sample_spec ss;\r
+\r
+  if ( device != 0 ) return false;\r
+  if ( mode != INPUT && mode != OUTPUT ) return false;\r
+  if ( channels != 1 && channels != 2 ) {\r
+    errorText_ = "RtApiPulse::probeDeviceOpen: unsupported number of channels.";\r
+    return false;\r
+  }\r
+  ss.channels = channels;\r
+\r
+  if ( firstChannel != 0 ) return false;\r
+\r
+  bool sr_found = false;\r
+  for ( const unsigned int *sr = SUPPORTED_SAMPLERATES; *sr; ++sr ) {\r
+    if ( sampleRate == *sr ) {\r
+      sr_found = true;\r
+      stream_.sampleRate = sampleRate;\r
+      ss.rate = sampleRate;\r
+      break;\r
+    }\r
+  }\r
+  if ( !sr_found ) {\r
+    errorText_ = "RtApiPulse::probeDeviceOpen: unsupported sample rate.";\r
+    return false;\r
+  }\r
+\r
+  bool sf_found = 0;\r
+  for ( const rtaudio_pa_format_mapping_t *sf = supported_sampleformats;\r
+        sf->rtaudio_format && sf->pa_format != PA_SAMPLE_INVALID; ++sf ) {\r
+    if ( format == sf->rtaudio_format ) {\r
+      sf_found = true;\r
+      stream_.userFormat = sf->rtaudio_format;\r
+      stream_.deviceFormat[mode] = stream_.userFormat;\r
+      ss.format = sf->pa_format;\r
+      break;\r
+    }\r
+  }\r
+  if ( !sf_found ) { // Use internal data format conversion.\r
+    stream_.userFormat = format;\r
+    stream_.deviceFormat[mode] = RTAUDIO_FLOAT32;\r
+    ss.format = PA_SAMPLE_FLOAT32LE;\r
+  }\r
+\r
+  // Set other stream parameters.\r
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED ) stream_.userInterleaved = false;\r
+  else stream_.userInterleaved = true;\r
+  stream_.deviceInterleaved[mode] = true;\r
+  stream_.nBuffers = 1;\r
+  stream_.doByteSwap[mode] = false;\r
+  stream_.nUserChannels[mode] = channels;\r
+  stream_.nDeviceChannels[mode] = channels + firstChannel;\r
+  stream_.channelOffset[mode] = 0;\r
+  std::string streamName = "RtAudio";\r
+\r
+  // Set flags for buffer conversion.\r
+  stream_.doConvertBuffer[mode] = false;\r
+  if ( stream_.userFormat != stream_.deviceFormat[mode] )\r
+    stream_.doConvertBuffer[mode] = true;\r
+  if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )\r
+    stream_.doConvertBuffer[mode] = true;\r
+\r
+  // Allocate necessary internal buffers.\r
+  bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );\r
+  stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );\r
+  if ( stream_.userBuffer[mode] == NULL ) {\r
+    errorText_ = "RtApiPulse::probeDeviceOpen: error allocating user buffer memory.";\r
+    goto error;\r
+  }\r
+  stream_.bufferSize = *bufferSize;\r
+\r
+  if ( stream_.doConvertBuffer[mode] ) {\r
+\r
+    bool makeBuffer = true;\r
+    bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );\r
+    if ( mode == INPUT ) {\r
+      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {\r
+        unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
+        if ( bufferBytes <= bytesOut ) makeBuffer = false;\r
+      }\r
+    }\r
+\r
+    if ( makeBuffer ) {\r
+      bufferBytes *= *bufferSize;\r
+      if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );\r
+      stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );\r
+      if ( stream_.deviceBuffer == NULL ) {\r
+        errorText_ = "RtApiPulse::probeDeviceOpen: error allocating device buffer memory.";\r
+        goto error;\r
+      }\r
+    }\r
+  }\r
+\r
+  stream_.device[mode] = device;\r
+\r
+  // Setup the buffer conversion information structure.\r
+  if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );\r
+\r
+  if ( !stream_.apiHandle ) {\r
+    PulseAudioHandle *pah = new PulseAudioHandle;\r
+    if ( !pah ) {\r
+      errorText_ = "RtApiPulse::probeDeviceOpen: error allocating memory for handle.";\r
+      goto error;\r
+    }\r
+\r
+    stream_.apiHandle = pah;\r
+    if ( pthread_cond_init( &pah->runnable_cv, NULL ) != 0 ) {\r
+      errorText_ = "RtApiPulse::probeDeviceOpen: error creating condition variable.";\r
+      goto error;\r
+    }\r
+  }\r
+  pah = static_cast<PulseAudioHandle *>( stream_.apiHandle );\r
+\r
+  int error;\r
+  if ( options && !options->streamName.empty() ) streamName = options->streamName;\r
+  switch ( mode ) {\r
+  case INPUT:\r
+    pa_buffer_attr buffer_attr;\r
+    buffer_attr.fragsize = bufferBytes;\r
+    buffer_attr.maxlength = -1;\r
+\r
+    pah->s_rec = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_RECORD, NULL, "Record", &ss, NULL, &buffer_attr, &error );\r
+    if ( !pah->s_rec ) {\r
+      errorText_ = "RtApiPulse::probeDeviceOpen: error connecting input to PulseAudio server.";\r
+      goto error;\r
+    }\r
+    break;\r
+  case OUTPUT:\r
+    pah->s_play = pa_simple_new( NULL, streamName.c_str(), PA_STREAM_PLAYBACK, NULL, "Playback", &ss, NULL, NULL, &error );\r
+    if ( !pah->s_play ) {\r
+      errorText_ = "RtApiPulse::probeDeviceOpen: error connecting output to PulseAudio server.";\r
+      goto error;\r
+    }\r
+    break;\r
+  default:\r
+    goto error;\r
+  }\r
+\r
+  if ( stream_.mode == UNINITIALIZED )\r
+    stream_.mode = mode;\r
+  else if ( stream_.mode == mode )\r
+    goto error;\r
+  else\r
+    stream_.mode = DUPLEX;\r
+\r
+  if ( !stream_.callbackInfo.isRunning ) {\r
+    stream_.callbackInfo.object = this;\r
+    stream_.callbackInfo.isRunning = true;\r
+    if ( pthread_create( &pah->thread, NULL, pulseaudio_callback, (void *)&stream_.callbackInfo) != 0 ) {\r
+      errorText_ = "RtApiPulse::probeDeviceOpen: error creating thread.";\r
+      goto error;\r
+    }\r
+  }\r
+\r
+  stream_.state = STREAM_STOPPED;\r
+  return true;\r
\r
+ error:\r
+  if ( pah && stream_.callbackInfo.isRunning ) {\r
+    pthread_cond_destroy( &pah->runnable_cv );\r
+    delete pah;\r
+    stream_.apiHandle = 0;\r
+  }\r
+\r
+  for ( int i=0; i<2; i++ ) {\r
+    if ( stream_.userBuffer[i] ) {\r
+      free( stream_.userBuffer[i] );\r
+      stream_.userBuffer[i] = 0;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceBuffer ) {\r
+    free( stream_.deviceBuffer );\r
+    stream_.deviceBuffer = 0;\r
+  }\r
+\r
+  return FAILURE;\r
+}\r
+\r
+//******************** End of __LINUX_PULSE__ *********************//\r
+#endif\r
+\r
+#if defined(__LINUX_OSS__)\r
+\r
+#include <unistd.h>\r
+#include <sys/ioctl.h>\r
+#include <unistd.h>\r
+#include <fcntl.h>\r
+#include <sys/soundcard.h>\r
+#include <errno.h>\r
+#include <math.h>\r
+\r
+static void *ossCallbackHandler(void * ptr);\r
+\r
+// A structure to hold various information related to the OSS API\r
+// implementation.\r
+struct OssHandle {\r
+  int id[2];    // device ids\r
+  bool xrun[2];\r
+  bool triggered;\r
+  pthread_cond_t runnable;\r
+\r
+  OssHandle()\r
+    :triggered(false) { id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }\r
+};\r
+\r
+RtApiOss :: RtApiOss()\r
+{\r
+  // Nothing to do here.\r
+}\r
+\r
+RtApiOss :: ~RtApiOss()\r
+{\r
+  if ( stream_.state != STREAM_CLOSED ) closeStream();\r
+}\r
+\r
+unsigned int RtApiOss :: getDeviceCount( void )\r
+{\r
+  int mixerfd = open( "/dev/mixer", O_RDWR, 0 );\r
+  if ( mixerfd == -1 ) {\r
+    errorText_ = "RtApiOss::getDeviceCount: error opening '/dev/mixer'.";\r
+    error( RtAudioError::WARNING );\r
+    return 0;\r
+  }\r
+\r
+  oss_sysinfo sysinfo;\r
+  if ( ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo ) == -1 ) {\r
+    close( mixerfd );\r
+    errorText_ = "RtApiOss::getDeviceCount: error getting sysinfo, OSS version >= 4.0 is required.";\r
+    error( RtAudioError::WARNING );\r
+    return 0;\r
+  }\r
+\r
+  close( mixerfd );\r
+  return sysinfo.numaudios;\r
+}\r
+\r
+RtAudio::DeviceInfo RtApiOss :: getDeviceInfo( unsigned int device )\r
+{\r
+  RtAudio::DeviceInfo info;\r
+  info.probed = false;\r
+\r
+  int mixerfd = open( "/dev/mixer", O_RDWR, 0 );\r
+  if ( mixerfd == -1 ) {\r
+    errorText_ = "RtApiOss::getDeviceInfo: error opening '/dev/mixer'.";\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  oss_sysinfo sysinfo;\r
+  int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );\r
+  if ( result == -1 ) {\r
+    close( mixerfd );\r
+    errorText_ = "RtApiOss::getDeviceInfo: error getting sysinfo, OSS version >= 4.0 is required.";\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  unsigned nDevices = sysinfo.numaudios;\r
+  if ( nDevices == 0 ) {\r
+    close( mixerfd );\r
+    errorText_ = "RtApiOss::getDeviceInfo: no devices found!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return info;\r
+  }\r
+\r
+  if ( device >= nDevices ) {\r
+    close( mixerfd );\r
+    errorText_ = "RtApiOss::getDeviceInfo: device ID is invalid!";\r
+    error( RtAudioError::INVALID_USE );\r
+    return info;\r
+  }\r
+\r
+  oss_audioinfo ainfo;\r
+  ainfo.dev = device;\r
+  result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );\r
+  close( mixerfd );\r
+  if ( result == -1 ) {\r
+    errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // Probe channels\r
+  if ( ainfo.caps & PCM_CAP_OUTPUT ) info.outputChannels = ainfo.max_channels;\r
+  if ( ainfo.caps & PCM_CAP_INPUT ) info.inputChannels = ainfo.max_channels;\r
+  if ( ainfo.caps & PCM_CAP_DUPLEX ) {\r
+    if ( info.outputChannels > 0 && info.inputChannels > 0 && ainfo.caps & PCM_CAP_DUPLEX )\r
+      info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;\r
+  }\r
+\r
+  // Probe data formats ... do for input\r
+  unsigned long mask = ainfo.iformats;\r
+  if ( mask & AFMT_S16_LE || mask & AFMT_S16_BE )\r
+    info.nativeFormats |= RTAUDIO_SINT16;\r
+  if ( mask & AFMT_S8 )\r
+    info.nativeFormats |= RTAUDIO_SINT8;\r
+  if ( mask & AFMT_S32_LE || mask & AFMT_S32_BE )\r
+    info.nativeFormats |= RTAUDIO_SINT32;\r
+  if ( mask & AFMT_FLOAT )\r
+    info.nativeFormats |= RTAUDIO_FLOAT32;\r
+  if ( mask & AFMT_S24_LE || mask & AFMT_S24_BE )\r
+    info.nativeFormats |= RTAUDIO_SINT24;\r
+\r
+  // Check that we have at least one supported format\r
+  if ( info.nativeFormats == 0 ) {\r
+    errorStream_ << "RtApiOss::getDeviceInfo: device (" << ainfo.name << ") data format not supported by RtAudio.";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+    return info;\r
+  }\r
+\r
+  // Probe the supported sample rates.\r
+  info.sampleRates.clear();\r
+  if ( ainfo.nrates ) {\r
+    for ( unsigned int i=0; i<ainfo.nrates; i++ ) {\r
+      for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
+        if ( ainfo.rates[i] == SAMPLE_RATES[k] ) {\r
+          info.sampleRates.push_back( SAMPLE_RATES[k] );\r
+\r
+          if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )\r
+            info.preferredSampleRate = SAMPLE_RATES[k];\r
+\r
+          break;\r
+        }\r
+      }\r
+    }\r
+  }\r
+  else {\r
+    // Check min and max rate values;\r
+    for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {\r
+      if ( ainfo.min_rate <= (int) SAMPLE_RATES[k] && ainfo.max_rate >= (int) SAMPLE_RATES[k] ) {\r
+        info.sampleRates.push_back( SAMPLE_RATES[k] );\r
+\r
+        if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )\r
+          info.preferredSampleRate = SAMPLE_RATES[k];\r
+      }\r
+    }\r
+  }\r
+\r
+  if ( info.sampleRates.size() == 0 ) {\r
+    errorStream_ << "RtApiOss::getDeviceInfo: no supported sample rates found for device (" << ainfo.name << ").";\r
+    errorText_ = errorStream_.str();\r
+    error( RtAudioError::WARNING );\r
+  }\r
+  else {\r
+    info.probed = true;\r
+    info.name = ainfo.name;\r
+  }\r
+\r
+  return info;\r
+}\r
+\r
+\r
+bool RtApiOss :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,\r
+                                  unsigned int firstChannel, unsigned int sampleRate,\r
+                                  RtAudioFormat format, unsigned int *bufferSize,\r
+                                  RtAudio::StreamOptions *options )\r
+{\r
+  int mixerfd = open( "/dev/mixer", O_RDWR, 0 );\r
+  if ( mixerfd == -1 ) {\r
+    errorText_ = "RtApiOss::probeDeviceOpen: error opening '/dev/mixer'.";\r
+    return FAILURE;\r
+  }\r
+\r
+  oss_sysinfo sysinfo;\r
+  int result = ioctl( mixerfd, SNDCTL_SYSINFO, &sysinfo );\r
+  if ( result == -1 ) {\r
+    close( mixerfd );\r
+    errorText_ = "RtApiOss::probeDeviceOpen: error getting sysinfo, OSS version >= 4.0 is required.";\r
+    return FAILURE;\r
+  }\r
+\r
+  unsigned nDevices = sysinfo.numaudios;\r
+  if ( nDevices == 0 ) {\r
+    // This should not happen because a check is made before this function is called.\r
+    close( mixerfd );\r
+    errorText_ = "RtApiOss::probeDeviceOpen: no devices found!";\r
+    return FAILURE;\r
+  }\r
+\r
+  if ( device >= nDevices ) {\r
+    // This should not happen because a check is made before this function is called.\r
+    close( mixerfd );\r
+    errorText_ = "RtApiOss::probeDeviceOpen: device ID is invalid!";\r
+    return FAILURE;\r
+  }\r
+\r
+  oss_audioinfo ainfo;\r
+  ainfo.dev = device;\r
+  result = ioctl( mixerfd, SNDCTL_AUDIOINFO, &ainfo );\r
+  close( mixerfd );\r
+  if ( result == -1 ) {\r
+    errorStream_ << "RtApiOss::getDeviceInfo: error getting device (" << ainfo.name << ") info.";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Check if device supports input or output\r
+  if ( ( mode == OUTPUT && !( ainfo.caps & PCM_CAP_OUTPUT ) ) ||\r
+       ( mode == INPUT && !( ainfo.caps & PCM_CAP_INPUT ) ) ) {\r
+    if ( mode == OUTPUT )\r
+      errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support output.";\r
+    else\r
+      errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support input.";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  int flags = 0;\r
+  OssHandle *handle = (OssHandle *) stream_.apiHandle;\r
+  if ( mode == OUTPUT )\r
+    flags |= O_WRONLY;\r
+  else { // mode == INPUT\r
+    if (stream_.mode == OUTPUT && stream_.device[0] == device) {\r
+      // We just set the same device for playback ... close and reopen for duplex (OSS only).\r
+      close( handle->id[0] );\r
+      handle->id[0] = 0;\r
+      if ( !( ainfo.caps & PCM_CAP_DUPLEX ) ) {\r
+        errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support duplex mode.";\r
+        errorText_ = errorStream_.str();\r
+        return FAILURE;\r
+      }\r
+      // Check that the number previously set channels is the same.\r
+      if ( stream_.nUserChannels[0] != channels ) {\r
+        errorStream_ << "RtApiOss::probeDeviceOpen: input/output channels must be equal for OSS duplex device (" << ainfo.name << ").";\r
+        errorText_ = errorStream_.str();\r
+        return FAILURE;\r
+      }\r
+      flags |= O_RDWR;\r
+    }\r
+    else\r
+      flags |= O_RDONLY;\r
+  }\r
+\r
+  // Set exclusive access if specified.\r
+  if ( options && options->flags & RTAUDIO_HOG_DEVICE ) flags |= O_EXCL;\r
+\r
+  // Try to open the device.\r
+  int fd;\r
+  fd = open( ainfo.devnode, flags, 0 );\r
+  if ( fd == -1 ) {\r
+    if ( errno == EBUSY )\r
+      errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") is busy.";\r
+    else\r
+      errorStream_ << "RtApiOss::probeDeviceOpen: error opening device (" << ainfo.name << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // For duplex operation, specifically set this mode (this doesn't seem to work).\r
+  /*\r
+    if ( flags | O_RDWR ) {\r
+    result = ioctl( fd, SNDCTL_DSP_SETDUPLEX, NULL );\r
+    if ( result == -1) {\r
+    errorStream_ << "RtApiOss::probeDeviceOpen: error setting duplex mode for device (" << ainfo.name << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+    }\r
+    }\r
+  */\r
+\r
+  // Check the device channel support.\r
+  stream_.nUserChannels[mode] = channels;\r
+  if ( ainfo.max_channels < (int)(channels + firstChannel) ) {\r
+    close( fd );\r
+    errorStream_ << "RtApiOss::probeDeviceOpen: the device (" << ainfo.name << ") does not support requested channel parameters.";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Set the number of channels.\r
+  int deviceChannels = channels + firstChannel;\r
+  result = ioctl( fd, SNDCTL_DSP_CHANNELS, &deviceChannels );\r
+  if ( result == -1 || deviceChannels < (int)(channels + firstChannel) ) {\r
+    close( fd );\r
+    errorStream_ << "RtApiOss::probeDeviceOpen: error setting channel parameters on device (" << ainfo.name << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+  stream_.nDeviceChannels[mode] = deviceChannels;\r
+\r
+  // Get the data format mask\r
+  int mask;\r
+  result = ioctl( fd, SNDCTL_DSP_GETFMTS, &mask );\r
+  if ( result == -1 ) {\r
+    close( fd );\r
+    errorStream_ << "RtApiOss::probeDeviceOpen: error getting device (" << ainfo.name << ") data formats.";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Determine how to set the device format.\r
+  stream_.userFormat = format;\r
+  int deviceFormat = -1;\r
+  stream_.doByteSwap[mode] = false;\r
+  if ( format == RTAUDIO_SINT8 ) {\r
+    if ( mask & AFMT_S8 ) {\r
+      deviceFormat = AFMT_S8;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
+    }\r
+  }\r
+  else if ( format == RTAUDIO_SINT16 ) {\r
+    if ( mask & AFMT_S16_NE ) {\r
+      deviceFormat = AFMT_S16_NE;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
+    }\r
+    else if ( mask & AFMT_S16_OE ) {\r
+      deviceFormat = AFMT_S16_OE;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
+      stream_.doByteSwap[mode] = true;\r
+    }\r
+  }\r
+  else if ( format == RTAUDIO_SINT24 ) {\r
+    if ( mask & AFMT_S24_NE ) {\r
+      deviceFormat = AFMT_S24_NE;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT24;\r
+    }\r
+    else if ( mask & AFMT_S24_OE ) {\r
+      deviceFormat = AFMT_S24_OE;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT24;\r
+      stream_.doByteSwap[mode] = true;\r
+    }\r
+  }\r
+  else if ( format == RTAUDIO_SINT32 ) {\r
+    if ( mask & AFMT_S32_NE ) {\r
+      deviceFormat = AFMT_S32_NE;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT32;\r
+    }\r
+    else if ( mask & AFMT_S32_OE ) {\r
+      deviceFormat = AFMT_S32_OE;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT32;\r
+      stream_.doByteSwap[mode] = true;\r
+    }\r
+  }\r
+\r
+  if ( deviceFormat == -1 ) {\r
+    // The user requested format is not natively supported by the device.\r
+    if ( mask & AFMT_S16_NE ) {\r
+      deviceFormat = AFMT_S16_NE;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
+    }\r
+    else if ( mask & AFMT_S32_NE ) {\r
+      deviceFormat = AFMT_S32_NE;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT32;\r
+    }\r
+    else if ( mask & AFMT_S24_NE ) {\r
+      deviceFormat = AFMT_S24_NE;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT24;\r
+    }\r
+    else if ( mask & AFMT_S16_OE ) {\r
+      deviceFormat = AFMT_S16_OE;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT16;\r
+      stream_.doByteSwap[mode] = true;\r
+    }\r
+    else if ( mask & AFMT_S32_OE ) {\r
+      deviceFormat = AFMT_S32_OE;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT32;\r
+      stream_.doByteSwap[mode] = true;\r
+    }\r
+    else if ( mask & AFMT_S24_OE ) {\r
+      deviceFormat = AFMT_S24_OE;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT24;\r
+      stream_.doByteSwap[mode] = true;\r
+    }\r
+    else if ( mask & AFMT_S8) {\r
+      deviceFormat = AFMT_S8;\r
+      stream_.deviceFormat[mode] = RTAUDIO_SINT8;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceFormat[mode] == 0 ) {\r
+    // This really shouldn't happen ...\r
+    close( fd );\r
+    errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") data format not supported by RtAudio.";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Set the data format.\r
+  int temp = deviceFormat;\r
+  result = ioctl( fd, SNDCTL_DSP_SETFMT, &deviceFormat );\r
+  if ( result == -1 || deviceFormat != temp ) {\r
+    close( fd );\r
+    errorStream_ << "RtApiOss::probeDeviceOpen: error setting data format on device (" << ainfo.name << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Attempt to set the buffer size.  According to OSS, the minimum\r
+  // number of buffers is two.  The supposed minimum buffer size is 16\r
+  // bytes, so that will be our lower bound.  The argument to this\r
+  // call is in the form 0xMMMMSSSS (hex), where the buffer size (in\r
+  // bytes) is given as 2^SSSS and the number of buffers as 2^MMMM.\r
+  // We'll check the actual value used near the end of the setup\r
+  // procedure.\r
+  int ossBufferBytes = *bufferSize * formatBytes( stream_.deviceFormat[mode] ) * deviceChannels;\r
+  if ( ossBufferBytes < 16 ) ossBufferBytes = 16;\r
+  int buffers = 0;\r
+  if ( options ) buffers = options->numberOfBuffers;\r
+  if ( options && options->flags & RTAUDIO_MINIMIZE_LATENCY ) buffers = 2;\r
+  if ( buffers < 2 ) buffers = 3;\r
+  temp = ((int) buffers << 16) + (int)( log10( (double)ossBufferBytes ) / log10( 2.0 ) );\r
+  result = ioctl( fd, SNDCTL_DSP_SETFRAGMENT, &temp );\r
+  if ( result == -1 ) {\r
+    close( fd );\r
+    errorStream_ << "RtApiOss::probeDeviceOpen: error setting buffer size on device (" << ainfo.name << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+  stream_.nBuffers = buffers;\r
+\r
+  // Save buffer size (in sample frames).\r
+  *bufferSize = ossBufferBytes / ( formatBytes(stream_.deviceFormat[mode]) * deviceChannels );\r
+  stream_.bufferSize = *bufferSize;\r
+\r
+  // Set the sample rate.\r
+  int srate = sampleRate;\r
+  result = ioctl( fd, SNDCTL_DSP_SPEED, &srate );\r
+  if ( result == -1 ) {\r
+    close( fd );\r
+    errorStream_ << "RtApiOss::probeDeviceOpen: error setting sample rate (" << sampleRate << ") on device (" << ainfo.name << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+\r
+  // Verify the sample rate setup worked.\r
+  if ( abs( srate - sampleRate ) > 100 ) {\r
+    close( fd );\r
+    errorStream_ << "RtApiOss::probeDeviceOpen: device (" << ainfo.name << ") does not support sample rate (" << sampleRate << ").";\r
+    errorText_ = errorStream_.str();\r
+    return FAILURE;\r
+  }\r
+  stream_.sampleRate = sampleRate;\r
+\r
+  if ( mode == INPUT && stream_.mode == OUTPUT && stream_.device[0] == device) {\r
+    // We're doing duplex setup here.\r
+    stream_.deviceFormat[0] = stream_.deviceFormat[1];\r
+    stream_.nDeviceChannels[0] = deviceChannels;\r
+  }\r
+\r
+  // Set interleaving parameters.\r
+  stream_.userInterleaved = true;\r
+  stream_.deviceInterleaved[mode] =  true;\r
+  if ( options && options->flags & RTAUDIO_NONINTERLEAVED )\r
+    stream_.userInterleaved = false;\r
+\r
+  // Set flags for buffer conversion\r
+  stream_.doConvertBuffer[mode] = false;\r
+  if ( stream_.userFormat != stream_.deviceFormat[mode] )\r
+    stream_.doConvertBuffer[mode] = true;\r
+  if ( stream_.nUserChannels[mode] < stream_.nDeviceChannels[mode] )\r
+    stream_.doConvertBuffer[mode] = true;\r
+  if ( stream_.userInterleaved != stream_.deviceInterleaved[mode] &&\r
+       stream_.nUserChannels[mode] > 1 )\r
+    stream_.doConvertBuffer[mode] = true;\r
+\r
+  // Allocate the stream handles if necessary and then save.\r
+  if ( stream_.apiHandle == 0 ) {\r
+    try {\r
+      handle = new OssHandle;\r
+    }\r
+    catch ( std::bad_alloc& ) {\r
+      errorText_ = "RtApiOss::probeDeviceOpen: error allocating OssHandle memory.";\r
+      goto error;\r
+    }\r
+\r
+    if ( pthread_cond_init( &handle->runnable, NULL ) ) {\r
+      errorText_ = "RtApiOss::probeDeviceOpen: error initializing pthread condition variable.";\r
+      goto error;\r
+    }\r
+\r
+    stream_.apiHandle = (void *) handle;\r
+  }\r
+  else {\r
+    handle = (OssHandle *) stream_.apiHandle;\r
+  }\r
+  handle->id[mode] = fd;\r
+\r
+  // Allocate necessary internal buffers.\r
+  unsigned long bufferBytes;\r
+  bufferBytes = stream_.nUserChannels[mode] * *bufferSize * formatBytes( stream_.userFormat );\r
+  stream_.userBuffer[mode] = (char *) calloc( bufferBytes, 1 );\r
+  if ( stream_.userBuffer[mode] == NULL ) {\r
+    errorText_ = "RtApiOss::probeDeviceOpen: error allocating user buffer memory.";\r
+    goto error;\r
+  }\r
+\r
+  if ( stream_.doConvertBuffer[mode] ) {\r
+\r
+    bool makeBuffer = true;\r
+    bufferBytes = stream_.nDeviceChannels[mode] * formatBytes( stream_.deviceFormat[mode] );\r
+    if ( mode == INPUT ) {\r
+      if ( stream_.mode == OUTPUT && stream_.deviceBuffer ) {\r
+        unsigned long bytesOut = stream_.nDeviceChannels[0] * formatBytes( stream_.deviceFormat[0] );\r
+        if ( bufferBytes <= bytesOut ) makeBuffer = false;\r
+      }\r
+    }\r
+\r
+    if ( makeBuffer ) {\r
+      bufferBytes *= *bufferSize;\r
+      if ( stream_.deviceBuffer ) free( stream_.deviceBuffer );\r
+      stream_.deviceBuffer = (char *) calloc( bufferBytes, 1 );\r
+      if ( stream_.deviceBuffer == NULL ) {\r
+        errorText_ = "RtApiOss::probeDeviceOpen: error allocating device buffer memory.";\r
+        goto error;\r
+      }\r
+    }\r
+  }\r
+\r
+  stream_.device[mode] = device;\r
+  stream_.state = STREAM_STOPPED;\r
+\r
+  // Setup the buffer conversion information structure.\r
+  if ( stream_.doConvertBuffer[mode] ) setConvertInfo( mode, firstChannel );\r
+\r
+  // Setup thread if necessary.\r
+  if ( stream_.mode == OUTPUT && mode == INPUT ) {\r
+    // We had already set up an output stream.\r
+    stream_.mode = DUPLEX;\r
+    if ( stream_.device[0] == device ) handle->id[0] = fd;\r
+  }\r
+  else {\r
+    stream_.mode = mode;\r
+\r
+    // Setup callback thread.\r
+    stream_.callbackInfo.object = (void *) this;\r
+\r
+    // Set the thread attributes for joinable and realtime scheduling\r
+    // priority.  The higher priority will only take affect if the\r
+    // program is run as root or suid.\r
+    pthread_attr_t attr;\r
+    pthread_attr_init( &attr );\r
+    pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );\r
+#ifdef SCHED_RR // Undefined with some OSes (eg: NetBSD 1.6.x with GNU Pthread)\r
+    if ( options && options->flags & RTAUDIO_SCHEDULE_REALTIME ) {\r
+      struct sched_param param;\r
+      int priority = options->priority;\r
+      int min = sched_get_priority_min( SCHED_RR );\r
+      int max = sched_get_priority_max( SCHED_RR );\r
+      if ( priority < min ) priority = min;\r
+      else if ( priority > max ) priority = max;\r
+      param.sched_priority = priority;\r
+      pthread_attr_setschedparam( &attr, &param );\r
+      pthread_attr_setschedpolicy( &attr, SCHED_RR );\r
+    }\r
+    else\r
+      pthread_attr_setschedpolicy( &attr, SCHED_OTHER );\r
+#else\r
+    pthread_attr_setschedpolicy( &attr, SCHED_OTHER );\r
+#endif\r
+\r
+    stream_.callbackInfo.isRunning = true;\r
+    result = pthread_create( &stream_.callbackInfo.thread, &attr, ossCallbackHandler, &stream_.callbackInfo );\r
+    pthread_attr_destroy( &attr );\r
+    if ( result ) {\r
+      stream_.callbackInfo.isRunning = false;\r
+      errorText_ = "RtApiOss::error creating callback thread!";\r
+      goto error;\r
+    }\r
+  }\r
+\r
+  return SUCCESS;\r
+\r
+ error:\r
+  if ( handle ) {\r
+    pthread_cond_destroy( &handle->runnable );\r
+    if ( handle->id[0] ) close( handle->id[0] );\r
+    if ( handle->id[1] ) close( handle->id[1] );\r
+    delete handle;\r
+    stream_.apiHandle = 0;\r
+  }\r
+\r
+  for ( int i=0; i<2; i++ ) {\r
+    if ( stream_.userBuffer[i] ) {\r
+      free( stream_.userBuffer[i] );\r
+      stream_.userBuffer[i] = 0;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceBuffer ) {\r
+    free( stream_.deviceBuffer );\r
+    stream_.deviceBuffer = 0;\r
+  }\r
+\r
+  return FAILURE;\r
+}\r
+\r
+void RtApiOss :: closeStream()\r
+{\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiOss::closeStream(): no open stream to close!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  OssHandle *handle = (OssHandle *) stream_.apiHandle;\r
+  stream_.callbackInfo.isRunning = false;\r
+  MUTEX_LOCK( &stream_.mutex );\r
+  if ( stream_.state == STREAM_STOPPED )\r
+    pthread_cond_signal( &handle->runnable );\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+  pthread_join( stream_.callbackInfo.thread, NULL );\r
+\r
+  if ( stream_.state == STREAM_RUNNING ) {\r
+    if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )\r
+      ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );\r
+    else\r
+      ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );\r
+    stream_.state = STREAM_STOPPED;\r
+  }\r
+\r
+  if ( handle ) {\r
+    pthread_cond_destroy( &handle->runnable );\r
+    if ( handle->id[0] ) close( handle->id[0] );\r
+    if ( handle->id[1] ) close( handle->id[1] );\r
+    delete handle;\r
+    stream_.apiHandle = 0;\r
+  }\r
+\r
+  for ( int i=0; i<2; i++ ) {\r
+    if ( stream_.userBuffer[i] ) {\r
+      free( stream_.userBuffer[i] );\r
+      stream_.userBuffer[i] = 0;\r
+    }\r
+  }\r
+\r
+  if ( stream_.deviceBuffer ) {\r
+    free( stream_.deviceBuffer );\r
+    stream_.deviceBuffer = 0;\r
+  }\r
+\r
+  stream_.mode = UNINITIALIZED;\r
+  stream_.state = STREAM_CLOSED;\r
+}\r
+\r
+void RtApiOss :: startStream()\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_RUNNING ) {\r
+    errorText_ = "RtApiOss::startStream(): the stream is already running!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  stream_.state = STREAM_RUNNING;\r
+\r
+  // No need to do anything else here ... OSS automatically starts\r
+  // when fed samples.\r
+\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+\r
+  OssHandle *handle = (OssHandle *) stream_.apiHandle;\r
+  pthread_cond_signal( &handle->runnable );\r
+}\r
+\r
+void RtApiOss :: stopStream()\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiOss::stopStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  // The state might change while waiting on a mutex.\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    MUTEX_UNLOCK( &stream_.mutex );\r
+    return;\r
+  }\r
+\r
+  int result = 0;\r
+  OssHandle *handle = (OssHandle *) stream_.apiHandle;\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+\r
+    // Flush the output with zeros a few times.\r
+    char *buffer;\r
+    int samples;\r
+    RtAudioFormat format;\r
+\r
+    if ( stream_.doConvertBuffer[0] ) {\r
+      buffer = stream_.deviceBuffer;\r
+      samples = stream_.bufferSize * stream_.nDeviceChannels[0];\r
+      format = stream_.deviceFormat[0];\r
+    }\r
+    else {\r
+      buffer = stream_.userBuffer[0];\r
+      samples = stream_.bufferSize * stream_.nUserChannels[0];\r
+      format = stream_.userFormat;\r
+    }\r
+\r
+    memset( buffer, 0, samples * formatBytes(format) );\r
+    for ( unsigned int i=0; i<stream_.nBuffers+1; i++ ) {\r
+      result = write( handle->id[0], buffer, samples * formatBytes(format) );\r
+      if ( result == -1 ) {\r
+        errorText_ = "RtApiOss::stopStream: audio write error.";\r
+        error( RtAudioError::WARNING );\r
+      }\r
+    }\r
+\r
+    result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );\r
+    if ( result == -1 ) {\r
+      errorStream_ << "RtApiOss::stopStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+    handle->triggered = false;\r
+  }\r
+\r
+  if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {\r
+    result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );\r
+    if ( result == -1 ) {\r
+      errorStream_ << "RtApiOss::stopStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+  }\r
+\r
+ unlock:\r
+  stream_.state = STREAM_STOPPED;\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+\r
+  if ( result != -1 ) return;\r
+  error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiOss :: abortStream()\r
+{\r
+  verifyStream();\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    errorText_ = "RtApiOss::abortStream(): the stream is already stopped!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  // The state might change while waiting on a mutex.\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    MUTEX_UNLOCK( &stream_.mutex );\r
+    return;\r
+  }\r
+\r
+  int result = 0;\r
+  OssHandle *handle = (OssHandle *) stream_.apiHandle;\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+    result = ioctl( handle->id[0], SNDCTL_DSP_HALT, 0 );\r
+    if ( result == -1 ) {\r
+      errorStream_ << "RtApiOss::abortStream: system error stopping callback procedure on device (" << stream_.device[0] << ").";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+    handle->triggered = false;\r
+  }\r
+\r
+  if ( stream_.mode == INPUT || ( stream_.mode == DUPLEX && handle->id[0] != handle->id[1] ) ) {\r
+    result = ioctl( handle->id[1], SNDCTL_DSP_HALT, 0 );\r
+    if ( result == -1 ) {\r
+      errorStream_ << "RtApiOss::abortStream: system error stopping input callback procedure on device (" << stream_.device[0] << ").";\r
+      errorText_ = errorStream_.str();\r
+      goto unlock;\r
+    }\r
+  }\r
+\r
+ unlock:\r
+  stream_.state = STREAM_STOPPED;\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+\r
+  if ( result != -1 ) return;\r
+  error( RtAudioError::SYSTEM_ERROR );\r
+}\r
+\r
+void RtApiOss :: callbackEvent()\r
+{\r
+  OssHandle *handle = (OssHandle *) stream_.apiHandle;\r
+  if ( stream_.state == STREAM_STOPPED ) {\r
+    MUTEX_LOCK( &stream_.mutex );\r
+    pthread_cond_wait( &handle->runnable, &stream_.mutex );\r
+    if ( stream_.state != STREAM_RUNNING ) {\r
+      MUTEX_UNLOCK( &stream_.mutex );\r
+      return;\r
+    }\r
+    MUTEX_UNLOCK( &stream_.mutex );\r
+  }\r
+\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApiOss::callbackEvent(): the stream is closed ... this shouldn't happen!";\r
+    error( RtAudioError::WARNING );\r
+    return;\r
+  }\r
+\r
+  // Invoke user callback to get fresh output data.\r
+  int doStopStream = 0;\r
+  RtAudioCallback callback = (RtAudioCallback) stream_.callbackInfo.callback;\r
+  double streamTime = getStreamTime();\r
+  RtAudioStreamStatus status = 0;\r
+  if ( stream_.mode != INPUT && handle->xrun[0] == true ) {\r
+    status |= RTAUDIO_OUTPUT_UNDERFLOW;\r
+    handle->xrun[0] = false;\r
+  }\r
+  if ( stream_.mode != OUTPUT && handle->xrun[1] == true ) {\r
+    status |= RTAUDIO_INPUT_OVERFLOW;\r
+    handle->xrun[1] = false;\r
+  }\r
+  doStopStream = callback( stream_.userBuffer[0], stream_.userBuffer[1],\r
+                           stream_.bufferSize, streamTime, status, stream_.callbackInfo.userData );\r
+  if ( doStopStream == 2 ) {\r
+    this->abortStream();\r
+    return;\r
+  }\r
+\r
+  MUTEX_LOCK( &stream_.mutex );\r
+\r
+  // The state might change while waiting on a mutex.\r
+  if ( stream_.state == STREAM_STOPPED ) goto unlock;\r
+\r
+  int result;\r
+  char *buffer;\r
+  int samples;\r
+  RtAudioFormat format;\r
+\r
+  if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX ) {\r
+\r
+    // Setup parameters and do buffer conversion if necessary.\r
+    if ( stream_.doConvertBuffer[0] ) {\r
+      buffer = stream_.deviceBuffer;\r
+      convertBuffer( buffer, stream_.userBuffer[0], stream_.convertInfo[0] );\r
+      samples = stream_.bufferSize * stream_.nDeviceChannels[0];\r
+      format = stream_.deviceFormat[0];\r
+    }\r
+    else {\r
+      buffer = stream_.userBuffer[0];\r
+      samples = stream_.bufferSize * stream_.nUserChannels[0];\r
+      format = stream_.userFormat;\r
+    }\r
+\r
+    // Do byte swapping if necessary.\r
+    if ( stream_.doByteSwap[0] )\r
+      byteSwapBuffer( buffer, samples, format );\r
+\r
+    if ( stream_.mode == DUPLEX && handle->triggered == false ) {\r
+      int trig = 0;\r
+      ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );\r
+      result = write( handle->id[0], buffer, samples * formatBytes(format) );\r
+      trig = PCM_ENABLE_INPUT|PCM_ENABLE_OUTPUT;\r
+      ioctl( handle->id[0], SNDCTL_DSP_SETTRIGGER, &trig );\r
+      handle->triggered = true;\r
+    }\r
+    else\r
+      // Write samples to device.\r
+      result = write( handle->id[0], buffer, samples * formatBytes(format) );\r
+\r
+    if ( result == -1 ) {\r
+      // We'll assume this is an underrun, though there isn't a\r
+      // specific means for determining that.\r
+      handle->xrun[0] = true;\r
+      errorText_ = "RtApiOss::callbackEvent: audio write error.";\r
+      error( RtAudioError::WARNING );\r
+      // Continue on to input section.\r
+    }\r
+  }\r
+\r
+  if ( stream_.mode == INPUT || stream_.mode == DUPLEX ) {\r
+\r
+    // Setup parameters.\r
+    if ( stream_.doConvertBuffer[1] ) {\r
+      buffer = stream_.deviceBuffer;\r
+      samples = stream_.bufferSize * stream_.nDeviceChannels[1];\r
+      format = stream_.deviceFormat[1];\r
+    }\r
+    else {\r
+      buffer = stream_.userBuffer[1];\r
+      samples = stream_.bufferSize * stream_.nUserChannels[1];\r
+      format = stream_.userFormat;\r
+    }\r
+\r
+    // Read samples from device.\r
+    result = read( handle->id[1], buffer, samples * formatBytes(format) );\r
+\r
+    if ( result == -1 ) {\r
+      // We'll assume this is an overrun, though there isn't a\r
+      // specific means for determining that.\r
+      handle->xrun[1] = true;\r
+      errorText_ = "RtApiOss::callbackEvent: audio read error.";\r
+      error( RtAudioError::WARNING );\r
+      goto unlock;\r
+    }\r
+\r
+    // Do byte swapping if necessary.\r
+    if ( stream_.doByteSwap[1] )\r
+      byteSwapBuffer( buffer, samples, format );\r
+\r
+    // Do buffer conversion if necessary.\r
+    if ( stream_.doConvertBuffer[1] )\r
+      convertBuffer( stream_.userBuffer[1], stream_.deviceBuffer, stream_.convertInfo[1] );\r
+  }\r
+\r
+ unlock:\r
+  MUTEX_UNLOCK( &stream_.mutex );\r
+\r
+  RtApi::tickStreamTime();\r
+  if ( doStopStream == 1 ) this->stopStream();\r
+}\r
+\r
+static void *ossCallbackHandler( void *ptr )\r
+{\r
+  CallbackInfo *info = (CallbackInfo *) ptr;\r
+  RtApiOss *object = (RtApiOss *) info->object;\r
+  bool *isRunning = &info->isRunning;\r
+\r
+  while ( *isRunning == true ) {\r
+    pthread_testcancel();\r
+    object->callbackEvent();\r
+  }\r
+\r
+  pthread_exit( NULL );\r
+}\r
+\r
+//******************** End of __LINUX_OSS__ *********************//\r
+#endif\r
+\r
+\r
+// *************************************************** //\r
+//\r
+// Protected common (OS-independent) RtAudio methods.\r
+//\r
+// *************************************************** //\r
+\r
+// This method can be modified to control the behavior of error\r
+// message printing.\r
+void RtApi :: error( RtAudioError::Type type )\r
+{\r
+  errorStream_.str(""); // clear the ostringstream\r
+\r
+  RtAudioErrorCallback errorCallback = (RtAudioErrorCallback) stream_.callbackInfo.errorCallback;\r
+  if ( errorCallback ) {\r
+    // abortStream() can generate new error messages. Ignore them. Just keep original one.\r
+\r
+    if ( firstErrorOccurred_ )\r
+      return;\r
+\r
+    firstErrorOccurred_ = true;\r
+    const std::string errorMessage = errorText_;\r
+\r
+    if ( type != RtAudioError::WARNING && stream_.state != STREAM_STOPPED) {\r
+      stream_.callbackInfo.isRunning = false; // exit from the thread\r
+      abortStream();\r
+    }\r
+\r
+    errorCallback( type, errorMessage );\r
+    firstErrorOccurred_ = false;\r
+    return;\r
+  }\r
+\r
+  if ( type == RtAudioError::WARNING && showWarnings_ == true )\r
+    std::cerr << '\n' << errorText_ << "\n\n";\r
+  else if ( type != RtAudioError::WARNING )\r
+    throw( RtAudioError( errorText_, type ) );\r
+}\r
+\r
+void RtApi :: verifyStream()\r
+{\r
+  if ( stream_.state == STREAM_CLOSED ) {\r
+    errorText_ = "RtApi:: a stream is not open!";\r
+    error( RtAudioError::INVALID_USE );\r
+  }\r
+}\r
+\r
+void RtApi :: clearStreamInfo()\r
+{\r
+  stream_.mode = UNINITIALIZED;\r
+  stream_.state = STREAM_CLOSED;\r
+  stream_.sampleRate = 0;\r
+  stream_.bufferSize = 0;\r
+  stream_.nBuffers = 0;\r
+  stream_.userFormat = 0;\r
+  stream_.userInterleaved = true;\r
+  stream_.streamTime = 0.0;\r
+  stream_.apiHandle = 0;\r
+  stream_.deviceBuffer = 0;\r
+  stream_.callbackInfo.callback = 0;\r
+  stream_.callbackInfo.userData = 0;\r
+  stream_.callbackInfo.isRunning = false;\r
+  stream_.callbackInfo.errorCallback = 0;\r
+  for ( int i=0; i<2; i++ ) {\r
+    stream_.device[i] = 11111;\r
+    stream_.doConvertBuffer[i] = false;\r
+    stream_.deviceInterleaved[i] = true;\r
+    stream_.doByteSwap[i] = false;\r
+    stream_.nUserChannels[i] = 0;\r
+    stream_.nDeviceChannels[i] = 0;\r
+    stream_.channelOffset[i] = 0;\r
+    stream_.deviceFormat[i] = 0;\r
+    stream_.latency[i] = 0;\r
+    stream_.userBuffer[i] = 0;\r
+    stream_.convertInfo[i].channels = 0;\r
+    stream_.convertInfo[i].inJump = 0;\r
+    stream_.convertInfo[i].outJump = 0;\r
+    stream_.convertInfo[i].inFormat = 0;\r
+    stream_.convertInfo[i].outFormat = 0;\r
+    stream_.convertInfo[i].inOffset.clear();\r
+    stream_.convertInfo[i].outOffset.clear();\r
+  }\r
+}\r
+\r
+unsigned int RtApi :: formatBytes( RtAudioFormat format )\r
+{\r
+  if ( format == RTAUDIO_SINT16 )\r
+    return 2;\r
+  else if ( format == RTAUDIO_SINT32 || format == RTAUDIO_FLOAT32 )\r
+    return 4;\r
+  else if ( format == RTAUDIO_FLOAT64 )\r
+    return 8;\r
+  else if ( format == RTAUDIO_SINT24 )\r
+    return 3;\r
+  else if ( format == RTAUDIO_SINT8 )\r
+    return 1;\r
+\r
+  errorText_ = "RtApi::formatBytes: undefined format.";\r
+  error( RtAudioError::WARNING );\r
+\r
+  return 0;\r
+}\r
+\r
+void RtApi :: setConvertInfo( StreamMode mode, unsigned int firstChannel )\r
+{\r
+  if ( mode == INPUT ) { // convert device to user buffer\r
+    stream_.convertInfo[mode].inJump = stream_.nDeviceChannels[1];\r
+    stream_.convertInfo[mode].outJump = stream_.nUserChannels[1];\r
+    stream_.convertInfo[mode].inFormat = stream_.deviceFormat[1];\r
+    stream_.convertInfo[mode].outFormat = stream_.userFormat;\r
+  }\r
+  else { // convert user to device buffer\r
+    stream_.convertInfo[mode].inJump = stream_.nUserChannels[0];\r
+    stream_.convertInfo[mode].outJump = stream_.nDeviceChannels[0];\r
+    stream_.convertInfo[mode].inFormat = stream_.userFormat;\r
+    stream_.convertInfo[mode].outFormat = stream_.deviceFormat[0];\r
+  }\r
+\r
+  if ( stream_.convertInfo[mode].inJump < stream_.convertInfo[mode].outJump )\r
+    stream_.convertInfo[mode].channels = stream_.convertInfo[mode].inJump;\r
+  else\r
+    stream_.convertInfo[mode].channels = stream_.convertInfo[mode].outJump;\r
+\r
+  // Set up the interleave/deinterleave offsets.\r
+  if ( stream_.deviceInterleaved[mode] != stream_.userInterleaved ) {\r
+    if ( ( mode == OUTPUT && stream_.deviceInterleaved[mode] ) ||\r
+         ( mode == INPUT && stream_.userInterleaved ) ) {\r
+      for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {\r
+        stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );\r
+        stream_.convertInfo[mode].outOffset.push_back( k );\r
+        stream_.convertInfo[mode].inJump = 1;\r
+      }\r
+    }\r
+    else {\r
+      for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {\r
+        stream_.convertInfo[mode].inOffset.push_back( k );\r
+        stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );\r
+        stream_.convertInfo[mode].outJump = 1;\r
+      }\r
+    }\r
+  }\r
+  else { // no (de)interleaving\r
+    if ( stream_.userInterleaved ) {\r
+      for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {\r
+        stream_.convertInfo[mode].inOffset.push_back( k );\r
+        stream_.convertInfo[mode].outOffset.push_back( k );\r
+      }\r
+    }\r
+    else {\r
+      for ( int k=0; k<stream_.convertInfo[mode].channels; k++ ) {\r
+        stream_.convertInfo[mode].inOffset.push_back( k * stream_.bufferSize );\r
+        stream_.convertInfo[mode].outOffset.push_back( k * stream_.bufferSize );\r
+        stream_.convertInfo[mode].inJump = 1;\r
+        stream_.convertInfo[mode].outJump = 1;\r
+      }\r
+    }\r
+  }\r
+\r
+  // Add channel offset.\r
+  if ( firstChannel > 0 ) {\r
+    if ( stream_.deviceInterleaved[mode] ) {\r
+      if ( mode == OUTPUT ) {\r
+        for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )\r
+          stream_.convertInfo[mode].outOffset[k] += firstChannel;\r
+      }\r
+      else {\r
+        for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )\r
+          stream_.convertInfo[mode].inOffset[k] += firstChannel;\r
+      }\r
+    }\r
+    else {\r
+      if ( mode == OUTPUT ) {\r
+        for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )\r
+          stream_.convertInfo[mode].outOffset[k] += ( firstChannel * stream_.bufferSize );\r
+      }\r
+      else {\r
+        for ( int k=0; k<stream_.convertInfo[mode].channels; k++ )\r
+          stream_.convertInfo[mode].inOffset[k] += ( firstChannel  * stream_.bufferSize );\r
+      }\r
+    }\r
+  }\r
+}\r
+\r
+void RtApi :: convertBuffer( char *outBuffer, char *inBuffer, ConvertInfo &info )\r
+{\r
+  // This function does format conversion, input/output channel compensation, and\r
+  // data interleaving/deinterleaving.  24-bit integers are assumed to occupy\r
+  // the lower three bytes of a 32-bit integer.\r
+\r
+  // Clear our device buffer when in/out duplex device channels are different\r
+  if ( outBuffer == stream_.deviceBuffer && stream_.mode == DUPLEX &&\r
+       ( stream_.nDeviceChannels[0] < stream_.nDeviceChannels[1] ) )\r
+    memset( outBuffer, 0, stream_.bufferSize * info.outJump * formatBytes( info.outFormat ) );\r
+\r
+  int j;\r
+  if (info.outFormat == RTAUDIO_FLOAT64) {\r
+    Float64 scale;\r
+    Float64 *out = (Float64 *)outBuffer;\r
+\r
+    if (info.inFormat == RTAUDIO_SINT8) {\r
+      signed char *in = (signed char *)inBuffer;\r
+      scale = 1.0 / 127.5;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];\r
+          out[info.outOffset[j]] += 0.5;\r
+          out[info.outOffset[j]] *= scale;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT16) {\r
+      Int16 *in = (Int16 *)inBuffer;\r
+      scale = 1.0 / 32767.5;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];\r
+          out[info.outOffset[j]] += 0.5;\r
+          out[info.outOffset[j]] *= scale;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT24) {\r
+      Int24 *in = (Int24 *)inBuffer;\r
+      scale = 1.0 / 8388607.5;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Float64) (in[info.inOffset[j]].asInt());\r
+          out[info.outOffset[j]] += 0.5;\r
+          out[info.outOffset[j]] *= scale;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT32) {\r
+      Int32 *in = (Int32 *)inBuffer;\r
+      scale = 1.0 / 2147483647.5;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];\r
+          out[info.outOffset[j]] += 0.5;\r
+          out[info.outOffset[j]] *= scale;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_FLOAT32) {\r
+      Float32 *in = (Float32 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Float64) in[info.inOffset[j]];\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_FLOAT64) {\r
+      // Channel compensation and/or (de)interleaving only.\r
+      Float64 *in = (Float64 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = in[info.inOffset[j]];\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+  }\r
+  else if (info.outFormat == RTAUDIO_FLOAT32) {\r
+    Float32 scale;\r
+    Float32 *out = (Float32 *)outBuffer;\r
+\r
+    if (info.inFormat == RTAUDIO_SINT8) {\r
+      signed char *in = (signed char *)inBuffer;\r
+      scale = (Float32) ( 1.0 / 127.5 );\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];\r
+          out[info.outOffset[j]] += 0.5;\r
+          out[info.outOffset[j]] *= scale;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT16) {\r
+      Int16 *in = (Int16 *)inBuffer;\r
+      scale = (Float32) ( 1.0 / 32767.5 );\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];\r
+          out[info.outOffset[j]] += 0.5;\r
+          out[info.outOffset[j]] *= scale;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT24) {\r
+      Int24 *in = (Int24 *)inBuffer;\r
+      scale = (Float32) ( 1.0 / 8388607.5 );\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Float32) (in[info.inOffset[j]].asInt());\r
+          out[info.outOffset[j]] += 0.5;\r
+          out[info.outOffset[j]] *= scale;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT32) {\r
+      Int32 *in = (Int32 *)inBuffer;\r
+      scale = (Float32) ( 1.0 / 2147483647.5 );\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];\r
+          out[info.outOffset[j]] += 0.5;\r
+          out[info.outOffset[j]] *= scale;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_FLOAT32) {\r
+      // Channel compensation and/or (de)interleaving only.\r
+      Float32 *in = (Float32 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = in[info.inOffset[j]];\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_FLOAT64) {\r
+      Float64 *in = (Float64 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Float32) in[info.inOffset[j]];\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+  }\r
+  else if (info.outFormat == RTAUDIO_SINT32) {\r
+    Int32 *out = (Int32 *)outBuffer;\r
+    if (info.inFormat == RTAUDIO_SINT8) {\r
+      signed char *in = (signed char *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];\r
+          out[info.outOffset[j]] <<= 24;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT16) {\r
+      Int16 *in = (Int16 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]];\r
+          out[info.outOffset[j]] <<= 16;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT24) {\r
+      Int24 *in = (Int24 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int32) in[info.inOffset[j]].asInt();\r
+          out[info.outOffset[j]] <<= 8;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT32) {\r
+      // Channel compensation and/or (de)interleaving only.\r
+      Int32 *in = (Int32 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = in[info.inOffset[j]];\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_FLOAT32) {\r
+      Float32 *in = (Float32 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_FLOAT64) {\r
+      Float64 *in = (Float64 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 2147483647.5 - 0.5);\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+  }\r
+  else if (info.outFormat == RTAUDIO_SINT24) {\r
+    Int24 *out = (Int24 *)outBuffer;\r
+    if (info.inFormat == RTAUDIO_SINT8) {\r
+      signed char *in = (signed char *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 16);\r
+          //out[info.outOffset[j]] <<= 16;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT16) {\r
+      Int16 *in = (Int16 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] << 8);\r
+          //out[info.outOffset[j]] <<= 8;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT24) {\r
+      // Channel compensation and/or (de)interleaving only.\r
+      Int24 *in = (Int24 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = in[info.inOffset[j]];\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT32) {\r
+      Int32 *in = (Int32 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] >> 8);\r
+          //out[info.outOffset[j]] >>= 8;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_FLOAT32) {\r
+      Float32 *in = (Float32 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_FLOAT64) {\r
+      Float64 *in = (Float64 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int32) (in[info.inOffset[j]] * 8388607.5 - 0.5);\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+  }\r
+  else if (info.outFormat == RTAUDIO_SINT16) {\r
+    Int16 *out = (Int16 *)outBuffer;\r
+    if (info.inFormat == RTAUDIO_SINT8) {\r
+      signed char *in = (signed char *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int16) in[info.inOffset[j]];\r
+          out[info.outOffset[j]] <<= 8;\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT16) {\r
+      // Channel compensation and/or (de)interleaving only.\r
+      Int16 *in = (Int16 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = in[info.inOffset[j]];\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT24) {\r
+      Int24 *in = (Int24 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]].asInt() >> 8);\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT32) {\r
+      Int32 *in = (Int32 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int16) ((in[info.inOffset[j]] >> 16) & 0x0000ffff);\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_FLOAT32) {\r
+      Float32 *in = (Float32 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_FLOAT64) {\r
+      Float64 *in = (Float64 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (Int16) (in[info.inOffset[j]] * 32767.5 - 0.5);\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+  }\r
+  else if (info.outFormat == RTAUDIO_SINT8) {\r
+    signed char *out = (signed char *)outBuffer;\r
+    if (info.inFormat == RTAUDIO_SINT8) {\r
+      // Channel compensation and/or (de)interleaving only.\r
+      signed char *in = (signed char *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = in[info.inOffset[j]];\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    if (info.inFormat == RTAUDIO_SINT16) {\r
+      Int16 *in = (Int16 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 8) & 0x00ff);\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT24) {\r
+      Int24 *in = (Int24 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]].asInt() >> 16);\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_SINT32) {\r
+      Int32 *in = (Int32 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (signed char) ((in[info.inOffset[j]] >> 24) & 0x000000ff);\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_FLOAT32) {\r
+      Float32 *in = (Float32 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+    else if (info.inFormat == RTAUDIO_FLOAT64) {\r
+      Float64 *in = (Float64 *)inBuffer;\r
+      for (unsigned int i=0; i<stream_.bufferSize; i++) {\r
+        for (j=0; j<info.channels; j++) {\r
+          out[info.outOffset[j]] = (signed char) (in[info.inOffset[j]] * 127.5 - 0.5);\r
+        }\r
+        in += info.inJump;\r
+        out += info.outJump;\r
+      }\r
+    }\r
+  }\r
+}\r
+\r
+//static inline uint16_t bswap_16(uint16_t x) { return (x>>8) | (x<<8); }\r
+//static inline uint32_t bswap_32(uint32_t x) { return (bswap_16(x&0xffff)<<16) | (bswap_16(x>>16)); }\r
+//static inline uint64_t bswap_64(uint64_t x) { return (((unsigned long long)bswap_32(x&0xffffffffull))<<32) | (bswap_32(x>>32)); }\r
+\r
+void RtApi :: byteSwapBuffer( char *buffer, unsigned int samples, RtAudioFormat format )\r
+{\r
+  char val;\r
+  char *ptr;\r
+\r
+  ptr = buffer;\r
+  if ( format == RTAUDIO_SINT16 ) {\r
+    for ( unsigned int i=0; i<samples; i++ ) {\r
+      // Swap 1st and 2nd bytes.\r
+      val = *(ptr);\r
+      *(ptr) = *(ptr+1);\r
+      *(ptr+1) = val;\r
+\r
+      // Increment 2 bytes.\r
+      ptr += 2;\r
+    }\r
+  }\r
+  else if ( format == RTAUDIO_SINT32 ||\r
+            format == RTAUDIO_FLOAT32 ) {\r
+    for ( unsigned int i=0; i<samples; i++ ) {\r
+      // Swap 1st and 4th bytes.\r
+      val = *(ptr);\r
+      *(ptr) = *(ptr+3);\r
+      *(ptr+3) = val;\r
+\r
+      // Swap 2nd and 3rd bytes.\r
+      ptr += 1;\r
+      val = *(ptr);\r
+      *(ptr) = *(ptr+1);\r
+      *(ptr+1) = val;\r
+\r
+      // Increment 3 more bytes.\r
+      ptr += 3;\r
+    }\r
+  }\r
+  else if ( format == RTAUDIO_SINT24 ) {\r
+    for ( unsigned int i=0; i<samples; i++ ) {\r
+      // Swap 1st and 3rd bytes.\r
+      val = *(ptr);\r
+      *(ptr) = *(ptr+2);\r
+      *(ptr+2) = val;\r
+\r
+      // Increment 2 more bytes.\r
+      ptr += 2;\r
+    }\r
+  }\r
+  else if ( format == RTAUDIO_FLOAT64 ) {\r
+    for ( unsigned int i=0; i<samples; i++ ) {\r
+      // Swap 1st and 8th bytes\r
+      val = *(ptr);\r
+      *(ptr) = *(ptr+7);\r
+      *(ptr+7) = val;\r
+\r
+      // Swap 2nd and 7th bytes\r
+      ptr += 1;\r
+      val = *(ptr);\r
+      *(ptr) = *(ptr+5);\r
+      *(ptr+5) = val;\r
+\r
+      // Swap 3rd and 6th bytes\r
+      ptr += 1;\r
+      val = *(ptr);\r
+      *(ptr) = *(ptr+3);\r
+      *(ptr+3) = val;\r
+\r
+      // Swap 4th and 5th bytes\r
+      ptr += 1;\r
+      val = *(ptr);\r
+      *(ptr) = *(ptr+1);\r
+      *(ptr+1) = val;\r
+\r
+      // Increment 5 more bytes.\r
+      ptr += 5;\r
+    }\r
+  }\r
+}\r
+\r
+  // Indentation settings for Vim and Emacs\r
+  //\r
+  // Local Variables:\r
+  // c-basic-offset: 2\r
+  // indent-tabs-mode: nil\r
+  // End:\r
+  //\r
+  // vim: et sts=2 sw=2\r
+\r