Version 2.0
authorGary Scavone <gary@music.mcgill.ca>
Thu, 6 Dec 2007 01:40:05 +0000 (01:40 +0000)
committerStephen Sinclair <sinclair@music.mcgill.ca>
Wed, 9 Oct 2013 23:08:11 +0000 (01:08 +0200)
30 files changed:
README [new file with mode: 0644]
RtAudio.cpp [new file with mode: 0644]
RtAudio.h [new file with mode: 0644]
doc/Doxyfile [new file with mode: 0644]
doc/ccrma.gif [new file with mode: 0644]
doc/footer.html [new file with mode: 0644]
doc/header.html [new file with mode: 0644]
doc/tutorial.txt [new file with mode: 0644]
rtaudio.dsw [new file with mode: 0644]
tests/Debug/.placeholder [new file with mode: 0644]
tests/Makefile [new file with mode: 0644]
tests/Release/.placeholder [new file with mode: 0644]
tests/call_inout.cpp [new file with mode: 0644]
tests/call_inout.dsp [new file with mode: 0644]
tests/call_saw.cpp [new file with mode: 0644]
tests/call_saw.dsp [new file with mode: 0644]
tests/call_twostreams.cpp [new file with mode: 0644]
tests/call_twostreams.dsp [new file with mode: 0644]
tests/in_out.cpp [new file with mode: 0644]
tests/in_out.dsp [new file with mode: 0644]
tests/info.cpp [new file with mode: 0644]
tests/info.dsp [new file with mode: 0644]
tests/play_raw.cpp [new file with mode: 0644]
tests/play_raw.dsp [new file with mode: 0644]
tests/play_saw.cpp [new file with mode: 0644]
tests/play_saw.dsp [new file with mode: 0644]
tests/record_raw.cpp [new file with mode: 0644]
tests/record_raw.dsp [new file with mode: 0644]
tests/twostreams.cpp [new file with mode: 0644]
tests/twostreams.dsp [new file with mode: 0644]

diff --git a/README b/README
new file mode 100644 (file)
index 0000000..729f1e8
--- /dev/null
+++ b/README
@@ -0,0 +1,12 @@
+
+This is the parent directory of the RtAudio distribution.  Here is a quick description of what is contained here:
+
+RtAudio.h   - class header
+RtAudio.cpp - class source
+rtaudio.dsw - Visual C++ 6.0 workspace file
+
+Directories:
+
+tests - various test programs and Visual C++ 6.0 project files
+doc   - complete documentation in a variety of formats (see doc/html/index.html)
+
diff --git a/RtAudio.cpp b/RtAudio.cpp
new file mode 100644 (file)
index 0000000..d2f8724
--- /dev/null
@@ -0,0 +1,4997 @@
+/******************************************/
+/*
+  RtAudio - realtime sound I/O C++ class
+  Version 2.0 by Gary P. Scavone, 2001-2002.
+*/
+/******************************************/
+
+#include "RtAudio.h"
+#include <vector>
+#include <stdio.h>
+
+// Static variable definitions.
+const unsigned int RtAudio :: SAMPLE_RATES[] = {
+  4000, 5512, 8000, 9600, 11025, 16000, 22050,
+  32000, 44100, 48000, 88200, 96000, 176400, 192000
+};
+const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT8 = 1;
+const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT16 = 2;
+const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT24 = 4;
+const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_SINT32 = 8;
+const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_FLOAT32 = 16;
+const RtAudio::RTAUDIO_FORMAT RtAudio :: RTAUDIO_FLOAT64 = 32;
+
+#if defined(__WINDOWS_DS_)
+  #define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)
+  #define MUTEX_LOCK(A)       EnterCriticalSection(A)
+  #define MUTEX_UNLOCK(A)     LeaveCriticalSection(A)
+  typedef unsigned THREAD_RETURN;
+#else // pthread API
+  #define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)
+  #define MUTEX_LOCK(A)       pthread_mutex_lock(A)
+  #define MUTEX_UNLOCK(A)     pthread_mutex_unlock(A)
+  typedef void * THREAD_RETURN;
+#endif
+
+// *************************************************** //
+//
+// Public common (OS-independent) methods.
+//
+// *************************************************** //
+
+RtAudio :: RtAudio()
+{
+  initialize();
+
+  if (nDevices <= 0) {
+    sprintf(message, "RtAudio: no audio devices found!");
+    error(RtAudioError::NO_DEVICES_FOUND);
+  }
+}
+
+RtAudio :: RtAudio(int *streamID,
+                   int outputDevice, int outputChannels,
+                   int inputDevice, int inputChannels,
+                   RTAUDIO_FORMAT format, int sampleRate,
+                   int *bufferSize, int numberOfBuffers)
+{
+  initialize();
+
+  if (nDevices <= 0) {
+    sprintf(message, "RtAudio: no audio devices found!");
+    error(RtAudioError::NO_DEVICES_FOUND);
+  }
+
+  try {
+    *streamID = openStream(outputDevice, outputChannels, inputDevice, inputChannels,
+                           format, sampleRate, bufferSize, numberOfBuffers);
+  }
+  catch (RtAudioError &exception) {
+    // deallocate the RTAUDIO_DEVICE structures
+    if (devices) free(devices);
+    error(exception.getType());
+  }
+}
+
+RtAudio :: ~RtAudio()
+{
+  // close any existing streams
+  while ( streams.size() )
+    closeStream( streams.begin()->first );
+
+  // deallocate the RTAUDIO_DEVICE structures
+  if (devices) free(devices);
+}
+
+int RtAudio :: openStream(int outputDevice, int outputChannels,
+                          int inputDevice, int inputChannels,
+                          RTAUDIO_FORMAT format, int sampleRate,
+                          int *bufferSize, int numberOfBuffers)
+{
+  static int streamKey = 0; // Unique stream identifier ... OK for multiple instances.
+
+  if (outputChannels < 1 && inputChannels < 1) {
+    sprintf(message,"RtAudio: one or both 'channel' parameters must be greater than zero.");
+    error(RtAudioError::INVALID_PARAMETER);
+  }
+
+  if ( formatBytes(format) == 0 ) {
+    sprintf(message,"RtAudio: 'format' parameter value is undefined.");
+    error(RtAudioError::INVALID_PARAMETER);
+  }
+
+  if ( outputChannels > 0 ) {
+    if (outputDevice >= nDevices || outputDevice < 0) {
+      sprintf(message,"RtAudio: 'outputDevice' parameter value (%d) is invalid.", outputDevice);
+      error(RtAudioError::INVALID_PARAMETER);
+    }
+  }
+
+  if ( inputChannels > 0 ) {
+    if (inputDevice >= nDevices || inputDevice < 0) {
+      sprintf(message,"RtAudio: 'inputDevice' parameter value (%d) is invalid.", inputDevice);
+      error(RtAudioError::INVALID_PARAMETER);
+    }
+  }
+
+  // Allocate a new stream structure.
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) calloc(1, sizeof(RTAUDIO_STREAM));
+  if (stream == NULL) {
+    sprintf(message, "RtAudio: memory allocation error!");
+    error(RtAudioError::MEMORY_ERROR);
+  }
+  streams[++streamKey] = (void *) stream;
+  stream->mode = UNINITIALIZED;
+
+  bool result = SUCCESS;
+  int device;
+  STREAM_MODE mode;
+  int channels;
+  if ( outputChannels > 0 ) {
+
+    device = outputDevice;
+    mode = PLAYBACK;
+    channels = outputChannels;
+
+    if (device == 0) { // Try default device first.
+      for (int i=0; i<nDevices; i++) {
+        if (devices[i].probed == false) {
+          // If the device wasn't successfully probed before, try it
+          // again now.
+          clearDeviceInfo(&devices[i]);
+          probeDeviceInfo(&devices[i]);
+          if (devices[i].probed == false)
+            continue;
+        }
+        result = probeDeviceOpen(i, stream, mode, channels, sampleRate,
+                                 format, bufferSize, numberOfBuffers);
+        if (result == SUCCESS)
+          break;
+      }
+    }
+    else {
+      result = probeDeviceOpen(device, stream, mode, channels, sampleRate,
+                               format, bufferSize, numberOfBuffers);
+    }
+  }
+
+  if ( inputChannels > 0 && result == SUCCESS ) {
+
+    device = inputDevice;
+    mode = RECORD;
+    channels = inputChannels;
+
+    if (device == 0) { // Try default device first.
+      for (int i=0; i<nDevices; i++) {
+        if (devices[i].probed == false) {
+          // If the device wasn't successfully probed before, try it
+          // again now.
+          clearDeviceInfo(&devices[i]);
+          probeDeviceInfo(&devices[i]);
+          if (devices[i].probed == false)
+            continue;
+        }
+        result = probeDeviceOpen(i, stream, mode, channels, sampleRate,
+                                 format, bufferSize, numberOfBuffers);
+        if (result == SUCCESS)
+          break;
+      }
+    }
+    else {
+      result = probeDeviceOpen(device, stream, mode, channels, sampleRate,
+                               format, bufferSize, numberOfBuffers);
+    }
+  }
+
+  if ( result == SUCCESS ) {
+    MUTEX_INITIALIZE(&stream->mutex);
+    return streamKey;
+  }
+
+  // If we get here, all attempted probes failed.  Close any opened
+  // devices and delete the allocated stream.
+  closeStream(streamKey);
+  sprintf(message,"RtAudio: no devices found for given parameters.");
+  error(RtAudioError::INVALID_PARAMETER);
+
+  return -1;
+}
+
+int RtAudio :: getDeviceCount(void)
+{
+  return nDevices;
+}
+
+void RtAudio :: getDeviceInfo(int device, RTAUDIO_DEVICE *info)
+{
+  if (device >= nDevices || device < 0) {
+    sprintf(message, "RtAudio: invalid device specifier (%d)!", device);
+    error(RtAudioError::INVALID_DEVICE);
+  }
+
+  // If the device wasn't successfully probed before, try it again.
+  if (devices[device].probed == false) {
+    clearDeviceInfo(&devices[device]);
+    probeDeviceInfo(&devices[device]);
+  }
+
+  // Clear the info structure.
+  memset(info, 0, sizeof(RTAUDIO_DEVICE));
+
+  strncpy(info->name, devices[device].name, 128);
+  info->probed = devices[device].probed;
+  if ( info->probed == true ) {
+    info->maxOutputChannels = devices[device].maxOutputChannels;
+    info->maxInputChannels = devices[device].maxInputChannels;
+    info->maxDuplexChannels = devices[device].maxDuplexChannels;
+    info->minOutputChannels = devices[device].minOutputChannels;
+    info->minInputChannels = devices[device].minInputChannels;
+    info->minDuplexChannels = devices[device].minDuplexChannels;
+    info->hasDuplexSupport = devices[device].hasDuplexSupport;
+    info->nSampleRates = devices[device].nSampleRates;
+    if (info->nSampleRates == -1) {
+      info->sampleRates[0] = devices[device].sampleRates[0];
+      info->sampleRates[1] = devices[device].sampleRates[1];
+    }
+    else {
+      for (int i=0; i<info->nSampleRates; i++)
+        info->sampleRates[i] = devices[device].sampleRates[i];
+    }
+    info->nativeFormats = devices[device].nativeFormats;
+  }
+
+  return;
+}
+
+char * const RtAudio :: getStreamBuffer(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  return stream->userBuffer;
+}
+
+// This global structure is used to pass information to the thread
+// function.  I tried other methods but had intermittent errors due to
+// variable persistence during thread startup.
+struct {
+  RtAudio *object;
+  int streamID;
+} thread_info;
+
+#if defined(__WINDOWS_DS_)
+  extern "C" unsigned __stdcall callbackHandler(void *ptr);
+#else
+  extern "C" void *callbackHandler(void *ptr);
+#endif
+
+void RtAudio :: setStreamCallback(int streamID, RTAUDIO_CALLBACK callback, void *userData)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  stream->callback = callback;
+  stream->userData = userData;
+  stream->usingCallback = true;
+  thread_info.object = this;
+  thread_info.streamID = streamID;
+
+  int err = 0;
+#if defined(__WINDOWS_DS_)
+  unsigned thread_id;
+  stream->thread = _beginthreadex(NULL, 0, &callbackHandler,
+                                  &stream->usingCallback, 0, &thread_id);
+  if (stream->thread == 0) err = -1;
+  // When spawning multiple threads in quick succession, it appears to be
+  // necessary to wait a bit for each to initialize ... another windism!
+  Sleep(1);
+#else
+  err = pthread_create(&stream->thread, NULL, callbackHandler, &stream->usingCallback);
+#endif
+
+  if (err) {
+    stream->usingCallback = false;
+    sprintf(message, "RtAudio: error starting callback thread!");
+    error(RtAudioError::THREAD_ERROR);
+  }
+}
+
+// *************************************************** //
+//
+// OS/API-specific methods.
+//
+// *************************************************** //
+
+#if defined(__LINUX_ALSA_)
+
+void RtAudio :: initialize(void)
+{
+  int card, err, device;
+  int devices_per_card[32] = {0};
+  char name[32];
+  snd_ctl_t *handle;
+  snd_ctl_card_info_t *info;
+  snd_ctl_card_info_alloca(&info);
+
+  // Count cards and devices
+  nDevices = 0;
+  card = -1;
+  snd_card_next(&card);
+  while (card >= 0) {
+    sprintf(name, "hw:%d", card);
+    err = snd_ctl_open(&handle, name, 0);
+    if (err < 0) {
+      sprintf(message, "RtAudio: ALSA control open (%i): %s.", card, snd_strerror(err));
+      error(RtAudioError::WARNING);
+      goto next_card;
+               }
+    err = snd_ctl_card_info(handle, info);
+               if (err < 0) {
+      sprintf(message, "RtAudio: ALSA control hardware info (%i): %s.", card, snd_strerror(err));
+      error(RtAudioError::WARNING);
+      goto next_card;
+               }
+               device = -1;
+               while (1) {
+      err = snd_ctl_pcm_next_device(handle, &device);
+                       if (err < 0) {
+        sprintf(message, "RtAudio: ALSA control next device (%i): %s.", card, snd_strerror(err));
+        error(RtAudioError::WARNING);
+        break;
+      }
+                       if (device < 0)
+        break;
+      nDevices++;
+      devices_per_card[card]++;
+    }
+
+  next_card:
+    snd_ctl_close(handle);
+    snd_card_next(&card);
+  }
+
+  if (nDevices == 0) return;
+
+  //  Allocate the RTAUDIO_DEVICE structures.
+  devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE));
+  if (devices == NULL) {
+    sprintf(message, "RtAudio: memory allocation error!");
+    error(RtAudioError::MEMORY_ERROR);
+  }
+
+  // Write device ascii identifiers to device structures and then
+  // probe the device capabilities.
+  card = 0;
+  device = 0;
+  for (int i=0; i<nDevices; i++) {
+    if (devices_per_card[card])
+      sprintf(devices[i].name, "hw:%d,%d", card, device);
+    if (devices_per_card[card] <= device+1) {
+      card++;
+      device = 0;
+    }
+    else
+      device++;
+    probeDeviceInfo(&devices[i]);
+  }
+
+  return;
+}
+
+void RtAudio :: probeDeviceInfo(RTAUDIO_DEVICE *info)
+{
+  int err;
+  int open_mode = SND_PCM_ASYNC;
+  snd_pcm_t *handle;
+  snd_pcm_stream_t stream;
+
+  // First try for playback
+  stream = SND_PCM_STREAM_PLAYBACK;
+  err = snd_pcm_open(&handle, info->name, stream, open_mode);
+  if (err < 0) {
+    sprintf(message, "RtAudio: ALSA pcm playback open (%s): %s.",
+            info->name, snd_strerror(err));
+    error(RtAudioError::WARNING);
+    goto capture_probe;
+  }
+
+  snd_pcm_hw_params_t *params;
+  snd_pcm_hw_params_alloca(&params);
+
+  // 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, "RtAudio: ALSA hardware probe error (%s): %s.",
+            info->name, snd_strerror(err));
+    error(RtAudioError::WARNING);
+    goto capture_probe;
+  }
+
+  // Get output channel information.
+  info->minOutputChannels = snd_pcm_hw_params_get_channels_min(params);
+  info->maxOutputChannels = snd_pcm_hw_params_get_channels_max(params);
+
+  snd_pcm_close(handle);
+
+ capture_probe:
+  // Now try for capture
+  stream = SND_PCM_STREAM_CAPTURE;
+  err = snd_pcm_open(&handle, info->name, stream, open_mode);
+  if (err < 0) {
+    sprintf(message, "RtAudio: ALSA pcm capture open (%s): %s.",
+            info->name, snd_strerror(err));
+    error(RtAudioError::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, "RtAudio: ALSA hardware probe error (%s): %s.",
+            info->name, snd_strerror(err));
+    error(RtAudioError::WARNING);
+    if (info->maxOutputChannels > 0)
+      goto probe_parameters;
+    else
+      return;
+  }
+
+  // Get input channel information.
+  info->minInputChannels = snd_pcm_hw_params_get_channels_min(params);
+  info->maxInputChannels = snd_pcm_hw_params_get_channels_max(params);
+
+  // 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;
+
+  snd_pcm_close(handle);
+
+ probe_parameters:
+  // At this point, we just 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)
+    stream = SND_PCM_STREAM_PLAYBACK;
+  else
+    stream = SND_PCM_STREAM_CAPTURE;
+
+  err = snd_pcm_open(&handle, info->name, stream, open_mode);
+  if (err < 0) {
+    sprintf(message, "RtAudio: ALSA pcm (%s) won't reopen during probe: %s.",
+            info->name, snd_strerror(err));
+    error(RtAudioError::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, "RtAudio: ALSA hardware reopen probe error (%s): %s.",
+            info->name, snd_strerror(err));
+    error(RtAudioError::WARNING);
+    return;
+  }
+
+  // Test a non-standard sample rate to see if continuous rate is supported.
+  int dir = 0;
+  if (snd_pcm_hw_params_test_rate(handle, params, 35500, dir) == 0) {
+    // It appears that continuous sample rate support is available.
+    info->nSampleRates = -1;
+    info->sampleRates[0] = snd_pcm_hw_params_get_rate_min(params, &dir);
+    info->sampleRates[1] = snd_pcm_hw_params_get_rate_max(params, &dir);
+  }
+  else {
+    // No continuous rate support ... test our discrete set of sample rate values.
+    info->nSampleRates = 0;
+    for (int i=0; i<MAX_SAMPLE_RATES; i++) {
+      if (snd_pcm_hw_params_test_rate(handle, params, SAMPLE_RATES[i], dir) == 0) {
+        info->sampleRates[info->nSampleRates] = SAMPLE_RATES[i];
+        info->nSampleRates++;
+      }
+    }
+    if (info->nSampleRates == 0) {
+      snd_pcm_close(handle);
+      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, "RtAudio: ALSA PCM device (%s) data format not supported by RtAudio.",
+            info->name);
+    error(RtAudioError::WARNING);
+    return;
+  }
+
+  // That's all ... close the device and return
+  snd_pcm_close(handle);
+  info->probed = true;
+  return;
+}
+
+bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream,
+                                STREAM_MODE mode, int channels, 
+                                int sampleRate, RTAUDIO_FORMAT 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;
+
+  snd_pcm_stream_t alsa_stream;
+  if (mode == PLAYBACK)
+    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,"RtAudio: ALSA pcm device (%s) won't open: %s.",
+            name, snd_strerror(err));
+    error(RtAudioError::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, "RtAudio: ALSA error getting parameter handle (%s): %s.",
+            name, snd_strerror(err));
+    error(RtAudioError::WARNING);
+    return FAILURE;
+  }
+
+#if defined(RTAUDIO_DEBUG)
+  fprintf(stderr, "\nRtAudio: ALSA 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
+  err = snd_pcm_hw_params_set_access(handle, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED);
+  if (err < 0) {
+    // No interleave support ... try non-interleave.
+               err = snd_pcm_hw_params_set_access(handle, hw_params, SND_PCM_ACCESS_RW_NONINTERLEAVED);
+    if (err < 0) {
+      snd_pcm_close(handle);
+      sprintf(message, "RtAudio: ALSA error setting access ( (%s): %s.",
+              name, snd_strerror(err));
+      error(RtAudioError::WARNING);
+      return FAILURE;
+    }
+    stream->deInterleave[mode] = true;
+  }
+
+  // Determine how to set the device format.
+  stream->userFormat = format;
+  snd_pcm_format_t device_format;
+
+  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,"RtAudio: ALSA pcm device (%s) data format not supported by RtAudio.", name);
+  snd_pcm_close(handle);
+  error(RtAudioError::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, "RtAudio: ALSA error setting format (%s): %s.",
+            name, snd_strerror(err));
+    error(RtAudioError::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, "RtAudio: ALSA error getting format endian-ness (%s): %s.",
+              name, snd_strerror(err));
+      error(RtAudioError::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;
+  int device_channels = snd_pcm_hw_params_get_channels_max(hw_params);
+  if (device_channels < channels) {
+    snd_pcm_close(handle);
+    sprintf(message, "RtAudio: channels (%d) not supported by device (%s).",
+            channels, name);
+    error(RtAudioError::WARNING);
+    return FAILURE;
+  }
+
+  device_channels = snd_pcm_hw_params_get_channels_min(hw_params);
+  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, "RtAudio: ALSA error setting channels (%d) on device (%s): %s.",
+            device_channels, name, snd_strerror(err));
+    error(RtAudioError::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, "RtAudio: ALSA error setting sample rate (%d) on device (%s): %s.",
+            sampleRate, name, snd_strerror(err));
+    error(RtAudioError::WARNING);
+    return FAILURE;
+  }
+
+  // Set the buffer number, which in ALSA is referred to as the "period".
+  int dir;
+  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_get_periods_min(hw_params, &dir);
+  if (err > periods) periods = err;
+
+  err = snd_pcm_hw_params_set_periods(handle, hw_params, periods, 0);
+  if (err < 0) {
+    snd_pcm_close(handle);
+    sprintf(message, "RtAudio: ALSA error setting periods (%s): %s.",
+            name, snd_strerror(err));
+    error(RtAudioError::WARNING);
+    return FAILURE;
+  }
+
+  // Set the buffer (or period) size.
+  err = snd_pcm_hw_params_get_period_size_min(hw_params, &dir);
+  if (err > *bufferSize) *bufferSize = err;
+
+  err = snd_pcm_hw_params_set_period_size(handle, hw_params, *bufferSize, 0);
+  if (err < 0) {
+    snd_pcm_close(handle);
+    sprintf(message, "RtAudio: ALSA error setting period size (%s): %s.",
+            name, snd_strerror(err));
+    error(RtAudioError::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, "RtAudio: ALSA error installing hardware configuration (%s): %s.",
+            name, snd_strerror(err));
+    error(RtAudioError::WARNING);
+    return FAILURE;
+  }
+
+#if defined(RTAUDIO_DEBUG)
+  fprintf(stderr, "\nRtAudio: ALSA dump hardware params after installation:\n\n");
+  snd_pcm_hw_params_dump(hw_params, out);
+#endif
+
+  /*
+  // Install the software configuration
+  snd_pcm_sw_params_t *sw_params = NULL;
+  snd_pcm_sw_params_alloca(&sw_params);
+  snd_pcm_sw_params_current(handle, sw_params);
+  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(RtAudioError::WARNING);
+    return FAILURE;
+  }
+  */
+
+  // Set handle and flags for buffer conversion
+  stream->handle[mode] = handle;
+  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)
+      goto memory_error;
+  }
+
+  if ( stream->doConvertBuffer[mode] ) {
+
+    long buffer_bytes;
+    bool makeBuffer = true;
+    if ( mode == PLAYBACK )
+      buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
+    else { // mode == RECORD
+      buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]);
+      if ( stream->mode == PLAYBACK ) {
+        long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
+        if ( buffer_bytes > bytes_out )
+          buffer_bytes = (buffer_bytes > bytes_out) ? buffer_bytes : bytes_out;
+        else
+          makeBuffer = false;
+      }
+    }
+
+    if ( makeBuffer ) {
+      buffer_bytes *= *bufferSize;
+      if (stream->deviceBuffer) free(stream->deviceBuffer);
+      stream->deviceBuffer = (char *) calloc(buffer_bytes, 1);
+      if (stream->deviceBuffer == NULL)
+        goto memory_error;
+    }
+  }
+
+  stream->device[mode] = device;
+  stream->state = STREAM_STOPPED;
+  if ( stream->mode == PLAYBACK && mode == RECORD )
+    // We had already set up an output stream.
+    stream->mode = DUPLEX;
+  else
+    stream->mode = mode;
+  stream->nBuffers = periods;
+  stream->sampleRate = sampleRate;
+
+  return SUCCESS;
+
+ memory_error:
+  if (stream->handle[0]) {
+    snd_pcm_close(stream->handle[0]);
+    stream->handle[0] = 0;
+  }
+  if (stream->handle[1]) {
+    snd_pcm_close(stream->handle[1]);
+    stream->handle[1] = 0;
+  }
+  if (stream->userBuffer) {
+    free(stream->userBuffer);
+    stream->userBuffer = 0;
+  }
+  sprintf(message, "RtAudio: ALSA error allocating buffer memory (%s).", name);
+  error(RtAudioError::WARNING);
+  return FAILURE;
+}
+
+void RtAudio :: cancelStreamCallback(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  if (stream->usingCallback) {
+    stream->usingCallback = false;
+    pthread_cancel(stream->thread);
+    pthread_join(stream->thread, NULL);
+    stream->thread = 0;
+    stream->callback = NULL;
+    stream->userData = NULL;
+  }
+}
+
+void RtAudio :: closeStream(int streamID)
+{
+  // 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 ( streams.find( streamID ) == streams.end() ) {
+    sprintf(message, "RtAudio: invalid stream identifier!");
+    error(RtAudioError::WARNING);
+    return;
+  }
+
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamID];
+
+  if (stream->usingCallback) {
+    pthread_cancel(stream->thread);
+    pthread_join(stream->thread, NULL);
+  }
+
+  if (stream->state == STREAM_RUNNING) {
+    if (stream->mode == PLAYBACK || stream->mode == DUPLEX)
+      snd_pcm_drop(stream->handle[0]);
+    if (stream->mode == RECORD || stream->mode == DUPLEX)
+      snd_pcm_drop(stream->handle[1]);
+  }
+
+  pthread_mutex_destroy(&stream->mutex);
+
+  if (stream->handle[0])
+    snd_pcm_close(stream->handle[0]);
+
+  if (stream->handle[1])
+    snd_pcm_close(stream->handle[1]);
+
+  if (stream->userBuffer)
+    free(stream->userBuffer);
+
+  if (stream->deviceBuffer)
+    free(stream->deviceBuffer);
+
+  free(stream);
+  streams.erase(streamID);
+}
+
+void RtAudio :: startStream(int streamID)
+{
+  // This method calls snd_pcm_prepare if the device isn't already in that state.
+
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  if (stream->state == STREAM_RUNNING)
+    goto unlock;
+
+  int err;
+  snd_pcm_state_t state;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+    state = snd_pcm_state(stream->handle[0]);
+    if (state != SND_PCM_STATE_PREPARED) {
+      err = snd_pcm_prepare(stream->handle[0]);
+      if (err < 0) {
+        sprintf(message, "RtAudio: ALSA error preparing pcm device (%s): %s.",
+                devices[stream->device[0]].name, snd_strerror(err));
+        MUTEX_UNLOCK(&stream->mutex);
+        error(RtAudioError::DRIVER_ERROR);
+      }
+    }
+  }
+
+  if (stream->mode == RECORD || stream->mode == DUPLEX) {
+    state = snd_pcm_state(stream->handle[1]);
+    if (state != SND_PCM_STATE_PREPARED) {
+      err = snd_pcm_prepare(stream->handle[1]);
+      if (err < 0) {
+        sprintf(message, "RtAudio: ALSA error preparing pcm device (%s): %s.",
+                devices[stream->device[1]].name, snd_strerror(err));
+        MUTEX_UNLOCK(&stream->mutex);
+        error(RtAudioError::DRIVER_ERROR);
+      }
+    }
+  }
+  stream->state = STREAM_RUNNING;
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+}
+
+void RtAudio :: stopStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  if (stream->state == STREAM_STOPPED)
+    goto unlock;
+
+  int err;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+    err = snd_pcm_drain(stream->handle[0]);
+    if (err < 0) {
+      sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.",
+              devices[stream->device[0]].name, snd_strerror(err));
+      MUTEX_UNLOCK(&stream->mutex);
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+
+  if (stream->mode == RECORD || stream->mode == DUPLEX) {
+    err = snd_pcm_drain(stream->handle[1]);
+    if (err < 0) {
+      sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.",
+              devices[stream->device[1]].name, snd_strerror(err));
+      MUTEX_UNLOCK(&stream->mutex);
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+  stream->state = STREAM_STOPPED;
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+}
+
+void RtAudio :: abortStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  if (stream->state == STREAM_STOPPED)
+    goto unlock;
+
+  int err;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+    err = snd_pcm_drop(stream->handle[0]);
+    if (err < 0) {
+      sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.",
+              devices[stream->device[0]].name, snd_strerror(err));
+      MUTEX_UNLOCK(&stream->mutex);
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+
+  if (stream->mode == RECORD || stream->mode == DUPLEX) {
+    err = snd_pcm_drop(stream->handle[1]);
+    if (err < 0) {
+      sprintf(message, "RtAudio: ALSA error draining pcm device (%s): %s.",
+              devices[stream->device[1]].name, snd_strerror(err));
+      MUTEX_UNLOCK(&stream->mutex);
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+  stream->state = STREAM_STOPPED;
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+}
+
+int RtAudio :: streamWillBlock(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  int err = 0, frames = 0;
+  if (stream->state == STREAM_STOPPED)
+    goto unlock;
+
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+    err = snd_pcm_avail_update(stream->handle[0]);
+    if (err < 0) {
+      sprintf(message, "RtAudio: ALSA error getting available frames for device (%s): %s.",
+              devices[stream->device[0]].name, snd_strerror(err));
+      MUTEX_UNLOCK(&stream->mutex);
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+
+  frames = err;
+
+  if (stream->mode == RECORD || stream->mode == DUPLEX) {
+    err = snd_pcm_avail_update(stream->handle[1]);
+    if (err < 0) {
+      sprintf(message, "RtAudio: ALSA error getting available frames for device (%s): %s.",
+              devices[stream->device[1]].name, snd_strerror(err));
+      MUTEX_UNLOCK(&stream->mutex);
+      error(RtAudioError::DRIVER_ERROR);
+    }
+    if (frames > err) frames = err;
+  }
+
+  frames = stream->bufferSize - frames;
+  if (frames < 0) frames = 0;
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+  return frames;
+}
+
+void RtAudio :: tickStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  int stopStream = 0;
+  if (stream->state == STREAM_STOPPED) {
+    if (stream->usingCallback) usleep(50000); // sleep 50 milliseconds
+    return;
+  }
+  else if (stream->usingCallback) {
+    stopStream = stream->callback(stream->userBuffer, stream->bufferSize, stream->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;
+  RTAUDIO_FORMAT format;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+
+    // Setup parameters and do buffer conversion if necessary.
+    if (stream->doConvertBuffer[0]) {
+      convertStreamBuffer(stream, PLAYBACK);
+      buffer = stream->deviceBuffer;
+      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 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(stream->handle[0], bufs, stream->bufferSize);
+    }
+    else
+      err = snd_pcm_writei(stream->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(stream->handle[0]);
+        if (state == SND_PCM_STATE_XRUN) {
+          sprintf(message, "RtAudio: ALSA underrun detected.");
+          error(RtAudioError::WARNING);
+          err = snd_pcm_prepare(stream->handle[0]);
+          if (err < 0) {
+            sprintf(message, "RtAudio: ALSA error preparing handle after underrun: %s.",
+                    snd_strerror(err));
+            MUTEX_UNLOCK(&stream->mutex);
+            error(RtAudioError::DRIVER_ERROR);
+          }
+        }
+        else {
+          sprintf(message, "RtAudio: ALSA error, current state is %s.",
+                  snd_pcm_state_name(state));
+          MUTEX_UNLOCK(&stream->mutex);
+          error(RtAudioError::DRIVER_ERROR);
+        }
+        goto unlock;
+      }
+      else {
+        sprintf(message, "RtAudio: ALSA audio write error for device (%s): %s.",
+                devices[stream->device[0]].name, snd_strerror(err));
+        MUTEX_UNLOCK(&stream->mutex);
+        error(RtAudioError::DRIVER_ERROR);
+      }
+    }
+  }
+
+  if (stream->mode == RECORD || 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(stream->handle[1], bufs, stream->bufferSize);
+    }
+    else
+      err = snd_pcm_readi(stream->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(stream->handle[1]);
+        if (state == SND_PCM_STATE_XRUN) {
+          sprintf(message, "RtAudio: ALSA overrun detected.");
+          error(RtAudioError::WARNING);
+          err = snd_pcm_prepare(stream->handle[1]);
+          if (err < 0) {
+            sprintf(message, "RtAudio: ALSA error preparing handle after overrun: %s.",
+                    snd_strerror(err));
+            MUTEX_UNLOCK(&stream->mutex);
+            error(RtAudioError::DRIVER_ERROR);
+          }
+        }
+        else {
+          sprintf(message, "RtAudio: ALSA error, current state is %s.",
+                  snd_pcm_state_name(state));
+          MUTEX_UNLOCK(&stream->mutex);
+          error(RtAudioError::DRIVER_ERROR);
+        }
+        goto unlock;
+      }
+      else {
+        sprintf(message, "RtAudio: ALSA audio read error for device (%s): %s.",
+                devices[stream->device[1]].name, snd_strerror(err));
+        MUTEX_UNLOCK(&stream->mutex);
+        error(RtAudioError::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])
+      convertStreamBuffer(stream, RECORD);
+  }
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+
+  if (stream->usingCallback && stopStream)
+    this->stopStream(streamID);
+}
+
+extern "C" void *callbackHandler(void *ptr)
+{
+  RtAudio *object = thread_info.object;
+  int stream = thread_info.streamID;
+  bool *usingCallback = (bool *) ptr;
+
+  while ( *usingCallback ) {
+    pthread_testcancel();
+    try {
+      object->tickStream(stream);
+    }
+    catch (RtAudioError &exception) {
+      fprintf(stderr, "\nCallback thread error (%s) ... closing thread.\n\n",
+              exception.getMessage());
+      break;
+    }
+  }
+
+  return 0;
+}
+
+//******************** End of __LINUX_ALSA_ *********************//
+
+#elif defined(__LINUX_OSS_)
+
+#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
+
+void RtAudio :: 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 one case 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, "RtAudio: cannot read value of symbolic link %s.", DAC_NAME);
+        error(RtAudioError::SYSTEM_ERROR);
+      }
+    }
+  }
+  else {
+    sprintf(message, "RtAudio: cannot stat %s.", DAC_NAME);
+    error(RtAudioError::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;
+  char names[MAX_DEVICES][16];
+  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, "RtAudio: OSS record device (%s) is busy.", device_name);
+            error(RtAudioError::WARNING);
+            // still count it for now
+          }
+        }
+      }
+      else {
+        sprintf(message, "RtAudio: OSS playback device (%s) is busy.", device_name);
+        error(RtAudioError::WARNING);
+        // still count it for now
+      }
+    }
+
+    if (fd >= 0) close(fd);
+    strncpy(names[nDevices], device_name, 16);
+    nDevices++;
+  }
+
+  if (nDevices == 0) return;
+
+  //  Allocate the DEVICE_CONTROL structures.
+  devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE));
+  if (devices == NULL) {
+    sprintf(message, "RtAudio: memory allocation error!");
+    error(RtAudioError::MEMORY_ERROR);
+  }
+
+  // Write device ascii identifiers to device control structure and then probe capabilities.
+  for (i=0; i<nDevices; i++) {
+    strncpy(devices[i].name, names[i], 16);
+    probeDeviceInfo(&devices[i]);
+  }
+
+  return;
+}
+
+void RtAudio :: probeDeviceInfo(RTAUDIO_DEVICE *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, O_WRONLY | O_NONBLOCK);
+  if (fd == -1) {
+    // Open device failed ... either busy or doesn't exist
+    if (errno == EBUSY || errno == EAGAIN)
+      sprintf(message, "RtAudio: OSS playback device (%s) is busy and cannot be probed.",
+              info->name);
+    else
+      sprintf(message, "RtAudio: OSS playback device (%s) open error.", info->name);
+    error(RtAudioError::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 = channels;
+
+  // 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 = channels;
+  close(fd);
+
+ capture_probe:
+  // Now try for capture
+  fd = open(info->name, 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, "RtAudio: OSS capture device (%s) is busy and cannot be probed.",
+              info->name);
+    else
+      sprintf(message, "RtAudio: OSS capture device (%s) open error.", info->name);
+    error(RtAudioError::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 = channels;
+
+  // 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 = channels;
+  close(fd);
+
+  // 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, 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 = channels;
+
+    // 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 = channels;
+  }
+  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, O_WRONLY | O_NONBLOCK);
+    channels = info->maxOutputChannels;
+  }
+  else {
+    fd = open(info->name, O_RDONLY | O_NONBLOCK);
+    channels = info->maxInputChannels;
+  }
+
+  if (fd == -1) {
+    // We've got some sort of conflict ... abort
+    sprintf(message, "RtAudio: OSS device (%s) won't reopen during probe.",
+            info->name);
+    error(RtAudioError::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, "RtAudio: OSS device (%s) won't revert to previous channel setting.",
+            info->name);
+    error(RtAudioError::WARNING);
+    return;
+  }
+
+  if (ioctl(fd, SNDCTL_DSP_GETFMTS, &mask) == -1) {
+    close(fd);
+    sprintf(message, "RtAudio: OSS device (%s) can't get supported audio formats.",
+            info->name);
+    error(RtAudioError::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, "RtAudio: OSS device (%s) data format not supported by RtAudio.",
+            info->name);
+    error(RtAudioError::WARNING);
+    return;
+  }
+
+  // Set the format
+  i = format;
+  if (ioctl(fd, SNDCTL_DSP_SETFMT, &format) == -1 || format != i) {
+    close(fd);
+    sprintf(message, "RtAudio: OSS device (%s) error setting data format.",
+            info->name);
+    error(RtAudioError::WARNING);
+    return;
+  }
+
+  // Probe the supported sample rates ... first get lower limit
+  int speed = 1;
+  if (ioctl(fd, SNDCTL_DSP_SPEED, &speed) == -1) {
+    // If we get here, we're probably using an ALSA driver with OSS-emulation,
+    // which doesn't conform to the OSS specification.  In this case,
+    // we'll probe our predefined list of sample rates for working values.
+    info->nSampleRates = 0;
+    for (i=0; i<MAX_SAMPLE_RATES; i++) {
+      speed = SAMPLE_RATES[i];
+      if (ioctl(fd, SNDCTL_DSP_SPEED, &speed) != -1) {
+        info->sampleRates[info->nSampleRates] = SAMPLE_RATES[i];
+        info->nSampleRates++;
+      }
+    }
+    if (info->nSampleRates == 0) {
+      close(fd);
+      return;
+    }
+    goto finished;
+  }
+  info->sampleRates[0] = speed;
+
+  // Now get upper limit
+  speed = 1000000;
+  if (ioctl(fd, SNDCTL_DSP_SPEED, &speed) == -1) {
+    close(fd);
+    sprintf(message, "RtAudio: OSS device (%s) error setting sample rate.",
+            info->name);
+    error(RtAudioError::WARNING);
+    return;
+  }
+  info->sampleRates[1] = speed;
+  info->nSampleRates = -1;
+
+ finished: // That's all ... close the device and return
+  close(fd);
+  info->probed = true;
+  return;
+}
+
+bool RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream,
+                                STREAM_MODE mode, int channels, 
+                                int sampleRate, RTAUDIO_FORMAT format,
+                                int *bufferSize, int numberOfBuffers)
+{
+  int buffers, buffer_bytes, device_channels, device_format;
+  int srate, temp, fd;
+
+  const char *name = devices[device].name;
+
+  if (mode == PLAYBACK)
+    fd = open(name, O_WRONLY | O_NONBLOCK);
+  else { // mode == RECORD
+    if (stream->mode == PLAYBACK && stream->device[0] == device) {
+      // We just set the same device for playback ... close and reopen for duplex (OSS only).
+      close(stream->handle[0]);
+      stream->handle[0] = 0;
+      // First check that the number previously set channels is the same.
+      if (stream->nUserChannels[0] != channels) {
+        sprintf(message, "RtAudio: 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, "RtAudio: OSS device (%s) is busy and cannot be opened.",
+              name);
+    else
+      sprintf(message, "RtAudio: OSS device (%s) cannot be opened.", name);
+    goto error;
+  }
+
+  // Now reopen in blocking mode.
+  close(fd);
+  if (mode == PLAYBACK)
+    fd = open(name, O_WRONLY | O_SYNC);
+  else { // mode == RECORD
+    if (stream->mode == PLAYBACK && stream->device[0] == device)
+      fd = open(name, O_RDWR | O_SYNC);
+    else
+      fd = open(name, O_RDONLY | O_SYNC);
+  }
+
+  if (fd == -1) {
+    sprintf(message, "RtAudio: OSS 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, "RtAudio: OSS 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, "RtAudio: OSS 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 == PLAYBACK) {
+    if (channels < devices[device].minOutputChannels)
+      device_channels = devices[device].minOutputChannels;
+  }
+  else { // mode == RECORD
+    if (stream->mode == PLAYBACK && 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, "RtAudio: OSS 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, "RtAudio: OSS 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, "RtAudio: OSS 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, "RtAudio: OSS 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, "RtAudio: OSS 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, "RtAudio: OSS 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 == RECORD && stream->mode == PLAYBACK &&
+      stream->device[0] == device) {
+    // We're doing duplex setup here.
+    stream->deviceFormat[0] = stream->deviceFormat[1];
+    stream->nDeviceChannels[0] = device_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;
+
+  // 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, "RtAudio: OSS error allocating user buffer memory (%s).",
+              name);
+      goto error;
+    }
+  }
+
+  if ( stream->doConvertBuffer[mode] ) {
+
+    long buffer_bytes;
+    bool makeBuffer = true;
+    if ( mode == PLAYBACK )
+      buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
+    else { // mode == RECORD
+      buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]);
+      if ( stream->mode == PLAYBACK ) {
+        long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
+        if ( buffer_bytes > bytes_out )
+          buffer_bytes = (buffer_bytes > bytes_out) ? buffer_bytes : bytes_out;
+        else
+          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);
+        free(stream->userBuffer);
+        sprintf(message, "RtAudio: OSS error allocating device buffer memory (%s).",
+                name);
+        goto error;
+      }
+    }
+  }
+
+  stream->device[mode] = device;
+  stream->handle[mode] = fd;
+  stream->state = STREAM_STOPPED;
+  if ( stream->mode == PLAYBACK && mode == RECORD ) {
+    stream->mode = DUPLEX;
+    if (stream->device[0] == device)
+      stream->handle[0] = fd;
+  }
+  else
+    stream->mode = mode;
+
+  return SUCCESS;
+
+ error:
+  if (stream->handle[0]) {
+    close(stream->handle[0]);
+    stream->handle[0] = 0;
+  }
+  error(RtAudioError::WARNING);
+  return FAILURE;
+}
+
+void RtAudio :: cancelStreamCallback(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  if (stream->usingCallback) {
+    stream->usingCallback = false;
+    pthread_cancel(stream->thread);
+    pthread_join(stream->thread, NULL);
+    stream->thread = 0;
+    stream->callback = NULL;
+    stream->userData = NULL;
+  }
+}
+
+void RtAudio :: closeStream(int streamID)
+{
+  // 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 ( streams.find( streamID ) == streams.end() ) {
+    sprintf(message, "RtAudio: invalid stream identifier!");
+    error(RtAudioError::WARNING);
+    return;
+  }
+
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamID];
+
+  if (stream->usingCallback) {
+    pthread_cancel(stream->thread);
+    pthread_join(stream->thread, NULL);
+  }
+
+  if (stream->state == STREAM_RUNNING) {
+    if (stream->mode == PLAYBACK || stream->mode == DUPLEX)
+      ioctl(stream->handle[0], SNDCTL_DSP_RESET, 0);
+    if (stream->mode == RECORD || stream->mode == DUPLEX)
+      ioctl(stream->handle[1], SNDCTL_DSP_RESET, 0);
+  }
+
+  pthread_mutex_destroy(&stream->mutex);
+
+  if (stream->handle[0])
+    close(stream->handle[0]);
+
+  if (stream->handle[1])
+    close(stream->handle[1]);
+
+  if (stream->userBuffer)
+    free(stream->userBuffer);
+
+  if (stream->deviceBuffer)
+    free(stream->deviceBuffer);
+
+  free(stream);
+  streams.erase(streamID);
+}
+
+void RtAudio :: startStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  stream->state = STREAM_RUNNING;
+
+  // No need to do anything else here ... OSS automatically starts when fed samples.
+}
+
+void RtAudio :: stopStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  if (stream->state == STREAM_STOPPED)
+    goto unlock;
+
+  int err;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+    err = ioctl(stream->handle[0], SNDCTL_DSP_SYNC, 0);
+    if (err < -1) {
+      sprintf(message, "RtAudio: OSS error stopping device (%s).",
+              devices[stream->device[0]].name);
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+  else {
+    err = ioctl(stream->handle[1], SNDCTL_DSP_SYNC, 0);
+    if (err < -1) {
+      sprintf(message, "RtAudio: OSS error stopping device (%s).",
+              devices[stream->device[1]].name);
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+  stream->state = STREAM_STOPPED;
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+}
+
+void RtAudio :: abortStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  if (stream->state == STREAM_STOPPED)
+    goto unlock;
+
+  int err;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+    err = ioctl(stream->handle[0], SNDCTL_DSP_RESET, 0);
+    if (err < -1) {
+      sprintf(message, "RtAudio: OSS error aborting device (%s).",
+              devices[stream->device[0]].name);
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+  else {
+    err = ioctl(stream->handle[1], SNDCTL_DSP_RESET, 0);
+    if (err < -1) {
+      sprintf(message, "RtAudio: OSS error aborting device (%s).",
+              devices[stream->device[1]].name);
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+  stream->state = STREAM_STOPPED;
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+}
+
+int RtAudio :: streamWillBlock(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  int bytes, channels = 0, frames = 0;
+  if (stream->state == STREAM_STOPPED)
+    goto unlock;
+
+  audio_buf_info info;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+    ioctl(stream->handle[0], SNDCTL_DSP_GETOSPACE, &info);
+    bytes = info.bytes;
+    channels = stream->nDeviceChannels[0];
+  }
+
+  if (stream->mode == RECORD || stream->mode == DUPLEX) {
+    ioctl(stream->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;
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+  return frames;
+}
+
+void RtAudio :: tickStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  int stopStream = 0;
+  if (stream->state == STREAM_STOPPED) {
+    if (stream->usingCallback) usleep(50000); // sleep 50 milliseconds
+    return;
+  }
+  else if (stream->usingCallback) {
+    stopStream = stream->callback(stream->userBuffer, stream->bufferSize, stream->userData);
+  }
+
+  MUTEX_LOCK(&stream->mutex);
+
+  // The state might change while waiting on a mutex.
+  if (stream->state == STREAM_STOPPED)
+    goto unlock;
+
+  int result;
+  char *buffer;
+  int samples;
+  RTAUDIO_FORMAT format;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+
+    // Setup parameters and do buffer conversion if necessary.
+    if (stream->doConvertBuffer[0]) {
+      convertStreamBuffer(stream, PLAYBACK);
+      buffer = stream->deviceBuffer;
+      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(stream->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, "RtAudio: OSS audio write error for device (%s).",
+              devices[stream->device[0]].name);
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+
+  if (stream->mode == RECORD || 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(stream->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, "RtAudio: OSS audio read error for device (%s).",
+              devices[stream->device[1]].name);
+      error(RtAudioError::DRIVER_ERROR);
+    }
+
+    // Do byte swapping if necessary.
+    if (stream->doByteSwap[1])
+      byteSwapBuffer(buffer, samples, format);
+
+    // Do buffer conversion if necessary.
+    if (stream->doConvertBuffer[1])
+      convertStreamBuffer(stream, RECORD);
+  }
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+
+  if (stream->usingCallback && stopStream)
+    this->stopStream(streamID);
+}
+
+extern "C" void *callbackHandler(void *ptr)
+{
+  RtAudio *object = thread_info.object;
+  int stream = thread_info.streamID;
+  bool *usingCallback = (bool *) ptr;
+
+  while ( *usingCallback ) {
+    pthread_testcancel();
+    try {
+      object->tickStream(stream);
+    }
+    catch (RtAudioError &exception) {
+      fprintf(stderr, "\nCallback thread error (%s) ... closing thread.\n\n",
+              exception.getMessage());
+      break;
+    }
+  }
+
+  return 0;
+}
+
+//******************** End of __LINUX_OSS_ *********************//
+
+#elif defined(__WINDOWS_DS_) // Windows DirectSound API
+
+#include <dsound.h>
+
+// Declarations for utility functions, callbacks, and structures
+// specific to the DirectSound implementation.
+static bool CALLBACK deviceCountCallback(LPGUID lpguid,
+                                         LPCSTR lpcstrDescription,
+                                         LPCSTR lpcstrModule,
+                                         LPVOID lpContext);
+
+static bool CALLBACK deviceInfoCallback(LPGUID lpguid,
+                                        LPCSTR lpcstrDescription,
+                                        LPCSTR lpcstrModule,
+                                        LPVOID lpContext);
+
+static char* getErrorString(int code);
+
+struct enum_info {
+  char name[64];
+  LPGUID id;
+  bool isInput;
+  bool isValid;
+};
+
+// RtAudio methods for DirectSound implementation.
+void RtAudio :: initialize(void)
+{
+  int i, ins = 0, outs = 0, count = 0;
+  int index = 0;
+  HRESULT result;
+  nDevices = 0;
+
+  // Count DirectSound devices.
+  result = DirectSoundEnumerate((LPDSENUMCALLBACK)deviceCountCallback, &outs);
+  if ( FAILED(result) ) {
+    sprintf(message, "RtAudio: Unable to enumerate through sound playback devices: %s.",
+            getErrorString(result));
+    error(RtAudioError::DRIVER_ERROR);
+  }
+
+  // Count DirectSoundCapture devices.
+  result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceCountCallback, &ins);
+  if ( FAILED(result) ) {
+    sprintf(message, "RtAudio: Unable to enumerate through sound capture devices: %s.",
+            getErrorString(result));
+    error(RtAudioError::DRIVER_ERROR);
+  }
+
+  count = ins + outs;
+  if (count == 0) return;
+
+  std::vector<enum_info> info(count);
+  for (i=0; i<count; i++) {
+    info[i].name[0] = '\0';
+    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, "RtAudio: Unable to enumerate through sound playback devices: %s.",
+            getErrorString(result));
+    error(RtAudioError::DRIVER_ERROR);
+  }
+
+  // Get capture device info and check capabilities.
+  result = DirectSoundCaptureEnumerate((LPDSENUMCALLBACK)deviceInfoCallback, &info[0]);
+  if ( FAILED(result) ) {
+    sprintf(message, "RtAudio: Unable to enumerate through sound capture devices: %s.",
+            getErrorString(result));
+    error(RtAudioError::DRIVER_ERROR);
+  }
+
+  // Parse the devices and check validity.  Devices are considered
+  // invalid if they cannot be opened, they report no supported data
+  // formats, or they report < 1 supported channels.
+  for (i=0; i<count; i++) {
+    if (info[i].isValid && info[i].id == NULL ) // default device
+      nDevices++;
+  }
+
+  // We group the default input and output devices together (as one
+  // device) .
+  if (nDevices > 0) {
+    nDevices = 1;
+    index = 1;
+  }
+
+  // Non-default devices are listed separately.
+  for (i=0; i<count; i++) {
+    if (info[i].isValid && info[i].id != NULL )
+      nDevices++;
+  }
+
+  if (nDevices == 0) return;
+
+  //  Allocate the RTAUDIO_DEVICE structures.
+  devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE));
+  if (devices == NULL) {
+    sprintf(message, "RtAudio: memory allocation error!");
+    error(RtAudioError::MEMORY_ERROR);
+  }
+
+  // Initialize the GUIDs to NULL for later validation.
+  for (i=0; i<nDevices; i++) {
+    devices[i].id[0] = NULL;
+    devices[i].id[1] = NULL;
+  }
+
+  // Rename the default device(s).
+  if (index)
+    strcpy(devices[0].name, "Default Input/Output Devices");
+
+  // Copy the names and GUIDs to our devices structures.
+  for (i=0; i<count; i++) {
+    if (info[i].isValid && info[i].id != NULL ) {
+      strncpy(devices[index].name, info[i].name, 64);
+      if (info[i].isInput)
+        devices[index].id[1] = info[i].id;
+      else
+        devices[index].id[0] = info[i].id;
+      index++;
+    }
+  }
+
+  for (i=0;i<nDevices; i++)
+    probeDeviceInfo(&devices[i]);
+
+  return;
+}
+
+void RtAudio :: probeDeviceInfo(RTAUDIO_DEVICE *info)
+{
+  HRESULT result;
+
+  // Get the device index so that we can check the device handle.
+  int index;
+  for (index=0; index<nDevices; index++)
+    if ( info == &devices[index] ) break;
+
+  if ( index >= nDevices ) {
+    sprintf(message, "RtAudio: device (%s) indexing error in DirectSound probeDeviceInfo().",
+            info->name);
+    error(RtAudioError::WARNING);
+    return;
+  }
+
+  // Do capture probe first.  If this is not the default device (index
+  // = 0) _and_ GUID = NULL, then the capture handle is invalid.
+  if ( index != 0 && info->id[1] == NULL )
+    goto playback_probe;
+
+  LPDIRECTSOUNDCAPTURE  input;
+  result = DirectSoundCaptureCreate( info->id[0], &input, NULL );
+  if ( FAILED(result) ) {
+    sprintf(message, "RtAudio: Could not create DirectSound capture object (%s): %s.",
+            info->name, getErrorString(result));
+    error(RtAudioError::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, "RtAudio: Could not get DirectSound capture capabilities (%s): %s.",
+            info->name, getErrorString(result));
+    error(RtAudioError::WARNING);
+    goto playback_probe;
+  }
+
+  // Get input channel information.
+  info->minInputChannels = 1;
+  info->maxInputChannels = in_caps.dwChannels;
+
+  // Get sample rate and format information.
+  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[info->nSampleRates++] = 11025;
+      if( in_caps.dwFormats & WAVE_FORMAT_2S16 ) info->sampleRates[info->nSampleRates++] = 22050;
+      if( in_caps.dwFormats & WAVE_FORMAT_4S16 ) info->sampleRates[info->nSampleRates++] = 44100;
+    }
+    else if ( info->nativeFormats & RTAUDIO_SINT8 ) {
+      if( in_caps.dwFormats & WAVE_FORMAT_1S08 ) info->sampleRates[info->nSampleRates++] = 11025;
+      if( in_caps.dwFormats & WAVE_FORMAT_2S08 ) info->sampleRates[info->nSampleRates++] = 22050;
+      if( in_caps.dwFormats & WAVE_FORMAT_4S08 ) info->sampleRates[info->nSampleRates++] = 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[info->nSampleRates++] = 11025;
+      if( in_caps.dwFormats & WAVE_FORMAT_2M16 ) info->sampleRates[info->nSampleRates++] = 22050;
+      if( in_caps.dwFormats & WAVE_FORMAT_4M16 ) info->sampleRates[info->nSampleRates++] = 44100;
+    }
+    else if ( info->nativeFormats & RTAUDIO_SINT8 ) {
+      if( in_caps.dwFormats & WAVE_FORMAT_1M08 ) info->sampleRates[info->nSampleRates++] = 11025;
+      if( in_caps.dwFormats & WAVE_FORMAT_2M08 ) info->sampleRates[info->nSampleRates++] = 22050;
+      if( in_caps.dwFormats & WAVE_FORMAT_4M08 ) info->sampleRates[info->nSampleRates++] = 44100;
+    }
+  }
+  else info->minInputChannels = 0; // technically, this would be an error
+
+  input->Release();
+
+ playback_probe:
+  LPDIRECTSOUND  output;
+  DSCAPS out_caps;
+
+  // Now do playback probe.  If this is not the default device (index
+  // = 0) _and_ GUID = NULL, then the playback handle is invalid.
+  if ( index != 0 && info->id[0] == NULL )
+    goto check_parameters;
+
+  result = DirectSoundCreate( info->id[0], &output, NULL );
+  if ( FAILED(result) ) {
+    sprintf(message, "RtAudio: Could not create DirectSound playback object (%s): %s.",
+            info->name, getErrorString(result));
+    error(RtAudioError::WARNING);
+    goto check_parameters;
+  }
+
+  out_caps.dwSize = sizeof(out_caps);
+  result = output->GetCaps( &out_caps );
+  if ( FAILED(result) ) {
+    output->Release();
+    sprintf(message, "RtAudio: Could not get DirectSound playback capabilities (%s): %s.",
+            info->name, getErrorString(result));
+    error(RtAudioError::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->nSampleRates == 0 ) {
+    info->sampleRates[0] = (int) out_caps.dwMinSecondarySampleRate;
+    info->sampleRates[1] = (int) out_caps.dwMaxSecondarySampleRate;
+    if ( out_caps.dwFlags & DSCAPS_CONTINUOUSRATE )
+      info->nSampleRates = -1;
+    else if ( out_caps.dwMinSecondarySampleRate == out_caps.dwMaxSecondarySampleRate ) {
+      if ( out_caps.dwMinSecondarySampleRate == 0 ) {
+        // This is a bogus driver report ... fake the range and cross
+        // your fingers.
+        info->sampleRates[0] = 11025;
+                               info->sampleRates[1] = 48000;
+        info->nSampleRates = -1; /* continuous range */
+        sprintf(message, "RtAudio: bogus sample rates reported by DirectSound driver ... using defaults (%s).",
+                info->name);
+        error(RtAudioError::WARNING);
+      }
+      else {
+        info->nSampleRates = 1;
+                       }
+    }
+    else if ( (out_caps.dwMinSecondarySampleRate < 1000.0) &&
+              (out_caps.dwMaxSecondarySampleRate > 50000.0) ) {
+      // This is a bogus driver report ... support for only two
+      // distant rates.  We'll assume this is a range.
+      info->nSampleRates = -1;
+      sprintf(message, "RtAudio: bogus sample rates reported by DirectSound driver ... using range (%s).",
+              info->name);
+      error(RtAudioError::WARNING);
+    }
+    else info->nSampleRates = 2;
+  }
+  else {
+    // Check input rates against output rate range
+    for ( int i=info->nSampleRates-1; i>=0; i-- ) {
+      if ( info->sampleRates[i] <= out_caps.dwMaxSecondarySampleRate )
+        break;
+      info->nSampleRates--;
+    }
+    while ( info->sampleRates[0] < out_caps.dwMinSecondarySampleRate ) {
+      info->nSampleRates--;
+      for ( int i=0; i<info->nSampleRates; i++)
+        info->sampleRates[i] = info->sampleRates[i+1];
+      if ( info->nSampleRates <= 0 ) break;
+    }
+  }
+
+  // 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 )
+    return;
+  if ( info->nSampleRates == 0 || info->nativeFormats == 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 RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream,
+                                STREAM_MODE mode, int channels, 
+                                int sampleRate, RTAUDIO_FORMAT 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, "RtAudio: no reported data formats for DirectSound device (%s).",
+            devices[device].name);
+    error(RtAudioError::WARNING);
+    return FAILURE;
+  }
+
+  waveFormat.nBlockAlign = waveFormat.nChannels * waveFormat.wBitsPerSample / 8;
+  waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
+
+  if ( mode == PLAYBACK ) {
+
+    LPGUID id = devices[device].id[0];
+    LPDIRECTSOUND  object;
+    LPDIRECTSOUNDBUFFER buffer;
+    DSBUFFERDESC bufferDescription;
+    
+    result = DirectSoundCreate( id, &object, NULL );
+    if ( FAILED(result) ) {
+      sprintf(message, "RtAudio: Could not create DirectSound playback object (%s): %s.",
+              devices[device].name, getErrorString(result));
+      error(RtAudioError::WARNING);
+      return FAILURE;
+    }
+
+    // Set cooperative level to DSSCL_EXCLUSIVE
+    result = object->SetCooperativeLevel(hWnd, DSSCL_EXCLUSIVE);
+    if ( FAILED(result) ) {
+      object->Release();
+      sprintf(message, "RtAudio: Unable to set DirectSound cooperative level (%s): %s.",
+              devices[device].name, getErrorString(result));
+      error(RtAudioError::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.
+    // 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, "RtAudio: Unable to access DS primary buffer (%s): %s.",
+              devices[device].name, getErrorString(result));
+      error(RtAudioError::WARNING);
+      return FAILURE;
+    }
+
+    // Set the primary DS buffer sound format.
+    result = buffer->SetFormat(&waveFormat);
+    if ( FAILED(result) ) {
+      object->Release();
+      sprintf(message, "RtAudio: Unable to set DS primary buffer format (%s): %s.",
+              devices[device].name, getErrorString(result));
+      error(RtAudioError::WARNING);
+      return FAILURE;
+    }
+
+    // Setup the secondary DS buffer description.
+    buffer_size = channels * *bufferSize * nBuffers * waveFormat.wBitsPerSample / 8;
+    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, "RtAudio: Unable to create secondary DS buffer (%s): %s.",
+                devices[device].name, getErrorString(result));
+        error(RtAudioError::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();
+      sprintf(message, "RtAudio: Unable to lock DS buffer (%s): %s.",
+              devices[device].name, getErrorString(result));
+      error(RtAudioError::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();
+      sprintf(message, "RtAudio: Unable to unlock DS buffer(%s): %s.",
+              devices[device].name, getErrorString(result));
+      error(RtAudioError::WARNING);
+      return FAILURE;
+    }
+
+    stream->handle[0].object = (void *) object;
+    stream->handle[0].buffer = (void *) buffer;
+    stream->nDeviceChannels[0] = channels;
+  }
+
+  if ( mode == RECORD ) {
+
+    LPGUID id = devices[device].id[1];
+    LPDIRECTSOUNDCAPTURE  object;
+    LPDIRECTSOUNDCAPTUREBUFFER buffer;
+    DSCBUFFERDESC bufferDescription;
+
+    result = DirectSoundCaptureCreate( id, &object, NULL );
+    if ( FAILED(result) ) {
+      sprintf(message, "RtAudio: Could not create DirectSound capture object (%s): %s.",
+              devices[device].name, getErrorString(result));
+      error(RtAudioError::WARNING);
+      return FAILURE;
+    }
+
+    // Setup the secondary DS buffer description.
+    buffer_size = channels * *bufferSize * nBuffers * waveFormat.wBitsPerSample / 8;
+    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, "RtAudio: Unable to create DS capture buffer (%s): %s.",
+              devices[device].name, getErrorString(result));
+      error(RtAudioError::WARNING);
+      return FAILURE;
+    }
+
+    // Lock the capture buffer
+    result = buffer->Lock(0, buffer_size, &audioPtr, &dataLen, NULL, NULL, 0);
+    if ( FAILED(result) ) {
+      object->Release();
+      sprintf(message, "RtAudio: Unable to lock DS capture buffer (%s): %s.",
+              devices[device].name, getErrorString(result));
+      error(RtAudioError::WARNING);
+      return FAILURE;
+    }
+
+    // Zero the buffer
+    ZeroMemory(audioPtr, dataLen);
+
+    // Unlock the buffer
+    result = buffer->Unlock(audioPtr, dataLen, NULL, 0);
+    if ( FAILED(result) ) {
+      object->Release();
+      sprintf(message, "RtAudio: Unable to unlock DS capture buffer (%s): %s.",
+              devices[device].name, getErrorString(result));
+      error(RtAudioError::WARNING);
+      return FAILURE;
+    }
+
+    stream->handle[1].object = (void *) object;
+    stream->handle[1].buffer = (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;
+  *bufferSize = buffer_size / (channels * nBuffers * waveFormat.wBitsPerSample / 8);
+  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)
+      goto memory_error;
+  }
+
+  if ( stream->doConvertBuffer[mode] ) {
+
+    long buffer_bytes;
+    bool makeBuffer = true;
+    if ( mode == PLAYBACK )
+      buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
+    else { // mode == RECORD
+      buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]);
+      if ( stream->mode == PLAYBACK ) {
+        long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
+        if ( buffer_bytes > bytes_out )
+          buffer_bytes = (buffer_bytes > bytes_out) ? buffer_bytes : bytes_out;
+        else
+          makeBuffer = false;
+      }
+    }
+
+    if ( makeBuffer ) {
+      buffer_bytes *= *bufferSize;
+      if (stream->deviceBuffer) free(stream->deviceBuffer);
+      stream->deviceBuffer = (char *) calloc(buffer_bytes, 1);
+      if (stream->deviceBuffer == NULL)
+        goto memory_error;
+    }
+  }
+
+  stream->device[mode] = device;
+  stream->state = STREAM_STOPPED;
+  if ( stream->mode == PLAYBACK && mode == RECORD )
+    // We had already set up an output stream.
+    stream->mode = DUPLEX;
+  else
+    stream->mode = mode;
+  stream->nBuffers = nBuffers;
+  stream->sampleRate = sampleRate;
+
+  return SUCCESS;
+
+ memory_error:
+  if (stream->handle[0].object) {
+    LPDIRECTSOUND object = (LPDIRECTSOUND) stream->handle[0].object;
+    LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
+    if (buffer) {
+      buffer->Release();
+      stream->handle[0].buffer = NULL;
+    }
+    object->Release();
+    stream->handle[0].object = NULL;
+  }
+  if (stream->handle[1].object) {
+    LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) stream->handle[1].object;
+    LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer;
+    if (buffer) {
+      buffer->Release();
+      stream->handle[1].buffer = NULL;
+    }
+    object->Release();
+    stream->handle[1].object = NULL;
+  }
+  if (stream->userBuffer) {
+    free(stream->userBuffer);
+    stream->userBuffer = 0;
+  }
+  sprintf(message, "RtAudio: error allocating buffer memory (%s).",
+          devices[device].name);
+  error(RtAudioError::WARNING);
+  return FAILURE;
+}
+
+void RtAudio :: cancelStreamCallback(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  if (stream->usingCallback) {
+    stream->usingCallback = false;
+    WaitForSingleObject( (HANDLE)stream->thread, INFINITE );
+    CloseHandle( (HANDLE)stream->thread );
+    stream->thread = 0;
+    stream->callback = NULL;
+    stream->userData = NULL;
+  }
+}
+
+void RtAudio :: closeStream(int streamID)
+{
+  // 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 ( streams.find( streamID ) == streams.end() ) {
+    sprintf(message, "RtAudio: invalid stream identifier!");
+    error(RtAudioError::WARNING);
+    return;
+  }
+
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamID];
+
+  if (stream->usingCallback) {
+    stream->usingCallback = false;
+    WaitForSingleObject( (HANDLE)stream->thread, INFINITE );
+    CloseHandle( (HANDLE)stream->thread );
+  }
+
+  DeleteCriticalSection(&stream->mutex);
+
+  if (stream->handle[0].object) {
+    LPDIRECTSOUND object = (LPDIRECTSOUND) stream->handle[0].object;
+    LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
+    if (buffer) {
+      buffer->Stop();
+      buffer->Release();
+    }
+    object->Release();
+  }
+
+  if (stream->handle[1].object) {
+    LPDIRECTSOUNDCAPTURE object = (LPDIRECTSOUNDCAPTURE) stream->handle[1].object;
+    LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer;
+    if (buffer) {
+      buffer->Stop();
+      buffer->Release();
+    }
+    object->Release();
+  }
+
+  if (stream->userBuffer)
+    free(stream->userBuffer);
+
+  if (stream->deviceBuffer)
+    free(stream->deviceBuffer);
+
+  free(stream);
+  streams.erase(streamID);
+}
+
+void RtAudio :: startStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  if (stream->state == STREAM_RUNNING)
+    goto unlock;
+
+  HRESULT result;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+    LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
+    result = buffer->Play(0, 0, DSBPLAY_LOOPING );
+    if ( FAILED(result) ) {
+      sprintf(message, "RtAudio: Unable to start DS buffer (%s): %s.",
+              devices[stream->device[0]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+
+  if (stream->mode == RECORD || stream->mode == DUPLEX) {
+    LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer;
+    result = buffer->Start(DSCBSTART_LOOPING );
+    if ( FAILED(result) ) {
+      sprintf(message, "RtAudio: Unable to start DS capture buffer (%s): %s.",
+              devices[stream->device[1]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+  stream->state = STREAM_RUNNING;
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+}
+
+void RtAudio :: stopStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  if (stream->state == STREAM_STOPPED) {
+    MUTEX_UNLOCK(&stream->mutex);
+    return;
+  }
+
+  // There is no specific DirectSound API call to "drain" a buffer
+  // before stopping.  We can hack this for playback by writing zeroes
+  // for another bufferSize * nBuffers frames.  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;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+
+    DWORD currentPos, safePos;
+    long buffer_bytes = stream->bufferSize * stream->nDeviceChannels[0];
+    buffer_bytes *= formatBytes(stream->deviceFormat[0]);
+
+    LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
+    UINT nextWritePos = stream->handle[0].bufferPointer;
+    dsBufferSize = buffer_bytes * stream->nBuffers;
+
+    // Write zeroes for nBuffer counts.
+    for (int i=0; i<stream->nBuffers; i++) {
+
+      // Find out where the read and "safe write" pointers are.
+      result = dsBuffer->GetCurrentPosition(&currentPos, &safePos);
+      if ( FAILED(result) ) {
+        sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.",
+                devices[stream->device[0]].name, getErrorString(result));
+        error(RtAudioError::DRIVER_ERROR);
+      }
+
+      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 ) {
+        float millis = (endWrite - currentPos) * 900.0;
+        millis /= ( formatBytes(stream->deviceFormat[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, "RtAudio: Unable to get current DS position (%s): %s.",
+                  devices[stream->device[0]].name, getErrorString(result));
+          error(RtAudioError::DRIVER_ERROR);
+        }
+        if ( currentPos < 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, "RtAudio: Unable to lock DS buffer during playback (%s): %s.",
+                devices[stream->device[0]].name, getErrorString(result));
+        error(RtAudioError::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, "RtAudio: Unable to unlock DS buffer during playback (%s): %s.",
+                devices[stream->device[0]].name, getErrorString(result));
+        error(RtAudioError::DRIVER_ERROR);
+      }
+      nextWritePos = (nextWritePos + bufferSize1 + bufferSize2) % dsBufferSize;
+      stream->handle[0].bufferPointer = nextWritePos;
+    }
+
+    // If we play again, start at the beginning of the buffer.
+    stream->handle[0].bufferPointer = 0;
+  }
+
+  if (stream->mode == RECORD || stream->mode == DUPLEX) {
+    LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer;
+    buffer1 = NULL;
+    bufferSize1 = 0;
+
+    result = buffer->Stop();
+    if ( FAILED(result) ) {
+      sprintf(message, "RtAudio: Unable to stop DS capture buffer (%s): %s",
+              devices[stream->device[1]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+
+    dsBufferSize = stream->bufferSize * stream->nDeviceChannels[1];
+    dsBufferSize *= formatBytes(stream->deviceFormat[1]) * stream->nBuffers;
+
+    // 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, "RtAudio: Unable to lock DS capture buffer (%s): %s.",
+              devices[stream->device[1]].name, getErrorString(result));
+      error(RtAudioError::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, "RtAudio: Unable to unlock DS capture buffer (%s): %s.",
+              devices[stream->device[1]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+
+    // If we start recording again, we must begin at beginning of buffer.
+    stream->handle[1].bufferPointer = 0;
+  }
+  stream->state = STREAM_STOPPED;
+
+  MUTEX_UNLOCK(&stream->mutex);
+}
+
+void RtAudio :: abortStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  if (stream->state == STREAM_STOPPED)
+    goto unlock;
+
+  HRESULT result;
+  long dsBufferSize;
+  LPVOID audioPtr;
+  DWORD dataLen;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+    LPDIRECTSOUNDBUFFER buffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
+    result = buffer->Stop();
+    if ( FAILED(result) ) {
+      sprintf(message, "RtAudio: Unable to stop DS buffer (%s): %s",
+              devices[stream->device[0]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+
+    dsBufferSize = stream->bufferSize * stream->nDeviceChannels[0];
+    dsBufferSize *= formatBytes(stream->deviceFormat[0]) * stream->nBuffers;
+
+    // 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, "RtAudio: Unable to lock DS buffer (%s): %s.",
+              devices[stream->device[0]].name, getErrorString(result));
+      error(RtAudioError::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, "RtAudio: Unable to unlock DS buffer (%s): %s.",
+              devices[stream->device[0]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+
+    // If we start playing again, we must begin at beginning of buffer.
+    stream->handle[0].bufferPointer = 0;
+  }
+
+  if (stream->mode == RECORD || stream->mode == DUPLEX) {
+    LPDIRECTSOUNDCAPTUREBUFFER buffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer;
+    audioPtr = NULL;
+    dataLen = 0;
+
+    result = buffer->Stop();
+    if ( FAILED(result) ) {
+      sprintf(message, "RtAudio: Unable to stop DS capture buffer (%s): %s",
+              devices[stream->device[1]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+
+    dsBufferSize = stream->bufferSize * stream->nDeviceChannels[1];
+    dsBufferSize *= formatBytes(stream->deviceFormat[1]) * stream->nBuffers;
+
+    // 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, "RtAudio: Unable to lock DS capture buffer (%s): %s.",
+              devices[stream->device[1]].name, getErrorString(result));
+      error(RtAudioError::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, "RtAudio: Unable to unlock DS capture buffer (%s): %s.",
+              devices[stream->device[1]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+
+    // If we start recording again, we must begin at beginning of buffer.
+    stream->handle[1].bufferPointer = 0;
+  }
+  stream->state = STREAM_STOPPED;
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+}
+
+int RtAudio :: streamWillBlock(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  int frames = 0;
+  int channels = 1;
+  if (stream->state == STREAM_STOPPED)
+    goto unlock;
+
+  HRESULT result;
+  DWORD currentPos, safePos;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+
+    LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
+    UINT nextWritePos = stream->handle[0].bufferPointer;
+    channels = stream->nDeviceChannels[0];
+    DWORD dsBufferSize = stream->bufferSize * channels;
+    dsBufferSize *= formatBytes(stream->deviceFormat[0]) * stream->nBuffers;
+
+    // Find out where the read and "safe write" pointers are.
+    result = dsBuffer->GetCurrentPosition(&currentPos, &safePos);
+    if ( FAILED(result) ) {
+      sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.",
+              devices[stream->device[0]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+
+    if ( currentPos < nextWritePos ) currentPos += dsBufferSize; // unwrap offset
+    frames = currentPos - nextWritePos;
+    frames /= channels * formatBytes(stream->deviceFormat[0]);
+  }
+
+  if (stream->mode == RECORD || stream->mode == DUPLEX) {
+
+    LPDIRECTSOUNDCAPTUREBUFFER dsBuffer = (LPDIRECTSOUNDCAPTUREBUFFER) stream->handle[1].buffer;
+    UINT nextReadPos = stream->handle[1].bufferPointer;
+    channels = stream->nDeviceChannels[1];
+    DWORD dsBufferSize = stream->bufferSize * channels;
+    dsBufferSize *= formatBytes(stream->deviceFormat[1]) * stream->nBuffers;
+
+    // Find out where the write and "safe read" pointers are.
+    result = dsBuffer->GetCurrentPosition(&currentPos, &safePos);
+    if ( FAILED(result) ) {
+      sprintf(message, "RtAudio: Unable to get current DS capture position (%s): %s.",
+              devices[stream->device[1]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+
+    if ( safePos < nextReadPos ) safePos += dsBufferSize; // unwrap offset
+
+    if (stream->mode == DUPLEX ) {
+      // Take largest value of the two.
+      int temp = safePos - nextReadPos;
+      temp /= channels * formatBytes(stream->deviceFormat[1]);
+      frames = ( temp > frames ) ? temp : frames;
+    }
+    else {
+      frames = safePos - nextReadPos;
+      frames /= channels * formatBytes(stream->deviceFormat[1]);
+    }
+  }
+
+  frames = stream->bufferSize - frames;
+  if (frames < 0) frames = 0;
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+  return frames;
+}
+
+void RtAudio :: tickStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  int stopStream = 0;
+  if (stream->state == STREAM_STOPPED) {
+    if (stream->usingCallback) Sleep(50); // sleep 50 milliseconds
+    return;
+  }
+  else if (stream->usingCallback) {
+    stopStream = stream->callback(stream->userBuffer, stream->bufferSize, stream->userData);    
+  }
+
+  MUTEX_LOCK(&stream->mutex);
+
+  // The state might change while waiting on a mutex.
+  if (stream->state == STREAM_STOPPED)
+    goto unlock;
+
+  HRESULT result;
+  DWORD currentPos, safePos;
+  LPVOID buffer1, buffer2;
+  DWORD bufferSize1, bufferSize2;
+  char *buffer;
+  long buffer_bytes;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+
+    // Setup parameters and do buffer conversion if necessary.
+    if (stream->doConvertBuffer[0]) {
+      convertStreamBuffer(stream, PLAYBACK);
+      buffer = stream->deviceBuffer;
+      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.
+
+    LPDIRECTSOUNDBUFFER dsBuffer = (LPDIRECTSOUNDBUFFER) stream->handle[0].buffer;
+    UINT nextWritePos = stream->handle[0].bufferPointer;
+    DWORD dsBufferSize = buffer_bytes * stream->nBuffers;
+
+    // Find out where the read and "safe write" pointers are.
+    result = dsBuffer->GetCurrentPosition(&currentPos, &safePos);
+    if ( FAILED(result) ) {
+      sprintf(message, "RtAudio: Unable to get current DS position (%s): %s.",
+              devices[stream->device[0]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+
+    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 ) {
+      // 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.
+      float millis = (endWrite - currentPos) * 900.0;
+      millis /= ( formatBytes(stream->deviceFormat[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, "RtAudio: Unable to get current DS position (%s): %s.",
+              devices[stream->device[0]].name, getErrorString(result));
+        error(RtAudioError::DRIVER_ERROR);
+      }
+      if ( currentPos < 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, "RtAudio: Unable to lock DS buffer during playback (%s): %s.",
+              devices[stream->device[0]].name, getErrorString(result));
+      error(RtAudioError::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, "RtAudio: Unable to unlock DS buffer during playback (%s): %s.",
+              devices[stream->device[0]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+    nextWritePos = (nextWritePos + bufferSize1 + bufferSize2) % dsBufferSize;
+    stream->handle[0].bufferPointer = nextWritePos;
+  }
+
+  if (stream->mode == RECORD || 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) stream->handle[1].buffer;
+    UINT nextReadPos = stream->handle[1].bufferPointer;
+    DWORD dsBufferSize = buffer_bytes * stream->nBuffers;
+
+    // Find out where the write and "safe read" pointers are.
+    result = dsBuffer->GetCurrentPosition(&currentPos, &safePos);
+    if ( FAILED(result) ) {
+      sprintf(message, "RtAudio: Unable to get current DS capture position (%s): %s.",
+              devices[stream->device[1]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+
+    if ( safePos < nextReadPos ) safePos += dsBufferSize; // unwrap offset
+    DWORD endRead = nextReadPos + buffer_bytes;
+
+    // Check whether the entire write region is behind the play pointer.
+    while ( safePos < endRead ) {
+      // See comments for playback.
+      float millis = (endRead - safePos) * 900.0;
+      millis /= ( formatBytes(stream->deviceFormat[1]) * 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, "RtAudio: Unable to get current DS capture position (%s): %s.",
+                devices[stream->device[1]].name, getErrorString(result));
+        error(RtAudioError::DRIVER_ERROR);
+      }
+      
+      if ( safePos < nextReadPos ) safePos += dsBufferSize; // unwrap offset
+    }
+
+    // Lock free space in the buffer
+    result = dsBuffer->Lock (nextReadPos, buffer_bytes, &buffer1,
+                             &bufferSize1, &buffer2, &bufferSize2, 0);
+    if ( FAILED(result) ) {
+      sprintf(message, "RtAudio: Unable to lock DS buffer during capture (%s): %s.",
+              devices[stream->device[1]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+
+    // Copy our buffer into the DS buffer
+    CopyMemory(buffer, buffer1, bufferSize1);
+    if (buffer2 != NULL) CopyMemory(buffer+bufferSize1, buffer2, 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, "RtAudio: Unable to unlock DS buffer during capture (%s): %s.",
+              devices[stream->device[1]].name, getErrorString(result));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+    stream->handle[1].bufferPointer = nextReadPos;
+
+    // No byte swapping necessary in DirectSound implementation.
+
+    // Do buffer conversion if necessary.
+    if (stream->doConvertBuffer[1])
+      convertStreamBuffer(stream, RECORD);
+  }
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+
+  if (stream->usingCallback && stopStream)
+    this->stopStream(streamID);
+}
+
+// Definitions for utility functions and callbacks
+// specific to the DirectSound implementation.
+
+extern "C" unsigned __stdcall callbackHandler(void *ptr)
+{
+  RtAudio *object = thread_info.object;
+  int stream = thread_info.streamID;
+  bool *usingCallback = (bool *) ptr;
+
+  while ( *usingCallback ) {
+    try {
+      object->tickStream(stream);
+    }
+    catch (RtAudioError &exception) {
+      fprintf(stderr, "\nCallback thread error (%s) ... closing thread.\n\n",
+              exception.getMessage());
+      break;
+    }
+  }
+
+  _endthreadex( 0 );
+  return 0;
+}
+
+static bool CALLBACK deviceCountCallback(LPGUID lpguid,
+                                         LPCSTR lpcstrDescription,
+                                         LPCSTR lpcstrModule,
+                                         LPVOID lpContext)
+{
+  int *pointer = ((int *) lpContext);
+  (*pointer)++;
+
+  return true;
+}
+
+static bool CALLBACK deviceInfoCallback(LPGUID lpguid,
+                                        LPCSTR lpcstrDescription,
+                                        LPCSTR lpcstrModule,
+                                        LPVOID lpContext)
+{
+  enum_info *info = ((enum_info *) lpContext);
+  while (strlen(info->name) > 0) info++;
+
+  strncpy(info->name, lpcstrDescription, 64);
+  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 char* getErrorString(int code)
+{
+       switch (code) {
+
+  case DSERR_ALLOCATED:
+    return "Direct Sound already allocated";
+
+  case DSERR_CONTROLUNAVAIL:
+    return "Direct Sound control unavailable";
+
+  case DSERR_INVALIDPARAM:
+    return "Direct Sound invalid parameter";
+
+  case DSERR_INVALIDCALL:
+    return "Direct Sound invalid call";
+
+  case DSERR_GENERIC:
+    return "Direct Sound generic error";
+
+  case DSERR_PRIOLEVELNEEDED:
+    return "Direct Sound Priority level needed";
+
+  case DSERR_OUTOFMEMORY:
+    return "Direct Sound out of memory";
+
+  case DSERR_BADFORMAT:
+    return "Direct Sound bad format";
+
+  case DSERR_UNSUPPORTED:
+    return "Direct Sound unsupported error";
+
+  case DSERR_NODRIVER:
+    return "Direct Sound no driver error";
+
+  case DSERR_ALREADYINITIALIZED:
+    return "Direct Sound already initialized";
+
+  case DSERR_NOAGGREGATION:
+    return "Direct Sound no aggregation";
+
+  case DSERR_BUFFERLOST:
+    return "Direct Sound buffer lost";
+
+  case DSERR_OTHERAPPHASPRIO:
+    return "Direct Sound other app has priority";
+
+  case DSERR_UNINITIALIZED:
+    return "Direct Sound uninitialized";
+
+  default:
+    return "Direct Sound unknown error";
+       }
+}
+
+//******************** End of __WINDOWS_DS_ *********************//
+
+#elif defined(__IRIX_AL_) // SGI's AL API for IRIX
+
+#include <unistd.h>
+#include <errno.h>
+
+void RtAudio :: 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, "RtAudio: AL error counting devices: %s.",
+            alGetErrorString(oserror()));
+    error(RtAudioError::DRIVER_ERROR);
+  }
+
+  if (nDevices <= 0) return;
+
+  ALvalue *vls = (ALvalue *) new ALvalue[nDevices];
+
+  // Add one for our default input/output devices.
+  nDevices++;
+
+  //  Allocate the DEVICE_CONTROL structures.
+  devices = (RTAUDIO_DEVICE *) calloc(nDevices, sizeof(RTAUDIO_DEVICE));
+  if (devices == NULL) {
+    sprintf(message, "RtAudio: memory allocation error!");
+    error(RtAudioError::MEMORY_ERROR);
+  }
+
+  // Write device ascii identifiers to device info structure.
+  char name[32];
+  int outs, ins, i;
+  ALpv pvs[1];
+  pvs[0].param = AL_NAME;
+  pvs[0].value.ptr = name;
+  pvs[0].sizeIn = 32;
+
+  strcpy(devices[0].name, "Default Input/Output Devices");
+
+  outs = alQueryValues(AL_SYSTEM, AL_DEFAULT_OUTPUT, vls, nDevices-1, 0, 0);
+  if (outs < 0) {
+    sprintf(message, "RtAudio: AL error getting output devices: %s.",
+            alGetErrorString(oserror()));
+    error(RtAudioError::DRIVER_ERROR);
+  }
+
+  for (i=0; i<outs; i++) {
+    if (alGetParams(vls[i].i, pvs, 1) < 0) {
+      sprintf(message, "RtAudio: AL error querying output devices: %s.",
+              alGetErrorString(oserror()));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+    strncpy(devices[i+1].name, name, 32);
+    devices[i+1].id[0] = vls[i].i;
+  }
+
+  ins = alQueryValues(AL_SYSTEM, AL_DEFAULT_INPUT, &vls[outs], nDevices-outs-1, 0, 0);
+  if (ins < 0) {
+    sprintf(message, "RtAudio: AL error getting input devices: %s.",
+            alGetErrorString(oserror()));
+    error(RtAudioError::DRIVER_ERROR);
+  }
+
+  for (i=outs; i<ins+outs; i++) {
+    if (alGetParams(vls[i].i, pvs, 1) < 0) {
+      sprintf(message, "RtAudio: AL error querying input devices: %s.",
+              alGetErrorString(oserror()));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+    strncpy(devices[i+1].name, name, 32);
+    devices[i+1].id[1] = vls[i].i;
+  }
+
+  delete [] vls;
+
+  return;
+}
+
+void RtAudio :: probeDeviceInfo(RTAUDIO_DEVICE *info)
+{
+  int resource, result, i;
+  ALvalue value;
+  ALparamInfo pinfo;
+
+  // Get output resource ID if it exists.
+  if ( !strncmp(info->name, "Default Input/Output Devices", 28) ) {
+    result = alQueryValues(AL_SYSTEM, AL_DEFAULT_OUTPUT, &value, 1, 0, 0);
+    if (result < 0) {
+      sprintf(message, "RtAudio: AL error getting default output device id: %s.",
+              alGetErrorString(oserror()));
+      error(RtAudioError::WARNING);
+    }
+    else
+      resource = value.i;
+  }
+  else
+    resource = info->id[0];
+
+  if (resource > 0) {
+
+    // Probe output device parameters.
+    result = alQueryValues(resource, AL_CHANNELS, &value, 1, 0, 0);
+    if (result < 0) {
+      sprintf(message, "RtAudio: AL error getting device (%s) channels: %s.",
+              info->name, alGetErrorString(oserror()));
+      error(RtAudioError::WARNING);
+    }
+    else {
+      info->maxOutputChannels = value.i;
+      info->minOutputChannels = 1;
+    }
+
+    result = alGetParamInfo(resource, AL_RATE, &pinfo);
+    if (result < 0) {
+      sprintf(message, "RtAudio: AL error getting device (%s) rates: %s.",
+              info->name, alGetErrorString(oserror()));
+      error(RtAudioError::WARNING);
+    }
+    else {
+      info->nSampleRates = 0;
+      for (i=0; i<MAX_SAMPLE_RATES; i++) {
+        if ( SAMPLE_RATES[i] >= pinfo.min.i && SAMPLE_RATES[i] <= pinfo.max.i ) {
+          info->sampleRates[info->nSampleRates] = SAMPLE_RATES[i];
+          info->nSampleRates++;
+        }
+      }
+    }
+
+    // The AL library supports all our formats, except 24-bit and 32-bit ints.
+    info->nativeFormats = (RTAUDIO_FORMAT) 51;
+  }
+
+  // Now get input resource ID if it exists.
+  if ( !strncmp(info->name, "Default Input/Output Devices", 28) ) {
+    result = alQueryValues(AL_SYSTEM, AL_DEFAULT_INPUT, &value, 1, 0, 0);
+    if (result < 0) {
+      sprintf(message, "RtAudio: AL error getting default input device id: %s.",
+              alGetErrorString(oserror()));
+      error(RtAudioError::WARNING);
+    }
+    else
+      resource = value.i;
+  }
+  else
+    resource = info->id[1];
+
+  if (resource > 0) {
+
+    // Probe input device parameters.
+    result = alQueryValues(resource, AL_CHANNELS, &value, 1, 0, 0);
+    if (result < 0) {
+      sprintf(message, "RtAudio: AL error getting device (%s) channels: %s.",
+              info->name, alGetErrorString(oserror()));
+      error(RtAudioError::WARNING);
+    }
+    else {
+      info->maxInputChannels = value.i;
+      info->minInputChannels = 1;
+    }
+
+    result = alGetParamInfo(resource, AL_RATE, &pinfo);
+    if (result < 0) {
+      sprintf(message, "RtAudio: AL error getting device (%s) rates: %s.",
+              info->name, alGetErrorString(oserror()));
+      error(RtAudioError::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->nSampleRates = 0;
+      for (i=0; i<MAX_SAMPLE_RATES; i++) {
+        if ( SAMPLE_RATES[i] >= pinfo.min.i && SAMPLE_RATES[i] <= pinfo.max.i ) {
+          info->sampleRates[info->nSampleRates] = SAMPLE_RATES[i];
+          info->nSampleRates++;
+        }
+      }
+    }
+
+    // The AL library supports all our formats, except 24-bit and 32-bit ints.
+    info->nativeFormats = (RTAUDIO_FORMAT) 51;
+  }
+
+  if ( info->maxInputChannels == 0 && info->maxOutputChannels == 0 )
+    return;
+  if ( info->nSampleRates == 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 RtAudio :: probeDeviceOpen(int device, RTAUDIO_STREAM *stream,
+                                STREAM_MODE mode, int channels, 
+                                int sampleRate, RTAUDIO_FORMAT format,
+                                int *bufferSize, int numberOfBuffers)
+{
+  int result, resource, nBuffers;
+  ALconfig al_config;
+  ALport port;
+  ALpv pvs[2];
+
+  // Get a new ALconfig structure.
+  al_config = alNewConfig();
+  if ( !al_config ) {
+    sprintf(message,"RtAudio: can't get AL config: %s.",
+            alGetErrorString(oserror()));
+    error(RtAudioError::WARNING);
+    return FAILURE;
+  }
+
+  // Set the channels.
+  result = alSetChannels(al_config, channels);
+  if ( result < 0 ) {
+    sprintf(message,"RtAudio: can't set %d channels in AL config: %s.",
+            channels, alGetErrorString(oserror()));
+    error(RtAudioError::WARNING);
+    return FAILURE;
+  }
+
+  // Set the queue (buffer) size.
+  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 ) {
+    sprintf(message,"RtAudio: can't set buffer size (%ld) in AL config: %s.",
+            buffer_size, alGetErrorString(oserror()));
+    error(RtAudioError::WARNING);
+    return FAILURE;
+  }
+
+  // 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 ) {
+    sprintf(message,"RtAudio: AL error setting sample format in AL config: %s.",
+            alGetErrorString(oserror()));
+    error(RtAudioError::WARNING);
+    return FAILURE;
+  }
+
+  if (mode == PLAYBACK) {
+
+    // Set our device.
+    if (device == 0)
+      resource = AL_DEFAULT_OUTPUT;
+    else
+      resource = devices[device].id[0];
+    result = alSetDevice(al_config, resource);
+    if ( result == -1 ) {
+      sprintf(message,"RtAudio: AL error setting device (%s) in AL config: %s.",
+              devices[device].name, alGetErrorString(oserror()));
+      error(RtAudioError::WARNING);
+      return FAILURE;
+    }
+
+    // Open the port.
+    port = alOpenPort("RtAudio Output Port", "w", al_config);
+    if( !port ) {
+      sprintf(message,"RtAudio: AL error opening output port: %s.",
+              alGetErrorString(oserror()));
+      error(RtAudioError::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);
+      sprintf(message,"RtAudio: AL error setting sample rate (%d) for device (%s): %s.",
+              sampleRate, devices[device].name, alGetErrorString(oserror()));
+      error(RtAudioError::WARNING);
+      return FAILURE;
+    }
+  }
+  else { // mode == RECORD
+
+    // Set our device.
+    if (device == 0)
+      resource = AL_DEFAULT_INPUT;
+    else
+      resource = devices[device].id[1];
+    result = alSetDevice(al_config, resource);
+    if ( result == -1 ) {
+      sprintf(message,"RtAudio: AL error setting device (%s) in AL config: %s.",
+              devices[device].name, alGetErrorString(oserror()));
+      error(RtAudioError::WARNING);
+      return FAILURE;
+    }
+
+    // Open the port.
+    port = alOpenPort("RtAudio Output Port", "r", al_config);
+    if( !port ) {
+      sprintf(message,"RtAudio: AL error opening input port: %s.",
+              alGetErrorString(oserror()));
+      error(RtAudioError::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);
+      sprintf(message,"RtAudio: AL error setting sample rate (%d) for device (%s): %s.",
+              sampleRate, devices[device].name, alGetErrorString(oserror()));
+      error(RtAudioError::WARNING);
+      return FAILURE;
+    }
+  }
+
+  alFreeConfig(al_config);
+
+  stream->nUserChannels[mode] = channels;
+  stream->nDeviceChannels[mode] = channels;
+
+  // Set handle and flags for buffer conversion
+  stream->handle[mode] = port;
+  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)
+      goto memory_error;
+  }
+
+  if ( stream->doConvertBuffer[mode] ) {
+
+    long buffer_bytes;
+    bool makeBuffer = true;
+    if ( mode == PLAYBACK )
+      buffer_bytes = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
+    else { // mode == RECORD
+      buffer_bytes = stream->nDeviceChannels[1] * formatBytes(stream->deviceFormat[1]);
+      if ( stream->mode == PLAYBACK ) {
+        long bytes_out = stream->nDeviceChannels[0] * formatBytes(stream->deviceFormat[0]);
+        if ( buffer_bytes > bytes_out )
+          buffer_bytes = (buffer_bytes > bytes_out) ? buffer_bytes : bytes_out;
+        else
+          makeBuffer = false;
+      }
+    }
+
+    if ( makeBuffer ) {
+      buffer_bytes *= *bufferSize;
+      if (stream->deviceBuffer) free(stream->deviceBuffer);
+      stream->deviceBuffer = (char *) calloc(buffer_bytes, 1);
+      if (stream->deviceBuffer == NULL)
+        goto memory_error;
+    }
+  }
+
+  stream->device[mode] = device;
+  stream->state = STREAM_STOPPED;
+  if ( stream->mode == PLAYBACK && mode == RECORD )
+    // We had already set up an output stream.
+    stream->mode = DUPLEX;
+  else
+    stream->mode = mode;
+  stream->nBuffers = nBuffers;
+  stream->bufferSize = *bufferSize;
+  stream->sampleRate = sampleRate;
+
+  return SUCCESS;
+
+ memory_error:
+  if (stream->handle[0]) {
+    alClosePort(stream->handle[0]);
+    stream->handle[0] = 0;
+  }
+  if (stream->handle[1]) {
+    alClosePort(stream->handle[1]);
+    stream->handle[1] = 0;
+  }
+  if (stream->userBuffer) {
+    free(stream->userBuffer);
+    stream->userBuffer = 0;
+  }
+  sprintf(message, "RtAudio: ALSA error allocating buffer memory for device (%s).",
+          devices[device].name);
+  error(RtAudioError::WARNING);
+  return FAILURE;
+}
+
+void RtAudio :: cancelStreamCallback(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  if (stream->usingCallback) {
+    stream->usingCallback = false;
+    pthread_cancel(stream->thread);
+    pthread_join(stream->thread, NULL);
+    stream->thread = 0;
+    stream->callback = NULL;
+    stream->userData = NULL;
+  }
+}
+
+void RtAudio :: closeStream(int streamID)
+{
+  // 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 ( streams.find( streamID ) == streams.end() ) {
+    sprintf(message, "RtAudio: invalid stream identifier!");
+    error(RtAudioError::WARNING);
+    return;
+  }
+
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) streams[streamID];
+
+  if (stream->usingCallback) {
+    pthread_cancel(stream->thread);
+    pthread_join(stream->thread, NULL);
+  }
+
+  pthread_mutex_destroy(&stream->mutex);
+
+  if (stream->handle[0])
+    alClosePort(stream->handle[0]);
+
+  if (stream->handle[1])
+    alClosePort(stream->handle[1]);
+
+  if (stream->userBuffer)
+    free(stream->userBuffer);
+
+  if (stream->deviceBuffer)
+    free(stream->deviceBuffer);
+
+  free(stream);
+  streams.erase(streamID);
+}
+
+void RtAudio :: startStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  if (stream->state == STREAM_RUNNING)
+    return;
+
+  // The AL port is ready as soon as it is opened.
+  stream->state = STREAM_RUNNING;
+}
+
+void RtAudio :: stopStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  if (stream->state == STREAM_STOPPED)
+    goto unlock;
+
+  int result;
+  int buffer_size = stream->bufferSize * stream->nBuffers;
+
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX)
+    alZeroFrames(stream->handle[0], buffer_size);
+
+  if (stream->mode == RECORD || stream->mode == DUPLEX) {
+    result = alDiscardFrames(stream->handle[1], buffer_size);
+    if (result == -1) {
+      sprintf(message, "RtAudio: AL error draining stream device (%s): %s.",
+              devices[stream->device[1]].name, alGetErrorString(oserror()));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+  stream->state = STREAM_STOPPED;
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+}
+
+void RtAudio :: abortStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  if (stream->state == STREAM_STOPPED)
+    goto unlock;
+
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+
+    int buffer_size = stream->bufferSize * stream->nBuffers;
+    int result = alDiscardFrames(stream->handle[0], buffer_size);
+    if (result == -1) {
+      sprintf(message, "RtAudio: AL error aborting stream device (%s): %s.",
+              devices[stream->device[0]].name, alGetErrorString(oserror()));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+
+  // There is no clear action to take on the input stream, since the
+  // port will continue to run in any event.
+  stream->state = STREAM_STOPPED;
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+}
+
+int RtAudio :: streamWillBlock(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  MUTEX_LOCK(&stream->mutex);
+
+  int frames = 0;
+  if (stream->state == STREAM_STOPPED)
+    goto unlock;
+
+  int err = 0;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+    err = alGetFillable(stream->handle[0]);
+    if (err < 0) {
+      sprintf(message, "RtAudio: AL error getting available frames for stream (%s): %s.",
+              devices[stream->device[0]].name, alGetErrorString(oserror()));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+  }
+
+  frames = err;
+
+  if (stream->mode == RECORD || stream->mode == DUPLEX) {
+    err = alGetFilled(stream->handle[1]);
+    if (err < 0) {
+      sprintf(message, "RtAudio: AL error getting available frames for stream (%s): %s.",
+              devices[stream->device[1]].name, alGetErrorString(oserror()));
+      error(RtAudioError::DRIVER_ERROR);
+    }
+    if (frames > err) frames = err;
+  }
+
+  frames = stream->bufferSize - frames;
+  if (frames < 0) frames = 0;
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+  return frames;
+}
+
+void RtAudio :: tickStream(int streamID)
+{
+  RTAUDIO_STREAM *stream = (RTAUDIO_STREAM *) verifyStream(streamID);
+
+  int stopStream = 0;
+  if (stream->state == STREAM_STOPPED) {
+    if (stream->usingCallback) usleep(50000); // sleep 50 milliseconds
+    return;
+  }
+  else if (stream->usingCallback) {
+    stopStream = stream->callback(stream->userBuffer, stream->bufferSize, stream->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;
+  RTAUDIO_FORMAT format;
+  if (stream->mode == PLAYBACK || stream->mode == DUPLEX) {
+
+    // Setup parameters and do buffer conversion if necessary.
+    if (stream->doConvertBuffer[0]) {
+      convertStreamBuffer(stream, PLAYBACK);
+      buffer = stream->deviceBuffer;
+      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(stream->handle[0], buffer, stream->bufferSize);
+  }
+
+  if (stream->mode == RECORD || 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(stream->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])
+      convertStreamBuffer(stream, RECORD);
+  }
+
+ unlock:
+  MUTEX_UNLOCK(&stream->mutex);
+
+  if (stream->usingCallback && stopStream)
+    this->stopStream(streamID);
+}
+
+extern "C" void *callbackHandler(void *ptr)
+{
+  RtAudio *object = thread_info.object;
+  int stream = thread_info.streamID;
+  bool *usingCallback = (bool *) ptr;
+
+  while ( *usingCallback ) {
+    pthread_testcancel();
+    try {
+      object->tickStream(stream);
+    }
+    catch (RtAudioError &exception) {
+      fprintf(stderr, "\nCallback thread error (%s) ... closing thread.\n\n",
+              exception.getMessage());
+      break;
+    }
+  }
+
+  return 0;
+}
+
+//******************** End of __IRIX_AL_ *********************//
+
+#endif
+
+
+// *************************************************** //
+//
+// Private common (OS-independent) RtAudio methods.
+//
+// *************************************************** //
+
+// This method can be modified to control the behavior of error
+// message reporting and throwing.
+void RtAudio :: error(RtAudioError::TYPE type)
+{
+  if (type == RtAudioError::WARNING)
+    fprintf(stderr, "\n%s\n\n", message);
+  else if (type == RtAudioError::DEBUG_WARNING) {
+#if defined(RTAUDIO_DEBUG)
+    fprintf(stderr, "\n%s\n\n", message);
+#endif
+  }
+  else
+    throw RtAudioError(message, type);
+}
+
+void *RtAudio :: verifyStream(int streamID)
+{
+  // Verify the stream key.
+  if ( streams.find( streamID ) == streams.end() ) {
+    sprintf(message, "RtAudio: invalid stream identifier!");
+    error(RtAudioError::INVALID_STREAM);
+  }
+
+  return streams[streamID];
+}
+
+void RtAudio :: clearDeviceInfo(RTAUDIO_DEVICE *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->nSampleRates = 0;
+  for (int i=0; i<MAX_SAMPLE_RATES; i++)
+    info->sampleRates[i] = 0;
+  info->nativeFormats = 0;
+}
+
+int RtAudio :: formatBytes(RTAUDIO_FORMAT 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,"RtAudio: undefined format in formatBytes().");
+  error(RtAudioError::WARNING);
+
+  return 0;
+}
+
+void RtAudio :: convertStreamBuffer(RTAUDIO_STREAM *stream, STREAM_MODE mode)
+{
+  // This method 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.
+
+  int j, channels_in, channels_out, channels;
+  RTAUDIO_FORMAT format_in, format_out;
+  char *input, *output;
+
+  if (mode == RECORD) { // convert device to user buffer
+    input = stream->deviceBuffer;
+    output = stream->userBuffer;
+    channels_in = stream->nDeviceChannels[1];
+    channels_out = stream->nUserChannels[1];
+    format_in = stream->deviceFormat[1];
+    format_out = stream->userFormat;
+  }
+  else { // convert user to device buffer
+    input = stream->userBuffer;
+    output = stream->deviceBuffer;
+    channels_in = stream->nUserChannels[0];
+    channels_out = stream->nDeviceChannels[0];
+    format_in = stream->userFormat;
+    format_out = stream->deviceFormat[0];
+
+    // clear our device buffer when in/out duplex device channels are different
+    if ( stream->mode == DUPLEX &&
+         stream->nDeviceChannels[0] != stream->nDeviceChannels[1] )
+      memset(output, 0, stream->bufferSize * channels_out * formatBytes(format_out));
+  }
+
+  channels = (channels_in < channels_out) ? channels_in : channels_out;
+
+  // Set up the interleave/deinterleave offsets
+  std::vector<int> offset_in(channels);
+  std::vector<int> offset_out(channels);
+  if (mode == RECORD && stream->deInterleave[1]) {
+    for (int k=0; k<channels; k++) {
+      offset_in[k] = k * stream->bufferSize;
+      offset_out[k] = k;
+    }
+  }
+  else if (mode == PLAYBACK && stream->deInterleave[0]) {
+    for (int k=0; k<channels; k++) {
+      offset_in[k] = k;
+      offset_out[k] = k * stream->bufferSize;
+    }
+  }
+  else {
+    for (int k=0; k<channels; k++) {
+      offset_in[k] = k;
+      offset_out[k] = k;
+    }
+  }
+
+  if (format_out == RTAUDIO_FLOAT64) {
+    FLOAT64 scale;
+    FLOAT64 *out = (FLOAT64 *)output;
+
+    if (format_in == RTAUDIO_SINT8) {
+      signed char *in = (signed char *)input;
+      scale = 1.0 / 128.0;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (FLOAT64) in[offset_in[j]];
+          out[offset_out[j]] *= scale;
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT16) {
+      INT16 *in = (INT16 *)input;
+      scale = 1.0 / 32768.0;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (FLOAT64) in[offset_in[j]];
+          out[offset_out[j]] *= scale;
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT24) {
+      INT32 *in = (INT32 *)input;
+      scale = 1.0 / 2147483648.0;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (FLOAT64) (in[offset_in[j]] & 0xffffff00);
+          out[offset_out[j]] *= scale;
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT32) {
+      INT32 *in = (INT32 *)input;
+      scale = 1.0 / 2147483648.0;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (FLOAT64) in[offset_in[j]];
+          out[offset_out[j]] *= scale;
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_FLOAT32) {
+      FLOAT32 *in = (FLOAT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (FLOAT64) in[offset_in[j]];
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_FLOAT64) {
+      // Channel compensation and/or (de)interleaving only.
+      FLOAT64 *in = (FLOAT64 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = in[offset_in[j]];
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+  }
+  else if (format_out == RTAUDIO_FLOAT32) {
+    FLOAT32 scale;
+    FLOAT32 *out = (FLOAT32 *)output;
+
+    if (format_in == RTAUDIO_SINT8) {
+      signed char *in = (signed char *)input;
+      scale = 1.0 / 128.0;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (FLOAT32) in[offset_in[j]];
+          out[offset_out[j]] *= scale;
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT16) {
+      INT16 *in = (INT16 *)input;
+      scale = 1.0 / 32768.0;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (FLOAT32) in[offset_in[j]];
+          out[offset_out[j]] *= scale;
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT24) {
+      INT32 *in = (INT32 *)input;
+      scale = 1.0 / 2147483648.0;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (FLOAT32) (in[offset_in[j]] & 0xffffff00);
+          out[offset_out[j]] *= scale;
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT32) {
+      INT32 *in = (INT32 *)input;
+      scale = 1.0 / 2147483648.0;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (FLOAT32) in[offset_in[j]];
+          out[offset_out[j]] *= scale;
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_FLOAT32) {
+      // Channel compensation and/or (de)interleaving only.
+      FLOAT32 *in = (FLOAT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = in[offset_in[j]];
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_FLOAT64) {
+      FLOAT64 *in = (FLOAT64 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (FLOAT32) in[offset_in[j]];
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+  }
+  else if (format_out == RTAUDIO_SINT32) {
+    INT32 *out = (INT32 *)output;
+    if (format_in == RTAUDIO_SINT8) {
+      signed char *in = (signed char *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT32) in[offset_in[j]];
+          out[offset_out[j]] <<= 24;
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT16) {
+      INT16 *in = (INT16 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT32) in[offset_in[j]];
+          out[offset_out[j]] <<= 16;
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT24) {
+      INT32 *in = (INT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT32) in[offset_in[j]];
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT32) {
+      // Channel compensation and/or (de)interleaving only.
+      INT32 *in = (INT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = in[offset_in[j]];
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_FLOAT32) {
+      FLOAT32 *in = (FLOAT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT32) (in[offset_in[j]] * 2147483647.0);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_FLOAT64) {
+      FLOAT64 *in = (FLOAT64 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT32) (in[offset_in[j]] * 2147483647.0);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+  }
+  else if (format_out == RTAUDIO_SINT24) {
+    INT32 *out = (INT32 *)output;
+    if (format_in == RTAUDIO_SINT8) {
+      signed char *in = (signed char *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT32) in[offset_in[j]];
+          out[offset_out[j]] <<= 24;
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT16) {
+      INT16 *in = (INT16 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT32) in[offset_in[j]];
+          out[offset_out[j]] <<= 16;
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT24) {
+      // Channel compensation and/or (de)interleaving only.
+      INT32 *in = (INT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = in[offset_in[j]];
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT32) {
+      INT32 *in = (INT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT32) (in[offset_in[j]] & 0xffffff00);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_FLOAT32) {
+      FLOAT32 *in = (FLOAT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT32) (in[offset_in[j]] * 2147483647.0);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_FLOAT64) {
+      FLOAT64 *in = (FLOAT64 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT32) (in[offset_in[j]] * 2147483647.0);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+  }
+  else if (format_out == RTAUDIO_SINT16) {
+    INT16 *out = (INT16 *)output;
+    if (format_in == RTAUDIO_SINT8) {
+      signed char *in = (signed char *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT16) in[offset_in[j]];
+          out[offset_out[j]] <<= 8;
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT16) {
+      // Channel compensation and/or (de)interleaving only.
+      INT16 *in = (INT16 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = in[offset_in[j]];
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT24) {
+      INT32 *in = (INT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT16) ((in[offset_in[j]] >> 16) & 0x0000ffff);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT32) {
+      INT32 *in = (INT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT16) ((in[offset_in[j]] >> 16) & 0x0000ffff);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_FLOAT32) {
+      FLOAT32 *in = (FLOAT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT16) (in[offset_in[j]] * 32767.0);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_FLOAT64) {
+      FLOAT64 *in = (FLOAT64 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (INT16) (in[offset_in[j]] * 32767.0);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+  }
+  else if (format_out == RTAUDIO_SINT8) {
+    signed char *out = (signed char *)output;
+    if (format_in == RTAUDIO_SINT8) {
+      // Channel compensation and/or (de)interleaving only.
+      signed char *in = (signed char *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = in[offset_in[j]];
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    if (format_in == RTAUDIO_SINT16) {
+      INT16 *in = (INT16 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (signed char) ((in[offset_in[j]] >> 8) & 0x00ff);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT24) {
+      INT32 *in = (INT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (signed char) ((in[offset_in[j]] >> 24) & 0x000000ff);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_SINT32) {
+      INT32 *in = (INT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (signed char) ((in[offset_in[j]] >> 24) & 0x000000ff);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_FLOAT32) {
+      FLOAT32 *in = (FLOAT32 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (signed char) (in[offset_in[j]] * 127.0);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+    else if (format_in == RTAUDIO_FLOAT64) {
+      FLOAT64 *in = (FLOAT64 *)input;
+      for (int i=0; i<stream->bufferSize; i++) {
+        for (j=0; j<channels; j++) {
+          out[offset_out[j]] = (signed char) (in[offset_in[j]] * 127.0);
+        }
+        in += channels_in;
+        out += channels_out;
+      }
+    }
+  }
+}
+
+void RtAudio :: byteSwapBuffer(char *buffer, int samples, RTAUDIO_FORMAT 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;
+    }
+  }
+}
+
+
+// *************************************************** //
+//
+// RtAudioError class definition.
+//
+// *************************************************** //
+
+RtAudioError :: RtAudioError(const char *p, TYPE tipe)
+{
+  type = tipe;
+  strncpy(error_message, p, 256);
+}
+
+RtAudioError :: ~RtAudioError()
+{
+}
+
+void RtAudioError :: printMessage()
+{
+  printf("\n%s\n\n", error_message);
+}
diff --git a/RtAudio.h b/RtAudio.h
new file mode 100644 (file)
index 0000000..cc073e8
--- /dev/null
+++ b/RtAudio.h
@@ -0,0 +1,430 @@
+/******************************************/
+/*
+  RtAudio - realtime sound I/O C++ class
+  Version 2.0 by Gary P. Scavone, 2001-2002.
+*/
+/******************************************/
+
+#if !defined(__RtAudio_h)
+#define __RtAudio_h
+
+#include <map>
+
+#if defined(__LINUX_ALSA_)
+  #include <alsa/asoundlib.h>
+  #include <pthread.h>
+  #include <unistd.h>
+
+  typedef snd_pcm_t *AUDIO_HANDLE;
+  typedef int DEVICE_ID;
+  typedef pthread_t THREAD_HANDLE;
+  typedef pthread_mutex_t MUTEX;
+
+#elif defined(__LINUX_OSS_)
+  #include <pthread.h>
+  #include <unistd.h>
+
+  typedef int AUDIO_HANDLE;
+  typedef int DEVICE_ID;
+  typedef pthread_t THREAD_HANDLE;
+  typedef pthread_mutex_t MUTEX;
+
+#elif defined(__WINDOWS_DS_)
+  #include <windows.h>
+  #include <process.h>
+
+  // The following struct is used to hold the extra variables
+  // specific to the DirectSound implementation.
+  typedef struct {
+    void * object;
+    void * buffer;
+    UINT bufferPointer;
+  } AUDIO_HANDLE;
+
+  typedef LPGUID DEVICE_ID;
+  typedef unsigned long THREAD_HANDLE;
+  typedef CRITICAL_SECTION MUTEX;
+
+#elif defined(__IRIX_AL_)
+  #include <dmedia/audio.h>
+  #include <pthread.h>
+  #include <unistd.h>
+
+  typedef ALport AUDIO_HANDLE;
+  typedef int DEVICE_ID;
+  typedef pthread_t THREAD_HANDLE;
+  typedef pthread_mutex_t MUTEX;
+
+#endif
+
+
+// *************************************************** //
+//
+// RtAudioError class declaration.
+//
+// *************************************************** //
+
+class RtAudioError
+{
+public:
+  enum TYPE {
+    WARNING,
+    DEBUG_WARNING,
+    UNSPECIFIED,
+    NO_DEVICES_FOUND,
+    INVALID_DEVICE,
+    INVALID_STREAM,
+    MEMORY_ERROR,
+    INVALID_PARAMETER,
+    DRIVER_ERROR,
+    SYSTEM_ERROR,
+    THREAD_ERROR
+  };
+
+protected:
+  char error_message[256];
+  TYPE type;
+
+public:
+  //! The constructor.
+  RtAudioError(const char *p, TYPE tipe = RtAudioError::UNSPECIFIED);
+
+  //! The destructor.
+  virtual ~RtAudioError(void);
+
+  //! Prints "thrown" error message to stdout.
+  virtual void printMessage(void);
+
+  //! Returns the "thrown" error message TYPE.
+  virtual const TYPE& getType(void) { return type; }
+
+  //! Returns the "thrown" error message string.
+  virtual const char *getMessage(void) { return error_message; }
+};
+
+
+// *************************************************** //
+//
+// RtAudio class declaration.
+//
+// *************************************************** //
+
+class RtAudio
+{
+public:
+
+  // Support for signed integers and floats.  Audio data fed to/from
+  // the tickStream() routine is assumed to ALWAYS be in host
+  // byte order.  The internal routines will automatically take care of
+  // any necessary byte-swapping between the host format and the
+  // soundcard.  Thus, endian-ness is not a concern in the following
+  // format definitions.
+  typedef unsigned long RTAUDIO_FORMAT;
+  static const RTAUDIO_FORMAT RTAUDIO_SINT8;
+  static const RTAUDIO_FORMAT RTAUDIO_SINT16;
+  static const RTAUDIO_FORMAT RTAUDIO_SINT24; /*!< Upper 3 bytes of 32-bit integer. */
+  static const RTAUDIO_FORMAT RTAUDIO_SINT32;
+  static const RTAUDIO_FORMAT RTAUDIO_FLOAT32; /*!< Normalized between plus/minus 1.0. */
+  static const RTAUDIO_FORMAT RTAUDIO_FLOAT64; /*!< Normalized between plus/minus 1.0. */
+
+  //static const int MAX_SAMPLE_RATES = 14;
+  enum { MAX_SAMPLE_RATES = 14 };
+
+  typedef int (*RTAUDIO_CALLBACK)(char *buffer, int bufferSize, void *userData);
+
+  typedef struct {
+    char name[128];
+    DEVICE_ID id[2];  /*!< No value reported by getDeviceInfo(). */
+    bool probed;       /*!< true if the device capabilities were successfully probed. */
+    int maxOutputChannels;
+    int maxInputChannels;
+    int maxDuplexChannels;
+    int minOutputChannels;
+    int minInputChannels;
+    int minDuplexChannels;
+    bool hasDuplexSupport; /*!< true if device supports duplex mode. */
+    int nSampleRates;      /*!< Number of discrete rates or -1 if range supported. */
+    int sampleRates[MAX_SAMPLE_RATES]; /*!< Supported rates or (min, max) if range. */
+    RTAUDIO_FORMAT nativeFormats;     /*!< Bit mask of supported data formats. */
+  } RTAUDIO_DEVICE;
+
+  //! The default constructor.
+  /*!
+    Probes the system to make sure at least one audio
+    input/output device is available and determines
+    the api-specific identifier for each device found.
+    An RtAudioError error can be thrown if no devices are
+    found or if a memory allocation error occurs.
+  */
+  RtAudio();
+
+  //! A constructor which can be used to open a stream during instantiation.
+  /*!
+    The specified output and/or input device identifiers correspond
+    to those enumerated via the getDeviceInfo() method.  If device =
+    0, the default or first available devices meeting the given
+    parameters is selected.  If an output or input channel value is
+    zero, the corresponding device value is ignored.  When a stream is
+    successfully opened, its identifier is returned via the "streamID"
+    pointer.  An RtAudioError can be thrown if no devices are found
+    for the given parameters, if a memory allocation error occurs, or
+    if a driver error occurs. \sa openStream()
+  */
+  RtAudio(int *streamID,
+          int outputDevice, int outputChannels,
+          int inputDevice, int inputChannels,
+          RTAUDIO_FORMAT format, int sampleRate,
+          int *bufferSize, int numberOfBuffers);
+
+  //! The destructor.
+  /*!
+    Stops and closes any open streams and devices and deallocates
+    buffer and structure memory.
+  */
+  ~RtAudio();
+
+  //! A public method for opening a stream with the specified parameters.
+  /*!
+    If successful, the opened stream ID is returned.  Otherwise, an
+    RtAudioError is thrown.
+
+    \param outputDevice: If equal to 0, the default or first device
+           found meeting the given parameters is opened.  Otherwise, the
+           device number should correspond to one of those enumerated via
+           the getDeviceInfo() method.
+    \param outputChannels: The desired number of output channels.  If
+           equal to zero, the outputDevice identifier is ignored.
+    \param inputDevice: If equal to 0, the default or first device
+           found meeting the given parameters is opened.  Otherwise, the
+           device number should correspond to one of those enumerated via
+           the getDeviceInfo() method.
+    \param inputChannels: The desired number of input channels.  If
+           equal to zero, the inputDevice identifier is ignored.
+    \param format: An RTAUDIO_FORMAT specifying the desired sample data format.
+    \param sampleRate: The desired sample rate (sample frames per second).
+    \param *bufferSize: A pointer value indicating the desired internal buffer
+           size in sample frames.  The actual value used by the device is
+           returned via the same pointer.  A value of zero can be specified,
+           in which case the lowest allowable value is determined.
+    \param numberOfBuffers: A value which can be used to help control device
+           latency.  More buffers typically result in more robust performance,
+           though at a cost of greater latency.  A value of zero can be
+           specified, in which case the lowest allowable value is used.
+  */
+  int openStream(int outputDevice, int outputChannels,
+                 int inputDevice, int inputChannels,
+                 RTAUDIO_FORMAT format, int sampleRate,
+                 int *bufferSize, int numberOfBuffers);
+
+  //! A public method which sets a user-defined callback function for a given stream.
+  /*!
+    This method assigns a callback function to a specific,
+    previously opened stream for non-blocking stream functionality.  A
+    separate process is initiated, though the user function is called
+    only when the stream is "running" (between calls to the
+    startStream() and stopStream() methods, respectively).  The
+    callback process remains active for the duration of the stream and
+    is automatically shutdown when the stream is closed (via the
+    closeStream() method or by object destruction).  The callback
+    process can also be shutdown and the user function de-referenced
+    through an explicit call to the cancelStreamCallback() method.
+    Note that a single stream can use only blocking or callback
+    functionality at the same time, though it is possible to alternate
+    modes on the same stream through the use of the
+    setStreamCallback() and cancelStreamCallback() methods (the
+    blocking tickStream() method can be used before a callback is set
+    and/or after a callback is cancelled).  An RtAudioError will be
+    thrown for an invalid device argument.
+  */
+  void setStreamCallback(int streamID, RTAUDIO_CALLBACK callback, void *userData);
+
+  //! A public method which cancels a callback process and function for a given stream.
+  /*!
+    This method shuts down a callback process and de-references the
+    user function for a specific stream.  Callback functionality can
+    subsequently be restarted on the stream via the
+    setStreamCallback() method.  An RtAudioError will be thrown for an
+    invalid device argument.
+   */
+  void cancelStreamCallback(int streamID);
+
+  //! A public method which returns the number of audio devices found.
+  int getDeviceCount(void);
+
+  //! Fill a user-supplied RTAUDIO_DEVICE structure for a specified device.
+  /*!
+    Any device between 0 and getDeviceCount()-1 is valid.  If a
+    device is busy or otherwise unavailable, the structure member
+    "probed" has a value of "false".  The system default input and
+    output devices are referenced by device identifier = 0.  On
+    systems which allow dynamic default device settings, the default
+    devices are not identified by name (specific device enumerations
+    are assigned device identifiers > 0).  An RtAudioError will be
+    thrown for an invalid device argument.
+  */
+  void getDeviceInfo(int device, RTAUDIO_DEVICE *info);
+
+  //! A public method which returns a pointer to the buffer for an open stream.
+  /*!
+    The user should fill and/or read the buffer data in interleaved format
+    and then call the tickStream() method.  An RtAudioError will be
+    thrown for an invalid stream identifier.
+  */
+  char * const getStreamBuffer(int streamID);
+
+  //! Public method used to trigger processing of input/output data for a stream.
+  /*!
+    This method blocks until all buffer data is read/written.  An
+    RtAudioError will be thrown for an invalid stream identifier or if
+    a driver error occurs.
+  */
+  void tickStream(int streamID);
+
+  //! Public method which closes a stream and frees any associated buffers.
+  /*!
+    If an invalid stream identifier is specified, this method
+    issues a warning and returns (an RtAudioError is not thrown).
+  */
+  void closeStream(int streamID);
+
+  //! Public method which starts a stream.
+  /*!
+    An RtAudioError will be thrown for an invalid stream identifier
+    or if a driver error occurs.
+  */
+  void startStream(int streamID);
+
+  //! Stop a stream, allowing any samples remaining in the queue to be played out and/or read in.
+  /*!
+    An RtAudioError will be thrown for an invalid stream identifier
+    or if a driver error occurs.
+  */
+  void stopStream(int streamID);
+
+  //! Stop a stream, discarding any samples remaining in the input/output queue.
+  /*!
+    An RtAudioError will be thrown for an invalid stream identifier
+    or if a driver error occurs.
+  */
+  void abortStream(int streamID);
+
+  //! Queries a stream to determine whether a call to the tickStream() method will block.
+  /*!
+    A return value of 0 indicates that the stream will NOT block.  A positive
+    return value indicates the number of sample frames that cannot yet be
+    processed without blocking.
+  */
+  int streamWillBlock(int streamID);
+
+protected:
+
+private:
+
+  static const unsigned int SAMPLE_RATES[MAX_SAMPLE_RATES];
+
+  enum { FAILURE, SUCCESS };
+
+  enum STREAM_MODE {
+    PLAYBACK,
+    RECORD,
+    DUPLEX,
+    UNINITIALIZED = -75
+  };
+
+  enum STREAM_STATE {
+    STREAM_STOPPED,
+    STREAM_RUNNING
+  };
+
+  typedef struct {
+    int device[2];           // Playback and record, respectively.
+    STREAM_MODE mode;       // PLAYBACK, RECORD, or DUPLEX.
+    AUDIO_HANDLE handle[2]; // Playback and record handles, respectively.
+    STREAM_STATE state;     // STOPPED or RUNNING
+    char *userBuffer;
+    char *deviceBuffer;
+    bool doConvertBuffer[2]; // Playback and record, respectively.
+    bool deInterleave[2];    // Playback and record, respectively.
+    bool doByteSwap[2];      // Playback and record, respectively.
+    int sampleRate;
+    int bufferSize;
+    int nBuffers;
+    int nUserChannels[2];    // Playback and record, respectively.
+    int nDeviceChannels[2];  // Playback and record channels, respectively.
+    RTAUDIO_FORMAT userFormat;
+    RTAUDIO_FORMAT deviceFormat[2]; // Playback and record, respectively.
+    bool usingCallback;
+    THREAD_HANDLE thread;
+    MUTEX mutex;
+    RTAUDIO_CALLBACK callback;
+    void *userData;
+  } RTAUDIO_STREAM;
+
+  typedef signed short INT16;
+  typedef signed int INT32;
+  typedef float FLOAT32;
+  typedef double FLOAT64;
+
+  char message[256];
+  int nDevices;
+  RTAUDIO_DEVICE *devices;
+
+  std::map<int, void *> streams;
+
+  //! Private error method to allow global control over error handling.
+  void error(RtAudioError::TYPE type);
+
+  /*!
+    Private method to count the system audio devices, allocate the
+    RTAUDIO_DEVICE structures, and probe the device capabilities.
+  */
+  void initialize(void);
+
+  //! Private method to clear an RTAUDIO_DEVICE structure.
+  void clearDeviceInfo(RTAUDIO_DEVICE *info);
+
+  /*!
+    Private method which attempts to fill an RTAUDIO_DEVICE
+    structure for a given device.  If an error is encountered during
+    the probe, a "warning" message is reported and the value of
+    "probed" remains false (no exception is thrown).  A successful
+    probe is indicated by probed = true.
+  */
+  void probeDeviceInfo(RTAUDIO_DEVICE *info);
+
+  /*!
+    Private method which attempts to open a device with the given parameters.
+    If an error is encountered during the probe, a "warning" message is
+    reported and FAILURE is returned (no exception is thrown). A
+    successful probe is indicated by a return value of SUCCESS.
+  */
+  bool probeDeviceOpen(int device, RTAUDIO_STREAM *stream,
+                       STREAM_MODE mode, int channels, 
+                       int sampleRate, RTAUDIO_FORMAT format,
+                       int *bufferSize, int numberOfBuffers);
+
+  /*!
+    Private common method used to check validity of a user-passed
+    stream ID.  When the ID is valid, this method returns a pointer to
+    an RTAUDIO_STREAM structure (in the form of a void pointer).
+    Otherwise, an "invalid identifier" exception is thrown.
+  */
+  void *verifyStream(int streamID);
+
+  /*!
+    Private method used to perform format, channel number, and/or interleaving
+    conversions between the user and device buffers.
+  */
+  void convertStreamBuffer(RTAUDIO_STREAM *stream, STREAM_MODE mode);
+
+  //! Private method used to perform byte-swapping on buffers.
+  void byteSwapBuffer(char *buffer, int samples, RTAUDIO_FORMAT format);
+
+  //! Private method which returns the number of bytes for a given format.
+  int formatBytes(RTAUDIO_FORMAT format);
+};
+
+// Uncomment the following definition to have extra information spewed to stderr.
+//#define RTAUDIO_DEBUG
+
+#endif
diff --git a/doc/Doxyfile b/doc/Doxyfile
new file mode 100644 (file)
index 0000000..a5ab761
--- /dev/null
@@ -0,0 +1,155 @@
+# Doxyfile 1.2.6\r
+\r
+#---------------------------------------------------------------------------\r
+# General configuration options\r
+#---------------------------------------------------------------------------\r
+PROJECT_NAME           = RtAudio\r
+PROJECT_NUMBER         = \r
+OUTPUT_DIRECTORY       = .\r
+OUTPUT_LANGUAGE        = English\r
+EXTRACT_ALL            = YES\r
+EXTRACT_PRIVATE        = NO\r
+EXTRACT_STATIC         = NO\r
+HIDE_UNDOC_MEMBERS     = NO\r
+HIDE_UNDOC_CLASSES     = NO\r
+BRIEF_MEMBER_DESC      = YES\r
+REPEAT_BRIEF           = YES\r
+ALWAYS_DETAILED_SEC    = NO\r
+FULL_PATH_NAMES        = NO\r
+STRIP_FROM_PATH        = \r
+INTERNAL_DOCS          = NO\r
+CLASS_DIAGRAMS         = YES\r
+SOURCE_BROWSER         = NO\r
+INLINE_SOURCES         = NO\r
+STRIP_CODE_COMMENTS    = YES\r
+CASE_SENSE_NAMES       = YES\r
+HIDE_SCOPE_NAMES       = NO\r
+VERBATIM_HEADERS       = YES\r
+SHOW_INCLUDE_FILES     = YES\r
+JAVADOC_AUTOBRIEF      = NO\r
+INHERIT_DOCS           = YES\r
+INLINE_INFO            = YES\r
+SORT_MEMBER_DOCS       = NO\r
+DISTRIBUTE_GROUP_DOC   = NO\r
+TAB_SIZE               = 8\r
+ENABLED_SECTIONS       = \r
+GENERATE_TODOLIST      = YES\r
+GENERATE_TESTLIST      = YES\r
+GENERATE_BUGLIST       = YES\r
+ALIASES                = \r
+MAX_INITIALIZER_LINES  = 30\r
+OPTIMIZE_OUTPUT_FOR_C  = NO\r
+SHOW_USED_FILES        = YES\r
+#---------------------------------------------------------------------------\r
+# configuration options related to warning and progress messages\r
+#---------------------------------------------------------------------------\r
+QUIET                  = NO\r
+WARNINGS               = YES\r
+WARN_IF_UNDOCUMENTED   = YES\r
+WARN_FORMAT            = "$file:$line: $text"\r
+WARN_LOGFILE           = \r
+#---------------------------------------------------------------------------\r
+# configuration options related to the input files\r
+#---------------------------------------------------------------------------\r
+INPUT                  = tutorial.txt ../RtAudio.h\r
+FILE_PATTERNS          = \r
+RECURSIVE              = NO\r
+EXCLUDE                = \r
+EXCLUDE_PATTERNS       = \r
+EXAMPLE_PATH           = \r
+EXAMPLE_PATTERNS       = \r
+IMAGE_PATH             = \r
+INPUT_FILTER           = \r
+FILTER_SOURCE_FILES    = NO\r
+#---------------------------------------------------------------------------\r
+# configuration options related to the alphabetical class index\r
+#---------------------------------------------------------------------------\r
+ALPHABETICAL_INDEX     = NO\r
+COLS_IN_ALPHA_INDEX    = 5\r
+IGNORE_PREFIX          = \r
+#---------------------------------------------------------------------------\r
+# configuration options related to the HTML output\r
+#---------------------------------------------------------------------------\r
+GENERATE_HTML          = YES\r
+HTML_OUTPUT            = html\r
+HTML_HEADER            = header.html\r
+HTML_FOOTER            = footer.html\r
+HTML_STYLESHEET        = \r
+HTML_ALIGN_MEMBERS     = YES\r
+GENERATE_HTMLHELP      = NO\r
+GENERATE_CHI           = NO\r
+BINARY_TOC             = NO\r
+TOC_EXPAND             = NO\r
+DISABLE_INDEX          = YES\r
+ENUM_VALUES_PER_LINE   = 4\r
+GENERATE_TREEVIEW      = NO\r
+TREEVIEW_WIDTH         = 250\r
+#---------------------------------------------------------------------------\r
+# configuration options related to the LaTeX output\r
+#---------------------------------------------------------------------------\r
+GENERATE_LATEX         = YES\r
+LATEX_OUTPUT           = latex\r
+COMPACT_LATEX          = NO\r
+PAPER_TYPE             = a4wide\r
+EXTRA_PACKAGES         = \r
+LATEX_HEADER           = \r
+PDF_HYPERLINKS         = NO\r
+USE_PDFLATEX           = NO\r
+LATEX_BATCHMODE        = NO\r
+#---------------------------------------------------------------------------\r
+# configuration options related to the RTF output\r
+#---------------------------------------------------------------------------\r
+GENERATE_RTF           = YES\r
+RTF_OUTPUT             = rtf\r
+COMPACT_RTF            = NO\r
+RTF_HYPERLINKS         = NO\r
+RTF_STYLESHEET_FILE    = \r
+#---------------------------------------------------------------------------\r
+# configuration options related to the man page output\r
+#---------------------------------------------------------------------------\r
+GENERATE_MAN           = YES\r
+MAN_OUTPUT             = man\r
+MAN_EXTENSION          = .3\r
+#---------------------------------------------------------------------------\r
+# Configuration options related to the preprocessor   \r
+#---------------------------------------------------------------------------\r
+ENABLE_PREPROCESSING   = YES\r
+MACRO_EXPANSION        = NO\r
+EXPAND_ONLY_PREDEF     = NO\r
+SEARCH_INCLUDES        = YES\r
+INCLUDE_PATH           = \r
+INCLUDE_FILE_PATTERNS  = \r
+PREDEFINED             = \r
+EXPAND_AS_DEFINED      = \r
+#---------------------------------------------------------------------------\r
+# Configuration::addtions related to external references   \r
+#---------------------------------------------------------------------------\r
+TAGFILES               = \r
+GENERATE_TAGFILE       = \r
+ALLEXTERNALS           = NO\r
+PERL_PATH              = /usr/bin/perl\r
+#---------------------------------------------------------------------------\r
+# Configuration options related to the dot tool   \r
+#---------------------------------------------------------------------------\r
+HAVE_DOT               = NO\r
+CLASS_GRAPH            = YES\r
+COLLABORATION_GRAPH    = YES\r
+INCLUDE_GRAPH          = YES\r
+INCLUDED_BY_GRAPH      = YES\r
+GRAPHICAL_HIERARCHY    = YES\r
+DOT_PATH               = \r
+MAX_DOT_GRAPH_WIDTH    = 1024\r
+MAX_DOT_GRAPH_HEIGHT   = 1024\r
+GENERATE_LEGEND        = YES\r
+DOT_CLEANUP            = YES\r
+#---------------------------------------------------------------------------\r
+# Configuration::addtions related to the search engine   \r
+#---------------------------------------------------------------------------\r
+SEARCHENGINE           = NO\r
+CGI_NAME               = search.cgi\r
+CGI_URL                = \r
+DOC_URL                = \r
+DOC_ABSPATH            = \r
+BIN_ABSPATH            = /usr/local/bin/\r
+EXT_DOC_PATHS          = \r
+\r
diff --git a/doc/ccrma.gif b/doc/ccrma.gif
new file mode 100644 (file)
index 0000000..8a7418c
Binary files /dev/null and b/doc/ccrma.gif differ
diff --git a/doc/footer.html b/doc/footer.html
new file mode 100644 (file)
index 0000000..410e43f
--- /dev/null
@@ -0,0 +1,9 @@
+<HR>\r
+\r
+<table><tr><td><img src="../ccrma.gif">\r
+  <td>&copy;2001-2002 CCRMA, Stanford University. All Rights Reserved.<br>\r
+  Maintained by Gary P. Scavone, <a href="mailto:gary@ccrma.stanford.edu">gary@ccrma.stanford.edu</a><P>\r
+</table>\r
+\r
+</BODY>\r
+</HTML>
\ No newline at end of file
diff --git a/doc/header.html b/doc/header.html
new file mode 100644 (file)
index 0000000..ab47e24
--- /dev/null
@@ -0,0 +1,9 @@
+<HTML>\r
+<HEAD>\r
+<TITLE>The RtAudio Tutorial</TITLE>\r
+<LINK HREF="doxygen.css" REL="stylesheet" TYPE="text/css">\r
+</HEAD>\r
+<BODY BGCOLOR="#FFFFFF">\r
+<CENTER>\r
+<a class="qindex" href="index.html">Tutorial</a> &nbsp; <a class="qindex" href="annotated.html">Class/Enum List</a> &nbsp; <a class="qindex" href="files.html">File List</a> &nbsp; <a class="qindex" href="functions.html">Compound Members</a> &nbsp; </CENTER>\r
+<HR>
\ No newline at end of file
diff --git a/doc/tutorial.txt b/doc/tutorial.txt
new file mode 100644 (file)
index 0000000..6a3bc98
--- /dev/null
@@ -0,0 +1,628 @@
+/*! \mainpage The RtAudio Tutorial\r
+\r
+<BODY BGCOLOR="white">\r
+\r
+<CENTER>\r
+\ref intro &nbsp;&nbsp; \ref download &nbsp;&nbsp; \ref start &nbsp;&nbsp; \ref error &nbsp;&nbsp; \ref probing &nbsp;&nbsp; \ref settings &nbsp;&nbsp; \ref playbackb &nbsp;&nbsp; \ref playbackc &nbsp;&nbsp; \ref recording &nbsp;&nbsp; \ref duplex &nbsp;&nbsp; \ref methods &nbsp;&nbsp; \ref compiling &nbsp;&nbsp; \ref osnotes &nbsp;&nbsp; \ref acknowledge\r
+</CENTER>\r
+\r
+\section intro Introduction\r
+\r
+RtAudio is a C++ class which provides a common API (Application Programming Interface) for realtime audio input/output across Linux (native ALSA and OSS), SGI, and Windows operating systems.  RtAudio significantly simplifies the process of interacting with computer audio hardware.  It was designed with the following goals:\r
+\r
+<UL>\r
+  <LI>object oriented C++ design</LI>\r
+  <LI>simple, common API across all supported platforms</LI>\r
+  <LI>single independent header and source file for easy inclusion in programming projects (no libraries!)</LI>\r
+  <LI>blocking functionality</LI>\r
+  <LI>callback functionality</LI>\r
+  <LI>extensive audio device parameter control</LI>\r
+  <LI>audio device capability probing</LI>\r
+  <LI>automatic internal conversion for data format, channel number compensation, de-interleaving, and byte-swapping</LI>\r
+  <LI>control over multiple audio streams and devices with a single instance</LI>\r
+</UL>\r
+\r
+RtAudio incorporates the concept of audio streams, which represent audio output (playback) and/or input (recording).  Available audio devices and their capabilities can be enumerated and then specified when opening a stream.  Multiple streams can run at the same time and, when allowed by the underlying audio API, a single device can serve multiple streams.\r
+\r
+The RtAudio API provides both blocking (synchronous) and callback (asynchronous) functionality.  Callbacks are typically used in conjunction with graphical user interfaces (GUI).  Blocking functionality is often necessary for explicit control of multiple input/output stream synchronization or when audio must be synchronized with other system events.\r
+\r
+\section download Download\r
+\r
+Latest Release (22 January 2002): <A href="release/rtaudio-2.0.tgz">Version 2.0 (111 kB tar/gzipped)</A>\r
+\r
+\section start Getting Started\r
+\r
+The first thing that must be done when using RtAudio is to create an instance of the class.  The default constructor RtAudio::RtAudio() scans the underlying audio system to verify that at least one device is available.  RtAudio often uses C++ exceptions to report errors, necessitating try/catch blocks around most member functions.  The following code example demonstrates default object construction and destruction:\r
+\r
+\code\r
+\r
+#include "RtAudio.h"\r
+\r
+int main()\r
+{\r
+  RtAudio *audio;\r
+\r
+  // Default RtAudio constructor\r
+  try {\r
+    audio = new RtAudio();\r
+  }\r
+  catch (RtAudioError &error) {\r
+    // Handle the exception here\r
+  }\r
+\r
+  // Clean up\r
+  delete audio;\r
+}\r
+\endcode\r
+\r
+Obviously, this example doesn't demonstrate any of the real functionality of RtAudio.  However, all uses of RtAudio must begin with a constructor (either default or overloaded varieties) and must end with class destruction.  Further, it is necessary that all class methods which can throw a C++ exception be called within a try/catch block.\r
+\r
+\r
+\section error Error Handling\r
+\r
+RtAudio uses a C++ exception handler called RtAudioError, which is declared and defined within the RtAudio class files.  The RtAudioError class is quite simple but it does allow errors to be "caught" by RtAudioError::TYPE.  Almost all RtAudio methods can "throw" an RtAudioError, most typically if an invalid stream identifier is supplied to a method or a driver error occurs.  There are a number of cases within RtAudio where warning messages may be displayed but an exception is not thrown.  There is a private RtAudio method, error(), which can be modified to globally control how these messages are handled and reported.\r
+\r
+\r
+\section probing Probing Device Capabilities\r
+\r
+A programmer may wish to query the available audio device capabilities before deciding which to use.  The following example outlines how this can be done.\r
+\r
+\code\r
+\r
+// probe.cpp\r
+\r
+#include <iostream.h>\r
+#include "RtAudio.h"\r
+\r
+int main()\r
+{\r
+  RtAudio *audio;\r
+\r
+  // Default RtAudio constructor\r
+  try {\r
+    audio = new RtAudio();\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+    exit(EXIT_FAILURE);\r
+  }\r
+\r
+  // Determine the number of devices available\r
+  int devices = audio->getDeviceCount();\r
+\r
+  // Scan through devices for various capabilities\r
+  RtAudio::RTAUDIO_DEVICE info;\r
+  for (int i=0; i<devices; i++) {\r
+\r
+    try {\r
+      audio->getDeviceInfo(i, &info);\r
+    }\r
+    catch (RtAudioError &error) {\r
+      error.printMessage();\r
+      break;\r
+    }\r
+\r
+    // Print, for example, the maximum number of output channels for each device\r
+    cout << "device = " << i;\r
+    cout << ": maximum output channels = " << info.maxOutputChannels << endl;\r
+  }\r
+\r
+  // Clean up\r
+  delete audio;\r
+\r
+  return 0;\r
+}\r
+\endcode\r
+\r
+The RTAUDIO_DEVICE structure is defined in RtAudio.h and provides a variety of information useful in assessing the capabilities of a device:\r
+\r
+\code\r
+  typedef struct {\r
+    char name[128];\r
+    DEVICE_ID id[2];                      // No value reported by getDeviceInfo().\r
+    bool probed;                          // true if the device probe was successful.\r
+    int maxOutputChannels;\r
+    int maxInputChannels;\r
+    int maxDuplexChannels;\r
+    int minOutputChannels;\r
+    int minInputChannels;\r
+    int minDuplexChannels;\r
+    bool hasDuplexSupport;                // true if duplex supported\r
+    int nSampleRates;                     // Number of discrete rates, or -1 if range supported.\r
+    double sampleRates[MAX_SAMPLE_RATES]; // Supported sample rates, or {min, max} if range.\r
+    RTAUDIO_FORMAT nativeFormats;\r
+  } RTAUDIO_DEVICE;\r
+\endcode\r
+\r
+The following data formats are defined and fully supported by RtAudio:\r
+\r
+\code\r
+  typedef unsigned long RTAUDIO_FORMAT;\r
+  static const RTAUDIO_FORMAT  RTAUDIO_SINT8;   // Signed 8-bit integer\r
+  static const RTAUDIO_FORMAT  RTAUDIO_SINT16;  // Signed 16-bit integer\r
+  static const RTAUDIO_FORMAT  RTAUDIO_SINT24;  // Signed 24-bit integer\r
+  static const RTAUDIO_FORMAT  RTAUDIO_SINT32;  // Signed 32-bit integer\r
+  static const RTAUDIO_FORMAT  RTAUDIO_FLOAT32; // 32-bit float\r
+  static const RTAUDIO_FORMAT  RTAUDIO_FLOAT64; // 64-bit double\r
+\endcode\r
+\r
+The <I>nativeFormats</I> member of the RtAudio::RTAUDIO_DEVICE structure is a bit mask of the above formats which are natively supported by the device.  However, RtAudio will automatically provide format conversion if a particular format is not natively supported.  When the <I>probed</I> member of the RTAUDIO_DEVICE structure is false, the remaining structure members are likely unknown and the device is probably unusable.\r
+\r
+In general, the user need not be concerned with the minimum channel values reported in the RTAUDIO_DEVICE structure.  While some audio devices may require a minimum channel value > 1, RtAudio will provide automatic channel number compensation when the number of channels set by the user is less than that required by the device.  Channel compensation is <I>NOT</I> possible when the number of channels set by the user is greater than that supported by the device.\r
+\r
+It should be noted that the capabilities reported by a device driver or underlying audio API are not always accurate and/or may be dependent on a combination of device settings.\r
+\r
+\r
+\section settings Device Settings\r
+\r
+The next step in using RtAudio is to open a stream with a particular set of device settings.\r
+\r
+\code\r
+\r
+#include "RtAudio.h"\r
+\r
+int main()\r
+{\r
+  int channels = 2;\r
+  int sample_rate = 44100;\r
+  int buffer_size = 256;  // 256 sample frames\r
+  int n_buffers = 4;      // number of internal buffers used by device\r
+  int device = 0;         // 0 indicates the default or first available device\r
+  int stream;             // our stream identifier\r
+  RtAudio *audio;\r
+\r
+  // Instantiate RtAudio and open a stream within a try/catch block\r
+  try {\r
+    audio = new RtAudio();\r
+    stream = audio->openStream(device, channels, 0, 0, RtAudio::RTAUDIO_FLOAT32,\r
+                               sample_rate, &buffer_size, n_buffers);\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+    exit(EXIT_FAILURE);\r
+  }\r
+\r
+  // Clean up\r
+  delete audio;\r
+\r
+  return 0;\r
+}\r
+\endcode\r
+\r
+The RtAudio::openStream() method attempts to open a stream with a specified set of parameter values.  When successful, a stream identifier is returned.  In this case, we attempt to open a playback stream on device 0 with two channels, 32-bit floating point data, a sample rate of 44100 Hz, a frame rate of 256 sample frames per read/write, and 4 internal device buffers.  When device = 0, RtAudio first attempts to open the default audio device with the given parameters.  If that attempt fails, an attempt is made to find a device or set of devices which will meet the given parameters.  If all attempts are unsuccessful, an RtAudioError is thrown.  When a non-zero device value is specified, an attempt is made to open that device only.\r
+\r
+RtAudio provides four signed integer and two floating point data formats which can be specified using the RtAudio::RTAUDIO_FORMAT parameter values mentioned earlier.  If the opened device does not natively support the given format, RtAudio will automatically perform the necessary data format conversion.\r
+\r
+Buffer sizes in RtAudio are <I>ALWAYS</I> given in sample frame units.  For example, if you open an output stream with 4 channels and set <I>bufferSize</I> to 512, you will have to write 2048 samples of data to the output buffer within your callback or between calls to RtAudio::tickStream().  In this case, a single sample frame of data contains 4 samples of data. \r
+\r
+The <I>bufferSize</I> parameter specifies the desired number of sample frames which will be written to and/or read from a device per write/read operation.  The <I>nBuffers</I> parameter is used in setting the underlying device buffer parameters.  Both the <I>bufferSize</I> and <I>nBuffers</I> parameters can be used to control stream latency though there is no guarantee that the passed values will be those used by a device.  In general, lower values for both parameters will produce less latency but perhaps less robust performance.  Both parameters can be specified with values of zero, in which case the smallest allowable values will be used.  The <I>bufferSize</I> parameter is passed as a pointer and the actual value used by the stream is set during the device setup procedure.  <I>bufferSize</I> values should be a power of two.  Optimal and allowable buffer values tend to vary between systems and devices.  Check the \ref osnotes section for general guidelines.\r
+\r
+As noted earlier, the device capabilities reported by a driver or underlying audio API are not always accurate and/or may be dependent on a combination of device settings.  Because of this, RtAudio does not attempt to query a device's capabilities or use previously reported values when opening a device.  Instead, RtAudio simply attempts to set the given parameters on a specified device and then checks whether the setup is successful or not.\r
+\r
+\r
+\section playbackb Playback (blocking functionality)\r
+\r
+Once the device is open for playback, there are only a few final steps necessary for realtime audio output.  We'll first provide an example (blocking functionality) and then discuss the details.\r
+\r
+\code\r
+// playback.cpp\r
+\r
+#include "RtAudio.h"\r
+\r
+int main()\r
+{\r
+  int count;\r
+  int channels = 2;\r
+  int sample_rate = 44100;\r
+  int buffer_size = 256;  // 256 sample frames\r
+  int n_buffers = 4;      // number of internal buffers used by device\r
+  float *buffer;\r
+  int device = 0;         // 0 indicates the default or first available device\r
+  int stream;             // our stream identifier\r
+  RtAudio *audio;\r
+\r
+  // Open a stream during RtAudio instantiation\r
+  try {\r
+    audio = new RtAudio(&stream, device, channels, 0, 0, RtAudio::RTAUDIO_FLOAT32,\r
+                        sample_rate, &buffer_size, n_buffers);\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+    exit(EXIT_FAILURE);\r
+  }\r
+\r
+  try {\r
+    // Get a pointer to the stream buffer\r
+    buffer = (float *) audio->getStreamBuffer(stream);\r
+\r
+    // Start the stream\r
+    audio->startStream(stream);\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+    goto cleanup;\r
+  }\r
+\r
+  // An example loop which runs for about 40000 sample frames\r
+  count = 0;\r
+  while (count < 40000) {\r
+    // Generate your samples and fill the buffer with buffer_size sample frames of data\r
+    ...\r
+\r
+    // Trigger the output of the data buffer\r
+    try {\r
+      audio->tickStream(stream);\r
+    }\r
+    catch (RtAudioError &error) {\r
+      error.printMessage();\r
+      goto cleanup;\r
+    }\r
+\r
+    count += buffer_size;\r
+  }\r
+\r
+  try {\r
+    // Stop and close the stream\r
+    audio->stopStream(stream);\r
+    audio->closeStream(stream);\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+  }\r
+\r
+ cleanup:\r
+  delete audio;\r
+\r
+  return 0;\r
+}\r
+\endcode\r
+\r
+The first thing to notice in this example is that we attempt to open a stream during class instantiation with an overloaded constructor.  This constructor simply combines the functionality of the default constructor, used earlier, and the RtAudio::openStream() method.  Again, we have specified a device value of 0, indicating that the default or first available device meeting the given parameters should be used.  The integer identifier of the opened stream is returned via the <I>stream</I> pointer value.  An attempt is made to open the stream with the specified <I>bufferSize</I> value.  However, it is possible that the device will not accept this value, in which case the closest allowable size is used and returned via the pointer value.   The constructor can fail if no available devices are found, or a memory allocation or device driver error occurs.  Note that you should not call the RtAudio destructor if an exception is thrown during instantiation.\r
+\r
+Because RtAudio can be used to simultaneously control more than a single stream, it is necessary that the stream identifier be provided to nearly all public methods.  Assuming the constructor is successful, it is necessary to get a pointer to the buffer, provided by RtAudio, for use in feeding data to/from the opened stream.  Note that the user should <I>NOT</I> attempt to deallocate the stream buffer memory ... memory management for the stream buffer will be automatically controlled by RtAudio.  After starting the stream with RtAudio::startStream(), one simply fills that buffer, which is of length equal to the returned <I>bufferSize</I> value, with interleaved audio data (in the specified format) for playback.  Finally, a call to the RtAudio::tickStream() routine triggers a blocking write call for the stream.\r
+\r
+In general, one should call the RtAudio::stopStream() and RtAudio::closeStream() methods after finishing with a stream.  However, both methods will implicitly be called during object destruction if necessary.\r
+\r
+\r
+\section playbackc Playback (callback functionality)\r
+\r
+The primary difference in using RtAudio with callback functionality involves the creation of a user-defined callback function.  Here is an example which produces a sawtooth waveform for playback.\r
+\r
+\code\r
+\r
+#include <iostream.h>\r
+#include "RtAudio.h"\r
+\r
+// Two-channel sawtooth wave generator.\r
+int sawtooth(char *buffer, int buffer_size, void *data)\r
+{\r
+  int i, j;\r
+  double *my_buffer = (double *) buffer;\r
+  double *my_data = (double *) data;\r
+\r
+  // Write interleaved audio data.\r
+  for (i=0; i<buffer_size; i++) {\r
+    for (j=0; j<2; j++) {\r
+      *my_buffer++ = my_data[j];\r
+\r
+      my_data[j] += 0.005 * (j+1+(j*0.1));\r
+      if (my_data[j] >= 1.0) my_data[j] -= 2.0;\r
+    }\r
+  }\r
+\r
+  return 0;\r
+}\r
+\r
+int main()\r
+{\r
+  int channels = 2;\r
+  int sample_rate = 44100;\r
+  int buffer_size = 256;  // 256 sample frames\r
+  int n_buffers = 4;      // number of internal buffers used by device\r
+  int device = 0;         // 0 indicates the default or first available device\r
+  int stream;             // our stream identifier\r
+  double data[2];\r
+  char input;\r
+  RtAudio *audio;\r
+\r
+  // Open a stream during RtAudio instantiation\r
+  try {\r
+    audio = new RtAudio(&stream, device, channels, 0, 0, RtAudio::RTAUDIO_FLOAT64,\r
+                        sample_rate, &buffer_size, n_buffers);\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+    exit(EXIT_FAILURE);\r
+  }\r
+\r
+  try {\r
+    // Set the stream callback function\r
+    audio->setStreamCallback(stream, &sawtooth, (void *)data);\r
+\r
+    // Start the stream\r
+    audio->startStream(stream);\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+    goto cleanup;\r
+  }\r
+\r
+  cout << "\nPlaying ... press <enter> to quit.\n";\r
+  cin.get(input);\r
+\r
+  try {\r
+    // Stop and close the stream\r
+    audio->stopStream(stream);\r
+    audio->closeStream(stream);\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+  }\r
+\r
+ cleanup:\r
+  delete audio;\r
+\r
+  return 0;\r
+}\r
+\endcode\r
+\r
+After opening the device in exactly the same way as the previous example (except with a data format change), we must set our callback function for the stream using RtAudio::setStreamCallback().  This method will spawn a new process (or thread) which automatically calls the callback function when more data is needed.  Note that the callback function is called only when the stream is "running" (between calls to the RtAudio::startStream() and RtAudio::stopStream() methods).  The last argument to RtAudio::setStreamCallback() is a pointer to arbitrary data that you wish to access from within your callback function.\r
+\r
+In this example, we stop the stream with an explicit call to RtAudio::stopStream().  When using callback functionality, it is also possible to stop a stream by returning a non-zero value from the callback function.\r
+\r
+Once set with RtAudio::setStreamCallback, the callback process will continue to run for the life of the stream (until the stream is closed with RtAudio::closeStream() or the RtAudio instance is deleted).  It is possible to disassociate a callback function and cancel its process for an open stream using the RtAudio::cancelStreamCallback() method.  The stream can then be used with blocking functionality or a new callback can be associated with it.\r
+\r
+\r
+\section recording Recording\r
+\r
+Using RtAudio for audio input is almost identical to the way it is used for playback.  Here's the blocking playback example rewritten for recording:\r
+\r
+\code\r
+// record.cpp\r
+\r
+#include "RtAudio.h"\r
+\r
+int main()\r
+{\r
+  int count;\r
+  int channels = 2;\r
+  int sample_rate = 44100;\r
+  int buffer_size = 256;  // 256 sample frames\r
+  int n_buffers = 4;      // number of internal buffers used by device\r
+  float *buffer;\r
+  int device = 0;         // 0 indicates the default or first available device\r
+  int stream;             // our stream identifier\r
+  RtAudio *audio;\r
+\r
+  // Instantiate RtAudio and open a stream.\r
+  try {\r
+    audio = new RtAudio(&stream, 0, 0, device, channels,\r
+                        RtAudio::RTAUDIO_FLOAT32, sample_rate, &buffer_size, n_buffers);\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+    exit(EXIT_FAILURE);\r
+  }\r
+\r
+  try {\r
+    // Get a pointer to the stream buffer\r
+    buffer = (float *) audio->getStreamBuffer(stream);\r
+\r
+    // Start the stream\r
+    audio->startStream(stream);\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+    goto cleanup;\r
+  }\r
+\r
+  // An example loop which runs for about 40000 sample frames\r
+  count = 0;\r
+  while (count < 40000) {\r
+\r
+    // Read a buffer of data\r
+    try {\r
+      audio->tickStream(stream);\r
+    }\r
+    catch (RtAudioError &error) {\r
+      error.printMessage();\r
+      goto cleanup;\r
+    }\r
+\r
+    // Process the input samples (buffer_size sample frames) that were read\r
+    ...\r
+\r
+    count += buffer_size;\r
+  }\r
+\r
+  try {\r
+    // Stop the stream\r
+    audio->stopStream(stream);\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+  }\r
+\r
+ cleanup:\r
+  delete audio;\r
+\r
+  return 0;\r
+}\r
+\endcode\r
+\r
+In this example, the stream was opened for recording with a non-zero <I>inputChannels</I> value.  The only other difference between this example and that for playback involves the order of data processing in the loop, where it is necessary to first read a buffer of input data before manipulating it.\r
+\r
+\r
+\section duplex Duplex Mode\r
+\r
+Finally, it is easy to use RtAudio for simultaneous audio input/output, or duplex operation.  In this example, we use a callback function and pass our recorded data directly through for playback.\r
+\r
+\code\r
+// duplex.cpp\r
+\r
+#include <iostream.h>\r
+#include "RtAudio.h"\r
+\r
+// Pass-through function.\r
+int pass(char *buffer, int buffer_size, void *)\r
+{\r
+  // Surprise!!  We do nothing to pass the data through.\r
+  return 0;\r
+}\r
+\r
+int main()\r
+{\r
+  int channels = 2;\r
+  int sample_rate = 44100;\r
+  int buffer_size = 256;  // 256 sample frames\r
+  int n_buffers = 4;      // number of internal buffers used by device\r
+  int device = 0;         // 0 indicates the default or first available device\r
+  int stream;             // our stream identifier\r
+  double data[2];\r
+  char input;\r
+  RtAudio *audio;\r
+\r
+  // Open a stream during RtAudio instantiation\r
+  try {\r
+    audio = new RtAudio(&stream, device, channels, device, channels, RtAudio::RTAUDIO_FLOAT64,\r
+                        sample_rate, &buffer_size, n_buffers);\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+    exit(EXIT_FAILURE);\r
+  }\r
+\r
+  try {\r
+    // Set the stream callback function\r
+    audio->setStreamCallback(stream, &pass, NULL);\r
+\r
+    // Start the stream\r
+    audio->startStream(stream);\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+    goto cleanup;\r
+  }\r
+\r
+  cout << "\nRunning duplex ... press <enter> to quit.\n";\r
+  cin.get(input);\r
+\r
+  try {\r
+    // Stop and close the stream\r
+    audio->stopStream(stream);\r
+    audio->closeStream(stream);\r
+  }\r
+  catch (RtAudioError &error) {\r
+    error.printMessage();\r
+  }\r
+\r
+ cleanup:\r
+  delete audio;\r
+\r
+  return 0;\r
+}\r
+\endcode\r
+\r
+When an RtAudio stream is running in duplex mode (nonzero input <I>AND</I> output channels), the audio write (playback) operation always occurs before the audio read (record) operation.  This sequence allows the use of a single buffer to store both output and input data.\r
+\r
+As we see with this example, the write-read sequence of operations does not preclude the use of RtAudio in situations where input data is first processed and then output through a duplex stream.  When the stream buffer is first allocated, it is initialized with zeros, which produces no audible result when output to the device.  In this example, anything recorded by the audio stream input will be played out during the next round of audio processing.\r
+\r
+Note that duplex operation can also be achieved by opening one output stream and one input stream using the same or different devices.  However, there may be timing problems when attempting to use two different devices, due to possible device clock variations.  This becomes even more difficult to achieve using two separate callback streams because it is not possible to explicitly control the calling order of the callback functions.\r
+\r
+\r
+\section methods Summary of Methods\r
+\r
+The following is short summary of public methods (not including constructors and the destructor) provided by RtAudio:\r
+\r
+<UL>\r
+<LI>RtAudio::openStream(): opens a stream with the specified parameters.</LI>\r
+<LI>RtAudio::setStreamCallback(): sets a user-defined callback function for a given stream.</LI>\r
+<LI>RtAudio::cancelStreamCallback(): cancels a callback process and function for a given stream.</LI>\r
+<LI>RtAudio::getDeviceCount(): returns the number of audio devices available.</LI>\r
+<LI>RtAudio::getDeviceInfo(): fills a user-supplied RTAUDIO_DEVICE structure for a specified device.</LI>\r
+<LI>RtAudio::getStreamBuffer(): returns a pointer to the stream buffer.</LI>\r
+<LI>RtAudio::tickStream(): triggers processing of input/output data for a stream (blocking).</LI>\r
+<LI>RtAudio::closeStream(): closes the specified stream (implicitly called during object destruction).  Once a stream is closed, the stream identifier is invalid and should not be used in calling any other RtAudio methods.</LI>\r
+<LI>RtAudio::startStream(): (re)starts the specified stream, typically after it has been stopped with either stopStream() or abortStream() or after first opening the stream.</LI>\r
+<LI>RtAudio::stopStream(): stops the specified stream, allowing any remaining samples in the queue to be played out and/or read in.  This does not implicitly call RtAudio::closeStream().</LI>\r
+<LI>RtAudio::abortStream(): stops the specified stream, discarding any remaining samples in the queue.  This does not implicitly call closeStream().</LI>\r
+<LI>RtAudio::streamWillBlock(): queries a stream to determine whether a call to the <I>tickStream()</I> method will block.  A return value of 0 indicates that the stream will NOT block.  A positive return value indicates the  number of sample frames that cannot yet be processed without blocking.</LI>\r
+</UL>\r
+\r
+\r
+\section compiling Compiling\r
+\r
+In order to compile RtAudio for a specific OS and audio API, it is necessary to supply the appropriate preprocessor definition and library within the compiler statement:\r
+<P>\r
+\r
+<TABLE BORDER=2 COLS=5 WIDTH="100%">\r
+<TR BGCOLOR="beige">\r
+  <TD WIDTH="5%"><B>OS:</B></TD>\r
+  <TD WIDTH="5%"><B>Audio API:</B></TD>\r
+  <TD WIDTH="5%"><B>Preprocessor Definition:</B></TD>\r
+  <TD WIDTH="5%"><B>Library:</B></TD>\r
+  <TD><B>Example Compiler Statement:</B></TD>\r
+</TR>\r
+<TR>\r
+  <TD>Linux</TD>\r
+  <TD>ALSA</TD>\r
+  <TD>__LINUX_ALSA_</TD>\r
+  <TD><TT>libasound, libpthread</TT></TD>\r
+  <TD><TT>g++ -Wall -D__LINUX_ALSA_ -o probe probe.cpp RtAudio.cpp -lasound -lpthread</TT></TD>\r
+</TR>\r
+<TR>\r
+  <TD>Linux</TD>\r
+  <TD>OSS</TD>\r
+  <TD>__LINUX_OSS_</TD>\r
+  <TD><TT>libpthread</TT></TD>\r
+  <TD><TT>g++ -Wall -D__LINUX_OSS_ -o probe probe.cpp RtAudio.cpp -lpthread</TT></TD>\r
+</TR>\r
+<TR>\r
+  <TD>Irix</TD>\r
+  <TD>AL</TD>\r
+  <TD>__IRIX_AL_</TD>\r
+  <TD><TT>libaudio, libpthread</TT></TD>\r
+  <TD><TT>CC -Wall -D__IRIX_AL_ -o probe probe.cpp RtAudio.cpp -laudio -lpthread</TT></TD>\r
+</TR>\r
+<TR>\r
+  <TD>Windows</TD>\r
+  <TD>Direct Sound</TD>\r
+  <TD>__WINDOWS_DS_</TD>\r
+  <TD><TT>dsound.lib (ver. 5.0 or higher), multithreaded</TT></TD>\r
+  <TD><I>compiler specific</I></TD>\r
+</TR>\r
+</TABLE>\r
+<P>\r
+\r
+The example compiler statements above could be used to compile the <TT>probe.cpp</TT> example file, assuming that <TT>probe.cpp</TT>, <TT>RtAudio.h</TT>, and <TT>RtAudio.cpp</TT> all exist in the same directory.\r
+\r
+\section osnotes OS Notes\r
+\r
+RtAudio is designed to provide a common API across the various supported operating systems and audio libraries.  Despite that, however, some issues need to be mentioned with regard to each.\r
+\r
+\subsection linux Linux:\r
+\r
+RtAudio for Linux was developed under Redhat distributions 7.0 - 7.2.  Two different audio APIs are supported on Linux platforms: OSS and <A href="http://www.alsa-project.org/">ALSA</A>.  The OSS API has existed for at least 6 years and the Linux kernel is distributed with free versions of OSS audio drivers.  Therefore, a generic Linux system is most likely to have OSS support.  The ALSA API is relatively new and at this time is not part of the Linux kernel distribution.  Work is in progress to make ALSA part of the 2.5 development kernel series.  Despite that, the ALSA API offers significantly better functionality than the OSS API.  RtAudio provides support for the 0.9 and higher versions of ALSA.  Input/output latency on the order of 15-20 milliseconds can typically be achieved under both OSS or ALSA by fine-tuning the RtAudio buffer parameters (without kernel modifications).  Latencies on the order of 5 milliseconds or less can be achieved using a low-latency kernel patch and increasing FIFO scheduling priority.  The pthread library, which is used for callback functionality, is a standard component of all Linux distributions.\r
+\r
+The ALSA library includes OSS emulation support.  That means that you can run programs compiled for the OSS API even when using the ALSA drivers and library.  It should be noted however that OSS emulation under ALSA is not perfect.  Specifically, channel number queries seem to consistently produce invalid results.  While OSS emulation is successful for the majority of RtAudio tests, it is recommended that the native ALSA implementation of RtAudio be used on systems which have ALSA drivers installed.\r
+\r
+The ALSA implementation of RtAudio makes no use of the ALSA "plug" interface.  All necessary data format conversions, channel compensation, deinterleaving, and byte-swapping is handled by internal RtAudio routines.\r
+\r
+\subsection irix Irix (SGI):\r
+\r
+The Irix version of RtAudio was written and tested on an SGI Indy running Irix version 6.5 and the newer "al" audio library.  RtAudio does not compile under Irix version 6.3 because the C++ compiler is too old.  Despite the relatively slow speed of the Indy, RtAudio was found to behave quite well and input/output latency was very good.  No problems were found with respect to using the pthread library.\r
+\r
+\subsection windows Windows:\r
+\r
+RtAudio under Windows is written using the DirectSound API.  In order to compile RtAudio under Windows, you must have the header and source files for DirectSound version 0.5 or higher.  As far as I know, you cannot compile RtAudio for Windows NT because there is not sufficient DirectSound support.  Audio output latency with DirectSound can be reasonably good (on the order of 20 milliseconds).  On the other hand, input audio latency tends to be terrible (100 milliseconds or more).  Further, DirectSound drivers tend to crash easily when experimenting with buffer parameters.  On my system, I found it necessary to use values around nBuffers = 8 and bufferSize = 512 to avoid crashing my system.  RtAudio was developed with Visual C++ version 6.0.  I was forced in several instances to modify code in order to get it to compile under the non-standard version of C++ that Microsoft so unprofessionally implemented.  We can only hope that the developers of Visual C++ 7.0 will have time to read the C++ standard. \r
+\r
+\r
+\section acknowledge Acknowledgments\r
+\r
+The RtAudio API incorporates many of the concepts developed in the <A href="http://www.portaudio.com/">PortAudio</A> project by Phil Burk and Ross Bencina.  Early development also incorporated ideas from Bill Schottstaedt's <A href="http://www-ccrma.stanford.edu/software/snd/sndlib/">sndlib</A>.  The CCRMA <A href="http://www-ccrma.stanford.edu/groups/soundwire/">SoundWire group</A> provided valuable feedback during the API proposal stages.\r
+\r
+RtAudio was slowly developed over the course of many months while in residence at the <A href="http://www.iua.upf.es/">Institut Universitari de L'Audiovisual (IUA)</A> in Barcelona, Spain, the <A href="http://www.acoustics.hut.fi/">Laboratory of Acoustics and Audio Signal Processing</A> at the Helsinki University of Technology, Finland, and the <A href="http://www-ccrma.stanford.edu/">Center for Computer Research in Music and Acoustics (CCRMA)</A> at <A href="http://www.stanford.edu/">Stanford University</A>.  This work was supported in part by the United States Air Force Office of Scientific Research (grant \#F49620-99-1-0293).\r
+\r
+These documentation files were generated using <A href="http://www.doxygen.org/">doxygen</A> by Dimitri van Heesch.\r
+\r
+*/\r
diff --git a/rtaudio.dsw b/rtaudio.dsw
new file mode 100644 (file)
index 0000000..2d6a46c
--- /dev/null
@@ -0,0 +1,125 @@
+Microsoft Developer Studio Workspace File, Format Version 6.00\r
+# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!\r
+\r
+###############################################################################\r
+\r
+Project: "call_inout"=.\tests\call_inout.dsp - Package Owner=<4>\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<4>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
+Project: "call_saw"=.\tests\call_saw.dsp - Package Owner=<4>\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<4>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
+Project: "call_twostreams"=.\tests\call_twostreams.dsp - Package Owner=<4>\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<4>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
+Project: "in_out"=.\tests\in_out.dsp - Package Owner=<4>\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<4>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
+Project: "info"=.\tests\info.dsp - Package Owner=<4>\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<4>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
+Project: "play_raw"=.\tests\play_raw.dsp - Package Owner=<4>\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<4>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
+Project: "play_saw"=.\tests\play_saw.dsp - Package Owner=<4>\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<4>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
+Project: "record_raw"=.\tests\record_raw.dsp - Package Owner=<4>\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<4>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
+Project: "twostreams"=.\tests\twostreams.dsp - Package Owner=<4>\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<4>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
+Global:\r
+\r
+Package=<5>\r
+{{{\r
+}}}\r
+\r
+Package=<3>\r
+{{{\r
+}}}\r
+\r
+###############################################################################\r
+\r
diff --git a/tests/Debug/.placeholder b/tests/Debug/.placeholder
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/tests/Makefile b/tests/Makefile
new file mode 100644 (file)
index 0000000..2f69c73
--- /dev/null
@@ -0,0 +1,58 @@
+
+OS = $(shell uname)
+
+RM = /bin/rm
+
+ifeq ($(OS),Linux) # These are for Linux
+       INSTR = info play_saw record_raw in_out play_raw twostreams call_saw call_inout call_twostreams
+       CC = g++ -Wall -D__LINUX_OSS_# -g -pg -O3
+       LIBRARY = -lpthread
+#      CC = g++ -g -Wall -D__LINUX_ALSA_ # -g -pg -O3
+#      LIBRARY = -lpthread -lasound
+       INCLUDE = -I../
+endif
+
+ifeq ($(OS),IRIX) # These are for SGI
+       INSTR = info play_saw record_raw in_out play_raw twostreams call_saw call_inout call_twostreams
+       CC = CC -D__IRIX_AL_ # -g -fullwarn -D__SGI_CC__ -O2
+       LIBRARY = -laudio -lpthread
+       INCLUDE = -I../
+endif
+
+all: $(INSTR)
+
+clean :
+       rm $(INSTR) *~ *.raw core *.o 
+
+cleanIns : 
+       rm $(INSTR)
+
+strip : 
+       strip $(INSTR)
+
+info: info.cpp ../RtAudio.cpp ../RtAudio.h
+       $(CC) -o info info.cpp ../RtAudio.cpp $(LIBRARY) $(INCLUDE)
+
+play_saw: play_saw.cpp ../RtAudio.cpp ../RtAudio.h
+       $(CC) -o play_saw play_saw.cpp ../RtAudio.cpp $(LIBRARY) $(INCLUDE)
+
+play_raw: play_raw.cpp ../RtAudio.cpp ../RtAudio.h
+       $(CC) -o play_raw play_raw.cpp ../RtAudio.cpp $(LIBRARY) $(INCLUDE)
+
+record_raw: record_raw.cpp ../RtAudio.cpp ../RtAudio.h
+       $(CC) -o record_raw record_raw.cpp ../RtAudio.cpp $(LIBRARY) $(INCLUDE)
+
+in_out: in_out.cpp ../RtAudio.cpp ../RtAudio.h
+       $(CC) -o in_out in_out.cpp ../RtAudio.cpp $(LIBRARY) $(INCLUDE)
+
+twostreams: twostreams.cpp ../RtAudio.cpp ../RtAudio.h
+       $(CC) -o twostreams twostreams.cpp ../RtAudio.cpp $(LIBRARY) $(INCLUDE)
+
+call_saw: call_saw.cpp ../RtAudio.cpp ../RtAudio.h
+       $(CC) -o call_saw call_saw.cpp ../RtAudio.cpp $(LIBRARY) $(INCLUDE)
+
+call_inout: call_inout.cpp ../RtAudio.cpp ../RtAudio.h
+       $(CC) -o call_inout call_inout.cpp ../RtAudio.cpp $(LIBRARY) $(INCLUDE)
+
+call_twostreams: call_twostreams.cpp ../RtAudio.cpp ../RtAudio.h
+       $(CC) -o call_twostreams call_twostreams.cpp ../RtAudio.cpp $(LIBRARY) $(INCLUDE)
\ No newline at end of file
diff --git a/tests/Release/.placeholder b/tests/Release/.placeholder
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/tests/call_inout.cpp b/tests/call_inout.cpp
new file mode 100644 (file)
index 0000000..c4ae167
--- /dev/null
@@ -0,0 +1,100 @@
+/******************************************/
+/*
+  call_inout.c
+  by Gary P. Scavone, 2001
+
+  Records from default input and passes it
+  through to the output.  Takes number of
+  channels and sample rate as input arguments.
+  Uses callback functionality.
+*/
+/******************************************/
+
+#include "RtAudio.h"
+#include <iostream.h>
+
+/*
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT24
+
+typedef char  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT8
+
+typedef signed short  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT16
+
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT32
+
+typedef float  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT32
+*/
+
+typedef double  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT64
+
+void usage(void) {
+  /* Error function in case of incorrect command-line
+     argument specifications
+  */
+  cout << "\nuseage: call_inout N fs\n";
+  cout << "    where N = number of channels,\n";
+  cout << "    and fs = the sample rate.\n\n";
+  exit(0);
+}
+
+int inout(char *buffer, int buffer_size, void *)
+{
+  // Surprise!!  We do nothing to pass the data through.
+  return 0;
+}
+
+int main(int argc, char *argv[])
+{
+  int device, stream, chans, fs;
+  RtAudio *audio;
+  char input;
+
+  // minimal command-line checking
+  if (argc != 3) usage();
+
+  chans = (int) atoi(argv[1]);
+  fs = (int) atoi(argv[2]);
+
+  // Open the realtime output device
+  int buffer_size = 512;
+  device = 0; // default device
+  try {
+    audio = new RtAudio(&stream, device, chans, device, chans,
+                        FORMAT, fs, &buffer_size, 8);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    exit(EXIT_FAILURE);
+  }
+
+  try {
+    audio->setStreamCallback(stream, &inout, NULL);
+    audio->startStream(stream);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  cout << "\nRunning ... press <enter> to quit.\n";
+  cin.get(input);
+
+  try {
+    audio->stopStream(stream);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+  }
+
+ cleanup:
+  audio->closeStream(stream);
+  delete audio;
+
+  return 0;
+}
diff --git a/tests/call_inout.dsp b/tests/call_inout.dsp
new file mode 100644 (file)
index 0000000..9aac77e
--- /dev/null
@@ -0,0 +1,110 @@
+# Microsoft Developer Studio Project File - Name="call_inout" - Package Owner=<4>\r
+# Microsoft Developer Studio Generated Build File, Format Version 6.00\r
+# ** DO NOT EDIT **\r
+\r
+# TARGTYPE "Win32 (x86) Console Application" 0x0103\r
+\r
+CFG=call_inout - Win32 Debug\r
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r
+!MESSAGE use the Export Makefile command and run\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "call_inout.mak".\r
+!MESSAGE \r
+!MESSAGE You can specify a configuration when running NMAKE\r
+!MESSAGE by defining the macro CFG on the command line. For example:\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "call_inout.mak" CFG="call_inout - Win32 Debug"\r
+!MESSAGE \r
+!MESSAGE Possible choices for configuration are:\r
+!MESSAGE \r
+!MESSAGE "call_inout - Win32 Release" (based on "Win32 (x86) Console Application")\r
+!MESSAGE "call_inout - Win32 Debug" (based on "Win32 (x86) Console Application")\r
+!MESSAGE \r
+\r
+# Begin Project\r
+# PROP AllowPerConfigDependencies 0\r
+# PROP Scc_ProjName ""\r
+# PROP Scc_LocalPath ""\r
+CPP=cl.exe\r
+RSC=rc.exe\r
+\r
+!IF  "$(CFG)" == "call_inout - Win32 Release"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 0\r
+# PROP BASE Output_Dir "call_inout___Win32_Release"\r
+# PROP BASE Intermediate_Dir "call_inout___Win32_Release"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 0\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Release"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
+# ADD CPP /nologo /MT /W3 /GX /O2 /I "../" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /c\r
+# ADD BASE RSC /l 0x409 /d "NDEBUG"\r
+# ADD RSC /l 0x409 /d "NDEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /machine:I386\r
+\r
+!ELSEIF  "$(CFG)" == "call_inout - Win32 Debug"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 1\r
+# PROP BASE Output_Dir "call_inout___Win32_Debug"\r
+# PROP BASE Intermediate_Dir "call_inout___Win32_Debug"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 1\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Debug"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ  /c\r
+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /GZ  /c\r
+# ADD BASE RSC /l 0x409 /d "_DEBUG"\r
+# ADD RSC /l 0x409 /d "_DEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+\r
+!ENDIF \r
+\r
+# Begin Target\r
+\r
+# Name "call_inout - Win32 Release"\r
+# Name "call_inout - Win32 Debug"\r
+# Begin Group "Source Files"\r
+\r
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"\r
+# Begin Source File\r
+\r
+SOURCE=.\call_inout.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.cpp\r
+# End Source File\r
+# End Group\r
+# Begin Group "Header Files"\r
+\r
+# PROP Default_Filter "h;hpp;hxx;hm;inl"\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.h\r
+# End Source File\r
+# End Group\r
+# Begin Group "Resource Files"\r
+\r
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+# End Group\r
+# End Target\r
+# End Project\r
diff --git a/tests/call_saw.cpp b/tests/call_saw.cpp
new file mode 100644 (file)
index 0000000..cb5509d
--- /dev/null
@@ -0,0 +1,128 @@
+/******************************************/
+/*
+  call_saw.c
+  by Gary P. Scavone, 2001
+
+  Play sawtooth waveforms of distinct frequency.
+  Takes number of channels and sample rate as
+  input arguments.  Use callback functionality.
+*/
+/******************************************/
+
+#include "RtAudio.h"
+#include <iostream.h>
+
+/*
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT24
+#define SCALE  2147483647.0
+
+typedef char  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT8
+#define SCALE  127.0
+
+typedef signed short  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT16
+#define SCALE  32767.0
+
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT32
+#define SCALE  2147483647.0
+*/
+typedef float  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT32
+#define SCALE  1.0
+
+/*
+typedef double  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT64
+#define SCALE  1.0
+*/
+
+#define BASE_RATE 0.005
+#define TIME   1.0
+
+void usage(void) {
+  /* Error function in case of incorrect command-line
+     argument specifications
+  */
+  cout << "\nuseage: call_saw N fs\n";
+  cout << "    where N = number of channels,\n";
+  cout << "    and fs = the sample rate.\n\n";
+  exit(0);
+}
+
+int chans;
+
+int saw(char *buffer, int buffer_size, void *data)
+{
+  int i, j;
+  extern int chans;
+  MY_TYPE *my_buffer = (MY_TYPE *) buffer;
+  double *my_data = (double *) data;
+
+  for (i=0; i<buffer_size; i++) {
+    for (j=0; j<chans; j++) {
+      *my_buffer++ = (MY_TYPE) (my_data[j] * SCALE);
+      my_data[j] += BASE_RATE * (j+1+(j*0.1));
+      if (my_data[j] >= 1.0) my_data[j] -= 2.0;
+    }
+  }
+
+  return 0;
+}
+
+int main(int argc, char *argv[])
+{
+  int device, stream, buffer_size, fs;
+  RtAudio *audio;
+  double *data;
+  char input;
+
+  // minimal command-line checking
+  if (argc != 3) usage();
+
+  chans = (int) atoi(argv[1]);
+  fs = (int) atoi(argv[2]);
+
+  // Open the realtime output device
+  buffer_size = 256;
+  device = 0; // default device
+  try {
+    audio = new RtAudio(&stream, device, chans, 0, 0,
+                        FORMAT, fs, &buffer_size, 4);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    exit(EXIT_FAILURE);
+  }
+
+  data = (double *) calloc(chans, sizeof(double));
+
+  try {
+    audio->setStreamCallback(stream, &saw, (void *)data);
+    audio->startStream(stream);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  cout << "\nPlaying ... press <enter> to quit.\n";
+  cin.get(input);
+
+  // Stop the stream.
+  try {
+    audio->stopStream(stream);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+  }
+
+ cleanup:
+  audio->closeStream(stream);
+  delete audio;
+  if (data) free(data);
+
+  return 0;
+}
diff --git a/tests/call_saw.dsp b/tests/call_saw.dsp
new file mode 100644 (file)
index 0000000..344989b
--- /dev/null
@@ -0,0 +1,110 @@
+# Microsoft Developer Studio Project File - Name="call_saw" - Package Owner=<4>\r
+# Microsoft Developer Studio Generated Build File, Format Version 6.00\r
+# ** DO NOT EDIT **\r
+\r
+# TARGTYPE "Win32 (x86) Console Application" 0x0103\r
+\r
+CFG=call_saw - Win32 Debug\r
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r
+!MESSAGE use the Export Makefile command and run\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "call_saw.mak".\r
+!MESSAGE \r
+!MESSAGE You can specify a configuration when running NMAKE\r
+!MESSAGE by defining the macro CFG on the command line. For example:\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "call_saw.mak" CFG="call_saw - Win32 Debug"\r
+!MESSAGE \r
+!MESSAGE Possible choices for configuration are:\r
+!MESSAGE \r
+!MESSAGE "call_saw - Win32 Release" (based on "Win32 (x86) Console Application")\r
+!MESSAGE "call_saw - Win32 Debug" (based on "Win32 (x86) Console Application")\r
+!MESSAGE \r
+\r
+# Begin Project\r
+# PROP AllowPerConfigDependencies 0\r
+# PROP Scc_ProjName ""\r
+# PROP Scc_LocalPath ""\r
+CPP=cl.exe\r
+RSC=rc.exe\r
+\r
+!IF  "$(CFG)" == "call_saw - Win32 Release"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 0\r
+# PROP BASE Output_Dir "call_saw___Win32_Release"\r
+# PROP BASE Intermediate_Dir "call_saw___Win32_Release"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 0\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Release"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
+# ADD CPP /nologo /MT /W3 /GX /O2 /I "../" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /c\r
+# ADD BASE RSC /l 0x409 /d "NDEBUG"\r
+# ADD RSC /l 0x409 /d "NDEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /machine:I386\r
+\r
+!ELSEIF  "$(CFG)" == "call_saw - Win32 Debug"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 1\r
+# PROP BASE Output_Dir "call_saw___Win32_Debug"\r
+# PROP BASE Intermediate_Dir "call_saw___Win32_Debug"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 1\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Debug"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ  /c\r
+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /GZ  /c\r
+# ADD BASE RSC /l 0x409 /d "_DEBUG"\r
+# ADD RSC /l 0x409 /d "_DEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+\r
+!ENDIF \r
+\r
+# Begin Target\r
+\r
+# Name "call_saw - Win32 Release"\r
+# Name "call_saw - Win32 Debug"\r
+# Begin Group "Source Files"\r
+\r
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"\r
+# Begin Source File\r
+\r
+SOURCE=.\call_saw.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.cpp\r
+# End Source File\r
+# End Group\r
+# Begin Group "Header Files"\r
+\r
+# PROP Default_Filter "h;hpp;hxx;hm;inl"\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.h\r
+# End Source File\r
+# End Group\r
+# Begin Group "Resource Files"\r
+\r
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+# End Group\r
+# End Target\r
+# End Project\r
diff --git a/tests/call_twostreams.cpp b/tests/call_twostreams.cpp
new file mode 100644 (file)
index 0000000..d763cc5
--- /dev/null
@@ -0,0 +1,166 @@
+/******************************************/
+/*
+  twostreams.cpp
+  by Gary P. Scavone, 2001
+
+  Text executable using two streams with
+  callbacks.
+*/
+/******************************************/
+
+#include "RtAudio.h"
+#include <iostream.h>
+
+/*
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT24
+#define SCALE  2147483647.0
+
+typedef char  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT8
+#define SCALE  127.0
+
+typedef signed short  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT16
+#define SCALE  32767.0
+
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT32
+#define SCALE  2147483647.0
+
+typedef float  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT32
+#define SCALE  1.0
+*/
+
+typedef double  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT64
+#define SCALE  1.0
+
+void usage(void) {
+  /* Error function in case of incorrect command-line
+     argument specifications
+  */
+  cout << "\nuseage: call_twostreams N fs\n";
+  cout << "    where N = number of channels,\n";
+  cout << "    and fs = the sample rate.\n\n";
+  exit(0);
+}
+
+int chans;
+
+int in(char *buffer, int buffer_size, void *data)
+{
+  extern int chans;
+  MY_TYPE *my_buffer = (MY_TYPE *) buffer;
+  MY_TYPE *my_data = (MY_TYPE *) data;
+  long buffer_bytes = buffer_size * chans * sizeof(MY_TYPE);
+
+  memcpy(my_data, my_buffer, buffer_bytes);
+
+  return 0;
+}
+
+int out(char *buffer, int buffer_size, void *data)
+{
+  extern int chans;
+  MY_TYPE *my_buffer = (MY_TYPE *) buffer;
+  MY_TYPE *my_data = (MY_TYPE *) data;
+  long buffer_bytes = buffer_size * chans * sizeof(MY_TYPE);
+
+  memcpy(my_buffer, my_data, buffer_bytes);
+
+  return 0;
+}
+
+int main(int argc, char *argv[])
+{
+  int device, buffer_size, stream1, stream2, fs;
+  MY_TYPE *data = 0;
+  RtAudio *audio;
+  char input;
+
+  // minimal command-line checking
+  if (argc != 3) usage();
+
+  chans = (int) atoi(argv[1]);
+  fs = (int) atoi(argv[2]);
+
+  // Open the realtime output device
+  buffer_size = 512;
+  device = 0; // default device
+  try {
+    audio = new RtAudio();
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    exit(EXIT_FAILURE);
+  }
+
+  try {
+    stream1 = audio->openStream(0, 0, device, chans,
+                                FORMAT, fs, &buffer_size, 8);
+    stream2 = audio->openStream(device, chans, 0, 0,
+                                FORMAT, fs, &buffer_size, 8);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  data = (MY_TYPE *) calloc(chans*buffer_size, sizeof(MY_TYPE));
+  try {
+    audio->setStreamCallback(stream1, &in, (void *)data);
+    audio->setStreamCallback(stream2, &out, (void *)data);
+    audio->startStream(stream1);
+    audio->startStream(stream2);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  cout << "\nRunning two streams (quasi-duplex) ... press <enter> to quit.\n";
+  cin.get(input);
+
+  cout << "\nStopping both streams.\n";
+  try {
+    audio->stopStream(stream1);
+    audio->stopStream(stream2);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  cout << "\nPress <enter> to restart streams:\n";
+  cin.get(input);
+
+  try {
+    audio->startStream(stream1);
+    audio->startStream(stream2);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  cout << "\nRunning two streams (quasi-duplex) ... press <enter> to quit.\n";
+  cin.get(input);
+
+  try {
+    audio->stopStream(stream1);
+    audio->stopStream(stream2);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+  }
+
+ cleanup:
+  audio->closeStream(stream1);
+  audio->closeStream(stream2);
+  delete audio;
+  if (data) free(data);
+
+  return 0;
+}
diff --git a/tests/call_twostreams.dsp b/tests/call_twostreams.dsp
new file mode 100644 (file)
index 0000000..b81d0d7
--- /dev/null
@@ -0,0 +1,110 @@
+# Microsoft Developer Studio Project File - Name="call_twostreams" - Package Owner=<4>\r
+# Microsoft Developer Studio Generated Build File, Format Version 6.00\r
+# ** DO NOT EDIT **\r
+\r
+# TARGTYPE "Win32 (x86) Console Application" 0x0103\r
+\r
+CFG=call_twostreams - Win32 Debug\r
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r
+!MESSAGE use the Export Makefile command and run\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "call_twostreams.mak".\r
+!MESSAGE \r
+!MESSAGE You can specify a configuration when running NMAKE\r
+!MESSAGE by defining the macro CFG on the command line. For example:\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "call_twostreams.mak" CFG="call_twostreams - Win32 Debug"\r
+!MESSAGE \r
+!MESSAGE Possible choices for configuration are:\r
+!MESSAGE \r
+!MESSAGE "call_twostreams - Win32 Release" (based on "Win32 (x86) Console Application")\r
+!MESSAGE "call_twostreams - Win32 Debug" (based on "Win32 (x86) Console Application")\r
+!MESSAGE \r
+\r
+# Begin Project\r
+# PROP AllowPerConfigDependencies 0\r
+# PROP Scc_ProjName ""\r
+# PROP Scc_LocalPath ""\r
+CPP=cl.exe\r
+RSC=rc.exe\r
+\r
+!IF  "$(CFG)" == "call_twostreams - Win32 Release"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 0\r
+# PROP BASE Output_Dir "call_twostreams___Win32_Release"\r
+# PROP BASE Intermediate_Dir "call_twostreams___Win32_Release"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 0\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Release"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
+# ADD CPP /nologo /MT /W3 /GX /O2 /I "../" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /c\r
+# ADD BASE RSC /l 0x409 /d "NDEBUG"\r
+# ADD RSC /l 0x409 /d "NDEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /machine:I386\r
+\r
+!ELSEIF  "$(CFG)" == "call_twostreams - Win32 Debug"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 1\r
+# PROP BASE Output_Dir "call_twostreams___Win32_Debug"\r
+# PROP BASE Intermediate_Dir "call_twostreams___Win32_Debug"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 1\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Debug"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ  /c\r
+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /GZ  /c\r
+# ADD BASE RSC /l 0x409 /d "_DEBUG"\r
+# ADD RSC /l 0x409 /d "_DEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib  kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+\r
+!ENDIF \r
+\r
+# Begin Target\r
+\r
+# Name "call_twostreams - Win32 Release"\r
+# Name "call_twostreams - Win32 Debug"\r
+# Begin Group "Source Files"\r
+\r
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"\r
+# Begin Source File\r
+\r
+SOURCE=.\call_twostreams.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.cpp\r
+# End Source File\r
+# End Group\r
+# Begin Group "Header Files"\r
+\r
+# PROP Default_Filter "h;hpp;hxx;hm;inl"\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.h\r
+# End Source File\r
+# End Group\r
+# Begin Group "Resource Files"\r
+\r
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+# End Group\r
+# End Target\r
+# End Project\r
diff --git a/tests/in_out.cpp b/tests/in_out.cpp
new file mode 100644 (file)
index 0000000..7513497
--- /dev/null
@@ -0,0 +1,109 @@
+/******************************************/
+/*
+  in_out.c
+  by Gary P. Scavone, 2001
+
+  Records from default input and passes it
+  through to the output.  Takes number of
+  channels and sample rate as input arguments.
+  Use blocking functionality.
+*/
+/******************************************/
+
+#include "RtAudio.h"
+#include <iostream.h>
+
+/*
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT24
+
+typedef char  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT8
+
+typedef signed short  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT16
+
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT32
+
+typedef float  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT32
+*/
+
+typedef double  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT64
+
+#define TIME   4.0
+
+void usage(void) {
+  /* Error function in case of incorrect command-line
+     argument specifications
+  */
+  cout << "\nuseage: in_out N fs\n";
+  cout << "    where N = number of channels,\n";
+  cout << "    and fs = the sample rate.\n\n";
+  exit(0);
+}
+
+int main(int argc, char *argv[])
+{
+  int chans, fs, device, buffer_size, stream;
+  long frames, counter = 0;
+  MY_TYPE *buffer;
+  RtAudio *audio;
+
+  // minimal command-line checking
+  if (argc != 3) usage();
+
+  chans = (int) atoi(argv[1]);
+  fs = (int) atoi(argv[2]);
+
+  // Open the realtime output device
+  buffer_size = 512;
+  device = 0; // default device
+  try {
+    audio = new RtAudio(&stream, device, chans, device, chans,
+                        FORMAT, fs, &buffer_size, 8);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    exit(EXIT_FAILURE);
+  }
+
+  frames = (long) (fs * TIME);
+
+  try {
+    buffer = (MY_TYPE *) audio->getStreamBuffer(stream);
+    audio->startStream(stream);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  cout << "\nRunning for " << TIME << " seconds ... fragment_size = " << buffer_size << endl;
+  while (counter < frames) {
+
+    try {
+      audio->tickStream(stream);
+    }
+    catch (RtAudioError &m) {
+      m.printMessage();
+      goto cleanup;
+    }
+    counter += buffer_size;
+  }
+
+  try {
+    audio->stopStream(stream);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+  }
+
+ cleanup:
+  audio->closeStream(stream);
+  delete audio;
+
+  return 0;
+}
diff --git a/tests/in_out.dsp b/tests/in_out.dsp
new file mode 100644 (file)
index 0000000..ddfa94f
--- /dev/null
@@ -0,0 +1,110 @@
+# Microsoft Developer Studio Project File - Name="in_out" - Package Owner=<4>\r
+# Microsoft Developer Studio Generated Build File, Format Version 6.00\r
+# ** DO NOT EDIT **\r
+\r
+# TARGTYPE "Win32 (x86) Console Application" 0x0103\r
+\r
+CFG=in_out - Win32 Debug\r
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r
+!MESSAGE use the Export Makefile command and run\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "in_out.mak".\r
+!MESSAGE \r
+!MESSAGE You can specify a configuration when running NMAKE\r
+!MESSAGE by defining the macro CFG on the command line. For example:\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "in_out.mak" CFG="in_out - Win32 Debug"\r
+!MESSAGE \r
+!MESSAGE Possible choices for configuration are:\r
+!MESSAGE \r
+!MESSAGE "in_out - Win32 Release" (based on "Win32 (x86) Console Application")\r
+!MESSAGE "in_out - Win32 Debug" (based on "Win32 (x86) Console Application")\r
+!MESSAGE \r
+\r
+# Begin Project\r
+# PROP AllowPerConfigDependencies 0\r
+# PROP Scc_ProjName ""\r
+# PROP Scc_LocalPath ""\r
+CPP=cl.exe\r
+RSC=rc.exe\r
+\r
+!IF  "$(CFG)" == "in_out - Win32 Release"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 0\r
+# PROP BASE Output_Dir "in_out___Win32_Release"\r
+# PROP BASE Intermediate_Dir "in_out___Win32_Release"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 0\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Release"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
+# ADD CPP /nologo /MT /W3 /GX /O2 /I "../" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /c\r
+# ADD BASE RSC /l 0x409 /d "NDEBUG"\r
+# ADD RSC /l 0x409 /d "NDEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /machine:I386\r
+\r
+!ELSEIF  "$(CFG)" == "in_out - Win32 Debug"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 1\r
+# PROP BASE Output_Dir "in_out___Win32_Debug"\r
+# PROP BASE Intermediate_Dir "in_out___Win32_Debug"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 1\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Debug"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c\r
+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /GZ /c\r
+# ADD BASE RSC /l 0x409 /d "_DEBUG"\r
+# ADD RSC /l 0x409 /d "_DEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+\r
+!ENDIF \r
+\r
+# Begin Target\r
+\r
+# Name "in_out - Win32 Release"\r
+# Name "in_out - Win32 Debug"\r
+# Begin Group "Source Files"\r
+\r
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"\r
+# Begin Source File\r
+\r
+SOURCE=.\in_out.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.cpp\r
+# End Source File\r
+# End Group\r
+# Begin Group "Header Files"\r
+\r
+# PROP Default_Filter "h;hpp;hxx;hm;inl"\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.h\r
+# End Source File\r
+# End Group\r
+# Begin Group "Resource Files"\r
+\r
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+# End Group\r
+# End Target\r
+# End Project\r
diff --git a/tests/info.cpp b/tests/info.cpp
new file mode 100644 (file)
index 0000000..a4cfcf2
--- /dev/null
@@ -0,0 +1,66 @@
+/******************************************/
+/*
+  info.cpp
+  by Gary P. Scavone, 2001
+
+  Prints audio system/device info.
+*/
+/******************************************/
+
+#include "RtAudio.h"
+#include <iostream.h>
+
+int main(int argc, char *argv[])
+{
+  RtAudio *audio;
+  RtAudio::RTAUDIO_DEVICE my_info;
+  try {
+    audio = new RtAudio();
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    exit(EXIT_FAILURE);
+  }
+
+  int devices = audio->getDeviceCount();
+  cout << "\nFound " << devices << " devices ...\n";
+
+  for (int i=0; i<devices; i++) {
+    try {
+      audio->getDeviceInfo(i, &my_info);
+    }
+    catch (RtAudioError &m) {
+      m.printMessage();
+      break;
+    }
+
+    cout << "\nname = " << my_info.name << '\n';
+    if (my_info.probed == true)
+      cout << "probe successful\n";
+    else
+      cout << "probe unsuccessful\n";
+    cout << "maxOutputChans = " << my_info.maxOutputChannels << '\n';
+    cout << "minOutputChans = " << my_info.minOutputChannels << '\n';
+    cout << "maxInputChans = " << my_info.maxInputChannels << '\n';
+    cout << "minInputChans = " << my_info.minInputChannels << '\n';
+    cout << "maxDuplexChans = " << my_info.maxDuplexChannels << '\n';
+    cout << "minDuplexChans = " << my_info.minDuplexChannels << '\n';
+    if (my_info.hasDuplexSupport)
+      cout << "duplex support = true\n";
+    else
+      cout << "duplex support = false\n";
+    cout << "format = " << my_info.nativeFormats << '\n';
+    if (my_info.nSampleRates == -1)
+      cout << "min_srate = " << my_info.sampleRates[0] << ", max_srate = " << my_info.sampleRates[1] << '\n';
+    else {
+      cout << "sample rates = ";
+      for (int j=0; j<my_info.nSampleRates; j++)
+        cout << my_info.sampleRates[j] << " ";
+      cout << endl;
+    }
+  }
+  cout << endl;
+
+  delete audio;
+  return 0;
+}
diff --git a/tests/info.dsp b/tests/info.dsp
new file mode 100644 (file)
index 0000000..067803a
--- /dev/null
@@ -0,0 +1,110 @@
+# Microsoft Developer Studio Project File - Name="info" - Package Owner=<4>\r
+# Microsoft Developer Studio Generated Build File, Format Version 6.00\r
+# ** DO NOT EDIT **\r
+\r
+# TARGTYPE "Win32 (x86) Console Application" 0x0103\r
+\r
+CFG=info - Win32 Debug\r
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r
+!MESSAGE use the Export Makefile command and run\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "info.mak".\r
+!MESSAGE \r
+!MESSAGE You can specify a configuration when running NMAKE\r
+!MESSAGE by defining the macro CFG on the command line. For example:\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "info.mak" CFG="info - Win32 Debug"\r
+!MESSAGE \r
+!MESSAGE Possible choices for configuration are:\r
+!MESSAGE \r
+!MESSAGE "info - Win32 Release" (based on "Win32 (x86) Console Application")\r
+!MESSAGE "info - Win32 Debug" (based on "Win32 (x86) Console Application")\r
+!MESSAGE \r
+\r
+# Begin Project\r
+# PROP AllowPerConfigDependencies 0\r
+# PROP Scc_ProjName ""\r
+# PROP Scc_LocalPath ""\r
+CPP=cl.exe\r
+RSC=rc.exe\r
+\r
+!IF  "$(CFG)" == "info - Win32 Release"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 0\r
+# PROP BASE Output_Dir "Release"\r
+# PROP BASE Intermediate_Dir "Release"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 0\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Release"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
+# ADD CPP /nologo /MT /W3 /GX /O2 /I "../" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /c\r
+# ADD BASE RSC /l 0x409 /d "NDEBUG"\r
+# ADD RSC /l 0x409 /d "NDEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /machine:I386\r
+\r
+!ELSEIF  "$(CFG)" == "info - Win32 Debug"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 1\r
+# PROP BASE Output_Dir "info___Win32_Debug"\r
+# PROP BASE Intermediate_Dir "info___Win32_Debug"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 1\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Debug"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c\r
+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /GZ /c\r
+# ADD BASE RSC /l 0x409 /d "_DEBUG"\r
+# ADD RSC /l 0x409 /d "_DEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+\r
+!ENDIF \r
+\r
+# Begin Target\r
+\r
+# Name "info - Win32 Release"\r
+# Name "info - Win32 Debug"\r
+# Begin Group "Source Files"\r
+\r
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"\r
+# Begin Source File\r
+\r
+SOURCE=.\info.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.cpp\r
+# End Source File\r
+# End Group\r
+# Begin Group "Header Files"\r
+\r
+# PROP Default_Filter "h;hpp;hxx;hm;inl"\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.h\r
+# End Source File\r
+# End Group\r
+# Begin Group "Resource Files"\r
+\r
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+# End Group\r
+# End Target\r
+# End Project\r
diff --git a/tests/play_raw.cpp b/tests/play_raw.cpp
new file mode 100644 (file)
index 0000000..827f533
--- /dev/null
@@ -0,0 +1,128 @@
+/******************************************/
+/*
+  play_raw.c
+  by Gary P. Scavone, 2001
+
+  Play a raw file.  It is necessary that the
+  file be of the same format as defined below.
+  Uses blocking functionality.
+*/
+/******************************************/
+
+#include "RtAudio.h"
+#include <iostream.h>
+#include <stdio.h>
+
+/*
+typedef char  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT8
+#define SCALE  127.0
+
+typedef signed short  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT16
+#define SCALE  32767.0
+
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT24
+#define SCALE  8388607.0
+
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT32
+#define SCALE  2147483647.0
+
+typedef float  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT32
+#define SCALE  1.0;
+*/
+
+typedef double  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT64
+#define SCALE  1.0;
+
+void usage(void) {
+  /* Error function in case of incorrect command-line
+     argument specifications
+  */
+  cout << "\nuseage: play_raw N fs file\n";
+  cout << "    where N = number of channels,\n";
+  cout << "    fs = the sample rate, \n";
+  cout << "    and file = the raw file to play.\n\n"; 
+  exit(0);
+}
+
+int main(int argc, char *argv[])
+{
+  int chans, fs, device, buffer_size, count, stream;
+  long counter = 0;
+  MY_TYPE *buffer;
+  char *file;
+  FILE *fd;
+  RtAudio *audio;
+
+  // minimal command-line checking
+  if (argc != 4) usage();
+
+  chans = (int) atoi(argv[1]);
+  fs = (int) atoi(argv[2]);
+  file = argv[3];
+
+  fd = fopen(file,"rb");
+  if (!fd) {
+    cout << "can't find file!\n";
+    exit(0);
+  }
+
+  // Open the realtime output device
+  buffer_size = 256;
+  device = 0; // default device
+  try {
+    audio = new RtAudio(&stream, device, chans, 0, 0,
+                        FORMAT, fs, &buffer_size, 2);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    fclose(fd);
+    exit(EXIT_FAILURE);
+  }
+
+  try {
+    buffer = (MY_TYPE *) audio->getStreamBuffer(stream);
+    audio->startStream(stream);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  while (1) {
+    count = fread(buffer, chans * sizeof(MY_TYPE), buffer_size, fd);
+
+    if (count == buffer_size) {
+      try {
+        audio->tickStream(stream);
+      }
+      catch (RtAudioError &m) {
+        m.printMessage();
+        goto cleanup;
+      }
+    }
+    else
+      break;
+        
+    counter += buffer_size;
+  }
+
+  try {
+    audio->stopStream(stream);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+  }
+
+ cleanup:
+  audio->closeStream(stream);
+  delete audio;
+  fclose(fd);
+
+  return 0;
+}
diff --git a/tests/play_raw.dsp b/tests/play_raw.dsp
new file mode 100644 (file)
index 0000000..dab880a
--- /dev/null
@@ -0,0 +1,110 @@
+# Microsoft Developer Studio Project File - Name="play_raw" - Package Owner=<4>\r
+# Microsoft Developer Studio Generated Build File, Format Version 6.00\r
+# ** DO NOT EDIT **\r
+\r
+# TARGTYPE "Win32 (x86) Console Application" 0x0103\r
+\r
+CFG=play_raw - Win32 Debug\r
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r
+!MESSAGE use the Export Makefile command and run\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "play_raw.mak".\r
+!MESSAGE \r
+!MESSAGE You can specify a configuration when running NMAKE\r
+!MESSAGE by defining the macro CFG on the command line. For example:\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "play_raw.mak" CFG="play_raw - Win32 Debug"\r
+!MESSAGE \r
+!MESSAGE Possible choices for configuration are:\r
+!MESSAGE \r
+!MESSAGE "play_raw - Win32 Release" (based on "Win32 (x86) Console Application")\r
+!MESSAGE "play_raw - Win32 Debug" (based on "Win32 (x86) Console Application")\r
+!MESSAGE \r
+\r
+# Begin Project\r
+# PROP AllowPerConfigDependencies 0\r
+# PROP Scc_ProjName ""\r
+# PROP Scc_LocalPath ""\r
+CPP=cl.exe\r
+RSC=rc.exe\r
+\r
+!IF  "$(CFG)" == "play_raw - Win32 Release"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 0\r
+# PROP BASE Output_Dir "Release"\r
+# PROP BASE Intermediate_Dir "Release"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 0\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Release"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
+# ADD CPP /nologo /MT /W3 /GX /O2 /I "../" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /c\r
+# ADD BASE RSC /l 0x409 /d "NDEBUG"\r
+# ADD RSC /l 0x409 /d "NDEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /machine:I386\r
+\r
+!ELSEIF  "$(CFG)" == "play_raw - Win32 Debug"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 1\r
+# PROP BASE Output_Dir "play_raw___Win32_Debug"\r
+# PROP BASE Intermediate_Dir "play_raw___Win32_Debug"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 1\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Debug"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c\r
+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /GZ /c\r
+# ADD BASE RSC /l 0x409 /d "_DEBUG"\r
+# ADD RSC /l 0x409 /d "_DEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+\r
+!ENDIF \r
+\r
+# Begin Target\r
+\r
+# Name "play_raw - Win32 Release"\r
+# Name "play_raw - Win32 Debug"\r
+# Begin Group "Source Files"\r
+\r
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"\r
+# Begin Source File\r
+\r
+SOURCE=.\play_raw.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.cpp\r
+# End Source File\r
+# End Group\r
+# Begin Group "Header Files"\r
+\r
+# PROP Default_Filter "h;hpp;hxx;hm;inl"\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.h\r
+# End Source File\r
+# End Group\r
+# Begin Group "Resource Files"\r
+\r
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+# End Group\r
+# End Target\r
+# End Project\r
diff --git a/tests/play_saw.cpp b/tests/play_saw.cpp
new file mode 100644 (file)
index 0000000..bd865aa
--- /dev/null
@@ -0,0 +1,128 @@
+/******************************************/
+/*
+  play_saw.c
+  by Gary P. Scavone, 2001
+
+  Play sawtooth waveforms of distinct frequency.
+  Takes number of channels and sample rate as
+  input arguments.  Uses blocking functionality.
+*/
+/******************************************/
+
+#include "RtAudio.h"
+#include <iostream.h>
+
+/*
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT24
+#define SCALE  2147483647.0
+
+typedef char  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT8
+#define SCALE  127.0
+
+typedef signed short  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT16
+#define SCALE  32767.0
+
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT32
+#define SCALE  2147483647.0
+*/
+typedef float  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT32
+#define SCALE  1.0
+
+/*
+typedef double  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT64
+#define SCALE  1.0
+*/
+
+#define BASE_RATE 0.005
+#define TIME   1.0
+
+void usage(void) {
+  /* Error function in case of incorrect command-line
+     argument specifications
+  */
+  cout << "\nuseage: play_saw N fs\n";
+  cout << "    where N = number of channels,\n";
+  cout << "    and fs = the sample rate.\n\n";
+  exit(0);
+}
+
+int main(int argc, char *argv[])
+{
+  int chans, fs, device, buffer_size, stream;
+  long frames, counter = 0, i, j;
+  MY_TYPE *buffer;
+  RtAudio *audio;
+  double *data;
+
+  // minimal command-line checking
+  if (argc != 3) usage();
+
+  chans = (int) atoi(argv[1]);
+  fs = (int) atoi(argv[2]);
+
+  // Open the realtime output device
+  buffer_size = 256;
+  device = 0; // default device
+  try {
+    audio = new RtAudio(&stream, device, chans, 0, 0,
+                        FORMAT, fs, &buffer_size, 4);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    exit(EXIT_FAILURE);
+  }
+
+  frames = (long) (fs * TIME);
+  data = (double *) calloc(chans, sizeof(double));
+
+  try {
+    buffer = (MY_TYPE *) audio->getStreamBuffer(stream);
+    audio->startStream(stream);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  cout << "\nPlaying for " << TIME << " seconds." << endl;
+  while (counter < frames) {
+    for (i=0; i<buffer_size; i++) {
+      for (j=0; j<chans; j++) {
+        buffer[i*chans+j] = (MY_TYPE) (data[j] * SCALE);
+        data[j] += BASE_RATE * (j+1+(j*0.1));
+        if (data[j] >= 1.0) data[j] -= 2.0;
+      }
+    }
+
+    try {
+      //cout << "frames until no block = " << audio->streamWillBlock(stream) << endl;
+      audio->tickStream(stream);
+    }
+    catch (RtAudioError &m) {
+      m.printMessage();
+      goto cleanup;
+    }
+
+    counter += buffer_size;
+  }
+
+  try {
+    audio->stopStream(stream);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+  }
+
+ cleanup:
+  audio->closeStream(stream);
+  delete audio;
+  if (data) free(data);
+
+  return 0;
+}
diff --git a/tests/play_saw.dsp b/tests/play_saw.dsp
new file mode 100644 (file)
index 0000000..b6f9313
--- /dev/null
@@ -0,0 +1,110 @@
+# Microsoft Developer Studio Project File - Name="play_saw" - Package Owner=<4>\r
+# Microsoft Developer Studio Generated Build File, Format Version 6.00\r
+# ** DO NOT EDIT **\r
+\r
+# TARGTYPE "Win32 (x86) Console Application" 0x0103\r
+\r
+CFG=play_saw - Win32 Debug\r
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r
+!MESSAGE use the Export Makefile command and run\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "play_saw.mak".\r
+!MESSAGE \r
+!MESSAGE You can specify a configuration when running NMAKE\r
+!MESSAGE by defining the macro CFG on the command line. For example:\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "play_saw.mak" CFG="play_saw - Win32 Debug"\r
+!MESSAGE \r
+!MESSAGE Possible choices for configuration are:\r
+!MESSAGE \r
+!MESSAGE "play_saw - Win32 Release" (based on "Win32 (x86) Console Application")\r
+!MESSAGE "play_saw - Win32 Debug" (based on "Win32 (x86) Console Application")\r
+!MESSAGE \r
+\r
+# Begin Project\r
+# PROP AllowPerConfigDependencies 0\r
+# PROP Scc_ProjName ""\r
+# PROP Scc_LocalPath ""\r
+CPP=cl.exe\r
+RSC=rc.exe\r
+\r
+!IF  "$(CFG)" == "play_saw - Win32 Release"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 0\r
+# PROP BASE Output_Dir "Release"\r
+# PROP BASE Intermediate_Dir "Release"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 0\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Release"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
+# ADD CPP /nologo /MT /W3 /GX /O2 /I "../" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /c\r
+# ADD BASE RSC /l 0x409 /d "NDEBUG"\r
+# ADD RSC /l 0x409 /d "NDEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /machine:I386\r
+\r
+!ELSEIF  "$(CFG)" == "play_saw - Win32 Debug"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 1\r
+# PROP BASE Output_Dir "play_saw___Win32_Debug"\r
+# PROP BASE Intermediate_Dir "play_saw___Win32_Debug"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 1\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Debug"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c\r
+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /GZ /c\r
+# ADD BASE RSC /l 0x409 /d "_DEBUG"\r
+# ADD RSC /l 0x409 /d "_DEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+\r
+!ENDIF \r
+\r
+# Begin Target\r
+\r
+# Name "play_saw - Win32 Release"\r
+# Name "play_saw - Win32 Debug"\r
+# Begin Group "Source Files"\r
+\r
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"\r
+# Begin Source File\r
+\r
+SOURCE=.\play_saw.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.cpp\r
+# End Source File\r
+# End Group\r
+# Begin Group "Header Files"\r
+\r
+# PROP Default_Filter "h;hpp;hxx;hm;inl"\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.h\r
+# End Source File\r
+# End Group\r
+# Begin Group "Resource Files"\r
+\r
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+# End Group\r
+# End Target\r
+# End Project\r
diff --git a/tests/record_raw.cpp b/tests/record_raw.cpp
new file mode 100644 (file)
index 0000000..739566e
--- /dev/null
@@ -0,0 +1,114 @@
+/******************************************/
+/*
+  record_raw.c
+  by Gary P. Scavone, 2001
+
+  Records from default input.  Takes
+  number of channels and sample rate
+  as input arguments. Uses blocking calls.
+*/
+/******************************************/
+
+#include "RtAudio.h"
+#include <stdio.h>
+#include <iostream.h>
+
+/*
+typedef char  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT8
+
+typedef signed short  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT16
+
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT24
+
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT32
+
+typedef float  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT32
+*/
+
+typedef double  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT64
+
+#define TIME   2.0
+
+void usage(void) {
+  /* Error function in case of incorrect command-line
+     argument specifications
+  */
+  cout << "\nuseage: record_raw N fs\n";
+  cout << "    where N = number of channels,\n";
+  cout << "    and fs = the sample rate.\n\n";
+  exit(0);
+}
+
+int main(int argc, char *argv[])
+{
+  int chans, fs, device, buffer_size, stream;
+  long frames, counter = 0;
+  MY_TYPE *buffer;
+  FILE *fd;
+  RtAudio *audio;
+
+  // minimal command-line checking
+  if (argc != 3) usage();
+
+  chans = (int) atoi(argv[1]);
+  fs = (int) atoi(argv[2]);
+
+  // Open the realtime output device
+  buffer_size = 512;
+  device = 0; // default device
+  try {
+    audio = new RtAudio(&stream, 0, 0, device, chans,
+                        FORMAT, fs, &buffer_size, 8);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    exit(EXIT_FAILURE);
+  }
+
+  fd = fopen("test.raw","wb");
+  frames = (long) (fs * TIME);
+
+  try {
+    buffer = (MY_TYPE *) audio->getStreamBuffer(stream);
+    audio->startStream(stream);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  cout << "\nRecording for " << TIME << " seconds ... writing file test.raw." << endl;
+  while (counter < frames) {
+
+    try {
+      audio->tickStream(stream);
+    }
+    catch (RtAudioError &m) {
+      m.printMessage();
+      goto cleanup;
+    }
+
+    fwrite(buffer, sizeof(MY_TYPE), chans * buffer_size, fd);
+    counter += buffer_size;
+  }
+
+  try {
+    audio->stopStream(stream);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+  }
+
+ cleanup:
+  audio->closeStream(stream);
+  delete audio;
+  fclose(fd);
+
+  return 0;
+}
diff --git a/tests/record_raw.dsp b/tests/record_raw.dsp
new file mode 100644 (file)
index 0000000..4b1f1e4
--- /dev/null
@@ -0,0 +1,110 @@
+# Microsoft Developer Studio Project File - Name="record_raw" - Package Owner=<4>\r
+# Microsoft Developer Studio Generated Build File, Format Version 6.00\r
+# ** DO NOT EDIT **\r
+\r
+# TARGTYPE "Win32 (x86) Console Application" 0x0103\r
+\r
+CFG=record_raw - Win32 Debug\r
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r
+!MESSAGE use the Export Makefile command and run\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "record_raw.mak".\r
+!MESSAGE \r
+!MESSAGE You can specify a configuration when running NMAKE\r
+!MESSAGE by defining the macro CFG on the command line. For example:\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "record_raw.mak" CFG="record_raw - Win32 Debug"\r
+!MESSAGE \r
+!MESSAGE Possible choices for configuration are:\r
+!MESSAGE \r
+!MESSAGE "record_raw - Win32 Release" (based on "Win32 (x86) Console Application")\r
+!MESSAGE "record_raw - Win32 Debug" (based on "Win32 (x86) Console Application")\r
+!MESSAGE \r
+\r
+# Begin Project\r
+# PROP AllowPerConfigDependencies 0\r
+# PROP Scc_ProjName ""\r
+# PROP Scc_LocalPath ""\r
+CPP=cl.exe\r
+RSC=rc.exe\r
+\r
+!IF  "$(CFG)" == "record_raw - Win32 Release"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 0\r
+# PROP BASE Output_Dir "Release"\r
+# PROP BASE Intermediate_Dir "Release"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 0\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Release"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
+# ADD CPP /nologo /MT /W3 /GX /O2 /I "../" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /c\r
+# ADD BASE RSC /l 0x409 /d "NDEBUG"\r
+# ADD RSC /l 0x409 /d "NDEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /machine:I386\r
+\r
+!ELSEIF  "$(CFG)" == "record_raw - Win32 Debug"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 1\r
+# PROP BASE Output_Dir "record_raw___Win32_Debug"\r
+# PROP BASE Intermediate_Dir "record_raw___Win32_Debug"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 1\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Debug"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c\r
+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /GZ /c\r
+# ADD BASE RSC /l 0x409 /d "_DEBUG"\r
+# ADD RSC /l 0x409 /d "_DEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+\r
+!ENDIF \r
+\r
+# Begin Target\r
+\r
+# Name "record_raw - Win32 Release"\r
+# Name "record_raw - Win32 Debug"\r
+# Begin Group "Source Files"\r
+\r
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"\r
+# Begin Source File\r
+\r
+SOURCE=.\record_raw.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.cpp\r
+# End Source File\r
+# End Group\r
+# Begin Group "Header Files"\r
+\r
+# PROP Default_Filter "h;hpp;hxx;hm;inl"\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.h\r
+# End Source File\r
+# End Group\r
+# Begin Group "Resource Files"\r
+\r
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+# End Group\r
+# End Target\r
+# End Project\r
diff --git a/tests/twostreams.cpp b/tests/twostreams.cpp
new file mode 100644 (file)
index 0000000..1f7a05d
--- /dev/null
@@ -0,0 +1,204 @@
+/******************************************/
+/*
+  twostreams.cpp
+  by Gary P. Scavone, 2001
+
+  Text executable for audio playback,
+  recording, duplex operation, stopping,
+  starting, and aborting operations.
+  Takes number of channels and sample
+  rate as input arguments.  Runs input
+  and output through two separate streams.
+  Uses blocking functionality.
+*/
+/******************************************/
+
+#include "RtAudio.h"
+#include <iostream.h>
+#include <stdio.h>
+
+/*
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT24
+#define SCALE  2147483647.0
+
+typedef char  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT8
+#define SCALE  127.0
+
+typedef signed short  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT16
+#define SCALE  32767.0
+
+typedef signed long  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_SINT32
+#define SCALE  2147483647.0
+
+typedef float  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT32
+#define SCALE  1.0
+*/
+
+typedef double  MY_TYPE;
+#define FORMAT RtAudio::RTAUDIO_FLOAT64
+#define SCALE  1.0
+
+#define BASE_RATE 0.005
+#define TIME 2.0
+
+void usage(void) {
+  /* Error function in case of incorrect command-line
+     argument specifications
+  */
+  cout << "\nuseage: twostreams N fs\n";
+  cout << "    where N = number of channels,\n";
+  cout << "    and fs = the sample rate.\n\n";
+  exit(0);
+}
+
+int main(int argc, char *argv[])
+{
+  int chans, fs, device, buffer_size, stream1, stream2;
+  long frames, counter = 0, i, j;
+  MY_TYPE *buffer1, *buffer2;
+  RtAudio *audio;
+  FILE *fd;
+  double *data;
+
+  // minimal command-line checking
+  if (argc != 3) usage();
+
+  chans = (int) atoi(argv[1]);
+  fs = (int) atoi(argv[2]);
+
+  // Open the realtime output device
+  buffer_size = 512;
+  device = 0; // default device
+  try {
+    audio = new RtAudio();
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    exit(EXIT_FAILURE);
+  }
+
+  try {
+    stream1 = audio->openStream(device, chans, 0, 0,
+                                FORMAT, fs, &buffer_size, 8);
+    stream2 = audio->openStream(0, 0, device, chans,
+                                FORMAT, fs, &buffer_size, 8);
+    buffer1 = (MY_TYPE *) audio->getStreamBuffer(stream1);
+    buffer2 = (MY_TYPE *) audio->getStreamBuffer(stream2);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  frames = (long) (fs * TIME);
+  data = (double *) calloc(chans, sizeof(double));
+
+  try {
+    audio->startStream(stream1);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  cout << "\nStarting sawtooth playback stream for " << TIME << " seconds." << endl;
+  while (counter < frames) {
+    for (i=0; i<buffer_size; i++) {
+      for (j=0; j<chans; j++) {
+        buffer1[i*chans+j] = (MY_TYPE) (data[j] * SCALE);
+        data[j] += BASE_RATE * (j+1+(j*0.1));
+        if (data[j] >= 1.0) data[j] -= 2.0;
+      }
+    }
+
+    try {
+      audio->tickStream(stream1);
+    }
+    catch (RtAudioError &m) {
+      m.printMessage();
+      goto cleanup;
+    }
+
+    counter += buffer_size;
+  }
+
+  cout << "\nStopping playback stream." << endl;
+  try {
+    audio->stopStream(stream1);
+    audio->startStream(stream2);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  fd = fopen("test.raw","wb");
+
+  counter = 0;
+  cout << "\nStarting recording stream for " << TIME << " seconds." << endl;
+  while (counter < frames) {
+
+    try {
+      audio->tickStream(stream2);
+    }
+    catch (RtAudioError &m) {
+      m.printMessage();
+      goto cleanup;
+    }
+
+    fwrite(buffer2, sizeof(MY_TYPE), chans * buffer_size, fd);
+    counter += buffer_size;
+  }
+
+  fclose(fd);
+  cout << "\nAborting recording." << endl;
+
+  try {
+    audio->abortStream(stream2);
+    audio->startStream(stream1);
+    audio->startStream(stream2);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+    goto cleanup;
+  }
+
+  counter = 0;
+  cout << "\nStarting playback and record streams (quasi-duplex) for " << TIME << " seconds." << endl;
+  while (counter < frames) {
+
+    try {
+      audio->tickStream(stream2);
+      memcpy(buffer1, buffer2, sizeof(MY_TYPE) * chans * buffer_size);
+      audio->tickStream(stream1);
+    }
+    catch (RtAudioError &m) {
+      m.printMessage();
+      goto cleanup;
+    }
+
+    counter += buffer_size;
+  }
+
+  cout << "\nStopping both streams." << endl;
+  try {
+    audio->stopStream(stream1);
+    audio->stopStream(stream2);
+  }
+  catch (RtAudioError &m) {
+    m.printMessage();
+  }
+
+ cleanup:
+  audio->closeStream(stream1);
+  audio->closeStream(stream2);
+  delete audio;
+  if (data) free(data);
+
+  return 0;
+}
diff --git a/tests/twostreams.dsp b/tests/twostreams.dsp
new file mode 100644 (file)
index 0000000..0e69ae2
--- /dev/null
@@ -0,0 +1,110 @@
+# Microsoft Developer Studio Project File - Name="twostreams" - Package Owner=<4>\r
+# Microsoft Developer Studio Generated Build File, Format Version 6.00\r
+# ** DO NOT EDIT **\r
+\r
+# TARGTYPE "Win32 (x86) Console Application" 0x0103\r
+\r
+CFG=twostreams - Win32 Debug\r
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,\r
+!MESSAGE use the Export Makefile command and run\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "twostreams.mak".\r
+!MESSAGE \r
+!MESSAGE You can specify a configuration when running NMAKE\r
+!MESSAGE by defining the macro CFG on the command line. For example:\r
+!MESSAGE \r
+!MESSAGE NMAKE /f "twostreams.mak" CFG="twostreams - Win32 Debug"\r
+!MESSAGE \r
+!MESSAGE Possible choices for configuration are:\r
+!MESSAGE \r
+!MESSAGE "twostreams - Win32 Release" (based on "Win32 (x86) Console Application")\r
+!MESSAGE "twostreams - Win32 Debug" (based on "Win32 (x86) Console Application")\r
+!MESSAGE \r
+\r
+# Begin Project\r
+# PROP AllowPerConfigDependencies 0\r
+# PROP Scc_ProjName ""\r
+# PROP Scc_LocalPath ""\r
+CPP=cl.exe\r
+RSC=rc.exe\r
+\r
+!IF  "$(CFG)" == "twostreams - Win32 Release"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 0\r
+# PROP BASE Output_Dir "twostreams___Win32_Release"\r
+# PROP BASE Intermediate_Dir "twostreams___Win32_Release"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 0\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Release"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c\r
+# ADD CPP /nologo /MT /W3 /GX /O2 /I "../" /D "NDEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /c\r
+# ADD BASE RSC /l 0x409 /d "NDEBUG"\r
+# ADD RSC /l 0x409 /d "NDEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /machine:I386\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /machine:I386\r
+\r
+!ELSEIF  "$(CFG)" == "twostreams - Win32 Debug"\r
+\r
+# PROP BASE Use_MFC 0\r
+# PROP BASE Use_Debug_Libraries 1\r
+# PROP BASE Output_Dir "twostreams___Win32_Debug"\r
+# PROP BASE Intermediate_Dir "twostreams___Win32_Debug"\r
+# PROP BASE Target_Dir ""\r
+# PROP Use_MFC 0\r
+# PROP Use_Debug_Libraries 1\r
+# PROP Output_Dir ""\r
+# PROP Intermediate_Dir "Debug"\r
+# PROP Ignore_Export_Lib 0\r
+# PROP Target_Dir ""\r
+# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c\r
+# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "../" /D "_DEBUG" /D "WIN32" /D "_CONSOLE" /D "_MBCS" /D "__WINDOWS_DS_" /YX /FD /GZ /c\r
+# ADD BASE RSC /l 0x409 /d "_DEBUG"\r
+# ADD RSC /l 0x409 /d "_DEBUG"\r
+BSC32=bscmake.exe\r
+# ADD BASE BSC32 /nologo\r
+# ADD BSC32 /nologo\r
+LINK32=link.exe\r
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib dsound.lib /nologo /subsystem:console /debug /machine:I386 /pdbtype:sept\r
+\r
+!ENDIF \r
+\r
+# Begin Target\r
+\r
+# Name "twostreams - Win32 Release"\r
+# Name "twostreams - Win32 Debug"\r
+# Begin Group "Source Files"\r
+\r
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.cpp\r
+# End Source File\r
+# Begin Source File\r
+\r
+SOURCE=.\twostreams.cpp\r
+# End Source File\r
+# End Group\r
+# Begin Group "Header Files"\r
+\r
+# PROP Default_Filter "h;hpp;hxx;hm;inl"\r
+# Begin Source File\r
+\r
+SOURCE=..\RtAudio.h\r
+# End Source File\r
+# End Group\r
+# Begin Group "Resource Files"\r
+\r
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"\r
+# End Group\r
+# End Target\r
+# End Project\r