aboutsummaryrefslogtreecommitdiff
path: root/pd/portaudio/src
diff options
context:
space:
mode:
Diffstat (limited to 'pd/portaudio/src')
-rw-r--r--pd/portaudio/src/hostapi/alsa/pa_linux_alsa.c3552
-rw-r--r--pd/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp563
-rw-r--r--pd/portaudio/src/hostapi/asio/iasiothiscallresolver.h197
-rw-r--r--pd/portaudio/src/hostapi/asio/pa_asio.cpp3023
-rw-r--r--pd/portaudio/src/hostapi/coreaudio/notes.txt190
-rw-r--r--pd/portaudio/src/hostapi/coreaudio/pa_mac_core.c2238
-rw-r--r--pd/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c564
-rw-r--r--pd/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h133
-rw-r--r--pd/portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h162
-rw-r--r--pd/portaudio/src/hostapi/coreaudio/pa_mac_core_old.c913
-rw-r--r--pd/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c611
-rw-r--r--pd/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h205
-rw-r--r--pd/portaudio/src/hostapi/jack/pa_jack.c1756
-rw-r--r--pd/portaudio/src/hostapi/oss/low_latency_tip.txtbin0 -> 3111 bytes
-rw-r--r--pd/portaudio/src/hostapi/oss/pa_unix_oss.c1946
-rw-r--r--pd/portaudio/src/hostapi/oss/recplay.c114
-rw-r--r--pd/portaudio/src/hostapi/wmme/pa_win_wmme.c3646
-rw-r--r--pd/portaudio/src/os/mac_osx/pa_mac_hostapis.c87
-rw-r--r--pd/portaudio/src/os/unix/pa_unix_hostapis.c78
-rw-r--r--pd/portaudio/src/os/unix/pa_unix_util.c666
-rw-r--r--pd/portaudio/src/os/unix/pa_unix_util.h224
-rw-r--r--pd/portaudio/src/os/win/pa_win_hostapis.c100
-rw-r--r--pd/portaudio/src/os/win/pa_win_util.c147
-rw-r--r--pd/portaudio/src/os/win/pa_x86_plain_converters.c1219
-rw-r--r--pd/portaudio/src/os/win/pa_x86_plain_converters.h60
25 files changed, 22394 insertions, 0 deletions
diff --git a/pd/portaudio/src/hostapi/alsa/pa_linux_alsa.c b/pd/portaudio/src/hostapi/alsa/pa_linux_alsa.c
new file mode 100644
index 00000000..2c403698
--- /dev/null
+++ b/pd/portaudio/src/hostapi/alsa/pa_linux_alsa.c
@@ -0,0 +1,3552 @@
+/*
+ * $Id: pa_linux_alsa.c,v 1.1 2007-08-18 23:49:33 millerpuckette Exp $
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ * ALSA implementation by Joshua Haberman and Arve Knudsen
+ *
+ * Copyright (c) 2002 Joshua Haberman <joshua@haberman.com>
+ * Copyright (c) 2005-2006 Arve Knudsen <aknuds-1@broadpark.no>
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#define ALSA_PCM_NEW_HW_PARAMS_API
+#define ALSA_PCM_NEW_SW_PARAMS_API
+#include <alsa/asoundlib.h>
+#undef ALSA_PCM_NEW_HW_PARAMS_API
+#undef ALSA_PCM_NEW_SW_PARAMS_API
+
+#include <sys/poll.h>
+#include <string.h> /* strlen() */
+#include <limits.h>
+#include <math.h>
+#include <pthread.h>
+#include <signal.h>
+#include <time.h>
+#include <sys/mman.h>
+#include <signal.h> /* For sig_atomic_t */
+
+#include "pa_util.h"
+#include "pa_unix_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "pa_endianness.h"
+#include "pa_debugprint.h"
+
+#include "pa_linux_alsa.h"
+
+/* Check return value of ALSA function, and map it to PaError */
+#define ENSURE_(expr, code) \
+ do { \
+ if( UNLIKELY( (aErr_ = (expr)) < 0 ) ) \
+ { \
+ /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
+ if( (code) == paUnanticipatedHostError && pthread_equal( pthread_self(), paUnixMainThread) ) \
+ { \
+ PaUtil_SetLastHostErrorInfo( paALSA, aErr_, snd_strerror( aErr_ ) ); \
+ } \
+ PaUtil_DebugPrint( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" ); \
+ if( (code) == paUnanticipatedHostError ) \
+ PA_DEBUG(( "Host error description: %s\n", snd_strerror( aErr_ ) )); \
+ result = (code); \
+ goto error; \
+ } \
+ } while( 0 );
+
+#define ASSERT_CALL_(expr, success) \
+ aErr_ = (expr); \
+ assert( success == aErr_ );
+
+static int aErr_; /* Used with ENSURE_ */
+static int numPeriods_ = 4;
+
+int PaAlsa_SetNumPeriods( int numPeriods )
+{
+ numPeriods_ = numPeriods;
+ return paNoError;
+}
+
+typedef enum
+{
+ StreamDirection_In,
+ StreamDirection_Out
+} StreamDirection;
+
+typedef struct
+{
+ PaSampleFormat hostSampleFormat;
+ unsigned long framesPerBuffer;
+ int numUserChannels, numHostChannels;
+ int userInterleaved, hostInterleaved;
+ PaDeviceIndex device; /* Keep the device index */
+
+ snd_pcm_t *pcm;
+ snd_pcm_uframes_t bufferSize;
+ snd_pcm_format_t nativeFormat;
+ unsigned int nfds;
+ int ready; /* Marked ready from poll */
+ void **userBuffers;
+ snd_pcm_uframes_t offset;
+ StreamDirection streamDir;
+
+ snd_pcm_channel_area_t *channelAreas; /* Needed for channel adaption */
+} PaAlsaStreamComponent;
+
+/* Implementation specific stream structure */
+typedef struct PaAlsaStream
+{
+ PaUtilStreamRepresentation streamRepresentation;
+ PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+ PaUtilBufferProcessor bufferProcessor;
+ PaUnixThread thread;
+
+ unsigned long framesPerUserBuffer, maxFramesPerHostBuffer;
+
+ int primeBuffers;
+ int callbackMode; /* bool: are we running in callback mode? */
+ int pcmsSynced; /* Have we successfully synced pcms */
+ int rtSched;
+
+ /* the callback thread uses these to poll the sound device(s), waiting
+ * for data to be ready/available */
+ struct pollfd* pfds;
+ int pollTimeout;
+
+ /* Used in communication between threads */
+ volatile sig_atomic_t callback_finished; /* bool: are we in the "callback finished" state? */
+ volatile sig_atomic_t callbackAbort; /* Drop frames? */
+ volatile sig_atomic_t isActive; /* Is stream in active state? (Between StartStream and StopStream || !paContinue) */
+ PaUnixMutex stateMtx; /* Used to synchronize access to stream state */
+
+ int neverDropInput;
+
+ PaTime underrun;
+ PaTime overrun;
+
+ PaAlsaStreamComponent capture, playback;
+}
+PaAlsaStream;
+
+/* PaAlsaHostApiRepresentation - host api datastructure specific to this implementation */
+
+typedef struct PaAlsaHostApiRepresentation
+{
+ PaUtilHostApiRepresentation baseHostApiRep;
+ PaUtilStreamInterface callbackStreamInterface;
+ PaUtilStreamInterface blockingStreamInterface;
+
+ PaUtilAllocationGroup *allocations;
+
+ PaHostApiIndex hostApiIndex;
+}
+PaAlsaHostApiRepresentation;
+
+typedef struct PaAlsaDeviceInfo
+{
+ PaDeviceInfo baseDeviceInfo;
+ char *alsaName;
+ int isPlug;
+ int minInputChannels;
+ int minOutputChannels;
+}
+PaAlsaDeviceInfo;
+
+/* prototypes for functions declared in this file */
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+ PaStream** s,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate,
+ unsigned long framesPerBuffer,
+ PaStreamFlags streamFlags,
+ PaStreamCallback *callback,
+ void *userData );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError BuildDeviceList( PaAlsaHostApiRepresentation *hostApi );
+static int SetApproximateSampleRate( snd_pcm_t *pcm, snd_pcm_hw_params_t *hwParams, double sampleRate );
+static int GetExactSampleRate( snd_pcm_hw_params_t *hwParams, double *sampleRate );
+
+/* Callback prototypes */
+static void *CallbackThreadFunc( void *userData );
+
+/* Blocking prototypes */
+static signed long GetStreamReadAvailable( PaStream* s );
+static signed long GetStreamWriteAvailable( PaStream* s );
+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+
+
+static const PaAlsaDeviceInfo *GetDeviceInfo( const PaUtilHostApiRepresentation *hostApi, int device )
+{
+ return (const PaAlsaDeviceInfo *)hostApi->deviceInfos[device];
+}
+
+static void AlsaErrorHandler(const char *file, int line, const char *function, int err, const char *fmt, ...)
+{
+}
+
+PaError PaAlsa_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+ PaError result = paNoError;
+ PaAlsaHostApiRepresentation *alsaHostApi = NULL;
+
+ PA_UNLESS( alsaHostApi = (PaAlsaHostApiRepresentation*) PaUtil_AllocateMemory(
+ sizeof(PaAlsaHostApiRepresentation) ), paInsufficientMemory );
+ PA_UNLESS( alsaHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
+ alsaHostApi->hostApiIndex = hostApiIndex;
+
+ *hostApi = (PaUtilHostApiRepresentation*)alsaHostApi;
+ (*hostApi)->info.structVersion = 1;
+ (*hostApi)->info.type = paALSA;
+ (*hostApi)->info.name = "ALSA";
+
+ (*hostApi)->Terminate = Terminate;
+ (*hostApi)->OpenStream = OpenStream;
+ (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+ ENSURE_( snd_lib_error_set_handler(AlsaErrorHandler), paUnanticipatedHostError );
+
+ PA_ENSURE( BuildDeviceList( alsaHostApi ) );
+
+ PaUtil_InitializeStreamInterface( &alsaHostApi->callbackStreamInterface,
+ CloseStream, StartStream,
+ StopStream, AbortStream,
+ IsStreamStopped, IsStreamActive,
+ GetStreamTime, GetStreamCpuLoad,
+ PaUtil_DummyRead, PaUtil_DummyWrite,
+ PaUtil_DummyGetReadAvailable,
+ PaUtil_DummyGetWriteAvailable );
+
+ PaUtil_InitializeStreamInterface( &alsaHostApi->blockingStreamInterface,
+ CloseStream, StartStream,
+ StopStream, AbortStream,
+ IsStreamStopped, IsStreamActive,
+ GetStreamTime, PaUtil_DummyGetCpuLoad,
+ ReadStream, WriteStream,
+ GetStreamReadAvailable,
+ GetStreamWriteAvailable );
+
+ PA_ENSURE( PaUnixThreading_Initialize() );
+
+ return result;
+
+error:
+ if( alsaHostApi )
+ {
+ if( alsaHostApi->allocations )
+ {
+ PaUtil_FreeAllAllocations( alsaHostApi->allocations );
+ PaUtil_DestroyAllocationGroup( alsaHostApi->allocations );
+ }
+
+ PaUtil_FreeMemory( alsaHostApi );
+ }
+
+ return result;
+}
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+ PaAlsaHostApiRepresentation *alsaHostApi = (PaAlsaHostApiRepresentation*)hostApi;
+
+ assert( hostApi );
+
+ if( alsaHostApi->allocations )
+ {
+ PaUtil_FreeAllAllocations( alsaHostApi->allocations );
+ PaUtil_DestroyAllocationGroup( alsaHostApi->allocations );
+ }
+
+ PaUtil_FreeMemory( alsaHostApi );
+ snd_config_update_free_global();
+}
+
+/** Determine max channels and default latencies.
+ *
+ * This function provides functionality to grope an opened (might be opened for capture or playback) pcm device for
+ * traits like max channels, suitable default latencies and default sample rate. Upon error, max channels is set to zero,
+ * and a suitable result returned. The device is closed before returning.
+ */
+static PaError GropeDevice( snd_pcm_t* pcm, int isPlug, StreamDirection mode, int openBlocking,
+ PaAlsaDeviceInfo* devInfo, int* canMmap )
+{
+ PaError result = paNoError;
+ snd_pcm_hw_params_t *hwParams;
+ snd_pcm_uframes_t lowLatency = 512, highLatency = 2048;
+ unsigned int minChans, maxChans;
+ int* minChannels, * maxChannels;
+ double * defaultLowLatency, * defaultHighLatency, * defaultSampleRate =
+ &devInfo->baseDeviceInfo.defaultSampleRate;
+ double defaultSr = *defaultSampleRate;
+
+ assert( pcm );
+
+ if( StreamDirection_In == mode )
+ {
+ minChannels = &devInfo->minInputChannels;
+ maxChannels = &devInfo->baseDeviceInfo.maxInputChannels;
+ defaultLowLatency = &devInfo->baseDeviceInfo.defaultLowInputLatency;
+ defaultHighLatency = &devInfo->baseDeviceInfo.defaultHighInputLatency;
+ }
+ else
+ {
+ minChannels = &devInfo->minOutputChannels;
+ maxChannels = &devInfo->baseDeviceInfo.maxOutputChannels;
+ defaultLowLatency = &devInfo->baseDeviceInfo.defaultLowOutputLatency;
+ defaultHighLatency = &devInfo->baseDeviceInfo.defaultHighOutputLatency;
+ }
+
+ ENSURE_( snd_pcm_nonblock( pcm, 0 ), paUnanticipatedHostError );
+
+ snd_pcm_hw_params_alloca( &hwParams );
+ snd_pcm_hw_params_any( pcm, hwParams );
+
+ *canMmap = snd_pcm_hw_params_test_access( pcm, hwParams, SND_PCM_ACCESS_MMAP_INTERLEAVED ) >= 0 ||
+ snd_pcm_hw_params_test_access( pcm, hwParams, SND_PCM_ACCESS_MMAP_NONINTERLEAVED ) >= 0;
+
+ if( defaultSr >= 0 )
+ {
+ /* Could be that the device opened in one mode supports samplerates that the other mode wont have,
+ * so try again .. */
+ if( SetApproximateSampleRate( pcm, hwParams, defaultSr ) < 0 )
+ {
+ defaultSr = -1.;
+ PA_DEBUG(( "%s: Original default samplerate failed, trying again ..\n", __FUNCTION__ ));
+ }
+ }
+
+ if( defaultSr < 0. ) /* Default sample rate not set */
+ {
+ unsigned int sampleRate = 44100; /* Will contain approximate rate returned by alsa-lib */
+ if( snd_pcm_hw_params_set_rate_near( pcm, hwParams, &sampleRate, NULL ) < 0)
+ {
+ result = paUnanticipatedHostError;
+ goto error;
+ }
+ ENSURE_( GetExactSampleRate( hwParams, &defaultSr ), paUnanticipatedHostError );
+ }
+
+ ENSURE_( snd_pcm_hw_params_get_channels_min( hwParams, &minChans ), paUnanticipatedHostError );
+ ENSURE_( snd_pcm_hw_params_get_channels_max( hwParams, &maxChans ), paUnanticipatedHostError );
+ assert( maxChans <= INT_MAX );
+ assert( maxChans > 0 ); /* Weird linking issue could cause wrong version of ALSA symbols to be called,
+ resulting in zeroed values */
+
+ /* XXX: Limit to sensible number (ALSA plugins accept a crazy amount of channels)? */
+ if( isPlug && maxChans > 128 )
+ {
+ maxChans = 128;
+ PA_DEBUG(( "%s: Limiting number of plugin channels to %u\n", __FUNCTION__, maxChans ));
+ }
+
+ /* TWEAKME:
+ *
+ * Giving values for default min and max latency is not
+ * straightforward. Here are our objectives:
+ *
+ * * for low latency, we want to give the lowest value
+ * that will work reliably. This varies based on the
+ * sound card, kernel, CPU, etc. I think it is better
+ * to give sub-optimal latency than to give a number
+ * too low and cause dropouts. My conservative
+ * estimate at this point is to base it on 4096-sample
+ * latency at 44.1 kHz, which gives a latency of 23ms.
+ * * for high latency we want to give a large enough
+ * value that dropouts are basically impossible. This
+ * doesn't really require as much tweaking, since
+ * providing too large a number will just cause us to
+ * select the nearest setting that will work at stream
+ * config time.
+ */
+ ENSURE_( snd_pcm_hw_params_set_buffer_size_near( pcm, hwParams, &lowLatency ), paUnanticipatedHostError );
+
+ /* Have to reset hwParams, to set new buffer size */
+ ENSURE_( snd_pcm_hw_params_any( pcm, hwParams ), paUnanticipatedHostError );
+ ENSURE_( snd_pcm_hw_params_set_buffer_size_near( pcm, hwParams, &highLatency ), paUnanticipatedHostError );
+
+ *minChannels = (int)minChans;
+ *maxChannels = (int)maxChans;
+ *defaultSampleRate = defaultSr;
+ *defaultLowLatency = (double) lowLatency / *defaultSampleRate;
+ *defaultHighLatency = (double) highLatency / *defaultSampleRate;
+
+end:
+ snd_pcm_close( pcm );
+ return result;
+
+error:
+ goto end;
+}
+
+/* Initialize device info with invalid values (maxInputChannels and maxOutputChannels are set to zero since these indicate
+ * wether input/output is available) */
+static void InitializeDeviceInfo( PaDeviceInfo *deviceInfo )
+{
+ deviceInfo->structVersion = -1;
+ deviceInfo->name = NULL;
+ deviceInfo->hostApi = -1;
+ deviceInfo->maxInputChannels = 0;
+ deviceInfo->maxOutputChannels = 0;
+ deviceInfo->defaultLowInputLatency = -1.;
+ deviceInfo->defaultLowOutputLatency = -1.;
+ deviceInfo->defaultHighInputLatency = -1.;
+ deviceInfo->defaultHighOutputLatency = -1.;
+ deviceInfo->defaultSampleRate = -1.;
+}
+
+/* Helper struct */
+typedef struct
+{
+ char *alsaName;
+ char *name;
+ int isPlug;
+ int hasPlayback;
+ int hasCapture;
+} HwDevInfo;
+
+
+HwDevInfo predefinedNames[] = {
+ { "center_lfe", NULL, 0, 1, 0 },
+/* { "default", NULL, 0, 1, 0 }, */
+/* { "dmix", NULL, 0, 1, 0 }, */
+/* { "dpl", NULL, 0, 1, 0 }, */
+/* { "dsnoop", NULL, 0, 1, 0 }, */
+ { "front", NULL, 0, 1, 0 },
+ { "iec958", NULL, 0, 1, 0 },
+/* { "modem", NULL, 0, 1, 0 }, */
+ { "rear", NULL, 0, 1, 0 },
+ { "side", NULL, 0, 1, 0 },
+/* { "spdif", NULL, 0, 0, 0 }, */
+ { "surround40", NULL, 0, 1, 0 },
+ { "surround41", NULL, 0, 1, 0 },
+ { "surround50", NULL, 0, 1, 0 },
+ { "surround51", NULL, 0, 1, 0 },
+ { "surround71", NULL, 0, 1, 0 },
+ { NULL, NULL, 0, 1, 0 }
+};
+
+static const HwDevInfo *FindDeviceName( const char *name )
+{
+ int i;
+
+ for( i = 0; predefinedNames[i].alsaName; i++ )
+ {
+ if( strcmp( name, predefinedNames[i].alsaName ) == 0 )
+ {
+ return &predefinedNames[i];
+ }
+ }
+
+ return NULL;
+}
+
+static PaError PaAlsa_StrDup( PaAlsaHostApiRepresentation *alsaApi,
+ char **dst,
+ const char *src)
+{
+ PaError result = paNoError;
+ int len = strlen( src ) + 1;
+
+ /* PA_DEBUG(("PaStrDup %s %d\n", src, len)); */
+
+ PA_UNLESS( *dst = (char *)PaUtil_GroupAllocateMemory( alsaApi->allocations, len ),
+ paInsufficientMemory );
+ strncpy( *dst, src, len );
+
+error:
+ return result;
+}
+
+/* Disregard some standard plugins
+ */
+static int IgnorePlugin( const char *pluginId )
+{
+ static const char *ignoredPlugins[] = {"hw", "plughw", "plug", "dsnoop", "tee",
+ "file", "null", "shm", "cards", "rate_convert", NULL};
+ int i = 0;
+ while( ignoredPlugins[i] )
+ {
+ if( !strcmp( pluginId, ignoredPlugins[i] ) )
+ {
+ return 1;
+ }
+ ++i;
+ }
+
+ return 0;
+}
+
+/** Open PCM device.
+ *
+ * Wrapper around snd_pcm_open which may repeatedly retry opening a device if it is busy, for
+ * a certain time. This is because dmix may temporarily hold on to a device after it (dmix)
+ * has been opened and closed.
+ * @param mode: Open mode (e.g., SND_PCM_BLOCKING).
+ * @param waitOnBusy: Retry opening busy device for up to one second?
+ **/
+static int OpenPcm( snd_pcm_t **pcmp, const char *name, snd_pcm_stream_t stream, int mode, int waitOnBusy )
+{
+ int tries = 0, maxTries = waitOnBusy ? 100 : 0;
+ int ret = snd_pcm_open( pcmp, name, stream, mode );
+ for( tries = 0; tries < maxTries && -EBUSY == ret; ++tries )
+ {
+ Pa_Sleep( 10 );
+ ret = snd_pcm_open( pcmp, name, stream, mode );
+ if( -EBUSY != ret )
+ {
+ PA_DEBUG(( "%s: Successfully opened initially busy device after %d tries\n",
+ __FUNCTION__, tries ));
+ }
+ }
+ if( -EBUSY == ret )
+ {
+ PA_DEBUG(( "%s: Failed to open busy device '%s'\n",
+ __FUNCTION__, name ));
+ }
+
+ return ret;
+}
+
+static PaError FillInDevInfo( PaAlsaHostApiRepresentation *alsaApi, HwDevInfo* deviceName, int blocking,
+ PaAlsaDeviceInfo* devInfo, int* devIdx )
+{
+ PaError result = 0;
+ PaDeviceInfo *baseDeviceInfo = &devInfo->baseDeviceInfo;
+ snd_pcm_t *pcm;
+ int canMmap = -1;
+ PaUtilHostApiRepresentation *baseApi = &alsaApi->baseHostApiRep;
+
+ /* Zero fields */
+ InitializeDeviceInfo( baseDeviceInfo );
+
+ /* to determine device capabilities, we must open the device and query the
+ * hardware parameter configuration space */
+
+ /* Query capture */
+ if( deviceName->hasCapture &&
+ OpenPcm( &pcm, deviceName->alsaName, SND_PCM_STREAM_CAPTURE, blocking, 0 )
+ >= 0 )
+ {
+ if( GropeDevice( pcm, deviceName->isPlug, StreamDirection_In, blocking, devInfo,
+ &canMmap ) != paNoError )
+ {
+ /* Error */
+ PA_DEBUG(("%s: Failed groping %s for capture\n", __FUNCTION__, deviceName->alsaName));
+ goto end;
+ }
+ }
+
+ /* Query playback */
+ if( deviceName->hasPlayback &&
+ OpenPcm( &pcm, deviceName->alsaName, SND_PCM_STREAM_PLAYBACK, blocking, 0 )
+ >= 0 )
+ {
+ if( GropeDevice( pcm, deviceName->isPlug, StreamDirection_Out, blocking, devInfo,
+ &canMmap ) != paNoError )
+ {
+ /* Error */
+ PA_DEBUG(("%s: Failed groping %s for playback\n", __FUNCTION__, deviceName->alsaName));
+ goto end;
+ }
+ }
+
+ if( 0 == canMmap )
+ {
+ PA_DEBUG(("%s: Device %s doesn't support mmap\n", __FUNCTION__, deviceName->alsaName));
+ goto end;
+ }
+
+ baseDeviceInfo->structVersion = 2;
+ baseDeviceInfo->hostApi = alsaApi->hostApiIndex;
+ baseDeviceInfo->name = deviceName->name;
+ devInfo->alsaName = deviceName->alsaName;
+ devInfo->isPlug = deviceName->isPlug;
+
+ /* A: Storing pointer to PaAlsaDeviceInfo object as pointer to PaDeviceInfo object.
+ * Should now be safe to add device info, unless the device supports neither capture nor playback
+ */
+ if( baseDeviceInfo->maxInputChannels > 0 || baseDeviceInfo->maxOutputChannels > 0 )
+ {
+ /* Make device default if there isn't already one or it is the ALSA "default" device */
+ if( baseApi->info.defaultInputDevice == paNoDevice && baseDeviceInfo->maxInputChannels > 0 )
+ baseApi->info.defaultInputDevice = *devIdx;
+ if( (baseApi->info.defaultOutputDevice == paNoDevice || !strcmp(deviceName->alsaName,
+ "default" )) && baseDeviceInfo->maxOutputChannels > 0 )
+ {
+ baseApi->info.defaultOutputDevice = *devIdx;
+ PA_DEBUG(("Default output device: %s\n", deviceName->name));
+ }
+ PA_DEBUG(("%s: Adding device %s: %d\n", __FUNCTION__, deviceName->name, *devIdx));
+ baseApi->deviceInfos[*devIdx] = (PaDeviceInfo *) devInfo;
+ (*devIdx) += 1;
+ }
+
+end:
+ return result;
+}
+
+/* Build PaDeviceInfo list, ignore devices for which we cannot determine capabilities (possibly busy, sigh) */
+static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi )
+{
+ PaUtilHostApiRepresentation *baseApi = &alsaApi->baseHostApiRep;
+ PaAlsaDeviceInfo *deviceInfoArray;
+ int cardIdx = -1, devIdx = 0;
+ snd_ctl_card_info_t *cardInfo;
+ PaError result = paNoError;
+ size_t numDeviceNames = 0, maxDeviceNames = 1, i;
+ HwDevInfo *hwDevInfos = NULL;
+ snd_config_t *topNode = NULL;
+ snd_pcm_info_t *pcmInfo;
+ int res;
+ int blocking = SND_PCM_NONBLOCK;
+ char alsaCardName[50];
+#ifdef PA_ENABLE_DEBUG_OUTPUT
+ PaTime startTime = PaUtil_GetTime();
+#endif
+
+ if( getenv( "PA_ALSA_INITIALIZE_BLOCK" ) && atoi( getenv( "PA_ALSA_INITIALIZE_BLOCK" ) ) )
+ blocking = 0;
+
+ /* These two will be set to the first working input and output device, respectively */
+ baseApi->info.defaultInputDevice = paNoDevice;
+ baseApi->info.defaultOutputDevice = paNoDevice;
+
+ /* Gather info about hw devices
+
+ * snd_card_next() modifies the integer passed to it to be:
+ * the index of the first card if the parameter is -1
+ * the index of the next card if the parameter is the index of a card
+ * -1 if there are no more cards
+ *
+ * The function itself returns 0 if it succeeded. */
+ cardIdx = -1;
+ snd_ctl_card_info_alloca( &cardInfo );
+ snd_pcm_info_alloca( &pcmInfo );
+ while( snd_card_next( &cardIdx ) == 0 && cardIdx >= 0 )
+ {
+ char *cardName;
+ int devIdx = -1;
+ snd_ctl_t *ctl;
+ char buf[50];
+
+ snprintf( alsaCardName, sizeof (alsaCardName), "hw:%d", cardIdx );
+
+ /* Acquire name of card */
+ if( snd_ctl_open( &ctl, alsaCardName, 0 ) < 0 )
+ {
+ /* Unable to open card :( */
+ PA_DEBUG(( "%s: Unable to open device %s\n", __FUNCTION__, alsaCardName ));
+ continue;
+ }
+ snd_ctl_card_info( ctl, cardInfo );
+
+ PA_ENSURE( PaAlsa_StrDup( alsaApi, &cardName, snd_ctl_card_info_get_name( cardInfo )) );
+
+ while( snd_ctl_pcm_next_device( ctl, &devIdx ) == 0 && devIdx >= 0 )
+ {
+ char *alsaDeviceName, *deviceName;
+ size_t len;
+ int hasPlayback = 0, hasCapture = 0;
+ snprintf( buf, sizeof (buf), "hw:%d,%d", cardIdx, devIdx );
+
+ /* Obtain info about this particular device */
+ snd_pcm_info_set_device( pcmInfo, devIdx );
+ snd_pcm_info_set_subdevice( pcmInfo, 0 );
+ snd_pcm_info_set_stream( pcmInfo, SND_PCM_STREAM_CAPTURE );
+ if( snd_ctl_pcm_info( ctl, pcmInfo ) >= 0 )
+ {
+ hasCapture = 1;
+ }
+
+ snd_pcm_info_set_stream( pcmInfo, SND_PCM_STREAM_PLAYBACK );
+ if( snd_ctl_pcm_info( ctl, pcmInfo ) >= 0 )
+ {
+ hasPlayback = 1;
+ }
+
+ if( !hasPlayback && !hasCapture )
+ {
+ /* Error */
+ continue;
+ }
+
+ /* The length of the string written by snprintf plus terminating 0 */
+ len = snprintf( NULL, 0, "%s: %s (%s)", cardName, snd_pcm_info_get_name( pcmInfo ), buf ) + 1;
+ PA_UNLESS( deviceName = (char *)PaUtil_GroupAllocateMemory( alsaApi->allocations, len ),
+ paInsufficientMemory );
+ snprintf( deviceName, len, "%s: %s (%s)", cardName,
+ snd_pcm_info_get_name( pcmInfo ), buf );
+
+ ++numDeviceNames;
+ if( !hwDevInfos || numDeviceNames > maxDeviceNames )
+ {
+ maxDeviceNames *= 2;
+ PA_UNLESS( hwDevInfos = (HwDevInfo *) realloc( hwDevInfos, maxDeviceNames * sizeof (HwDevInfo) ),
+ paInsufficientMemory );
+ }
+
+ PA_ENSURE( PaAlsa_StrDup( alsaApi, &alsaDeviceName, buf ) );
+
+ hwDevInfos[ numDeviceNames - 1 ].alsaName = alsaDeviceName;
+ hwDevInfos[ numDeviceNames - 1 ].name = deviceName;
+ hwDevInfos[ numDeviceNames - 1 ].isPlug = 0;
+ hwDevInfos[ numDeviceNames - 1 ].hasPlayback = hasPlayback;
+ hwDevInfos[ numDeviceNames - 1 ].hasCapture = hasCapture;
+ }
+ snd_ctl_close( ctl );
+ }
+
+ /* Iterate over plugin devices */
+
+ if( NULL == snd_config )
+ {
+ /* snd_config_update is called implicitly by some functions, if this hasn't happened snd_config will be NULL (bleh) */
+ ENSURE_( snd_config_update(), paUnanticipatedHostError );
+ PA_DEBUG(( "Updating snd_config\n" ));
+ }
+ assert( snd_config );
+ if( (res = snd_config_search( snd_config, "pcm", &topNode )) >= 0 )
+ {
+ snd_config_iterator_t i, next;
+
+ snd_config_for_each( i, next, topNode )
+ {
+ const char *tpStr = "unknown", *idStr = NULL;
+ int err = 0;
+
+ char *alsaDeviceName, *deviceName;
+ const HwDevInfo *predefined = NULL;
+ snd_config_t *n = snd_config_iterator_entry( i ), * tp = NULL;;
+
+ if( (err = snd_config_search( n, "type", &tp )) < 0 )
+ {
+ if( -ENOENT != err )
+ {
+ ENSURE_(err, paUnanticipatedHostError);
+ }
+ }
+ else
+ {
+ ENSURE_( snd_config_get_string( tp, &tpStr ), paUnanticipatedHostError );
+ }
+ ENSURE_( snd_config_get_id( n, &idStr ), paUnanticipatedHostError );
+ if( IgnorePlugin( idStr ) )
+ {
+ PA_DEBUG(( "%s: Ignoring ALSA plugin device %s of type %s\n", __FUNCTION__, idStr, tpStr ));
+ continue;
+ }
+ PA_DEBUG(( "%s: Found plugin %s of type %s\n", __FUNCTION__, idStr, tpStr ));
+
+ PA_UNLESS( alsaDeviceName = (char*)PaUtil_GroupAllocateMemory( alsaApi->allocations,
+ strlen(idStr) + 6 ), paInsufficientMemory );
+ strcpy( alsaDeviceName, idStr );
+ PA_UNLESS( deviceName = (char*)PaUtil_GroupAllocateMemory( alsaApi->allocations,
+ strlen(idStr) + 1 ), paInsufficientMemory );
+ strcpy( deviceName, idStr );
+
+ ++numDeviceNames;
+ if( !hwDevInfos || numDeviceNames > maxDeviceNames )
+ {
+ maxDeviceNames *= 2;
+ PA_UNLESS( hwDevInfos = (HwDevInfo *) realloc( hwDevInfos, maxDeviceNames * sizeof (HwDevInfo) ),
+ paInsufficientMemory );
+ }
+
+ predefined = FindDeviceName( alsaDeviceName );
+
+ hwDevInfos[numDeviceNames - 1].alsaName = alsaDeviceName;
+ hwDevInfos[numDeviceNames - 1].name = deviceName;
+ hwDevInfos[numDeviceNames - 1].isPlug = 1;
+
+ if( predefined )
+ {
+ hwDevInfos[numDeviceNames - 1].hasPlayback =
+ predefined->hasPlayback;
+ hwDevInfos[numDeviceNames - 1].hasCapture =
+ predefined->hasCapture;
+ }
+ else
+ {
+ hwDevInfos[numDeviceNames - 1].hasPlayback = 1;
+ hwDevInfos[numDeviceNames - 1].hasCapture = 1;
+ }
+ }
+ }
+ else
+ PA_DEBUG(( "%s: Iterating over ALSA plugins failed: %s\n", __FUNCTION__, snd_strerror( res ) ));
+
+ /* allocate deviceInfo memory based on the number of devices */
+ PA_UNLESS( baseApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+ alsaApi->allocations, sizeof(PaDeviceInfo*) * (numDeviceNames) ), paInsufficientMemory );
+
+ /* allocate all device info structs in a contiguous block */
+ PA_UNLESS( deviceInfoArray = (PaAlsaDeviceInfo*)PaUtil_GroupAllocateMemory(
+ alsaApi->allocations, sizeof(PaAlsaDeviceInfo) * numDeviceNames ), paInsufficientMemory );
+
+ /* Loop over list of cards, filling in info. If a device is deemed unavailable (can't get name),
+ * it's ignored.
+ *
+ * Note that we do this in two stages. This is a workaround owing to the fact that the 'dmix'
+ * plugin may cause the underlying hardware device to be busy for a short while even after it
+ * (dmix) is closed. The 'default' plugin may also point to the dmix plugin, so the same goes
+ * for this.
+ */
+
+ for( i = 0, devIdx = 0; i < numDeviceNames; ++i )
+ {
+ PaAlsaDeviceInfo* devInfo = &deviceInfoArray[i];
+ HwDevInfo* hwInfo = &hwDevInfos[i];
+ if( !strcmp( hwInfo->name, "dmix" ) || !strcmp( hwInfo->name, "default" ) )
+ {
+ continue;
+ }
+
+ PA_ENSURE( FillInDevInfo( alsaApi, hwInfo, blocking, devInfo, &devIdx ) );
+ }
+ assert( devIdx < numDeviceNames );
+ /* Now inspect 'dmix' and 'default' plugins */
+ for( i = 0; i < numDeviceNames; ++i )
+ {
+ PaAlsaDeviceInfo* devInfo = &deviceInfoArray[i];
+ HwDevInfo* hwInfo = &hwDevInfos[i];
+ if( strcmp( hwInfo->name, "dmix" ) && strcmp( hwInfo->name, "default" ) )
+ {
+ continue;
+ }
+
+ PA_ENSURE( FillInDevInfo( alsaApi, hwInfo, blocking, devInfo,
+ &devIdx ) );
+ }
+ free( hwDevInfos );
+
+ baseApi->info.deviceCount = devIdx; /* Number of successfully queried devices */
+
+#ifdef PA_ENABLE_DEBUG_OUTPUT
+ PA_DEBUG(( "%s: Building device list took %f seconds\n", __FUNCTION__, PaUtil_GetTime() - startTime ));
+#endif
+
+end:
+ return result;
+
+error:
+ /* No particular action */
+ goto end;
+}
+
+/* Check against known device capabilities */
+static PaError ValidateParameters( const PaStreamParameters *parameters, PaUtilHostApiRepresentation *hostApi, StreamDirection mode )
+{
+ PaError result = paNoError;
+ int maxChans;
+ const PaAlsaDeviceInfo *deviceInfo = NULL;
+ assert( parameters );
+
+ if( parameters->device != paUseHostApiSpecificDeviceSpecification )
+ {
+ assert( parameters->device < hostApi->info.deviceCount );
+ PA_UNLESS( parameters->hostApiSpecificStreamInfo == NULL, paBadIODeviceCombination );
+ deviceInfo = GetDeviceInfo( hostApi, parameters->device );
+ }
+ else
+ {
+ const PaAlsaStreamInfo *streamInfo = parameters->hostApiSpecificStreamInfo;
+
+ PA_UNLESS( parameters->device == paUseHostApiSpecificDeviceSpecification, paInvalidDevice );
+ PA_UNLESS( streamInfo->size == sizeof (PaAlsaStreamInfo) && streamInfo->version == 1,
+ paIncompatibleHostApiSpecificStreamInfo );
+ PA_UNLESS( streamInfo->deviceString != NULL, paInvalidDevice );
+
+ /* Skip further checking */
+ return paNoError;
+ }
+
+ assert( deviceInfo );
+ assert( parameters->hostApiSpecificStreamInfo == NULL );
+ maxChans = (StreamDirection_In == mode ? deviceInfo->baseDeviceInfo.maxInputChannels :
+ deviceInfo->baseDeviceInfo.maxOutputChannels);
+ PA_UNLESS( parameters->channelCount <= maxChans, paInvalidChannelCount );
+
+error:
+ return result;
+}
+
+/* Given an open stream, what sample formats are available? */
+static PaSampleFormat GetAvailableFormats( snd_pcm_t *pcm )
+{
+ PaSampleFormat available = 0;
+ snd_pcm_hw_params_t *hwParams;
+ snd_pcm_hw_params_alloca( &hwParams );
+
+ snd_pcm_hw_params_any( pcm, hwParams );
+
+ if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_FLOAT ) >= 0)
+ available |= paFloat32;
+
+ if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S32 ) >= 0)
+ available |= paInt32;
+
+#ifdef PA_LITTLE_ENDIAN
+ if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24_3LE ) >= 0)
+ available |= paInt24;
+#elif defined PA_BIG_ENDIAN
+ if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S24_3BE ) >= 0)
+ available |= paInt24;
+#endif
+
+ if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S16 ) >= 0)
+ available |= paInt16;
+
+ if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_U8 ) >= 0)
+ available |= paUInt8;
+
+ if( snd_pcm_hw_params_test_format( pcm, hwParams, SND_PCM_FORMAT_S8 ) >= 0)
+ available |= paInt8;
+
+ return available;
+}
+
+static snd_pcm_format_t Pa2AlsaFormat( PaSampleFormat paFormat )
+{
+ switch( paFormat )
+ {
+ case paFloat32:
+ return SND_PCM_FORMAT_FLOAT;
+
+ case paInt16:
+ return SND_PCM_FORMAT_S16;
+
+ case paInt24:
+#ifdef PA_LITTLE_ENDIAN
+ return SND_PCM_FORMAT_S24_3LE;
+#elif defined PA_BIG_ENDIAN
+ return SND_PCM_FORMAT_S24_3BE;
+#endif
+
+ case paInt32:
+ return SND_PCM_FORMAT_S32;
+
+ case paInt8:
+ return SND_PCM_FORMAT_S8;
+
+ case paUInt8:
+ return SND_PCM_FORMAT_U8;
+
+ default:
+ return SND_PCM_FORMAT_UNKNOWN;
+ }
+}
+
+/** Open an ALSA pcm handle.
+ *
+ * The device to be open can be specified in a custom PaAlsaStreamInfo struct, or it will be a device number. In case of a
+ * device number, it maybe specified through an env variable (PA_ALSA_PLUGHW) that we should open the corresponding plugin
+ * device.
+ */
+static PaError AlsaOpen( const PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *params, StreamDirection
+ streamDir, snd_pcm_t **pcm )
+{
+ PaError result = paNoError;
+ int ret;
+ char dnameArray[50];
+ const char* deviceName = dnameArray;
+ const PaAlsaDeviceInfo *deviceInfo = NULL;
+ PaAlsaStreamInfo *streamInfo = (PaAlsaStreamInfo *)params->hostApiSpecificStreamInfo;
+
+ if( !streamInfo )
+ {
+ int usePlug = 0;
+ deviceInfo = GetDeviceInfo( hostApi, params->device );
+
+ /* If device name starts with hw: and PA_ALSA_PLUGHW is 1, we open the plughw device instead */
+ if( !strncmp( "hw:", deviceInfo->alsaName, 3 ) && getenv( "PA_ALSA_PLUGHW" ) )
+ usePlug = atoi( getenv( "PA_ALSA_PLUGHW" ) );
+ if( usePlug )
+ snprintf( dnameArray, 50, "plug%s", deviceInfo->alsaName );
+ else
+ deviceName = deviceInfo->alsaName;
+ }
+ else
+ deviceName = streamInfo->deviceString;
+
+ PA_DEBUG(( "%s: Opening device %s\n", __FUNCTION__, deviceName ));
+ if( (ret = OpenPcm( pcm, deviceName, streamDir == StreamDirection_In ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
+ SND_PCM_NONBLOCK, 1 )) < 0 )
+ {
+ /* Not to be closed */
+ *pcm = NULL;
+ ENSURE_( ret, -EBUSY == ret ? paDeviceUnavailable : paBadIODeviceCombination );
+ }
+ ENSURE_( snd_pcm_nonblock( *pcm, 0 ), paUnanticipatedHostError );
+
+end:
+ return result;
+
+error:
+ goto end;
+}
+
+static PaError TestParameters( const PaUtilHostApiRepresentation *hostApi, const PaStreamParameters *parameters,
+ double sampleRate, StreamDirection streamDir )
+{
+ PaError result = paNoError;
+ snd_pcm_t *pcm = NULL;
+ PaSampleFormat availableFormats;
+ /* We are able to adapt to a number of channels less than what the device supports */
+ unsigned int numHostChannels;
+ PaSampleFormat hostFormat;
+ snd_pcm_hw_params_t *hwParams;
+ snd_pcm_hw_params_alloca( &hwParams );
+
+ if( !parameters->hostApiSpecificStreamInfo )
+ {
+ const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( hostApi, parameters->device );
+ numHostChannels = PA_MAX( parameters->channelCount, StreamDirection_In == streamDir ?
+ devInfo->minInputChannels : devInfo->minOutputChannels );
+ }
+ else
+ numHostChannels = parameters->channelCount;
+
+ PA_ENSURE( AlsaOpen( hostApi, parameters, streamDir, &pcm ) );
+
+ snd_pcm_hw_params_any( pcm, hwParams );
+
+ if( SetApproximateSampleRate( pcm, hwParams, sampleRate ) < 0 )
+ {
+ result = paInvalidSampleRate;
+ goto error;
+ }
+
+ if( snd_pcm_hw_params_set_channels( pcm, hwParams, numHostChannels ) < 0 )
+ {
+ result = paInvalidChannelCount;
+ goto error;
+ }
+
+ /* See if we can find a best possible match */
+ availableFormats = GetAvailableFormats( pcm );
+ PA_ENSURE( hostFormat = PaUtil_SelectClosestAvailableFormat( availableFormats, parameters->sampleFormat ) );
+ ENSURE_( snd_pcm_hw_params_set_format( pcm, hwParams, Pa2AlsaFormat( hostFormat ) ), paUnanticipatedHostError );
+
+ {
+ /* It happens that this call fails because the device is busy */
+ int ret = 0;
+ if( (ret = snd_pcm_hw_params( pcm, hwParams )) < 0)
+ {
+ if( -EINVAL == ret )
+ {
+ /* Don't know what to return here */
+ result = paBadIODeviceCombination;
+ goto error;
+ }
+ else if( -EBUSY == ret )
+ {
+ result = paDeviceUnavailable;
+ PA_DEBUG(( "%s: Device is busy\n", __FUNCTION__ ));
+ }
+ else
+ {
+ result = paUnanticipatedHostError;
+ }
+
+ ENSURE_( ret, result );
+ }
+ }
+
+end:
+ if( pcm )
+ {
+ snd_pcm_close( pcm );
+ }
+ return result;
+
+error:
+ goto end;
+}
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate )
+{
+ int inputChannelCount = 0, outputChannelCount = 0;
+ PaSampleFormat inputSampleFormat, outputSampleFormat;
+ PaError result = paFormatIsSupported;
+
+ if( inputParameters )
+ {
+ PA_ENSURE( ValidateParameters( inputParameters, hostApi, StreamDirection_In ) );
+
+ inputChannelCount = inputParameters->channelCount;
+ inputSampleFormat = inputParameters->sampleFormat;
+ }
+
+ if( outputParameters )
+ {
+ PA_ENSURE( ValidateParameters( outputParameters, hostApi, StreamDirection_Out ) );
+
+ outputChannelCount = outputParameters->channelCount;
+ outputSampleFormat = outputParameters->sampleFormat;
+ }
+
+ if( inputChannelCount )
+ {
+ if( (result = TestParameters( hostApi, inputParameters, sampleRate, StreamDirection_In ))
+ != paNoError )
+ goto error;
+ }
+ if ( outputChannelCount )
+ {
+ if( (result = TestParameters( hostApi, outputParameters, sampleRate, StreamDirection_Out ))
+ != paNoError )
+ goto error;
+ }
+
+ return paFormatIsSupported;
+
+error:
+ return result;
+}
+
+static PaError PaAlsaStreamComponent_Initialize( PaAlsaStreamComponent *self, PaAlsaHostApiRepresentation *alsaApi,
+ const PaStreamParameters *params, StreamDirection streamDir, int callbackMode )
+{
+ PaError result = paNoError;
+ PaSampleFormat userSampleFormat = params->sampleFormat, hostSampleFormat;
+ assert( params->channelCount > 0 );
+
+ /* Make sure things have an initial value */
+ memset( self, 0, sizeof (PaAlsaStreamComponent) );
+
+ if( NULL == params->hostApiSpecificStreamInfo )
+ {
+ const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( &alsaApi->baseHostApiRep, params->device );
+ self->numHostChannels = PA_MAX( params->channelCount, StreamDirection_In == streamDir ? devInfo->minInputChannels
+ : devInfo->minOutputChannels );
+ }
+ else
+ {
+ /* We're blissfully unaware of the minimum channelCount */
+ self->numHostChannels = params->channelCount;
+ }
+
+ self->device = params->device;
+
+ PA_ENSURE( AlsaOpen( &alsaApi->baseHostApiRep, params, streamDir, &self->pcm ) );
+ self->nfds = snd_pcm_poll_descriptors_count( self->pcm );
+ hostSampleFormat = PaUtil_SelectClosestAvailableFormat( GetAvailableFormats( self->pcm ), userSampleFormat );
+
+ self->hostSampleFormat = hostSampleFormat;
+ self->nativeFormat = Pa2AlsaFormat( hostSampleFormat );
+ self->hostInterleaved = self->userInterleaved = !(userSampleFormat & paNonInterleaved);
+ self->numUserChannels = params->channelCount;
+ self->streamDir = streamDir;
+
+ if( !callbackMode && !self->userInterleaved )
+ {
+ /* Pre-allocate non-interleaved user provided buffers */
+ PA_UNLESS( self->userBuffers = PaUtil_AllocateMemory( sizeof (void *) * self->numUserChannels ),
+ paInsufficientMemory );
+ }
+
+error:
+ return result;
+}
+
+static void PaAlsaStreamComponent_Terminate( PaAlsaStreamComponent *self )
+{
+ snd_pcm_close( self->pcm );
+ if( self->userBuffers )
+ PaUtil_FreeMemory( self->userBuffers );
+}
+
+/*
+static int nearbyint_(float value) {
+ if( value - (int)value > .5 )
+ return (int)ceil( value );
+ return (int)floor( value );
+}
+*/
+
+/** Initiate configuration, preparing for determining a period size suitable for both capture and playback components.
+ *
+ */
+static PaError PaAlsaStreamComponent_InitialConfigure( PaAlsaStreamComponent *self, const PaStreamParameters *params,
+ int primeBuffers, snd_pcm_hw_params_t *hwParams, double *sampleRate )
+{
+ /* Configuration consists of setting all of ALSA's parameters.
+ * These parameters come in two flavors: hardware parameters
+ * and software paramters. Hardware parameters will affect
+ * the way the device is initialized, software parameters
+ * affect the way ALSA interacts with me, the user-level client.
+ */
+
+ PaError result = paNoError;
+ snd_pcm_access_t accessMode, alternateAccessMode;
+ int dir = 0;
+ snd_pcm_t *pcm = self->pcm;
+ double sr = *sampleRate;
+ unsigned int minPeriods = 2;
+
+ /* self->framesPerBuffer = framesPerHostBuffer; */
+
+ /* ... fill up the configuration space with all possibile
+ * combinations of parameters this device will accept */
+ ENSURE_( snd_pcm_hw_params_any( pcm, hwParams ), paUnanticipatedHostError );
+
+ ENSURE_( snd_pcm_hw_params_set_periods_integer( pcm, hwParams ), paUnanticipatedHostError );
+ /* I think there should be at least 2 periods (even though ALSA doesn't appear to enforce this) */
+ dir = 0;
+ ENSURE_( snd_pcm_hw_params_set_periods_min( pcm, hwParams, &minPeriods, &dir ), paUnanticipatedHostError );
+
+ if( self->userInterleaved )
+ {
+ accessMode = SND_PCM_ACCESS_MMAP_INTERLEAVED;
+ alternateAccessMode = SND_PCM_ACCESS_MMAP_NONINTERLEAVED;
+ }
+ else
+ {
+ accessMode = SND_PCM_ACCESS_MMAP_NONINTERLEAVED;
+ alternateAccessMode = SND_PCM_ACCESS_MMAP_INTERLEAVED;
+ }
+ /* If requested access mode fails, try alternate mode */
+ if( snd_pcm_hw_params_set_access( pcm, hwParams, accessMode ) < 0 )
+ {
+ int err = 0;
+ if( (err = snd_pcm_hw_params_set_access( pcm, hwParams, alternateAccessMode )) < 0)
+ {
+ result = paUnanticipatedHostError;
+ if( -EINVAL == err )
+ {
+ PaUtil_SetLastHostErrorInfo( paALSA, err, "PA ALSA requires that a device supports mmap access" );
+ }
+ else
+ {
+ PaUtil_SetLastHostErrorInfo( paALSA, err, snd_strerror( err ) );
+ }
+ goto error;
+ }
+ /* Flip mode */
+ self->hostInterleaved = !self->userInterleaved;
+ }
+
+ ENSURE_( snd_pcm_hw_params_set_format( pcm, hwParams, self->nativeFormat ), paUnanticipatedHostError );
+
+ ENSURE_( SetApproximateSampleRate( pcm, hwParams, sr ), paInvalidSampleRate );
+ ENSURE_( GetExactSampleRate( hwParams, &sr ), paUnanticipatedHostError );
+ /* reject if there's no sample rate within 1% of the one requested */
+ if( (fabs( *sampleRate - sr ) / *sampleRate) > 0.01 )
+ {
+ PA_DEBUG(("%s: Wanted %f, closest sample rate was %d\n", __FUNCTION__, sampleRate, sr ));
+ PA_ENSURE( paInvalidSampleRate );
+ }
+
+ ENSURE_( snd_pcm_hw_params_set_channels( pcm, hwParams, self->numHostChannels ), paInvalidChannelCount );
+
+ *sampleRate = sr;
+
+end:
+ return result;
+
+error:
+ /* No particular action */
+ goto end;
+}
+
+/** Finish the configuration of the component's ALSA device.
+ *
+ * As part of this method, the component's bufferSize attribute will be set.
+ * @param latency: The latency for this component.
+ */
+static PaError PaAlsaStreamComponent_FinishConfigure( PaAlsaStreamComponent *self, snd_pcm_hw_params_t* hwParams,
+ const PaStreamParameters *params, int primeBuffers, double sampleRate, PaTime* latency )
+{
+ PaError result = paNoError;
+ snd_pcm_sw_params_t* swParams;
+ snd_pcm_uframes_t bufSz = 0;
+ *latency = -1.;
+
+ snd_pcm_sw_params_alloca( &swParams );
+
+ bufSz = params->suggestedLatency * sampleRate;
+ ENSURE_( snd_pcm_hw_params_set_buffer_size_near( self->pcm, hwParams, &bufSz ), paUnanticipatedHostError );
+
+ /* Set the parameters! */
+ {
+ int r = snd_pcm_hw_params( self->pcm, hwParams );
+#ifdef PA_ENABLE_DEBUG_OUTPUT
+ if( r < 0 )
+ {
+ snd_output_t *output = NULL;
+ snd_output_stdio_attach( &output, stderr, 0 );
+ snd_pcm_hw_params_dump( hwParams, output );
+ }
+#endif
+ ENSURE_(r, paUnanticipatedHostError );
+ }
+ ENSURE_( snd_pcm_hw_params_get_buffer_size( hwParams, &self->bufferSize ), paUnanticipatedHostError );
+ /* Latency in seconds */
+ *latency = self->bufferSize / sampleRate;
+
+ /* Now software parameters... */
+ ENSURE_( snd_pcm_sw_params_current( self->pcm, swParams ), paUnanticipatedHostError );
+
+ ENSURE_( snd_pcm_sw_params_set_start_threshold( self->pcm, swParams, self->framesPerBuffer ), paUnanticipatedHostError );
+ ENSURE_( snd_pcm_sw_params_set_stop_threshold( self->pcm, swParams, self->bufferSize ), paUnanticipatedHostError );
+
+ /* Silence buffer in the case of underrun */
+ if( !primeBuffers ) /* XXX: Make sense? */
+ {
+ snd_pcm_uframes_t boundary;
+ ENSURE_( snd_pcm_sw_params_get_boundary( swParams, &boundary ), paUnanticipatedHostError );
+ ENSURE_( snd_pcm_sw_params_set_silence_threshold( self->pcm, swParams, 0 ), paUnanticipatedHostError );
+ ENSURE_( snd_pcm_sw_params_set_silence_size( self->pcm, swParams, boundary ), paUnanticipatedHostError );
+ }
+
+ ENSURE_( snd_pcm_sw_params_set_avail_min( self->pcm, swParams, self->framesPerBuffer ), paUnanticipatedHostError );
+ ENSURE_( snd_pcm_sw_params_set_xfer_align( self->pcm, swParams, 1 ), paUnanticipatedHostError );
+ ENSURE_( snd_pcm_sw_params_set_tstamp_mode( self->pcm, swParams, SND_PCM_TSTAMP_MMAP ), paUnanticipatedHostError );
+
+ /* Set the parameters! */
+ ENSURE_( snd_pcm_sw_params( self->pcm, swParams ), paUnanticipatedHostError );
+
+error:
+ return result;
+}
+
+static PaError PaAlsaStream_Initialize( PaAlsaStream *self, PaAlsaHostApiRepresentation *alsaApi, const PaStreamParameters *inParams,
+ const PaStreamParameters *outParams, double sampleRate, unsigned long framesPerUserBuffer, PaStreamCallback callback,
+ PaStreamFlags streamFlags, void *userData )
+{
+ PaError result = paNoError;
+ assert( self );
+
+ memset( self, 0, sizeof (PaAlsaStream) );
+
+ if( NULL != callback )
+ {
+ PaUtil_InitializeStreamRepresentation( &self->streamRepresentation,
+ &alsaApi->callbackStreamInterface,
+ callback, userData );
+ self->callbackMode = 1;
+ }
+ else
+ {
+ PaUtil_InitializeStreamRepresentation( &self->streamRepresentation,
+ &alsaApi->blockingStreamInterface,
+ NULL, userData );
+ }
+
+ self->framesPerUserBuffer = framesPerUserBuffer;
+ self->neverDropInput = streamFlags & paNeverDropInput;
+ /* XXX: Ignore paPrimeOutputBuffersUsingStreamCallback untill buffer priming is fully supported in pa_process.c */
+ /*
+ if( outParams & streamFlags & paPrimeOutputBuffersUsingStreamCallback )
+ self->primeBuffers = 1;
+ */
+ memset( &self->capture, 0, sizeof (PaAlsaStreamComponent) );
+ memset( &self->playback, 0, sizeof (PaAlsaStreamComponent) );
+ if( inParams )
+ {
+ PA_ENSURE( PaAlsaStreamComponent_Initialize( &self->capture, alsaApi, inParams, StreamDirection_In, NULL != callback ) );
+ }
+ if( outParams )
+ {
+ PA_ENSURE( PaAlsaStreamComponent_Initialize( &self->playback, alsaApi, outParams, StreamDirection_Out, NULL != callback ) );
+ }
+
+ assert( self->capture.nfds || self->playback.nfds );
+
+ PA_UNLESS( self->pfds = (struct pollfd*)PaUtil_AllocateMemory( (self->capture.nfds +
+ self->playback.nfds) * sizeof (struct pollfd) ), paInsufficientMemory );
+
+ PaUtil_InitializeCpuLoadMeasurer( &self->cpuLoadMeasurer, sampleRate );
+ ASSERT_CALL_( PaUnixMutex_Initialize( &self->stateMtx ), paNoError );
+
+error:
+ return result;
+}
+
+/** Free resources associated with stream, and eventually stream itself.
+ *
+ * Frees allocated memory, and terminates individual StreamComponents.
+ */
+static void PaAlsaStream_Terminate( PaAlsaStream *self )
+{
+ assert( self );
+
+ if( self->capture.pcm )
+ {
+ PaAlsaStreamComponent_Terminate( &self->capture );
+ }
+ if( self->playback.pcm )
+ {
+ PaAlsaStreamComponent_Terminate( &self->playback );
+ }
+
+ PaUtil_FreeMemory( self->pfds );
+ ASSERT_CALL_( PaUnixMutex_Terminate( &self->stateMtx ), paNoError );
+
+ PaUtil_FreeMemory( self );
+}
+
+/** Calculate polling timeout
+ *
+ * @param frames Time to wait
+ * @return Polling timeout in milliseconds
+ */
+static int CalculatePollTimeout( const PaAlsaStream *stream, unsigned long frames )
+{
+ assert( stream->streamRepresentation.streamInfo.sampleRate > 0.0 );
+ /* Period in msecs, rounded up */
+ return (int)ceil( 1000 * frames / stream->streamRepresentation.streamInfo.sampleRate );
+}
+
+/** Determine size per host buffer.
+ *
+ * During this method call, the component's framesPerBuffer attribute gets computed, and the corresponding period size
+ * gets configured for the device.
+ * @param accurate: If the configured period size is non-integer, this will be set to 0.
+ */
+static PaError PaAlsaStreamComponent_DetermineFramesPerBuffer( PaAlsaStreamComponent* self, const PaStreamParameters* params,
+ unsigned long framesPerUserBuffer, double sampleRate, snd_pcm_hw_params_t* hwParams, int* accurate )
+{
+ PaError result = paNoError;
+ unsigned long bufferSize = params->suggestedLatency * sampleRate, framesPerHostBuffer;
+ int dir = 0;
+
+ {
+ snd_pcm_uframes_t tmp;
+ snd_pcm_hw_params_get_buffer_size_min( hwParams, &tmp );
+ bufferSize = PA_MAX( bufferSize, tmp );
+ snd_pcm_hw_params_get_buffer_size_max( hwParams, &tmp );
+ bufferSize = PA_MIN( bufferSize, tmp );
+ }
+
+ assert( bufferSize > 0 );
+
+ if( framesPerUserBuffer != paFramesPerBufferUnspecified )
+ {
+ /* Preferably the host buffer size should be a multiple of the user buffer size */
+
+ if( bufferSize > framesPerUserBuffer )
+ {
+ snd_pcm_uframes_t remainder = bufferSize % framesPerUserBuffer;
+ if( remainder > framesPerUserBuffer / 2. )
+ bufferSize += framesPerUserBuffer - remainder;
+ else
+ bufferSize -= remainder;
+
+ assert( bufferSize % framesPerUserBuffer == 0 );
+ }
+ else if( framesPerUserBuffer % bufferSize != 0 )
+ {
+ /* Find a good compromise between user specified latency and buffer size */
+ if( bufferSize > framesPerUserBuffer * .75 )
+ {
+ bufferSize = framesPerUserBuffer;
+ }
+ else
+ {
+ snd_pcm_uframes_t newSz = framesPerUserBuffer;
+ while( newSz / 2 >= bufferSize )
+ {
+ if( framesPerUserBuffer % (newSz / 2) != 0 )
+ {
+ /* No use dividing any further */
+ break;
+ }
+ newSz /= 2;
+ }
+ bufferSize = newSz;
+ }
+
+ assert( framesPerUserBuffer % bufferSize == 0 );
+ }
+ }
+
+ /* Using the base number of periods, we try to approximate the suggested latency (+1 period),
+ finding a combination of period/buffer size which best fits these constraints */
+ {
+ unsigned numPeriods = numPeriods_, maxPeriods = 0;
+ /* It may be that the device only supports 2 periods for instance */
+ dir = 0;
+ ENSURE_( snd_pcm_hw_params_get_periods_max( hwParams, &maxPeriods, &dir ), paUnanticipatedHostError );
+ assert( maxPeriods > 1 );
+ numPeriods = PA_MIN( maxPeriods, numPeriods );
+
+ if( framesPerUserBuffer != paFramesPerBufferUnspecified )
+ {
+ /* Try to get a power-of-two of the user buffer size. */
+ framesPerHostBuffer = framesPerUserBuffer;
+ if( framesPerHostBuffer < bufferSize )
+ {
+ while( bufferSize / framesPerHostBuffer > numPeriods )
+ {
+ framesPerHostBuffer *= 2;
+ }
+ /* One extra period is preferrable to one less (should be more robust) */
+ if( bufferSize / framesPerHostBuffer < numPeriods )
+ {
+ framesPerHostBuffer /= 2;
+ }
+ }
+ else
+ {
+ while( bufferSize / framesPerHostBuffer < numPeriods )
+ {
+ if( framesPerUserBuffer % (framesPerHostBuffer / 2) != 0 )
+ {
+ /* Can't be divided any further */
+ break;
+ }
+ framesPerHostBuffer /= 2;
+ }
+ }
+
+ if( framesPerHostBuffer < framesPerUserBuffer )
+ {
+ assert( framesPerUserBuffer % framesPerHostBuffer == 0 );
+ if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 )
+ {
+ if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer * 2, 0 ) == 0 )
+ framesPerHostBuffer *= 2;
+ else if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer / 2, 0 ) == 0 )
+ framesPerHostBuffer /= 2;
+ }
+ }
+ else
+ {
+ assert( framesPerHostBuffer % framesPerUserBuffer == 0 );
+ if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer, 0 ) < 0 )
+ {
+ if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer + framesPerUserBuffer, 0 ) == 0 )
+ framesPerHostBuffer += framesPerUserBuffer;
+ else if( snd_pcm_hw_params_test_period_size( self->pcm, hwParams, framesPerHostBuffer - framesPerUserBuffer, 0 ) == 0 )
+ framesPerHostBuffer -= framesPerUserBuffer;
+ }
+ }
+ }
+ else
+ {
+ framesPerHostBuffer = bufferSize / numPeriods;
+ }
+ }
+
+ assert( framesPerHostBuffer > 0 );
+ {
+ snd_pcm_uframes_t min = 0, max = 0;
+ ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParams, &min, NULL ), paUnanticipatedHostError );
+ ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParams, &max, NULL ), paUnanticipatedHostError );
+
+ if( framesPerHostBuffer < min )
+ {
+ PA_DEBUG(( "%s: The determined period size (%lu) is less than minimum (%lu)\n", __FUNCTION__,
+ framesPerHostBuffer, min ));
+ framesPerHostBuffer = min;
+ }
+ else if( framesPerHostBuffer > max )
+ {
+ PA_DEBUG(( "%s: The determined period size (%lu) is greater than maximum (%lu)\n", __FUNCTION__,
+ framesPerHostBuffer, max ));
+ framesPerHostBuffer = max;
+ }
+
+ assert( framesPerHostBuffer >= min && framesPerHostBuffer <= max );
+ dir = 0;
+ ENSURE_( snd_pcm_hw_params_set_period_size_near( self->pcm, hwParams, &framesPerHostBuffer, &dir ),
+ paUnanticipatedHostError );
+ if( dir != 0 )
+ {
+ PA_DEBUG(( "%s: The configured period size is non-integer.\n", __FUNCTION__, dir ));
+ *accurate = 0;
+ }
+ }
+ self->framesPerBuffer = framesPerHostBuffer;
+
+error:
+ return result;
+}
+
+/* We need to determine how many frames per host buffer (period) to use. Our
+ * goals are to provide the best possible performance, but also to
+ * honor the requested latency settings as closely as we can. Therefore this
+ * decision is based on:
+ *
+ * - the period sizes that playback and/or capture support. The
+ * host buffer size has to be one of these.
+ * - the number of periods that playback and/or capture support.
+ *
+ * We want to make period_size*(num_periods-1) to be as close as possible
+ * to latency*rate for both playback and capture.
+ *
+ * This method will determine suitable period sizes for capture and playback handles, and report the maximum number of
+ * frames per host buffer. The latter is relevant, in case we should be so unfortunate that the period size differs
+ * between capture and playback. If this should happen, the stream's hostBufferSizeMode attribute will be set to
+ * paUtilBoundedHostBufferSize, because the best we can do is limit the size of individual host buffers to the upper
+ * bound. The size of host buffers scheduled for processing should only matter if the user has specified a buffer size,
+ * but when he/she does we must strive for an optimal configuration. By default we'll opt for a fixed host buffer size,
+ * which should be fine if the period size is the same for capture and playback. In general, if there is a specified user
+ * buffer size, this method tries it best to determine a period size which is a multiple of the user buffer size.
+ *
+ * The framesPerBuffer attributes of the individual capture and playback components of the stream are set to corresponding
+ * values determined here. Since these should be reported as
+ *
+ * This is one of those blocks of code that will just take a lot of
+ * refinement to be any good.
+ *
+ * In the full-duplex case it is possible that the routine was unable
+ * to find a number of frames per buffer acceptable to both devices
+ * TODO: Implement an algorithm to find the value closest to acceptance
+ * by both devices, to minimize difference between period sizes?
+ *
+ * @param determinedFramesPerHostBuffer: The determined host buffer size.
+ */
+static PaError PaAlsaStream_DetermineFramesPerBuffer( PaAlsaStream* self, double sampleRate, const PaStreamParameters* inputParameters,
+ const PaStreamParameters* outputParameters, unsigned long framesPerUserBuffer, snd_pcm_hw_params_t* hwParamsCapture,
+ snd_pcm_hw_params_t* hwParamsPlayback, PaUtilHostBufferSizeMode* hostBufferSizeMode )
+{
+ PaError result = paNoError;
+ unsigned long framesPerHostBuffer = 0;
+ int dir = 0;
+ int accurate = 1;
+ unsigned numPeriods = numPeriods_;
+
+ if( self->capture.pcm && self->playback.pcm )
+ {
+ if( framesPerUserBuffer == paFramesPerBufferUnspecified )
+ {
+ /* Come up with a common desired latency */
+ snd_pcm_uframes_t desiredBufSz, e, minPeriodSize, maxPeriodSize, optimalPeriodSize, periodSize,
+ minCapture, minPlayback, maxCapture, maxPlayback;
+
+ dir = 0;
+ ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParamsCapture, &minCapture, &dir ), paUnanticipatedHostError );
+ dir = 0;
+ ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParamsPlayback, &minPlayback, &dir ), paUnanticipatedHostError );
+ dir = 0;
+ ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParamsCapture, &maxCapture, &dir ), paUnanticipatedHostError );
+ dir = 0;
+ ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParamsPlayback, &maxPlayback, &dir ), paUnanticipatedHostError );
+ minPeriodSize = PA_MAX( minPlayback, minCapture );
+ maxPeriodSize = PA_MIN( maxPlayback, maxCapture );
+ PA_UNLESS( minPeriodSize <= maxPeriodSize, paBadIODeviceCombination );
+
+ desiredBufSz = (snd_pcm_uframes_t)(PA_MIN( outputParameters->suggestedLatency, inputParameters->suggestedLatency )
+ * sampleRate);
+ /* Clamp desiredBufSz */
+ {
+ snd_pcm_uframes_t maxBufferSize;
+ snd_pcm_uframes_t maxBufferSizeCapture, maxBufferSizePlayback;
+ ENSURE_( snd_pcm_hw_params_get_buffer_size_max( hwParamsCapture, &maxBufferSizeCapture ), paUnanticipatedHostError );
+ ENSURE_( snd_pcm_hw_params_get_buffer_size_max( hwParamsPlayback, &maxBufferSizePlayback ), paUnanticipatedHostError );
+ maxBufferSize = PA_MIN( maxBufferSizeCapture, maxBufferSizePlayback );
+
+ desiredBufSz = PA_MIN( desiredBufSz, maxBufferSize );
+ }
+
+ /* Find the closest power of 2 */
+ e = ilogb( minPeriodSize );
+ if( minPeriodSize & (minPeriodSize - 1) )
+ e += 1;
+ periodSize = (snd_pcm_uframes_t)pow( 2, e );
+
+ while( periodSize <= maxPeriodSize )
+ {
+ if( snd_pcm_hw_params_test_period_size( self->playback.pcm, hwParamsPlayback, periodSize, 0 ) >= 0 &&
+ snd_pcm_hw_params_test_period_size( self->capture.pcm, hwParamsCapture, periodSize, 0 ) >= 0 )
+ {
+ /* OK! */
+ break;
+ }
+
+ periodSize *= 2;
+ }
+
+ optimalPeriodSize = PA_MAX( desiredBufSz / numPeriods, minPeriodSize );
+ optimalPeriodSize = PA_MIN( optimalPeriodSize, maxPeriodSize );
+
+ /* Find the closest power of 2 */
+ e = ilogb( optimalPeriodSize );
+ if( optimalPeriodSize & (optimalPeriodSize - 1) )
+ e += 1;
+ optimalPeriodSize = (snd_pcm_uframes_t)pow( 2, e );
+
+ while( optimalPeriodSize >= periodSize )
+ {
+ if( snd_pcm_hw_params_test_period_size( self->capture.pcm, hwParamsCapture, optimalPeriodSize, 0 ) < 0 )
+ continue;
+ if( snd_pcm_hw_params_test_period_size( self->playback.pcm, hwParamsPlayback, optimalPeriodSize, 0 ) >= 0 )
+ break;
+ optimalPeriodSize /= 2;
+ }
+ if( optimalPeriodSize > periodSize )
+ periodSize = optimalPeriodSize;
+
+ if( periodSize <= maxPeriodSize )
+ {
+ /* Looks good, the periodSize _should_ be acceptable by both devices */
+ ENSURE_( snd_pcm_hw_params_set_period_size( self->capture.pcm, hwParamsCapture, periodSize, 0 ),
+ paUnanticipatedHostError );
+ ENSURE_( snd_pcm_hw_params_set_period_size( self->playback.pcm, hwParamsPlayback, periodSize, 0 ),
+ paUnanticipatedHostError );
+ self->capture.framesPerBuffer = self->playback.framesPerBuffer = periodSize;
+ framesPerHostBuffer = periodSize;
+ }
+ else
+ {
+ /* Unable to find a common period size, oh well */
+ optimalPeriodSize = PA_MAX( desiredBufSz / numPeriods, minPeriodSize );
+ optimalPeriodSize = PA_MIN( optimalPeriodSize, maxPeriodSize );
+
+ self->capture.framesPerBuffer = optimalPeriodSize;
+ dir = 0;
+ ENSURE_( snd_pcm_hw_params_set_period_size_near( self->capture.pcm, hwParamsCapture, &self->capture.framesPerBuffer, &dir ),
+ paUnanticipatedHostError );
+ self->playback.framesPerBuffer = optimalPeriodSize;
+ dir = 0;
+ ENSURE_( snd_pcm_hw_params_set_period_size_near( self->playback.pcm, hwParamsPlayback, &self->playback.framesPerBuffer, &dir ),
+ paUnanticipatedHostError );
+ framesPerHostBuffer = PA_MAX( self->capture.framesPerBuffer, self->playback.framesPerBuffer );
+ *hostBufferSizeMode = paUtilBoundedHostBufferSize;
+ }
+ }
+ else
+ {
+ /* We choose the simple route and determine a suitable number of frames per buffer for one component of
+ * the stream, then we hope that this will work for the other component too (it should!).
+ */
+
+ unsigned maxPeriods = 0;
+ PaAlsaStreamComponent* first = &self->capture, * second = &self->playback;
+ const PaStreamParameters* firstStreamParams = inputParameters;
+ snd_pcm_hw_params_t* firstHwParams = hwParamsCapture, * secondHwParams = hwParamsPlayback;
+
+ dir = 0;
+ ENSURE_( snd_pcm_hw_params_get_periods_max( hwParamsPlayback, &maxPeriods, &dir ), paUnanticipatedHostError );
+ if( maxPeriods < numPeriods )
+ {
+ /* The playback component is trickier to get right, try that first */
+ first = &self->playback;
+ second = &self->capture;
+ firstStreamParams = outputParameters;
+ firstHwParams = hwParamsPlayback;
+ secondHwParams = hwParamsCapture;
+ }
+
+ PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( first, firstStreamParams, framesPerUserBuffer,
+ sampleRate, firstHwParams, &accurate ) );
+
+ second->framesPerBuffer = first->framesPerBuffer;
+ dir = 0;
+ ENSURE_( snd_pcm_hw_params_set_period_size_near( second->pcm, secondHwParams, &second->framesPerBuffer, &dir ),
+ paUnanticipatedHostError );
+ if( self->capture.framesPerBuffer == self->playback.framesPerBuffer )
+ {
+ framesPerHostBuffer = self->capture.framesPerBuffer;
+ }
+ else
+ {
+ framesPerHostBuffer = PA_MAX( self->capture.framesPerBuffer, self->playback.framesPerBuffer );
+ *hostBufferSizeMode = paUtilBoundedHostBufferSize;
+ }
+ }
+ }
+ else /* half-duplex is a slightly simpler case */
+ {
+ if( self->capture.pcm )
+ {
+ PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( &self->capture, inputParameters, framesPerUserBuffer,
+ sampleRate, hwParamsCapture, &accurate) );
+ framesPerHostBuffer = self->capture.framesPerBuffer;
+ }
+ else
+ {
+ assert( self->playback.pcm );
+ PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( &self->playback, outputParameters, framesPerUserBuffer,
+ sampleRate, hwParamsPlayback, &accurate ) );
+ framesPerHostBuffer = self->playback.framesPerBuffer;
+ }
+ }
+
+ PA_UNLESS( framesPerHostBuffer != 0, paInternalError );
+ self->maxFramesPerHostBuffer = framesPerHostBuffer;
+
+ if( !accurate )
+ {
+ /* Don't know the exact size per host buffer */
+ *hostBufferSizeMode = paUtilBoundedHostBufferSize;
+ /* Raise upper bound */
+ ++self->maxFramesPerHostBuffer;
+ }
+
+error:
+ return result;
+}
+
+/** Set up ALSA stream parameters.
+ *
+ */
+static PaError PaAlsaStream_Configure( PaAlsaStream *self, const PaStreamParameters *inParams, const PaStreamParameters*
+ outParams, double sampleRate, unsigned long framesPerUserBuffer, double* inputLatency, double* outputLatency,
+ PaUtilHostBufferSizeMode* hostBufferSizeMode )
+{
+ PaError result = paNoError;
+ double realSr = sampleRate;
+ snd_pcm_hw_params_t* hwParamsCapture, * hwParamsPlayback;
+
+ snd_pcm_hw_params_alloca( &hwParamsCapture );
+ snd_pcm_hw_params_alloca( &hwParamsPlayback );
+
+ if( self->capture.pcm )
+ PA_ENSURE( PaAlsaStreamComponent_InitialConfigure( &self->capture, inParams, self->primeBuffers, hwParamsCapture,
+ &realSr ) );
+ if( self->playback.pcm )
+ PA_ENSURE( PaAlsaStreamComponent_InitialConfigure( &self->playback, outParams, self->primeBuffers, hwParamsPlayback,
+ &realSr ) );
+
+ PA_ENSURE( PaAlsaStream_DetermineFramesPerBuffer( self, realSr, inParams, outParams, framesPerUserBuffer,
+ hwParamsCapture, hwParamsPlayback, hostBufferSizeMode ) );
+
+ if( self->capture.pcm )
+ {
+ assert( self->capture.framesPerBuffer != 0 );
+ PA_ENSURE( PaAlsaStreamComponent_FinishConfigure( &self->capture, hwParamsCapture, inParams, self->primeBuffers, realSr,
+ inputLatency ) );
+ PA_DEBUG(( "%s: Capture period size: %lu, latency: %f\n", __FUNCTION__, self->capture.framesPerBuffer, *inputLatency ));
+ }
+ if( self->playback.pcm )
+ {
+ assert( self->playback.framesPerBuffer != 0 );
+ PA_ENSURE( PaAlsaStreamComponent_FinishConfigure( &self->playback, hwParamsPlayback, outParams, self->primeBuffers, realSr,
+ outputLatency ) );
+ PA_DEBUG(( "%s: Playback period size: %lu, latency: %f\n", __FUNCTION__, self->playback.framesPerBuffer, *outputLatency ));
+ }
+
+ /* Should be exact now */
+ self->streamRepresentation.streamInfo.sampleRate = realSr;
+
+ /* this will cause the two streams to automatically start/stop/prepare in sync.
+ * We only need to execute these operations on one of the pair.
+ * A: We don't want to do this on a blocking stream.
+ */
+ if( self->callbackMode && self->capture.pcm && self->playback.pcm )
+ {
+ int err = snd_pcm_link( self->capture.pcm, self->playback.pcm );
+ if( err == 0 )
+ self->pcmsSynced = 1;
+ else
+ PA_DEBUG(( "%s: Unable to sync pcms: %s\n", __FUNCTION__, snd_strerror( err ) ));
+ }
+
+ {
+ unsigned long minFramesPerHostBuffer = PA_MIN( self->capture.pcm ? self->capture.framesPerBuffer : ULONG_MAX,
+ self->playback.pcm ? self->playback.framesPerBuffer : ULONG_MAX );
+ self->pollTimeout = CalculatePollTimeout( self, minFramesPerHostBuffer ); /* Period in msecs, rounded up */
+
+ /* Time before watchdog unthrottles realtime thread == 1/4 of period time in msecs */
+ /* self->threading.throttledSleepTime = (unsigned long) (minFramesPerHostBuffer / sampleRate / 4 * 1000); */
+ }
+
+ if( self->callbackMode )
+ {
+ /* If the user expects a certain number of frames per callback we will either have to rely on block adaption
+ * (framesPerHostBuffer is not an integer multiple of framesPerBuffer) or we can simply align the number
+ * of host buffer frames with what the user specified */
+ if( self->framesPerUserBuffer != paFramesPerBufferUnspecified )
+ {
+ /* self->alignFrames = 1; */
+
+ /* Unless the ratio between number of host and user buffer frames is an integer we will have to rely
+ * on block adaption */
+ /*
+ if( framesPerHostBuffer % framesPerBuffer != 0 || (self->capture.pcm && self->playback.pcm &&
+ self->capture.framesPerBuffer != self->playback.framesPerBuffer) )
+ self->useBlockAdaption = 1;
+ else
+ self->alignFrames = 1;
+ */
+ }
+ }
+
+error:
+ return result;
+}
+
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+ PaStream** s,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate,
+ unsigned long framesPerBuffer,
+ PaStreamFlags streamFlags,
+ PaStreamCallback* callback,
+ void *userData )
+{
+ PaError result = paNoError;
+ PaAlsaHostApiRepresentation *alsaHostApi = (PaAlsaHostApiRepresentation*)hostApi;
+ PaAlsaStream *stream = NULL;
+ PaSampleFormat hostInputSampleFormat = 0, hostOutputSampleFormat = 0;
+ PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0;
+ int numInputChannels = 0, numOutputChannels = 0;
+ PaTime inputLatency, outputLatency;
+ /* Operate with fixed host buffer size by default, since other modes will invariably lead to block adaption */
+ /* XXX: Use Bounded by default? Output tends to get stuttery with Fixed ... */
+ PaUtilHostBufferSizeMode hostBufferSizeMode = paUtilFixedHostBufferSize;
+
+ if( (streamFlags & paPlatformSpecificFlags) != 0 )
+ return paInvalidFlag;
+
+ if( inputParameters )
+ {
+ PA_ENSURE( ValidateParameters( inputParameters, hostApi, StreamDirection_In ) );
+
+ numInputChannels = inputParameters->channelCount;
+ inputSampleFormat = inputParameters->sampleFormat;
+ }
+ if( outputParameters )
+ {
+ PA_ENSURE( ValidateParameters( outputParameters, hostApi, StreamDirection_Out ) );
+
+ numOutputChannels = outputParameters->channelCount;
+ outputSampleFormat = outputParameters->sampleFormat;
+ }
+
+ /* XXX: Why do we support this anyway? */
+ if( framesPerBuffer == paFramesPerBufferUnspecified && getenv( "PA_ALSA_PERIODSIZE" ) != NULL )
+ {
+ PA_DEBUG(( "%s: Getting framesPerBuffer from environment\n", __FUNCTION__ ));
+ framesPerBuffer = atoi( getenv("PA_ALSA_PERIODSIZE") );
+ }
+
+ PA_UNLESS( stream = (PaAlsaStream*)PaUtil_AllocateMemory( sizeof(PaAlsaStream) ), paInsufficientMemory );
+ PA_ENSURE( PaAlsaStream_Initialize( stream, alsaHostApi, inputParameters, outputParameters, sampleRate,
+ framesPerBuffer, callback, streamFlags, userData ) );
+
+ PA_ENSURE( PaAlsaStream_Configure( stream, inputParameters, outputParameters, sampleRate, framesPerBuffer,
+ &inputLatency, &outputLatency, &hostBufferSizeMode ) );
+ hostInputSampleFormat = stream->capture.hostSampleFormat;
+ hostOutputSampleFormat = stream->playback.hostSampleFormat;
+
+ PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+ numInputChannels, inputSampleFormat, hostInputSampleFormat,
+ numOutputChannels, outputSampleFormat, hostOutputSampleFormat,
+ sampleRate, streamFlags, framesPerBuffer, stream->maxFramesPerHostBuffer,
+ hostBufferSizeMode, callback, userData ) );
+
+ /* Ok, buffer processor is initialized, now we can deduce it's latency */
+ if( numInputChannels > 0 )
+ stream->streamRepresentation.streamInfo.inputLatency = inputLatency + PaUtil_GetBufferProcessorInputLatency(
+ &stream->bufferProcessor );
+ if( numOutputChannels > 0 )
+ stream->streamRepresentation.streamInfo.outputLatency = outputLatency + PaUtil_GetBufferProcessorOutputLatency(
+ &stream->bufferProcessor );
+
+ *s = (PaStream*)stream;
+
+ return result;
+
+error:
+ if( stream )
+ {
+ PA_DEBUG(( "%s: Stream in error, terminating\n", __FUNCTION__ ));
+ PaAlsaStream_Terminate( stream );
+ }
+
+ return result;
+}
+
+static PaError CloseStream( PaStream* s )
+{
+ PaError result = paNoError;
+ PaAlsaStream *stream = (PaAlsaStream*)s;
+
+ PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+ PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+
+ PaAlsaStream_Terminate( stream );
+
+ return result;
+}
+
+static void SilenceBuffer( PaAlsaStream *stream )
+{
+ const snd_pcm_channel_area_t *areas;
+ snd_pcm_uframes_t frames = (snd_pcm_uframes_t)snd_pcm_avail_update( stream->playback.pcm ), offset;
+
+ snd_pcm_mmap_begin( stream->playback.pcm, &areas, &offset, &frames );
+ snd_pcm_areas_silence( areas, offset, stream->playback.numHostChannels, frames, stream->playback.nativeFormat );
+ snd_pcm_mmap_commit( stream->playback.pcm, offset, frames );
+}
+
+/** Start/prepare pcm(s) for streaming.
+ *
+ * Depending on wether the stream is in callback or blocking mode, we will respectively start or simply
+ * prepare the playback pcm. If the buffer has _not_ been primed, we will in callback mode prepare and
+ * silence the buffer before starting playback. In blocking mode we simply prepare, as the playback will
+ * be started automatically as the user writes to output.
+ *
+ * The capture pcm, however, will simply be prepared and started.
+ */
+static PaError AlsaStart( PaAlsaStream *stream, int priming )
+{
+ PaError result = paNoError;
+
+ if( stream->playback.pcm )
+ {
+ if( stream->callbackMode )
+ {
+ if( !priming )
+ {
+ /* Buffer isn't primed, so prepare and silence */
+ ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
+ SilenceBuffer( stream );
+ }
+ ENSURE_( snd_pcm_start( stream->playback.pcm ), paUnanticipatedHostError );
+ }
+ else
+ ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
+ }
+ if( stream->capture.pcm && !stream->pcmsSynced )
+ {
+ ENSURE_( snd_pcm_prepare( stream->capture.pcm ), paUnanticipatedHostError );
+ /* For a blocking stream we want to start capture as well, since nothing will happen otherwise */
+ ENSURE_( snd_pcm_start( stream->capture.pcm ), paUnanticipatedHostError );
+ }
+
+end:
+ return result;
+error:
+ goto end;
+}
+
+/** Utility function for determining if pcms are in running state.
+ *
+ */
+#if 0
+static int IsRunning( PaAlsaStream *stream )
+{
+ int result = 0;
+
+ PA_ENSURE( PaUnixMutex_Lock( &stream->stateMtx ) );
+ if( stream->capture.pcm )
+ {
+ snd_pcm_state_t capture_state = snd_pcm_state( stream->capture.pcm );
+
+ if( capture_state == SND_PCM_STATE_RUNNING || capture_state == SND_PCM_STATE_XRUN
+ || capture_state == SND_PCM_STATE_DRAINING )
+ {
+ result = 1;
+ goto end;
+ }
+ }
+
+ if( stream->playback.pcm )
+ {
+ snd_pcm_state_t playback_state = snd_pcm_state( stream->playback.pcm );
+
+ if( playback_state == SND_PCM_STATE_RUNNING || playback_state == SND_PCM_STATE_XRUN
+ || playback_state == SND_PCM_STATE_DRAINING )
+ {
+ result = 1;
+ goto end;
+ }
+ }
+
+end:
+ ASSERT_CALL_( PaUnixMutex_Unlock( &stream->stateMtx ), paNoError );
+ return result;
+error:
+ goto error;
+}
+#endif
+
+static PaError StartStream( PaStream *s )
+{
+ PaError result = paNoError;
+ PaAlsaStream* stream = (PaAlsaStream*)s;
+ int streamStarted = 0; /* So we can know wether we need to take the stream down */
+
+ /* Ready the processor */
+ PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+
+ /* Set now, so we can test for activity further down */
+ stream->isActive = 1;
+
+ if( stream->callbackMode )
+ {
+ PA_ENSURE( PaUnixThread_New( &stream->thread, &CallbackThreadFunc, stream, 1., stream->rtSched ) );
+ }
+ else
+ {
+ PA_ENSURE( AlsaStart( stream, 0 ) );
+ streamStarted = 1;
+ }
+
+end:
+ return result;
+error:
+ if( streamStarted )
+ {
+ AbortStream( stream );
+ }
+ stream->isActive = 0;
+
+ goto end;
+}
+
+/** Stop PCM handle, either softly or abruptly.
+ */
+static PaError AlsaStop( PaAlsaStream *stream, int abort )
+{
+ PaError result = paNoError;
+ /* XXX: Seems that draining the dmix device may trigger a race condition in ALSA */
+ if( stream->capture.pcm && !strcmp( Pa_GetDeviceInfo( stream->capture.device )->name,
+ "dmix" ) )
+ {
+ abort = 1;
+ }
+ else if( stream->playback.pcm && !strcmp( Pa_GetDeviceInfo( stream->playback.device )->name,
+ "dmix" ) )
+ {
+ abort = 1;
+ }
+
+ if( abort )
+ {
+ if( stream->playback.pcm )
+ {
+ ENSURE_( snd_pcm_drop( stream->playback.pcm ), paUnanticipatedHostError );
+ }
+ if( stream->capture.pcm && !stream->pcmsSynced )
+ {
+ ENSURE_( snd_pcm_drop( stream->capture.pcm ), paUnanticipatedHostError );
+ }
+
+ PA_DEBUG(( "%s: Dropped frames\n", __FUNCTION__ ));
+ }
+ else
+ {
+ if( stream->playback.pcm )
+ {
+ ENSURE_( snd_pcm_nonblock( stream->playback.pcm, 0 ), paUnanticipatedHostError );
+ if( snd_pcm_drain( stream->playback.pcm ) < 0 )
+ {
+ PA_DEBUG(( "%s: Draining playback handle failed!\n", __FUNCTION__ ));
+ }
+ }
+ if( stream->capture.pcm && !stream->pcmsSynced )
+ {
+ /* We don't need to retrieve any remaining frames */
+ if( snd_pcm_drain( stream->capture.pcm ) < 0 )
+ {
+ PA_DEBUG(( "%s: Draining capture handle failed!\n", __FUNCTION__ ));
+ }
+ }
+ }
+
+end:
+ return result;
+error:
+ goto end;
+}
+
+/** Stop or abort stream.
+ *
+ * If a stream is in callback mode we will have to inspect wether the background thread has
+ * finished, or we will have to take it out. In either case we join the thread before
+ * returning. In blocking mode, we simply tell ALSA to stop abruptly (abort) or finish
+ * buffers (drain)
+ *
+ * Stream will be considered inactive (!PaAlsaStream::isActive) after a call to this function
+ */
+static PaError RealStop( PaAlsaStream *stream, int abort )
+{
+ PaError result = paNoError;
+
+ /* First deal with the callback thread, cancelling and/or joining
+ * it if necessary
+ */
+ if( stream->callbackMode )
+ {
+ PaError threadRes;
+ stream->callbackAbort = abort;
+
+ if( !abort )
+ {
+ PA_DEBUG(( "Stopping callback\n" ));
+ }
+ PA_ENSURE( PaUnixThread_Terminate( &stream->thread, !abort, &threadRes ) );
+ if( threadRes != paNoError )
+ {
+ PA_DEBUG(( "Callback thread returned: %d\n", threadRes ));
+ }
+#if 0
+ if( watchdogRes != paNoError )
+ PA_DEBUG(( "Watchdog thread returned: %d\n", watchdogRes ));
+#endif
+
+ stream->callback_finished = 0;
+ }
+ else
+ {
+ PA_ENSURE( AlsaStop( stream, abort ) );
+ }
+
+ stream->isActive = 0;
+
+end:
+ return result;
+
+error:
+ goto end;
+}
+
+static PaError StopStream( PaStream *s )
+{
+ return RealStop( (PaAlsaStream *) s, 0 );
+}
+
+static PaError AbortStream( PaStream *s )
+{
+ return RealStop( (PaAlsaStream * ) s, 1 );
+}
+
+/** The stream is considered stopped before StartStream, or AFTER a call to Abort/StopStream (callback
+ * returning !paContinue is not considered)
+ *
+ */
+static PaError IsStreamStopped( PaStream *s )
+{
+ PaAlsaStream *stream = (PaAlsaStream *)s;
+
+ /* callback_finished indicates we need to join callback thread (ie. in Abort/StopStream) */
+ return !IsStreamActive( s ) && !stream->callback_finished;
+}
+
+static PaError IsStreamActive( PaStream *s )
+{
+ PaAlsaStream *stream = (PaAlsaStream*)s;
+ return stream->isActive;
+}
+
+static PaTime GetStreamTime( PaStream *s )
+{
+ PaAlsaStream *stream = (PaAlsaStream*)s;
+
+ snd_timestamp_t timestamp;
+ snd_pcm_status_t* status;
+ snd_pcm_status_alloca( &status );
+
+ /* TODO: what if we have both? does it really matter? */
+
+ /* TODO: if running in callback mode, this will mean
+ * libasound routines are being called from multiple threads.
+ * need to verify that libasound is thread-safe. */
+
+ if( stream->capture.pcm )
+ {
+ snd_pcm_status( stream->capture.pcm, status );
+ }
+ else if( stream->playback.pcm )
+ {
+ snd_pcm_status( stream->playback.pcm, status );
+ }
+
+ snd_pcm_status_get_tstamp( status, &timestamp );
+ return timestamp.tv_sec + (PaTime)timestamp.tv_usec / 1e6;
+}
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+ PaAlsaStream *stream = (PaAlsaStream*)s;
+
+ return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+static int SetApproximateSampleRate( snd_pcm_t *pcm, snd_pcm_hw_params_t *hwParams, double sampleRate )
+{
+ unsigned long approx = (unsigned long) sampleRate;
+ int dir = 0;
+ double fraction = sampleRate - approx;
+
+ assert( pcm && hwParams );
+
+ if( fraction > 0.0 )
+ {
+ if( fraction > 0.5 )
+ {
+ ++approx;
+ dir = -1;
+ }
+ else
+ dir = 1;
+ }
+
+ return snd_pcm_hw_params_set_rate( pcm, hwParams, approx, dir );
+}
+
+/* Return exact sample rate in param sampleRate */
+static int GetExactSampleRate( snd_pcm_hw_params_t *hwParams, double *sampleRate )
+{
+ unsigned int num, den;
+ int err;
+
+ assert( hwParams );
+
+ err = snd_pcm_hw_params_get_rate_numden( hwParams, &num, &den );
+ *sampleRate = (double) num / den;
+
+ return err;
+}
+
+/* Utility functions for blocking/callback interfaces */
+
+/* Atomic restart of stream (we don't want the intermediate state visible) */
+static PaError AlsaRestart( PaAlsaStream *stream )
+{
+ PaError result = paNoError;
+
+ PA_ENSURE( PaUnixMutex_Lock( &stream->stateMtx ) );
+ PA_ENSURE( AlsaStop( stream, 0 ) );
+ PA_ENSURE( AlsaStart( stream, 0 ) );
+
+ PA_DEBUG(( "%s: Restarted audio\n", __FUNCTION__ ));
+
+error:
+ PA_ENSURE( PaUnixMutex_Unlock( &stream->stateMtx ) );
+
+ return result;
+}
+
+/** Recover from xrun state.
+ *
+ */
+static PaError PaAlsaStream_HandleXrun( PaAlsaStream *self )
+{
+ PaError result = paNoError;
+ snd_pcm_status_t *st;
+ PaTime now = PaUtil_GetTime();
+ snd_timestamp_t t;
+
+ snd_pcm_status_alloca( &st );
+
+ if( self->playback.pcm )
+ {
+ snd_pcm_status( self->playback.pcm, st );
+ if( snd_pcm_status_get_state( st ) == SND_PCM_STATE_XRUN )
+ {
+ snd_pcm_status_get_trigger_tstamp( st, &t );
+ self->underrun = now * 1000 - ((PaTime) t.tv_sec * 1000 + (PaTime) t.tv_usec / 1000);
+ }
+ }
+ if( self->capture.pcm )
+ {
+ snd_pcm_status( self->capture.pcm, st );
+ if( snd_pcm_status_get_state( st ) == SND_PCM_STATE_XRUN )
+ {
+ snd_pcm_status_get_trigger_tstamp( st, &t );
+ self->overrun = now * 1000 - ((PaTime) t.tv_sec * 1000 + (PaTime) t.tv_usec / 1000);
+ }
+ }
+
+ PA_ENSURE( AlsaRestart( self ) );
+
+end:
+ return result;
+error:
+ goto end;
+}
+
+/** Decide if we should continue polling for specified direction, eventually adjust the poll timeout.
+ *
+ */
+static PaError ContinuePoll( const PaAlsaStream *stream, StreamDirection streamDir, int *pollTimeout, int *continuePoll )
+{
+ PaError result = paNoError;
+ snd_pcm_sframes_t delay, margin;
+ int err;
+ const PaAlsaStreamComponent *component = NULL, *otherComponent = NULL;
+
+ *continuePoll = 1;
+
+ if( StreamDirection_In == streamDir )
+ {
+ component = &stream->capture;
+ otherComponent = &stream->playback;
+ }
+ else
+ {
+ component = &stream->playback;
+ otherComponent = &stream->capture;
+ }
+
+ /* ALSA docs say that negative delay should indicate xrun, but in my experience snd_pcm_delay returns -EPIPE */
+ if( (err = snd_pcm_delay( otherComponent->pcm, &delay )) < 0 )
+ {
+ if( err == -EPIPE )
+ {
+ /* Xrun */
+ *continuePoll = 0;
+ goto error;
+ }
+
+ ENSURE_( err, paUnanticipatedHostError );
+ }
+
+ if( StreamDirection_Out == streamDir )
+ {
+ /* Number of eligible frames before capture overrun */
+ delay = otherComponent->bufferSize - delay;
+ }
+ margin = delay - otherComponent->framesPerBuffer / 2;
+
+ if( margin < 0 )
+ {
+ PA_DEBUG(( "%s: Stopping poll for %s\n", __FUNCTION__, StreamDirection_In == streamDir ? "capture" : "playback" ));
+ *continuePoll = 0;
+ }
+ else if( margin < otherComponent->framesPerBuffer )
+ {
+ *pollTimeout = CalculatePollTimeout( stream, margin );
+ PA_DEBUG(( "%s: Trying to poll again for %s frames, pollTimeout: %d\n",
+ __FUNCTION__, StreamDirection_In == streamDir ? "capture" : "playback", *pollTimeout ));
+ }
+
+error:
+ return result;
+}
+
+/* Callback interface */
+
+static void OnExit( void *data )
+{
+ PaAlsaStream *stream = (PaAlsaStream *) data;
+
+ assert( data );
+
+ PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
+
+ stream->callback_finished = 1; /* Let the outside world know stream was stopped in callback */
+ PA_DEBUG(( "%s: Stopping ALSA handles\n", __FUNCTION__ ));
+ AlsaStop( stream, stream->callbackAbort );
+
+ PA_DEBUG(( "%s: Stoppage\n", __FUNCTION__ ));
+
+ /* Eventually notify user all buffers have played */
+ if( stream->streamRepresentation.streamFinishedCallback )
+ {
+ stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+ }
+ stream->isActive = 0;
+}
+
+static void CalculateTimeInfo( PaAlsaStream *stream, PaStreamCallbackTimeInfo *timeInfo )
+{
+ snd_pcm_status_t *capture_status, *playback_status;
+ snd_timestamp_t capture_timestamp, playback_timestamp;
+ PaTime capture_time = 0., playback_time = 0.;
+
+ snd_pcm_status_alloca( &capture_status );
+ snd_pcm_status_alloca( &playback_status );
+
+ if( stream->capture.pcm )
+ {
+ snd_pcm_sframes_t capture_delay;
+
+ snd_pcm_status( stream->capture.pcm, capture_status );
+ snd_pcm_status_get_tstamp( capture_status, &capture_timestamp );
+
+ capture_time = capture_timestamp.tv_sec +
+ ((PaTime)capture_timestamp.tv_usec / 1000000.0);
+ timeInfo->currentTime = capture_time;
+
+ capture_delay = snd_pcm_status_get_delay( capture_status );
+ timeInfo->inputBufferAdcTime = timeInfo->currentTime -
+ (PaTime)capture_delay / stream->streamRepresentation.streamInfo.sampleRate;
+ }
+ if( stream->playback.pcm )
+ {
+ snd_pcm_sframes_t playback_delay;
+
+ snd_pcm_status( stream->playback.pcm, playback_status );
+ snd_pcm_status_get_tstamp( playback_status, &playback_timestamp );
+
+ playback_time = playback_timestamp.tv_sec +
+ ((PaTime)playback_timestamp.tv_usec / 1000000.0);
+
+ if( stream->capture.pcm ) /* Full duplex */
+ {
+ /* Hmm, we have both a playback and a capture timestamp.
+ * Hopefully they are the same... */
+ if( fabs( capture_time - playback_time ) > 0.01 )
+ PA_DEBUG(("Capture time and playback time differ by %f\n", fabs(capture_time-playback_time)));
+ }
+ else
+ timeInfo->currentTime = playback_time;
+
+ playback_delay = snd_pcm_status_get_delay( playback_status );
+ timeInfo->outputBufferDacTime = timeInfo->currentTime +
+ (PaTime)playback_delay / stream->streamRepresentation.streamInfo.sampleRate;
+ }
+}
+
+/** Called after buffer processing is finished.
+ *
+ * A number of mmapped frames is committed, it is possible that an xrun has occurred in the meantime.
+ *
+ * @param numFrames The number of frames that has been processed
+ * @param xrun Return whether an xrun has occurred
+ */
+static PaError PaAlsaStreamComponent_EndProcessing( PaAlsaStreamComponent *self, unsigned long numFrames, int *xrun )
+{
+ PaError result = paNoError;
+ int res;
+
+ /* @concern FullDuplex It is possible that only one direction is marked ready after polling, and processed
+ * afterwards
+ */
+ if( !self->ready )
+ goto end;
+
+ res = snd_pcm_mmap_commit( self->pcm, self->offset, numFrames );
+ if( res == -EPIPE || res == -ESTRPIPE )
+ {
+ *xrun = 1;
+ }
+ else
+ {
+ ENSURE_( res, paUnanticipatedHostError );
+ }
+
+end:
+error:
+ return result;
+}
+
+/* Extract buffer from channel area */
+static unsigned char *ExtractAddress( const snd_pcm_channel_area_t *area, snd_pcm_uframes_t offset )
+{
+ return (unsigned char *) area->addr + (area->first + offset * area->step) / 8;
+}
+
+/** Do necessary adaption between user and host channels.
+ *
+ @concern ChannelAdaption Adapting between user and host channels can involve silencing unused channels and
+ duplicating mono information if host outputs come in pairs.
+ */
+static PaError PaAlsaStreamComponent_DoChannelAdaption( PaAlsaStreamComponent *self, PaUtilBufferProcessor *bp, int numFrames )
+{
+ PaError result = paNoError;
+ unsigned char *p;
+ int i;
+ int unusedChans = self->numHostChannels - self->numUserChannels;
+ unsigned char *src, *dst;
+ int convertMono = (self->numHostChannels % 2) == 0 && (self->numUserChannels % 2) != 0;
+
+ assert( StreamDirection_Out == self->streamDir );
+
+ if( self->hostInterleaved )
+ {
+ int swidth = snd_pcm_format_size( self->nativeFormat, 1 );
+ unsigned char *buffer = ExtractAddress( self->channelAreas, self->offset );
+
+ /* Start after the last user channel */
+ p = buffer + self->numUserChannels * swidth;
+
+ if( convertMono )
+ {
+ /* Convert the last user channel into stereo pair */
+ src = buffer + (self->numUserChannels - 1) * swidth;
+ for( i = 0; i < numFrames; ++i )
+ {
+ dst = src + swidth;
+ memcpy( dst, src, swidth );
+ src += self->numHostChannels * swidth;
+ }
+
+ /* Don't touch the channel we just wrote to */
+ p += swidth;
+ --unusedChans;
+ }
+
+ if( unusedChans > 0 )
+ {
+ /* Silence unused output channels */
+ for( i = 0; i < numFrames; ++i )
+ {
+ memset( p, 0, swidth * unusedChans );
+ p += self->numHostChannels * swidth;
+ }
+ }
+ }
+ else
+ {
+ /* We extract the last user channel */
+ if( convertMono )
+ {
+ ENSURE_( snd_pcm_area_copy( self->channelAreas + self->numUserChannels, self->offset, self->channelAreas +
+ (self->numUserChannels - 1), self->offset, numFrames, self->nativeFormat ), paUnanticipatedHostError );
+ --unusedChans;
+ }
+ if( unusedChans > 0 )
+ {
+ snd_pcm_areas_silence( self->channelAreas + (self->numHostChannels - unusedChans), self->offset, unusedChans, numFrames,
+ self->nativeFormat );
+ }
+ }
+
+error:
+ return result;
+}
+
+static PaError PaAlsaStream_EndProcessing( PaAlsaStream *self, unsigned long numFrames, int *xrunOccurred )
+{
+ PaError result = paNoError;
+ int xrun = 0;
+
+ if( self->capture.pcm )
+ {
+ PA_ENSURE( PaAlsaStreamComponent_EndProcessing( &self->capture, numFrames, &xrun ) );
+ }
+ if( self->playback.pcm )
+ {
+ if( self->playback.numHostChannels > self->playback.numUserChannels )
+ {
+ PA_ENSURE( PaAlsaStreamComponent_DoChannelAdaption( &self->playback, &self->bufferProcessor, numFrames ) );
+ }
+ PA_ENSURE( PaAlsaStreamComponent_EndProcessing( &self->playback, numFrames, &xrun ) );
+ }
+
+error:
+ *xrunOccurred = xrun;
+ return result;
+}
+
+/** Update the number of available frames.
+ *
+ */
+static PaError PaAlsaStreamComponent_GetAvailableFrames( PaAlsaStreamComponent *self, unsigned long *numFrames, int *xrunOccurred )
+{
+ PaError result = paNoError;
+ snd_pcm_sframes_t framesAvail = snd_pcm_avail_update( self->pcm );
+ *xrunOccurred = 0;
+
+ if( -EPIPE == framesAvail )
+ {
+ *xrunOccurred = 1;
+ framesAvail = 0;
+ }
+ else
+ {
+ ENSURE_( framesAvail, paUnanticipatedHostError );
+ }
+
+ *numFrames = framesAvail;
+
+error:
+ return result;
+}
+
+/** Fill in pollfd objects.
+ */
+static PaError PaAlsaStreamComponent_BeginPolling( PaAlsaStreamComponent* self, struct pollfd* pfds )
+{
+ PaError result = paNoError;
+ int ret = snd_pcm_poll_descriptors( self->pcm, pfds, self->nfds );
+ (void)ret; /* Prevent unused variable warning if asserts are turned off */
+ assert( ret == self->nfds );
+
+ self->ready = 0;
+
+ return result;
+}
+
+/** Examine results from poll().
+ *
+ * @param pfds pollfds to inspect
+ * @param shouldPoll Should we continue to poll
+ * @param xrun Has an xrun occurred
+ */
+static PaError PaAlsaStreamComponent_EndPolling( PaAlsaStreamComponent* self, struct pollfd* pfds, int* shouldPoll, int* xrun )
+{
+ PaError result = paNoError;
+ unsigned short revents;
+
+ ENSURE_( snd_pcm_poll_descriptors_revents( self->pcm, pfds, self->nfds, &revents ), paUnanticipatedHostError );
+ if( revents != 0 )
+ {
+ if( revents & POLLERR )
+ {
+ *xrun = 1;
+ }
+ else
+ self->ready = 1;
+
+ *shouldPoll = 0;
+ }
+
+error:
+ return result;
+}
+
+/** Return the number of available frames for this stream.
+ *
+ * @concern FullDuplex The minimum available for the two directions is calculated, it might be desirable to ignore
+ * one direction however (not marked ready from poll), so this is controlled by queryCapture and queryPlayback.
+ *
+ * @param queryCapture Check available for capture
+ * @param queryPlayback Check available for playback
+ * @param available The returned number of frames
+ * @param xrunOccurred Return whether an xrun has occurred
+ */
+static PaError PaAlsaStream_GetAvailableFrames( PaAlsaStream *self, int queryCapture, int queryPlayback, unsigned long
+ *available, int *xrunOccurred )
+{
+ PaError result = paNoError;
+ unsigned long captureFrames, playbackFrames;
+ *xrunOccurred = 0;
+
+ assert( queryCapture || queryPlayback );
+
+ if( queryCapture )
+ {
+ assert( self->capture.pcm );
+ PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &self->capture, &captureFrames, xrunOccurred ) );
+ if( *xrunOccurred )
+ {
+ goto end;
+ }
+ }
+ if( queryPlayback )
+ {
+ assert( self->playback.pcm );
+ PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &self->playback, &playbackFrames, xrunOccurred ) );
+ if( *xrunOccurred )
+ {
+ goto end;
+ }
+ }
+
+ if( queryCapture && queryPlayback )
+ {
+ *available = PA_MIN( captureFrames, playbackFrames );
+ /*PA_DEBUG(("capture: %lu, playback: %lu, combined: %lu\n", captureFrames, playbackFrames, *available));*/
+ }
+ else if( queryCapture )
+ {
+ *available = captureFrames;
+ }
+ else
+ {
+ *available = playbackFrames;
+ }
+
+end:
+error:
+ return result;
+}
+
+/** Wait for and report available buffer space from ALSA.
+ *
+ * Unless ALSA reports a minimum of frames available for I/O, we poll the ALSA filedescriptors for more.
+ * Both of these operations can uncover xrun conditions.
+ *
+ * @concern Xruns Both polling and querying available frames can report an xrun condition.
+ *
+ * @param framesAvail Return the number of available frames
+ * @param xrunOccurred Return whether an xrun has occurred
+ */
+static PaError PaAlsaStream_WaitForFrames( PaAlsaStream *self, unsigned long *framesAvail, int *xrunOccurred )
+{
+ PaError result = paNoError;
+ int pollPlayback = self->playback.pcm != NULL, pollCapture = self->capture.pcm != NULL;
+ int pollTimeout = self->pollTimeout;
+ int xrun = 0;
+
+ assert( self );
+ assert( framesAvail );
+
+ if( !self->callbackMode )
+ {
+ /* In blocking mode we will only wait if necessary */
+ PA_ENSURE( PaAlsaStream_GetAvailableFrames( self, self->capture.pcm != NULL, self->playback.pcm != NULL,
+ framesAvail, &xrun ) );
+ if( xrun )
+ {
+ goto end;
+ }
+
+ if( *framesAvail > 0 )
+ {
+ /* Mark pcms ready from poll */
+ if( self->capture.pcm )
+ self->capture.ready = 1;
+ if( self->playback.pcm )
+ self->playback.ready = 1;
+
+ goto end;
+ }
+ }
+
+ while( pollPlayback || pollCapture )
+ {
+ int totalFds = 0;
+ struct pollfd *capturePfds = NULL, *playbackPfds = NULL;
+
+ pthread_testcancel();
+
+ if( pollCapture )
+ {
+ capturePfds = self->pfds;
+ PA_ENSURE( PaAlsaStreamComponent_BeginPolling( &self->capture, capturePfds ) );
+ totalFds += self->capture.nfds;
+ }
+ if( pollPlayback )
+ {
+ playbackPfds = self->pfds + (self->capture.pcm ? self->capture.nfds : 0);
+ PA_ENSURE( PaAlsaStreamComponent_BeginPolling( &self->playback, playbackPfds ) );
+ totalFds += self->playback.nfds;
+ }
+
+ if( poll( self->pfds, totalFds, pollTimeout ) < 0 )
+ {
+ /* XXX: Depend on preprocessor condition? */
+ if( errno == EINTR )
+ {
+ /* gdb */
+ continue;
+ }
+
+ /* TODO: Add macro for checking system calls */
+ PA_ENSURE( paInternalError );
+ }
+
+ /* check the return status of our pfds */
+ if( pollCapture )
+ {
+ PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->capture, capturePfds, &pollCapture, &xrun ) );
+ }
+ if( pollPlayback )
+ {
+ PA_ENSURE( PaAlsaStreamComponent_EndPolling( &self->playback, playbackPfds, &pollPlayback, &xrun ) );
+ }
+ if( xrun )
+ {
+ break;
+ }
+
+ /* @concern FullDuplex If only one of two pcms is ready we may want to compromise between the two.
+ * If there is less than half a period's worth of samples left of frames in the other pcm's buffer we will
+ * stop polling.
+ */
+ if( self->capture.pcm && self->playback.pcm )
+ {
+ if( pollCapture && !pollPlayback )
+ {
+ PA_ENSURE( ContinuePoll( self, StreamDirection_In, &pollTimeout, &pollCapture ) );
+ }
+ else if( pollPlayback && !pollCapture )
+ {
+ PA_ENSURE( ContinuePoll( self, StreamDirection_Out, &pollTimeout, &pollPlayback ) );
+ }
+ }
+ }
+
+ if( !xrun )
+ {
+ /* Get the number of available frames for the pcms that are marked ready.
+ * @concern FullDuplex If only one direction is marked ready (from poll), the number of frames available for
+ * the other direction is returned. Output is normally preferred over capture however, so capture frames may be
+ * discarded to avoid overrun unless paNeverDropInput is specified.
+ */
+ int captureReady = self->capture.pcm ? self->capture.ready : 0,
+ playbackReady = self->playback.pcm ? self->playback.ready : 0;
+ PA_ENSURE( PaAlsaStream_GetAvailableFrames( self, captureReady, playbackReady, framesAvail, &xrun ) );
+
+ if( self->capture.pcm && self->playback.pcm )
+ {
+ if( !self->playback.ready && !self->neverDropInput )
+ {
+ /* Drop input, a period's worth */
+ assert( self->capture.ready );
+ PaAlsaStreamComponent_EndProcessing( &self->capture, PA_MIN( self->capture.framesPerBuffer,
+ *framesAvail ), &xrun );
+ *framesAvail = 0;
+ self->capture.ready = 0;
+ }
+ }
+ else if( self->capture.pcm )
+ assert( self->capture.ready );
+ else
+ assert( self->playback.ready );
+ }
+
+end:
+error:
+ if( xrun )
+ {
+ /* Recover from the xrun state */
+ PA_ENSURE( PaAlsaStream_HandleXrun( self ) );
+ *framesAvail = 0;
+ }
+ else
+ {
+ if( 0 != *framesAvail )
+ {
+ /* If we're reporting frames eligible for processing, one of the handles better be ready */
+ PA_UNLESS( self->capture.ready || self->playback.ready, paInternalError );
+ }
+ }
+ *xrunOccurred = xrun;
+
+ return result;
+}
+
+/** Register per-channel ALSA buffer information with buffer processor.
+ *
+ * Mmapped buffer space is acquired from ALSA, and registered with the buffer processor. Differences between the
+ * number of host and user channels is taken into account.
+ *
+ * @param numFrames On entrance the number of requested frames, on exit the number of contiguously accessible frames.
+ */
+static PaError PaAlsaStreamComponent_RegisterChannels( PaAlsaStreamComponent* self, PaUtilBufferProcessor* bp,
+ unsigned long* numFrames, int* xrun )
+{
+ PaError result = paNoError;
+ const snd_pcm_channel_area_t *areas, *area;
+ void (*setChannel)(PaUtilBufferProcessor *, unsigned int, void *, unsigned int) =
+ StreamDirection_In == self->streamDir ? PaUtil_SetInputChannel : PaUtil_SetOutputChannel;
+ unsigned char *buffer, *p;
+ int i;
+ unsigned long framesAvail;
+
+ /* This _must_ be called before mmap_begin */
+ PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( self, &framesAvail, xrun ) );
+ if( *xrun )
+ {
+ *numFrames = 0;
+ goto end;
+ }
+
+ ENSURE_( snd_pcm_mmap_begin( self->pcm, &areas, &self->offset, numFrames ), paUnanticipatedHostError );
+
+ if( self->hostInterleaved )
+ {
+ int swidth = snd_pcm_format_size( self->nativeFormat, 1 );
+
+ p = buffer = ExtractAddress( areas, self->offset );
+ for( i = 0; i < self->numUserChannels; ++i )
+ {
+ /* We're setting the channels up to userChannels, but the stride will be hostChannels samples */
+ setChannel( bp, i, p, self->numHostChannels );
+ p += swidth;
+ }
+ }
+ else
+ {
+ for( i = 0; i < self->numUserChannels; ++i )
+ {
+ area = areas + i;
+ buffer = ExtractAddress( area, self->offset );
+ setChannel( bp, i, buffer, 1 );
+ }
+ }
+
+ /* @concern ChannelAdaption Buffer address is recorded so we can do some channel adaption later */
+ self->channelAreas = (snd_pcm_channel_area_t *)areas;
+
+end:
+error:
+ return result;
+}
+
+/** Initiate buffer processing.
+ *
+ * ALSA buffers are registered with the PA buffer processor and the buffer size (in frames) set.
+ *
+ * @concern FullDuplex If both directions are being processed, the minimum amount of frames for the two directions is
+ * calculated.
+ *
+ * @param numFrames On entrance the number of available frames, on exit the number of received frames
+ * @param xrunOccurred Return whether an xrun has occurred
+ */
+static PaError PaAlsaStream_SetUpBuffers( PaAlsaStream* self, unsigned long* numFrames, int* xrunOccurred )
+{
+ PaError result = paNoError;
+ unsigned long captureFrames = ULONG_MAX, playbackFrames = ULONG_MAX, commonFrames = 0;
+ int xrun = 0;
+
+ if( *xrunOccurred )
+ {
+ *numFrames = 0;
+ return result;
+ }
+ /* If we got here at least one of the pcm's should be marked ready */
+ PA_UNLESS( self->capture.ready || self->playback.ready, paInternalError );
+
+ /* Extract per-channel ALSA buffer pointers and register them with the buffer processor.
+ * It is possible that a direction is not marked ready however, because it is out of sync with the other.
+ */
+ if( self->capture.pcm && self->capture.ready )
+ {
+ captureFrames = *numFrames;
+ PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->capture, &self->bufferProcessor, &captureFrames,
+ &xrun ) );
+ }
+ if( self->playback.pcm && self->playback.ready )
+ {
+ playbackFrames = *numFrames;
+ PA_ENSURE( PaAlsaStreamComponent_RegisterChannels( &self->playback, &self->bufferProcessor, &playbackFrames,
+ &xrun ) );
+ }
+ if( xrun )
+ {
+ /* Nothing more to do */
+ assert( 0 == commonFrames );
+ goto end;
+ }
+
+ commonFrames = PA_MIN( captureFrames, playbackFrames );
+ /* assert( commonFrames <= *numFrames ); */
+ if( commonFrames > *numFrames )
+ {
+ /* Hmmm ... how come there are more frames available than we requested!? Blah. */
+ PA_DEBUG(( "%s: Common available frames are reported to be more than number requested: %lu, %lu, callbackMode: %d\n", __FUNCTION__,
+ commonFrames, *numFrames, self->callbackMode ));
+ if( self->capture.pcm )
+ {
+ PA_DEBUG(( "%s: captureFrames: %lu, capture.ready: %d\n", __FUNCTION__, captureFrames, self->capture.ready ));
+ }
+ if( self->playback.pcm )
+ {
+ PA_DEBUG(( "%s: playbackFrames: %lu, playback.ready: %d\n", __FUNCTION__, playbackFrames, self->playback.ready ));
+ }
+
+ commonFrames = 0;
+ goto end;
+ }
+
+ /* Inform PortAudio of the number of frames we got.
+ * @concern FullDuplex We might be experiencing underflow in either end; if its an input underflow, we go on
+ * with output. If its output underflow however, depending on the paNeverDropInput flag, we may want to simply
+ * discard the excess input or call the callback with paOutputOverflow flagged.
+ */
+ if( self->capture.pcm )
+ {
+ if( self->capture.ready )
+ {
+ PaUtil_SetInputFrameCount( &self->bufferProcessor, commonFrames );
+ }
+ else
+ {
+ /* We have input underflow */
+ PaUtil_SetNoInput( &self->bufferProcessor );
+ }
+ }
+ if( self->playback.pcm )
+ {
+ if( self->playback.ready )
+ {
+ PaUtil_SetOutputFrameCount( &self->bufferProcessor, commonFrames );
+ }
+ else
+ {
+ /* We have output underflow, but keeping input data (paNeverDropInput) */
+ assert( self->neverDropInput );
+ assert( self->capture.pcm != NULL );
+ PA_DEBUG(( "%s: Setting output buffers to NULL\n", __FUNCTION__ ));
+ PaUtil_SetNoOutput( &self->bufferProcessor );
+ }
+ }
+
+end:
+ *numFrames = commonFrames;
+error:
+ if( xrun )
+ {
+ PA_ENSURE( PaAlsaStream_HandleXrun( self ) );
+ *numFrames = 0;
+ }
+ *xrunOccurred = xrun;
+
+ return result;
+}
+
+/** Callback thread's function.
+ *
+ * Roughly, the workflow can be described in the following way: The number of available frames that can be processed
+ * directly is obtained from ALSA, we then request as much directly accessible memory as possible within this amount
+ * from ALSA. The buffer memory is registered with the PA buffer processor and processing is carried out with
+ * PaUtil_EndBufferProcessing. Finally, the number of processed frames is reported to ALSA. The processing can
+ * happen in several iterations untill we have consumed the known number of available frames (or an xrun is detected).
+ */
+static void *CallbackThreadFunc( void *userData )
+{
+ PaError result = paNoError;
+ PaAlsaStream *stream = (PaAlsaStream*) userData;
+ PaStreamCallbackTimeInfo timeInfo = {0, 0, 0};
+ snd_pcm_sframes_t startThreshold = 0;
+ int callbackResult = paContinue;
+ PaStreamCallbackFlags cbFlags = 0; /* We might want to keep state across iterations */
+ int streamStarted = 0;
+
+ assert( stream );
+
+ /* Execute OnExit when exiting */
+ pthread_cleanup_push( &OnExit, stream );
+
+ /* Not implemented */
+ assert( !stream->primeBuffers );
+
+ /* @concern StreamStart If the output is being primed the output pcm needs to be prepared, otherwise the
+ * stream is started immediately. The latter involves signaling the waiting main thread.
+ */
+ if( stream->primeBuffers )
+ {
+ snd_pcm_sframes_t avail;
+
+ if( stream->playback.pcm )
+ ENSURE_( snd_pcm_prepare( stream->playback.pcm ), paUnanticipatedHostError );
+ if( stream->capture.pcm && !stream->pcmsSynced )
+ ENSURE_( snd_pcm_prepare( stream->capture.pcm ), paUnanticipatedHostError );
+
+ /* We can't be certain that the whole ring buffer is available for priming, but there should be
+ * at least one period */
+ avail = snd_pcm_avail_update( stream->playback.pcm );
+ startThreshold = avail - (avail % stream->playback.framesPerBuffer);
+ assert( startThreshold >= stream->playback.framesPerBuffer );
+ }
+ else
+ {
+ PA_ENSURE( PaUnixThread_PrepareNotify( &stream->thread ) );
+ /* Buffer will be zeroed */
+ PA_ENSURE( AlsaStart( stream, 0 ) );
+ PA_ENSURE( PaUnixThread_NotifyParent( &stream->thread ) );
+
+ streamStarted = 1;
+ }
+
+ while( 1 )
+ {
+ unsigned long framesAvail, framesGot;
+ int xrun = 0;
+
+ pthread_testcancel();
+
+ /* @concern StreamStop if the main thread has requested a stop and the stream has not been effectively
+ * stopped we signal this condition by modifying callbackResult (we'll want to flush buffered output).
+ */
+ if( PaUnixThread_StopRequested( &stream->thread ) && paContinue == callbackResult )
+ {
+ PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
+ callbackResult = paComplete;
+ }
+
+ if( paContinue != callbackResult )
+ {
+ stream->callbackAbort = (paAbort == callbackResult);
+ if( stream->callbackAbort ||
+ /** @concern BlockAdaption: Go on if adaption buffers are empty */
+ PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
+ {
+ goto end;
+ }
+
+ PA_DEBUG(( "%s: Flushing buffer processor\n", __FUNCTION__ ));
+ /* There is still buffered output that needs to be processed */
+ }
+
+ /* Wait for data to become available, this comes down to polling the ALSA file descriptors untill we have
+ * a number of available frames.
+ */
+ PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) );
+ if( xrun )
+ {
+ assert( 0 == framesAvail );
+ continue;
+
+ /* XXX: Report xruns to the user? A situation is conceivable where the callback is never invoked due
+ * to constant xruns, it might be desirable to notify the user of this.
+ */
+ }
+
+ /* Consume buffer space. Once we have a number of frames available for consumption we must retrieve the
+ * mmapped buffers from ALSA, this is contiguously accessible memory however, so we may receive smaller
+ * portions at a time than is available as a whole. Therefore we should be prepared to process several
+ * chunks successively. The buffers are passed to the PA buffer processor.
+ */
+ while( framesAvail > 0 )
+ {
+ xrun = 0;
+
+ pthread_testcancel();
+
+ /** @concern Xruns Under/overflows are to be reported to the callback */
+ if( stream->underrun > 0.0 )
+ {
+ cbFlags |= paOutputUnderflow;
+ stream->underrun = 0.0;
+ }
+ if( stream->overrun > 0.0 )
+ {
+ cbFlags |= paInputOverflow;
+ stream->overrun = 0.0;
+ }
+ if( stream->capture.pcm && stream->playback.pcm )
+ {
+ /** @concern FullDuplex It's possible that only one direction is being processed to avoid an
+ * under- or overflow, this should be reported correspondingly */
+ if( !stream->capture.ready )
+ {
+ cbFlags |= paInputUnderflow;
+ PA_DEBUG(( "%s: Input underflow\n", __FUNCTION__ ));
+ }
+ else if( !stream->playback.ready )
+ {
+ cbFlags |= paOutputOverflow;
+ PA_DEBUG(( "%s: Output overflow\n", __FUNCTION__ ));
+ }
+ }
+
+#if 0
+ CallbackUpdate( &stream->threading );
+#endif
+ CalculateTimeInfo( stream, &timeInfo );
+ PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, cbFlags );
+ cbFlags = 0;
+
+ /* CPU load measurement should include processing activivity external to the stream callback */
+ PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+
+ framesGot = framesAvail;
+ if( paUtilFixedHostBufferSize == stream->bufferProcessor.hostBufferSizeMode )
+ {
+ /* We've committed to a fixed host buffer size, stick to that */
+ framesGot = framesGot >= stream->maxFramesPerHostBuffer ? stream->maxFramesPerHostBuffer : 0;
+ }
+ else
+ {
+ /* We've committed to an upper bound on the size of host buffers */
+ assert( paUtilBoundedHostBufferSize == stream->bufferProcessor.hostBufferSizeMode );
+ framesGot = PA_MIN( framesGot, stream->maxFramesPerHostBuffer );
+ }
+ PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) );
+ /* Check the host buffer size against the buffer processor configuration */
+ framesAvail -= framesGot;
+
+ if( framesGot > 0 )
+ {
+ assert( !xrun );
+ PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
+ PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) );
+ }
+ PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesGot );
+
+ if( 0 == framesGot )
+ {
+ /* Go back to polling for more frames */
+ break;
+
+ }
+
+ if( paContinue != callbackResult )
+ break;
+ }
+ }
+
+ /* Match pthread_cleanup_push */
+ pthread_cleanup_pop( 1 );
+
+end:
+ PA_DEBUG(( "%s: Thread %d exiting\n ", __FUNCTION__, pthread_self() ));
+ PaUnixThreading_EXIT( result );
+error:
+ goto end;
+}
+
+/* Blocking interface */
+
+static PaError ReadStream( PaStream* s, void *buffer, unsigned long frames )
+{
+ PaError result = paNoError;
+ PaAlsaStream *stream = (PaAlsaStream*)s;
+ unsigned long framesGot, framesAvail;
+ void *userBuffer;
+ snd_pcm_t *save = stream->playback.pcm;
+
+ assert( stream );
+
+ PA_UNLESS( stream->capture.pcm, paCanNotReadFromAnOutputOnlyStream );
+
+ /* Disregard playback */
+ stream->playback.pcm = NULL;
+
+ if( stream->overrun > 0. )
+ {
+ result = paInputOverflowed;
+ stream->overrun = 0.0;
+ }
+
+ if( stream->capture.userInterleaved )
+ {
+ userBuffer = buffer;
+ }
+ else
+ {
+ /* Copy channels into local array */
+ userBuffer = stream->capture.userBuffers;
+ memcpy( userBuffer, buffer, sizeof (void *) * stream->capture.numUserChannels );
+ }
+
+ /* Start stream if in prepared state */
+ if( snd_pcm_state( stream->capture.pcm ) == SND_PCM_STATE_PREPARED )
+ {
+ ENSURE_( snd_pcm_start( stream->capture.pcm ), paUnanticipatedHostError );
+ }
+
+ while( frames > 0 )
+ {
+ int xrun = 0;
+ PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) );
+ framesGot = PA_MIN( framesAvail, frames );
+
+ PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) );
+ if( framesGot > 0 )
+ {
+ framesGot = PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesGot );
+ PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) );
+ frames -= framesGot;
+ }
+ }
+
+end:
+ stream->playback.pcm = save;
+ return result;
+error:
+ goto end;
+}
+
+static PaError WriteStream( PaStream* s, const void *buffer, unsigned long frames )
+{
+ PaError result = paNoError;
+ signed long err;
+ PaAlsaStream *stream = (PaAlsaStream*)s;
+ snd_pcm_uframes_t framesGot, framesAvail;
+ const void *userBuffer;
+ snd_pcm_t *save = stream->capture.pcm;
+
+ assert( stream );
+
+ PA_UNLESS( stream->playback.pcm, paCanNotWriteToAnInputOnlyStream );
+
+ /* Disregard capture */
+ stream->capture.pcm = NULL;
+
+ if( stream->underrun > 0. )
+ {
+ result = paOutputUnderflowed;
+ stream->underrun = 0.0;
+ }
+
+ if( stream->playback.userInterleaved )
+ userBuffer = buffer;
+ else /* Copy channels into local array */
+ {
+ userBuffer = stream->playback.userBuffers;
+ memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->playback.numUserChannels );
+ }
+
+ while( frames > 0 )
+ {
+ int xrun = 0;
+ snd_pcm_uframes_t hwAvail;
+
+ PA_ENSURE( PaAlsaStream_WaitForFrames( stream, &framesAvail, &xrun ) );
+ framesGot = PA_MIN( framesAvail, frames );
+
+ PA_ENSURE( PaAlsaStream_SetUpBuffers( stream, &framesGot, &xrun ) );
+ if( framesGot > 0 )
+ {
+ framesGot = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, framesGot );
+ PA_ENSURE( PaAlsaStream_EndProcessing( stream, framesGot, &xrun ) );
+ frames -= framesGot;
+ }
+
+ /* Start stream after one period of samples worth */
+
+ /* Frames residing in buffer */
+ PA_ENSURE( err = GetStreamWriteAvailable( stream ) );
+ framesAvail = err;
+ hwAvail = stream->playback.bufferSize - framesAvail;
+
+ if( snd_pcm_state( stream->playback.pcm ) == SND_PCM_STATE_PREPARED &&
+ hwAvail >= stream->playback.framesPerBuffer )
+ {
+ ENSURE_( snd_pcm_start( stream->playback.pcm ), paUnanticipatedHostError );
+ }
+ }
+
+end:
+ stream->capture.pcm = save;
+ return result;
+error:
+ goto end;
+}
+
+/* Return frames available for reading. In the event of an overflow, the capture pcm will be restarted */
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+ PaError result = paNoError;
+ PaAlsaStream *stream = (PaAlsaStream*)s;
+ unsigned long avail;
+ int xrun;
+
+ PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->capture, &avail, &xrun ) );
+ if( xrun )
+ {
+ PA_ENSURE( PaAlsaStream_HandleXrun( stream ) );
+ PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->capture, &avail, &xrun ) );
+ if( xrun )
+ PA_ENSURE( paInputOverflowed );
+ }
+
+ return (signed long)avail;
+
+error:
+ return result;
+}
+
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+ PaError result = paNoError;
+ PaAlsaStream *stream = (PaAlsaStream*)s;
+ unsigned long avail;
+ int xrun;
+
+ PA_ENSURE( PaAlsaStreamComponent_GetAvailableFrames( &stream->playback, &avail, &xrun ) );
+ if( xrun )
+ {
+ snd_pcm_sframes_t savail;
+
+ PA_ENSURE( PaAlsaStream_HandleXrun( stream ) );
+ savail = snd_pcm_avail_update( stream->playback.pcm );
+
+ /* savail should not contain -EPIPE now, since PaAlsaStream_HandleXrun will only prepare the pcm */
+ ENSURE_( savail, paUnanticipatedHostError );
+
+ avail = (unsigned long) savail;
+ }
+
+ return (signed long)avail;
+
+error:
+ return result;
+}
+
+/* Extensions */
+
+void PaAlsa_InitializeStreamInfo( PaAlsaStreamInfo *info )
+{
+ info->size = sizeof (PaAlsaStreamInfo);
+ info->hostApiType = paALSA;
+ info->version = 1;
+ info->deviceString = NULL;
+}
+
+void PaAlsa_EnableRealtimeScheduling( PaStream *s, int enable )
+{
+ PaAlsaStream *stream = (PaAlsaStream *) s;
+ stream->rtSched = enable;
+}
+
+#if 0
+void PaAlsa_EnableWatchdog( PaStream *s, int enable )
+{
+ PaAlsaStream *stream = (PaAlsaStream *) s;
+ stream->thread.useWatchdog = enable;
+}
+#endif
+
+PaError PaAlsa_GetStreamInputCard(PaStream* s, int* card) {
+ PaAlsaStream *stream = (PaAlsaStream *) s;
+ snd_pcm_info_t* pcmInfo;
+ PaError result = paNoError;
+
+ /* XXX: More descriptive error? */
+ PA_UNLESS( stream->capture.pcm, paDeviceUnavailable );
+
+ snd_pcm_info_alloca( &pcmInfo );
+ PA_ENSURE( snd_pcm_info( stream->capture.pcm, pcmInfo ) );
+ *card = snd_pcm_info_get_card( pcmInfo );
+
+error:
+ return result;
+}
+
+PaError PaAlsa_GetStreamOutputCard(PaStream* s, int* card) {
+ PaAlsaStream *stream = (PaAlsaStream *) s;
+ snd_pcm_info_t* pcmInfo;
+ PaError result = paNoError;
+
+ /* XXX: More descriptive error? */
+ PA_UNLESS( stream->playback.pcm, paDeviceUnavailable );
+
+ snd_pcm_info_alloca( &pcmInfo );
+ PA_ENSURE( snd_pcm_info( stream->playback.pcm, pcmInfo ) );
+ *card = snd_pcm_info_get_card( pcmInfo );
+
+error:
+ return result;
+}
diff --git a/pd/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp b/pd/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp
new file mode 100644
index 00000000..8dfefbd6
--- /dev/null
+++ b/pd/portaudio/src/hostapi/asio/iasiothiscallresolver.cpp
@@ -0,0 +1,563 @@
+/*
+ IASIOThiscallResolver.cpp see the comments in iasiothiscallresolver.h for
+ the top level description - this comment describes the technical details of
+ the implementation.
+
+ The latest version of this file is available from:
+ http://www.audiomulch.com/~rossb/code/calliasio
+
+ please email comments to Ross Bencina <rossb@audiomulch.com>
+
+ BACKGROUND
+
+ The IASIO interface declared in the Steinberg ASIO 2 SDK declares
+ functions with no explicit calling convention. This causes MSVC++ to default
+ to using the thiscall convention, which is a proprietary convention not
+ implemented by some non-microsoft compilers - notably borland BCC,
+ C++Builder, and gcc. MSVC++ is the defacto standard compiler used by
+ Steinberg. As a result of this situation, the ASIO sdk will compile with
+ any compiler, however attempting to execute the compiled code will cause a
+ crash due to different default calling conventions on non-Microsoft
+ compilers.
+
+ IASIOThiscallResolver solves the problem by providing an adapter class that
+ delegates to the IASIO interface using the correct calling convention
+ (thiscall). Due to the lack of support for thiscall in the Borland and GCC
+ compilers, the calls have been implemented in assembly language.
+
+ A number of macros are defined for thiscall function calls with different
+ numbers of parameters, with and without return values - it may be possible
+ to modify the format of these macros to make them work with other inline
+ assemblers.
+
+
+ THISCALL DEFINITION
+
+ A number of definitions of the thiscall calling convention are floating
+ around the internet. The following definition has been validated against
+ output from the MSVC++ compiler:
+
+ For non-vararg functions, thiscall works as follows: the object (this)
+ pointer is passed in ECX. All arguments are passed on the stack in
+ right to left order. The return value is placed in EAX. The callee
+ clears the passed arguments from the stack.
+
+
+ FINDING FUNCTION POINTERS FROM AN IASIO POINTER
+
+ The first field of a COM object is a pointer to its vtble. Thus a pointer
+ to an object implementing the IASIO interface also points to a pointer to
+ that object's vtbl. The vtble is a table of function pointers for all of
+ the virtual functions exposed by the implemented interfaces.
+
+ If we consider a variable declared as a pointer to IASO:
+
+ IASIO *theAsioDriver
+
+ theAsioDriver points to:
+
+ object implementing IASIO
+ {
+ IASIOvtbl *vtbl
+ other data
+ }
+
+ in other words, theAsioDriver points to a pointer to an IASIOvtbl
+
+ vtbl points to a table of function pointers:
+
+ IASIOvtbl ( interface IASIO : public IUnknown )
+ {
+ (IUnknown functions)
+ 0 virtual HRESULT STDMETHODCALLTYPE (*QueryInterface)(REFIID riid, void **ppv) = 0;
+ 4 virtual ULONG STDMETHODCALLTYPE (*AddRef)() = 0;
+ 8 virtual ULONG STDMETHODCALLTYPE (*Release)() = 0;
+
+ (IASIO functions)
+ 12 virtual ASIOBool (*init)(void *sysHandle) = 0;
+ 16 virtual void (*getDriverName)(char *name) = 0;
+ 20 virtual long (*getDriverVersion)() = 0;
+ 24 virtual void (*getErrorMessage)(char *string) = 0;
+ 28 virtual ASIOError (*start)() = 0;
+ 32 virtual ASIOError (*stop)() = 0;
+ 36 virtual ASIOError (*getChannels)(long *numInputChannels, long *numOutputChannels) = 0;
+ 40 virtual ASIOError (*getLatencies)(long *inputLatency, long *outputLatency) = 0;
+ 44 virtual ASIOError (*getBufferSize)(long *minSize, long *maxSize,
+ long *preferredSize, long *granularity) = 0;
+ 48 virtual ASIOError (*canSampleRate)(ASIOSampleRate sampleRate) = 0;
+ 52 virtual ASIOError (*getSampleRate)(ASIOSampleRate *sampleRate) = 0;
+ 56 virtual ASIOError (*setSampleRate)(ASIOSampleRate sampleRate) = 0;
+ 60 virtual ASIOError (*getClockSources)(ASIOClockSource *clocks, long *numSources) = 0;
+ 64 virtual ASIOError (*setClockSource)(long reference) = 0;
+ 68 virtual ASIOError (*getSamplePosition)(ASIOSamples *sPos, ASIOTimeStamp *tStamp) = 0;
+ 72 virtual ASIOError (*getChannelInfo)(ASIOChannelInfo *info) = 0;
+ 76 virtual ASIOError (*createBuffers)(ASIOBufferInfo *bufferInfos, long numChannels,
+ long bufferSize, ASIOCallbacks *callbacks) = 0;
+ 80 virtual ASIOError (*disposeBuffers)() = 0;
+ 84 virtual ASIOError (*controlPanel)() = 0;
+ 88 virtual ASIOError (*future)(long selector,void *opt) = 0;
+ 92 virtual ASIOError (*outputReady)() = 0;
+ };
+
+ The numbers in the left column show the byte offset of each function ptr
+ from the beginning of the vtbl. These numbers are used in the code below
+ to select different functions.
+
+ In order to find the address of a particular function, theAsioDriver
+ must first be dereferenced to find the value of the vtbl pointer:
+
+ mov eax, theAsioDriver
+ mov edx, [theAsioDriver] // edx now points to vtbl[0]
+
+ Then an offset must be added to the vtbl pointer to select a
+ particular function, for example vtbl+44 points to the slot containing
+ a pointer to the getBufferSize function.
+
+ Finally vtbl+x must be dereferenced to obtain the value of the function
+ pointer stored in that address:
+
+ call [edx+44] // call the function pointed to by
+ // the value in the getBufferSize field of the vtbl
+
+
+ SEE ALSO
+
+ Martin Fay's OpenASIO DLL at http://www.martinfay.com solves the same
+ problem by providing a new COM interface which wraps IASIO with an
+ interface that uses portable calling conventions. OpenASIO must be compiled
+ with MSVC, and requires that you ship the OpenASIO DLL with your
+ application.
+
+
+ ACKNOWLEDGEMENTS
+
+ Ross Bencina: worked out the thiscall details above, wrote the original
+ Borland asm macros, and a patch for asio.cpp (which is no longer needed).
+ Thanks to Martin Fay for introducing me to the issues discussed here,
+ and to Rene G. Ceballos for assisting with asm dumps from MSVC++.
+
+ Antti Silvast: converted the original calliasio to work with gcc and NASM
+ by implementing the asm code in a separate file.
+
+ Fraser Adams: modified the original calliasio containing the Borland inline
+ asm to add inline asm for gcc i.e. Intel syntax for Borland and AT&T syntax
+ for gcc. This seems a neater approach for gcc than to have a separate .asm
+ file and it means that we only need one version of the thiscall patch.
+
+ Fraser Adams: rewrote the original calliasio patch in the form of the
+ IASIOThiscallResolver class in order to avoid modifications to files from
+ the Steinberg SDK, which may have had potential licence issues.
+
+ Andrew Baldwin: contributed fixes for compatibility problems with more
+ recent versions of the gcc assembler.
+*/
+
+
+// We only need IASIOThiscallResolver at all if we are on Win32. For other
+// platforms we simply bypass the IASIOThiscallResolver definition to allow us
+// to be safely #include'd whatever the platform to keep client code portable
+#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
+
+
+// If microsoft compiler we can call IASIO directly so IASIOThiscallResolver
+// is not used.
+#if !defined(_MSC_VER)
+
+
+#include <new>
+#include <assert.h>
+
+// We have a mechanism in iasiothiscallresolver.h to ensure that asio.h is
+// #include'd before it in client code, we do NOT want to do this test here.
+#define iasiothiscallresolver_sourcefile 1
+#include "iasiothiscallresolver.h"
+#undef iasiothiscallresolver_sourcefile
+
+// iasiothiscallresolver.h redefines ASIOInit for clients, but we don't want
+// this macro defined in this translation unit.
+#undef ASIOInit
+
+
+// theAsioDriver is a global pointer to the current IASIO instance which the
+// ASIO SDK uses to perform all actions on the IASIO interface. We substitute
+// our own forwarding interface into this pointer.
+extern IASIO* theAsioDriver;
+
+
+// The following macros define the inline assembler for BORLAND first then gcc
+
+#if defined(__BCPLUSPLUS__) || defined(__BORLANDC__)
+
+
+#define CALL_THISCALL_0( resultName, thisPtr, funcOffset )\
+ void *this_ = (thisPtr); \
+ __asm { \
+ mov ecx, this_ ; \
+ mov eax, [ecx] ; \
+ call [eax+funcOffset] ; \
+ mov resultName, eax ; \
+ }
+
+
+#define CALL_VOID_THISCALL_1( thisPtr, funcOffset, param1 )\
+ void *this_ = (thisPtr); \
+ __asm { \
+ mov eax, param1 ; \
+ push eax ; \
+ mov ecx, this_ ; \
+ mov eax, [ecx] ; \
+ call [eax+funcOffset] ; \
+ }
+
+
+#define CALL_THISCALL_1( resultName, thisPtr, funcOffset, param1 )\
+ void *this_ = (thisPtr); \
+ __asm { \
+ mov eax, param1 ; \
+ push eax ; \
+ mov ecx, this_ ; \
+ mov eax, [ecx] ; \
+ call [eax+funcOffset] ; \
+ mov resultName, eax ; \
+ }
+
+
+#define CALL_THISCALL_1_DOUBLE( resultName, thisPtr, funcOffset, param1 )\
+ void *this_ = (thisPtr); \
+ void *doubleParamPtr_ (&param1); \
+ __asm { \
+ mov eax, doubleParamPtr_ ; \
+ push [eax+4] ; \
+ push [eax] ; \
+ mov ecx, this_ ; \
+ mov eax, [ecx] ; \
+ call [eax+funcOffset] ; \
+ mov resultName, eax ; \
+ }
+
+
+#define CALL_THISCALL_2( resultName, thisPtr, funcOffset, param1, param2 )\
+ void *this_ = (thisPtr); \
+ __asm { \
+ mov eax, param2 ; \
+ push eax ; \
+ mov eax, param1 ; \
+ push eax ; \
+ mov ecx, this_ ; \
+ mov eax, [ecx] ; \
+ call [eax+funcOffset] ; \
+ mov resultName, eax ; \
+ }
+
+
+#define CALL_THISCALL_4( resultName, thisPtr, funcOffset, param1, param2, param3, param4 )\
+ void *this_ = (thisPtr); \
+ __asm { \
+ mov eax, param4 ; \
+ push eax ; \
+ mov eax, param3 ; \
+ push eax ; \
+ mov eax, param2 ; \
+ push eax ; \
+ mov eax, param1 ; \
+ push eax ; \
+ mov ecx, this_ ; \
+ mov eax, [ecx] ; \
+ call [eax+funcOffset] ; \
+ mov resultName, eax ; \
+ }
+
+
+#elif defined(__GNUC__)
+
+
+#define CALL_THISCALL_0( resultName, thisPtr, funcOffset ) \
+ __asm__ __volatile__ ("movl (%1), %%edx\n\t" \
+ "call *"#funcOffset"(%%edx)\n\t" \
+ :"=a"(resultName) /* Output Operands */ \
+ :"c"(thisPtr) /* Input Operands */ \
+ ); \
+
+
+#define CALL_VOID_THISCALL_1( thisPtr, funcOffset, param1 ) \
+ __asm__ __volatile__ ("pushl %0\n\t" \
+ "movl (%1), %%edx\n\t" \
+ "call *"#funcOffset"(%%edx)\n\t" \
+ : /* Output Operands */ \
+ :"r"(param1), /* Input Operands */ \
+ "c"(thisPtr) \
+ ); \
+
+
+#define CALL_THISCALL_1( resultName, thisPtr, funcOffset, param1 ) \
+ __asm__ __volatile__ ("pushl %1\n\t" \
+ "movl (%2), %%edx\n\t" \
+ "call *"#funcOffset"(%%edx)\n\t" \
+ :"=a"(resultName) /* Output Operands */ \
+ :"r"(param1), /* Input Operands */ \
+ "c"(thisPtr) \
+ ); \
+
+
+#define CALL_THISCALL_1_DOUBLE( resultName, thisPtr, funcOffset, param1 ) \
+ __asm__ __volatile__ ("pushl 4(%1)\n\t" \
+ "pushl (%1)\n\t" \
+ "movl (%2), %%edx\n\t" \
+ "call *"#funcOffset"(%%edx);\n\t" \
+ :"=a"(resultName) /* Output Operands */ \
+ :"a"(&param1), /* Input Operands */ \
+ /* Note: Using "r" above instead of "a" fails */ \
+ /* when using GCC 3.3.3, and maybe later versions*/\
+ "c"(thisPtr) \
+ ); \
+
+
+#define CALL_THISCALL_2( resultName, thisPtr, funcOffset, param1, param2 ) \
+ __asm__ __volatile__ ("pushl %1\n\t" \
+ "pushl %2\n\t" \
+ "movl (%3), %%edx\n\t" \
+ "call *"#funcOffset"(%%edx)\n\t" \
+ :"=a"(resultName) /* Output Operands */ \
+ :"r"(param2), /* Input Operands */ \
+ "r"(param1), \
+ "c"(thisPtr) \
+ ); \
+
+
+#define CALL_THISCALL_4( resultName, thisPtr, funcOffset, param1, param2, param3, param4 )\
+ __asm__ __volatile__ ("pushl %1\n\t" \
+ "pushl %2\n\t" \
+ "pushl %3\n\t" \
+ "pushl %4\n\t" \
+ "movl (%5), %%edx\n\t" \
+ "call *"#funcOffset"(%%edx)\n\t" \
+ :"=a"(resultName) /* Output Operands */ \
+ :"r"(param4), /* Input Operands */ \
+ "r"(param3), \
+ "r"(param2), \
+ "r"(param1), \
+ "c"(thisPtr) \
+ ); \
+
+#endif
+
+
+
+// Our static singleton instance.
+IASIOThiscallResolver IASIOThiscallResolver::instance;
+
+// Constructor called to initialize static Singleton instance above. Note that
+// it is important not to clear that_ incase it has already been set by the call
+// to placement new in ASIOInit().
+IASIOThiscallResolver::IASIOThiscallResolver()
+{
+}
+
+// Constructor called from ASIOInit() below
+IASIOThiscallResolver::IASIOThiscallResolver(IASIO* that)
+: that_( that )
+{
+}
+
+// Implement IUnknown methods as assert(false). IASIOThiscallResolver is not
+// really a COM object, just a wrapper which will work with the ASIO SDK.
+// If you wanted to use ASIO without the SDK you might want to implement COM
+// aggregation in these methods.
+HRESULT STDMETHODCALLTYPE IASIOThiscallResolver::QueryInterface(REFIID riid, void **ppv)
+{
+ (void)riid; // suppress unused variable warning
+
+ assert( false ); // this function should never be called by the ASIO SDK.
+
+ *ppv = NULL;
+ return E_NOINTERFACE;
+}
+
+ULONG STDMETHODCALLTYPE IASIOThiscallResolver::AddRef()
+{
+ assert( false ); // this function should never be called by the ASIO SDK.
+
+ return 1;
+}
+
+ULONG STDMETHODCALLTYPE IASIOThiscallResolver::Release()
+{
+ assert( false ); // this function should never be called by the ASIO SDK.
+
+ return 1;
+}
+
+
+// Implement the IASIO interface methods by performing the vptr manipulation
+// described above then delegating to the real implementation.
+ASIOBool IASIOThiscallResolver::init(void *sysHandle)
+{
+ ASIOBool result;
+ CALL_THISCALL_1( result, that_, 12, sysHandle );
+ return result;
+}
+
+void IASIOThiscallResolver::getDriverName(char *name)
+{
+ CALL_VOID_THISCALL_1( that_, 16, name );
+}
+
+long IASIOThiscallResolver::getDriverVersion()
+{
+ ASIOBool result;
+ CALL_THISCALL_0( result, that_, 20 );
+ return result;
+}
+
+void IASIOThiscallResolver::getErrorMessage(char *string)
+{
+ CALL_VOID_THISCALL_1( that_, 24, string );
+}
+
+ASIOError IASIOThiscallResolver::start()
+{
+ ASIOBool result;
+ CALL_THISCALL_0( result, that_, 28 );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::stop()
+{
+ ASIOBool result;
+ CALL_THISCALL_0( result, that_, 32 );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::getChannels(long *numInputChannels, long *numOutputChannels)
+{
+ ASIOBool result;
+ CALL_THISCALL_2( result, that_, 36, numInputChannels, numOutputChannels );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::getLatencies(long *inputLatency, long *outputLatency)
+{
+ ASIOBool result;
+ CALL_THISCALL_2( result, that_, 40, inputLatency, outputLatency );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::getBufferSize(long *minSize, long *maxSize,
+ long *preferredSize, long *granularity)
+{
+ ASIOBool result;
+ CALL_THISCALL_4( result, that_, 44, minSize, maxSize, preferredSize, granularity );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::canSampleRate(ASIOSampleRate sampleRate)
+{
+ ASIOBool result;
+ CALL_THISCALL_1_DOUBLE( result, that_, 48, sampleRate );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::getSampleRate(ASIOSampleRate *sampleRate)
+{
+ ASIOBool result;
+ CALL_THISCALL_1( result, that_, 52, sampleRate );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::setSampleRate(ASIOSampleRate sampleRate)
+{
+ ASIOBool result;
+ CALL_THISCALL_1_DOUBLE( result, that_, 56, sampleRate );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::getClockSources(ASIOClockSource *clocks, long *numSources)
+{
+ ASIOBool result;
+ CALL_THISCALL_2( result, that_, 60, clocks, numSources );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::setClockSource(long reference)
+{
+ ASIOBool result;
+ CALL_THISCALL_1( result, that_, 64, reference );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp)
+{
+ ASIOBool result;
+ CALL_THISCALL_2( result, that_, 68, sPos, tStamp );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::getChannelInfo(ASIOChannelInfo *info)
+{
+ ASIOBool result;
+ CALL_THISCALL_1( result, that_, 72, info );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::createBuffers(ASIOBufferInfo *bufferInfos,
+ long numChannels, long bufferSize, ASIOCallbacks *callbacks)
+{
+ ASIOBool result;
+ CALL_THISCALL_4( result, that_, 76, bufferInfos, numChannels, bufferSize, callbacks );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::disposeBuffers()
+{
+ ASIOBool result;
+ CALL_THISCALL_0( result, that_, 80 );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::controlPanel()
+{
+ ASIOBool result;
+ CALL_THISCALL_0( result, that_, 84 );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::future(long selector,void *opt)
+{
+ ASIOBool result;
+ CALL_THISCALL_2( result, that_, 88, selector, opt );
+ return result;
+}
+
+ASIOError IASIOThiscallResolver::outputReady()
+{
+ ASIOBool result;
+ CALL_THISCALL_0( result, that_, 92 );
+ return result;
+}
+
+
+// Implement our substitute ASIOInit() method
+ASIOError IASIOThiscallResolver::ASIOInit(ASIODriverInfo *info)
+{
+ // To ensure that our instance's vptr is correctly constructed, even if
+ // ASIOInit is called prior to main(), we explicitly call its constructor
+ // (potentially over the top of an existing instance). Note that this is
+ // pretty ugly, and is only safe because IASIOThiscallResolver has no
+ // destructor and contains no objects with destructors.
+ new((void*)&instance) IASIOThiscallResolver( theAsioDriver );
+
+ // Interpose between ASIO client code and the real driver.
+ theAsioDriver = &instance;
+
+ // Note that we never need to switch theAsioDriver back to point to the
+ // real driver because theAsioDriver is reset to zero in ASIOExit().
+
+ // Delegate to the real ASIOInit
+ return ::ASIOInit(info);
+}
+
+
+#endif /* !defined(_MSC_VER) */
+
+#endif /* Win32 */
+
diff --git a/pd/portaudio/src/hostapi/asio/iasiothiscallresolver.h b/pd/portaudio/src/hostapi/asio/iasiothiscallresolver.h
new file mode 100644
index 00000000..2ecfed79
--- /dev/null
+++ b/pd/portaudio/src/hostapi/asio/iasiothiscallresolver.h
@@ -0,0 +1,197 @@
+// ****************************************************************************
+// File: IASIOThiscallResolver.h
+// Description: The IASIOThiscallResolver class implements the IASIO
+// interface and acts as a proxy to the real IASIO interface by
+// calling through its vptr table using the thiscall calling
+// convention. To put it another way, we interpose
+// IASIOThiscallResolver between ASIO SDK code and the driver.
+// This is necessary because most non-Microsoft compilers don't
+// implement the thiscall calling convention used by IASIO.
+//
+// iasiothiscallresolver.cpp contains the background of this
+// problem plus a technical description of the vptr
+// manipulations.
+//
+// In order to use this mechanism one simply has to add
+// iasiothiscallresolver.cpp to the list of files to compile
+// and #include <iasiothiscallresolver.h>
+//
+// Note that this #include must come after the other ASIO SDK
+// #includes, for example:
+//
+// #include <windows.h>
+// #include <asiosys.h>
+// #include <asio.h>
+// #include <asiodrivers.h>
+// #include <iasiothiscallresolver.h>
+//
+// Actually the important thing is to #include
+// <iasiothiscallresolver.h> after <asio.h>. We have
+// incorporated a test to enforce this ordering.
+//
+// The code transparently takes care of the interposition by
+// using macro substitution to intercept calls to ASIOInit()
+// and ASIOExit(). We save the original ASIO global
+// "theAsioDriver" in our "that" variable, and then set
+// "theAsioDriver" to equal our IASIOThiscallResolver instance.
+//
+// Whilst this method of resolving the thiscall problem requires
+// the addition of #include <iasiothiscallresolver.h> to client
+// code it has the advantage that it does not break the terms
+// of the ASIO licence by publishing it. We are NOT modifying
+// any Steinberg code here, we are merely implementing the IASIO
+// interface in the same way that we would need to do if we
+// wished to provide an open source ASIO driver.
+//
+// For compilation with MinGW -lole32 needs to be added to the
+// linker options. For BORLAND, linking with Import32.lib is
+// sufficient.
+//
+// The dependencies are with: CoInitialize, CoUninitialize,
+// CoCreateInstance, CLSIDFromString - used by asiolist.cpp
+// and are required on Windows whether ThiscallResolver is used
+// or not.
+//
+// Searching for the above strings in the root library path
+// of your compiler should enable the correct libraries to be
+// identified if they aren't immediately obvious.
+//
+// Note that the current implementation of IASIOThiscallResolver
+// is not COM compliant - it does not correctly implement the
+// IUnknown interface. Implementing it is not necessary because
+// it is not called by parts of the ASIO SDK which call through
+// theAsioDriver ptr. The IUnknown methods are implemented as
+// assert(false) to ensure that the code fails if they are
+// ever called.
+// Restrictions: None. Public Domain & Open Source distribute freely
+// You may use IASIOThiscallResolver commercially as well as
+// privately.
+// You the user assume the responsibility for the use of the
+// files, binary or text, and there is no guarantee or warranty,
+// expressed or implied, including but not limited to the
+// implied warranties of merchantability and fitness for a
+// particular purpose. You assume all responsibility and agree
+// to hold no entity, copyright holder or distributors liable
+// for any loss of data or inaccurate representations of data
+// as a result of using IASIOThiscallResolver.
+// Version: 1.4 Added separate macro CALL_THISCALL_1_DOUBLE from
+// Andrew Baldwin, and volatile for whole gcc asm blocks,
+// both for compatibility with newer gcc versions. Cleaned up
+// Borland asm to use one less register.
+// 1.3 Switched to including assert.h for better compatibility.
+// Wrapped entire .h and .cpp contents with a check for
+// _MSC_VER to provide better compatibility with MS compilers.
+// Changed Singleton implementation to use static instance
+// instead of freestore allocated instance. Removed ASIOExit
+// macro as it is no longer needed.
+// 1.2 Removed semicolons from ASIOInit and ASIOExit macros to
+// allow them to be embedded in expressions (if statements).
+// Cleaned up some comments. Removed combase.c dependency (it
+// doesn't compile with BCB anyway) by stubbing IUnknown.
+// 1.1 Incorporated comments from Ross Bencina including things
+// such as changing name from ThiscallResolver to
+// IASIOThiscallResolver, tidying up the constructor, fixing
+// a bug in IASIOThiscallResolver::ASIOExit() and improving
+// portability through the use of conditional compilation
+// 1.0 Initial working version.
+// Created: 6/09/2003
+// Authors: Fraser Adams
+// Ross Bencina
+// Rene G. Ceballos
+// Martin Fay
+// Antti Silvast
+// Andrew Baldwin
+//
+// ****************************************************************************
+
+
+#ifndef included_iasiothiscallresolver_h
+#define included_iasiothiscallresolver_h
+
+// We only need IASIOThiscallResolver at all if we are on Win32. For other
+// platforms we simply bypass the IASIOThiscallResolver definition to allow us
+// to be safely #include'd whatever the platform to keep client code portable
+#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
+
+
+// If microsoft compiler we can call IASIO directly so IASIOThiscallResolver
+// is not used.
+#if !defined(_MSC_VER)
+
+
+// The following is in order to ensure that this header is only included after
+// the other ASIO headers (except for the case of iasiothiscallresolver.cpp).
+// We need to do this because IASIOThiscallResolver works by eclipsing the
+// original definition of ASIOInit() with a macro (see below).
+#if !defined(iasiothiscallresolver_sourcefile)
+ #if !defined(__ASIO_H)
+ #error iasiothiscallresolver.h must be included AFTER asio.h
+ #endif
+#endif
+
+#include <windows.h>
+#include <asiodrvr.h> /* From ASIO SDK */
+
+
+class IASIOThiscallResolver : public IASIO {
+private:
+ IASIO* that_; // Points to the real IASIO
+
+ static IASIOThiscallResolver instance; // Singleton instance
+
+ // Constructors - declared private so construction is limited to
+ // our Singleton instance
+ IASIOThiscallResolver();
+ IASIOThiscallResolver(IASIO* that);
+public:
+
+ // Methods from the IUnknown interface. We don't fully implement IUnknown
+ // because the ASIO SDK never calls these methods through theAsioDriver ptr.
+ // These methods are implemented as assert(false).
+ virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv);
+ virtual ULONG STDMETHODCALLTYPE AddRef();
+ virtual ULONG STDMETHODCALLTYPE Release();
+
+ // Methods from the IASIO interface, implemented as forwarning calls to that.
+ virtual ASIOBool init(void *sysHandle);
+ virtual void getDriverName(char *name);
+ virtual long getDriverVersion();
+ virtual void getErrorMessage(char *string);
+ virtual ASIOError start();
+ virtual ASIOError stop();
+ virtual ASIOError getChannels(long *numInputChannels, long *numOutputChannels);
+ virtual ASIOError getLatencies(long *inputLatency, long *outputLatency);
+ virtual ASIOError getBufferSize(long *minSize, long *maxSize, long *preferredSize, long *granularity);
+ virtual ASIOError canSampleRate(ASIOSampleRate sampleRate);
+ virtual ASIOError getSampleRate(ASIOSampleRate *sampleRate);
+ virtual ASIOError setSampleRate(ASIOSampleRate sampleRate);
+ virtual ASIOError getClockSources(ASIOClockSource *clocks, long *numSources);
+ virtual ASIOError setClockSource(long reference);
+ virtual ASIOError getSamplePosition(ASIOSamples *sPos, ASIOTimeStamp *tStamp);
+ virtual ASIOError getChannelInfo(ASIOChannelInfo *info);
+ virtual ASIOError createBuffers(ASIOBufferInfo *bufferInfos, long numChannels, long bufferSize, ASIOCallbacks *callbacks);
+ virtual ASIOError disposeBuffers();
+ virtual ASIOError controlPanel();
+ virtual ASIOError future(long selector,void *opt);
+ virtual ASIOError outputReady();
+
+ // Class method, see ASIOInit() macro below.
+ static ASIOError ASIOInit(ASIODriverInfo *info); // Delegates to ::ASIOInit
+};
+
+
+// Replace calls to ASIOInit with our interposing version.
+// This macro enables us to perform thiscall resolution simply by #including
+// <iasiothiscallresolver.h> after the asio #includes (this file _must_ be
+// included _after_ the asio #includes)
+
+#define ASIOInit(name) IASIOThiscallResolver::ASIOInit((name))
+
+
+#endif /* !defined(_MSC_VER) */
+
+#endif /* Win32 */
+
+#endif /* included_iasiothiscallresolver_h */
+
+
diff --git a/pd/portaudio/src/hostapi/asio/pa_asio.cpp b/pd/portaudio/src/hostapi/asio/pa_asio.cpp
new file mode 100644
index 00000000..de7ced5c
--- /dev/null
+++ b/pd/portaudio/src/hostapi/asio/pa_asio.cpp
@@ -0,0 +1,3023 @@
+/*
+ * $Id: pa_asio.cpp,v 1.1 2007-08-18 23:49:33 millerpuckette Exp $
+ * Portable Audio I/O Library for ASIO Drivers
+ *
+ * Author: Stephane Letz
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 2000-2002 Stephane Letz, Phil Burk, Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/* Modification History
+
+ 08-03-01 First version : Stephane Letz
+ 08-06-01 Tweaks for PC, use C++, buffer allocation, Float32 to Int32 conversion : Phil Burk
+ 08-20-01 More conversion, PA_StreamTime, Pa_GetHostError : Stephane Letz
+ 08-21-01 PaUInt8 bug correction, implementation of ASIOSTFloat32LSB and ASIOSTFloat32MSB native formats : Stephane Letz
+ 08-24-01 MAX_INT32_FP hack, another Uint8 fix : Stephane and Phil
+ 08-27-01 Implementation of hostBufferSize < userBufferSize case, better management of the ouput buffer when
+ the stream is stopped : Stephane Letz
+ 08-28-01 Check the stream pointer for null in bufferSwitchTimeInfo, correct bug in bufferSwitchTimeInfo when
+ the stream is stopped : Stephane Letz
+ 10-12-01 Correct the PaHost_CalcNumHostBuffers function: computes FramesPerHostBuffer to be the lowest that
+ respect requested FramesPerUserBuffer and userBuffersPerHostBuffer : Stephane Letz
+ 10-26-01 Management of hostBufferSize and userBufferSize of any size : Stephane Letz
+ 10-27-01 Improve calculus of hostBufferSize to be multiple or divisor of userBufferSize if possible : Stephane and Phil
+ 10-29-01 Change MAX_INT32_FP to (2147483520.0f) to prevent roundup to 0x80000000 : Phil Burk
+ 10-31-01 Clear the ouput buffer and user buffers in PaHost_StartOutput, correct bug in GetFirstMultiple : Stephane Letz
+ 11-06-01 Rename functions : Stephane Letz
+ 11-08-01 New Pa_ASIO_Adaptor_Init function to init Callback adpatation variables, cleanup of Pa_ASIO_Callback_Input: Stephane Letz
+ 11-29-01 Break apart device loading to debug random failure in Pa_ASIO_QueryDeviceInfo ; Phil Burk
+ 01-03-02 Desallocate all resources in PaHost_Term for cases where Pa_CloseStream is not called properly : Stephane Letz
+ 02-01-02 Cleanup, test of multiple-stream opening : Stephane Letz
+ 19-02-02 New Pa_ASIO_loadDriver that calls CoInitialize on each thread on Windows : Stephane Letz
+ 09-04-02 Correct error code management in PaHost_Term, removes various compiler warning : Stephane Letz
+ 12-04-02 Add Mac includes for <Devices.h> and <Timer.h> : Phil Burk
+ 13-04-02 Removes another compiler warning : Stephane Letz
+ 30-04-02 Pa_ASIO_QueryDeviceInfo bug correction, memory allocation checking, better error handling : D Viens, P Burk, S Letz
+ 12-06-02 Rehashed into new multi-api infrastructure, added support for all ASIO sample formats : Ross Bencina
+ 18-06-02 Added pa_asio.h, PaAsio_GetAvailableLatencyValues() : Ross B.
+ 21-06-02 Added SelectHostBufferSize() which selects host buffer size based on user latency parameters : Ross Bencina
+ ** NOTE maintanance history is now stored in CVS **
+*/
+
+/** @file
+ @ingroup hostapi_src
+
+ Note that specific support for paInputUnderflow, paOutputOverflow and
+ paNeverDropInput is not necessary or possible with this driver due to the
+ synchronous full duplex double-buffered architecture of ASIO.
+
+ @todo check that CoInitialize()/CoUninitialize() are always correctly
+ paired, even in error cases.
+
+ @todo implement host api specific extension to set i/o buffer sizes in frames
+
+ @todo implement ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable
+
+ @todo implement IsFormatSupported
+
+ @todo work out how to implement stream stoppage from callback and
+ implement IsStreamActive properly. Stream stoppage could be implemented
+ using a high-priority thread blocked on an Event which is signalled
+ by the callback. Or, we could just call ASIO stop from the callback
+ and see what happens.
+
+ @todo rigorously check asio return codes and convert to pa error codes
+
+ @todo Different channels of a multichannel stream can have different sample
+ formats, but we assume that all are the same as the first channel for now.
+ Fixing this will require the block processor to maintain per-channel
+ conversion functions - could get nasty.
+
+ @todo investigate whether the asio processNow flag needs to be honoured
+
+ @todo handle asioMessages() callbacks in a useful way, or at least document
+ what cases we don't handle.
+
+ @todo miscellaneous other FIXMEs
+
+ @todo provide an asio-specific method for setting the systems specific
+ value (aka main window handle) - check that this matches the value
+ passed to PaAsio_ShowControlPanel, or remove it entirely from
+ PaAsio_ShowControlPanel. - this would allow PaAsio_ShowControlPanel
+ to be called for the currently open stream (at present all streams
+ must be closed).
+*/
+
+
+
+#include <stdio.h>
+#include <assert.h>
+#include <string.h>
+//#include <values.h>
+
+#include <windows.h>
+#include <mmsystem.h>
+
+#include "portaudio.h"
+#include "pa_asio.h"
+#include "pa_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "pa_debugprint.h"
+
+/* This version of pa_asio.cpp is currently only targetted at Win32,
+ It would require a few tweaks to work with pre-OS X Macintosh.
+ To make configuration easier, we define WIN32 here to make sure
+ that the ASIO SDK knows this is Win32.
+*/
+#ifndef WIN32
+#define WIN32
+#endif
+
+#include "asiosys.h"
+#include "asio.h"
+#include "asiodrivers.h"
+#include "iasiothiscallresolver.h"
+
+/*
+#if MAC
+#include <Devices.h>
+#include <Timer.h>
+#include <Math64.h>
+#else
+*/
+/*
+#include <math.h>
+#include <windows.h>
+#include <mmsystem.h>
+*/
+/*
+#endif
+*/
+
+/* external references */
+extern AsioDrivers* asioDrivers ;
+bool loadAsioDriver(char *name);
+
+
+/* We are trying to be compatible with CARBON but this has not been thoroughly tested. */
+/* not tested at all since new code was introduced. */
+#define CARBON_COMPATIBLE (0)
+
+
+
+
+/* prototypes for functions declared in this file */
+
+extern "C" PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex );
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+ PaStream** s,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate,
+ unsigned long framesPerBuffer,
+ PaStreamFlags streamFlags,
+ PaStreamCallback *streamCallback,
+ void *userData );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+static signed long GetStreamReadAvailable( PaStream* stream );
+static signed long GetStreamWriteAvailable( PaStream* stream );
+
+/* our ASIO callback functions */
+
+static void bufferSwitch(long index, ASIOBool processNow);
+static ASIOTime *bufferSwitchTimeInfo(ASIOTime *timeInfo, long index, ASIOBool processNow);
+static void sampleRateChanged(ASIOSampleRate sRate);
+static long asioMessages(long selector, long value, void* message, double* opt);
+
+static ASIOCallbacks asioCallbacks_ =
+ { bufferSwitch, sampleRateChanged, asioMessages, bufferSwitchTimeInfo };
+
+
+#define PA_ASIO_SET_LAST_HOST_ERROR( errorCode, errorText ) \
+ PaUtil_SetLastHostErrorInfo( paASIO, errorCode, errorText )
+
+
+static void PaAsio_SetLastSystemError( DWORD errorCode )
+{
+ LPVOID lpMsgBuf;
+ FormatMessage(
+ FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
+ NULL,
+ errorCode,
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPTSTR) &lpMsgBuf,
+ 0,
+ NULL
+ );
+ PaUtil_SetLastHostErrorInfo( paASIO, errorCode, (const char*)lpMsgBuf );
+ LocalFree( lpMsgBuf );
+}
+
+#define PA_ASIO_SET_LAST_SYSTEM_ERROR( errorCode ) \
+ PaAsio_SetLastSystemError( errorCode )
+
+
+static const char* PaAsio_GetAsioErrorText( ASIOError asioError )
+{
+ const char *result;
+
+ switch( asioError ){
+ case ASE_OK:
+ case ASE_SUCCESS: result = "Success"; break;
+ case ASE_NotPresent: result = "Hardware input or output is not present or available"; break;
+ case ASE_HWMalfunction: result = "Hardware is malfunctioning"; break;
+ case ASE_InvalidParameter: result = "Input parameter invalid"; break;
+ case ASE_InvalidMode: result = "Hardware is in a bad mode or used in a bad mode"; break;
+ case ASE_SPNotAdvancing: result = "Hardware is not running when sample position is inquired"; break;
+ case ASE_NoClock: result = "Sample clock or rate cannot be determined or is not present"; break;
+ case ASE_NoMemory: result = "Not enough memory for completing the request"; break;
+ default: result = "Unknown ASIO error"; break;
+ }
+
+ return result;
+}
+
+
+#define PA_ASIO_SET_LAST_ASIO_ERROR( asioError ) \
+ PaUtil_SetLastHostErrorInfo( paASIO, asioError, PaAsio_GetAsioErrorText( asioError ) )
+
+
+
+
+// Atomic increment and decrement operations
+#if MAC
+ /* need to be implemented on Mac */
+ inline long PaAsio_AtomicIncrement(volatile long* v) {return ++(*const_cast<long*>(v));}
+ inline long PaAsio_AtomicDecrement(volatile long* v) {return --(*const_cast<long*>(v));}
+#elif WINDOWS
+ inline long PaAsio_AtomicIncrement(volatile long* v) {return InterlockedIncrement(const_cast<long*>(v));}
+ inline long PaAsio_AtomicDecrement(volatile long* v) {return InterlockedDecrement(const_cast<long*>(v));}
+#endif
+
+
+
+typedef struct PaAsioDriverInfo
+{
+ ASIODriverInfo asioDriverInfo;
+ long inputChannelCount, outputChannelCount;
+ long bufferMinSize, bufferMaxSize, bufferPreferredSize, bufferGranularity;
+ bool postOutput;
+}
+PaAsioDriverInfo;
+
+
+/* PaAsioHostApiRepresentation - host api datastructure specific to this implementation */
+
+typedef struct
+{
+ PaUtilHostApiRepresentation inheritedHostApiRep;
+ PaUtilStreamInterface callbackStreamInterface;
+ PaUtilStreamInterface blockingStreamInterface;
+
+ PaUtilAllocationGroup *allocations;
+
+ void *systemSpecific;
+
+ /* the ASIO C API only allows one ASIO driver to be open at a time,
+ so we keep track of whether we have the driver open here, and
+ use this information to return errors from OpenStream if the
+ driver is already open.
+
+ openAsioDeviceIndex will be PaNoDevice if there is no device open
+ and a valid pa_asio (not global) device index otherwise.
+
+ openAsioDriverInfo is populated with the driver info for the
+ currently open device (if any)
+ */
+ PaDeviceIndex openAsioDeviceIndex;
+ PaAsioDriverInfo openAsioDriverInfo;
+}
+PaAsioHostApiRepresentation;
+
+
+/*
+ Retrieve <driverCount> driver names from ASIO, returned in a char**
+ allocated in <group>.
+*/
+static char **GetAsioDriverNames( PaUtilAllocationGroup *group, long driverCount )
+{
+ char **result = 0;
+ int i;
+
+ result =(char**)PaUtil_GroupAllocateMemory(
+ group, sizeof(char*) * driverCount );
+ if( !result )
+ goto error;
+
+ result[0] = (char*)PaUtil_GroupAllocateMemory(
+ group, 32 * driverCount );
+ if( !result[0] )
+ goto error;
+
+ for( i=0; i<driverCount; ++i )
+ result[i] = result[0] + (32 * i);
+
+ asioDrivers->getDriverNames( result, driverCount );
+
+error:
+ return result;
+}
+
+
+static PaSampleFormat AsioSampleTypeToPaNativeSampleFormat(ASIOSampleType type)
+{
+ switch (type) {
+ case ASIOSTInt16MSB:
+ case ASIOSTInt16LSB:
+ return paInt16;
+
+ case ASIOSTFloat32MSB:
+ case ASIOSTFloat32LSB:
+ case ASIOSTFloat64MSB:
+ case ASIOSTFloat64LSB:
+ return paFloat32;
+
+ case ASIOSTInt32MSB:
+ case ASIOSTInt32LSB:
+ case ASIOSTInt32MSB16:
+ case ASIOSTInt32LSB16:
+ case ASIOSTInt32MSB18:
+ case ASIOSTInt32MSB20:
+ case ASIOSTInt32MSB24:
+ case ASIOSTInt32LSB18:
+ case ASIOSTInt32LSB20:
+ case ASIOSTInt32LSB24:
+ return paInt32;
+
+ case ASIOSTInt24MSB:
+ case ASIOSTInt24LSB:
+ return paInt24;
+
+ default:
+ return paCustomFormat;
+ }
+}
+
+void AsioSampleTypeLOG(ASIOSampleType type)
+{
+ switch (type) {
+ case ASIOSTInt16MSB: PA_DEBUG(("ASIOSTInt16MSB\n")); break;
+ case ASIOSTInt16LSB: PA_DEBUG(("ASIOSTInt16LSB\n")); break;
+ case ASIOSTFloat32MSB:PA_DEBUG(("ASIOSTFloat32MSB\n"));break;
+ case ASIOSTFloat32LSB:PA_DEBUG(("ASIOSTFloat32LSB\n"));break;
+ case ASIOSTFloat64MSB:PA_DEBUG(("ASIOSTFloat64MSB\n"));break;
+ case ASIOSTFloat64LSB:PA_DEBUG(("ASIOSTFloat64LSB\n"));break;
+ case ASIOSTInt32MSB: PA_DEBUG(("ASIOSTInt32MSB\n")); break;
+ case ASIOSTInt32LSB: PA_DEBUG(("ASIOSTInt32LSB\n")); break;
+ case ASIOSTInt32MSB16:PA_DEBUG(("ASIOSTInt32MSB16\n"));break;
+ case ASIOSTInt32LSB16:PA_DEBUG(("ASIOSTInt32LSB16\n"));break;
+ case ASIOSTInt32MSB18:PA_DEBUG(("ASIOSTInt32MSB18\n"));break;
+ case ASIOSTInt32MSB20:PA_DEBUG(("ASIOSTInt32MSB20\n"));break;
+ case ASIOSTInt32MSB24:PA_DEBUG(("ASIOSTInt32MSB24\n"));break;
+ case ASIOSTInt32LSB18:PA_DEBUG(("ASIOSTInt32LSB18\n"));break;
+ case ASIOSTInt32LSB20:PA_DEBUG(("ASIOSTInt32LSB20\n"));break;
+ case ASIOSTInt32LSB24:PA_DEBUG(("ASIOSTInt32LSB24\n"));break;
+ case ASIOSTInt24MSB: PA_DEBUG(("ASIOSTInt24MSB\n")); break;
+ case ASIOSTInt24LSB: PA_DEBUG(("ASIOSTInt24LSB\n")); break;
+ default: PA_DEBUG(("Custom Format%d\n",type));break;
+
+ }
+}
+
+static int BytesPerAsioSample( ASIOSampleType sampleType )
+{
+ switch (sampleType) {
+ case ASIOSTInt16MSB:
+ case ASIOSTInt16LSB:
+ return 2;
+
+ case ASIOSTFloat64MSB:
+ case ASIOSTFloat64LSB:
+ return 8;
+
+ case ASIOSTFloat32MSB:
+ case ASIOSTFloat32LSB:
+ case ASIOSTInt32MSB:
+ case ASIOSTInt32LSB:
+ case ASIOSTInt32MSB16:
+ case ASIOSTInt32LSB16:
+ case ASIOSTInt32MSB18:
+ case ASIOSTInt32MSB20:
+ case ASIOSTInt32MSB24:
+ case ASIOSTInt32LSB18:
+ case ASIOSTInt32LSB20:
+ case ASIOSTInt32LSB24:
+ return 4;
+
+ case ASIOSTInt24MSB:
+ case ASIOSTInt24LSB:
+ return 3;
+
+ default:
+ return 0;
+ }
+}
+
+
+static void Swap16( void *buffer, long shift, long count )
+{
+ unsigned short *p = (unsigned short*)buffer;
+ unsigned short temp;
+ (void) shift; /* unused parameter */
+
+ while( count-- )
+ {
+ temp = *p;
+ *p++ = (unsigned short)((temp<<8) | (temp>>8));
+ }
+}
+
+static void Swap24( void *buffer, long shift, long count )
+{
+ unsigned char *p = (unsigned char*)buffer;
+ unsigned char temp;
+ (void) shift; /* unused parameter */
+
+ while( count-- )
+ {
+ temp = *p;
+ *p = *(p+2);
+ *(p+2) = temp;
+ p += 3;
+ }
+}
+
+#define PA_SWAP32_( x ) ((x>>24) | ((x>>8)&0xFF00) | ((x<<8)&0xFF0000) | (x<<24));
+
+static void Swap32( void *buffer, long shift, long count )
+{
+ unsigned long *p = (unsigned long*)buffer;
+ unsigned long temp;
+ (void) shift; /* unused parameter */
+
+ while( count-- )
+ {
+ temp = *p;
+ *p++ = PA_SWAP32_( temp);
+ }
+}
+
+static void SwapShiftLeft32( void *buffer, long shift, long count )
+{
+ unsigned long *p = (unsigned long*)buffer;
+ unsigned long temp;
+
+ while( count-- )
+ {
+ temp = *p;
+ temp = PA_SWAP32_( temp);
+ *p++ = temp << shift;
+ }
+}
+
+static void ShiftRightSwap32( void *buffer, long shift, long count )
+{
+ unsigned long *p = (unsigned long*)buffer;
+ unsigned long temp;
+
+ while( count-- )
+ {
+ temp = *p >> shift;
+ *p++ = PA_SWAP32_( temp);
+ }
+}
+
+static void ShiftLeft32( void *buffer, long shift, long count )
+{
+ unsigned long *p = (unsigned long*)buffer;
+ unsigned long temp;
+
+ while( count-- )
+ {
+ temp = *p;
+ *p++ = temp << shift;
+ }
+}
+
+static void ShiftRight32( void *buffer, long shift, long count )
+{
+ unsigned long *p = (unsigned long*)buffer;
+ unsigned long temp;
+
+ while( count-- )
+ {
+ temp = *p;
+ *p++ = temp >> shift;
+ }
+}
+
+#define PA_SWAP_( x, y ) temp=x; x = y; y = temp;
+
+static void Swap64ConvertFloat64ToFloat32( void *buffer, long shift, long count )
+{
+ double *in = (double*)buffer;
+ float *out = (float*)buffer;
+ unsigned char *p;
+ unsigned char temp;
+ (void) shift; /* unused parameter */
+
+ while( count-- )
+ {
+ p = (unsigned char*)in;
+ PA_SWAP_( p[0], p[7] );
+ PA_SWAP_( p[1], p[6] );
+ PA_SWAP_( p[2], p[5] );
+ PA_SWAP_( p[3], p[4] );
+
+ *out++ = (float) (*in++);
+ }
+}
+
+static void ConvertFloat64ToFloat32( void *buffer, long shift, long count )
+{
+ double *in = (double*)buffer;
+ float *out = (float*)buffer;
+ (void) shift; /* unused parameter */
+
+ while( count-- )
+ *out++ = (float) (*in++);
+}
+
+static void ConvertFloat32ToFloat64Swap64( void *buffer, long shift, long count )
+{
+ float *in = ((float*)buffer) + (count-1);
+ double *out = ((double*)buffer) + (count-1);
+ unsigned char *p;
+ unsigned char temp;
+ (void) shift; /* unused parameter */
+
+ while( count-- )
+ {
+ *out = *in--;
+
+ p = (unsigned char*)out;
+ PA_SWAP_( p[0], p[7] );
+ PA_SWAP_( p[1], p[6] );
+ PA_SWAP_( p[2], p[5] );
+ PA_SWAP_( p[3], p[4] );
+
+ out--;
+ }
+}
+
+static void ConvertFloat32ToFloat64( void *buffer, long shift, long count )
+{
+ float *in = ((float*)buffer) + (count-1);
+ double *out = ((double*)buffer) + (count-1);
+ (void) shift; /* unused parameter */
+
+ while( count-- )
+ *out-- = *in--;
+}
+
+#ifdef MAC
+#define PA_MSB_IS_NATIVE_
+#undef PA_LSB_IS_NATIVE_
+#endif
+
+#ifdef WINDOWS
+#undef PA_MSB_IS_NATIVE_
+#define PA_LSB_IS_NATIVE_
+#endif
+
+typedef void PaAsioBufferConverter( void *, long, long );
+
+static void SelectAsioToPaConverter( ASIOSampleType type, PaAsioBufferConverter **converter, long *shift )
+{
+ *shift = 0;
+ *converter = 0;
+
+ switch (type) {
+ case ASIOSTInt16MSB:
+ /* dest: paInt16, no conversion necessary, possible byte swap*/
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = Swap16;
+ #endif
+ break;
+ case ASIOSTInt16LSB:
+ /* dest: paInt16, no conversion necessary, possible byte swap*/
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = Swap16;
+ #endif
+ break;
+ case ASIOSTFloat32MSB:
+ /* dest: paFloat32, no conversion necessary, possible byte swap*/
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = Swap32;
+ #endif
+ break;
+ case ASIOSTFloat32LSB:
+ /* dest: paFloat32, no conversion necessary, possible byte swap*/
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = Swap32;
+ #endif
+ break;
+ case ASIOSTFloat64MSB:
+ /* dest: paFloat32, in-place conversion to/from float32, possible byte swap*/
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = Swap64ConvertFloat64ToFloat32;
+ #else
+ *converter = ConvertFloat64ToFloat32;
+ #endif
+ break;
+ case ASIOSTFloat64LSB:
+ /* dest: paFloat32, in-place conversion to/from float32, possible byte swap*/
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = Swap64ConvertFloat64ToFloat32;
+ #else
+ *converter = ConvertFloat64ToFloat32;
+ #endif
+ break;
+ case ASIOSTInt32MSB:
+ /* dest: paInt32, no conversion necessary, possible byte swap */
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = Swap32;
+ #endif
+ break;
+ case ASIOSTInt32LSB:
+ /* dest: paInt32, no conversion necessary, possible byte swap */
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = Swap32;
+ #endif
+ break;
+ case ASIOSTInt32MSB16:
+ /* dest: paInt32, 16 bit shift, possible byte swap */
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = SwapShiftLeft32;
+ #else
+ *converter = ShiftLeft32;
+ #endif
+ *shift = 16;
+ break;
+ case ASIOSTInt32MSB18:
+ /* dest: paInt32, 14 bit shift, possible byte swap */
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = SwapShiftLeft32;
+ #else
+ *converter = ShiftLeft32;
+ #endif
+ *shift = 14;
+ break;
+ case ASIOSTInt32MSB20:
+ /* dest: paInt32, 12 bit shift, possible byte swap */
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = SwapShiftLeft32;
+ #else
+ *converter = ShiftLeft32;
+ #endif
+ *shift = 12;
+ break;
+ case ASIOSTInt32MSB24:
+ /* dest: paInt32, 8 bit shift, possible byte swap */
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = SwapShiftLeft32;
+ #else
+ *converter = ShiftLeft32;
+ #endif
+ *shift = 8;
+ break;
+ case ASIOSTInt32LSB16:
+ /* dest: paInt32, 16 bit shift, possible byte swap */
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = SwapShiftLeft32;
+ #else
+ *converter = ShiftLeft32;
+ #endif
+ *shift = 16;
+ break;
+ case ASIOSTInt32LSB18:
+ /* dest: paInt32, 14 bit shift, possible byte swap */
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = SwapShiftLeft32;
+ #else
+ *converter = ShiftLeft32;
+ #endif
+ *shift = 14;
+ break;
+ case ASIOSTInt32LSB20:
+ /* dest: paInt32, 12 bit shift, possible byte swap */
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = SwapShiftLeft32;
+ #else
+ *converter = ShiftLeft32;
+ #endif
+ *shift = 12;
+ break;
+ case ASIOSTInt32LSB24:
+ /* dest: paInt32, 8 bit shift, possible byte swap */
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = SwapShiftLeft32;
+ #else
+ *converter = ShiftLeft32;
+ #endif
+ *shift = 8;
+ break;
+ case ASIOSTInt24MSB:
+ /* dest: paInt24, no conversion necessary, possible byte swap */
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = Swap24;
+ #endif
+ break;
+ case ASIOSTInt24LSB:
+ /* dest: paInt24, no conversion necessary, possible byte swap */
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = Swap24;
+ #endif
+ break;
+ }
+}
+
+
+static void SelectPaToAsioConverter( ASIOSampleType type, PaAsioBufferConverter **converter, long *shift )
+{
+ *shift = 0;
+ *converter = 0;
+
+ switch (type) {
+ case ASIOSTInt16MSB:
+ /* src: paInt16, no conversion necessary, possible byte swap*/
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = Swap16;
+ #endif
+ break;
+ case ASIOSTInt16LSB:
+ /* src: paInt16, no conversion necessary, possible byte swap*/
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = Swap16;
+ #endif
+ break;
+ case ASIOSTFloat32MSB:
+ /* src: paFloat32, no conversion necessary, possible byte swap*/
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = Swap32;
+ #endif
+ break;
+ case ASIOSTFloat32LSB:
+ /* src: paFloat32, no conversion necessary, possible byte swap*/
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = Swap32;
+ #endif
+ break;
+ case ASIOSTFloat64MSB:
+ /* src: paFloat32, in-place conversion to/from float32, possible byte swap*/
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = ConvertFloat32ToFloat64Swap64;
+ #else
+ *converter = ConvertFloat32ToFloat64;
+ #endif
+ break;
+ case ASIOSTFloat64LSB:
+ /* src: paFloat32, in-place conversion to/from float32, possible byte swap*/
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = ConvertFloat32ToFloat64Swap64;
+ #else
+ *converter = ConvertFloat32ToFloat64;
+ #endif
+ break;
+ case ASIOSTInt32MSB:
+ /* src: paInt32, no conversion necessary, possible byte swap */
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = Swap32;
+ #endif
+ break;
+ case ASIOSTInt32LSB:
+ /* src: paInt32, no conversion necessary, possible byte swap */
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = Swap32;
+ #endif
+ break;
+ case ASIOSTInt32MSB16:
+ /* src: paInt32, 16 bit shift, possible byte swap */
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = ShiftRightSwap32;
+ #else
+ *converter = ShiftRight32;
+ #endif
+ *shift = 16;
+ break;
+ case ASIOSTInt32MSB18:
+ /* src: paInt32, 14 bit shift, possible byte swap */
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = ShiftRightSwap32;
+ #else
+ *converter = ShiftRight32;
+ #endif
+ *shift = 14;
+ break;
+ case ASIOSTInt32MSB20:
+ /* src: paInt32, 12 bit shift, possible byte swap */
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = ShiftRightSwap32;
+ #else
+ *converter = ShiftRight32;
+ #endif
+ *shift = 12;
+ break;
+ case ASIOSTInt32MSB24:
+ /* src: paInt32, 8 bit shift, possible byte swap */
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = ShiftRightSwap32;
+ #else
+ *converter = ShiftRight32;
+ #endif
+ *shift = 8;
+ break;
+ case ASIOSTInt32LSB16:
+ /* src: paInt32, 16 bit shift, possible byte swap */
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = ShiftRightSwap32;
+ #else
+ *converter = ShiftRight32;
+ #endif
+ *shift = 16;
+ break;
+ case ASIOSTInt32LSB18:
+ /* src: paInt32, 14 bit shift, possible byte swap */
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = ShiftRightSwap32;
+ #else
+ *converter = ShiftRight32;
+ #endif
+ *shift = 14;
+ break;
+ case ASIOSTInt32LSB20:
+ /* src: paInt32, 12 bit shift, possible byte swap */
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = ShiftRightSwap32;
+ #else
+ *converter = ShiftRight32;
+ #endif
+ *shift = 12;
+ break;
+ case ASIOSTInt32LSB24:
+ /* src: paInt32, 8 bit shift, possible byte swap */
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = ShiftRightSwap32;
+ #else
+ *converter = ShiftRight32;
+ #endif
+ *shift = 8;
+ break;
+ case ASIOSTInt24MSB:
+ /* src: paInt24, no conversion necessary, possible byte swap */
+ #ifdef PA_LSB_IS_NATIVE_
+ *converter = Swap24;
+ #endif
+ break;
+ case ASIOSTInt24LSB:
+ /* src: paInt24, no conversion necessary, possible byte swap */
+ #ifdef PA_MSB_IS_NATIVE_
+ *converter = Swap24;
+ #endif
+ break;
+ }
+}
+
+
+typedef struct PaAsioDeviceInfo
+{
+ PaDeviceInfo commonDeviceInfo;
+ long minBufferSize;
+ long maxBufferSize;
+ long preferredBufferSize;
+ long bufferGranularity;
+
+ ASIOChannelInfo *asioChannelInfos;
+}
+PaAsioDeviceInfo;
+
+
+PaError PaAsio_GetAvailableLatencyValues( PaDeviceIndex device,
+ long *minLatency, long *maxLatency, long *preferredLatency, long *granularity )
+{
+ PaError result;
+ PaUtilHostApiRepresentation *hostApi;
+ PaDeviceIndex hostApiDevice;
+
+ result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
+
+ if( result == paNoError )
+ {
+ result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi );
+
+ if( result == paNoError )
+ {
+ PaAsioDeviceInfo *asioDeviceInfo =
+ (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice];
+
+ *minLatency = asioDeviceInfo->minBufferSize;
+ *maxLatency = asioDeviceInfo->maxBufferSize;
+ *preferredLatency = asioDeviceInfo->preferredBufferSize;
+ *granularity = asioDeviceInfo->bufferGranularity;
+ }
+ }
+
+ return result;
+}
+
+
+
+/*
+ load the asio driver named by <driverName> and return statistics about
+ the driver in info. If no error occurred, the driver will remain open
+ and must be closed by the called by calling ASIOExit() - if an error
+ is returned the driver will already be closed.
+*/
+static PaError LoadAsioDriver( const char *driverName,
+ PaAsioDriverInfo *driverInfo, void *systemSpecific )
+{
+ PaError result = paNoError;
+ ASIOError asioError;
+ int asioIsInitialized = 0;
+
+ if( !loadAsioDriver( const_cast<char*>(driverName) ) )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_HOST_ERROR( 0, "Failed to load ASIO driver" );
+ goto error;
+ }
+
+ memset( &driverInfo->asioDriverInfo, 0, sizeof(ASIODriverInfo) );
+ driverInfo->asioDriverInfo.asioVersion = 2;
+ driverInfo->asioDriverInfo.sysRef = systemSpecific;
+ if( (asioError = ASIOInit( &driverInfo->asioDriverInfo )) != ASE_OK )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+ goto error;
+ }
+ else
+ {
+ asioIsInitialized = 1;
+ }
+
+ if( (asioError = ASIOGetChannels(&driverInfo->inputChannelCount,
+ &driverInfo->outputChannelCount)) != ASE_OK )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+ goto error;
+ }
+
+ if( (asioError = ASIOGetBufferSize(&driverInfo->bufferMinSize,
+ &driverInfo->bufferMaxSize, &driverInfo->bufferPreferredSize,
+ &driverInfo->bufferGranularity)) != ASE_OK )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+ goto error;
+ }
+
+ if( ASIOOutputReady() == ASE_OK )
+ driverInfo->postOutput = true;
+ else
+ driverInfo->postOutput = false;
+
+ return result;
+
+error:
+ if( asioIsInitialized )
+ ASIOExit();
+
+ return result;
+}
+
+
+#define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_ 13 /* must be the same number of elements as in the array below */
+static ASIOSampleRate defaultSampleRateSearchOrder_[]
+ = {44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0,
+ 192000.0, 16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };
+
+
+/* we look up IsDebuggerPresent at runtime incase it isn't present (on Win95 for example) */
+typedef BOOL (WINAPI *IsDebuggerPresentPtr)(VOID);
+IsDebuggerPresentPtr IsDebuggerPresent_ = 0;
+//FARPROC IsDebuggerPresent_ = 0; // this is the current way to do it apparently according to davidv
+
+PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+ PaError result = paNoError;
+ int i, driverCount;
+ PaAsioHostApiRepresentation *asioHostApi;
+ PaAsioDeviceInfo *deviceInfoArray;
+ char **names;
+ PaAsioDriverInfo paAsioDriverInfo;
+
+ asioHostApi = (PaAsioHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaAsioHostApiRepresentation) );
+ if( !asioHostApi )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ asioHostApi->allocations = PaUtil_CreateAllocationGroup();
+ if( !asioHostApi->allocations )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ asioHostApi->systemSpecific = 0;
+ asioHostApi->openAsioDeviceIndex = paNoDevice;
+
+ *hostApi = &asioHostApi->inheritedHostApiRep;
+ (*hostApi)->info.structVersion = 1;
+
+ (*hostApi)->info.type = paASIO;
+ (*hostApi)->info.name = "ASIO";
+ (*hostApi)->info.deviceCount = 0;
+
+ #ifdef WINDOWS
+ /* use desktop window as system specific ptr */
+ asioHostApi->systemSpecific = GetDesktopWindow();
+ CoInitialize(NULL);
+ #endif
+
+ /* MUST BE CHECKED : to force fragments loading on Mac */
+ loadAsioDriver( "dummy" );
+
+ /* driverCount is the number of installed drivers - not necessarily
+ the number of installed physical devices. */
+ #if MAC
+ driverCount = asioDrivers->getNumFragments();
+ #elif WINDOWS
+ driverCount = asioDrivers->asioGetNumDev();
+ #endif
+
+ if( driverCount > 0 )
+ {
+ names = GetAsioDriverNames( asioHostApi->allocations, driverCount );
+ if( !names )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+
+ /* allocate enough space for all drivers, even if some aren't installed */
+
+ (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+ asioHostApi->allocations, sizeof(PaDeviceInfo*) * driverCount );
+ if( !(*hostApi)->deviceInfos )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ /* allocate all device info structs in a contiguous block */
+ deviceInfoArray = (PaAsioDeviceInfo*)PaUtil_GroupAllocateMemory(
+ asioHostApi->allocations, sizeof(PaAsioDeviceInfo) * driverCount );
+ if( !deviceInfoArray )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ IsDebuggerPresent_ = GetProcAddress( LoadLibrary( "Kernel32.dll" ), "IsDebuggerPresent" );
+
+ for( i=0; i < driverCount; ++i )
+ {
+
+ PA_DEBUG(("ASIO names[%d]:%s\n",i,names[i]));
+
+ // Since portaudio opens ALL ASIO drivers, and no one else does that,
+ // we face fact that some drivers were not meant for it, drivers which act
+ // like shells on top of REAL drivers, for instance.
+ // so we get duplicate handles, locks and other problems.
+ // so lets NOT try to load any such wrappers.
+ // The ones i [davidv] know of so far are:
+
+ if ( strcmp (names[i],"ASIO DirectX Full Duplex Driver") == 0
+ || strcmp (names[i],"ASIO Multimedia Driver") == 0
+ || strncmp(names[i],"Premiere",8) == 0 //"Premiere Elements Windows Sound 1.0"
+ || strncmp(names[i],"Adobe",5) == 0 //"Adobe Default Windows Sound 1.5"
+ || strncmp(names[i],"ReaRoute ASIO",13) == 0 //Reaper www.reaper.fm <- fix your stuff man.
+ )
+ {
+ PA_DEBUG(("BLACKLISTED!!!\n"));
+ continue;
+ }
+
+
+ if( IsDebuggerPresent_ && IsDebuggerPresent_() )
+ {
+ /* ASIO Digidesign Driver uses PACE copy protection which quits out
+ if a debugger is running. So we don't load it if a debugger is running. */
+ if( strcmp(names[i], "ASIO Digidesign Driver") == 0 )
+ {
+ PA_DEBUG(("BLACKLISTED!!! ASIO Digidesign Driver would quit the debugger\n"));
+ continue;
+ }
+ }
+
+
+ /* Attempt to load the asio driver... */
+ if( LoadAsioDriver( names[i], &paAsioDriverInfo, asioHostApi->systemSpecific ) == paNoError )
+ {
+ PaAsioDeviceInfo *asioDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];
+ PaDeviceInfo *deviceInfo = &asioDeviceInfo->commonDeviceInfo;
+
+ deviceInfo->structVersion = 2;
+ deviceInfo->hostApi = hostApiIndex;
+
+ deviceInfo->name = names[i];
+ PA_DEBUG(("PaAsio_Initialize: drv:%d name = %s\n", i,deviceInfo->name));
+ PA_DEBUG(("PaAsio_Initialize: drv:%d inputChannels = %d\n", i, paAsioDriverInfo.inputChannelCount));
+ PA_DEBUG(("PaAsio_Initialize: drv:%d outputChannels = %d\n", i, paAsioDriverInfo.outputChannelCount));
+ PA_DEBUG(("PaAsio_Initialize: drv:%d bufferMinSize = %d\n", i, paAsioDriverInfo.bufferMinSize));
+ PA_DEBUG(("PaAsio_Initialize: drv:%d bufferMaxSize = %d\n", i, paAsioDriverInfo.bufferMaxSize));
+ PA_DEBUG(("PaAsio_Initialize: drv:%d bufferPreferredSize = %d\n", i, paAsioDriverInfo.bufferPreferredSize));
+ PA_DEBUG(("PaAsio_Initialize: drv:%d bufferGranularity = %d\n", i, paAsioDriverInfo.bufferGranularity));
+
+ deviceInfo->maxInputChannels = paAsioDriverInfo.inputChannelCount;
+ deviceInfo->maxOutputChannels = paAsioDriverInfo.outputChannelCount;
+
+ deviceInfo->defaultSampleRate = 0.;
+ bool foundDefaultSampleRate = false;
+ for( int j=0; j < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++j )
+ {
+ ASIOError asioError = ASIOCanSampleRate( defaultSampleRateSearchOrder_[j] );
+ if( asioError != ASE_NoClock && asioError != ASE_NotPresent )
+ {
+ deviceInfo->defaultSampleRate = defaultSampleRateSearchOrder_[j];
+ foundDefaultSampleRate = true;
+ break;
+ }
+ }
+
+ PA_DEBUG(("PaAsio_Initialize: drv:%d defaultSampleRate = %f\n", i, deviceInfo->defaultSampleRate));
+
+ if( foundDefaultSampleRate ){
+
+ /* calculate default latency values from bufferPreferredSize
+ for default low latency, and bufferPreferredSize * 3
+ for default high latency.
+ use the default sample rate to convert from samples to
+ seconds. Without knowing what sample rate the user will
+ use this is the best we can do.
+ */
+
+ double defaultLowLatency =
+ paAsioDriverInfo.bufferPreferredSize / deviceInfo->defaultSampleRate;
+
+ deviceInfo->defaultLowInputLatency = defaultLowLatency;
+ deviceInfo->defaultLowOutputLatency = defaultLowLatency;
+
+ long defaultHighLatencyBufferSize =
+ paAsioDriverInfo.bufferPreferredSize * 3;
+
+ if( defaultHighLatencyBufferSize > paAsioDriverInfo.bufferMaxSize )
+ defaultHighLatencyBufferSize = paAsioDriverInfo.bufferMaxSize;
+
+ double defaultHighLatency =
+ defaultHighLatencyBufferSize / deviceInfo->defaultSampleRate;
+
+ if( defaultHighLatency < defaultLowLatency )
+ defaultHighLatency = defaultLowLatency; /* just incase the driver returns something strange */
+
+ deviceInfo->defaultHighInputLatency = defaultHighLatency;
+ deviceInfo->defaultHighOutputLatency = defaultHighLatency;
+
+ }else{
+
+ deviceInfo->defaultLowInputLatency = 0.;
+ deviceInfo->defaultLowOutputLatency = 0.;
+ deviceInfo->defaultHighInputLatency = 0.;
+ deviceInfo->defaultHighOutputLatency = 0.;
+ }
+
+ PA_DEBUG(("PaAsio_Initialize: drv:%d defaultLowInputLatency = %f\n", i, deviceInfo->defaultLowInputLatency));
+ PA_DEBUG(("PaAsio_Initialize: drv:%d defaultLowOutputLatency = %f\n", i, deviceInfo->defaultLowOutputLatency));
+ PA_DEBUG(("PaAsio_Initialize: drv:%d defaultHighInputLatency = %f\n", i, deviceInfo->defaultHighInputLatency));
+ PA_DEBUG(("PaAsio_Initialize: drv:%d defaultHighOutputLatency = %f\n", i, deviceInfo->defaultHighOutputLatency));
+
+ asioDeviceInfo->minBufferSize = paAsioDriverInfo.bufferMinSize;
+ asioDeviceInfo->maxBufferSize = paAsioDriverInfo.bufferMaxSize;
+ asioDeviceInfo->preferredBufferSize = paAsioDriverInfo.bufferPreferredSize;
+ asioDeviceInfo->bufferGranularity = paAsioDriverInfo.bufferGranularity;
+
+
+ asioDeviceInfo->asioChannelInfos = (ASIOChannelInfo*)PaUtil_GroupAllocateMemory(
+ asioHostApi->allocations,
+ sizeof(ASIOChannelInfo) * (deviceInfo->maxInputChannels
+ + deviceInfo->maxOutputChannels) );
+ if( !asioDeviceInfo->asioChannelInfos )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ int a;
+
+ for( a=0; a < deviceInfo->maxInputChannels; ++a ){
+ asioDeviceInfo->asioChannelInfos[a].channel = a;
+ asioDeviceInfo->asioChannelInfos[a].isInput = ASIOTrue;
+ ASIOError asioError = ASIOGetChannelInfo( &asioDeviceInfo->asioChannelInfos[a] );
+ if( asioError != ASE_OK )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+ goto error;
+ }
+ }
+
+ for( a=0; a < deviceInfo->maxOutputChannels; ++a ){
+ int b = deviceInfo->maxInputChannels + a;
+ asioDeviceInfo->asioChannelInfos[b].channel = a;
+ asioDeviceInfo->asioChannelInfos[b].isInput = ASIOFalse;
+ ASIOError asioError = ASIOGetChannelInfo( &asioDeviceInfo->asioChannelInfos[b] );
+ if( asioError != ASE_OK )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+ goto error;
+ }
+ }
+
+
+ /* unload the driver */
+ ASIOExit();
+
+ (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;
+ ++(*hostApi)->info.deviceCount;
+ }
+ }
+ }
+
+ if( (*hostApi)->info.deviceCount > 0 )
+ {
+ (*hostApi)->info.defaultInputDevice = 0;
+ (*hostApi)->info.defaultOutputDevice = 0;
+ }
+ else
+ {
+ (*hostApi)->info.defaultInputDevice = paNoDevice;
+ (*hostApi)->info.defaultOutputDevice = paNoDevice;
+ }
+
+
+ (*hostApi)->Terminate = Terminate;
+ (*hostApi)->OpenStream = OpenStream;
+ (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+ PaUtil_InitializeStreamInterface( &asioHostApi->callbackStreamInterface, CloseStream, StartStream,
+ StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+ GetStreamTime, GetStreamCpuLoad,
+ PaUtil_DummyRead, PaUtil_DummyWrite,
+ PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
+
+ PaUtil_InitializeStreamInterface( &asioHostApi->blockingStreamInterface, CloseStream, StartStream,
+ StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+ GetStreamTime, PaUtil_DummyGetCpuLoad,
+ ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+
+ return result;
+
+error:
+ if( asioHostApi )
+ {
+ if( asioHostApi->allocations )
+ {
+ PaUtil_FreeAllAllocations( asioHostApi->allocations );
+ PaUtil_DestroyAllocationGroup( asioHostApi->allocations );
+ }
+
+ PaUtil_FreeMemory( asioHostApi );
+ }
+ return result;
+}
+
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+ PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
+
+ /*
+ IMPLEMENT ME:
+ - clean up any resources not handled by the allocation group
+ */
+
+ if( asioHostApi->allocations )
+ {
+ PaUtil_FreeAllAllocations( asioHostApi->allocations );
+ PaUtil_DestroyAllocationGroup( asioHostApi->allocations );
+ }
+
+ PaUtil_FreeMemory( asioHostApi );
+}
+
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate )
+{
+ PaError result = paNoError;
+ PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
+ PaAsioDriverInfo *driverInfo = &asioHostApi->openAsioDriverInfo;
+ int inputChannelCount, outputChannelCount;
+ PaSampleFormat inputSampleFormat, outputSampleFormat;
+ PaDeviceIndex asioDeviceIndex;
+ ASIOError asioError;
+
+ if( inputParameters && outputParameters )
+ {
+ /* full duplex ASIO stream must use the same device for input and output */
+
+ if( inputParameters->device != outputParameters->device )
+ return paBadIODeviceCombination;
+ }
+
+ if( inputParameters )
+ {
+ inputChannelCount = inputParameters->channelCount;
+ inputSampleFormat = inputParameters->sampleFormat;
+
+ /* all standard sample formats are supported by the buffer adapter,
+ this implementation doesn't support any custom sample formats */
+ if( inputSampleFormat & paCustomFormat )
+ return paSampleFormatNotSupported;
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+
+ if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ asioDeviceIndex = inputParameters->device;
+
+ /* validate inputStreamInfo */
+ /** @todo do more validation here */
+ // if( inputParameters->hostApiSpecificStreamInfo )
+ // return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+ }
+ else
+ {
+ inputChannelCount = 0;
+ }
+
+ if( outputParameters )
+ {
+ outputChannelCount = outputParameters->channelCount;
+ outputSampleFormat = outputParameters->sampleFormat;
+
+ /* all standard sample formats are supported by the buffer adapter,
+ this implementation doesn't support any custom sample formats */
+ if( outputSampleFormat & paCustomFormat )
+ return paSampleFormatNotSupported;
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+
+ if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ asioDeviceIndex = outputParameters->device;
+
+ /* validate outputStreamInfo */
+ /** @todo do more validation here */
+ // if( outputParameters->hostApiSpecificStreamInfo )
+ // return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+ }
+ else
+ {
+ outputChannelCount = 0;
+ }
+
+
+
+ /* if an ASIO device is open we can only get format information for the currently open device */
+
+ if( asioHostApi->openAsioDeviceIndex != paNoDevice
+ && asioHostApi->openAsioDeviceIndex != asioDeviceIndex )
+ {
+ return paDeviceUnavailable;
+ }
+
+
+ /* NOTE: we load the driver and use its current settings
+ rather than the ones in our device info structure which may be stale */
+
+ /* open the device if it's not already open */
+ if( asioHostApi->openAsioDeviceIndex == paNoDevice )
+ {
+ result = LoadAsioDriver( asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name,
+ driverInfo, asioHostApi->systemSpecific );
+ if( result != paNoError )
+ return result;
+ }
+
+ /* check that input device can support inputChannelCount */
+ if( inputChannelCount > 0 )
+ {
+ if( inputChannelCount > driverInfo->inputChannelCount )
+ {
+ result = paInvalidChannelCount;
+ goto done;
+ }
+ }
+
+ /* check that output device can support outputChannelCount */
+ if( outputChannelCount )
+ {
+ if( outputChannelCount > driverInfo->outputChannelCount )
+ {
+ result = paInvalidChannelCount;
+ goto done;
+ }
+ }
+
+ /* query for sample rate support */
+ asioError = ASIOCanSampleRate( sampleRate );
+ if( asioError == ASE_NoClock || asioError == ASE_NotPresent )
+ {
+ result = paInvalidSampleRate;
+ goto done;
+ }
+
+done:
+ /* close the device if it wasn't already open */
+ if( asioHostApi->openAsioDeviceIndex == paNoDevice )
+ {
+ ASIOExit(); /* not sure if we should check for errors here */
+ }
+
+ if( result == paNoError )
+ return paFormatIsSupported;
+ else
+ return result;
+}
+
+
+
+/* PaAsioStream - a stream data structure specifically for this implementation */
+
+typedef struct PaAsioStream
+{
+ PaUtilStreamRepresentation streamRepresentation;
+ PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+ PaUtilBufferProcessor bufferProcessor;
+
+ PaAsioHostApiRepresentation *asioHostApi;
+ unsigned long framesPerHostCallback;
+
+ /* ASIO driver info - these may not be needed for the life of the stream,
+ but store them here until we work out how format conversion is going
+ to work. */
+
+ ASIOBufferInfo *asioBufferInfos;
+ ASIOChannelInfo *asioChannelInfos;
+ long inputLatency, outputLatency; // actual latencies returned by asio
+
+ long inputChannelCount, outputChannelCount;
+ bool postOutput;
+
+ void **bufferPtrs; /* this is carved up for inputBufferPtrs and outputBufferPtrs */
+ void **inputBufferPtrs[2];
+ void **outputBufferPtrs[2];
+
+ PaAsioBufferConverter *inputBufferConverter;
+ long inputShift;
+ PaAsioBufferConverter *outputBufferConverter;
+ long outputShift;
+
+ volatile bool stopProcessing;
+ int stopPlayoutCount;
+ HANDLE completedBuffersPlayedEvent;
+
+ bool streamFinishedCallbackCalled;
+ volatile int isActive;
+ volatile bool zeroOutput; /* all future calls to the callback will output silence */
+
+ volatile long reenterCount;
+ volatile long reenterError;
+
+ PaStreamCallbackFlags callbackFlags;
+}
+PaAsioStream;
+
+static PaAsioStream *theAsioStream = 0; /* due to ASIO sdk limitations there can be only one stream */
+
+
+static void ZeroOutputBuffers( PaAsioStream *stream, long index )
+{
+ int i;
+
+ for( i=0; i < stream->outputChannelCount; ++i )
+ {
+ void *buffer = stream->asioBufferInfos[ i + stream->inputChannelCount ].buffers[index];
+
+ int bytesPerSample = BytesPerAsioSample( stream->asioChannelInfos[ i + stream->inputChannelCount ].type );
+
+ memset( buffer, 0, stream->framesPerHostCallback * bytesPerSample );
+ }
+}
+
+
+static unsigned long SelectHostBufferSize( unsigned long suggestedLatencyFrames,
+ PaAsioDriverInfo *driverInfo )
+{
+ unsigned long result;
+
+ if( suggestedLatencyFrames == 0 )
+ {
+ result = driverInfo->bufferPreferredSize;
+ }
+ else{
+ if( suggestedLatencyFrames <= (unsigned long)driverInfo->bufferMinSize )
+ {
+ result = driverInfo->bufferMinSize;
+ }
+ else if( suggestedLatencyFrames >= (unsigned long)driverInfo->bufferMaxSize )
+ {
+ result = driverInfo->bufferMaxSize;
+ }
+ else
+ {
+ if( driverInfo->bufferGranularity == -1 )
+ {
+ /* power-of-two */
+ result = 2;
+
+ while( result < suggestedLatencyFrames )
+ result *= 2;
+
+ if( result < (unsigned long)driverInfo->bufferMinSize )
+ result = driverInfo->bufferMinSize;
+
+ if( result > (unsigned long)driverInfo->bufferMaxSize )
+ result = driverInfo->bufferMaxSize;
+ }
+ else if( driverInfo->bufferGranularity == 0 )
+ {
+ /* the documentation states that bufferGranularity should be
+ zero when bufferMinSize, bufferMaxSize and
+ bufferPreferredSize are the same. We assume that is the case.
+ */
+
+ result = driverInfo->bufferPreferredSize;
+ }
+ else
+ {
+ /* modulo granularity */
+
+ unsigned long remainder =
+ suggestedLatencyFrames % driverInfo->bufferGranularity;
+
+ if( remainder == 0 )
+ {
+ result = suggestedLatencyFrames;
+ }
+ else
+ {
+ result = suggestedLatencyFrames
+ + (driverInfo->bufferGranularity - remainder);
+
+ if( result > (unsigned long)driverInfo->bufferMaxSize )
+ result = driverInfo->bufferMaxSize;
+ }
+ }
+ }
+ }
+
+ return result;
+}
+
+
+/* returns channelSelectors if present */
+
+static PaError ValidateAsioSpecificStreamInfo(
+ const PaStreamParameters *streamParameters,
+ const PaAsioStreamInfo *streamInfo,
+ int deviceChannelCount,
+ int **channelSelectors )
+{
+ if( streamInfo )
+ {
+ if( streamInfo->size != sizeof( PaAsioStreamInfo )
+ || streamInfo->version != 1 )
+ {
+ return paIncompatibleHostApiSpecificStreamInfo;
+ }
+
+ if( streamInfo->flags & paAsioUseChannelSelectors )
+ *channelSelectors = streamInfo->channelSelectors;
+
+ if( !(*channelSelectors) )
+ return paIncompatibleHostApiSpecificStreamInfo;
+
+ for( int i=0; i < streamParameters->channelCount; ++i ){
+ if( (*channelSelectors)[i] < 0
+ || (*channelSelectors)[i] >= deviceChannelCount ){
+ return paInvalidChannelCount;
+ }
+ }
+ }
+
+ return paNoError;
+}
+
+
+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
+
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+ PaStream** s,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate,
+ unsigned long framesPerBuffer,
+ PaStreamFlags streamFlags,
+ PaStreamCallback *streamCallback,
+ void *userData )
+{
+ PaError result = paNoError;
+ PaAsioHostApiRepresentation *asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
+ PaAsioStream *stream = 0;
+ PaAsioStreamInfo *inputStreamInfo, *outputStreamInfo;
+ unsigned long framesPerHostBuffer;
+ int inputChannelCount, outputChannelCount;
+ PaSampleFormat inputSampleFormat, outputSampleFormat;
+ PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
+ unsigned long suggestedInputLatencyFrames;
+ unsigned long suggestedOutputLatencyFrames;
+ PaDeviceIndex asioDeviceIndex;
+ ASIOError asioError;
+ int asioIsInitialized = 0;
+ int asioBuffersCreated = 0;
+ int completedBuffersPlayedEventInited = 0;
+ int i;
+ PaAsioDriverInfo *driverInfo;
+ int *inputChannelSelectors = 0;
+ int *outputChannelSelectors = 0;
+ bool isExternal = false;
+
+ /* unless we move to using lower level ASIO calls, we can only have
+ one device open at a time */
+ if( asioHostApi->openAsioDeviceIndex != paNoDevice ){
+ PA_DEBUG(("OpenStream paDeviceUnavailable\n"));
+ return paDeviceUnavailable;
+ }
+
+ if( inputParameters && outputParameters )
+ {
+ /* full duplex ASIO stream must use the same device for input and output */
+
+ if( inputParameters->device != outputParameters->device ){
+ PA_DEBUG(("OpenStream paBadIODeviceCombination\n"));
+ return paBadIODeviceCombination;
+ }
+ }
+
+ if( inputParameters )
+ {
+ inputChannelCount = inputParameters->channelCount;
+ inputSampleFormat = inputParameters->sampleFormat;
+ suggestedInputLatencyFrames = (unsigned long)((inputParameters->suggestedLatency * sampleRate)+0.5f);
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+ if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ asioDeviceIndex = inputParameters->device;
+
+ PaAsioDeviceInfo *asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[asioDeviceIndex];
+
+ /* validate hostApiSpecificStreamInfo */
+ inputStreamInfo = (PaAsioStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
+ result = ValidateAsioSpecificStreamInfo( inputParameters, inputStreamInfo,
+ asioDeviceInfo->commonDeviceInfo.maxInputChannels,
+ &inputChannelSelectors
+ );
+ if( result != paNoError ) return result;
+ }
+ else
+ {
+ inputChannelCount = 0;
+ inputSampleFormat = 0;
+ suggestedInputLatencyFrames = 0;
+ }
+
+ if( outputParameters )
+ {
+ outputChannelCount = outputParameters->channelCount;
+ outputSampleFormat = outputParameters->sampleFormat;
+ suggestedOutputLatencyFrames = (unsigned long)((outputParameters->suggestedLatency * sampleRate)+0.5f);
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+ if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ asioDeviceIndex = outputParameters->device;
+
+ PaAsioDeviceInfo *asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[asioDeviceIndex];
+
+ /* validate hostApiSpecificStreamInfo */
+ outputStreamInfo = (PaAsioStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
+ result = ValidateAsioSpecificStreamInfo( outputParameters, outputStreamInfo,
+ asioDeviceInfo->commonDeviceInfo.maxOutputChannels,
+ &outputChannelSelectors
+ );
+ if( result != paNoError ) return result;
+ }
+ else
+ {
+ outputChannelCount = 0;
+ outputSampleFormat = 0;
+ suggestedOutputLatencyFrames = 0;
+ }
+
+ driverInfo = &asioHostApi->openAsioDriverInfo;
+
+ /* NOTE: we load the driver and use its current settings
+ rather than the ones in our device info structure which may be stale */
+
+ result = LoadAsioDriver( asioHostApi->inheritedHostApiRep.deviceInfos[ asioDeviceIndex ]->name,
+ driverInfo, asioHostApi->systemSpecific );
+ if( result == paNoError )
+ asioIsInitialized = 1;
+ else{
+ PA_DEBUG(("OpenStream ERROR1\n"));
+ goto error;
+ }
+
+ /* check that input device can support inputChannelCount */
+ if( inputChannelCount > 0 )
+ {
+ if( inputChannelCount > driverInfo->inputChannelCount )
+ {
+ result = paInvalidChannelCount;
+ PA_DEBUG(("OpenStream ERROR2\n"));
+ goto error;
+ }
+ }
+
+ /* check that output device can support outputChannelCount */
+ if( outputChannelCount )
+ {
+ if( outputChannelCount > driverInfo->outputChannelCount )
+ {
+ result = paInvalidChannelCount;
+ PA_DEBUG(("OpenStream ERROR3\n"));
+ goto error;
+ }
+ }
+
+
+ /* davidv: listing ASIO Clock sources, there is an ongoing investigation by
+ me about whether or not call ASIOSetSampleRate if an external Clock is
+ used. A few drivers expected different things here */
+ {
+ ASIOClockSource clocks[32];
+ long numSources=32;
+ asioError = ASIOGetClockSources(clocks, &numSources);
+ if( asioError != ASE_OK ){
+ PA_DEBUG(("ERROR: ASIOGetClockSources: %s\n", PaAsio_GetAsioErrorText(asioError) ));
+ }else{
+ PA_DEBUG(("INFO ASIOGetClockSources listing %d clocks\n", numSources ));
+ for (int i=0;i<numSources;++i){
+ PA_DEBUG(("ASIOClockSource%d %s current:%d\n", i,clocks[i].name, clocks[i].isCurrentSource ));
+
+ /*
+ If you have problems with some drivers when externally clocked,
+ uncomment the next two lines
+ */
+ //if (clocks[i].isCurrentSource)
+ // isExternal = true;
+ }
+ }
+ }
+
+ // check that the device supports the requested sample rate
+
+ asioError = ASIOCanSampleRate( sampleRate );
+ PA_DEBUG(("ASIOCanSampleRate(%f):%d\n",sampleRate, asioError ));
+
+ if( asioError != ASE_OK )
+ {
+ result = paInvalidSampleRate;
+ PA_DEBUG(("ERROR: ASIOCanSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
+ goto error;
+ }
+
+
+ // retrieve the current sample rate, we only change to the requested
+ // sample rate if the device is not already in that rate.
+
+ ASIOSampleRate oldRate;
+ asioError = ASIOGetSampleRate(&oldRate);
+ if( asioError != ASE_OK )
+ {
+ result = paInvalidSampleRate;
+ PA_DEBUG(("ERROR: ASIOGetSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
+ goto error;
+ }
+ PA_DEBUG(("ASIOGetSampleRate:%f\n",oldRate));
+
+ if (oldRate != sampleRate){
+
+ PA_DEBUG(("before ASIOSetSampleRate(%f)\n",sampleRate));
+
+ asioError = ASIOSetSampleRate( isExternal?0:sampleRate );
+ /* Set sample rate */
+ if( asioError != ASE_OK )
+ {
+ result = paInvalidSampleRate;
+ PA_DEBUG(("ERROR: ASIOSetSampleRate: %s\n", PaAsio_GetAsioErrorText(asioError) ));
+ goto error;
+ }
+ PA_DEBUG(("after ASIOSetSampleRate(%f)\n",sampleRate));
+ }
+ else
+ {
+ PA_DEBUG(("No Need to change SR\n"));
+ }
+
+
+ /*
+ IMPLEMENT ME:
+ - if a full duplex stream is requested, check that the combination
+ of input and output parameters is supported
+ */
+
+ /* validate platform specific flags */
+ if( (streamFlags & paPlatformSpecificFlags) != 0 ){
+ PA_DEBUG(("OpenStream invalid flags!!\n"));
+ return paInvalidFlag; /* unexpected platform specific flag */
+ }
+
+
+ stream = (PaAsioStream*)PaUtil_AllocateMemory( sizeof(PaAsioStream) );
+ if( !stream )
+ {
+ result = paInsufficientMemory;
+ PA_DEBUG(("OpenStream ERROR5\n"));
+ goto error;
+ }
+
+ stream->completedBuffersPlayedEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
+ if( stream->completedBuffersPlayedEvent == NULL )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
+ PA_DEBUG(("OpenStream ERROR6\n"));
+ goto error;
+ }
+ completedBuffersPlayedEventInited = 1;
+
+
+ stream->asioBufferInfos = 0; /* for deallocation in error */
+ stream->asioChannelInfos = 0; /* for deallocation in error */
+ stream->bufferPtrs = 0; /* for deallocation in error */
+
+ if( streamCallback )
+ {
+ PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+ &asioHostApi->callbackStreamInterface, streamCallback, userData );
+ }
+ else
+ {
+ PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+ &asioHostApi->blockingStreamInterface, streamCallback, userData );
+ }
+
+
+ PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+
+
+ stream->asioBufferInfos = (ASIOBufferInfo*)PaUtil_AllocateMemory(
+ sizeof(ASIOBufferInfo) * (inputChannelCount + outputChannelCount) );
+ if( !stream->asioBufferInfos )
+ {
+ result = paInsufficientMemory;
+ PA_DEBUG(("OpenStream ERROR7\n"));
+ goto error;
+ }
+
+
+ for( i=0; i < inputChannelCount; ++i )
+ {
+ ASIOBufferInfo *info = &stream->asioBufferInfos[i];
+
+ info->isInput = ASIOTrue;
+
+ if( inputChannelSelectors ){
+ // inputChannelSelectors values have already been validated in
+ // ValidateAsioSpecificStreamInfo() above
+ info->channelNum = inputChannelSelectors[i];
+ }else{
+ info->channelNum = i;
+ }
+
+ info->buffers[0] = info->buffers[1] = 0;
+ }
+
+ for( i=0; i < outputChannelCount; ++i ){
+ ASIOBufferInfo *info = &stream->asioBufferInfos[inputChannelCount+i];
+
+ info->isInput = ASIOFalse;
+
+ if( outputChannelSelectors ){
+ // outputChannelSelectors values have already been validated in
+ // ValidateAsioSpecificStreamInfo() above
+ info->channelNum = outputChannelSelectors[i];
+ }else{
+ info->channelNum = i;
+ }
+
+ info->buffers[0] = info->buffers[1] = 0;
+ }
+
+
+ framesPerHostBuffer = SelectHostBufferSize(
+ (( suggestedInputLatencyFrames > suggestedOutputLatencyFrames )
+ ? suggestedInputLatencyFrames : suggestedOutputLatencyFrames),
+ driverInfo );
+
+
+ PA_DEBUG(("PaAsioOpenStream: framesPerHostBuffer :%d\n", framesPerHostBuffer));
+
+ asioError = ASIOCreateBuffers( stream->asioBufferInfos,
+ inputChannelCount+outputChannelCount,
+ framesPerHostBuffer, &asioCallbacks_ );
+
+ if( asioError != ASE_OK
+ && framesPerHostBuffer != (unsigned long)driverInfo->bufferPreferredSize )
+ {
+ PA_DEBUG(("ERROR: ASIOCreateBuffers: %s\n", PaAsio_GetAsioErrorText(asioError) ));
+ /*
+ Some buggy drivers (like the Hoontech DSP24) give incorrect
+ [min, preferred, max] values They should work with the preferred size
+ value, thus if Pa_ASIO_CreateBuffers fails with the hostBufferSize
+ computed in SelectHostBufferSize, we try again with the preferred size.
+ */
+
+ framesPerHostBuffer = driverInfo->bufferPreferredSize;
+
+ PA_DEBUG(("PaAsioOpenStream: CORRECTED framesPerHostBuffer :%d\n", framesPerHostBuffer));
+
+ ASIOError asioError2 = ASIOCreateBuffers( stream->asioBufferInfos,
+ inputChannelCount+outputChannelCount,
+ framesPerHostBuffer, &asioCallbacks_ );
+ if( asioError2 == ASE_OK )
+ asioError = ASE_OK;
+ }
+
+ if( asioError != ASE_OK )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+ PA_DEBUG(("OpenStream ERROR9\n"));
+ goto error;
+ }
+
+ asioBuffersCreated = 1;
+
+ stream->asioChannelInfos = (ASIOChannelInfo*)PaUtil_AllocateMemory(
+ sizeof(ASIOChannelInfo) * (inputChannelCount + outputChannelCount) );
+ if( !stream->asioChannelInfos )
+ {
+ result = paInsufficientMemory;
+ PA_DEBUG(("OpenStream ERROR10\n"));
+ goto error;
+ }
+
+ for( i=0; i < inputChannelCount + outputChannelCount; ++i )
+ {
+ stream->asioChannelInfos[i].channel = stream->asioBufferInfos[i].channelNum;
+ stream->asioChannelInfos[i].isInput = stream->asioBufferInfos[i].isInput;
+ asioError = ASIOGetChannelInfo( &stream->asioChannelInfos[i] );
+ if( asioError != ASE_OK )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+ PA_DEBUG(("OpenStream ERROR11\n"));
+ goto error;
+ }
+ }
+
+ stream->bufferPtrs = (void**)PaUtil_AllocateMemory(
+ 2 * sizeof(void*) * (inputChannelCount + outputChannelCount) );
+ if( !stream->bufferPtrs )
+ {
+ result = paInsufficientMemory;
+ PA_DEBUG(("OpenStream ERROR12\n"));
+ goto error;
+ }
+
+ if( inputChannelCount > 0 )
+ {
+ stream->inputBufferPtrs[0] = stream-> bufferPtrs;
+ stream->inputBufferPtrs[1] = &stream->bufferPtrs[inputChannelCount];
+
+ for( i=0; i<inputChannelCount; ++i )
+ {
+ stream->inputBufferPtrs[0][i] = stream->asioBufferInfos[i].buffers[0];
+ stream->inputBufferPtrs[1][i] = stream->asioBufferInfos[i].buffers[1];
+ }
+ }
+ else
+ {
+ stream->inputBufferPtrs[0] = 0;
+ stream->inputBufferPtrs[1] = 0;
+ }
+
+ if( outputChannelCount > 0 )
+ {
+ stream->outputBufferPtrs[0] = &stream->bufferPtrs[inputChannelCount*2];
+ stream->outputBufferPtrs[1] = &stream->bufferPtrs[inputChannelCount*2 + outputChannelCount];
+
+ for( i=0; i<outputChannelCount; ++i )
+ {
+ stream->outputBufferPtrs[0][i] = stream->asioBufferInfos[inputChannelCount+i].buffers[0];
+ stream->outputBufferPtrs[1][i] = stream->asioBufferInfos[inputChannelCount+i].buffers[1];
+ }
+ }
+ else
+ {
+ stream->outputBufferPtrs[0] = 0;
+ stream->outputBufferPtrs[1] = 0;
+ }
+
+ if( inputChannelCount > 0 )
+ {
+ /* FIXME: assume all channels use the same type for now */
+ ASIOSampleType inputType = stream->asioChannelInfos[0].type;
+
+ PA_DEBUG(("ASIO Input type:%d",inputType));
+ AsioSampleTypeLOG(inputType);
+ hostInputSampleFormat = AsioSampleTypeToPaNativeSampleFormat( inputType );
+
+ SelectAsioToPaConverter( inputType, &stream->inputBufferConverter, &stream->inputShift );
+ }
+ else
+ {
+ hostInputSampleFormat = 0;
+ stream->inputBufferConverter = 0;
+ }
+
+ if( outputChannelCount > 0 )
+ {
+ /* FIXME: assume all channels use the same type for now */
+ ASIOSampleType outputType = stream->asioChannelInfos[inputChannelCount].type;
+
+ PA_DEBUG(("ASIO Output type:%d",outputType));
+ AsioSampleTypeLOG(outputType);
+ hostOutputSampleFormat = AsioSampleTypeToPaNativeSampleFormat( outputType );
+
+ SelectPaToAsioConverter( outputType, &stream->outputBufferConverter, &stream->outputShift );
+ }
+ else
+ {
+ hostOutputSampleFormat = 0;
+ stream->outputBufferConverter = 0;
+ }
+
+ result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+ inputChannelCount, inputSampleFormat, hostInputSampleFormat,
+ outputChannelCount, outputSampleFormat, hostOutputSampleFormat,
+ sampleRate, streamFlags, framesPerBuffer,
+ framesPerHostBuffer, paUtilFixedHostBufferSize,
+ streamCallback, userData );
+ if( result != paNoError ){
+ PA_DEBUG(("OpenStream ERROR13\n"));
+ goto error;
+ }
+
+
+ ASIOGetLatencies( &stream->inputLatency, &stream->outputLatency );
+
+ stream->streamRepresentation.streamInfo.inputLatency =
+ (double)( PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor)
+ + stream->inputLatency) / sampleRate; // seconds
+ stream->streamRepresentation.streamInfo.outputLatency =
+ (double)( PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor)
+ + stream->outputLatency) / sampleRate; // seconds
+ stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+ // the code below prints the ASIO latency which doesn't include the
+ // buffer processor latency. it reports the added latency separately
+ PA_DEBUG(("PaAsio : ASIO InputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n",
+ stream->inputLatency,
+ (long)((stream->inputLatency*1000)/ sampleRate),
+ PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor),
+ (long)((PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor)*1000)/ sampleRate)
+ ));
+
+ PA_DEBUG(("PaAsio : ASIO OuputLatency = %ld (%ld ms), added buffProc:%ld (%ld ms)\n",
+ stream->outputLatency,
+ (long)((stream->outputLatency*1000)/ sampleRate),
+ PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor),
+ (long)((PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor)*1000)/ sampleRate)
+ ));
+
+ stream->asioHostApi = asioHostApi;
+ stream->framesPerHostCallback = framesPerHostBuffer;
+
+ stream->inputChannelCount = inputChannelCount;
+ stream->outputChannelCount = outputChannelCount;
+ stream->postOutput = driverInfo->postOutput;
+ stream->isActive = 0;
+
+ asioHostApi->openAsioDeviceIndex = asioDeviceIndex;
+
+ *s = (PaStream*)stream;
+
+ return result;
+
+error:
+ PA_DEBUG(("goto errored\n"));
+ if( stream )
+ {
+ if( completedBuffersPlayedEventInited )
+ CloseHandle( stream->completedBuffersPlayedEvent );
+
+ if( stream->asioBufferInfos )
+ PaUtil_FreeMemory( stream->asioBufferInfos );
+
+ if( stream->asioChannelInfos )
+ PaUtil_FreeMemory( stream->asioChannelInfos );
+
+ if( stream->bufferPtrs )
+ PaUtil_FreeMemory( stream->bufferPtrs );
+
+ PaUtil_FreeMemory( stream );
+ }
+
+ if( asioBuffersCreated )
+ ASIODisposeBuffers();
+
+ if( asioIsInitialized )
+ ASIOExit();
+
+ return result;
+}
+
+
+/*
+ When CloseStream() is called, the multi-api layer ensures that
+ the stream has already been stopped or aborted.
+*/
+static PaError CloseStream( PaStream* s )
+{
+ PaError result = paNoError;
+ PaAsioStream *stream = (PaAsioStream*)s;
+
+ /*
+ IMPLEMENT ME:
+ - additional stream closing + cleanup
+ */
+
+ PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+ PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+
+ stream->asioHostApi->openAsioDeviceIndex = paNoDevice;
+
+ CloseHandle( stream->completedBuffersPlayedEvent );
+
+ PaUtil_FreeMemory( stream->asioBufferInfos );
+ PaUtil_FreeMemory( stream->asioChannelInfos );
+ PaUtil_FreeMemory( stream->bufferPtrs );
+ PaUtil_FreeMemory( stream );
+
+ ASIODisposeBuffers();
+ ASIOExit();
+
+ return result;
+}
+
+
+static void bufferSwitch(long index, ASIOBool directProcess)
+{
+//TAKEN FROM THE ASIO SDK
+
+ // the actual processing callback.
+ // Beware that this is normally in a seperate thread, hence be sure that
+ // you take care about thread synchronization. This is omitted here for
+ // simplicity.
+
+ // as this is a "back door" into the bufferSwitchTimeInfo a timeInfo needs
+ // to be created though it will only set the timeInfo.samplePosition and
+ // timeInfo.systemTime fields and the according flags
+
+ ASIOTime timeInfo;
+ memset( &timeInfo, 0, sizeof (timeInfo) );
+
+ // get the time stamp of the buffer, not necessary if no
+ // synchronization to other media is required
+ if( ASIOGetSamplePosition(&timeInfo.timeInfo.samplePosition, &timeInfo.timeInfo.systemTime) == ASE_OK)
+ timeInfo.timeInfo.flags = kSystemTimeValid | kSamplePositionValid;
+
+ // Call the real callback
+ bufferSwitchTimeInfo( &timeInfo, index, directProcess );
+}
+
+
+// conversion from 64 bit ASIOSample/ASIOTimeStamp to double float
+#if NATIVE_INT64
+ #define ASIO64toDouble(a) (a)
+#else
+ const double twoRaisedTo32 = 4294967296.;
+ #define ASIO64toDouble(a) ((a).lo + (a).hi * twoRaisedTo32)
+#endif
+
+static ASIOTime *bufferSwitchTimeInfo( ASIOTime *timeInfo, long index, ASIOBool directProcess )
+{
+ // the actual processing callback.
+ // Beware that this is normally in a seperate thread, hence be sure that
+ // you take care about thread synchronization.
+
+
+ /* The SDK says the following about the directProcess flag:
+ suggests to the host whether it should immediately start processing
+ (directProcess == ASIOTrue), or whether its process should be deferred
+ because the call comes from a very low level (for instance, a high level
+ priority interrupt), and direct processing would cause timing instabilities for
+ the rest of the system. If in doubt, directProcess should be set to ASIOFalse.
+
+ We just ignore directProcess. This could cause incompatibilities with
+ drivers which really don't want the audio processing to occur in this
+ callback, but none have been identified yet.
+ */
+
+ (void) directProcess; /* suppress unused parameter warning */
+
+#if 0
+ // store the timeInfo for later use
+ asioDriverInfo.tInfo = *timeInfo;
+
+ // get the time stamp of the buffer, not necessary if no
+ // synchronization to other media is required
+
+ if (timeInfo->timeInfo.flags & kSystemTimeValid)
+ asioDriverInfo.nanoSeconds = ASIO64toDouble(timeInfo->timeInfo.systemTime);
+ else
+ asioDriverInfo.nanoSeconds = 0;
+
+ if (timeInfo->timeInfo.flags & kSamplePositionValid)
+ asioDriverInfo.samples = ASIO64toDouble(timeInfo->timeInfo.samplePosition);
+ else
+ asioDriverInfo.samples = 0;
+
+ if (timeInfo->timeCode.flags & kTcValid)
+ asioDriverInfo.tcSamples = ASIO64toDouble(timeInfo->timeCode.timeCodeSamples);
+ else
+ asioDriverInfo.tcSamples = 0;
+
+ // get the system reference time
+ asioDriverInfo.sysRefTime = get_sys_reference_time();
+#endif
+
+#if 0
+ // a few debug messages for the Windows device driver developer
+ // tells you the time when driver got its interrupt and the delay until the app receives
+ // the event notification.
+ static double last_samples = 0;
+ char tmp[128];
+ sprintf (tmp, "diff: %d / %d ms / %d ms / %d samples \n", asioDriverInfo.sysRefTime - (long)(asioDriverInfo.nanoSeconds / 1000000.0), asioDriverInfo.sysRefTime, (long)(asioDriverInfo.nanoSeconds / 1000000.0), (long)(asioDriverInfo.samples - last_samples));
+ OutputDebugString (tmp);
+ last_samples = asioDriverInfo.samples;
+#endif
+
+
+ if( !theAsioStream )
+ return 0L;
+
+ // Keep sample position
+ // FIXME: asioDriverInfo.pahsc_NumFramesDone = timeInfo->timeInfo.samplePosition.lo;
+
+
+ // protect against reentrancy
+ if( PaAsio_AtomicIncrement(&theAsioStream->reenterCount) )
+ {
+ theAsioStream->reenterError++;
+ //DBUG(("bufferSwitchTimeInfo : reentrancy detection = %d\n", asioDriverInfo.reenterError));
+ return 0L;
+ }
+
+ int buffersDone = 0;
+
+ do
+ {
+ if( buffersDone > 0 )
+ {
+ // this is a reentered buffer, we missed processing it on time
+ // set the input overflow and output underflow flags as appropriate
+
+ if( theAsioStream->inputChannelCount > 0 )
+ theAsioStream->callbackFlags |= paInputOverflow;
+
+ if( theAsioStream->outputChannelCount > 0 )
+ theAsioStream->callbackFlags |= paOutputUnderflow;
+ }
+ else
+ {
+ if( theAsioStream->zeroOutput )
+ {
+ ZeroOutputBuffers( theAsioStream, index );
+
+ // Finally if the driver supports the ASIOOutputReady() optimization,
+ // do it here, all data are in place
+ if( theAsioStream->postOutput )
+ ASIOOutputReady();
+
+ if( theAsioStream->stopProcessing )
+ {
+ if( theAsioStream->stopPlayoutCount < 2 )
+ {
+ ++theAsioStream->stopPlayoutCount;
+ if( theAsioStream->stopPlayoutCount == 2 )
+ {
+ theAsioStream->isActive = 0;
+ if( theAsioStream->streamRepresentation.streamFinishedCallback != 0 )
+ theAsioStream->streamRepresentation.streamFinishedCallback( theAsioStream->streamRepresentation.userData );
+ theAsioStream->streamFinishedCallbackCalled = true;
+ SetEvent( theAsioStream->completedBuffersPlayedEvent );
+ }
+ }
+ }
+ }
+ else
+ {
+
+#if 0
+// test code to try to detect slip conditions... these may work on some systems
+// but neither of them work on the RME Digi96
+
+// check that sample delta matches buffer size (otherwise we must have skipped
+// a buffer.
+static double last_samples = -512;
+double samples;
+//if( timeInfo->timeCode.flags & kTcValid )
+// samples = ASIO64toDouble(timeInfo->timeCode.timeCodeSamples);
+//else
+ samples = ASIO64toDouble(timeInfo->timeInfo.samplePosition);
+int delta = samples - last_samples;
+//printf( "%d\n", delta);
+last_samples = samples;
+
+if( delta > theAsioStream->framesPerHostCallback )
+{
+ if( theAsioStream->inputChannelCount > 0 )
+ theAsioStream->callbackFlags |= paInputOverflow;
+
+ if( theAsioStream->outputChannelCount > 0 )
+ theAsioStream->callbackFlags |= paOutputUnderflow;
+}
+
+// check that the buffer index is not the previous index (which would indicate
+// that a buffer was skipped.
+static int previousIndex = 1;
+if( index == previousIndex )
+{
+ if( theAsioStream->inputChannelCount > 0 )
+ theAsioStream->callbackFlags |= paInputOverflow;
+
+ if( theAsioStream->outputChannelCount > 0 )
+ theAsioStream->callbackFlags |= paOutputUnderflow;
+}
+previousIndex = index;
+#endif
+
+ int i;
+
+ PaUtil_BeginCpuLoadMeasurement( &theAsioStream->cpuLoadMeasurer );
+
+ PaStreamCallbackTimeInfo paTimeInfo;
+
+ // asio systemTime is supposed to be measured according to the same
+ // clock as timeGetTime
+ paTimeInfo.currentTime = (ASIO64toDouble( timeInfo->timeInfo.systemTime ) * .000000001);
+
+ /* patch from Paul Boege */
+ paTimeInfo.inputBufferAdcTime = paTimeInfo.currentTime -
+ ((double)theAsioStream->inputLatency/theAsioStream->streamRepresentation.streamInfo.sampleRate);
+
+ paTimeInfo.outputBufferDacTime = paTimeInfo.currentTime +
+ ((double)theAsioStream->outputLatency/theAsioStream->streamRepresentation.streamInfo.sampleRate);
+
+ /* old version is buggy because the buffer processor also adds in its latency to the time parameters
+ paTimeInfo.inputBufferAdcTime = paTimeInfo.currentTime - theAsioStream->streamRepresentation.streamInfo.inputLatency;
+ paTimeInfo.outputBufferDacTime = paTimeInfo.currentTime + theAsioStream->streamRepresentation.streamInfo.outputLatency;
+ */
+#if 1
+// detect underflows by checking inter-callback time > 2 buffer period
+static double previousTime = -1;
+if( previousTime > 0 ){
+
+ double delta = paTimeInfo.currentTime - previousTime;
+
+ if( delta >= 2. * (theAsioStream->framesPerHostCallback / theAsioStream->streamRepresentation.streamInfo.sampleRate) ){
+ if( theAsioStream->inputChannelCount > 0 )
+ theAsioStream->callbackFlags |= paInputOverflow;
+
+ if( theAsioStream->outputChannelCount > 0 )
+ theAsioStream->callbackFlags |= paOutputUnderflow;
+ }
+}
+previousTime = paTimeInfo.currentTime;
+#endif
+
+ // note that the above input and output times do not need to be
+ // adjusted for the latency of the buffer processor -- the buffer
+ // processor handles that.
+
+ if( theAsioStream->inputBufferConverter )
+ {
+ for( i=0; i<theAsioStream->inputChannelCount; i++ )
+ {
+ theAsioStream->inputBufferConverter( theAsioStream->inputBufferPtrs[index][i],
+ theAsioStream->inputShift, theAsioStream->framesPerHostCallback );
+ }
+ }
+
+ PaUtil_BeginBufferProcessing( &theAsioStream->bufferProcessor, &paTimeInfo, theAsioStream->callbackFlags );
+
+ /* reset status flags once they've been passed to the callback */
+ theAsioStream->callbackFlags = 0;
+
+ PaUtil_SetInputFrameCount( &theAsioStream->bufferProcessor, 0 /* default to host buffer size */ );
+ for( i=0; i<theAsioStream->inputChannelCount; ++i )
+ PaUtil_SetNonInterleavedInputChannel( &theAsioStream->bufferProcessor, i, theAsioStream->inputBufferPtrs[index][i] );
+
+ PaUtil_SetOutputFrameCount( &theAsioStream->bufferProcessor, 0 /* default to host buffer size */ );
+ for( i=0; i<theAsioStream->outputChannelCount; ++i )
+ PaUtil_SetNonInterleavedOutputChannel( &theAsioStream->bufferProcessor, i, theAsioStream->outputBufferPtrs[index][i] );
+
+ int callbackResult;
+ if( theAsioStream->stopProcessing )
+ callbackResult = paComplete;
+ else
+ callbackResult = paContinue;
+ unsigned long framesProcessed = PaUtil_EndBufferProcessing( &theAsioStream->bufferProcessor, &callbackResult );
+
+ if( theAsioStream->outputBufferConverter )
+ {
+ for( i=0; i<theAsioStream->outputChannelCount; i++ )
+ {
+ theAsioStream->outputBufferConverter( theAsioStream->outputBufferPtrs[index][i],
+ theAsioStream->outputShift, theAsioStream->framesPerHostCallback );
+ }
+ }
+
+ PaUtil_EndCpuLoadMeasurement( &theAsioStream->cpuLoadMeasurer, framesProcessed );
+
+ // Finally if the driver supports the ASIOOutputReady() optimization,
+ // do it here, all data are in place
+ if( theAsioStream->postOutput )
+ ASIOOutputReady();
+
+ if( callbackResult == paContinue )
+ {
+ /* nothing special to do */
+ }
+ else if( callbackResult == paAbort )
+ {
+ /* finish playback immediately */
+ theAsioStream->isActive = 0;
+ if( theAsioStream->streamRepresentation.streamFinishedCallback != 0 )
+ theAsioStream->streamRepresentation.streamFinishedCallback( theAsioStream->streamRepresentation.userData );
+ theAsioStream->streamFinishedCallbackCalled = true;
+ SetEvent( theAsioStream->completedBuffersPlayedEvent );
+ theAsioStream->zeroOutput = true;
+ }
+ else /* paComplete or other non-zero value indicating complete */
+ {
+ /* Finish playback once currently queued audio has completed. */
+ theAsioStream->stopProcessing = true;
+
+ if( PaUtil_IsBufferProcessorOutputEmpty( &theAsioStream->bufferProcessor ) )
+ {
+ theAsioStream->zeroOutput = true;
+ theAsioStream->stopPlayoutCount = 0;
+ }
+ }
+ }
+ }
+
+ ++buffersDone;
+ }while( PaAsio_AtomicDecrement(&theAsioStream->reenterCount) >= 0 );
+
+ return 0L;
+}
+
+
+static void sampleRateChanged(ASIOSampleRate sRate)
+{
+ // TAKEN FROM THE ASIO SDK
+ // do whatever you need to do if the sample rate changed
+ // usually this only happens during external sync.
+ // Audio processing is not stopped by the driver, actual sample rate
+ // might not have even changed, maybe only the sample rate status of an
+ // AES/EBU or S/PDIF digital input at the audio device.
+ // You might have to update time/sample related conversion routines, etc.
+
+ (void) sRate; /* unused parameter */
+ PA_DEBUG( ("sampleRateChanged : %d \n", sRate));
+}
+
+static long asioMessages(long selector, long value, void* message, double* opt)
+{
+// TAKEN FROM THE ASIO SDK
+ // currently the parameters "value", "message" and "opt" are not used.
+ long ret = 0;
+
+ (void) message; /* unused parameters */
+ (void) opt;
+
+ PA_DEBUG( ("asioMessages : %d , %d \n", selector, value));
+
+ switch(selector)
+ {
+ case kAsioSelectorSupported:
+ if(value == kAsioResetRequest
+ || value == kAsioEngineVersion
+ || value == kAsioResyncRequest
+ || value == kAsioLatenciesChanged
+ // the following three were added for ASIO 2.0, you don't necessarily have to support them
+ || value == kAsioSupportsTimeInfo
+ || value == kAsioSupportsTimeCode
+ || value == kAsioSupportsInputMonitor)
+ ret = 1L;
+ break;
+
+ case kAsioBufferSizeChange:
+ //printf("kAsioBufferSizeChange \n");
+ break;
+
+ case kAsioResetRequest:
+ // defer the task and perform the reset of the driver during the next "safe" situation
+ // You cannot reset the driver right now, as this code is called from the driver.
+ // Reset the driver is done by completely destruct is. I.e. ASIOStop(), ASIODisposeBuffers(), Destruction
+ // Afterwards you initialize the driver again.
+
+ /*FIXME: commented the next line out */
+ //asioDriverInfo.stopped; // In this sample the processing will just stop
+ ret = 1L;
+ break;
+
+ case kAsioResyncRequest:
+ // This informs the application, that the driver encountered some non fatal data loss.
+ // It is used for synchronization purposes of different media.
+ // Added mainly to work around the Win16Mutex problems in Windows 95/98 with the
+ // Windows Multimedia system, which could loose data because the Mutex was hold too long
+ // by another thread.
+ // However a driver can issue it in other situations, too.
+ ret = 1L;
+ break;
+
+ case kAsioLatenciesChanged:
+ // This will inform the host application that the drivers were latencies changed.
+ // Beware, it this does not mean that the buffer sizes have changed!
+ // You might need to update internal delay data.
+ ret = 1L;
+ //printf("kAsioLatenciesChanged \n");
+ break;
+
+ case kAsioEngineVersion:
+ // return the supported ASIO version of the host application
+ // If a host applications does not implement this selector, ASIO 1.0 is assumed
+ // by the driver
+ ret = 2L;
+ break;
+
+ case kAsioSupportsTimeInfo:
+ // informs the driver wether the asioCallbacks.bufferSwitchTimeInfo() callback
+ // is supported.
+ // For compatibility with ASIO 1.0 drivers the host application should always support
+ // the "old" bufferSwitch method, too.
+ ret = 1;
+ break;
+
+ case kAsioSupportsTimeCode:
+ // informs the driver wether application is interested in time code info.
+ // If an application does not need to know about time code, the driver has less work
+ // to do.
+ ret = 0;
+ break;
+ }
+ return ret;
+}
+
+
+static PaError StartStream( PaStream *s )
+{
+ PaError result = paNoError;
+ PaAsioStream *stream = (PaAsioStream*)s;
+ ASIOError asioError;
+
+ if( stream->outputChannelCount > 0 )
+ {
+ ZeroOutputBuffers( stream, 0 );
+ ZeroOutputBuffers( stream, 1 );
+ }
+
+ PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+ stream->stopProcessing = false;
+ stream->zeroOutput = false;
+
+ /* Reentrancy counter initialisation */
+ stream->reenterCount = -1;
+ stream->reenterError = 0;
+
+ stream->callbackFlags = 0;
+
+ if( ResetEvent( stream->completedBuffersPlayedEvent ) == 0 )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_SYSTEM_ERROR( GetLastError() );
+ }
+
+ if( result == paNoError )
+ {
+ theAsioStream = stream;
+ asioError = ASIOStart();
+ if( asioError == ASE_OK )
+ {
+ stream->isActive = 1;
+ stream->streamFinishedCallbackCalled = false;
+ }
+ else
+ {
+ theAsioStream = 0;
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+ }
+ }
+
+ return result;
+}
+
+
+static PaError StopStream( PaStream *s )
+{
+ PaError result = paNoError;
+ PaAsioStream *stream = (PaAsioStream*)s;
+ ASIOError asioError;
+
+ if( stream->isActive )
+ {
+ stream->stopProcessing = true;
+
+ /* wait for the stream to finish playing out enqueued buffers.
+ timeout after four times the stream latency.
+
+ @todo should use a better time out value - if the user buffer
+ length is longer than the asio buffer size then that should
+ be taken into account.
+ */
+ if( WaitForSingleObject( theAsioStream->completedBuffersPlayedEvent,
+ (DWORD)(stream->streamRepresentation.streamInfo.outputLatency * 1000. * 4.) )
+ == WAIT_TIMEOUT )
+ {
+ PA_DEBUG(("WaitForSingleObject() timed out in StopStream()\n" ));
+ }
+ }
+
+ asioError = ASIOStop();
+ if( asioError != ASE_OK )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+ }
+
+ theAsioStream = 0;
+ stream->isActive = 0;
+
+ if( !stream->streamFinishedCallbackCalled )
+ {
+ if( stream->streamRepresentation.streamFinishedCallback != 0 )
+ stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+ }
+
+ return result;
+}
+
+
+static PaError AbortStream( PaStream *s )
+{
+ PaError result = paNoError;
+ PaAsioStream *stream = (PaAsioStream*)s;
+ ASIOError asioError;
+
+ stream->zeroOutput = true;
+
+ asioError = ASIOStop();
+ if( asioError != ASE_OK )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+ }
+ else
+ {
+ // make sure that the callback is not still in-flight when ASIOStop()
+ // returns. This has been observed to happen on the Hoontech DSP24 for
+ // example.
+ int count = 2000; // only wait for 2 seconds, rather than hanging.
+ while( theAsioStream->reenterCount != -1 && count > 0 )
+ {
+ Sleep(1);
+ --count;
+ }
+ }
+
+ /* it is questionable whether we should zero theAsioStream if ASIOStop()
+ returns an error, because the callback could still be active. We assume
+ not - this is based on the fact that ASIOStop is unlikely to fail
+ if the callback is running - it's more likely to fail because the
+ callback is not running. */
+
+ theAsioStream = 0;
+ stream->isActive = 0;
+
+ if( !stream->streamFinishedCallbackCalled )
+ {
+ if( stream->streamRepresentation.streamFinishedCallback != 0 )
+ stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+ }
+
+ return result;
+}
+
+
+static PaError IsStreamStopped( PaStream *s )
+{
+ //PaAsioStream *stream = (PaAsioStream*)s;
+ (void) s; /* unused parameter */
+ return theAsioStream == 0;
+}
+
+
+static PaError IsStreamActive( PaStream *s )
+{
+ PaAsioStream *stream = (PaAsioStream*)s;
+
+ return stream->isActive;
+}
+
+
+static PaTime GetStreamTime( PaStream *s )
+{
+ (void) s; /* unused parameter */
+ return (double)timeGetTime() * .001;
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+ PaAsioStream *stream = (PaAsioStream*)s;
+
+ return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+
+/*
+ As separate stream interfaces are used for blocking and callback
+ streams, the following functions can be guaranteed to only be called
+ for blocking streams.
+*/
+
+static PaError ReadStream( PaStream* s,
+ void *buffer,
+ unsigned long frames )
+{
+ PaAsioStream *stream = (PaAsioStream*)s;
+
+ /* IMPLEMENT ME, see portaudio.h for required behavior*/
+ (void) stream; /* unused parameters */
+ (void) buffer;
+ (void) frames;
+
+ return paNoError;
+}
+
+
+static PaError WriteStream( PaStream* s,
+ const void *buffer,
+ unsigned long frames )
+{
+ PaAsioStream *stream = (PaAsioStream*)s;
+
+ /* IMPLEMENT ME, see portaudio.h for required behavior*/
+ (void) stream; /* unused parameters */
+ (void) buffer;
+ (void) frames;
+
+ return paNoError;
+}
+
+
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+ PaAsioStream *stream = (PaAsioStream*)s;
+
+ /* IMPLEMENT ME, see portaudio.h for required behavior*/
+ (void) stream; /* unused parameter */
+
+ return 0;
+}
+
+
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+ PaAsioStream *stream = (PaAsioStream*)s;
+
+ /* IMPLEMENT ME, see portaudio.h for required behavior*/
+ (void) stream; /* unused parameter */
+
+ return 0;
+}
+
+
+PaError PaAsio_ShowControlPanel( PaDeviceIndex device, void* systemSpecific )
+{
+ PaError result = paNoError;
+ PaUtilHostApiRepresentation *hostApi;
+ PaDeviceIndex hostApiDevice;
+ ASIODriverInfo asioDriverInfo;
+ ASIOError asioError;
+ int asioIsInitialized = 0;
+ PaAsioHostApiRepresentation *asioHostApi;
+ PaAsioDeviceInfo *asioDeviceInfo;
+
+
+ result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
+ if( result != paNoError )
+ goto error;
+
+ result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi );
+ if( result != paNoError )
+ goto error;
+
+ /*
+ In theory we could proceed if the currently open device was the same
+ one for which the control panel was requested, however because the
+ window pointer is not available until this function is called we
+ currently need to call ASIOInit() again here, which of course can't be
+ done safely while a stream is open.
+ */
+
+ asioHostApi = (PaAsioHostApiRepresentation*)hostApi;
+ if( asioHostApi->openAsioDeviceIndex != paNoDevice )
+ {
+ result = paDeviceUnavailable;
+ goto error;
+ }
+
+ asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice];
+
+ if( !loadAsioDriver( const_cast<char*>(asioDeviceInfo->commonDeviceInfo.name) ) )
+ {
+ result = paUnanticipatedHostError;
+ goto error;
+ }
+
+ /* CRUCIAL!!! */
+ memset( &asioDriverInfo, 0, sizeof(ASIODriverInfo) );
+ asioDriverInfo.asioVersion = 2;
+ asioDriverInfo.sysRef = systemSpecific;
+ asioError = ASIOInit( &asioDriverInfo );
+ if( asioError != ASE_OK )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+ goto error;
+ }
+ else
+ {
+ asioIsInitialized = 1;
+ }
+
+PA_DEBUG(("PaAsio_ShowControlPanel: ASIOInit(): %s\n", PaAsio_GetAsioErrorText(asioError) ));
+PA_DEBUG(("asioVersion: ASIOInit(): %ld\n", asioDriverInfo.asioVersion ));
+PA_DEBUG(("driverVersion: ASIOInit(): %ld\n", asioDriverInfo.driverVersion ));
+PA_DEBUG(("Name: ASIOInit(): %s\n", asioDriverInfo.name ));
+PA_DEBUG(("ErrorMessage: ASIOInit(): %s\n", asioDriverInfo.errorMessage ));
+
+ asioError = ASIOControlPanel();
+ if( asioError != ASE_OK )
+ {
+ PA_DEBUG(("PaAsio_ShowControlPanel: ASIOControlPanel(): %s\n", PaAsio_GetAsioErrorText(asioError) ));
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+ goto error;
+ }
+
+PA_DEBUG(("PaAsio_ShowControlPanel: ASIOControlPanel(): %s\n", PaAsio_GetAsioErrorText(asioError) ));
+
+ asioError = ASIOExit();
+ if( asioError != ASE_OK )
+ {
+ result = paUnanticipatedHostError;
+ PA_ASIO_SET_LAST_ASIO_ERROR( asioError );
+ asioIsInitialized = 0;
+ goto error;
+ }
+
+PA_DEBUG(("PaAsio_ShowControlPanel: ASIOExit(): %s\n", PaAsio_GetAsioErrorText(asioError) ));
+
+ return result;
+
+error:
+ if( asioIsInitialized )
+ ASIOExit();
+
+ return result;
+}
+
+
+PaError PaAsio_GetInputChannelName( PaDeviceIndex device, int channelIndex,
+ const char** channelName )
+{
+ PaError result = paNoError;
+ PaUtilHostApiRepresentation *hostApi;
+ PaDeviceIndex hostApiDevice;
+ PaAsioDeviceInfo *asioDeviceInfo;
+
+
+ result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
+ if( result != paNoError )
+ goto error;
+
+ result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi );
+ if( result != paNoError )
+ goto error;
+
+ asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice];
+
+ if( channelIndex < 0 || channelIndex >= asioDeviceInfo->commonDeviceInfo.maxInputChannels ){
+ result = paInvalidChannelCount;
+ goto error;
+ }
+
+ *channelName = asioDeviceInfo->asioChannelInfos[channelIndex].name;
+
+ return paNoError;
+
+error:
+ return result;
+}
+
+
+PaError PaAsio_GetOutputChannelName( PaDeviceIndex device, int channelIndex,
+ const char** channelName )
+{
+ PaError result = paNoError;
+ PaUtilHostApiRepresentation *hostApi;
+ PaDeviceIndex hostApiDevice;
+ PaAsioDeviceInfo *asioDeviceInfo;
+
+
+ result = PaUtil_GetHostApiRepresentation( &hostApi, paASIO );
+ if( result != paNoError )
+ goto error;
+
+ result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice, device, hostApi );
+ if( result != paNoError )
+ goto error;
+
+ asioDeviceInfo = (PaAsioDeviceInfo*)hostApi->deviceInfos[hostApiDevice];
+
+ if( channelIndex < 0 || channelIndex >= asioDeviceInfo->commonDeviceInfo.maxOutputChannels ){
+ result = paInvalidChannelCount;
+ goto error;
+ }
+
+ *channelName = asioDeviceInfo->asioChannelInfos[
+ asioDeviceInfo->commonDeviceInfo.maxInputChannels + channelIndex].name;
+
+ return paNoError;
+
+error:
+ return result;
+}
diff --git a/pd/portaudio/src/hostapi/coreaudio/notes.txt b/pd/portaudio/src/hostapi/coreaudio/notes.txt
new file mode 100644
index 00000000..ffe96962
--- /dev/null
+++ b/pd/portaudio/src/hostapi/coreaudio/notes.txt
@@ -0,0 +1,190 @@
+Notes on status of CoreAudio Implementation of PortAudio
+
+Document Last Updated December 9, 2005
+
+There are currently two implementations of PortAudio for Mac Core Audio.
+
+The original is in pa_mac_core_old.c, and the newer, default implementation
+is in pa_mac_core.c.
+Only pa_mac_core.c is currently developed and supported as it uses apple's
+current core audio technology. To select use the old implementation, replace
+pa_mac_core.c with pa_mac_core_old.c (eg. "cp pa_mac_core_auhal.c
+pa_mac_core.c"), then run configure and make as usual.
+
+-------------------------------------------
+
+Notes on Newer/Default AUHAL implementation:
+
+by Bjorn Roche
+
+Last Updated December 9, 2005
+
+Principle of Operation:
+
+This implementation uses AUHAL for audio I/O. To some extent, it also
+operates at the "HAL" Layer, though this behavior can be limited by
+platform specific flags (see pa_mac_core.h for details). The default
+settings should be reasonable: they don't change the SR of the device and
+don't cause interruptions if other devices are using the device.
+
+Major Software Elements Used: Apple's HAL AUs provide output SR
+conversion transparently, however, only on output, so this
+implementation uses AudioConverters to convert the sample rate on input.
+A PortAudio ring buffer is used to buffer input when sample rate
+conversion is required or when separate audio units are used for duplex
+IO. Finally, a PortAudio buffer processor is used to convert formats and
+provide additional buffers if needed. Internally, interleaved floating
+point data streams are used exclusively - the audio unit converts from
+the audio hardware's native format to interleaved float PCM and
+PortAudio's Buffer processor is used for conversion to user formats.
+
+Simplex Input: Simplex input uses a single callback. If sample rate
+conversion is required, a ring buffer and AudioConverter are used as
+well.
+
+Simplex output: Simplex output uses a single callback. No ring buffer or
+audio converter is used because AUHAL does its own output SR conversion.
+
+Duplex, one device (no SR conversion): When one device is used, a single
+callback is used. This achieves very low latency.
+
+Duplex, separate devices or SR conversion: When SR conversion is
+required, data must be buffered before it is converted and data is not
+always available at the same times on input and output, so SR conversion
+requires the same treatment as separate devices. The input callback
+reads data and puts it in the ring buffer. The output callback reads the
+data off the ring buffer, into an audio converter and finally to the
+buffer processor.
+
+Platform Specific Options:
+
+By using the flags in pa_mac_core.h, the user may specify several options.
+For example, the user can specify the sample-rate conversion quality, and
+the extent to which PA will attempt to "play nice" and to what extent it
+will interrupt other apps to improve performance. For example, if 44100 Hz
+sample rate is requested but the device is set at 48000 Hz, PA can either
+change the device for optimal playback ("Pro" mode), which may interrupt
+other programs playing back audio, or simple use a sample-rate coversion,
+which allows for friendlier sharing of the device ("Play Nice" mode).
+
+Additionally, the user may define a "channel mapping" by calling
+paSetupMacCoreChannelMap() on their stream info structure before opening
+the stream with it. See below for creating a channel map.
+
+Known issues:
+
+- Latency: Latency settings are ignored in most cases. Exceptions are when
+doing I/O between different devices and as a hint for selecting a realtively
+low or relatively high latency in conjunction with
+paHostFramesPerBufferUnspecified. Latency settings are always automatically
+bound to "safe" values, however, so setting extreme values here should not be
+an issue.
+
+- Buffer Size: paHostFramesPerBufferUnspecified and specific host buffer sizes
+are supported. paHostFramesPerBufferUnspecified works best in "pro" mode,
+where the buffer size and sample rate of the audio device is most likely
+to match the expected values.
+
+- Timing info. It reports on stream time, but I'm probably doing something
+wrong since patest_sine_time often reports negative latency numbers. Also,
+there are currently issues with some devices whehn plugging/unplugging
+devices.
+
+- xrun detection: The only xrun detection performed is when reading
+and writing the ring buffer. There is probably more that can be done.
+
+- abort/stop issues: stopping a stream is always a complete operation,
+but latency should be low enough to make the lack of a separate abort
+unnecessary. Apple clarifies its AudioOutputUnitStop() call here:
+http://lists.apple.com/archives/coreaudio-api/2005/Dec/msg00055.html
+
+- blocking interface: should work fine.
+
+- multichannel: It has been tested successfully on multichannel hardware
+from MOTU: traveler and 896HD. Also Presonus firepod and others. It is
+believed to work with all Core Audio devices, including virtual devices
+such as soundflower.
+
+- sample rate conversion quality: By default, SR conversion is the maximum
+available. This can be tweaked using flags pa_mac_core.h. Note that the AU
+render quyality property is used to set the sample rate conversion quality
+as "documented" here:
+http://lists.apple.com/archives/coreaudio-api/2004/Jan/msg00141.html
+
+- x86/Universal Binary: to build a universal binary, be sure to use
+the darwin makefile and not the usual configure && make combo.
+
+
+
+Creating a channel map:
+
+How to create the map array - Text taken From AUHAL.rtfd :
+[3] Channel Maps
+Clients can tell the AUHAL units which channels of the device they are interested in. For example, the client may be processing stereo data, but outputting to a six-channel device. This is done by using the kAudioOutputUnitProperty_ChannelMap property. To use this property:
+
+For Output:
+Create an array of SInt32 that is the size of the number of channels of the device (Get the Format of the AUHAL's output Element == 0)
+Initialize each of the array's values to -1 (-1 indicates that that channel is NOT to be presented in the conversion.)
+
+Next, for each channel of your app's output, set:
+channelMapArray[deviceOutputChannel] = desiredAppOutputChannel.
+
+For example: we have a 6 channel output device and our application has a stereo source it wants to provide to the device. Suppose we want that stereo source to go to the 3rd and 4th channels of the device. The channel map would look like this: { -1, -1, 0, 1, -1, -1 }
+
+Where the formats are:
+Input Element == 0: 2 channels (- client format - settable)
+Output Element == 0: 6 channels (- device format - NOT settable)
+
+So channel 2 (zero-based) of the device will take the first channel of output and channel 3 will take the second channel of output. (This translates to the 3rd and 4th plugs of the 6 output plugs of the device of course!)
+
+For Input:
+Create an array of SInt32 that is the size of the number of channels of the format you require for input. Get (or Set in this case as needed) the AUHAL's output Element == 1.
+
+Next, for each channel of input you require, set:
+channelMapArray[desiredAppInputChannel] = deviceOutputChannel;
+
+For example: we have a 6 channel input device from which we wish to receive stereo input from the 3rd and 4th channels. The channel map looks like this: { 2, 3 }
+
+Where the formats are:
+Input Element == 0: 2 channels (- device format - NOT settable)
+Output Element == 0: 6 channels (- client format - settable)
+
+
+
+----------------------------------------
+
+Notes on Original implementation:
+
+by Phil Burk and Darren Gibbs
+
+Last updated March 20, 2002
+
+WHAT WORKS
+
+Output with very low latency, <10 msec.
+Half duplex input or output.
+Full duplex on the same CoreAudio device.
+The paFLoat32, paInt16, paInt8, paUInt8 sample formats.
+Pa_GetCPULoad()
+Pa_StreamTime()
+
+KNOWN BUGS OR LIMITATIONS
+
+We do not yet support simultaneous input and output on different
+devices. Note that some CoreAudio devices like the Roland UH30 look
+like one device but are actually two different CoreAudio devices. The
+Built-In audio is typically one CoreAudio device.
+
+Mono doesn't work.
+
+DEVICE MAPPING
+
+CoreAudio devices can support both input and output. But the sample
+rates supported may be different. So we have map one or two PortAudio
+device to each CoreAudio device depending on whether it supports
+input, output or both.
+
+When we query devices, we first get a list of CoreAudio devices. Then
+we scan the list and add a PortAudio device for each CoreAudio device
+that supports input. Then we make a scan for output devices.
+
diff --git a/pd/portaudio/src/hostapi/coreaudio/pa_mac_core.c b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core.c
new file mode 100644
index 00000000..7c887bd6
--- /dev/null
+++ b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core.c
@@ -0,0 +1,2238 @@
+/*
+ * Implementation of the PortAudio API for Apple AUHAL
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
+ *
+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,
+ * Gord Peters, Stephane Letz, and Greg Pfiel.
+ *
+ * The following people also deserve acknowledgements:
+ *
+ * Olivier Tristan for feedback and testing
+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
+ * interface.
+ *
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/**
+ @file pa_mac_core
+ @ingroup hostapi_src
+ @author Bjorn Roche
+ @brief AUHAL implementation of PortAudio
+*/
+
+/* FIXME: not all error conditions call PaUtil_SetLastHostErrorInfo()
+ * PaMacCore_SetError() will do this.
+ */
+
+#include "pa_mac_core_internal.h"
+
+#include <string.h> /* strlen(), memcmp() etc. */
+
+#include "pa_mac_core.h"
+#include "pa_mac_core_utilities.h"
+#include "pa_mac_core_blocking.h"
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+/* prototypes for functions declared in this file */
+
+PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+/*
+ * Function declared in pa_mac_core.h. Sets up a PaMacCoreStreamInfoStruct
+ * with the requested flags and initializes channel map.
+ */
+void PaMacCore_SetupStreamInfo( PaMacCoreStreamInfo *data, const unsigned long flags )
+{
+ bzero( data, sizeof( PaMacCoreStreamInfo ) );
+ data->size = sizeof( PaMacCoreStreamInfo );
+ data->hostApiType = paCoreAudio;
+ data->version = 0x01;
+ data->flags = flags;
+ data->channelMap = NULL;
+ data->channelMapSize = 0;
+}
+
+/*
+ * Function declared in pa_mac_core.h. Adds channel mapping to a PaMacCoreStreamInfoStruct
+ */
+void PaMacCore_SetupChannelMap( PaMacCoreStreamInfo *data, const SInt32 * const channelMap, const unsigned long channelMapSize )
+{
+ data->channelMap = channelMap;
+ data->channelMapSize = channelMapSize;
+}
+static char *channelName = NULL;
+static int channelNameSize = 0;
+static bool ensureChannelNameSize( int size )
+{
+ if( size >= channelNameSize ) {
+ free( channelName );
+ channelName = (char *) malloc( ( channelNameSize = size ) + 1 );
+ if( !channelName ) {
+ channelNameSize = 0;
+ return false;
+ }
+ }
+ return true;
+}
+/*
+ * Function declared in pa_mac_core.h. retrives channel names.
+ */
+const char *PaMacCore_GetChannelName( int device, int channelIndex, bool input )
+{
+ struct PaUtilHostApiRepresentation *hostApi;
+ PaError err;
+ OSStatus error;
+ err = PaUtil_GetHostApiRepresentation( &hostApi, paCoreAudio );
+ assert(err == paNoError);
+ PaMacAUHAL *macCoreHostApi = (PaMacAUHAL*)hostApi;
+ AudioDeviceID hostApiDevice = macCoreHostApi->devIds[device];
+
+ UInt32 size = 0;
+
+ error = AudioDeviceGetPropertyInfo( hostApiDevice,
+ channelIndex + 1,
+ input,
+ kAudioDevicePropertyChannelName,
+ &size,
+ NULL );
+ if( error ) {
+ //try the CFString
+ CFStringRef name;
+ bool isDeviceName = false;
+ size = sizeof( name );
+ error = AudioDeviceGetProperty( hostApiDevice,
+ channelIndex + 1,
+ input,
+ kAudioDevicePropertyChannelNameCFString,
+ &size,
+ &name );
+ if( error ) { //as a last-ditch effort, get the device name. Later we'll append the channel number.
+ size = sizeof( name );
+ error = AudioDeviceGetProperty( hostApiDevice,
+ channelIndex + 1,
+ input,
+ kAudioDevicePropertyDeviceNameCFString,
+ &size,
+ &name );
+ if( error )
+ return NULL;
+ isDeviceName = true;
+ }
+ if( isDeviceName ) {
+ name = CFStringCreateWithFormat( NULL, NULL, CFSTR( "%@: %d"), name, channelIndex + 1 );
+ }
+
+ CFIndex length = CFStringGetLength(name);
+ while( ensureChannelNameSize( length * sizeof(UniChar) + 1 ) ) {
+ if( CFStringGetCString( name, channelName, channelNameSize, kCFStringEncodingUTF8 ) ) {
+ if( isDeviceName )
+ CFRelease( name );
+ return channelName;
+ }
+ if( length == 0 )
+ ++length;
+ length *= 2;
+ }
+ if( isDeviceName )
+ CFRelease( name );
+ return NULL;
+ }
+
+ //continue with C string:
+ if( !ensureChannelNameSize( size ) )
+ return NULL;
+
+ error = AudioDeviceGetProperty( hostApiDevice,
+ channelIndex + 1,
+ input,
+ kAudioDevicePropertyChannelName,
+ &size,
+ channelName );
+
+ if( error ) {
+ ERR( error );
+ return NULL;
+ }
+ return channelName;
+}
+
+
+
+
+
+AudioDeviceID PaMacCore_GetStreamInputDevice( PaStream* s )
+{
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+ VVDBUG(("PaMacCore_GetStreamInputHandle()\n"));
+
+ return ( stream->inputDevice );
+}
+
+AudioDeviceID PaMacCore_GetStreamOutputDevice( PaStream* s )
+{
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+ VVDBUG(("PaMacCore_GetStreamOutputHandle()\n"));
+
+ return ( stream->outputDevice );
+}
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#define RING_BUFFER_ADVANCE_DENOMINATOR (4)
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+ PaStream** s,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate,
+ unsigned long framesPerBuffer,
+ PaStreamFlags streamFlags,
+ PaStreamCallback *streamCallback,
+ void *userData );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static void setStreamStartTime( PaStream *stream );
+static OSStatus AudioIOProc( void *inRefCon,
+ AudioUnitRenderActionFlags *ioActionFlags,
+ const AudioTimeStamp *inTimeStamp,
+ UInt32 inBusNumber,
+ UInt32 inNumberFrames,
+ AudioBufferList *ioData );
+static double GetStreamCpuLoad( PaStream* stream );
+
+static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi,
+ PaDeviceInfo *deviceInfo,
+ AudioDeviceID macCoreDeviceId,
+ int isInput);
+
+static PaError OpenAndSetupOneAudioUnit(
+ const PaStreamParameters *inStreamParams,
+ const PaStreamParameters *outStreamParams,
+ const unsigned long requestedFramesPerBuffer,
+ unsigned long *actualInputFramesPerBuffer,
+ unsigned long *actualOutputFramesPerBuffer,
+ const PaMacAUHAL *auhalHostApi,
+ AudioUnit *audioUnit,
+ AudioConverterRef *srConverter,
+ AudioDeviceID *audioDevice,
+ const double sampleRate,
+ void *refCon );
+
+/* for setting errors. */
+#define PA_AUHAL_SET_LAST_HOST_ERROR( errorCode, errorText ) \
+ PaUtil_SetLastHostErrorInfo( paInDevelopment, errorCode, errorText )
+
+/*currently, this is only used in initialization, but it might be modified
+ to be used when the list of devices changes.*/
+static PaError gatherDeviceInfo(PaMacAUHAL *auhalHostApi)
+{
+ UInt32 size;
+ UInt32 propsize;
+ VVDBUG(("gatherDeviceInfo()\n"));
+ /* -- free any previous allocations -- */
+ if( auhalHostApi->devIds )
+ PaUtil_GroupFreeMemory(auhalHostApi->allocations, auhalHostApi->devIds);
+ auhalHostApi->devIds = NULL;
+
+ /* -- figure out how many devices there are -- */
+ AudioHardwareGetPropertyInfo( kAudioHardwarePropertyDevices,
+ &propsize,
+ NULL );
+ auhalHostApi->devCount = propsize / sizeof( AudioDeviceID );
+
+ VDBUG( ( "Found %ld device(s).\n", auhalHostApi->devCount ) );
+
+ /* -- copy the device IDs -- */
+ auhalHostApi->devIds = (AudioDeviceID *)PaUtil_GroupAllocateMemory(
+ auhalHostApi->allocations,
+ propsize );
+ if( !auhalHostApi->devIds )
+ return paInsufficientMemory;
+ AudioHardwareGetProperty( kAudioHardwarePropertyDevices,
+ &propsize,
+ auhalHostApi->devIds );
+#ifdef MAC_CORE_VERBOSE_DEBUG
+ {
+ int i;
+ for( i=0; i<auhalHostApi->devCount; ++i )
+ printf( "Device %d\t: %ld\n", i, auhalHostApi->devIds[i] );
+ }
+#endif
+
+ size = sizeof(AudioDeviceID);
+ auhalHostApi->defaultIn = kAudioDeviceUnknown;
+ auhalHostApi->defaultOut = kAudioDeviceUnknown;
+
+ /* determine the default device. */
+ /* I am not sure how these calls to AudioHardwareGetProperty()
+ could fail, but in case they do, we use the first available
+ device as the default. */
+ if( 0 != AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice,
+ &size,
+ &auhalHostApi->defaultIn) ) {
+ int i;
+ auhalHostApi->defaultIn = kAudioDeviceUnknown;
+ VDBUG(("Failed to get default input device from OS."));
+ VDBUG((" I will substitute the first available input Device."));
+ for( i=0; i<auhalHostApi->devCount; ++i ) {
+ PaDeviceInfo devInfo;
+ if( 0 != GetChannelInfo( auhalHostApi, &devInfo,
+ auhalHostApi->devIds[i], TRUE ) )
+ if( devInfo.maxInputChannels ) {
+ auhalHostApi->defaultIn = auhalHostApi->devIds[i];
+ break;
+ }
+ }
+ }
+ if( 0 != AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
+ &size,
+ &auhalHostApi->defaultOut) ) {
+ int i;
+ auhalHostApi->defaultIn = kAudioDeviceUnknown;
+ VDBUG(("Failed to get default output device from OS."));
+ VDBUG((" I will substitute the first available output Device."));
+ for( i=0; i<auhalHostApi->devCount; ++i ) {
+ PaDeviceInfo devInfo;
+ if( 0 != GetChannelInfo( auhalHostApi, &devInfo,
+ auhalHostApi->devIds[i], FALSE ) )
+ if( devInfo.maxOutputChannels ) {
+ auhalHostApi->defaultOut = auhalHostApi->devIds[i];
+ break;
+ }
+ }
+ }
+
+ VDBUG( ( "Default in : %ld\n", auhalHostApi->defaultIn ) );
+ VDBUG( ( "Default out: %ld\n", auhalHostApi->defaultOut ) );
+
+ return paNoError;
+}
+
+static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi,
+ PaDeviceInfo *deviceInfo,
+ AudioDeviceID macCoreDeviceId,
+ int isInput)
+{
+ UInt32 propSize;
+ PaError err = paNoError;
+ UInt32 i;
+ int numChannels = 0;
+ AudioBufferList *buflist = NULL;
+ UInt32 frameLatency;
+
+ VVDBUG(("GetChannelInfo()\n"));
+
+ /* Get the number of channels from the stream configuration.
+ Fail if we can't get this. */
+
+ err = ERR(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, NULL));
+ if (err)
+ return err;
+
+ buflist = PaUtil_AllocateMemory(propSize);
+ if( !buflist )
+ return paInsufficientMemory;
+ err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, buflist));
+ if (err)
+ goto error;
+
+ for (i = 0; i < buflist->mNumberBuffers; ++i)
+ numChannels += buflist->mBuffers[i].mNumberChannels;
+
+ if (isInput)
+ deviceInfo->maxInputChannels = numChannels;
+ else
+ deviceInfo->maxOutputChannels = numChannels;
+
+ if (numChannels > 0) /* do not try to retrieve the latency if there is no channels. */
+ {
+ /* Get the latency. Don't fail if we can't get this. */
+ /* default to something reasonable */
+ deviceInfo->defaultLowInputLatency = .01;
+ deviceInfo->defaultHighInputLatency = .10;
+ deviceInfo->defaultLowOutputLatency = .01;
+ deviceInfo->defaultHighOutputLatency = .10;
+ propSize = sizeof(UInt32);
+ err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &frameLatency));
+ if (!err)
+ {
+ /** FEEDBACK:
+ * This code was arrived at by trial and error, and some extentive, but not exhaustive
+ * testing. Sebastien Beaulieu <seb@plogue.com> has suggested using
+ * kAudioDevicePropertyLatency + kAudioDevicePropertySafetyOffset + buffer size instead.
+ * At the time this code was written, many users were reporting dropouts with audio
+ * programs that probably used this formula. This was probably
+ * around 10.4.4, and the problem is probably fixed now. So perhaps
+ * his formula should be reviewed and used.
+ * */
+ double secondLatency = frameLatency / deviceInfo->defaultSampleRate;
+ if (isInput)
+ {
+ deviceInfo->defaultLowInputLatency = 3 * secondLatency;
+ deviceInfo->defaultHighInputLatency = 3 * 10 * secondLatency;
+ }
+ else
+ {
+ deviceInfo->defaultLowOutputLatency = 3 * secondLatency;
+ deviceInfo->defaultHighOutputLatency = 3 * 10 * secondLatency;
+ }
+ }
+ }
+ PaUtil_FreeMemory( buflist );
+ return paNoError;
+ error:
+ PaUtil_FreeMemory( buflist );
+ return err;
+}
+
+static PaError InitializeDeviceInfo( PaMacAUHAL *auhalHostApi,
+ PaDeviceInfo *deviceInfo,
+ AudioDeviceID macCoreDeviceId,
+ PaHostApiIndex hostApiIndex )
+{
+ Float64 sampleRate;
+ char *name;
+ PaError err = paNoError;
+ UInt32 propSize;
+
+ VVDBUG(("InitializeDeviceInfo(): macCoreDeviceId=%ld\n", macCoreDeviceId));
+
+ memset(deviceInfo, 0, sizeof(deviceInfo));
+
+ deviceInfo->structVersion = 2;
+ deviceInfo->hostApi = hostApiIndex;
+
+ /* Get the device name. Fail if we can't get it. */
+ err = ERR(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL));
+ if (err)
+ return err;
+
+ name = PaUtil_GroupAllocateMemory(auhalHostApi->allocations,propSize);
+ if ( !name )
+ return paInsufficientMemory;
+ err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, name));
+ if (err)
+ return err;
+ deviceInfo->name = name;
+
+ /* Try to get the default sample rate. Don't fail if we can't get this. */
+ propSize = sizeof(Float64);
+ err = ERR(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &sampleRate));
+ if (err)
+ deviceInfo->defaultSampleRate = 0.0;
+ else
+ deviceInfo->defaultSampleRate = sampleRate;
+
+ /* Get the maximum number of input and output channels. Fail if we can't get this. */
+
+ err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 1);
+ if (err)
+ return err;
+
+ err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 0);
+ if (err)
+ return err;
+
+ return paNoError;
+}
+
+PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+ PaError result = paNoError;
+ int i;
+ PaMacAUHAL *auhalHostApi;
+ PaDeviceInfo *deviceInfoArray;
+
+ VVDBUG(("PaMacCore_Initialize(): hostApiIndex=%d\n", hostApiIndex));
+
+ auhalHostApi = (PaMacAUHAL*)PaUtil_AllocateMemory( sizeof(PaMacAUHAL) );
+ if( !auhalHostApi )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ auhalHostApi->allocations = PaUtil_CreateAllocationGroup();
+ if( !auhalHostApi->allocations )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ auhalHostApi->devIds = NULL;
+ auhalHostApi->devCount = 0;
+
+ /* get the info we need about the devices */
+ result = gatherDeviceInfo( auhalHostApi );
+ if( result != paNoError )
+ goto error;
+
+ *hostApi = &auhalHostApi->inheritedHostApiRep;
+ (*hostApi)->info.structVersion = 1;
+ (*hostApi)->info.type = paCoreAudio;
+ (*hostApi)->info.name = "Core Audio";
+
+ (*hostApi)->info.defaultInputDevice = paNoDevice;
+ (*hostApi)->info.defaultOutputDevice = paNoDevice;
+
+ (*hostApi)->info.deviceCount = 0;
+
+ if( auhalHostApi->devCount > 0 )
+ {
+ (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+ auhalHostApi->allocations, sizeof(PaDeviceInfo*) * auhalHostApi->devCount);
+ if( !(*hostApi)->deviceInfos )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ /* allocate all device info structs in a contiguous block */
+ deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory(
+ auhalHostApi->allocations, sizeof(PaDeviceInfo) * auhalHostApi->devCount );
+ if( !deviceInfoArray )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ for( i=0; i < auhalHostApi->devCount; ++i )
+ {
+ int err;
+ err = InitializeDeviceInfo( auhalHostApi, &deviceInfoArray[i],
+ auhalHostApi->devIds[i],
+ hostApiIndex );
+ if (err == paNoError)
+ { /* copy some info and set the defaults */
+ (*hostApi)->deviceInfos[(*hostApi)->info.deviceCount] = &deviceInfoArray[i];
+ if (auhalHostApi->devIds[i] == auhalHostApi->defaultIn)
+ (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
+ if (auhalHostApi->devIds[i] == auhalHostApi->defaultOut)
+ (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
+ (*hostApi)->info.deviceCount++;
+ }
+ else
+ { /* there was an error. we need to shift the devices down, so we ignore this one */
+ int j;
+ auhalHostApi->devCount--;
+ for( j=i; j<auhalHostApi->devCount; ++j )
+ auhalHostApi->devIds[j] = auhalHostApi->devIds[j+1];
+ i--;
+ }
+ }
+ }
+
+ (*hostApi)->Terminate = Terminate;
+ (*hostApi)->OpenStream = OpenStream;
+ (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+ PaUtil_InitializeStreamInterface( &auhalHostApi->callbackStreamInterface,
+ CloseStream, StartStream,
+ StopStream, AbortStream, IsStreamStopped,
+ IsStreamActive,
+ GetStreamTime, GetStreamCpuLoad,
+ PaUtil_DummyRead, PaUtil_DummyWrite,
+ PaUtil_DummyGetReadAvailable,
+ PaUtil_DummyGetWriteAvailable );
+
+ PaUtil_InitializeStreamInterface( &auhalHostApi->blockingStreamInterface,
+ CloseStream, StartStream,
+ StopStream, AbortStream, IsStreamStopped,
+ IsStreamActive,
+ GetStreamTime, PaUtil_DummyGetCpuLoad,
+ ReadStream, WriteStream,
+ GetStreamReadAvailable,
+ GetStreamWriteAvailable );
+
+ return result;
+
+error:
+ if( auhalHostApi )
+ {
+ if( auhalHostApi->allocations )
+ {
+ PaUtil_FreeAllAllocations( auhalHostApi->allocations );
+ PaUtil_DestroyAllocationGroup( auhalHostApi->allocations );
+ }
+
+ PaUtil_FreeMemory( auhalHostApi );
+ }
+ return result;
+}
+
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+ PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi;
+
+ VVDBUG(("Terminate()\n"));
+
+ /*
+ IMPLEMENT ME:
+ - clean up any resources not handled by the allocation group
+ TODO: Double check that everything is handled by alloc group
+ */
+
+ if( auhalHostApi->allocations )
+ {
+ PaUtil_FreeAllAllocations( auhalHostApi->allocations );
+ PaUtil_DestroyAllocationGroup( auhalHostApi->allocations );
+ }
+
+ PaUtil_FreeMemory( auhalHostApi );
+}
+
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate )
+{
+ int inputChannelCount, outputChannelCount;
+ PaSampleFormat inputSampleFormat, outputSampleFormat;
+
+ VVDBUG(("IsFormatSupported(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld sampleRate=%g\n",
+ inputParameters ? inputParameters->channelCount : -1,
+ inputParameters ? inputParameters->sampleFormat : -1,
+ outputParameters ? outputParameters->channelCount : -1,
+ outputParameters ? outputParameters->sampleFormat : -1,
+ (float) sampleRate ));
+
+ /** These first checks are standard PA checks. We do some fancier checks
+ later. */
+ if( inputParameters )
+ {
+ inputChannelCount = inputParameters->channelCount;
+ inputSampleFormat = inputParameters->sampleFormat;
+
+ /* all standard sample formats are supported by the buffer adapter,
+ this implementation doesn't support any custom sample formats */
+ if( inputSampleFormat & paCustomFormat )
+ return paSampleFormatNotSupported;
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+
+ if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ /* check that input device can support inputChannelCount */
+ if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+ return paInvalidChannelCount;
+ }
+ else
+ {
+ inputChannelCount = 0;
+ }
+
+ if( outputParameters )
+ {
+ outputChannelCount = outputParameters->channelCount;
+ outputSampleFormat = outputParameters->sampleFormat;
+
+ /* all standard sample formats are supported by the buffer adapter,
+ this implementation doesn't support any custom sample formats */
+ if( outputSampleFormat & paCustomFormat )
+ return paSampleFormatNotSupported;
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+
+ if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ /* check that output device can support outputChannelCount */
+ if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+ return paInvalidChannelCount;
+
+ }
+ else
+ {
+ outputChannelCount = 0;
+ }
+
+ /* FEEDBACK */
+ /* I think the only way to check a given format SR combo is */
+ /* to try opening it. This could be disruptive, is that Okay? */
+ /* The alternative is to just read off available sample rates, */
+ /* but this will not work %100 of the time (eg, a device that */
+ /* supports N output at one rate but only N/2 at a higher rate.)*/
+
+ /* The following code opens the device with the requested parameters to
+ see if it works. */
+ {
+ PaError err;
+ PaStream *s;
+ err = OpenStream( hostApi, &s, inputParameters, outputParameters,
+ sampleRate, 1024, 0, (PaStreamCallback *)1, NULL );
+ if( err != paNoError && err != paInvalidSampleRate )
+ DBUG( ( "OpenStream @ %g returned: %d: %s\n",
+ (float) sampleRate, err, Pa_GetErrorText( err ) ) );
+ if( err )
+ return err;
+ err = CloseStream( s );
+ if( err ) {
+ /* FEEDBACK: is this more serious? should we assert? */
+ DBUG( ( "WARNING: could not close Stream. %d: %s\n",
+ err, Pa_GetErrorText( err ) ) );
+ }
+ }
+
+ return paFormatIsSupported;
+}
+
+static PaError OpenAndSetupOneAudioUnit(
+ const PaStreamParameters *inStreamParams,
+ const PaStreamParameters *outStreamParams,
+ const unsigned long requestedFramesPerBuffer,
+ unsigned long *actualInputFramesPerBuffer,
+ unsigned long *actualOutputFramesPerBuffer,
+ const PaMacAUHAL *auhalHostApi,
+ AudioUnit *audioUnit,
+ AudioConverterRef *srConverter,
+ AudioDeviceID *audioDevice,
+ const double sampleRate,
+ void *refCon )
+{
+ ComponentDescription desc;
+ Component comp;
+ /*An Apple TN suggests using CAStreamBasicDescription, but that is C++*/
+ AudioStreamBasicDescription desiredFormat;
+ OSErr result = noErr;
+ PaError paResult = paNoError;
+ int line = 0;
+ UInt32 callbackKey;
+ AURenderCallbackStruct rcbs;
+ unsigned long macInputStreamFlags = paMacCorePlayNice;
+ unsigned long macOutputStreamFlags = paMacCorePlayNice;
+ SInt32 const *inChannelMap = NULL;
+ SInt32 const *outChannelMap = NULL;
+ unsigned long inChannelMapSize = 0;
+ unsigned long outChannelMapSize = 0;
+
+ VVDBUG(("OpenAndSetupOneAudioUnit(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld, requestedFramesPerBuffer=%ld\n",
+ inStreamParams ? inStreamParams->channelCount : -1,
+ inStreamParams ? inStreamParams->sampleFormat : -1,
+ outStreamParams ? outStreamParams->channelCount : -1,
+ outStreamParams ? outStreamParams->sampleFormat : -1,
+ requestedFramesPerBuffer ));
+
+ /* -- handle the degenerate case -- */
+ if( !inStreamParams && !outStreamParams ) {
+ *audioUnit = NULL;
+ *audioDevice = kAudioDeviceUnknown;
+ return paNoError;
+ }
+
+ /* -- get the user's api specific info, if they set any -- */
+ if( inStreamParams && inStreamParams->hostApiSpecificStreamInfo )
+ {
+ macInputStreamFlags=
+ ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)
+ ->flags;
+ inChannelMap = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)
+ ->channelMap;
+ inChannelMapSize = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)
+ ->channelMapSize;
+ }
+ if( outStreamParams && outStreamParams->hostApiSpecificStreamInfo )
+ {
+ macOutputStreamFlags=
+ ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)
+ ->flags;
+ outChannelMap = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)
+ ->channelMap;
+ outChannelMapSize = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)
+ ->channelMapSize;
+ }
+ /* Override user's flags here, if desired for testing. */
+
+ /*
+ * The HAL AU is a Mac OS style "component".
+ * the first few steps deal with that.
+ * Later steps work on a combination of Mac OS
+ * components and the slightly lower level
+ * HAL.
+ */
+
+ /* -- describe the output type AudioUnit -- */
+ /* Note: for the default AudioUnit, we could use the
+ * componentSubType value kAudioUnitSubType_DefaultOutput;
+ * but I don't think that's relevant here.
+ */
+ desc.componentType = kAudioUnitType_Output;
+ desc.componentSubType = kAudioUnitSubType_HALOutput;
+ desc.componentManufacturer = kAudioUnitManufacturer_Apple;
+ desc.componentFlags = 0;
+ desc.componentFlagsMask = 0;
+ /* -- find the component -- */
+ comp = FindNextComponent( NULL, &desc );
+ if( !comp )
+ {
+ DBUG( ( "AUHAL component not found." ) );
+ *audioUnit = NULL;
+ *audioDevice = kAudioDeviceUnknown;
+ return paUnanticipatedHostError;
+ }
+ /* -- open it -- */
+ result = OpenAComponent( comp, audioUnit );
+ if( result )
+ {
+ DBUG( ( "Failed to open AUHAL component." ) );
+ *audioUnit = NULL;
+ *audioDevice = kAudioDeviceUnknown;
+ return ERR( result );
+ }
+ /* -- prepare a little error handling logic / hackery -- */
+#define ERR_WRAP(mac_err) do { result = mac_err ; line = __LINE__ ; if ( result != noErr ) goto error ; } while(0)
+
+ /* -- if there is input, we have to explicitly enable input -- */
+ if( inStreamParams )
+ {
+ UInt32 enableIO = 1;
+ ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+ kAudioOutputUnitProperty_EnableIO,
+ kAudioUnitScope_Input,
+ INPUT_ELEMENT,
+ &enableIO,
+ sizeof(enableIO) ) );
+ }
+ /* -- if there is no output, we must explicitly disable output -- */
+ if( !outStreamParams )
+ {
+ UInt32 enableIO = 0;
+ ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+ kAudioOutputUnitProperty_EnableIO,
+ kAudioUnitScope_Output,
+ OUTPUT_ELEMENT,
+ &enableIO,
+ sizeof(enableIO) ) );
+ }
+
+ /* -- set the devices -- */
+ /* make sure input and output are the same device if we are doing input and
+ output. */
+ if( inStreamParams && outStreamParams )
+ {
+ assert( outStreamParams->device == inStreamParams->device );
+ }
+ if( inStreamParams )
+ {
+ *audioDevice = auhalHostApi->devIds[inStreamParams->device] ;
+ ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+ kAudioOutputUnitProperty_CurrentDevice,
+ kAudioUnitScope_Global,
+ INPUT_ELEMENT,
+ audioDevice,
+ sizeof(AudioDeviceID) ) );
+ }
+ if( outStreamParams )
+ {
+ *audioDevice = auhalHostApi->devIds[outStreamParams->device] ;
+ ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+ kAudioOutputUnitProperty_CurrentDevice,
+ kAudioUnitScope_Global,
+ OUTPUT_ELEMENT,
+ audioDevice,
+ sizeof(AudioDeviceID) ) );
+ }
+
+ /* -- set format -- */
+ bzero( &desiredFormat, sizeof(desiredFormat) );
+ desiredFormat.mFormatID = kAudioFormatLinearPCM ;
+ desiredFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
+ desiredFormat.mFramesPerPacket = 1;
+ desiredFormat.mBitsPerChannel = sizeof( float ) * 8;
+
+ result = 0;
+ /* set device format first, but only touch the device if the user asked */
+ if( inStreamParams ) {
+ /*The callback never calls back if we don't set the FPB */
+ /*This seems wierd, because I would think setting anything on the device
+ would be disruptive.*/
+ paResult = setBestFramesPerBuffer( *audioDevice, FALSE,
+ requestedFramesPerBuffer,
+ actualInputFramesPerBuffer );
+ if( paResult ) goto error;
+ if( macInputStreamFlags & paMacCoreChangeDeviceParameters ) {
+ bool requireExact;
+ requireExact=macInputStreamFlags & paMacCoreFailIfConversionRequired;
+ paResult = setBestSampleRateForDevice( *audioDevice, FALSE,
+ requireExact, sampleRate );
+ if( paResult ) goto error;
+ }
+ if( actualInputFramesPerBuffer && actualOutputFramesPerBuffer )
+ *actualOutputFramesPerBuffer = *actualInputFramesPerBuffer ;
+ }
+ if( outStreamParams && !inStreamParams ) {
+ /*The callback never calls back if we don't set the FPB */
+ /*This seems wierd, because I would think setting anything on the device
+ would be disruptive.*/
+ paResult = setBestFramesPerBuffer( *audioDevice, TRUE,
+ requestedFramesPerBuffer,
+ actualOutputFramesPerBuffer );
+ if( paResult ) goto error;
+ if( macOutputStreamFlags & paMacCoreChangeDeviceParameters ) {
+ bool requireExact;
+ requireExact=macOutputStreamFlags & paMacCoreFailIfConversionRequired;
+ paResult = setBestSampleRateForDevice( *audioDevice, TRUE,
+ requireExact, sampleRate );
+ if( paResult ) goto error;
+ }
+ }
+
+ /* -- set the quality of the output converter -- */
+ if( outStreamParams ) {
+ UInt32 value = kAudioConverterQuality_Max;
+ switch( macOutputStreamFlags & 0x0700 ) {
+ case 0x0100: /*paMacCore_ConversionQualityMin:*/
+ value=kRenderQuality_Min;
+ break;
+ case 0x0200: /*paMacCore_ConversionQualityLow:*/
+ value=kRenderQuality_Low;
+ break;
+ case 0x0300: /*paMacCore_ConversionQualityMedium:*/
+ value=kRenderQuality_Medium;
+ break;
+ case 0x0400: /*paMacCore_ConversionQualityHigh:*/
+ value=kRenderQuality_High;
+ break;
+ }
+ ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+ kAudioUnitProperty_RenderQuality,
+ kAudioUnitScope_Global,
+ OUTPUT_ELEMENT,
+ &value,
+ sizeof(value) ) );
+ }
+ /* now set the format on the Audio Units. */
+ if( outStreamParams )
+ {
+ desiredFormat.mSampleRate =sampleRate;
+ desiredFormat.mBytesPerPacket=sizeof(float)*outStreamParams->channelCount;
+ desiredFormat.mBytesPerFrame =sizeof(float)*outStreamParams->channelCount;
+ desiredFormat.mChannelsPerFrame = outStreamParams->channelCount;
+ ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+ kAudioUnitProperty_StreamFormat,
+ kAudioUnitScope_Input,
+ OUTPUT_ELEMENT,
+ &desiredFormat,
+ sizeof(AudioStreamBasicDescription) ) );
+ }
+ if( inStreamParams )
+ {
+ AudioStreamBasicDescription sourceFormat;
+ UInt32 size = sizeof( AudioStreamBasicDescription );
+
+ /* keep the sample rate of the device, or we confuse AUHAL */
+ ERR_WRAP( AudioUnitGetProperty( *audioUnit,
+ kAudioUnitProperty_StreamFormat,
+ kAudioUnitScope_Input,
+ INPUT_ELEMENT,
+ &sourceFormat,
+ &size ) );
+ desiredFormat.mSampleRate = sourceFormat.mSampleRate;
+ desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount;
+ desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount;
+ desiredFormat.mChannelsPerFrame = inStreamParams->channelCount;
+ ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+ kAudioUnitProperty_StreamFormat,
+ kAudioUnitScope_Output,
+ INPUT_ELEMENT,
+ &desiredFormat,
+ sizeof(AudioStreamBasicDescription) ) );
+ }
+ /* set the maximumFramesPerSlice */
+ /* not doing this causes real problems
+ (eg. the callback might not be called). The idea of setting both this
+ and the frames per buffer on the device is that we'll be most likely
+ to actually get the frame size we requested in the callback with the
+ minimum latency. */
+ if( outStreamParams ) {
+ UInt32 size = sizeof( *actualOutputFramesPerBuffer );
+ ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+ kAudioUnitProperty_MaximumFramesPerSlice,
+ kAudioUnitScope_Input,
+ OUTPUT_ELEMENT,
+ actualOutputFramesPerBuffer,
+ sizeof(unsigned long) ) );
+ ERR_WRAP( AudioUnitGetProperty( *audioUnit,
+ kAudioUnitProperty_MaximumFramesPerSlice,
+ kAudioUnitScope_Global,
+ OUTPUT_ELEMENT,
+ actualOutputFramesPerBuffer,
+ &size ) );
+ }
+ if( inStreamParams ) {
+ /*UInt32 size = sizeof( *actualInputFramesPerBuffer );*/
+ ERR_WRAP( AudioUnitSetProperty( *audioUnit,
+ kAudioUnitProperty_MaximumFramesPerSlice,
+ kAudioUnitScope_Output,
+ INPUT_ELEMENT,
+ actualInputFramesPerBuffer,
+ sizeof(unsigned long) ) );
+/* Don't know why this causes problems
+ ERR_WRAP( AudioUnitGetProperty( *audioUnit,
+ kAudioUnitProperty_MaximumFramesPerSlice,
+ kAudioUnitScope_Global, //Output,
+ INPUT_ELEMENT,
+ actualInputFramesPerBuffer,
+ &size ) );
+*/
+ }
+
+ /* -- if we have input, we may need to setup an SR converter -- */
+ /* even if we got the sample rate we asked for, we need to do
+ the conversion in case another program changes the underlying SR. */
+ /* FIXME: I think we need to monitor stream and change the converter if the incoming format changes. */
+ if( inStreamParams ) {
+ AudioStreamBasicDescription desiredFormat;
+ AudioStreamBasicDescription sourceFormat;
+ UInt32 sourceSize = sizeof( sourceFormat );
+ bzero( &desiredFormat, sizeof(desiredFormat) );
+ desiredFormat.mSampleRate = sampleRate;
+ desiredFormat.mFormatID = kAudioFormatLinearPCM ;
+ desiredFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
+ desiredFormat.mFramesPerPacket = 1;
+ desiredFormat.mBitsPerChannel = sizeof( float ) * 8;
+ desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount;
+ desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount;
+ desiredFormat.mChannelsPerFrame = inStreamParams->channelCount;
+
+ /* get the source format */
+ ERR_WRAP( AudioUnitGetProperty(
+ *audioUnit,
+ kAudioUnitProperty_StreamFormat,
+ kAudioUnitScope_Output,
+ INPUT_ELEMENT,
+ &sourceFormat,
+ &sourceSize ) );
+
+ if( desiredFormat.mSampleRate != sourceFormat.mSampleRate )
+ {
+ UInt32 value = kAudioConverterQuality_Max;
+ switch( macInputStreamFlags & 0x0700 ) {
+ case 0x0100: /*paMacCore_ConversionQualityMin:*/
+ value=kAudioConverterQuality_Min;
+ break;
+ case 0x0200: /*paMacCore_ConversionQualityLow:*/
+ value=kAudioConverterQuality_Low;
+ break;
+ case 0x0300: /*paMacCore_ConversionQualityMedium:*/
+ value=kAudioConverterQuality_Medium;
+ break;
+ case 0x0400: /*paMacCore_ConversionQualityHigh:*/
+ value=kAudioConverterQuality_High;
+ break;
+ }
+ VDBUG(( "Creating sample rate converter for input"
+ " to convert from %g to %g\n",
+ (float)sourceFormat.mSampleRate,
+ (float)desiredFormat.mSampleRate ) );
+ /* create our converter */
+ ERR_WRAP( AudioConverterNew(
+ &sourceFormat,
+ &desiredFormat,
+ srConverter ) );
+ /* Set quality */
+ ERR_WRAP( AudioConverterSetProperty(
+ *srConverter,
+ kAudioConverterSampleRateConverterQuality,
+ sizeof( value ),
+ &value ) );
+ }
+ }
+ /* -- set IOProc (callback) -- */
+ callbackKey = outStreamParams ? kAudioUnitProperty_SetRenderCallback
+ : kAudioOutputUnitProperty_SetInputCallback ;
+ rcbs.inputProc = AudioIOProc;
+ rcbs.inputProcRefCon = refCon;
+ ERR_WRAP( AudioUnitSetProperty(
+ *audioUnit,
+ callbackKey,
+ kAudioUnitScope_Output,
+ outStreamParams ? OUTPUT_ELEMENT : INPUT_ELEMENT,
+ &rcbs,
+ sizeof(rcbs)) );
+
+ if( inStreamParams && outStreamParams && *srConverter )
+ ERR_WRAP( AudioUnitSetProperty(
+ *audioUnit,
+ kAudioOutputUnitProperty_SetInputCallback,
+ kAudioUnitScope_Output,
+ INPUT_ELEMENT,
+ &rcbs,
+ sizeof(rcbs)) );
+
+ /* channel mapping. */
+ if(inChannelMap)
+ {
+ UInt32 mapSize = inChannelMapSize *sizeof(SInt32);
+
+ //for each channel of desired input, map the channel from
+ //the device's output channel.
+ ERR_WRAP( AudioUnitSetProperty(*audioUnit,
+ kAudioOutputUnitProperty_ChannelMap,
+ kAudioUnitScope_Output,
+ INPUT_ELEMENT,
+ inChannelMap,
+ mapSize));
+ }
+ if(outChannelMap)
+ {
+ UInt32 mapSize = outChannelMapSize *sizeof(SInt32);
+
+ //for each channel of desired output, map the channel from
+ //the device's output channel.
+ ERR_WRAP(AudioUnitSetProperty(*audioUnit,
+ kAudioOutputUnitProperty_ChannelMap,
+ kAudioUnitScope_Output,
+ OUTPUT_ELEMENT,
+ outChannelMap,
+ mapSize));
+ }
+ /* initialize the audio unit */
+ ERR_WRAP( AudioUnitInitialize(*audioUnit) );
+
+ if( inStreamParams && outStreamParams )
+ VDBUG( ("Opened device %ld for input and output.\n", *audioDevice ) );
+ else if( inStreamParams )
+ VDBUG( ("Opened device %ld for input.\n", *audioDevice ) );
+ else if( outStreamParams )
+ VDBUG( ("Opened device %ld for output.\n", *audioDevice ) );
+ return paNoError;
+#undef ERR_WRAP
+
+ error:
+ CloseComponent( *audioUnit );
+ *audioUnit = NULL;
+ if( result )
+ return PaMacCore_SetError( result, line, 1 );
+ return paResult;
+}
+
+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+ PaStream** s,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate,
+ unsigned long framesPerBuffer,
+ PaStreamFlags streamFlags,
+ PaStreamCallback *streamCallback,
+ void *userData )
+{
+ PaError result = paNoError;
+ PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi;
+ PaMacCoreStream *stream = 0;
+ int inputChannelCount, outputChannelCount;
+ PaSampleFormat inputSampleFormat, outputSampleFormat;
+ PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
+ VVDBUG(("OpenStream(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld SR=%g, FPB=%ld\n",
+ inputParameters ? inputParameters->channelCount : -1,
+ inputParameters ? inputParameters->sampleFormat : -1,
+ outputParameters ? outputParameters->channelCount : -1,
+ outputParameters ? outputParameters->sampleFormat : -1,
+ (float) sampleRate,
+ framesPerBuffer ));
+ VDBUG( ("Opening Stream.\n") );
+
+ /*These first few bits of code are from paSkeleton with few modifications.*/
+ if( inputParameters )
+ {
+ inputChannelCount = inputParameters->channelCount;
+ inputSampleFormat = inputParameters->sampleFormat;
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+
+ if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ /* check that input device can support inputChannelCount */
+ if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+ return paInvalidChannelCount;
+
+ /* Host supports interleaved float32 */
+ hostInputSampleFormat = paFloat32;
+ }
+ else
+ {
+ inputChannelCount = 0;
+ inputSampleFormat = hostInputSampleFormat = paFloat32; /* Surpress 'uninitialised var' warnings. */
+ }
+
+ if( outputParameters )
+ {
+ outputChannelCount = outputParameters->channelCount;
+ outputSampleFormat = outputParameters->sampleFormat;
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+
+ if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ /* check that output device can support inputChannelCount */
+ if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+ return paInvalidChannelCount;
+
+ /* Host supports interleaved float32 */
+ hostOutputSampleFormat = paFloat32;
+ }
+ else
+ {
+ outputChannelCount = 0;
+ outputSampleFormat = hostOutputSampleFormat = paFloat32; /* Surpress 'uninitialized var' warnings. */
+ }
+
+ /* validate platform specific flags */
+ if( (streamFlags & paPlatformSpecificFlags) != 0 )
+ return paInvalidFlag; /* unexpected platform specific flag */
+
+ stream = (PaMacCoreStream*)PaUtil_AllocateMemory( sizeof(PaMacCoreStream) );
+ if( !stream )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ /* If we fail after this point, we my be left in a bad state, with
+ some data structures setup and others not. So, first thing we
+ do is initialize everything so that if we fail, we know what hasn't
+ been touched.
+ */
+
+ stream->inputAudioBufferList.mBuffers[0].mData = NULL;
+ stream->inputRingBuffer.buffer = NULL;
+ bzero( &stream->blio, sizeof( PaMacBlio ) );
+/*
+ stream->blio.inputRingBuffer.buffer = NULL;
+ stream->blio.outputRingBuffer.buffer = NULL;
+ stream->blio.inputSampleFormat = inputParameters?inputParameters->sampleFormat:0;
+ stream->blio.inputSampleSize = computeSampleSizeFromFormat(stream->blio.inputSampleFormat);
+ stream->blio.outputSampleFormat=outputParameters?outputParameters->sampleFormat:0;
+ stream->blio.outputSampleSize = computeSampleSizeFromFormat(stream->blio.outputSampleFormat);
+*/
+ stream->inputSRConverter = NULL;
+ stream->inputUnit = NULL;
+ stream->outputUnit = NULL;
+ stream->inputFramesPerBuffer = 0;
+ stream->outputFramesPerBuffer = 0;
+ stream->bufferProcessorIsInitialized = FALSE;
+
+ /* assert( streamCallback ) ; */ /* only callback mode is implemented */
+ if( streamCallback )
+ {
+ PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+ &auhalHostApi->callbackStreamInterface,
+ streamCallback, userData );
+ }
+ else
+ {
+ PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+ &auhalHostApi->blockingStreamInterface,
+ BlioCallback, &stream->blio );
+ }
+
+ PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+
+ /* -- handle paFramesPerBufferUnspecified -- */
+ if( framesPerBuffer == paFramesPerBufferUnspecified ) {
+ long requested = 64;
+ if( inputParameters )
+ requested = MAX( requested, inputParameters->suggestedLatency * sampleRate / 2 );
+ if( outputParameters )
+ requested = MAX( requested, outputParameters->suggestedLatency *sampleRate / 2 );
+ VDBUG( ("Block Size unspecified. Based on Latency, the user wants a Block Size near: %ld.\n",
+ requested ) );
+ if( requested <= 64 ) {
+ /*requested a realtively low latency. make sure this is in range of devices */
+ /*try to get the device's min natural buffer size and use that (but no smaller than 64).*/
+ AudioValueRange audioRange;
+ size_t size = sizeof( audioRange );
+ if( inputParameters ) {
+ WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[inputParameters->device],
+ 0,
+ false,
+ kAudioDevicePropertyBufferFrameSizeRange,
+ &size, &audioRange ) );
+ if( result )
+ requested = MAX( requested, audioRange.mMinimum );
+ }
+ if( outputParameters ) {
+ WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[outputParameters->device],
+ 0,
+ false,
+ kAudioDevicePropertyBufferFrameSizeRange,
+ &size, &audioRange ) );
+ if( result )
+ requested = MAX( requested, audioRange.mMinimum );
+ }
+ } else {
+ /* requested a realtively high latency. make sure this is in range of devices */
+ /*try to get the device's max natural buffer size and use that (but no larger than 1024).*/
+ AudioValueRange audioRange;
+ size_t size = sizeof( audioRange );
+ requested = MIN( requested, 1024 );
+ if( inputParameters ) {
+ WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[inputParameters->device],
+ 0,
+ false,
+ kAudioDevicePropertyBufferFrameSizeRange,
+ &size, &audioRange ) );
+ if( result )
+ requested = MIN( requested, audioRange.mMaximum );
+ }
+ if( outputParameters ) {
+ WARNING( result = AudioDeviceGetProperty( auhalHostApi->devIds[outputParameters->device],
+ 0,
+ false,
+ kAudioDevicePropertyBufferFrameSizeRange,
+ &size, &audioRange ) );
+ if( result )
+ requested = MIN( requested, audioRange.mMaximum );
+ }
+ }
+ /* -- double check ranges -- */
+ if( requested > 1024 ) requested = 1024;
+ if( requested < 64 ) requested = 64;
+ VDBUG(("After querying hardware, setting block size to %ld.\n", requested));
+ framesPerBuffer = requested;
+ }
+
+ /* -- Now we actually open and setup streams. -- */
+ if( inputParameters && outputParameters && outputParameters->device == inputParameters->device )
+ { /* full duplex. One device. */
+ result = OpenAndSetupOneAudioUnit( inputParameters,
+ outputParameters,
+ framesPerBuffer,
+ &(stream->inputFramesPerBuffer),
+ &(stream->outputFramesPerBuffer),
+ auhalHostApi,
+ &(stream->inputUnit),
+ &(stream->inputSRConverter),
+ &(stream->inputDevice),
+ sampleRate,
+ stream );
+ stream->outputUnit = stream->inputUnit;
+ stream->outputDevice = stream->inputDevice;
+ if( result != paNoError )
+ goto error;
+ }
+ else
+ { /* full duplex, different devices OR simplex */
+ result = OpenAndSetupOneAudioUnit( NULL,
+ outputParameters,
+ framesPerBuffer,
+ NULL,
+ &(stream->outputFramesPerBuffer),
+ auhalHostApi,
+ &(stream->outputUnit),
+ NULL,
+ &(stream->outputDevice),
+ sampleRate,
+ stream );
+ if( result != paNoError )
+ goto error;
+ result = OpenAndSetupOneAudioUnit( inputParameters,
+ NULL,
+ framesPerBuffer,
+ &(stream->inputFramesPerBuffer),
+ NULL,
+ auhalHostApi,
+ &(stream->inputUnit),
+ &(stream->inputSRConverter),
+ &(stream->inputDevice),
+ sampleRate,
+ stream );
+ if( result != paNoError )
+ goto error;
+ }
+
+ if( stream->inputUnit ) {
+ const size_t szfl = sizeof(float);
+ /* setup the AudioBufferList used for input */
+ bzero( &stream->inputAudioBufferList, sizeof( AudioBufferList ) );
+ stream->inputAudioBufferList.mNumberBuffers = 1;
+ stream->inputAudioBufferList.mBuffers[0].mNumberChannels
+ = inputChannelCount;
+ stream->inputAudioBufferList.mBuffers[0].mDataByteSize
+ = stream->inputFramesPerBuffer*inputChannelCount*szfl;
+ stream->inputAudioBufferList.mBuffers[0].mData
+ = (float *) calloc(
+ stream->inputFramesPerBuffer*inputChannelCount,
+ szfl );
+ if( !stream->inputAudioBufferList.mBuffers[0].mData )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ /*
+ * If input and output devs are different or we are doing SR conversion,
+ * we also need a
+ * ring buffer to store inpt data while waiting for output
+ * data.
+ */
+ if( (stream->outputUnit && stream->inputUnit != stream->outputUnit)
+ || stream->inputSRConverter )
+ {
+ /* May want the ringSize ot initial position in
+ ring buffer to depend somewhat on sample rate change */
+
+ void *data;
+ long ringSize;
+
+ ringSize = computeRingBufferSize( inputParameters,
+ outputParameters,
+ stream->inputFramesPerBuffer,
+ stream->outputFramesPerBuffer,
+ sampleRate );
+ /*ringSize <<= 4; *//*16x bigger, for testing */
+
+
+ /*now, we need to allocate memory for the ring buffer*/
+ data = calloc( ringSize, szfl );
+ if( !data )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ /* now we can initialize the ring buffer */
+ PaUtil_InitializeRingBuffer( &stream->inputRingBuffer,
+ ringSize*szfl, data ) ;
+ /* advance the read point a little, so we are reading from the
+ middle of the buffer */
+ if( stream->outputUnit )
+ PaUtil_AdvanceRingBufferWriteIndex( &stream->inputRingBuffer, ringSize*szfl / RING_BUFFER_ADVANCE_DENOMINATOR );
+ }
+ }
+
+ /* -- initialize Blio Buffer Processors -- */
+ if( !streamCallback )
+ {
+ long ringSize;
+
+ ringSize = computeRingBufferSize( inputParameters,
+ outputParameters,
+ stream->inputFramesPerBuffer,
+ stream->outputFramesPerBuffer,
+ sampleRate );
+ result = initializeBlioRingBuffers( &stream->blio,
+ inputParameters?inputParameters->sampleFormat:0 ,
+ outputParameters?outputParameters->sampleFormat:0 ,
+ MAX(stream->inputFramesPerBuffer,stream->outputFramesPerBuffer),
+ ringSize,
+ inputParameters?inputChannelCount:0 ,
+ outputParameters?outputChannelCount:0 ) ;
+ if( result != paNoError )
+ goto error;
+ }
+
+ /* -- initialize Buffer Processor -- */
+ {
+ unsigned long maxHostFrames = stream->inputFramesPerBuffer;
+ if( stream->outputFramesPerBuffer > maxHostFrames )
+ maxHostFrames = stream->outputFramesPerBuffer;
+ result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+ inputChannelCount, inputSampleFormat,
+ hostInputSampleFormat,
+ outputChannelCount, outputSampleFormat,
+ hostOutputSampleFormat,
+ sampleRate,
+ streamFlags,
+ framesPerBuffer,
+ /* If sample rate conversion takes place, the buffer size
+ will not be known. */
+ maxHostFrames,
+ stream->inputSRConverter
+ ? paUtilUnknownHostBufferSize
+ : paUtilBoundedHostBufferSize,
+ streamCallback ? streamCallback : BlioCallback,
+ streamCallback ? userData : &stream->blio );
+ if( result != paNoError )
+ goto error;
+ }
+ stream->bufferProcessorIsInitialized = TRUE;
+
+ /*
+ IMPLEMENT ME: initialise the following fields with estimated or actual
+ values.
+ I think this is okay the way it is br 12/1/05
+ maybe need to change input latency estimate if IO devs differ
+ */
+ stream->streamRepresentation.streamInfo.inputLatency =
+ PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor)/sampleRate;
+ stream->streamRepresentation.streamInfo.outputLatency =
+ PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor)/sampleRate;
+ stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+ stream->sampleRate = sampleRate;
+ stream->outDeviceSampleRate = 0;
+ if( stream->outputUnit ) {
+ Float64 rate;
+ UInt32 size = sizeof( rate );
+ result = ERR( AudioDeviceGetProperty( stream->outputDevice,
+ 0,
+ FALSE,
+ kAudioDevicePropertyNominalSampleRate,
+ &size, &rate ) );
+ if( result )
+ goto error;
+ stream->outDeviceSampleRate = rate;
+ }
+ stream->inDeviceSampleRate = 0;
+ if( stream->inputUnit ) {
+ Float64 rate;
+ UInt32 size = sizeof( rate );
+ result = ERR( AudioDeviceGetProperty( stream->inputDevice,
+ 0,
+ TRUE,
+ kAudioDevicePropertyNominalSampleRate,
+ &size, &rate ) );
+ if( result )
+ goto error;
+ stream->inDeviceSampleRate = rate;
+ }
+ stream->userInChan = inputChannelCount;
+ stream->userOutChan = outputChannelCount;
+
+ stream->isTimeSet = FALSE;
+ stream->state = STOPPED;
+ stream->xrunFlags = 0;
+
+ *s = (PaStream*)stream;
+
+ return result;
+
+error:
+ CloseStream( stream );
+ return result;
+}
+
+PaTime GetStreamTime( PaStream *s )
+{
+ /* FIXME: I am not at all sure this timing info stuff is right.
+ patest_sine_time reports negative latencies, which is wierd.*/
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+ AudioTimeStamp timeStamp;
+
+ VVDBUG(("GetStreamTime()\n"));
+
+ if ( !stream->isTimeSet )
+ return (PaTime)0;
+
+ if ( stream->outputDevice ) {
+ AudioDeviceGetCurrentTime( stream->outputDevice, &timeStamp);
+ return (PaTime)(timeStamp.mSampleTime - stream->startTime.mSampleTime)/stream->outDeviceSampleRate;
+ } else if ( stream->inputDevice ) {
+ AudioDeviceGetCurrentTime( stream->inputDevice, &timeStamp);
+ return (PaTime)(timeStamp.mSampleTime - stream->startTime.mSampleTime)/stream->inDeviceSampleRate;
+ } else {
+ return (PaTime)0;
+ }
+}
+
+static void setStreamStartTime( PaStream *stream )
+{
+ /* FIXME: I am not at all sure this timing info stuff is right.
+ patest_sine_time reports negative latencies, which is wierd.*/
+ PaMacCoreStream *s = (PaMacCoreStream *) stream;
+ VVDBUG(("setStreamStartTime()\n"));
+ if( s->outputDevice )
+ AudioDeviceGetCurrentTime( s->outputDevice, &s->startTime);
+ else if( s->inputDevice )
+ AudioDeviceGetCurrentTime( s->inputDevice, &s->startTime);
+ else
+ bzero( &s->startTime, sizeof( s->startTime ) );
+
+ //FIXME: we need a memory barier here
+
+ s->isTimeSet = TRUE;
+}
+
+
+static PaTime TimeStampToSecs(PaMacCoreStream *stream, const AudioTimeStamp* timeStamp)
+{
+ VVDBUG(("TimeStampToSecs()\n"));
+ //printf( "ATS: %lu, %g, %g\n", timeStamp->mFlags, timeStamp->mSampleTime, timeStamp->mRateScalar );
+ if (timeStamp->mFlags & kAudioTimeStampSampleTimeValid)
+ return (timeStamp->mSampleTime / stream->sampleRate);
+ else
+ return 0;
+}
+
+#define RING_BUFFER_EMPTY (1000)
+
+static OSStatus ringBufferIOProc( AudioConverterRef inAudioConverter,
+ UInt32*ioDataSize,
+ void** outData,
+ void*inUserData )
+{
+ void *dummyData;
+ long dummySize;
+ PaUtilRingBuffer *rb = (PaUtilRingBuffer *) inUserData;
+
+ VVDBUG(("ringBufferIOProc()\n"));
+
+ assert( sizeof( UInt32 ) == sizeof( long ) );
+ if( PaUtil_GetRingBufferReadAvailable( rb ) == 0 ) {
+ *outData = NULL;
+ *ioDataSize = 0;
+ return RING_BUFFER_EMPTY;
+ }
+ PaUtil_GetRingBufferReadRegions( rb, *ioDataSize,
+ outData, (long *)ioDataSize,
+ &dummyData, &dummySize );
+
+ assert( *ioDataSize );
+ PaUtil_AdvanceRingBufferReadIndex( rb, *ioDataSize );
+
+ return noErr;
+}
+
+/*
+ * Called by the AudioUnit API to process audio from the sound card.
+ * This is where the magic happens.
+ */
+/* FEEDBACK: there is a lot of redundant code here because of how all the cases differ. This makes it hard to maintain, so if there are suggestinos for cleaning it up, I'm all ears. */
+static OSStatus AudioIOProc( void *inRefCon,
+ AudioUnitRenderActionFlags *ioActionFlags,
+ const AudioTimeStamp *inTimeStamp,
+ UInt32 inBusNumber,
+ UInt32 inNumberFrames,
+ AudioBufferList *ioData )
+{
+ unsigned long framesProcessed = 0;
+ PaStreamCallbackTimeInfo timeInfo = {0,0,0};
+ PaMacCoreStream *stream = (PaMacCoreStream*)inRefCon;
+ const bool isRender = inBusNumber == OUTPUT_ELEMENT;
+ int callbackResult = paContinue ;
+
+ VVDBUG(("AudioIOProc()\n"));
+
+ PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+
+ /* -----------------------------------------------------------------*\
+ This output may be useful for debugging,
+ But printing durring the callback is a bad enough idea that
+ this is not enabled by enableing the usual debugging calls.
+ \* -----------------------------------------------------------------*/
+ /*
+ static int renderCount = 0;
+ static int inputCount = 0;
+ printf( "------------------- starting reder/input\n" );
+ if( isRender )
+ printf("Render callback (%d):\t", ++renderCount);
+ else
+ printf("Input callback (%d):\t", ++inputCount);
+ printf( "Call totals: %d (input), %d (render)\n", inputCount, renderCount );
+
+ printf( "--- inBusNumber: %lu\n", inBusNumber );
+ printf( "--- inNumberFrames: %lu\n", inNumberFrames );
+ printf( "--- %x ioData\n", (unsigned) ioData );
+ if( ioData )
+ {
+ int i=0;
+ printf( "--- ioData.mNumBuffers %lu: \n", ioData->mNumberBuffers );
+ for( i=0; i<ioData->mNumberBuffers; ++i )
+ printf( "--- ioData buffer %d size: %lu.\n", i, ioData->mBuffers[i].mDataByteSize );
+ }
+ ----------------------------------------------------------------- */
+
+ if( !stream->isTimeSet )
+ setStreamStartTime( stream );
+
+ if( isRender ) {
+ AudioTimeStamp currentTime;
+ timeInfo.outputBufferDacTime = TimeStampToSecs(stream, inTimeStamp);
+ AudioDeviceGetCurrentTime(stream->outputDevice, &currentTime);
+ timeInfo.currentTime = TimeStampToSecs(stream, &currentTime);
+ }
+ if( isRender && stream->inputUnit == stream->outputUnit )
+ timeInfo.inputBufferAdcTime = TimeStampToSecs(stream, inTimeStamp);
+ if( !isRender ) {
+ AudioTimeStamp currentTime;
+ timeInfo.inputBufferAdcTime = TimeStampToSecs(stream, inTimeStamp);
+ AudioDeviceGetCurrentTime(stream->inputDevice, &currentTime);
+ timeInfo.currentTime = TimeStampToSecs(stream, &currentTime);
+ }
+
+ //printf( "---%g, %g, %g\n", timeInfo.inputBufferAdcTime, timeInfo.currentTime, timeInfo.outputBufferDacTime );
+
+ if( isRender && stream->inputUnit == stream->outputUnit
+ && !stream->inputSRConverter )
+ {
+ /* --------- Full Duplex, One Device, no SR Conversion -------
+ *
+ * This is the lowest latency case, and also the simplest.
+ * Input data and output data are available at the same time.
+ * we do not use the input SR converter or the input ring buffer.
+ *
+ */
+ OSErr err = 0;
+ unsigned long frames;
+
+ /* -- start processing -- */
+ PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),
+ &timeInfo,
+ stream->xrunFlags );
+ stream->xrunFlags = 0;
+
+ /* -- compute frames. do some checks -- */
+ assert( ioData->mNumberBuffers == 1 );
+ assert( ioData->mBuffers[0].mNumberChannels == stream->userOutChan );
+ frames = ioData->mBuffers[0].mDataByteSize;
+ frames /= sizeof( float ) * ioData->mBuffers[0].mNumberChannels;
+ /* -- copy and process input data -- */
+ err= AudioUnitRender(stream->inputUnit,
+ ioActionFlags,
+ inTimeStamp,
+ INPUT_ELEMENT,
+ inNumberFrames,
+ &stream->inputAudioBufferList );
+ /* FEEDBACK: I'm not sure what to do when this call fails */
+ assert( !err );
+
+ PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );
+ PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+ 0,
+ stream->inputAudioBufferList.mBuffers[0].mData,
+ stream->inputAudioBufferList.mBuffers[0].mNumberChannels);
+ /* -- Copy and process output data -- */
+ PaUtil_SetOutputFrameCount( &(stream->bufferProcessor), frames );
+ PaUtil_SetInterleavedOutputChannels( &(stream->bufferProcessor),
+ 0,
+ ioData->mBuffers[0].mData,
+ ioData->mBuffers[0].mNumberChannels);
+ /* -- complete processing -- */
+ framesProcessed =
+ PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+ &callbackResult );
+ }
+ else if( isRender )
+ {
+ /* -------- Output Side of Full Duplex (Separate Devices or SR Conversion)
+ * -- OR Simplex Output
+ *
+ * This case handles output data as in the full duplex case,
+ * and, if there is input data, reads it off the ring buffer
+ * and into the PA buffer processor. If sample rate conversion
+ * is required on input, that is done here as well.
+ */
+ unsigned long frames;
+
+ /* Sometimes, when stopping a duplex stream we get erroneous
+ xrun flags, so if this is our last run, clear the flags. */
+ int xrunFlags = stream->xrunFlags;
+/*
+ if( xrunFlags & paInputUnderflow )
+ printf( "input underflow.\n" );
+ if( xrunFlags & paInputOverflow )
+ printf( "input overflow.\n" );
+*/
+ if( stream->state == STOPPING || stream->state == CALLBACK_STOPPED )
+ xrunFlags = 0;
+
+ /* -- start processing -- */
+ PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),
+ &timeInfo,
+ xrunFlags );
+ stream->xrunFlags = 0; /* FEEDBACK: we only send flags to Buf Proc once */
+
+ /* -- Copy and process output data -- */
+ assert( ioData->mNumberBuffers == 1 );
+ frames = ioData->mBuffers[0].mDataByteSize;
+ frames /= sizeof( float ) * ioData->mBuffers[0].mNumberChannels;
+ assert( ioData->mBuffers[0].mNumberChannels == stream->userOutChan );
+ PaUtil_SetOutputFrameCount( &(stream->bufferProcessor), frames );
+ PaUtil_SetInterleavedOutputChannels( &(stream->bufferProcessor),
+ 0,
+ ioData->mBuffers[0].mData,
+ ioData->mBuffers[0].mNumberChannels);
+
+ /* -- copy and process input data, and complete processing -- */
+ if( stream->inputUnit ) {
+ const int flsz = sizeof( float );
+ /* Here, we read the data out of the ring buffer, through the
+ audio converter. */
+ int inChan = stream->inputAudioBufferList.mBuffers[0].mNumberChannels;
+ if( stream->inputSRConverter )
+ {
+ OSStatus err;
+ UInt32 size;
+ float data[ inChan * frames ];
+ size = sizeof( data );
+ err = AudioConverterFillBuffer(
+ stream->inputSRConverter,
+ ringBufferIOProc,
+ &stream->inputRingBuffer,
+ &size,
+ (void *)&data );
+ if( err == RING_BUFFER_EMPTY )
+ { /*the ring buffer callback underflowed */
+ err = 0;
+ bzero( ((char *)data) + size, sizeof(data)-size );
+ stream->xrunFlags |= paInputUnderflow;
+ }
+ ERR( err );
+ assert( !err );
+
+ PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );
+ PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+ 0,
+ data,
+ inChan );
+ framesProcessed =
+ PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+ &callbackResult );
+ }
+ else
+ {
+ /* Without the AudioConverter is actually a bit more complex
+ because we have to do a little buffer processing that the
+ AudioConverter would otherwise handle for us. */
+ void *data1, *data2;
+ long size1, size2;
+ PaUtil_GetRingBufferReadRegions( &stream->inputRingBuffer,
+ inChan*frames*flsz,
+ &data1, &size1,
+ &data2, &size2 );
+ if( size1 / ( flsz * inChan ) == frames ) {
+ /* simplest case: all in first buffer */
+ PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );
+ PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+ 0,
+ data1,
+ inChan );
+ framesProcessed =
+ PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+ &callbackResult );
+ PaUtil_AdvanceRingBufferReadIndex(&stream->inputRingBuffer, size1 );
+ } else if( ( size1 + size2 ) / ( flsz * inChan ) < frames ) {
+ /*we underflowed. take what data we can, zero the rest.*/
+ float data[frames*inChan];
+ if( size1 )
+ memcpy( data, data1, size1 );
+ if( size2 )
+ memcpy( data+size1, data2, size2 );
+ bzero( data+size1+size2, frames*flsz*inChan - size1 - size2 );
+
+ PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );
+ PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+ 0,
+ data,
+ inChan );
+ framesProcessed =
+ PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+ &callbackResult );
+ PaUtil_AdvanceRingBufferReadIndex( &stream->inputRingBuffer,
+ size1+size2 );
+ /* flag underflow */
+ stream->xrunFlags |= paInputUnderflow;
+ } else {
+ /*we got all the data, but split between buffers*/
+ PaUtil_SetInputFrameCount( &(stream->bufferProcessor),
+ size1 / ( flsz * inChan ) );
+ PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+ 0,
+ data1,
+ inChan );
+ PaUtil_Set2ndInputFrameCount( &(stream->bufferProcessor),
+ size2 / ( flsz * inChan ) );
+ PaUtil_Set2ndInterleavedInputChannels( &(stream->bufferProcessor),
+ 0,
+ data2,
+ inChan );
+ framesProcessed =
+ PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+ &callbackResult );
+ PaUtil_AdvanceRingBufferReadIndex(&stream->inputRingBuffer, size1+size2 );
+ }
+ }
+ } else {
+ framesProcessed =
+ PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+ &callbackResult );
+ }
+
+ }
+ else
+ {
+ /* ------------------ Input
+ *
+ * First, we read off the audio data and put it in the ring buffer.
+ * if this is an input-only stream, we need to process it more,
+ * otherwise, we let the output case deal with it.
+ */
+ OSErr err = 0;
+ int chan = stream->inputAudioBufferList.mBuffers[0].mNumberChannels ;
+ /* FIXME: looping here may not actually be necessary, but it was something I tried in testing. */
+ do {
+ err= AudioUnitRender(stream->inputUnit,
+ ioActionFlags,
+ inTimeStamp,
+ INPUT_ELEMENT,
+ inNumberFrames,
+ &stream->inputAudioBufferList );
+ if( err == -10874 )
+ inNumberFrames /= 2;
+ } while( err == -10874 && inNumberFrames > 1 );
+ /* FEEDBACK: I'm not sure what to do when this call fails */
+ ERR( err );
+ assert( !err );
+ if( stream->inputSRConverter || stream->outputUnit )
+ {
+ /* If this is duplex or we use a converter, put the data
+ into the ring buffer. */
+ long bytesIn, bytesOut;
+ bytesIn = sizeof( float ) * inNumberFrames * chan;
+ bytesOut = PaUtil_WriteRingBuffer( &stream->inputRingBuffer,
+ stream->inputAudioBufferList.mBuffers[0].mData,
+ bytesIn );
+ if( bytesIn != bytesOut )
+ stream->xrunFlags |= paInputOverflow ;
+ }
+ else
+ {
+ /* for simplex input w/o SR conversion,
+ just pop the data into the buffer processor.*/
+ PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),
+ &timeInfo,
+ stream->xrunFlags );
+ stream->xrunFlags = 0;
+
+ PaUtil_SetInputFrameCount( &(stream->bufferProcessor), inNumberFrames);
+ PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+ 0,
+ stream->inputAudioBufferList.mBuffers[0].mData,
+ chan );
+ framesProcessed =
+ PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+ &callbackResult );
+ }
+ if( !stream->outputUnit && stream->inputSRConverter )
+ {
+ /* ------------------ Simplex Input w/ SR Conversion
+ *
+ * if this is a simplex input stream, we need to read off the buffer,
+ * do our sample rate conversion and pass the results to the buffer
+ * processor.
+ * The logic here is complicated somewhat by the fact that we don't
+ * know how much data is available, so we loop on reasonably sized
+ * chunks, and let the BufferProcessor deal with the rest.
+ *
+ */
+ /*This might be too big or small depending on SR conversion*/
+ float data[ chan * inNumberFrames ];
+ OSStatus err;
+ do
+ { /*Run the buffer processor until we are out of data*/
+ UInt32 size;
+ long f;
+
+ size = sizeof( data );
+ err = AudioConverterFillBuffer(
+ stream->inputSRConverter,
+ ringBufferIOProc,
+ &stream->inputRingBuffer,
+ &size,
+ (void *)data );
+ if( err != RING_BUFFER_EMPTY )
+ ERR( err );
+ assert( err == 0 || err == RING_BUFFER_EMPTY );
+
+ f = size / ( chan * sizeof(float) );
+ PaUtil_SetInputFrameCount( &(stream->bufferProcessor), f );
+ if( f )
+ {
+ PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),
+ &timeInfo,
+ stream->xrunFlags );
+ stream->xrunFlags = 0;
+
+ PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
+ 0,
+ data,
+ chan );
+ framesProcessed =
+ PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
+ &callbackResult );
+ }
+ } while( callbackResult == paContinue && !err );
+ }
+ }
+
+ switch( callbackResult )
+ {
+ case paContinue: break;
+ case paComplete:
+ case paAbort:
+ stream->isTimeSet = FALSE;
+ stream->state = CALLBACK_STOPPED ;
+ if( stream->outputUnit )
+ AudioOutputUnitStop(stream->outputUnit);
+ if( stream->inputUnit )
+ AudioOutputUnitStop(stream->inputUnit);
+ break;
+ }
+
+ PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
+ return noErr;
+}
+
+
+/*
+ When CloseStream() is called, the multi-api layer ensures that
+ the stream has already been stopped or aborted.
+*/
+static PaError CloseStream( PaStream* s )
+{
+ /* This may be called from a failed OpenStream.
+ Therefore, each piece of info is treated seperately. */
+ PaError result = paNoError;
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+
+ VVDBUG(("CloseStream()\n"));
+ VDBUG( ( "Closing stream.\n" ) );
+
+ if( stream ) {
+ if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) {
+ AudioUnitUninitialize( stream->outputUnit );
+ CloseComponent( stream->outputUnit );
+ }
+ stream->outputUnit = NULL;
+ if( stream->inputUnit )
+ {
+ AudioUnitUninitialize( stream->inputUnit );
+ CloseComponent( stream->inputUnit );
+ stream->inputUnit = NULL;
+ }
+ if( stream->inputRingBuffer.buffer )
+ free( (void *) stream->inputRingBuffer.buffer );
+ stream->inputRingBuffer.buffer = NULL;
+ /*TODO: is there more that needs to be done on error
+ from AudioConverterDispose?*/
+ if( stream->inputSRConverter )
+ ERR( AudioConverterDispose( stream->inputSRConverter ) );
+ stream->inputSRConverter = NULL;
+ if( stream->inputAudioBufferList.mBuffers[0].mData )
+ free( stream->inputAudioBufferList.mBuffers[0].mData );
+ stream->inputAudioBufferList.mBuffers[0].mData = NULL;
+
+ result = destroyBlioRingBuffers( &stream->blio );
+ if( result )
+ return result;
+ if( stream->bufferProcessorIsInitialized )
+ PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+ PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+ PaUtil_FreeMemory( stream );
+ }
+
+ return result;
+}
+
+
+static PaError StartStream( PaStream *s )
+{
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+ OSErr result = noErr;
+ VVDBUG(("StartStream()\n"));
+ VDBUG( ( "Starting stream.\n" ) );
+
+#define ERR_WRAP(mac_err) do { result = mac_err ; if ( result != noErr ) return ERR(result) ; } while(0)
+
+ /*FIXME: maybe want to do this on close/abort for faster start? */
+ PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+ if( stream->inputSRConverter )
+ ERR_WRAP( AudioConverterReset( stream->inputSRConverter ) );
+
+ /* -- start -- */
+ stream->state = ACTIVE;
+ if( stream->inputUnit ) {
+ ERR_WRAP( AudioOutputUnitStart(stream->inputUnit) );
+ }
+ if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) {
+ ERR_WRAP( AudioOutputUnitStart(stream->outputUnit) );
+ }
+
+ //setStreamStartTime( stream );
+ //stream->isTimeSet = TRUE;
+
+ return paNoError;
+#undef ERR_WRAP
+}
+
+// it's not clear from appl's docs that this really waits
+// until all data is flushed.
+static ComponentResult BlockWhileAudioUnitIsRunning( AudioUnit audioUnit, AudioUnitElement element )
+{
+ Boolean isRunning = 1;
+ while( isRunning ) {
+ UInt32 s = sizeof( isRunning );
+ ComponentResult err = AudioUnitGetProperty( audioUnit, kAudioOutputUnitProperty_IsRunning, kAudioUnitScope_Global, element, &isRunning, &s );
+ if( err )
+ return err;
+ Pa_Sleep( 100 );
+ }
+ return noErr;
+}
+
+static PaError StopStream( PaStream *s )
+{
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+ OSErr result = noErr;
+ PaError paErr;
+ VVDBUG(("StopStream()\n"));
+
+ VDBUG( ("Waiting for BLIO.\n") );
+ waitUntilBlioWriteBufferIsFlushed( &stream->blio );
+ VDBUG( ( "Stopping stream.\n" ) );
+
+ stream->isTimeSet = FALSE;
+ stream->state = STOPPING;
+
+#define ERR_WRAP(mac_err) do { result = mac_err ; if ( result != noErr ) return ERR(result) ; } while(0)
+ /* -- stop and reset -- */
+ if( stream->inputUnit == stream->outputUnit && stream->inputUnit )
+ {
+ ERR_WRAP( AudioOutputUnitStop(stream->inputUnit) );
+ ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,0) );
+ ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,1) );
+ ERR_WRAP( AudioUnitReset(stream->inputUnit, kAudioUnitScope_Global, 1) );
+ ERR_WRAP( AudioUnitReset(stream->inputUnit, kAudioUnitScope_Global, 0) );
+ }
+ else
+ {
+ if( stream->inputUnit )
+ {
+ ERR_WRAP(AudioOutputUnitStop(stream->inputUnit) );
+ ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,1) );
+ ERR_WRAP(AudioUnitReset(stream->inputUnit,kAudioUnitScope_Global,1));
+ }
+ if( stream->outputUnit )
+ {
+ ERR_WRAP(AudioOutputUnitStop(stream->outputUnit));
+ ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->outputUnit,0) );
+ ERR_WRAP(AudioUnitReset(stream->outputUnit,kAudioUnitScope_Global,0));
+ }
+ }
+ if( stream->inputRingBuffer.buffer ) {
+ PaUtil_FlushRingBuffer( &stream->inputRingBuffer );
+ bzero( (void *)stream->inputRingBuffer.buffer,
+ stream->inputRingBuffer.bufferSize );
+ /* advance the write point a little, so we are reading from the
+ middle of the buffer. We'll need extra at the end because
+ testing has shown that this helps. */
+ if( stream->outputUnit )
+ PaUtil_AdvanceRingBufferWriteIndex( &stream->inputRingBuffer,
+ stream->inputRingBuffer.bufferSize
+ / RING_BUFFER_ADVANCE_DENOMINATOR );
+ }
+
+ stream->xrunFlags = 0;
+ stream->state = STOPPED;
+
+ paErr = resetBlioRingBuffers( &stream->blio );
+ if( paErr )
+ return paErr;
+
+/*
+ //stream->isTimeSet = FALSE;
+*/
+
+ VDBUG( ( "Stream Stopped.\n" ) );
+ return paNoError;
+#undef ERR_WRAP
+}
+
+static PaError AbortStream( PaStream *s )
+{
+ VVDBUG(("AbortStream()->StopStream()\n"));
+ VDBUG( ( "Aborting stream.\n" ) );
+ /* We have nothing faster than StopStream. */
+ return StopStream(s);
+}
+
+
+static PaError IsStreamStopped( PaStream *s )
+{
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+ VVDBUG(("IsStreamStopped()\n"));
+
+ return stream->state == STOPPED ? 1 : 0;
+}
+
+
+static PaError IsStreamActive( PaStream *s )
+{
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+ VVDBUG(("IsStreamActive()\n"));
+ return ( stream->state == ACTIVE || stream->state == STOPPING );
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+ VVDBUG(("GetStreamCpuLoad()\n"));
+
+ return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
diff --git a/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c
new file mode 100644
index 00000000..3b81389d
--- /dev/null
+++ b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c
@@ -0,0 +1,564 @@
+/*
+ * Implementation of the PortAudio API for Apple AUHAL
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
+ *
+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,
+ * Gord Peters, Stephane Letz, and Greg Pfiel.
+ *
+ * The following people also deserve acknowledgements:
+ *
+ * Olivier Tristan for feedback and testing
+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
+ * interface.
+ *
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostaip_src
+
+ This file contains the implementation
+ required for blocking I/O. It is separated from pa_mac_core.c simply to ease
+ development.
+*/
+
+#include "pa_mac_core_blocking.h"
+#include "pa_mac_core_internal.h"
+#include <assert.h>
+#ifdef MOSX_USE_NON_ATOMIC_FLAG_BITS
+# define OSAtomicOr32( a, b ) ( (*(b)) |= (a) )
+# define OSAtomicAnd32( a, b ) ( (*(b)) &= (a) )
+#else
+# include <libkern/OSAtomic.h>
+#endif
+
+/*
+ * This fnuction determines the size of a particular sample format.
+ * if the format is not recognized, this returns zero.
+ */
+static size_t computeSampleSizeFromFormat( PaSampleFormat format )
+{
+ switch( format ) {
+ case paFloat32: return 4;
+ case paInt32: return 4;
+ case paInt24: return 3;
+ case paInt16: return 2;
+ case paInt8: case paUInt8: return 1;
+ default: return 0;
+ }
+}
+
+
+/*
+ * Functions for initializing, resetting, and destroying BLIO structures.
+ *
+ */
+
+/* This should be called with the relevant info when initializing a stream for
+ callback. */
+PaError initializeBlioRingBuffers(
+ PaMacBlio *blio,
+ PaSampleFormat inputSampleFormat,
+ PaSampleFormat outputSampleFormat,
+ size_t framesPerBuffer,
+ long ringBufferSize,
+ int inChan,
+ int outChan )
+{
+ void *data;
+ int result;
+
+ /* zeroify things */
+ bzero( blio, sizeof( PaMacBlio ) );
+ /* this is redundant, but the buffers are used to check
+ if the bufffers have been initialized, so we do it explicitly. */
+ blio->inputRingBuffer.buffer = NULL;
+ blio->outputRingBuffer.buffer = NULL;
+
+ /* initialize simple data */
+ blio->inputSampleFormat = inputSampleFormat;
+ blio->inputSampleSize = computeSampleSizeFromFormat(inputSampleFormat);
+ blio->outputSampleFormat = outputSampleFormat;
+ blio->outputSampleSize = computeSampleSizeFromFormat(outputSampleFormat);
+ blio->framesPerBuffer = framesPerBuffer;
+ blio->inChan = inChan;
+ blio->outChan = outChan;
+ blio->statusFlags = 0;
+ blio->errors = paNoError;
+#ifdef PA_MAC_BLIO_MUTEX
+ blio->isInputEmpty = false;
+ blio->isOutputFull = false;
+#endif
+
+ /* setup ring buffers */
+#ifdef PA_MAC_BLIO_MUTEX
+ result = PaMacCore_SetUnixError( pthread_mutex_init(&(blio->inputMutex),NULL), 0 );
+ if( result )
+ goto error;
+ result = UNIX_ERR( pthread_cond_init( &(blio->inputCond), NULL ) );
+ if( result )
+ goto error;
+ result = UNIX_ERR( pthread_mutex_init(&(blio->outputMutex),NULL) );
+ if( result )
+ goto error;
+ result = UNIX_ERR( pthread_cond_init( &(blio->outputCond), NULL ) );
+#endif
+ if( inChan ) {
+ data = calloc( ringBufferSize, blio->inputSampleSize );
+ if( !data )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ assert( 0 == PaUtil_InitializeRingBuffer(
+ &blio->inputRingBuffer,
+ ringBufferSize*blio->inputSampleSize,
+ data ) );
+ }
+ if( outChan ) {
+ data = calloc( ringBufferSize, blio->outputSampleSize );
+ if( !data )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ assert( 0 == PaUtil_InitializeRingBuffer(
+ &blio->outputRingBuffer,
+ ringBufferSize*blio->outputSampleSize,
+ data ) );
+ }
+
+ result = resetBlioRingBuffers( blio );
+ if( result )
+ goto error;
+
+ return 0;
+
+ error:
+ destroyBlioRingBuffers( blio );
+ return result;
+}
+
+#ifdef PA_MAC_BLIO_MUTEX
+PaError blioSetIsInputEmpty( PaMacBlio *blio, bool isEmpty )
+{
+ PaError result = paNoError;
+ if( isEmpty == blio->isInputEmpty )
+ goto done;
+
+ /* we need to update the value. Here's what we do:
+ * - Lock the mutex, so noone else can write.
+ * - update the value.
+ * - unlock.
+ * - broadcast to all listeners.
+ */
+ result = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) );
+ if( result )
+ goto done;
+ blio->isInputEmpty = isEmpty;
+ result = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) );
+ if( result )
+ goto done;
+ result = UNIX_ERR( pthread_cond_broadcast( &blio->inputCond ) );
+ if( result )
+ goto done;
+
+ done:
+ return result;
+}
+PaError blioSetIsOutputFull( PaMacBlio *blio, bool isFull )
+{
+ PaError result = paNoError;
+ if( isFull == blio->isOutputFull )
+ goto done;
+
+ /* we need to update the value. Here's what we do:
+ * - Lock the mutex, so noone else can write.
+ * - update the value.
+ * - unlock.
+ * - broadcast to all listeners.
+ */
+ result = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) );
+ if( result )
+ goto done;
+ blio->isOutputFull = isFull;
+ result = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) );
+ if( result )
+ goto done;
+ result = UNIX_ERR( pthread_cond_broadcast( &blio->outputCond ) );
+ if( result )
+ goto done;
+
+ done:
+ return result;
+}
+#endif
+
+/* This should be called after stopping or aborting the stream, so that on next
+ start, the buffers will be ready. */
+PaError resetBlioRingBuffers( PaMacBlio *blio )
+{
+#ifdef PA_MAC__BLIO_MUTEX
+ int result;
+#endif
+ blio->statusFlags = 0;
+ if( blio->outputRingBuffer.buffer ) {
+ PaUtil_FlushRingBuffer( &blio->outputRingBuffer );
+ bzero( blio->outputRingBuffer.buffer,
+ blio->outputRingBuffer.bufferSize );
+ /* Advance buffer */
+ PaUtil_AdvanceRingBufferWriteIndex( &blio->outputRingBuffer, blio->outputRingBuffer.bufferSize );
+
+ /* Update isOutputFull. */
+#ifdef PA_MAC__BLIO_MUTEX
+ result = blioSetIsOutputFull( blio, toAdvance == blio->outputRingBuffer.bufferSize );
+ if( result )
+ goto error;
+#endif
+/*
+ printf( "------%d\n" , blio->framesPerBuffer );
+ printf( "------%d\n" , blio->outChan );
+ printf( "------%d\n" , blio->outputSampleSize );
+ printf( "------%d\n" , blio->framesPerBuffer*blio->outChan*blio->outputSampleSize );
+*/
+ }
+ if( blio->inputRingBuffer.buffer ) {
+ PaUtil_FlushRingBuffer( &blio->inputRingBuffer );
+ bzero( blio->inputRingBuffer.buffer,
+ blio->inputRingBuffer.bufferSize );
+ /* Update isInputEmpty. */
+#ifdef PA_MAC__BLIO_MUTEX
+ result = blioSetIsInputEmpty( blio, true );
+ if( result )
+ goto error;
+#endif
+ }
+ return paNoError;
+#ifdef PA_MAC__BLIO_MUTEX
+ error:
+ return result;
+#endif
+}
+
+/*This should be called when you are done with the blio. It can safely be called
+ multiple times if there are no exceptions. */
+PaError destroyBlioRingBuffers( PaMacBlio *blio )
+{
+ PaError result = paNoError;
+ if( blio->inputRingBuffer.buffer ) {
+ free( blio->inputRingBuffer.buffer );
+#ifdef PA_MAC__BLIO_MUTEX
+ result = UNIX_ERR( pthread_mutex_destroy( & blio->inputMutex ) );
+ if( result ) return result;
+ result = UNIX_ERR( pthread_cond_destroy( & blio->inputCond ) );
+ if( result ) return result;
+#endif
+ }
+ blio->inputRingBuffer.buffer = NULL;
+ if( blio->outputRingBuffer.buffer ) {
+ free( blio->outputRingBuffer.buffer );
+#ifdef PA_MAC__BLIO_MUTEX
+ result = UNIX_ERR( pthread_mutex_destroy( & blio->outputMutex ) );
+ if( result ) return result;
+ result = UNIX_ERR( pthread_cond_destroy( & blio->outputCond ) );
+ if( result ) return result;
+#endif
+ }
+ blio->outputRingBuffer.buffer = NULL;
+
+ return result;
+}
+
+/*
+ * this is the BlioCallback function. It expects to recieve a PaMacBlio Object
+ * pointer as userData.
+ *
+ */
+int BlioCallback( const void *input, void *output, unsigned long frameCount,
+ const PaStreamCallbackTimeInfo* timeInfo,
+ PaStreamCallbackFlags statusFlags,
+ void *userData )
+{
+ PaMacBlio *blio = (PaMacBlio*)userData;
+ long avail;
+ long toRead;
+ long toWrite;
+
+ /* set flags returned by OS: */
+ OSAtomicOr32( statusFlags, &blio->statusFlags ) ;
+
+ /* --- Handle Input Buffer --- */
+ if( blio->inChan ) {
+ avail = PaUtil_GetRingBufferWriteAvailable( &blio->inputRingBuffer );
+
+ /* check for underflow */
+ if( avail < frameCount * blio->inputSampleSize * blio->inChan )
+ OSAtomicOr32( paInputOverflow, &blio->statusFlags );
+
+ toRead = MIN( avail, frameCount * blio->inputSampleSize * blio->inChan );
+
+ /* copy the data */
+ /*printf( "reading %d\n", toRead );*/
+ assert( toRead == PaUtil_WriteRingBuffer( &blio->inputRingBuffer, input, toRead ) );
+#ifdef PA_MAC__BLIO_MUTEX
+ /* Priority inversion. See notes below. */
+ blioSetIsInputEmpty( blio, false );
+#endif
+ }
+
+
+ /* --- Handle Output Buffer --- */
+ if( blio->outChan ) {
+ avail = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer );
+
+ /* check for underflow */
+ if( avail < frameCount * blio->outputSampleSize * blio->outChan )
+ OSAtomicOr32( paOutputUnderflow, &blio->statusFlags );
+
+ toWrite = MIN( avail, frameCount * blio->outputSampleSize * blio->outChan );
+
+ if( toWrite != frameCount * blio->outputSampleSize * blio->outChan )
+ bzero( ((char *)output)+toWrite,
+ frameCount * blio->outputSampleSize * blio->outChan - toWrite );
+ /* copy the data */
+ /*printf( "writing %d\n", toWrite );*/
+ assert( toWrite == PaUtil_ReadRingBuffer( &blio->outputRingBuffer, output, toWrite ) );
+#ifdef PA_MAC__BLIO_MUTEX
+ /* We have a priority inversion here. However, we will only have to
+ wait if this was true and is now false, which means we've got
+ some room in the buffer.
+ Hopefully problems will be minimized. */
+ blioSetIsOutputFull( blio, false );
+#endif
+ }
+
+ return paContinue;
+}
+
+PaError ReadStream( PaStream* stream,
+ void *buffer,
+ unsigned long frames )
+{
+ PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;
+ char *cbuf = (char *) buffer;
+ PaError ret = paNoError;
+ VVDBUG(("ReadStream()\n"));
+
+ while( frames > 0 ) {
+ long avail;
+ long toRead;
+ do {
+ avail = PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer );
+/*
+ printf( "Read Buffer is %%%g full: %ld of %ld.\n",
+ 100 * (float)avail / (float) blio->inputRingBuffer.bufferSize,
+ avail, blio->inputRingBuffer.bufferSize );
+*/
+ if( avail == 0 ) {
+#ifdef PA_MAC_BLIO_MUTEX
+ /**block when empty*/
+ ret = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) );
+ if( ret )
+ return ret;
+ while( blio->isInputEmpty ) {
+ ret = UNIX_ERR( pthread_cond_wait( &blio->inputCond, &blio->inputMutex ) );
+ if( ret )
+ return ret;
+ }
+ ret = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) );
+ if( ret )
+ return ret;
+#else
+ Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL );
+#endif
+ }
+ } while( avail == 0 );
+ toRead = MIN( avail, frames * blio->inputSampleSize * blio->inChan );
+ toRead -= toRead % blio->inputSampleSize * blio->inChan ;
+ PaUtil_ReadRingBuffer( &blio->inputRingBuffer, (void *)cbuf, toRead );
+ cbuf += toRead;
+ frames -= toRead / ( blio->inputSampleSize * blio->inChan );
+
+ if( toRead == avail ) {
+#ifdef PA_MAC_BLIO_MUTEX
+ /* we just emptied the buffer, so we need to mark it as empty. */
+ ret = blioSetIsInputEmpty( blio, true );
+ if( ret )
+ return ret;
+ /* of course, in the meantime, the callback may have put some sats
+ in, so
+ so check for that, too, to avoid a race condition. */
+ if( PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer ) ) {
+ blioSetIsInputEmpty( blio, false );
+ if( ret )
+ return ret;
+ }
+#endif
+ }
+ }
+
+ /* Report either paNoError or paInputOverflowed. */
+ /* may also want to report other errors, but this is non-standard. */
+ ret = blio->statusFlags & paInputOverflow;
+
+ /* report underflow only once: */
+ if( ret ) {
+ OSAtomicAnd32( ~paInputOverflow, &blio->statusFlags );
+ ret = paInputOverflowed;
+ }
+
+ return ret;
+}
+
+
+PaError WriteStream( PaStream* stream,
+ const void *buffer,
+ unsigned long frames )
+{
+ PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;
+ char *cbuf = (char *) buffer;
+ PaError ret = paNoError;
+ VVDBUG(("WriteStream()\n"));
+
+ while( frames > 0 ) {
+ long avail = 0;
+ long toWrite;
+
+ do {
+ avail = PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer );
+/*
+ printf( "Write Buffer is %%%g full: %ld of %ld.\n",
+ 100 - 100 * (float)avail / (float) blio->outputRingBuffer.bufferSize,
+ avail, blio->outputRingBuffer.bufferSize );
+*/
+ if( avail == 0 ) {
+#ifdef PA_MAC_BLIO_MUTEX
+ /*block while full*/
+ ret = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) );
+ if( ret )
+ return ret;
+ while( blio->isOutputFull ) {
+ ret = UNIX_ERR( pthread_cond_wait( &blio->outputCond, &blio->outputMutex ) );
+ if( ret )
+ return ret;
+ }
+ ret = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) );
+ if( ret )
+ return ret;
+#else
+ Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL );
+#endif
+ }
+ } while( avail == 0 );
+
+ toWrite = MIN( avail, frames * blio->outputSampleSize * blio->outChan );
+ toWrite -= toWrite % blio->outputSampleSize * blio->outChan ;
+ PaUtil_WriteRingBuffer( &blio->outputRingBuffer, (void *)cbuf, toWrite );
+ cbuf += toWrite;
+ frames -= toWrite / ( blio->outputSampleSize * blio->outChan );
+
+#ifdef PA_MAC_BLIO_MUTEX
+ if( toWrite == avail ) {
+ /* we just filled up the buffer, so we need to mark it as filled. */
+ ret = blioSetIsOutputFull( blio, true );
+ if( ret )
+ return ret;
+ /* of course, in the meantime, we may have emptied the buffer, so
+ so check for that, too, to avoid a race condition. */
+ if( PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer ) ) {
+ blioSetIsOutputFull( blio, false );
+ if( ret )
+ return ret;
+ }
+ }
+#endif
+ }
+
+ /* Report either paNoError or paOutputUnderflowed. */
+ /* may also want to report other errors, but this is non-standard. */
+ ret = blio->statusFlags & paOutputUnderflow;
+
+ /* report underflow only once: */
+ if( ret ) {
+ OSAtomicAnd32( ~paOutputUnderflow, &blio->statusFlags );
+ ret = paOutputUnderflowed;
+ }
+
+ return ret;
+}
+
+/*
+ *
+ */
+void waitUntilBlioWriteBufferIsFlushed( PaMacBlio *blio )
+{
+ if( blio->outputRingBuffer.buffer ) {
+ long avail = PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer );
+ while( avail != blio->outputRingBuffer.bufferSize ) {
+ if( avail == 0 )
+ Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL );
+ avail = PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer );
+ }
+ }
+}
+
+
+signed long GetStreamReadAvailable( PaStream* stream )
+{
+ PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;
+ VVDBUG(("GetStreamReadAvailable()\n"));
+
+ return PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer )
+ / ( blio->outputSampleSize * blio->outChan );
+}
+
+
+signed long GetStreamWriteAvailable( PaStream* stream )
+{
+ PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio;
+ VVDBUG(("GetStreamWriteAvailable()\n"));
+
+ return PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer )
+ / ( blio->outputSampleSize * blio->outChan );
+}
+
diff --git a/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h
new file mode 100644
index 00000000..8ad79eaa
--- /dev/null
+++ b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h
@@ -0,0 +1,133 @@
+/*
+ * Internal blocking interfaces for PortAudio Apple AUHAL implementation
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
+ *
+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,
+ * Gord Peters, Stephane Letz, and Greg Pfiel.
+ *
+ * The following people also deserve acknowledgements:
+ *
+ * Olivier Tristan for feedback and testing
+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
+ * interface.
+ *
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostaip_src
+*/
+
+#ifndef PA_MAC_CORE_BLOCKING_H_
+#define PA_MAC_CORE_BLOCKING_H_
+
+#include "pa_ringbuffer.h"
+#include "portaudio.h"
+#include "pa_mac_core_utilities.h"
+
+/*
+ * Number of miliseconds to busy wait whil waiting for data in blocking calls.
+ */
+#define PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL (5)
+/*
+ * Define exactly one of these blocking methods
+ * PA_MAC_BLIO_MUTEX is not actively maintained.
+ */
+#define PA_MAC_BLIO_BUSY_WAIT
+/*
+#define PA_MAC_BLIO_MUTEX
+*/
+
+typedef struct {
+ PaUtilRingBuffer inputRingBuffer;
+ PaUtilRingBuffer outputRingBuffer;
+ PaSampleFormat inputSampleFormat;
+ size_t inputSampleSize;
+ PaSampleFormat outputSampleFormat;
+ size_t outputSampleSize;
+
+ size_t framesPerBuffer;
+
+ int inChan;
+ int outChan;
+
+ //PaStreamCallbackFlags statusFlags;
+ uint32_t statusFlags;
+ PaError errors;
+
+ /* Here we handle blocking, using condition variables. */
+#ifdef PA_MAC_BLIO_MUTEX
+ volatile bool isInputEmpty;
+ pthread_mutex_t inputMutex;
+ pthread_cond_t inputCond;
+
+ volatile bool isOutputFull;
+ pthread_mutex_t outputMutex;
+ pthread_cond_t outputCond;
+#endif
+}
+PaMacBlio;
+
+/*
+ * These functions operate on condition and related variables.
+ */
+
+PaError initializeBlioRingBuffers(
+ PaMacBlio *blio,
+ PaSampleFormat inputSampleFormat,
+ PaSampleFormat outputSampleFormat,
+ size_t framesPerBuffer,
+ long ringBufferSize,
+ int inChan,
+ int outChan );
+PaError destroyBlioRingBuffers( PaMacBlio *blio );
+PaError resetBlioRingBuffers( PaMacBlio *blio );
+
+int BlioCallback(
+ const void *input, void *output,
+ unsigned long frameCount,
+ const PaStreamCallbackTimeInfo* timeInfo,
+ PaStreamCallbackFlags statusFlags,
+ void *userData );
+
+void waitUntilBlioWriteBufferIsFlushed( PaMacBlio *blio );
+
+#endif /*PA_MAC_CORE_BLOCKING_H_*/
diff --git a/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h
new file mode 100644
index 00000000..998b819c
--- /dev/null
+++ b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h
@@ -0,0 +1,162 @@
+/*
+ * Internal interfaces for PortAudio Apple AUHAL implementation
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
+ *
+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,
+ * Gord Peters, Stephane Letz, and Greg Pfiel.
+ *
+ * The following people also deserve acknowledgements:
+ *
+ * Olivier Tristan for feedback and testing
+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
+ * interface.
+ *
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/**
+ @file pa_mac_core
+ @ingroup hostapi_src
+ @author Bjorn Roche
+ @brief AUHAL implementation of PortAudio
+*/
+
+#ifndef PA_MAC_CORE_INTERNAL_H__
+#define PA_MAC_CORE_INTERNAL_H__
+
+#include <AudioUnit/AudioUnit.h>
+#include <AudioToolbox/AudioToolbox.h>
+
+
+#include "portaudio.h"
+#include "pa_util.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_allocation.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "pa_ringbuffer.h"
+
+#include "pa_mac_core_blocking.h"
+
+/* function prototypes */
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+#define RING_BUFFER_ADVANCE_DENOMINATOR (4)
+
+PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+signed long GetStreamReadAvailable( PaStream* stream );
+signed long GetStreamWriteAvailable( PaStream* stream );
+/* PaMacAUHAL - host api datastructure specific to this implementation */
+typedef struct
+{
+ PaUtilHostApiRepresentation inheritedHostApiRep;
+ PaUtilStreamInterface callbackStreamInterface;
+ PaUtilStreamInterface blockingStreamInterface;
+
+ PaUtilAllocationGroup *allocations;
+
+ /* implementation specific data goes here */
+ long devCount;
+ AudioDeviceID *devIds; /*array of all audio devices*/
+ AudioDeviceID defaultIn;
+ AudioDeviceID defaultOut;
+}
+PaMacAUHAL;
+
+
+
+/* stream data structure specifically for this implementation */
+typedef struct PaMacCoreStream
+{
+ PaUtilStreamRepresentation streamRepresentation;
+ PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+ PaUtilBufferProcessor bufferProcessor;
+
+ /* implementation specific data goes here */
+ bool bufferProcessorIsInitialized;
+ AudioUnit inputUnit;
+ AudioUnit outputUnit;
+ AudioDeviceID inputDevice;
+ AudioDeviceID outputDevice;
+ size_t userInChan;
+ size_t userOutChan;
+ size_t inputFramesPerBuffer;
+ size_t outputFramesPerBuffer;
+ PaMacBlio blio;
+ /* We use this ring buffer when input and out devs are different. */
+ PaUtilRingBuffer inputRingBuffer;
+ /* We may need to do SR conversion on input. */
+ AudioConverterRef inputSRConverter;
+ /* We need to preallocate an inputBuffer for reading data. */
+ AudioBufferList inputAudioBufferList;
+ AudioTimeStamp startTime;
+ volatile PaStreamCallbackFlags xrunFlags;
+ volatile bool isTimeSet;
+ volatile enum {
+ STOPPED = 0, /* playback is completely stopped,
+ and the user has called StopStream(). */
+ CALLBACK_STOPPED = 1, /* callback has requested stop,
+ but user has not yet called StopStream(). */
+ STOPPING = 2, /* The stream is in the process of closing.
+ This state is just used internally;
+ externally it is indistinguishable from
+ ACTIVE.*/
+ ACTIVE = 3 /* The stream is active and running. */
+ } state;
+ double sampleRate;
+ //these may be different from the stream sample rate due to SR conversion:
+ double outDeviceSampleRate;
+ double inDeviceSampleRate;
+}
+PaMacCoreStream;
+
+#endif /* PA_MAC_CORE_INTERNAL_H__ */
diff --git a/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_old.c b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_old.c
new file mode 100644
index 00000000..0731b1f9
--- /dev/null
+++ b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_old.c
@@ -0,0 +1,913 @@
+/*
+ * $Id: pa_mac_core_old.c,v 1.1 2007-08-18 23:49:33 millerpuckette Exp $
+ * pa_mac_core.c
+ * Implementation of PortAudio for Mac OS X CoreAudio
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Authors: Ross Bencina and Phil Burk
+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+#include <CoreAudio/CoreAudio.h>
+#include <AudioToolbox/AudioToolbox.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include <assert.h>
+
+#include "portaudio.h"
+#include "pa_trace.h"
+#include "pa_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+
+// ===== constants =====
+
+// ===== structs =====
+#pragma mark structs
+
+// PaMacCoreHostApiRepresentation - host api datastructure specific to this implementation
+typedef struct PaMacCore_HAR
+{
+ PaUtilHostApiRepresentation inheritedHostApiRep;
+ PaUtilStreamInterface callbackStreamInterface;
+ PaUtilStreamInterface blockingStreamInterface;
+
+ PaUtilAllocationGroup *allocations;
+ AudioDeviceID *macCoreDeviceIds;
+}
+PaMacCoreHostApiRepresentation;
+
+typedef struct PaMacCore_DI
+{
+ PaDeviceInfo inheritedDeviceInfo;
+}
+PaMacCoreDeviceInfo;
+
+// PaMacCoreStream - a stream data structure specifically for this implementation
+typedef struct PaMacCore_S
+{
+ PaUtilStreamRepresentation streamRepresentation;
+ PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+ PaUtilBufferProcessor bufferProcessor;
+
+ int primeStreamUsingCallback;
+
+ AudioDeviceID inputDevice;
+ AudioDeviceID outputDevice;
+
+ // Processing thread management --------------
+// HANDLE abortEvent;
+// HANDLE processingThread;
+// DWORD processingThreadId;
+
+ char throttleProcessingThreadOnOverload; // 0 -> don't throtte, non-0 -> throttle
+ int processingThreadPriority;
+ int highThreadPriority;
+ int throttledThreadPriority;
+ unsigned long throttledSleepMsecs;
+
+ int isStopped;
+ volatile int isActive;
+ volatile int stopProcessing; // stop thread once existing buffers have been returned
+ volatile int abortProcessing; // stop thread immediately
+
+// DWORD allBuffersDurationMs; // used to calculate timeouts
+}
+PaMacCoreStream;
+
+// Data needed by the CoreAudio callback functions
+typedef struct PaMacCore_CD
+{
+ PaMacCoreStream *stream;
+ PaStreamCallback *callback;
+ void *userData;
+ PaUtilConverter *inputConverter;
+ PaUtilConverter *outputConverter;
+ void *inputBuffer;
+ void *outputBuffer;
+ int inputChannelCount;
+ int outputChannelCount;
+ PaSampleFormat inputSampleFormat;
+ PaSampleFormat outputSampleFormat;
+ PaUtilTriangularDitherGenerator *ditherGenerator;
+}
+PaMacClientData;
+
+// ===== CoreAudio-PortAudio bridge functions =====
+#pragma mark CoreAudio-PortAudio bridge functions
+
+// Maps CoreAudio OSStatus codes to PortAudio PaError codes
+static PaError conv_err(OSStatus error)
+{
+ PaError result;
+
+ switch (error) {
+ case kAudioHardwareNoError:
+ result = paNoError; break;
+ case kAudioHardwareNotRunningError:
+ result = paInternalError; break;
+ case kAudioHardwareUnspecifiedError:
+ result = paInternalError; break;
+ case kAudioHardwareUnknownPropertyError:
+ result = paInternalError; break;
+ case kAudioHardwareBadPropertySizeError:
+ result = paInternalError; break;
+ case kAudioHardwareIllegalOperationError:
+ result = paInternalError; break;
+ case kAudioHardwareBadDeviceError:
+ result = paInvalidDevice; break;
+ case kAudioHardwareBadStreamError:
+ result = paBadStreamPtr; break;
+ case kAudioHardwareUnsupportedOperationError:
+ result = paInternalError; break;
+ case kAudioDeviceUnsupportedFormatError:
+ result = paSampleFormatNotSupported; break;
+ case kAudioDevicePermissionsError:
+ result = paDeviceUnavailable; break;
+ default:
+ result = paInternalError;
+ }
+
+ return result;
+}
+
+/* This function is unused
+static AudioStreamBasicDescription *InitializeStreamDescription(const PaStreamParameters *parameters, double sampleRate)
+{
+ struct AudioStreamBasicDescription *streamDescription = PaUtil_AllocateMemory(sizeof(AudioStreamBasicDescription));
+ streamDescription->mSampleRate = sampleRate;
+ streamDescription->mFormatID = kAudioFormatLinearPCM;
+ streamDescription->mFormatFlags = 0;
+ streamDescription->mFramesPerPacket = 1;
+
+ if (parameters->sampleFormat & paNonInterleaved) {
+ streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsNonInterleaved;
+ streamDescription->mChannelsPerFrame = 1;
+ streamDescription->mBytesPerFrame = Pa_GetSampleSize(parameters->sampleFormat);
+ streamDescription->mBytesPerPacket = Pa_GetSampleSize(parameters->sampleFormat);
+ }
+ else {
+ streamDescription->mChannelsPerFrame = parameters->channelCount;
+ }
+
+ streamDescription->mBytesPerFrame = Pa_GetSampleSize(parameters->sampleFormat) * streamDescription->mChannelsPerFrame;
+ streamDescription->mBytesPerPacket = streamDescription->mBytesPerFrame * streamDescription->mFramesPerPacket;
+
+ if (parameters->sampleFormat & paFloat32) {
+ streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsFloat;
+ streamDescription->mBitsPerChannel = 32;
+ }
+ else if (parameters->sampleFormat & paInt32) {
+ streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
+ streamDescription->mBitsPerChannel = 32;
+ }
+ else if (parameters->sampleFormat & paInt24) {
+ streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
+ streamDescription->mBitsPerChannel = 24;
+ }
+ else if (parameters->sampleFormat & paInt16) {
+ streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
+ streamDescription->mBitsPerChannel = 16;
+ }
+ else if (parameters->sampleFormat & paInt8) {
+ streamDescription->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
+ streamDescription->mBitsPerChannel = 8;
+ }
+ else if (parameters->sampleFormat & paInt32) {
+ streamDescription->mBitsPerChannel = 8;
+ }
+
+ return streamDescription;
+}
+*/
+
+static PaStreamCallbackTimeInfo *InitializeTimeInfo(const AudioTimeStamp* now, const AudioTimeStamp* inputTime, const AudioTimeStamp* outputTime)
+{
+ PaStreamCallbackTimeInfo *timeInfo = PaUtil_AllocateMemory(sizeof(PaStreamCallbackTimeInfo));
+
+ timeInfo->inputBufferAdcTime = inputTime->mSampleTime;
+ timeInfo->currentTime = now->mSampleTime;
+ timeInfo->outputBufferDacTime = outputTime->mSampleTime;
+
+ return timeInfo;
+}
+
+// ===== support functions =====
+#pragma mark support functions
+
+static void CleanUp(PaMacCoreHostApiRepresentation *macCoreHostApi)
+{
+ if( macCoreHostApi->allocations )
+ {
+ PaUtil_FreeAllAllocations( macCoreHostApi->allocations );
+ PaUtil_DestroyAllocationGroup( macCoreHostApi->allocations );
+ }
+
+ PaUtil_FreeMemory( macCoreHostApi );
+}
+
+static PaError GetChannelInfo(PaDeviceInfo *deviceInfo, AudioDeviceID macCoreDeviceId, int isInput)
+{
+ UInt32 propSize;
+ PaError err = paNoError;
+ UInt32 i;
+ int numChannels = 0;
+ AudioBufferList *buflist;
+
+ err = conv_err(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, NULL));
+ buflist = PaUtil_AllocateMemory(propSize);
+ err = conv_err(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, buflist));
+ if (!err) {
+ for (i = 0; i < buflist->mNumberBuffers; ++i) {
+ numChannels += buflist->mBuffers[i].mNumberChannels;
+ }
+
+ if (isInput)
+ deviceInfo->maxInputChannels = numChannels;
+ else
+ deviceInfo->maxOutputChannels = numChannels;
+
+ int frameLatency;
+ propSize = sizeof(UInt32);
+ err = conv_err(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &frameLatency));
+ if (!err) {
+ double secondLatency = frameLatency / deviceInfo->defaultSampleRate;
+ if (isInput) {
+ deviceInfo->defaultLowInputLatency = secondLatency;
+ deviceInfo->defaultHighInputLatency = secondLatency;
+ }
+ else {
+ deviceInfo->defaultLowOutputLatency = secondLatency;
+ deviceInfo->defaultHighOutputLatency = secondLatency;
+ }
+ }
+ }
+ PaUtil_FreeMemory(buflist);
+
+ return err;
+}
+
+static PaError InitializeDeviceInfo(PaMacCoreDeviceInfo *macCoreDeviceInfo, AudioDeviceID macCoreDeviceId, PaHostApiIndex hostApiIndex )
+{
+ PaDeviceInfo *deviceInfo = &macCoreDeviceInfo->inheritedDeviceInfo;
+ deviceInfo->structVersion = 2;
+ deviceInfo->hostApi = hostApiIndex;
+
+ PaError err = paNoError;
+ UInt32 propSize;
+
+ err = conv_err(AudioDeviceGetPropertyInfo(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, NULL));
+ // FIXME: this allocation should be part of the allocations group
+ char *name = PaUtil_AllocateMemory(propSize);
+ err = conv_err(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, name));
+ if (!err) {
+ deviceInfo->name = name;
+ }
+
+ Float64 sampleRate;
+ propSize = sizeof(Float64);
+ err = conv_err(AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &sampleRate));
+ if (!err) {
+ deviceInfo->defaultSampleRate = sampleRate;
+ }
+
+
+ // Get channel info
+ err = GetChannelInfo(deviceInfo, macCoreDeviceId, 1);
+ err = GetChannelInfo(deviceInfo, macCoreDeviceId, 0);
+
+ return err;
+}
+
+static PaError InitializeDeviceInfos( PaMacCoreHostApiRepresentation *macCoreHostApi, PaHostApiIndex hostApiIndex )
+{
+ PaError result = paNoError;
+ PaUtilHostApiRepresentation *hostApi;
+ PaMacCoreDeviceInfo *deviceInfoArray;
+
+ // initialise device counts and default devices under the assumption that there are no devices. These values are incremented below if and when devices are successfully initialized.
+ hostApi = &macCoreHostApi->inheritedHostApiRep;
+ hostApi->info.deviceCount = 0;
+ hostApi->info.defaultInputDevice = paNoDevice;
+ hostApi->info.defaultOutputDevice = paNoDevice;
+
+ UInt32 propsize;
+ AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &propsize, NULL);
+ int numDevices = propsize / sizeof(AudioDeviceID);
+ hostApi->info.deviceCount = numDevices;
+ if (numDevices > 0) {
+ hostApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+ macCoreHostApi->allocations, sizeof(PaDeviceInfo*) * numDevices );
+ if( !hostApi->deviceInfos )
+ {
+ return paInsufficientMemory;
+ }
+
+ // allocate all device info structs in a contiguous block
+ deviceInfoArray = (PaMacCoreDeviceInfo*)PaUtil_GroupAllocateMemory(
+ macCoreHostApi->allocations, sizeof(PaMacCoreDeviceInfo) * numDevices );
+ if( !deviceInfoArray )
+ {
+ return paInsufficientMemory;
+ }
+
+ macCoreHostApi->macCoreDeviceIds = PaUtil_GroupAllocateMemory(macCoreHostApi->allocations, propsize);
+ AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &propsize, macCoreHostApi->macCoreDeviceIds);
+
+ AudioDeviceID defaultInputDevice, defaultOutputDevice;
+ propsize = sizeof(AudioDeviceID);
+ AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &propsize, &defaultInputDevice);
+ AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &propsize, &defaultOutputDevice);
+
+ UInt32 i;
+ for (i = 0; i < numDevices; ++i) {
+ if (macCoreHostApi->macCoreDeviceIds[i] == defaultInputDevice) {
+ hostApi->info.defaultInputDevice = i;
+ }
+ if (macCoreHostApi->macCoreDeviceIds[i] == defaultOutputDevice) {
+ hostApi->info.defaultOutputDevice = i;
+ }
+ InitializeDeviceInfo(&deviceInfoArray[i], macCoreHostApi->macCoreDeviceIds[i], hostApiIndex);
+ hostApi->deviceInfos[i] = &(deviceInfoArray[i].inheritedDeviceInfo);
+ }
+ }
+
+ return result;
+}
+
+static OSStatus CheckFormat(AudioDeviceID macCoreDeviceId, const PaStreamParameters *parameters, double sampleRate, int isInput)
+{
+ UInt32 propSize = sizeof(AudioStreamBasicDescription);
+ AudioStreamBasicDescription *streamDescription = PaUtil_AllocateMemory(propSize);
+
+ streamDescription->mSampleRate = sampleRate;
+ streamDescription->mFormatID = 0;
+ streamDescription->mFormatFlags = 0;
+ streamDescription->mBytesPerPacket = 0;
+ streamDescription->mFramesPerPacket = 0;
+ streamDescription->mBytesPerFrame = 0;
+ streamDescription->mChannelsPerFrame = 0;
+ streamDescription->mBitsPerChannel = 0;
+ streamDescription->mReserved = 0;
+
+ OSStatus result = AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamFormatSupported, &propSize, streamDescription);
+ PaUtil_FreeMemory(streamDescription);
+ return result;
+}
+
+static OSStatus CopyInputData(PaMacClientData* destination, const AudioBufferList *source, unsigned long frameCount)
+{
+ int frameSpacing, channelSpacing;
+ if (destination->inputSampleFormat & paNonInterleaved) {
+ frameSpacing = 1;
+ channelSpacing = destination->inputChannelCount;
+ }
+ else {
+ frameSpacing = destination->inputChannelCount;
+ channelSpacing = 1;
+ }
+
+ AudioBuffer const *inputBuffer = &source->mBuffers[0];
+ void *coreAudioBuffer = inputBuffer->mData;
+ void *portAudioBuffer = destination->inputBuffer;
+ UInt32 i, streamNumber, streamChannel;
+ for (i = streamNumber = streamChannel = 0; i < destination->inputChannelCount; ++i, ++streamChannel) {
+ if (streamChannel >= inputBuffer->mNumberChannels) {
+ ++streamNumber;
+ inputBuffer = &source->mBuffers[streamNumber];
+ coreAudioBuffer = inputBuffer->mData;
+ streamChannel = 0;
+ }
+ destination->inputConverter(portAudioBuffer, frameSpacing, coreAudioBuffer, inputBuffer->mNumberChannels, frameCount, destination->ditherGenerator);
+ coreAudioBuffer += sizeof(Float32);
+ portAudioBuffer += Pa_GetSampleSize(destination->inputSampleFormat) * channelSpacing;
+ }
+ return noErr;
+}
+
+static OSStatus CopyOutputData(AudioBufferList* destination, PaMacClientData *source, unsigned long frameCount)
+{
+ int frameSpacing, channelSpacing;
+ if (source->outputSampleFormat & paNonInterleaved) {
+ frameSpacing = 1;
+ channelSpacing = source->outputChannelCount;
+ }
+ else {
+ frameSpacing = source->outputChannelCount;
+ channelSpacing = 1;
+ }
+
+ AudioBuffer *outputBuffer = &destination->mBuffers[0];
+ void *coreAudioBuffer = outputBuffer->mData;
+ void *portAudioBuffer = source->outputBuffer;
+ UInt32 i, streamNumber, streamChannel;
+ for (i = streamNumber = streamChannel = 0; i < source->outputChannelCount; ++i, ++streamChannel) {
+ if (streamChannel >= outputBuffer->mNumberChannels) {
+ ++streamNumber;
+ outputBuffer = &destination->mBuffers[streamNumber];
+ coreAudioBuffer = outputBuffer->mData;
+ streamChannel = 0;
+ }
+ source->outputConverter(coreAudioBuffer, outputBuffer->mNumberChannels, portAudioBuffer, frameSpacing, frameCount, NULL);
+ coreAudioBuffer += sizeof(Float32);
+ portAudioBuffer += Pa_GetSampleSize(source->outputSampleFormat) * channelSpacing;
+ }
+ return noErr;
+}
+
+static OSStatus AudioIOProc( AudioDeviceID inDevice,
+ const AudioTimeStamp* inNow,
+ const AudioBufferList* inInputData,
+ const AudioTimeStamp* inInputTime,
+ AudioBufferList* outOutputData,
+ const AudioTimeStamp* inOutputTime,
+ void* inClientData)
+{
+ PaMacClientData *clientData = (PaMacClientData *)inClientData;
+ PaStreamCallbackTimeInfo *timeInfo = InitializeTimeInfo(inNow, inInputTime, inOutputTime);
+
+ PaUtil_BeginCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer );
+
+ AudioBuffer *outputBuffer = &outOutputData->mBuffers[0];
+ unsigned long frameCount = outputBuffer->mDataByteSize / (outputBuffer->mNumberChannels * sizeof(Float32));
+
+ if (clientData->inputBuffer) {
+ CopyInputData(clientData, inInputData, frameCount);
+ }
+ PaStreamCallbackResult result = clientData->callback(clientData->inputBuffer, clientData->outputBuffer, frameCount, timeInfo, paNoFlag, clientData->userData);
+ if (clientData->outputBuffer) {
+ CopyOutputData(outOutputData, clientData, frameCount);
+ }
+
+ PaUtil_EndCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer, frameCount );
+
+ if (result == paComplete || result == paAbort) {
+ Pa_StopStream(clientData->stream);
+ }
+
+ PaUtil_FreeMemory( timeInfo );
+ return noErr;
+}
+
+// This is not for input-only streams, this is for streams where the input device is different from the output device
+static OSStatus AudioInputProc( AudioDeviceID inDevice,
+ const AudioTimeStamp* inNow,
+ const AudioBufferList* inInputData,
+ const AudioTimeStamp* inInputTime,
+ AudioBufferList* outOutputData,
+ const AudioTimeStamp* inOutputTime,
+ void* inClientData)
+{
+ PaMacClientData *clientData = (PaMacClientData *)inClientData;
+ PaStreamCallbackTimeInfo *timeInfo = InitializeTimeInfo(inNow, inInputTime, inOutputTime);
+
+ PaUtil_BeginCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer );
+
+ AudioBuffer const *inputBuffer = &inInputData->mBuffers[0];
+ unsigned long frameCount = inputBuffer->mDataByteSize / (inputBuffer->mNumberChannels * sizeof(Float32));
+
+ CopyInputData(clientData, inInputData, frameCount);
+ PaStreamCallbackResult result = clientData->callback(clientData->inputBuffer, clientData->outputBuffer, frameCount, timeInfo, paNoFlag, clientData->userData);
+
+ PaUtil_EndCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer, frameCount );
+ if( result == paComplete || result == paAbort )
+ Pa_StopStream(clientData->stream);
+ PaUtil_FreeMemory( timeInfo );
+ return noErr;
+}
+
+// This is not for output-only streams, this is for streams where the input device is different from the output device
+static OSStatus AudioOutputProc( AudioDeviceID inDevice,
+ const AudioTimeStamp* inNow,
+ const AudioBufferList* inInputData,
+ const AudioTimeStamp* inInputTime,
+ AudioBufferList* outOutputData,
+ const AudioTimeStamp* inOutputTime,
+ void* inClientData)
+{
+ PaMacClientData *clientData = (PaMacClientData *)inClientData;
+ //PaStreamCallbackTimeInfo *timeInfo = InitializeTimeInfo(inNow, inInputTime, inOutputTime);
+
+ PaUtil_BeginCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer );
+
+ AudioBuffer *outputBuffer = &outOutputData->mBuffers[0];
+ unsigned long frameCount = outputBuffer->mDataByteSize / (outputBuffer->mNumberChannels * sizeof(Float32));
+
+ //clientData->callback(NULL, clientData->outputBuffer, frameCount, timeInfo, paNoFlag, clientData->userData);
+
+ CopyOutputData(outOutputData, clientData, frameCount);
+
+ PaUtil_EndCpuLoadMeasurement( &clientData->stream->cpuLoadMeasurer, frameCount );
+ return noErr;
+}
+
+static PaError SetSampleRate(AudioDeviceID device, double sampleRate, int isInput)
+{
+ PaError result = paNoError;
+
+ double actualSampleRate;
+ UInt32 propSize = sizeof(double);
+ result = conv_err(AudioDeviceSetProperty(device, NULL, 0, isInput, kAudioDevicePropertyNominalSampleRate, propSize, &sampleRate));
+
+ result = conv_err(AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyNominalSampleRate, &propSize, &actualSampleRate));
+
+ if (result == paNoError && actualSampleRate != sampleRate) {
+ result = paInvalidSampleRate;
+ }
+
+ return result;
+}
+
+static PaError SetFramesPerBuffer(AudioDeviceID device, unsigned long framesPerBuffer, int isInput)
+{
+ PaError result = paNoError;
+ UInt32 preferredFramesPerBuffer = framesPerBuffer;
+ // while (preferredFramesPerBuffer > UINT32_MAX) {
+ // preferredFramesPerBuffer /= 2;
+ // }
+
+ UInt32 actualFramesPerBuffer;
+ UInt32 propSize = sizeof(UInt32);
+ result = conv_err(AudioDeviceSetProperty(device, NULL, 0, isInput, kAudioDevicePropertyBufferFrameSize, propSize, &preferredFramesPerBuffer));
+
+ result = conv_err(AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyBufferFrameSize, &propSize, &actualFramesPerBuffer));
+
+ if (result != paNoError) {
+ // do nothing
+ }
+ else if (actualFramesPerBuffer > framesPerBuffer) {
+ result = paBufferTooSmall;
+ }
+ else if (actualFramesPerBuffer < framesPerBuffer) {
+ result = paBufferTooBig;
+ }
+
+ return result;
+}
+
+static PaError SetUpUnidirectionalStream(AudioDeviceID device, double sampleRate, unsigned long framesPerBuffer, int isInput)
+{
+ PaError err = paNoError;
+ err = SetSampleRate(device, sampleRate, isInput);
+ if( err == paNoError )
+ err = SetFramesPerBuffer(device, framesPerBuffer, isInput);
+ return err;
+}
+
+// ===== PortAudio functions =====
+#pragma mark PortAudio functions
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif // __cplusplus
+
+ PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+ PaMacCoreHostApiRepresentation *macCoreHostApi = (PaMacCoreHostApiRepresentation*)hostApi;
+
+ CleanUp(macCoreHostApi);
+}
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate )
+{
+ PaMacCoreHostApiRepresentation *macCoreHostApi = (PaMacCoreHostApiRepresentation*)hostApi;
+ PaDeviceInfo *deviceInfo;
+
+ PaError result = paNoError;
+ if (inputParameters) {
+ deviceInfo = macCoreHostApi->inheritedHostApiRep.deviceInfos[inputParameters->device];
+ if (inputParameters->channelCount > deviceInfo->maxInputChannels)
+ result = paInvalidChannelCount;
+ else if (CheckFormat(macCoreHostApi->macCoreDeviceIds[inputParameters->device], inputParameters, sampleRate, 1) != kAudioHardwareNoError) {
+ result = paInvalidSampleRate;
+ }
+ }
+ if (outputParameters && result == paNoError) {
+ deviceInfo = macCoreHostApi->inheritedHostApiRep.deviceInfos[outputParameters->device];
+ if (outputParameters->channelCount > deviceInfo->maxOutputChannels)
+ result = paInvalidChannelCount;
+ else if (CheckFormat(macCoreHostApi->macCoreDeviceIds[outputParameters->device], outputParameters, sampleRate, 0) != kAudioHardwareNoError) {
+ result = paInvalidSampleRate;
+ }
+ }
+
+ return result;
+}
+
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+ PaStream** s,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate,
+ unsigned long framesPerBuffer,
+ PaStreamFlags streamFlags,
+ PaStreamCallback *streamCallback,
+ void *userData )
+{
+ PaError err = paNoError;
+ PaMacCoreHostApiRepresentation *macCoreHostApi = (PaMacCoreHostApiRepresentation *)hostApi;
+ PaMacCoreStream *stream = PaUtil_AllocateMemory(sizeof(PaMacCoreStream));
+ stream->isActive = 0;
+ stream->isStopped = 1;
+ stream->inputDevice = kAudioDeviceUnknown;
+ stream->outputDevice = kAudioDeviceUnknown;
+
+ PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+ ( (streamCallback)
+ ? &macCoreHostApi->callbackStreamInterface
+ : &macCoreHostApi->blockingStreamInterface ),
+ streamCallback, userData );
+ PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+
+ *s = (PaStream*)stream;
+ PaMacClientData *clientData = PaUtil_AllocateMemory(sizeof(PaMacClientData));
+ clientData->stream = stream;
+ clientData->callback = streamCallback;
+ clientData->userData = userData;
+ clientData->inputBuffer = 0;
+ clientData->outputBuffer = 0;
+ clientData->ditherGenerator = PaUtil_AllocateMemory(sizeof(PaUtilTriangularDitherGenerator));
+ PaUtil_InitializeTriangularDitherState(clientData->ditherGenerator);
+
+ if (inputParameters != NULL) {
+ stream->inputDevice = macCoreHostApi->macCoreDeviceIds[inputParameters->device];
+ clientData->inputConverter = PaUtil_SelectConverter(paFloat32, inputParameters->sampleFormat, streamFlags);
+ clientData->inputBuffer = PaUtil_AllocateMemory(Pa_GetSampleSize(inputParameters->sampleFormat) * framesPerBuffer * inputParameters->channelCount);
+ clientData->inputChannelCount = inputParameters->channelCount;
+ clientData->inputSampleFormat = inputParameters->sampleFormat;
+ err = SetUpUnidirectionalStream(stream->inputDevice, sampleRate, framesPerBuffer, 1);
+ }
+
+ if (err == paNoError && outputParameters != NULL) {
+ stream->outputDevice = macCoreHostApi->macCoreDeviceIds[outputParameters->device];
+ clientData->outputConverter = PaUtil_SelectConverter(outputParameters->sampleFormat, paFloat32, streamFlags);
+ clientData->outputBuffer = PaUtil_AllocateMemory(Pa_GetSampleSize(outputParameters->sampleFormat) * framesPerBuffer * outputParameters->channelCount);
+ clientData->outputChannelCount = outputParameters->channelCount;
+ clientData->outputSampleFormat = outputParameters->sampleFormat;
+ err = SetUpUnidirectionalStream(stream->outputDevice, sampleRate, framesPerBuffer, 0);
+ }
+
+ if (inputParameters == NULL || outputParameters == NULL || stream->inputDevice == stream->outputDevice) {
+ AudioDeviceID device = (inputParameters == NULL) ? stream->outputDevice : stream->inputDevice;
+
+ AudioDeviceAddIOProc(device, AudioIOProc, clientData);
+ }
+ else {
+ // using different devices for input and output
+ AudioDeviceAddIOProc(stream->inputDevice, AudioInputProc, clientData);
+ AudioDeviceAddIOProc(stream->outputDevice, AudioOutputProc, clientData);
+ }
+
+ return err;
+}
+
+// Note: When CloseStream() is called, the multi-api layer ensures that the stream has already been stopped or aborted.
+static PaError CloseStream( PaStream* s )
+{
+ PaError err = paNoError;
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+
+ PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
+
+ if (stream->inputDevice != kAudioDeviceUnknown) {
+ if (stream->outputDevice == kAudioDeviceUnknown || stream->outputDevice == stream->inputDevice) {
+ err = conv_err(AudioDeviceRemoveIOProc(stream->inputDevice, AudioIOProc));
+ }
+ else {
+ err = conv_err(AudioDeviceRemoveIOProc(stream->inputDevice, AudioInputProc));
+ err = conv_err(AudioDeviceRemoveIOProc(stream->outputDevice, AudioOutputProc));
+ }
+ }
+ else {
+ err = conv_err(AudioDeviceRemoveIOProc(stream->outputDevice, AudioIOProc));
+ }
+
+ return err;
+}
+
+
+static PaError StartStream( PaStream *s )
+{
+ PaError err = paNoError;
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+
+ if (stream->inputDevice != kAudioDeviceUnknown) {
+ if (stream->outputDevice == kAudioDeviceUnknown || stream->outputDevice == stream->inputDevice) {
+ err = conv_err(AudioDeviceStart(stream->inputDevice, AudioIOProc));
+ }
+ else {
+ err = conv_err(AudioDeviceStart(stream->inputDevice, AudioInputProc));
+ err = conv_err(AudioDeviceStart(stream->outputDevice, AudioOutputProc));
+ }
+ }
+ else {
+ err = conv_err(AudioDeviceStart(stream->outputDevice, AudioIOProc));
+ }
+
+ stream->isActive = 1;
+ stream->isStopped = 0;
+ return err;
+}
+
+static PaError AbortStream( PaStream *s )
+{
+ PaError err = paNoError;
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+
+ if (stream->inputDevice != kAudioDeviceUnknown) {
+ if (stream->outputDevice == kAudioDeviceUnknown || stream->outputDevice == stream->inputDevice) {
+ err = conv_err(AudioDeviceStop(stream->inputDevice, AudioIOProc));
+ }
+ else {
+ err = conv_err(AudioDeviceStop(stream->inputDevice, AudioInputProc));
+ err = conv_err(AudioDeviceStop(stream->outputDevice, AudioOutputProc));
+ }
+ }
+ else {
+ err = conv_err(AudioDeviceStop(stream->outputDevice, AudioIOProc));
+ }
+
+ stream->isActive = 0;
+ stream->isStopped = 1;
+ return err;
+}
+
+static PaError StopStream( PaStream *s )
+{
+ // TODO: this should be nicer than abort
+ return AbortStream(s);
+}
+
+static PaError IsStreamStopped( PaStream *s )
+{
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+
+ return stream->isStopped;
+}
+
+
+static PaError IsStreamActive( PaStream *s )
+{
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+
+ return stream->isActive;
+}
+
+
+static PaTime GetStreamTime( PaStream *s )
+{
+ OSStatus err;
+ PaTime result;
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+
+ AudioTimeStamp *timeStamp = PaUtil_AllocateMemory(sizeof(AudioTimeStamp));
+ if (stream->inputDevice != kAudioDeviceUnknown) {
+ err = AudioDeviceGetCurrentTime(stream->inputDevice, timeStamp);
+ }
+ else {
+ err = AudioDeviceGetCurrentTime(stream->outputDevice, timeStamp);
+ }
+
+ result = err ? 0 : timeStamp->mSampleTime;
+ PaUtil_FreeMemory(timeStamp);
+
+ return result;
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+ PaMacCoreStream *stream = (PaMacCoreStream*)s;
+
+ return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+
+// As separate stream interfaces are used for blocking and callback streams, the following functions can be guaranteed to only be called for blocking streams.
+
+static PaError ReadStream( PaStream* s,
+ void *buffer,
+ unsigned long frames )
+{
+ return paInternalError;
+}
+
+
+static PaError WriteStream( PaStream* s,
+ const void *buffer,
+ unsigned long frames )
+{
+ return paInternalError;
+}
+
+
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+ return paInternalError;
+}
+
+
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+ return paInternalError;
+}
+
+// HostAPI-specific initialization function
+PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+ PaError result = paNoError;
+ PaMacCoreHostApiRepresentation *macCoreHostApi = (PaMacCoreHostApiRepresentation *)PaUtil_AllocateMemory( sizeof(PaMacCoreHostApiRepresentation) );
+ if( !macCoreHostApi )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ macCoreHostApi->allocations = PaUtil_CreateAllocationGroup();
+ if( !macCoreHostApi->allocations )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ *hostApi = &macCoreHostApi->inheritedHostApiRep;
+ (*hostApi)->info.structVersion = 1;
+ (*hostApi)->info.type = paCoreAudio;
+ (*hostApi)->info.name = "CoreAudio";
+
+ result = InitializeDeviceInfos(macCoreHostApi, hostApiIndex);
+ if (result != paNoError) {
+ goto error;
+ }
+
+ // Set up the proper callbacks to this HostApi's functions
+ (*hostApi)->Terminate = Terminate;
+ (*hostApi)->OpenStream = OpenStream;
+ (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+ PaUtil_InitializeStreamInterface( &macCoreHostApi->callbackStreamInterface, CloseStream, StartStream,
+ StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+ GetStreamTime, GetStreamCpuLoad,
+ PaUtil_DummyRead, PaUtil_DummyWrite,
+ PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
+
+ PaUtil_InitializeStreamInterface( &macCoreHostApi->blockingStreamInterface, CloseStream, StartStream,
+ StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+ GetStreamTime, PaUtil_DummyGetCpuLoad,
+ ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+
+ return result;
+
+error:
+ if( macCoreHostApi ) {
+ CleanUp(macCoreHostApi);
+ }
+
+ return result;
+}
diff --git a/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c
new file mode 100644
index 00000000..37403251
--- /dev/null
+++ b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c
@@ -0,0 +1,611 @@
+/*
+ * Helper and utility functions for pa_mac_core.c (Apple AUHAL implementation)
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
+ *
+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,
+ * Gord Peters, Stephane Letz, and Greg Pfiel.
+ *
+ * The following people also deserve acknowledgements:
+ *
+ * Olivier Tristan for feedback and testing
+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
+ * interface.
+ *
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#include "pa_mac_core_utilities.h"
+
+PaError PaMacCore_SetUnixError( int err, int line )
+{
+ PaError ret;
+ const char *errorText;
+
+ if( err == 0 )
+ {
+ return paNoError;
+ }
+
+ ret = paNoError;
+ errorText = strerror( err );
+
+ /** Map Unix error to PaError. Pretty much the only one that maps
+ is ENOMEM. */
+ if( err == ENOMEM )
+ ret = paInsufficientMemory;
+ else
+ ret = paInternalError;
+
+ DBUG(("%d on line %d: msg='%s'\n", err, line, errorText));
+ PaUtil_SetLastHostErrorInfo( paCoreAudio, err, errorText );
+
+ return ret;
+}
+
+/*
+ * Translates MacOS generated errors into PaErrors
+ */
+PaError PaMacCore_SetError(OSStatus error, int line, int isError)
+{
+ /*FIXME: still need to handle possible ComponentResult values.*/
+ /* unfortunately, they don't seem to be documented anywhere.*/
+ PaError result;
+ const char *errorType;
+ const char *errorText;
+
+ switch (error) {
+ case kAudioHardwareNoError:
+ return paNoError;
+ case kAudioHardwareNotRunningError:
+ errorText = "Audio Hardware Not Running";
+ result = paInternalError; break;
+ case kAudioHardwareUnspecifiedError:
+ errorText = "Unspecified Audio Hardware Error";
+ result = paInternalError; break;
+ case kAudioHardwareUnknownPropertyError:
+ errorText = "Audio Hardware: Unknown Property";
+ result = paInternalError; break;
+ case kAudioHardwareBadPropertySizeError:
+ errorText = "Audio Hardware: Bad Property Size";
+ result = paInternalError; break;
+ case kAudioHardwareIllegalOperationError:
+ errorText = "Audio Hardware: Illegal Operation";
+ result = paInternalError; break;
+ case kAudioHardwareBadDeviceError:
+ errorText = "Audio Hardware: Bad Device";
+ result = paInvalidDevice; break;
+ case kAudioHardwareBadStreamError:
+ errorText = "Audio Hardware: BadStream";
+ result = paBadStreamPtr; break;
+ case kAudioHardwareUnsupportedOperationError:
+ errorText = "Audio Hardware: Unsupported Operation";
+ result = paInternalError; break;
+ case kAudioDeviceUnsupportedFormatError:
+ errorText = "Audio Device: Unsupported Format";
+ result = paSampleFormatNotSupported; break;
+ case kAudioDevicePermissionsError:
+ errorText = "Audio Device: Permissions Error";
+ result = paDeviceUnavailable; break;
+ /* Audio Unit Errors: http://developer.apple.com/documentation/MusicAudio/Reference/CoreAudio/audio_units/chapter_5_section_3.html */
+ case kAudioUnitErr_InvalidProperty:
+ errorText = "Audio Unit: Invalid Property";
+ result = paInternalError; break;
+ case kAudioUnitErr_InvalidParameter:
+ errorText = "Audio Unit: Invalid Parameter";
+ result = paInternalError; break;
+ case kAudioUnitErr_NoConnection:
+ errorText = "Audio Unit: No Connection";
+ result = paInternalError; break;
+ case kAudioUnitErr_FailedInitialization:
+ errorText = "Audio Unit: Initialization Failed";
+ result = paInternalError; break;
+ case kAudioUnitErr_TooManyFramesToProcess:
+ errorText = "Audio Unit: Too Many Frames";
+ result = paInternalError; break;
+ case kAudioUnitErr_IllegalInstrument:
+ errorText = "Audio Unit: Illegal Instrument";
+ result = paInternalError; break;
+ case kAudioUnitErr_InstrumentTypeNotFound:
+ errorText = "Audio Unit: Instrument Type Not Found";
+ result = paInternalError; break;
+ case kAudioUnitErr_InvalidFile:
+ errorText = "Audio Unit: Invalid File";
+ result = paInternalError; break;
+ case kAudioUnitErr_UnknownFileType:
+ errorText = "Audio Unit: Unknown File Type";
+ result = paInternalError; break;
+ case kAudioUnitErr_FileNotSpecified:
+ errorText = "Audio Unit: File Not Specified";
+ result = paInternalError; break;
+ case kAudioUnitErr_FormatNotSupported:
+ errorText = "Audio Unit: Format Not Supported";
+ result = paInternalError; break;
+ case kAudioUnitErr_Uninitialized:
+ errorText = "Audio Unit: Unitialized";
+ result = paInternalError; break;
+ case kAudioUnitErr_InvalidScope:
+ errorText = "Audio Unit: Invalid Scope";
+ result = paInternalError; break;
+ case kAudioUnitErr_PropertyNotWritable:
+ errorText = "Audio Unit: PropertyNotWritable";
+ result = paInternalError; break;
+ case kAudioUnitErr_InvalidPropertyValue:
+ errorText = "Audio Unit: Invalid Property Value";
+ result = paInternalError; break;
+ case kAudioUnitErr_PropertyNotInUse:
+ errorText = "Audio Unit: Property Not In Use";
+ result = paInternalError; break;
+ case kAudioUnitErr_Initialized:
+ errorText = "Audio Unit: Initialized";
+ result = paInternalError; break;
+ case kAudioUnitErr_InvalidOfflineRender:
+ errorText = "Audio Unit: Invalid Offline Render";
+ result = paInternalError; break;
+ case kAudioUnitErr_Unauthorized:
+ errorText = "Audio Unit: Unauthorized";
+ result = paInternalError; break;
+ case kAudioUnitErr_CannotDoInCurrentContext:
+ errorText = "Audio Unit: cannot do in current context";
+ result = paInternalError; break;
+ default:
+ errorText = "Unknown Error";
+ result = paInternalError;
+ }
+
+ if (isError)
+ errorType = "Error";
+ else
+ errorType = "Warning";
+
+ if ((int)error < -99999 || (int)error > 99999)
+ DBUG(("%s on line %d: err='%4s', msg='%s'\n", errorType, line, (const char *)&error, errorText));
+ else
+ DBUG(("%s on line %d: err=%d, 0x%x, msg='%s'\n", errorType, line, (int)error, (unsigned)error, errorText));
+
+ PaUtil_SetLastHostErrorInfo( paCoreAudio, error, errorText );
+
+ return result;
+}
+
+/*
+ * This function computes an appropriate ring buffer size given
+ * a requested latency (in seconds), sample rate and framesPerBuffer.
+ *
+ * The returned ringBufferSize is computed using the following
+ * constraints:
+ * - it must be at least 4.
+ * - it must be at least 3x framesPerBuffer.
+ * - it must be at least 2x the suggestedLatency.
+ * - it must be a power of 2.
+ * This function attempts to compute the minimum such size.
+ *
+ * FEEDBACK: too liberal/conservative/another way?
+ */
+long computeRingBufferSize( const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ long inputFramesPerBuffer,
+ long outputFramesPerBuffer,
+ double sampleRate )
+{
+ long ringSize;
+ int index;
+ int i;
+ double latencyTimesChannelCount ;
+ long framesPerBufferTimesChannelCount ;
+
+ VVDBUG(( "computeRingBufferSize()\n" ));
+
+ assert( inputParameters || outputParameters );
+
+ if( outputParameters && inputParameters )
+ {
+ latencyTimesChannelCount = MAX(
+ inputParameters->suggestedLatency * inputParameters->channelCount,
+ outputParameters->suggestedLatency * outputParameters->channelCount );
+ framesPerBufferTimesChannelCount = MAX(
+ inputFramesPerBuffer * inputParameters->channelCount,
+ outputFramesPerBuffer * outputParameters->channelCount );
+ }
+ else if( outputParameters )
+ {
+ latencyTimesChannelCount
+ = outputParameters->suggestedLatency * outputParameters->channelCount;
+ framesPerBufferTimesChannelCount
+ = outputFramesPerBuffer * outputParameters->channelCount;
+ }
+ else /* we have inputParameters */
+ {
+ latencyTimesChannelCount
+ = inputParameters->suggestedLatency * inputParameters->channelCount;
+ framesPerBufferTimesChannelCount
+ = inputFramesPerBuffer * inputParameters->channelCount;
+ }
+
+ ringSize = (long) ( latencyTimesChannelCount * sampleRate * 2 + .5);
+ VDBUG( ( "suggested latency * channelCount: %d\n", (int) (latencyTimesChannelCount*sampleRate) ) );
+ if( ringSize < framesPerBufferTimesChannelCount * 3 )
+ ringSize = framesPerBufferTimesChannelCount * 3 ;
+ VDBUG(("framesPerBuffer*channelCount:%d\n",(int)framesPerBufferTimesChannelCount));
+ VDBUG(("Ringbuffer size (1): %d\n", (int)ringSize ));
+
+ /* make sure it's at least 4 */
+ ringSize = MAX( ringSize, 4 );
+
+ /* round up to the next power of 2 */
+ index = -1;
+ for( i=0; i<sizeof(long)*8; ++i )
+ if( ringSize >> i & 0x01 )
+ index = i;
+ assert( index > 0 );
+ if( ringSize <= ( 0x01 << index ) )
+ ringSize = 0x01 << index ;
+ else
+ ringSize = 0x01 << ( index + 1 );
+
+ VDBUG(( "Final Ringbuffer size (2): %d\n", (int)ringSize ));
+ return ringSize;
+}
+
+
+/*
+ * Durring testing of core audio, I found that serious crashes could occur
+ * if properties such as sample rate were changed multiple times in rapid
+ * succession. The function below has some fancy logic to make sure that changes
+ * are acknowledged before another is requested. That seems to help a lot.
+ */
+
+OSStatus propertyProc(
+ AudioDeviceID inDevice,
+ UInt32 inChannel,
+ Boolean isInput,
+ AudioDevicePropertyID inPropertyID,
+ void* inClientData )
+{
+ MutexAndBool *mab = (MutexAndBool *) inClientData;
+ mab->once = TRUE;
+ pthread_mutex_unlock( &(mab->mutex) );
+ return noErr;
+}
+
+/* sets the value of the given property and waits for the change to
+ be acknowledged, and returns the final value, which is not guaranteed
+ by this function to be the same as the desired value. Obviously, this
+ function can only be used for data whose input and output are the
+ same size and format, and their size and format are known in advance.*/
+PaError AudioDeviceSetPropertyNowAndWaitForChange(
+ AudioDeviceID inDevice,
+ UInt32 inChannel,
+ Boolean isInput,
+ AudioDevicePropertyID inPropertyID,
+ UInt32 inPropertyDataSize,
+ const void *inPropertyData,
+ void *outPropertyData )
+{
+ OSStatus macErr;
+ int unixErr;
+ MutexAndBool mab;
+ UInt32 outPropertyDataSize = inPropertyDataSize;
+
+ /* First, see if it already has that value. If so, return. */
+ macErr = AudioDeviceGetProperty( inDevice, inChannel,
+ isInput, inPropertyID,
+ &outPropertyDataSize, outPropertyData );
+ if( macErr )
+ goto failMac2;
+ if( inPropertyDataSize!=outPropertyDataSize )
+ return paInternalError;
+ if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) )
+ return paNoError;
+
+ /* setup and lock mutex */
+ mab.once = FALSE;
+ unixErr = pthread_mutex_init( &mab.mutex, NULL );
+ if( unixErr )
+ goto failUnix2;
+ unixErr = pthread_mutex_lock( &mab.mutex );
+ if( unixErr )
+ goto failUnix;
+
+ /* add property listener */
+ macErr = AudioDeviceAddPropertyListener( inDevice, inChannel, isInput,
+ inPropertyID, propertyProc,
+ &mab );
+ if( macErr )
+ goto failMac;
+ /* set property */
+ macErr = AudioDeviceSetProperty( inDevice, NULL, inChannel,
+ isInput, inPropertyID,
+ inPropertyDataSize, inPropertyData );
+ if( macErr ) {
+ /* we couldn't set the property, so we'll just unlock the mutex
+ and move on. */
+ pthread_mutex_unlock( &mab.mutex );
+ }
+
+ /* wait for property to change */
+ unixErr = pthread_mutex_lock( &mab.mutex );
+ if( unixErr )
+ goto failUnix;
+
+ /* now read the property back out */
+ macErr = AudioDeviceGetProperty( inDevice, inChannel,
+ isInput, inPropertyID,
+ &outPropertyDataSize, outPropertyData );
+ if( macErr )
+ goto failMac;
+ /* cleanup */
+ AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput,
+ inPropertyID, propertyProc );
+ unixErr = pthread_mutex_unlock( &mab.mutex );
+ if( unixErr )
+ goto failUnix2;
+ unixErr = pthread_mutex_destroy( &mab.mutex );
+ if( unixErr )
+ goto failUnix2;
+
+ return paNoError;
+
+ failUnix:
+ pthread_mutex_destroy( &mab.mutex );
+ AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput,
+ inPropertyID, propertyProc );
+
+ failUnix2:
+ DBUG( ("Error #%d while setting a device property: %s\n", unixErr, strerror( unixErr ) ) );
+ return paUnanticipatedHostError;
+
+ failMac:
+ pthread_mutex_destroy( &mab.mutex );
+ AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput,
+ inPropertyID, propertyProc );
+ failMac2:
+ return ERR( macErr );
+}
+
+/*
+ * Sets the sample rate the HAL device.
+ * if requireExact: set the sample rate or fail.
+ *
+ * otherwise : set the exact sample rate.
+ * If that fails, check for available sample rates, and choose one
+ * higher than the requested rate. If there isn't a higher one,
+ * just use the highest available.
+ */
+PaError setBestSampleRateForDevice( const AudioDeviceID device,
+ const bool isOutput,
+ const bool requireExact,
+ const Float64 desiredSrate )
+{
+ /*FIXME: changing the sample rate is disruptive to other programs using the
+ device, so it might be good to offer a custom flag to not change the
+ sample rate and just do conversion. (in my casual tests, there is
+ no disruption unless the sample rate really does need to change) */
+ const bool isInput = isOutput ? 0 : 1;
+ Float64 srate;
+ UInt32 propsize = sizeof( Float64 );
+ OSErr err;
+ AudioValueRange *ranges;
+ int i=0;
+ Float64 max = -1; /*the maximum rate available*/
+ Float64 best = -1; /*the lowest sample rate still greater than desired rate*/
+ VDBUG(("Setting sample rate for device %ld to %g.\n",device,(float)desiredSrate));
+
+ /* -- try setting the sample rate -- */
+ err = AudioDeviceSetPropertyNowAndWaitForChange(
+ device, 0, isInput,
+ kAudioDevicePropertyNominalSampleRate,
+ propsize, &desiredSrate, &srate );
+ if( err )
+ return err;
+
+ /* -- if the rate agrees, and we got no errors, we are done -- */
+ if( !err && srate == desiredSrate )
+ return paNoError;
+ /* -- we've failed if the rates disagree and we are setting input -- */
+ if( requireExact )
+ return paInvalidSampleRate;
+
+ /* -- generate a list of available sample rates -- */
+ err = AudioDeviceGetPropertyInfo( device, 0, isInput,
+ kAudioDevicePropertyAvailableNominalSampleRates,
+ &propsize, NULL );
+ if( err )
+ return ERR( err );
+ ranges = (AudioValueRange *)calloc( 1, propsize );
+ if( !ranges )
+ return paInsufficientMemory;
+ err = AudioDeviceGetProperty( device, 0, isInput,
+ kAudioDevicePropertyAvailableNominalSampleRates,
+ &propsize, ranges );
+ if( err )
+ {
+ free( ranges );
+ return ERR( err );
+ }
+ VDBUG(("Requested sample rate of %g was not available.\n", (float)desiredSrate));
+ VDBUG(("%lu Available Sample Rates are:\n",propsize/sizeof(AudioValueRange)));
+#ifdef MAC_CORE_VERBOSE_DEBUG
+ for( i=0; i<propsize/sizeof(AudioValueRange); ++i )
+ VDBUG( ("\t%g-%g\n",
+ (float) ranges[i].mMinimum,
+ (float) ranges[i].mMaximum ) );
+#endif
+ VDBUG(("-----\n"));
+
+ /* -- now pick the best available sample rate -- */
+ for( i=0; i<propsize/sizeof(AudioValueRange); ++i )
+ {
+ if( ranges[i].mMaximum > max ) max = ranges[i].mMaximum;
+ if( ranges[i].mMinimum > desiredSrate ) {
+ if( best < 0 )
+ best = ranges[i].mMinimum;
+ else if( ranges[i].mMinimum < best )
+ best = ranges[i].mMinimum;
+ }
+ }
+ if( best < 0 )
+ best = max;
+ VDBUG( ("Maximum Rate %g. best is %g.\n", max, best ) );
+ free( ranges );
+
+ /* -- set the sample rate -- */
+ propsize = sizeof( best );
+ err = AudioDeviceSetPropertyNowAndWaitForChange(
+ device, 0, isInput,
+ kAudioDevicePropertyNominalSampleRate,
+ propsize, &best, &srate );
+ if( err )
+ return err;
+
+ if( err )
+ return ERR( err );
+ /* -- if the set rate matches, we are done -- */
+ if( srate == best )
+ return paNoError;
+
+ /* -- otherwise, something wierd happened: we didn't set the rate, and we got no errors. Just bail. */
+ return paInternalError;
+}
+
+
+/*
+ Attempts to set the requestedFramesPerBuffer. If it can't set the exact
+ value, it settles for something smaller if available. If nothing smaller
+ is available, it uses the smallest available size.
+ actualFramesPerBuffer will be set to the actual value on successful return.
+ OK to pass NULL to actualFramesPerBuffer.
+ The logic is very simmilar too setBestSampleRate only failure here is
+ not usually catastrophic.
+*/
+PaError setBestFramesPerBuffer( const AudioDeviceID device,
+ const bool isOutput,
+ unsigned long requestedFramesPerBuffer,
+ unsigned long *actualFramesPerBuffer )
+{
+ UInt32 afpb;
+ const bool isInput = !isOutput;
+ UInt32 propsize = sizeof(UInt32);
+ OSErr err;
+ Float64 min = -1; /*the min blocksize*/
+ Float64 best = -1; /*the best blocksize*/
+ int i=0;
+ AudioValueRange *ranges;
+
+ if( actualFramesPerBuffer == NULL )
+ actualFramesPerBuffer = &afpb;
+
+
+ /* -- try and set exact FPB -- */
+ err = AudioDeviceSetProperty( device, NULL, 0, isInput,
+ kAudioDevicePropertyBufferFrameSize,
+ propsize, &requestedFramesPerBuffer);
+ err = AudioDeviceGetProperty( device, 0, isInput,
+ kAudioDevicePropertyBufferFrameSize,
+ &propsize, actualFramesPerBuffer);
+ if( err )
+ return ERR( err );
+ if( *actualFramesPerBuffer == requestedFramesPerBuffer )
+ return paNoError; /* we are done */
+
+ /* -- fetch available block sizes -- */
+ err = AudioDeviceGetPropertyInfo( device, 0, isInput,
+ kAudioDevicePropertyBufferSizeRange,
+ &propsize, NULL );
+ if( err )
+ return ERR( err );
+ ranges = (AudioValueRange *)calloc( 1, propsize );
+ if( !ranges )
+ return paInsufficientMemory;
+ err = AudioDeviceGetProperty( device, 0, isInput,
+ kAudioDevicePropertyBufferSizeRange,
+ &propsize, ranges );
+ if( err )
+ {
+ free( ranges );
+ return ERR( err );
+ }
+ VDBUG(("Requested block size of %lu was not available.\n",
+ requestedFramesPerBuffer ));
+ VDBUG(("%lu Available block sizes are:\n",propsize/sizeof(AudioValueRange)));
+#ifdef MAC_CORE_VERBOSE_DEBUG
+ for( i=0; i<propsize/sizeof(AudioValueRange); ++i )
+ VDBUG( ("\t%g-%g\n",
+ (float) ranges[i].mMinimum,
+ (float) ranges[i].mMaximum ) );
+#endif
+ VDBUG(("-----\n"));
+
+ /* --- now pick the best available framesPerBuffer -- */
+ for( i=0; i<propsize/sizeof(AudioValueRange); ++i )
+ {
+ if( min == -1 || ranges[i].mMinimum < min ) min = ranges[i].mMinimum;
+ if( ranges[i].mMaximum < requestedFramesPerBuffer ) {
+ if( best < 0 )
+ best = ranges[i].mMaximum;
+ else if( ranges[i].mMaximum > best )
+ best = ranges[i].mMaximum;
+ }
+ }
+ if( best == -1 )
+ best = min;
+ VDBUG( ("Minimum FPB %g. best is %g.\n", min, best ) );
+ free( ranges );
+
+ /* --- set the buffer size (ignore errors) -- */
+ requestedFramesPerBuffer = (UInt32) best ;
+ propsize = sizeof( UInt32 );
+ err = AudioDeviceSetProperty( device, NULL, 0, isInput,
+ kAudioDevicePropertyBufferSize,
+ propsize, &requestedFramesPerBuffer );
+ /* --- read the property to check that it was set -- */
+ err = AudioDeviceGetProperty( device, 0, isInput,
+ kAudioDevicePropertyBufferSize,
+ &propsize, actualFramesPerBuffer );
+
+ if( err )
+ return ERR( err );
+
+ return paNoError;
+}
diff --git a/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h
new file mode 100644
index 00000000..8a69c25a
--- /dev/null
+++ b/pd/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h
@@ -0,0 +1,205 @@
+/*
+ * Helper and utility functions for pa_mac_core.c (Apple AUHAL implementation)
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
+ * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
+ *
+ * Dominic's code was based on code by Phil Burk, Darren Gibbs,
+ * Gord Peters, Stephane Letz, and Greg Pfiel.
+ *
+ * The following people also deserve acknowledgements:
+ *
+ * Olivier Tristan for feedback and testing
+ * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
+ * interface.
+ *
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#ifndef PA_MAC_CORE_UTILITIES_H__
+#define PA_MAC_CORE_UTILITIES_H__
+
+#include <pthread.h>
+#include "portaudio.h"
+#include "pa_util.h"
+#include <AudioUnit/AudioUnit.h>
+#include <AudioToolbox/AudioToolbox.h>
+
+#ifndef MIN
+#define MIN(a, b) (((a)<(b))?(a):(b))
+#endif
+
+#ifndef MAX
+#define MAX(a, b) (((a)<(b))?(b):(a))
+#endif
+
+#define ERR(mac_error) PaMacCore_SetError(mac_error, __LINE__, 1 )
+#define WARNING(mac_error) PaMacCore_SetError(mac_error, __LINE__, 0 )
+
+
+/* Help keep track of AUHAL element numbers */
+#define INPUT_ELEMENT (1)
+#define OUTPUT_ELEMENT (0)
+
+/* Normal level of debugging: fine for most apps that don't mind the occational warning being printf'ed */
+/*
+ */
+#define MAC_CORE_DEBUG
+#ifdef MAC_CORE_DEBUG
+# define DBUG(MSG) do { printf("||PaMacCore (AUHAL)|| "); printf MSG ; fflush(stdout); } while(0)
+#else
+# define DBUG(MSG)
+#endif
+
+/* Verbose Debugging: useful for developement */
+/*
+#define MAC_CORE_VERBOSE_DEBUG
+*/
+#ifdef MAC_CORE_VERBOSE_DEBUG
+# define VDBUG(MSG) do { printf("||PaMacCore (v )|| "); printf MSG ; fflush(stdout); } while(0)
+#else
+# define VDBUG(MSG)
+#endif
+
+/* Very Verbose Debugging: Traces every call. */
+/*
+#define MAC_CORE_VERY_VERBOSE_DEBUG
+ */
+#ifdef MAC_CORE_VERY_VERBOSE_DEBUG
+# define VVDBUG(MSG) do { printf("||PaMacCore (vv)|| "); printf MSG ; fflush(stdout); } while(0)
+#else
+# define VVDBUG(MSG)
+#endif
+
+
+
+
+
+#define UNIX_ERR(err) PaMacCore_SetUnixError( err, __LINE__ )
+
+PaError PaMacCore_SetUnixError( int err, int line );
+
+/*
+ * Translates MacOS generated errors into PaErrors
+ */
+PaError PaMacCore_SetError(OSStatus error, int line, int isError);
+
+/*
+ * This function computes an appropriate ring buffer size given
+ * a requested latency (in seconds), sample rate and framesPerBuffer.
+ *
+ * The returned ringBufferSize is computed using the following
+ * constraints:
+ * - it must be at least 4.
+ * - it must be at least 3x framesPerBuffer.
+ * - it must be at least 2x the suggestedLatency.
+ * - it must be a power of 2.
+ * This function attempts to compute the minimum such size.
+ *
+ */
+long computeRingBufferSize( const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ long inputFramesPerBuffer,
+ long outputFramesPerBuffer,
+ double sampleRate );
+
+/*
+ * Durring testing of core audio, I found that serious crashes could occur
+ * if properties such as sample rate were changed multiple times in rapid
+ * succession. The function below has some fancy logic to make sure that changes
+ * are acknowledged before another is requested. That seems to help a lot.
+ */
+
+typedef struct {
+ bool once; /* I didn't end up using this. bdr */
+ pthread_mutex_t mutex;
+} MutexAndBool ;
+
+OSStatus propertyProc(
+ AudioDeviceID inDevice,
+ UInt32 inChannel,
+ Boolean isInput,
+ AudioDevicePropertyID inPropertyID,
+ void* inClientData );
+
+/* sets the value of the given property and waits for the change to
+ be acknowledged, and returns the final value, which is not guaranteed
+ by this function to be the same as the desired value. Obviously, this
+ function can only be used for data whose input and output are the
+ same size and format, and their size and format are known in advance.*/
+PaError AudioDeviceSetPropertyNowAndWaitForChange(
+ AudioDeviceID inDevice,
+ UInt32 inChannel,
+ Boolean isInput,
+ AudioDevicePropertyID inPropertyID,
+ UInt32 inPropertyDataSize,
+ const void *inPropertyData,
+ void *outPropertyData );
+
+/*
+ * Sets the sample rate the HAL device.
+ * if requireExact: set the sample rate or fail.
+ *
+ * otherwise : set the exact sample rate.
+ * If that fails, check for available sample rates, and choose one
+ * higher than the requested rate. If there isn't a higher one,
+ * just use the highest available.
+ */
+PaError setBestSampleRateForDevice( const AudioDeviceID device,
+ const bool isOutput,
+ const bool requireExact,
+ const Float64 desiredSrate );
+/*
+ Attempts to set the requestedFramesPerBuffer. If it can't set the exact
+ value, it settles for something smaller if available. If nothing smaller
+ is available, it uses the smallest available size.
+ actualFramesPerBuffer will be set to the actual value on successful return.
+ OK to pass NULL to actualFramesPerBuffer.
+ The logic is very simmilar too setBestSampleRate only failure here is
+ not usually catastrophic.
+*/
+PaError setBestFramesPerBuffer( const AudioDeviceID device,
+ const bool isOutput,
+ unsigned long requestedFramesPerBuffer,
+ unsigned long *actualFramesPerBuffer );
+#endif /* PA_MAC_CORE_UTILITIES_H__*/
diff --git a/pd/portaudio/src/hostapi/jack/pa_jack.c b/pd/portaudio/src/hostapi/jack/pa_jack.c
new file mode 100644
index 00000000..64eae29e
--- /dev/null
+++ b/pd/portaudio/src/hostapi/jack/pa_jack.c
@@ -0,0 +1,1756 @@
+/*
+ * $Id: pa_jack.c,v 1.1 2007-08-18 23:49:33 millerpuckette Exp $
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ * JACK Implementation by Joshua Haberman
+ *
+ * Copyright (c) 2004 Stefan Westerfeld <stefan@space.twc.de>
+ * Copyright (c) 2004 Arve Knudsen <aknuds-1@broadpark.no>
+ * Copyright (c) 2002 Joshua Haberman <joshua@haberman.com>
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#include <string.h>
+#include <regex.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <assert.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <errno.h> /* EBUSY */
+#include <signal.h> /* sig_atomic_t */
+#include <math.h>
+#include <semaphore.h>
+
+#include <jack/types.h>
+#include <jack/jack.h>
+
+#include "pa_util.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_process.h"
+#include "pa_allocation.h"
+#include "pa_cpuload.h"
+#include "pa_ringbuffer.h"
+#include "pa_debugprint.h"
+
+static int aErr_;
+static PaError paErr_; /* For use with ENSURE_PA */
+static pthread_t mainThread_;
+static char *jackErr_ = NULL;
+static const char* clientName_ = "PortAudio";
+
+#define STRINGIZE_HELPER(expr) #expr
+#define STRINGIZE(expr) STRINGIZE_HELPER(expr)
+
+/* Check PaError */
+#define ENSURE_PA(expr) \
+ do { \
+ if( (paErr_ = (expr)) < paNoError ) \
+ { \
+ if( (paErr_) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \
+ { \
+ if (! jackErr_ ) jackErr_ = "unknown error";\
+ PaUtil_SetLastHostErrorInfo( paJACK, -1, jackErr_ ); \
+ } \
+ PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
+ result = paErr_; \
+ goto error; \
+ } \
+ } while( 0 )
+
+#define UNLESS(expr, code) \
+ do { \
+ if( (expr) == 0 ) \
+ { \
+ if( (code) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \
+ { \
+ if (!jackErr_) jackErr_ = "unknown error";\
+ PaUtil_SetLastHostErrorInfo( paJACK, -1, jackErr_ ); \
+ } \
+ PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
+ result = (code); \
+ goto error; \
+ } \
+ } while( 0 )
+
+#define ASSERT_CALL(expr, success) \
+ aErr_ = (expr); \
+ assert( aErr_ == success );
+
+/*
+ * Functions that directly map to the PortAudio stream interface
+ */
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+ PaStream** s,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate,
+ unsigned long framesPerBuffer,
+ PaStreamFlags streamFlags,
+ PaStreamCallback *streamCallback,
+ void *userData );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+/*static PaTime GetStreamInputLatency( PaStream *stream );*/
+/*static PaTime GetStreamOutputLatency( PaStream *stream );*/
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+
+
+/*
+ * Data specific to this API
+ */
+
+struct PaJackStream;
+
+typedef struct
+{
+ PaUtilHostApiRepresentation commonHostApiRep;
+ PaUtilStreamInterface callbackStreamInterface;
+ PaUtilStreamInterface blockingStreamInterface;
+
+ PaUtilAllocationGroup *deviceInfoMemory;
+
+ jack_client_t *jack_client;
+ int jack_buffer_size;
+ PaHostApiIndex hostApiIndex;
+
+ pthread_mutex_t mtx;
+ pthread_cond_t cond;
+ unsigned long inputBase, outputBase;
+
+ /* For dealing with the process thread */
+ volatile int xrun; /* Received xrun notification from JACK? */
+ struct PaJackStream * volatile toAdd, * volatile toRemove;
+ struct PaJackStream *processQueue;
+ volatile sig_atomic_t jackIsDown;
+}
+PaJackHostApiRepresentation;
+
+/* PaJackStream - a stream data structure specifically for this implementation */
+
+typedef struct PaJackStream
+{
+ PaUtilStreamRepresentation streamRepresentation;
+ PaUtilBufferProcessor bufferProcessor;
+ PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+ PaJackHostApiRepresentation *hostApi;
+
+ /* our input and output ports */
+ jack_port_t **local_input_ports;
+ jack_port_t **local_output_ports;
+
+ /* the input and output ports of the client we are connecting to */
+ jack_port_t **remote_input_ports;
+ jack_port_t **remote_output_ports;
+
+ int num_incoming_connections;
+ int num_outgoing_connections;
+
+ jack_client_t *jack_client;
+
+ /* The stream is running if it's still producing samples.
+ * The stream is active if samples it produced are still being heard.
+ */
+ volatile sig_atomic_t is_running;
+ volatile sig_atomic_t is_active;
+ /* Used to signal processing thread that stream should start or stop, respectively */
+ volatile sig_atomic_t doStart, doStop, doAbort;
+
+ jack_nframes_t t0;
+
+ PaUtilAllocationGroup *stream_memory;
+
+ /* These are useful in the process callback */
+
+ int callbackResult;
+ int isSilenced;
+ int xrun;
+
+ /* These are useful for the blocking API */
+
+ int isBlockingStream;
+ PaUtilRingBuffer inFIFO;
+ PaUtilRingBuffer outFIFO;
+ volatile sig_atomic_t data_available;
+ sem_t data_semaphore;
+ int bytesPerFrame;
+ int samplesPerFrame;
+
+ struct PaJackStream *next;
+}
+PaJackStream;
+
+#define TRUE 1
+#define FALSE 0
+
+/*
+ * Functions specific to this API
+ */
+
+static int JackCallback( jack_nframes_t frames, void *userData );
+
+
+/*
+ *
+ * Implementation
+ *
+ */
+
+/* ---- blocking emulation layer ---- */
+
+/* Allocate buffer. */
+static PaError BlockingInitFIFO( PaUtilRingBuffer *rbuf, long numFrames, long bytesPerFrame )
+{
+ long numBytes = numFrames * bytesPerFrame;
+ char *buffer = (char *) malloc( numBytes );
+ if( buffer == NULL ) return paInsufficientMemory;
+ memset( buffer, 0, numBytes );
+ return (PaError) PaUtil_InitializeRingBuffer( rbuf, numBytes, buffer );
+}
+
+/* Free buffer. */
+static PaError BlockingTermFIFO( PaUtilRingBuffer *rbuf )
+{
+ if( rbuf->buffer ) free( rbuf->buffer );
+ rbuf->buffer = NULL;
+ return paNoError;
+}
+
+static int
+BlockingCallback( const void *inputBuffer,
+ void *outputBuffer,
+ unsigned long framesPerBuffer,
+ const PaStreamCallbackTimeInfo* timeInfo,
+ PaStreamCallbackFlags statusFlags,
+ void *userData )
+{
+ struct PaJackStream *stream = (PaJackStream *)userData;
+ long numBytes = stream->bytesPerFrame * framesPerBuffer;
+
+ /* This may get called with NULL inputBuffer during initial setup. */
+ if( inputBuffer != NULL )
+ {
+ PaUtil_WriteRingBuffer( &stream->inFIFO, inputBuffer, numBytes );
+ }
+ if( outputBuffer != NULL )
+ {
+ int numRead = PaUtil_ReadRingBuffer( &stream->outFIFO, outputBuffer, numBytes );
+ /* Zero out remainder of buffer if we run out of data. */
+ memset( (char *)outputBuffer + numRead, 0, numBytes - numRead );
+ }
+
+ if( !stream->data_available )
+ {
+ stream->data_available = 1;
+ sem_post( &stream->data_semaphore );
+ }
+ return paContinue;
+}
+
+static PaError
+BlockingBegin( PaJackStream *stream, int minimum_buffer_size )
+{
+ long doRead = 0;
+ long doWrite = 0;
+ PaError result = paNoError;
+ long numFrames;
+
+ doRead = stream->local_input_ports != NULL;
+ doWrite = stream->local_output_ports != NULL;
+ /* <FIXME> */
+ stream->samplesPerFrame = 2;
+ stream->bytesPerFrame = sizeof(float) * stream->samplesPerFrame;
+ /* </FIXME> */
+ numFrames = 32;
+ while (numFrames < minimum_buffer_size)
+ numFrames *= 2;
+
+ if( doRead )
+ {
+ ENSURE_PA( BlockingInitFIFO( &stream->inFIFO, numFrames, stream->bytesPerFrame ) );
+ }
+ if( doWrite )
+ {
+ long numBytes;
+
+ ENSURE_PA( BlockingInitFIFO( &stream->outFIFO, numFrames, stream->bytesPerFrame ) );
+
+ /* Make Write FIFO appear full initially. */
+ numBytes = PaUtil_GetRingBufferWriteAvailable( &stream->outFIFO );
+ PaUtil_AdvanceRingBufferWriteIndex( &stream->outFIFO, numBytes );
+ }
+
+ stream->data_available = 0;
+ sem_init( &stream->data_semaphore, 0, 0 );
+
+error:
+ return result;
+}
+
+static void
+BlockingEnd( PaJackStream *stream )
+{
+ BlockingTermFIFO( &stream->inFIFO );
+ BlockingTermFIFO( &stream->outFIFO );
+
+ sem_destroy( &stream->data_semaphore );
+}
+
+static PaError BlockingReadStream( PaStream* s, void *data, unsigned long numFrames )
+{
+ PaError result = paNoError;
+ PaJackStream *stream = (PaJackStream *)s;
+
+ long bytesRead;
+ char *p = (char *) data;
+ long numBytes = stream->bytesPerFrame * numFrames;
+ while( numBytes > 0 )
+ {
+ bytesRead = PaUtil_ReadRingBuffer( &stream->inFIFO, p, numBytes );
+ numBytes -= bytesRead;
+ p += bytesRead;
+ if( numBytes > 0 )
+ {
+ /* see write for an explanation */
+ if( stream->data_available )
+ stream->data_available = 0;
+ else
+ sem_wait( &stream->data_semaphore );
+ }
+ }
+
+ return result;
+}
+
+static PaError BlockingWriteStream( PaStream* s, const void *data, unsigned long numFrames )
+{
+ PaError result = paNoError;
+ PaJackStream *stream = (PaJackStream *)s;
+ long bytesWritten;
+ char *p = (char *) data;
+ long numBytes = stream->bytesPerFrame * numFrames;
+ while( numBytes > 0 )
+ {
+ bytesWritten = PaUtil_WriteRingBuffer( &stream->outFIFO, p, numBytes );
+ numBytes -= bytesWritten;
+ p += bytesWritten;
+ if( numBytes > 0 )
+ {
+ /* we use the following algorithm:
+ * (1) write data
+ * (2) if some data didn't fit into the ringbuffer, set data_available to 0
+ * to indicate to the audio that if space becomes available, we want to know
+ * (3) retry to write data (because it might be that between (1) and (2)
+ * new space in the buffer became available)
+ * (4) if this failed, we are sure that the buffer is really empty and
+ * we will definitely receive a notification when it becomes available
+ * thus we can safely sleep
+ *
+ * if the algorithm bailed out in step (3) before, it leaks a count of 1
+ * on the semaphore; however, it doesn't matter, because if we block in (4),
+ * we also do it in a loop
+ */
+ if( stream->data_available )
+ stream->data_available = 0;
+ else
+ sem_wait( &stream->data_semaphore );
+ }
+ }
+
+ return result;
+}
+
+static signed long
+BlockingGetStreamReadAvailable( PaStream* s )
+{
+ PaJackStream *stream = (PaJackStream *)s;
+
+ int bytesFull = PaUtil_GetRingBufferReadAvailable( &stream->inFIFO );
+ return bytesFull / stream->bytesPerFrame;
+}
+
+static signed long
+BlockingGetStreamWriteAvailable( PaStream* s )
+{
+ PaJackStream *stream = (PaJackStream *)s;
+
+ int bytesEmpty = PaUtil_GetRingBufferWriteAvailable( &stream->outFIFO );
+ return bytesEmpty / stream->bytesPerFrame;
+}
+
+static PaError
+BlockingWaitEmpty( PaStream *s )
+{
+ PaJackStream *stream = (PaJackStream *)s;
+
+ while( PaUtil_GetRingBufferReadAvailable( &stream->outFIFO ) > 0 )
+ {
+ stream->data_available = 0;
+ sem_wait( &stream->data_semaphore );
+ }
+ return 0;
+}
+
+/* ---- jack driver ---- */
+
+/* BuildDeviceList():
+ *
+ * The process of determining a list of PortAudio "devices" from
+ * JACK's client/port system is fairly involved, so it is separated
+ * into its own routine.
+ */
+
+static PaError BuildDeviceList( PaJackHostApiRepresentation *jackApi )
+{
+ /* Utility macros for the repetitive process of allocating memory */
+
+ /* JACK has no concept of a device. To JACK, there are clients
+ * which have an arbitrary number of ports. To make this
+ * intelligible to PortAudio clients, we will group each JACK client
+ * into a device, and make each port of that client a channel */
+
+ PaError result = paNoError;
+ PaUtilHostApiRepresentation *commonApi = &jackApi->commonHostApiRep;
+
+ const char **jack_ports = NULL;
+ char **client_names = NULL;
+ char *regex_pattern = NULL;
+ int port_index, client_index, i;
+ double globalSampleRate;
+ regex_t port_regex;
+ unsigned long numClients = 0, numPorts = 0;
+ char *tmp_client_name = NULL;
+
+ commonApi->info.defaultInputDevice = paNoDevice;
+ commonApi->info.defaultOutputDevice = paNoDevice;
+ commonApi->info.deviceCount = 0;
+
+ /* Parse the list of ports, using a regex to grab the client names */
+ ASSERT_CALL( regcomp( &port_regex, "^[^:]*", REG_EXTENDED ), 0 );
+
+ /* since we are rebuilding the list of devices, free all memory
+ * associated with the previous list */
+ PaUtil_FreeAllAllocations( jackApi->deviceInfoMemory );
+
+ regex_pattern = PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, jack_client_name_size() + 3 );
+ tmp_client_name = PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, jack_client_name_size() );
+
+ /* We can only retrieve the list of clients indirectly, by first
+ * asking for a list of all ports, then parsing the port names
+ * according to the client_name:port_name convention (which is
+ * enforced by jackd)
+ * A: If jack_get_ports returns NULL, there's nothing for us to do */
+ UNLESS( (jack_ports = jack_get_ports( jackApi->jack_client, "", "", 0 )) && jack_ports[0], paNoError );
+ /* Find number of ports */
+ while( jack_ports[numPorts] )
+ ++numPorts;
+ /* At least there will be one port per client :) */
+ UNLESS( client_names = PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory, numPorts *
+ sizeof (char *) ), paInsufficientMemory );
+
+ /* Build a list of clients from the list of ports */
+ for( numClients = 0, port_index = 0; jack_ports[port_index] != NULL; port_index++ )
+ {
+ int client_seen = FALSE;
+ regmatch_t match_info;
+ const char *port = jack_ports[port_index];
+
+ /* extract the client name from the port name, using a regex
+ * that parses the clientname:portname syntax */
+ UNLESS( !regexec( &port_regex, port, 1, &match_info, 0 ), paInternalError );
+ assert(match_info.rm_eo - match_info.rm_so < jack_client_name_size());
+ memcpy( tmp_client_name, port + match_info.rm_so,
+ match_info.rm_eo - match_info.rm_so );
+ tmp_client_name[match_info.rm_eo - match_info.rm_so] = '\0';
+
+ /* do we know about this port's client yet? */
+ for( i = 0; i < numClients; i++ )
+ {
+ if( strcmp( tmp_client_name, client_names[i] ) == 0 )
+ client_seen = TRUE;
+ }
+
+ if (client_seen)
+ continue; /* A: Nothing to see here, move along */
+
+ UNLESS( client_names[numClients] = (char*)PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory,
+ strlen(tmp_client_name) + 1), paInsufficientMemory );
+
+ /* The alsa_pcm client should go in spot 0. If this
+ * is the alsa_pcm client AND we are NOT about to put
+ * it in spot 0 put it in spot 0 and move whatever
+ * was already in spot 0 to the end. */
+ if( strcmp( "alsa_pcm", tmp_client_name ) == 0 && numClients > 0 )
+ {
+ /* alsa_pcm goes in spot 0 */
+ strcpy( client_names[ numClients ], client_names[0] );
+ strcpy( client_names[0], tmp_client_name );
+ }
+ else
+ {
+ /* put the new client at the end of the client list */
+ strcpy( client_names[ numClients ], tmp_client_name );
+ }
+ ++numClients;
+ }
+
+ /* Now we have a list of clients, which will become the list of
+ * PortAudio devices. */
+
+ /* there is one global sample rate all clients must conform to */
+
+ globalSampleRate = jack_get_sample_rate( jackApi->jack_client );
+ UNLESS( commonApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory,
+ sizeof(PaDeviceInfo*) * numClients ), paInsufficientMemory );
+
+ assert( commonApi->info.deviceCount == 0 );
+
+ /* Create a PaDeviceInfo structure for every client */
+ for( client_index = 0; client_index < numClients; client_index++ )
+ {
+ PaDeviceInfo *curDevInfo;
+ const char **clientPorts = NULL;
+
+ UNLESS( curDevInfo = (PaDeviceInfo*)PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory,
+ sizeof(PaDeviceInfo) ), paInsufficientMemory );
+ UNLESS( curDevInfo->name = (char*)PaUtil_GroupAllocateMemory( jackApi->deviceInfoMemory,
+ strlen(client_names[client_index]) + 1 ), paInsufficientMemory );
+ strcpy( (char *)curDevInfo->name, client_names[client_index] );
+
+ curDevInfo->structVersion = 2;
+ curDevInfo->hostApi = jackApi->hostApiIndex;
+
+ /* JACK is very inflexible: there is one sample rate the whole
+ * system must run at, and all clients must speak IEEE float. */
+ curDevInfo->defaultSampleRate = globalSampleRate;
+
+ /* To determine how many input and output channels are available,
+ * we re-query jackd with more specific parameters. */
+
+ sprintf( regex_pattern, "%s:.*", client_names[client_index] );
+
+ /* ... what are your output ports (that we could input from)? */
+ clientPorts = jack_get_ports( jackApi->jack_client, regex_pattern,
+ NULL, JackPortIsOutput);
+ curDevInfo->maxInputChannels = 0;
+ curDevInfo->defaultLowInputLatency = 0.;
+ curDevInfo->defaultHighInputLatency = 0.;
+ if( clientPorts )
+ {
+ jack_port_t *p = jack_port_by_name( jackApi->jack_client, clientPorts[0] );
+ curDevInfo->defaultLowInputLatency = curDevInfo->defaultHighInputLatency =
+ jack_port_get_latency( p ) / globalSampleRate;
+
+ for( i = 0; clientPorts[i] != NULL; i++)
+ {
+ /* The number of ports returned is the number of output channels.
+ * We don't care what they are, we just care how many */
+ curDevInfo->maxInputChannels++;
+ }
+ free(clientPorts);
+ }
+
+ /* ... what are your input ports (that we could output to)? */
+ clientPorts = jack_get_ports( jackApi->jack_client, regex_pattern,
+ NULL, JackPortIsInput);
+ curDevInfo->maxOutputChannels = 0;
+ curDevInfo->defaultLowOutputLatency = 0.;
+ curDevInfo->defaultHighOutputLatency = 0.;
+ if( clientPorts )
+ {
+ jack_port_t *p = jack_port_by_name( jackApi->jack_client, clientPorts[0] );
+ curDevInfo->defaultLowOutputLatency = curDevInfo->defaultHighOutputLatency =
+ jack_port_get_latency( p ) / globalSampleRate;
+
+ for( i = 0; clientPorts[i] != NULL; i++)
+ {
+ /* The number of ports returned is the number of input channels.
+ * We don't care what they are, we just care how many */
+ curDevInfo->maxOutputChannels++;
+ }
+ free(clientPorts);
+ }
+
+ /* Add this client to the list of devices */
+ commonApi->deviceInfos[client_index] = curDevInfo;
+ ++commonApi->info.deviceCount;
+ if( commonApi->info.defaultInputDevice == paNoDevice && curDevInfo->maxInputChannels > 0 )
+ commonApi->info.defaultInputDevice = client_index;
+ if( commonApi->info.defaultOutputDevice == paNoDevice && curDevInfo->maxOutputChannels > 0 )
+ commonApi->info.defaultOutputDevice = client_index;
+ }
+
+error:
+ regfree( &port_regex );
+ free( jack_ports );
+ return result;
+}
+
+static void UpdateSampleRate( PaJackStream *stream, double sampleRate )
+{
+ /* XXX: Maybe not the cleanest way of going about this? */
+ stream->cpuLoadMeasurer.samplingPeriod = stream->bufferProcessor.samplePeriod = 1. / sampleRate;
+ stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+}
+
+static void JackErrorCallback( const char *msg )
+{
+ if( pthread_self() == mainThread_ )
+ {
+ assert( msg );
+ jackErr_ = realloc( jackErr_, strlen( msg ) + 1 );
+ strcpy( jackErr_, msg );
+ }
+}
+
+static void JackOnShutdown( void *arg )
+{
+ PaJackHostApiRepresentation *jackApi = (PaJackHostApiRepresentation *)arg;
+ PaJackStream *stream = jackApi->processQueue;
+
+ PA_DEBUG(( "%s: JACK server is shutting down\n", __FUNCTION__ ));
+ for( ; stream; stream = stream->next )
+ {
+ stream->is_active = 0;
+ }
+
+ /* Make sure that the main thread doesn't get stuck waiting on the condition */
+ ASSERT_CALL( pthread_mutex_lock( &jackApi->mtx ), 0 );
+ jackApi->jackIsDown = 1;
+ ASSERT_CALL( pthread_cond_signal( &jackApi->cond ), 0 );
+ ASSERT_CALL( pthread_mutex_unlock( &jackApi->mtx ), 0 );
+
+}
+
+static int JackSrCb( jack_nframes_t nframes, void *arg )
+{
+ PaJackHostApiRepresentation *jackApi = (PaJackHostApiRepresentation *)arg;
+ double sampleRate = (double)nframes;
+ PaJackStream *stream = jackApi->processQueue;
+
+ /* Update all streams in process queue */
+ PA_DEBUG(( "%s: Acting on change in JACK samplerate: %f\n", __FUNCTION__, sampleRate ));
+ for( ; stream; stream = stream->next )
+ {
+ if( stream->streamRepresentation.streamInfo.sampleRate != sampleRate )
+ {
+ PA_DEBUG(( "%s: Updating samplerate\n", __FUNCTION__ ));
+ UpdateSampleRate( stream, sampleRate );
+ }
+ }
+
+ return 0;
+}
+
+static int JackXRunCb(void *arg) {
+ PaJackHostApiRepresentation *hostApi = (PaJackHostApiRepresentation *)arg;
+ assert( hostApi );
+ hostApi->xrun = TRUE;
+ PA_DEBUG(( "%s: JACK signalled xrun\n", __FUNCTION__ ));
+ return 0;
+}
+
+PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi,
+ PaHostApiIndex hostApiIndex )
+{
+ PaError result = paNoError;
+ PaJackHostApiRepresentation *jackHostApi;
+ int activated = 0;
+ jack_status_t jackStatus = 0;
+ *hostApi = NULL; /* Initialize to NULL */
+
+ UNLESS( jackHostApi = (PaJackHostApiRepresentation*)
+ PaUtil_AllocateMemory( sizeof(PaJackHostApiRepresentation) ), paInsufficientMemory );
+ UNLESS( jackHostApi->deviceInfoMemory = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
+
+ mainThread_ = pthread_self();
+ ASSERT_CALL( pthread_mutex_init( &jackHostApi->mtx, NULL ), 0 );
+ ASSERT_CALL( pthread_cond_init( &jackHostApi->cond, NULL ), 0 );
+
+ /* Try to become a client of the JACK server. If we cannot do
+ * this, then this API cannot be used. */
+
+ jackHostApi->jack_client = jack_client_open( clientName_, 0, &jackStatus );
+ if( !jackHostApi->jack_client )
+ {
+ /* the V19 development docs say that if an implementation
+ * detects that it cannot be used, it should return a NULL
+ * interface and paNoError */
+ result = paNoError;
+ goto error;
+ }
+
+ jackHostApi->hostApiIndex = hostApiIndex;
+
+ *hostApi = &jackHostApi->commonHostApiRep;
+ (*hostApi)->info.structVersion = 1;
+ (*hostApi)->info.type = paJACK;
+ (*hostApi)->info.name = "JACK Audio Connection Kit";
+
+ /* Build a device list by querying the JACK server */
+
+ ENSURE_PA( BuildDeviceList( jackHostApi ) );
+
+ /* Register functions */
+
+ (*hostApi)->Terminate = Terminate;
+ (*hostApi)->OpenStream = OpenStream;
+ (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+ PaUtil_InitializeStreamInterface( &jackHostApi->callbackStreamInterface,
+ CloseStream, StartStream,
+ StopStream, AbortStream,
+ IsStreamStopped, IsStreamActive,
+ GetStreamTime, GetStreamCpuLoad,
+ PaUtil_DummyRead, PaUtil_DummyWrite,
+ PaUtil_DummyGetReadAvailable,
+ PaUtil_DummyGetWriteAvailable );
+
+ PaUtil_InitializeStreamInterface( &jackHostApi->blockingStreamInterface, CloseStream, StartStream,
+ StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+ GetStreamTime, PaUtil_DummyGetCpuLoad,
+ BlockingReadStream, BlockingWriteStream,
+ BlockingGetStreamReadAvailable, BlockingGetStreamWriteAvailable );
+
+ jackHostApi->inputBase = jackHostApi->outputBase = 0;
+ jackHostApi->xrun = 0;
+ jackHostApi->toAdd = jackHostApi->toRemove = NULL;
+ jackHostApi->processQueue = NULL;
+ jackHostApi->jackIsDown = 0;
+
+ jack_on_shutdown( jackHostApi->jack_client, JackOnShutdown, jackHostApi );
+ jack_set_error_function( JackErrorCallback );
+ jackHostApi->jack_buffer_size = jack_get_buffer_size ( jackHostApi->jack_client );
+ /* Don't check for error, may not be supported (deprecated in at least jackdmp) */
+ jack_set_sample_rate_callback( jackHostApi->jack_client, JackSrCb, jackHostApi );
+ UNLESS( !jack_set_xrun_callback( jackHostApi->jack_client, JackXRunCb, jackHostApi ), paUnanticipatedHostError );
+ UNLESS( !jack_set_process_callback( jackHostApi->jack_client, JackCallback, jackHostApi ), paUnanticipatedHostError );
+ UNLESS( !jack_activate( jackHostApi->jack_client ), paUnanticipatedHostError );
+ activated = 1;
+
+ return result;
+
+error:
+ if( activated )
+ ASSERT_CALL( jack_deactivate( jackHostApi->jack_client ), 0 );
+
+ if( jackHostApi )
+ {
+ if( jackHostApi->jack_client )
+ ASSERT_CALL( jack_client_close( jackHostApi->jack_client ), 0 );
+
+ if( jackHostApi->deviceInfoMemory )
+ {
+ PaUtil_FreeAllAllocations( jackHostApi->deviceInfoMemory );
+ PaUtil_DestroyAllocationGroup( jackHostApi->deviceInfoMemory );
+ }
+
+ PaUtil_FreeMemory( jackHostApi );
+ }
+ return result;
+}
+
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+ PaJackHostApiRepresentation *jackHostApi = (PaJackHostApiRepresentation*)hostApi;
+
+ /* note: this automatically disconnects all ports, since a deactivated
+ * client is not allowed to have any ports connected */
+ ASSERT_CALL( jack_deactivate( jackHostApi->jack_client ), 0 );
+
+ ASSERT_CALL( pthread_mutex_destroy( &jackHostApi->mtx ), 0 );
+ ASSERT_CALL( pthread_cond_destroy( &jackHostApi->cond ), 0 );
+
+ ASSERT_CALL( jack_client_close( jackHostApi->jack_client ), 0 );
+
+ if( jackHostApi->deviceInfoMemory )
+ {
+ PaUtil_FreeAllAllocations( jackHostApi->deviceInfoMemory );
+ PaUtil_DestroyAllocationGroup( jackHostApi->deviceInfoMemory );
+ }
+
+ PaUtil_FreeMemory( jackHostApi );
+
+ free( jackErr_ );
+}
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate )
+{
+ int inputChannelCount = 0, outputChannelCount = 0;
+ PaSampleFormat inputSampleFormat, outputSampleFormat;
+
+ if( inputParameters )
+ {
+ inputChannelCount = inputParameters->channelCount;
+ inputSampleFormat = inputParameters->sampleFormat;
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+
+ if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ /* check that input device can support inputChannelCount */
+ if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+ return paInvalidChannelCount;
+
+ /* validate inputStreamInfo */
+ if( inputParameters->hostApiSpecificStreamInfo )
+ return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+ }
+ else
+ {
+ inputChannelCount = 0;
+ }
+
+ if( outputParameters )
+ {
+ outputChannelCount = outputParameters->channelCount;
+ outputSampleFormat = outputParameters->sampleFormat;
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+
+ if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ /* check that output device can support inputChannelCount */
+ if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+ return paInvalidChannelCount;
+
+ /* validate outputStreamInfo */
+ if( outputParameters->hostApiSpecificStreamInfo )
+ return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+ }
+ else
+ {
+ outputChannelCount = 0;
+ }
+
+ /*
+ The following check is not necessary for JACK.
+
+ - if a full duplex stream is requested, check that the combination
+ of input and output parameters is supported
+
+
+ Because the buffer adapter handles conversion between all standard
+ sample formats, the following checks are only required if paCustomFormat
+ is implemented, or under some other unusual conditions.
+
+ - check that input device can support inputSampleFormat, or that
+ we have the capability to convert from outputSampleFormat to
+ a native format
+
+ - check that output device can support outputSampleFormat, or that
+ we have the capability to convert from outputSampleFormat to
+ a native format
+ */
+
+ /* check that the device supports sampleRate */
+
+#define ABS(x) ( (x) > 0 ? (x) : -(x) )
+ if( ABS(sampleRate - jack_get_sample_rate(((PaJackHostApiRepresentation *) hostApi)->jack_client )) > 1 )
+ return paInvalidSampleRate;
+#undef ABS
+
+ return paFormatIsSupported;
+}
+
+/* Basic stream initialization */
+static PaError InitializeStream( PaJackStream *stream, PaJackHostApiRepresentation *hostApi, int numInputChannels,
+ int numOutputChannels )
+{
+ PaError result = paNoError;
+ assert( stream );
+
+ memset( stream, 0, sizeof (PaJackStream) );
+ UNLESS( stream->stream_memory = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
+ stream->jack_client = hostApi->jack_client;
+ stream->hostApi = hostApi;
+
+ if( numInputChannels > 0 )
+ {
+ UNLESS( stream->local_input_ports =
+ (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numInputChannels ),
+ paInsufficientMemory );
+ memset( stream->local_input_ports, 0, sizeof(jack_port_t*) * numInputChannels );
+ UNLESS( stream->remote_output_ports =
+ (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numInputChannels ),
+ paInsufficientMemory );
+ memset( stream->remote_output_ports, 0, sizeof(jack_port_t*) * numInputChannels );
+ }
+ if( numOutputChannels > 0 )
+ {
+ UNLESS( stream->local_output_ports =
+ (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numOutputChannels ),
+ paInsufficientMemory );
+ memset( stream->local_output_ports, 0, sizeof(jack_port_t*) * numOutputChannels );
+ UNLESS( stream->remote_input_ports =
+ (jack_port_t**) PaUtil_GroupAllocateMemory( stream->stream_memory, sizeof(jack_port_t*) * numOutputChannels ),
+ paInsufficientMemory );
+ memset( stream->remote_input_ports, 0, sizeof(jack_port_t*) * numOutputChannels );
+ }
+
+ stream->num_incoming_connections = numInputChannels;
+ stream->num_outgoing_connections = numOutputChannels;
+
+error:
+ return result;
+}
+
+/*!
+ * Free resources associated with stream, and eventually stream itself.
+ *
+ * Frees allocated memory, and closes opened pcms.
+ */
+static void CleanUpStream( PaJackStream *stream, int terminateStreamRepresentation, int terminateBufferProcessor )
+{
+ int i;
+ assert( stream );
+
+ if( stream->isBlockingStream )
+ BlockingEnd( stream );
+
+ for( i = 0; i < stream->num_incoming_connections; ++i )
+ {
+ if( stream->local_input_ports[i] )
+ ASSERT_CALL( jack_port_unregister( stream->jack_client, stream->local_input_ports[i] ), 0 );
+ }
+ for( i = 0; i < stream->num_outgoing_connections; ++i )
+ {
+ if( stream->local_output_ports[i] )
+ ASSERT_CALL( jack_port_unregister( stream->jack_client, stream->local_output_ports[i] ), 0 );
+ }
+
+ if( terminateStreamRepresentation )
+ PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+ if( terminateBufferProcessor )
+ PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+
+ if( stream->stream_memory )
+ {
+ PaUtil_FreeAllAllocations( stream->stream_memory );
+ PaUtil_DestroyAllocationGroup( stream->stream_memory );
+ }
+ PaUtil_FreeMemory( stream );
+}
+
+static PaError WaitCondition( PaJackHostApiRepresentation *hostApi )
+{
+ PaError result = paNoError;
+ int err = 0;
+ PaTime pt = PaUtil_GetTime();
+ struct timespec ts;
+
+ ts.tv_sec = (time_t) floor( pt + 1 );
+ ts.tv_nsec = (long) ((pt - floor( pt )) * 1000000000);
+ /* XXX: Best enclose in loop, in case of spurious wakeups? */
+ err = pthread_cond_timedwait( &hostApi->cond, &hostApi->mtx, &ts );
+
+ /* Make sure we didn't time out */
+ UNLESS( err != ETIMEDOUT, paTimedOut );
+ UNLESS( !err, paInternalError );
+
+error:
+ return result;
+}
+
+static PaError AddStream( PaJackStream *stream )
+{
+ PaError result = paNoError;
+ PaJackHostApiRepresentation *hostApi = stream->hostApi;
+ /* Add to queue of streams that should be processed */
+ ASSERT_CALL( pthread_mutex_lock( &hostApi->mtx ), 0 );
+ if( !hostApi->jackIsDown )
+ {
+ hostApi->toAdd = stream;
+ /* Unlock mutex and await signal from processing thread */
+ result = WaitCondition( stream->hostApi );
+ }
+ ASSERT_CALL( pthread_mutex_unlock( &hostApi->mtx ), 0 );
+ ENSURE_PA( result );
+
+ UNLESS( !hostApi->jackIsDown, paDeviceUnavailable );
+
+error:
+ return result;
+}
+
+/* Remove stream from processing queue */
+static PaError RemoveStream( PaJackStream *stream )
+{
+ PaError result = paNoError;
+ PaJackHostApiRepresentation *hostApi = stream->hostApi;
+
+ /* Add to queue over streams that should be processed */
+ ASSERT_CALL( pthread_mutex_lock( &hostApi->mtx ), 0 );
+ if( !hostApi->jackIsDown )
+ {
+ hostApi->toRemove = stream;
+ /* Unlock mutex and await signal from processing thread */
+ result = WaitCondition( stream->hostApi );
+ }
+ ASSERT_CALL( pthread_mutex_unlock( &hostApi->mtx ), 0 );
+ ENSURE_PA( result );
+
+error:
+ return result;
+}
+
+/* Add stream to JACK callback processing queue */
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+ PaStream** s,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate,
+ unsigned long framesPerBuffer,
+ PaStreamFlags streamFlags,
+ PaStreamCallback *streamCallback,
+ void *userData )
+{
+ PaError result = paNoError;
+ PaJackHostApiRepresentation *jackHostApi = (PaJackHostApiRepresentation*)hostApi;
+ PaJackStream *stream = NULL;
+ char *port_string = PaUtil_GroupAllocateMemory( jackHostApi->deviceInfoMemory, jack_port_name_size() );
+ unsigned long regexSz = jack_client_name_size() + 3;
+ char *regex_pattern = PaUtil_GroupAllocateMemory( jackHostApi->deviceInfoMemory, regexSz );
+ const char **jack_ports = NULL;
+ /* int jack_max_buffer_size = jack_get_buffer_size( jackHostApi->jack_client ); */
+ int i;
+ int inputChannelCount, outputChannelCount;
+ const double jackSr = jack_get_sample_rate( jackHostApi->jack_client );
+ PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0;
+ int bpInitialized = 0, srInitialized = 0; /* Initialized buffer processor and stream representation? */
+ unsigned long ofs;
+
+ /* validate platform specific flags */
+ if( (streamFlags & paPlatformSpecificFlags) != 0 )
+ return paInvalidFlag; /* unexpected platform specific flag */
+ if( (streamFlags & paPrimeOutputBuffersUsingStreamCallback) != 0 )
+ {
+ streamFlags &= ~paPrimeOutputBuffersUsingStreamCallback;
+ /*return paInvalidFlag;*/ /* This implementation does not support buffer priming */
+ }
+
+ if( framesPerBuffer != paFramesPerBufferUnspecified )
+ {
+ /* Jack operates with power of two buffers, and we don't support non-integer buffer adaption (yet) */
+ /*UNLESS( !(framesPerBuffer & (framesPerBuffer - 1)), paBufferTooBig );*/ /* TODO: Add descriptive error code? */
+ }
+
+ /* Preliminary checks */
+
+ if( inputParameters )
+ {
+ inputChannelCount = inputParameters->channelCount;
+ inputSampleFormat = inputParameters->sampleFormat;
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+
+ if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ /* check that input device can support inputChannelCount */
+ if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+ return paInvalidChannelCount;
+
+ /* validate inputStreamInfo */
+ if( inputParameters->hostApiSpecificStreamInfo )
+ return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+ }
+ else
+ {
+ inputChannelCount = 0;
+ }
+
+ if( outputParameters )
+ {
+ outputChannelCount = outputParameters->channelCount;
+ outputSampleFormat = outputParameters->sampleFormat;
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+
+ if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ /* check that output device can support inputChannelCount */
+ if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+ return paInvalidChannelCount;
+
+ /* validate outputStreamInfo */
+ if( outputParameters->hostApiSpecificStreamInfo )
+ return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+ }
+ else
+ {
+ outputChannelCount = 0;
+ }
+
+ /* ... check that the sample rate exactly matches the ONE acceptable rate
+ * A: This rate isn't necessarily constant though? */
+
+#define ABS(x) ( (x) > 0 ? (x) : -(x) )
+ if( ABS(sampleRate - jackSr) > 1 )
+ return paInvalidSampleRate;
+#undef ABS
+
+ UNLESS( stream = (PaJackStream*)PaUtil_AllocateMemory( sizeof(PaJackStream) ), paInsufficientMemory );
+ ENSURE_PA( InitializeStream( stream, jackHostApi, inputChannelCount, outputChannelCount ) );
+
+ /* the blocking emulation, if necessary */
+ stream->isBlockingStream = !streamCallback;
+ if( stream->isBlockingStream )
+ {
+ float latency = 0.001; /* 1ms is the absolute minimum we support */
+ int minimum_buffer_frames = 0;
+
+ if( inputParameters && inputParameters->suggestedLatency > latency )
+ latency = inputParameters->suggestedLatency;
+ else if( outputParameters && outputParameters->suggestedLatency > latency )
+ latency = outputParameters->suggestedLatency;
+
+ /* the latency the user asked for indicates the minimum buffer size in frames */
+ minimum_buffer_frames = (int) (latency * jack_get_sample_rate( jackHostApi->jack_client ));
+
+ /* we also need to be able to store at least three full jack buffers to avoid dropouts */
+ if( jackHostApi->jack_buffer_size * 3 > minimum_buffer_frames )
+ minimum_buffer_frames = jackHostApi->jack_buffer_size * 3;
+
+ /* setup blocking API data structures (FIXME: can fail) */
+ BlockingBegin( stream, minimum_buffer_frames );
+
+ /* install our own callback for the blocking API */
+ streamCallback = BlockingCallback;
+ userData = stream;
+
+ PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+ &jackHostApi->blockingStreamInterface, streamCallback, userData );
+ }
+ else
+ {
+ PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+ &jackHostApi->callbackStreamInterface, streamCallback, userData );
+ }
+ srInitialized = 1;
+ PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, jackSr );
+
+ /* create the JACK ports. We cannot connect them until audio
+ * processing begins */
+
+ /* Register a unique set of ports for this stream
+ * TODO: Robust allocation of new port names */
+
+ ofs = jackHostApi->inputBase;
+ for( i = 0; i < inputChannelCount; i++ )
+ {
+ snprintf( port_string, jack_port_name_size(), "in_%lu", ofs + i );
+ UNLESS( stream->local_input_ports[i] = jack_port_register(
+ jackHostApi->jack_client, port_string,
+ JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0 ), paInsufficientMemory );
+ }
+ jackHostApi->inputBase += inputChannelCount;
+
+ ofs = jackHostApi->outputBase;
+ for( i = 0; i < outputChannelCount; i++ )
+ {
+ snprintf( port_string, jack_port_name_size(), "out_%lu", ofs + i );
+ UNLESS( stream->local_output_ports[i] = jack_port_register(
+ jackHostApi->jack_client, port_string,
+ JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0 ), paInsufficientMemory );
+ }
+ jackHostApi->outputBase += outputChannelCount;
+
+ /* look up the jack_port_t's for the remote ports. We could do
+ * this at stream start time, but doing it here ensures the
+ * name lookup only happens once. */
+
+ if( inputChannelCount > 0 )
+ {
+ int err = 0;
+
+ /* Get output ports of our capture device */
+ snprintf( regex_pattern, regexSz, "%s:.*", hostApi->deviceInfos[ inputParameters->device ]->name );
+ UNLESS( jack_ports = jack_get_ports( jackHostApi->jack_client, regex_pattern,
+ NULL, JackPortIsOutput ), paUnanticipatedHostError );
+ for( i = 0; i < inputChannelCount && jack_ports[i]; i++ )
+ {
+ if( (stream->remote_output_ports[i] = jack_port_by_name(
+ jackHostApi->jack_client, jack_ports[i] )) == NULL )
+ {
+ err = 1;
+ break;
+ }
+ }
+ free( jack_ports );
+ UNLESS( !err, paInsufficientMemory );
+
+ /* Fewer ports than expected? */
+ UNLESS( i == inputChannelCount, paInternalError );
+ }
+
+ if( outputChannelCount > 0 )
+ {
+ int err = 0;
+
+ /* Get input ports of our playback device */
+ snprintf( regex_pattern, regexSz, "%s:.*", hostApi->deviceInfos[ outputParameters->device ]->name );
+ UNLESS( jack_ports = jack_get_ports( jackHostApi->jack_client, regex_pattern,
+ NULL, JackPortIsInput ), paUnanticipatedHostError );
+ for( i = 0; i < outputChannelCount && jack_ports[i]; i++ )
+ {
+ if( (stream->remote_input_ports[i] = jack_port_by_name(
+ jackHostApi->jack_client, jack_ports[i] )) == 0 )
+ {
+ err = 1;
+ break;
+ }
+ }
+ free( jack_ports );
+ UNLESS( !err , paInsufficientMemory );
+
+ /* Fewer ports than expected? */
+ UNLESS( i == outputChannelCount, paInternalError );
+ }
+
+ ENSURE_PA( PaUtil_InitializeBufferProcessor(
+ &stream->bufferProcessor,
+ inputChannelCount,
+ inputSampleFormat,
+ paFloat32, /* hostInputSampleFormat */
+ outputChannelCount,
+ outputSampleFormat,
+ paFloat32, /* hostOutputSampleFormat */
+ jackSr,
+ streamFlags,
+ framesPerBuffer,
+ 0, /* Ignored */
+ paUtilUnknownHostBufferSize, /* Buffer size may vary on JACK's discretion */
+ streamCallback,
+ userData ) );
+ bpInitialized = 1;
+
+ if( stream->num_incoming_connections > 0 )
+ stream->streamRepresentation.streamInfo.inputLatency = (jack_port_get_latency( stream->remote_output_ports[0] )
+ - jack_get_buffer_size( jackHostApi->jack_client ) /* One buffer is not counted as latency */
+ + PaUtil_GetBufferProcessorInputLatency( &stream->bufferProcessor )) / sampleRate;
+ if( stream->num_outgoing_connections > 0 )
+ stream->streamRepresentation.streamInfo.outputLatency = (jack_port_get_latency( stream->remote_input_ports[0] )
+ - jack_get_buffer_size( jackHostApi->jack_client ) /* One buffer is not counted as latency */
+ + PaUtil_GetBufferProcessorOutputLatency( &stream->bufferProcessor )) / sampleRate;
+
+ stream->streamRepresentation.streamInfo.sampleRate = jackSr;
+ stream->t0 = jack_frame_time( jackHostApi->jack_client ); /* A: Time should run from Pa_OpenStream */
+
+ /* Add to queue of opened streams */
+ ENSURE_PA( AddStream( stream ) );
+
+ *s = (PaStream*)stream;
+
+ return result;
+
+error:
+ if( stream )
+ CleanUpStream( stream, srInitialized, bpInitialized );
+
+ return result;
+}
+
+/*
+ When CloseStream() is called, the multi-api layer ensures that
+ the stream has already been stopped or aborted.
+*/
+static PaError CloseStream( PaStream* s )
+{
+ PaError result = paNoError;
+ PaJackStream *stream = (PaJackStream*)s;
+
+ /* Remove this stream from the processing queue */
+ ENSURE_PA( RemoveStream( stream ) );
+
+error:
+ CleanUpStream( stream, 1, 1 );
+ return result;
+}
+
+static PaError RealProcess( PaJackStream *stream, jack_nframes_t frames )
+{
+ PaError result = paNoError;
+ PaStreamCallbackTimeInfo timeInfo = {0,0,0};
+ int chn;
+ int framesProcessed;
+ const double sr = jack_get_sample_rate( stream->jack_client ); /* Shouldn't change during the process callback */
+ PaStreamCallbackFlags cbFlags = 0;
+
+ /* If the user has returned !paContinue from the callback we'll want to flush the internal buffers,
+ * when these are empty we can finally mark the stream as inactive */
+ if( stream->callbackResult != paContinue &&
+ PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
+ {
+ stream->is_active = 0;
+ if( stream->streamRepresentation.streamFinishedCallback )
+ stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+ PA_DEBUG(( "%s: Callback finished\n", __FUNCTION__ ));
+
+ goto end;
+ }
+
+ timeInfo.currentTime = (jack_frame_time( stream->jack_client ) - stream->t0) / sr;
+ if( stream->num_incoming_connections > 0 )
+ timeInfo.inputBufferAdcTime = timeInfo.currentTime - jack_port_get_latency( stream->remote_output_ports[0] )
+ / sr;
+ if( stream->num_outgoing_connections > 0 )
+ timeInfo.outputBufferDacTime = timeInfo.currentTime + jack_port_get_latency( stream->remote_input_ports[0] )
+ / sr;
+
+ PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+
+ if( stream->xrun )
+ {
+ /* XXX: Any way to tell which of these occurred? */
+ cbFlags = paOutputUnderflow | paInputOverflow;
+ stream->xrun = FALSE;
+ }
+ PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo,
+ cbFlags );
+
+ if( stream->num_incoming_connections > 0 )
+ PaUtil_SetInputFrameCount( &stream->bufferProcessor, frames );
+ if( stream->num_outgoing_connections > 0 )
+ PaUtil_SetOutputFrameCount( &stream->bufferProcessor, frames );
+
+ for( chn = 0; chn < stream->num_incoming_connections; chn++ )
+ {
+ jack_default_audio_sample_t *channel_buf = (jack_default_audio_sample_t*)
+ jack_port_get_buffer( stream->local_input_ports[chn],
+ frames );
+
+ PaUtil_SetNonInterleavedInputChannel( &stream->bufferProcessor,
+ chn,
+ channel_buf );
+ }
+
+ for( chn = 0; chn < stream->num_outgoing_connections; chn++ )
+ {
+ jack_default_audio_sample_t *channel_buf = (jack_default_audio_sample_t*)
+ jack_port_get_buffer( stream->local_output_ports[chn],
+ frames );
+
+ PaUtil_SetNonInterleavedOutputChannel( &stream->bufferProcessor,
+ chn,
+ channel_buf );
+ }
+
+ framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor,
+ &stream->callbackResult );
+ /* We've specified a host buffer size mode where every frame should be consumed by the buffer processor */
+ assert( framesProcessed == frames );
+
+ PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
+
+end:
+ return result;
+}
+
+/* Update the JACK callback's stream processing queue. */
+static PaError UpdateQueue( PaJackHostApiRepresentation *hostApi )
+{
+ PaError result = paNoError;
+ int queueModified = 0;
+ const double jackSr = jack_get_sample_rate( hostApi->jack_client );
+ int err;
+
+ if( (err = pthread_mutex_trylock( &hostApi->mtx )) != 0 )
+ {
+ assert( err == EBUSY );
+ return paNoError;
+ }
+
+ if( hostApi->toAdd )
+ {
+ if( hostApi->processQueue )
+ {
+ PaJackStream *node = hostApi->processQueue;
+ /* Advance to end of queue */
+ while( node->next )
+ node = node->next;
+
+ node->next = hostApi->toAdd;
+ }
+ else
+ {
+ /* The only queue entry. */
+ hostApi->processQueue = (PaJackStream *)hostApi->toAdd;
+ }
+
+ /* If necessary, update stream state */
+ if( hostApi->toAdd->streamRepresentation.streamInfo.sampleRate != jackSr )
+ UpdateSampleRate( hostApi->toAdd, jackSr );
+
+ hostApi->toAdd = NULL;
+ queueModified = 1;
+ }
+ if( hostApi->toRemove )
+ {
+ int removed = 0;
+ PaJackStream *node = hostApi->processQueue, *prev = NULL;
+ assert( hostApi->processQueue );
+
+ while( node )
+ {
+ if( node == hostApi->toRemove )
+ {
+ if( prev )
+ prev->next = node->next;
+ else
+ hostApi->processQueue = (PaJackStream *)node->next;
+
+ removed = 1;
+ break;
+ }
+
+ prev = node;
+ node = node->next;
+ }
+ UNLESS( removed, paInternalError );
+ hostApi->toRemove = NULL;
+ PA_DEBUG(( "%s: Removed stream from processing queue\n", __FUNCTION__ ));
+ queueModified = 1;
+ }
+
+ if( queueModified )
+ {
+ /* Signal that we've done what was asked of us */
+ ASSERT_CALL( pthread_cond_signal( &hostApi->cond ), 0 );
+ }
+
+error:
+ ASSERT_CALL( pthread_mutex_unlock( &hostApi->mtx ), 0 );
+
+ return result;
+}
+
+/* Audio processing callback invoked periodically from JACK. */
+static int JackCallback( jack_nframes_t frames, void *userData )
+{
+ PaError result = paNoError;
+ PaJackHostApiRepresentation *hostApi = (PaJackHostApiRepresentation *)userData;
+ PaJackStream *stream = NULL;
+ int xrun = hostApi->xrun;
+ hostApi->xrun = 0;
+
+ assert( hostApi );
+
+ ENSURE_PA( UpdateQueue( hostApi ) );
+
+ /* Process each stream */
+ stream = hostApi->processQueue;
+ for( ; stream; stream = stream->next )
+ {
+ if( xrun ) /* Don't override if already set */
+ stream->xrun = 1;
+
+ /* See if this stream is to be started */
+ if( stream->doStart )
+ {
+ /* If we can't obtain a lock, we'll try next time */
+ int err = pthread_mutex_trylock( &stream->hostApi->mtx );
+ if( !err )
+ {
+ if( stream->doStart ) /* Could potentially change before obtaining the lock */
+ {
+ stream->is_active = 1;
+ stream->doStart = 0;
+ PA_DEBUG(( "%s: Starting stream\n", __FUNCTION__ ));
+ ASSERT_CALL( pthread_cond_signal( &stream->hostApi->cond ), 0 );
+ stream->callbackResult = paContinue;
+ stream->isSilenced = 0;
+ }
+
+ ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 );
+ }
+ else
+ assert( err == EBUSY );
+ }
+ else if( stream->doStop || stream->doAbort ) /* Should we stop/abort stream? */
+ {
+ if( stream->callbackResult == paContinue ) /* Ok, make it stop */
+ {
+ PA_DEBUG(( "%s: Stopping stream\n", __FUNCTION__ ));
+ stream->callbackResult = stream->doStop ? paComplete : paAbort;
+ }
+ }
+
+ if( stream->is_active )
+ ENSURE_PA( RealProcess( stream, frames ) );
+ /* If we have just entered inactive state, silence output */
+ if( !stream->is_active && !stream->isSilenced )
+ {
+ int i;
+
+ /* Silence buffer after entering inactive state */
+ PA_DEBUG(( "Silencing the output\n" ));
+ for( i = 0; i < stream->num_outgoing_connections; ++i )
+ {
+ jack_default_audio_sample_t *buffer = jack_port_get_buffer( stream->local_output_ports[i], frames );
+ memset( buffer, 0, sizeof (jack_default_audio_sample_t) * frames );
+ }
+
+ stream->isSilenced = 1;
+ }
+
+ if( stream->doStop || stream->doAbort )
+ {
+ /* See if RealProcess has acted on the request */
+ if( !stream->is_active ) /* Ok, signal to the main thread that we've carried out the operation */
+ {
+ /* If we can't obtain a lock, we'll try next time */
+ int err = pthread_mutex_trylock( &stream->hostApi->mtx );
+ if( !err )
+ {
+ stream->doStop = stream->doAbort = 0;
+ ASSERT_CALL( pthread_cond_signal( &stream->hostApi->cond ), 0 );
+ ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 );
+ }
+ else
+ assert( err == EBUSY );
+ }
+ }
+ }
+
+ return 0;
+error:
+ return -1;
+}
+
+static PaError StartStream( PaStream *s )
+{
+ PaError result = paNoError;
+ PaJackStream *stream = (PaJackStream*)s;
+ int i;
+
+ /* Ready the processor */
+ PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+
+ /* Connect the ports. Note that the ports may already have been connected by someone else in
+ * the meantime, in which case JACK returns EEXIST. */
+
+ if( stream->num_incoming_connections > 0 )
+ {
+ for( i = 0; i < stream->num_incoming_connections; i++ )
+ {
+ int r = jack_connect( stream->jack_client, jack_port_name( stream->remote_output_ports[i] ),
+ jack_port_name( stream->local_input_ports[i] ) );
+ UNLESS( 0 == r || EEXIST == r, paUnanticipatedHostError );
+ }
+ }
+
+ if( stream->num_outgoing_connections > 0 )
+ {
+ for( i = 0; i < stream->num_outgoing_connections; i++ )
+ {
+ int r = jack_connect( stream->jack_client, jack_port_name( stream->local_output_ports[i] ),
+ jack_port_name( stream->remote_input_ports[i] ) );
+ UNLESS( 0 == r || EEXIST == r, paUnanticipatedHostError );
+ }
+ }
+
+ stream->xrun = FALSE;
+
+ /* Enable processing */
+
+ ASSERT_CALL( pthread_mutex_lock( &stream->hostApi->mtx ), 0 );
+ stream->doStart = 1;
+
+ /* Wait for stream to be started */
+ result = WaitCondition( stream->hostApi );
+ /*
+ do
+ {
+ err = pthread_cond_timedwait( &stream->hostApi->cond, &stream->hostApi->mtx, &ts );
+ } while( !stream->is_active && !err );
+ */
+ if( result != paNoError ) /* Something went wrong, call off the stream start */
+ {
+ stream->doStart = 0;
+ stream->is_active = 0; /* Cancel any processing */
+ }
+ ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 );
+
+ ENSURE_PA( result );
+
+ stream->is_running = TRUE;
+ PA_DEBUG(( "%s: Stream started\n", __FUNCTION__ ));
+
+error:
+ return result;
+}
+
+static PaError RealStop( PaJackStream *stream, int abort )
+{
+ PaError result = paNoError;
+ int i;
+
+ if( stream->isBlockingStream )
+ BlockingWaitEmpty ( stream );
+
+ ASSERT_CALL( pthread_mutex_lock( &stream->hostApi->mtx ), 0 );
+ if( abort )
+ stream->doAbort = 1;
+ else
+ stream->doStop = 1;
+
+ /* Wait for stream to be stopped */
+ result = WaitCondition( stream->hostApi );
+ ASSERT_CALL( pthread_mutex_unlock( &stream->hostApi->mtx ), 0 );
+ ENSURE_PA( result );
+
+ UNLESS( !stream->is_active, paInternalError );
+
+ PA_DEBUG(( "%s: Stream stopped\n", __FUNCTION__ ));
+
+error:
+ stream->is_running = FALSE;
+
+ /* Disconnect ports belonging to this stream */
+
+ if( !stream->hostApi->jackIsDown ) /* XXX: Well? */
+ {
+ for( i = 0; i < stream->num_incoming_connections; i++ )
+ {
+ if( jack_port_connected( stream->local_input_ports[i] ) )
+ {
+ UNLESS( !jack_port_disconnect( stream->jack_client, stream->local_input_ports[i] ),
+ paUnanticipatedHostError );
+ }
+ }
+ for( i = 0; i < stream->num_outgoing_connections; i++ )
+ {
+ if( jack_port_connected( stream->local_output_ports[i] ) )
+ {
+ UNLESS( !jack_port_disconnect( stream->jack_client, stream->local_output_ports[i] ),
+ paUnanticipatedHostError );
+ }
+ }
+ }
+
+ return result;
+}
+
+static PaError StopStream( PaStream *s )
+{
+ assert(s);
+ return RealStop( (PaJackStream *)s, 0 );
+}
+
+static PaError AbortStream( PaStream *s )
+{
+ assert(s);
+ return RealStop( (PaJackStream *)s, 1 );
+}
+
+static PaError IsStreamStopped( PaStream *s )
+{
+ PaJackStream *stream = (PaJackStream*)s;
+ return !stream->is_running;
+}
+
+
+static PaError IsStreamActive( PaStream *s )
+{
+ PaJackStream *stream = (PaJackStream*)s;
+ return stream->is_active;
+}
+
+
+static PaTime GetStreamTime( PaStream *s )
+{
+ PaJackStream *stream = (PaJackStream*)s;
+
+ /* A: Is this relevant?? --> TODO: what if we're recording-only? */
+ return (jack_frame_time( stream->jack_client ) - stream->t0) / (PaTime)jack_get_sample_rate( stream->jack_client );
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+ PaJackStream *stream = (PaJackStream*)s;
+ return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+PaError PaJack_SetClientName( const char* name )
+{
+ if( strlen( name ) > jack_client_name_size() )
+ {
+ /* OK, I don't know any better error code */
+ return paInvalidFlag;
+ }
+ clientName_ = name;
+ return paNoError;
+}
+
+PaError PaJack_GetClientName(const char** clientName)
+{
+ PaError result = paNoError;
+ PaJackHostApiRepresentation* jackHostApi = NULL;
+ ENSURE_PA( PaUtil_GetHostApiRepresentation( (PaUtilHostApiRepresentation**)&jackHostApi, paJACK ) );
+ *clientName = jack_get_client_name( jackHostApi->jack_client );
+
+error:
+ return result;
+}
diff --git a/pd/portaudio/src/hostapi/oss/low_latency_tip.txt b/pd/portaudio/src/hostapi/oss/low_latency_tip.txt
new file mode 100644
index 00000000..2d982b79
--- /dev/null
+++ b/pd/portaudio/src/hostapi/oss/low_latency_tip.txt
Binary files differ
diff --git a/pd/portaudio/src/hostapi/oss/pa_unix_oss.c b/pd/portaudio/src/hostapi/oss/pa_unix_oss.c
new file mode 100644
index 00000000..0895ce9a
--- /dev/null
+++ b/pd/portaudio/src/hostapi/oss/pa_unix_oss.c
@@ -0,0 +1,1946 @@
+/*
+ * $Id: pa_unix_oss.c,v 1.1 2007-08-18 23:49:33 millerpuckette Exp $
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ * OSS implementation by:
+ * Douglas Repetto
+ * Phil Burk
+ * Dominic Mazzoni
+ * Arve Knudsen
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/**
+ @file
+ @ingroup hostapi_src
+*/
+
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+#include <pthread.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/poll.h>
+#include <limits.h>
+#include <semaphore.h>
+
+#ifdef HAVE_SYS_SOUNDCARD_H
+# include <sys/soundcard.h>
+# define DEVICE_NAME_BASE "/dev/dsp"
+#elif defined(HAVE_LINUX_SOUNDCARD_H)
+# include <linux/soundcard.h>
+# define DEVICE_NAME_BASE "/dev/dsp"
+#elif defined(HAVE_MACHINE_SOUNDCARD_H)
+# include <machine/soundcard.h> /* JH20010905 */
+# define DEVICE_NAME_BASE "/dev/audio"
+#else
+# error No sound card header file
+#endif
+
+#include "portaudio.h"
+#include "pa_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "pa_unix_util.h"
+#include "pa_debugprint.h"
+
+static int sysErr_;
+static pthread_t mainThread_;
+
+/* Check return value of system call, and map it to PaError */
+#define ENSURE_(expr, code) \
+ do { \
+ if( UNLIKELY( (sysErr_ = (expr)) < 0 ) ) \
+ { \
+ /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
+ if( (code) == paUnanticipatedHostError && pthread_self() == mainThread_ ) \
+ { \
+ PaUtil_SetLastHostErrorInfo( paALSA, sysErr_, strerror( errno ) ); \
+ } \
+ \
+ PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
+ result = (code); \
+ goto error; \
+ } \
+ } while( 0 );
+
+#ifndef AFMT_S16_NE
+#define AFMT_S16_NE Get_AFMT_S16_NE()
+/*********************************************************************
+ * Some versions of OSS do not define AFMT_S16_NE. So check CPU.
+ * PowerPC is Big Endian. X86 is Little Endian.
+ */
+static int Get_AFMT_S16_NE( void )
+{
+ long testData = 1;
+ char *ptr = (char *) &testData;
+ int isLittle = ( *ptr == 1 ); /* Does address point to least significant byte? */
+ return isLittle ? AFMT_S16_LE : AFMT_S16_BE;
+}
+#endif
+
+/* PaOSSHostApiRepresentation - host api datastructure specific to this implementation */
+
+typedef struct
+{
+ PaUtilHostApiRepresentation inheritedHostApiRep;
+ PaUtilStreamInterface callbackStreamInterface;
+ PaUtilStreamInterface blockingStreamInterface;
+
+ PaUtilAllocationGroup *allocations;
+
+ PaHostApiIndex hostApiIndex;
+}
+PaOSSHostApiRepresentation;
+
+/** Per-direction structure for PaOssStream.
+ *
+ * Aspect StreamChannels: In case the user requests to open the same device for both capture and playback,
+ * but with different number of channels we will have to adapt between the number of user and host
+ * channels for at least one direction, since the configuration space is the same for both directions
+ * of an OSS device.
+ */
+typedef struct
+{
+ int fd;
+ const char *devName;
+ int userChannelCount, hostChannelCount;
+ int userInterleaved;
+ void *buffer;
+ PaSampleFormat userFormat, hostFormat;
+ double latency;
+ unsigned long hostFrames, numBufs;
+ void **userBuffers; /* For non-interleaved blocking */
+} PaOssStreamComponent;
+
+/** Implementation specific representation of a PaStream.
+ *
+ */
+typedef struct PaOssStream
+{
+ PaUtilStreamRepresentation streamRepresentation;
+ PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+ PaUtilBufferProcessor bufferProcessor;
+
+ PaUtilThreading threading;
+
+ int sharedDevice;
+ unsigned long framesPerHostBuffer;
+ int triggered; /* Have the devices been triggered yet (first start) */
+
+ int isActive;
+ int isStopped;
+
+ int lastPosPtr;
+ double lastStreamBytes;
+
+ int framesProcessed;
+
+ double sampleRate;
+
+ int callbackMode;
+ int callbackStop, callbackAbort;
+
+ PaOssStreamComponent *capture, *playback;
+ unsigned long pollTimeout;
+ sem_t semaphore;
+}
+PaOssStream;
+
+typedef enum {
+ StreamMode_In,
+ StreamMode_Out
+} StreamMode;
+
+/* prototypes for functions declared in this file */
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+ PaStream** s,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate,
+ unsigned long framesPerBuffer,
+ PaStreamFlags streamFlags,
+ PaStreamCallback *streamCallback,
+ void *userData );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+static signed long GetStreamReadAvailable( PaStream* stream );
+static signed long GetStreamWriteAvailable( PaStream* stream );
+static PaError BuildDeviceList( PaOSSHostApiRepresentation *hostApi );
+
+
+/** Initialize the OSS API implementation.
+ *
+ * This function will initialize host API datastructures and query host devices for information.
+ *
+ * Aspect DeviceCapabilities: Enumeration of host API devices is initiated from here
+ *
+ * Aspect FreeResources: If an error is encountered under way we have to free each resource allocated in this function,
+ * this happens with the usual "error" label.
+ */
+PaError PaOSS_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+ PaError result = paNoError;
+ PaOSSHostApiRepresentation *ossHostApi = NULL;
+
+ PA_UNLESS( ossHostApi = (PaOSSHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaOSSHostApiRepresentation) ),
+ paInsufficientMemory );
+ PA_UNLESS( ossHostApi->allocations = PaUtil_CreateAllocationGroup(), paInsufficientMemory );
+ ossHostApi->hostApiIndex = hostApiIndex;
+
+ /* Initialize host API structure */
+ *hostApi = &ossHostApi->inheritedHostApiRep;
+ (*hostApi)->info.structVersion = 1;
+ (*hostApi)->info.type = paOSS;
+ (*hostApi)->info.name = "OSS";
+ (*hostApi)->Terminate = Terminate;
+ (*hostApi)->OpenStream = OpenStream;
+ (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+ PA_ENSURE( BuildDeviceList( ossHostApi ) );
+
+ PaUtil_InitializeStreamInterface( &ossHostApi->callbackStreamInterface, CloseStream, StartStream,
+ StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+ GetStreamTime, GetStreamCpuLoad,
+ PaUtil_DummyRead, PaUtil_DummyWrite,
+ PaUtil_DummyGetReadAvailable,
+ PaUtil_DummyGetWriteAvailable );
+
+ PaUtil_InitializeStreamInterface( &ossHostApi->blockingStreamInterface, CloseStream, StartStream,
+ StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+ GetStreamTime, PaUtil_DummyGetCpuLoad,
+ ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+
+ mainThread_ = pthread_self();
+
+ return result;
+
+error:
+ if( ossHostApi )
+ {
+ if( ossHostApi->allocations )
+ {
+ PaUtil_FreeAllAllocations( ossHostApi->allocations );
+ PaUtil_DestroyAllocationGroup( ossHostApi->allocations );
+ }
+
+ PaUtil_FreeMemory( ossHostApi );
+ }
+ return result;
+}
+
+PaError PaUtil_InitializeDeviceInfo( PaDeviceInfo *deviceInfo, const char *name, PaHostApiIndex hostApiIndex, int maxInputChannels,
+ int maxOutputChannels, PaTime defaultLowInputLatency, PaTime defaultLowOutputLatency, PaTime defaultHighInputLatency,
+ PaTime defaultHighOutputLatency, double defaultSampleRate, PaUtilAllocationGroup *allocations )
+{
+ PaError result = paNoError;
+
+ deviceInfo->structVersion = 2;
+ if( allocations )
+ {
+ size_t len = strlen( name ) + 1;
+ PA_UNLESS( deviceInfo->name = PaUtil_GroupAllocateMemory( allocations, len ), paInsufficientMemory );
+ strncpy( (char *)deviceInfo->name, name, len );
+ }
+ else
+ deviceInfo->name = name;
+
+ deviceInfo->hostApi = hostApiIndex;
+ deviceInfo->maxInputChannels = maxInputChannels;
+ deviceInfo->maxOutputChannels = maxOutputChannels;
+ deviceInfo->defaultLowInputLatency = defaultLowInputLatency;
+ deviceInfo->defaultLowOutputLatency = defaultLowOutputLatency;
+ deviceInfo->defaultHighInputLatency = defaultHighInputLatency;
+ deviceInfo->defaultHighOutputLatency = defaultHighOutputLatency;
+ deviceInfo->defaultSampleRate = defaultSampleRate;
+
+error:
+ return result;
+}
+
+static PaError QueryDirection( const char *deviceName, StreamMode mode, double *defaultSampleRate, int *maxChannelCount,
+ double *defaultLowLatency, double *defaultHighLatency )
+{
+ PaError result = paNoError;
+ int numChannels, maxNumChannels;
+ int busy = 0;
+ int devHandle = -1;
+ int sr;
+ *maxChannelCount = 0; /* Default value in case this fails */
+
+ if ( (devHandle = open( deviceName, (mode == StreamMode_In ? O_RDONLY : O_WRONLY) | O_NONBLOCK )) < 0 )
+ {
+ if( errno == EBUSY || errno == EAGAIN )
+ {
+ PA_DEBUG(( "%s: Device %s busy\n", __FUNCTION__, deviceName ));
+ }
+ else
+ {
+ PA_DEBUG(( "%s: Can't access device: %s\n", __FUNCTION__, strerror( errno ) ));
+ }
+
+ return paDeviceUnavailable;
+ }
+
+ /* Negotiate for the maximum number of channels for this device. PLB20010927
+ * Consider up to 16 as the upper number of channels.
+ * Variable maxNumChannels should contain the actual upper limit after the call.
+ * Thanks to John Lazzaro and Heiko Purnhagen for suggestions.
+ */
+ maxNumChannels = 0;
+ for( numChannels = 1; numChannels <= 16; numChannels++ )
+ {
+ int temp = numChannels;
+ if( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &temp ) < 0 )
+ {
+ busy = EAGAIN == errno || EBUSY == errno;
+ /* ioctl() failed so bail out if we already have stereo */
+ if( maxNumChannels >= 2 )
+ break;
+ }
+ else
+ {
+ /* ioctl() worked but bail out if it does not support numChannels.
+ * We don't want to leave gaps in the numChannels supported.
+ */
+ if( (numChannels > 2) && (temp != numChannels) )
+ break;
+ if( temp > maxNumChannels )
+ maxNumChannels = temp; /* Save maximum. */
+ }
+ }
+ /* A: We're able to open a device for capture if it's busy playing back and vice versa,
+ * but we can't configure anything */
+ if( 0 == maxNumChannels && busy )
+ {
+ result = paDeviceUnavailable;
+ goto error;
+ }
+
+ /* The above negotiation may fail for an old driver so try this older technique. */
+ if( maxNumChannels < 1 )
+ {
+ int stereo = 1;
+ if( ioctl( devHandle, SNDCTL_DSP_STEREO, &stereo ) < 0 )
+ {
+ maxNumChannels = 1;
+ }
+ else
+ {
+ maxNumChannels = (stereo) ? 2 : 1;
+ }
+ PA_DEBUG(( "%s: use SNDCTL_DSP_STEREO, maxNumChannels = %d\n", __FUNCTION__, maxNumChannels ));
+ }
+
+ /* During channel negotiation, the last ioctl() may have failed. This can
+ * also cause sample rate negotiation to fail. Hence the following, to return
+ * to a supported number of channels. SG20011005 */
+ {
+ /* use most reasonable default value */
+ int temp = PA_MIN( maxNumChannels, 2 );
+ ENSURE_( ioctl( devHandle, SNDCTL_DSP_CHANNELS, &temp ), paUnanticipatedHostError );
+ }
+
+ /* Get supported sample rate closest to 44100 Hz */
+ if( *defaultSampleRate < 0 )
+ {
+ sr = 44100;
+ if( ioctl( devHandle, SNDCTL_DSP_SPEED, &sr ) < 0 )
+ {
+ result = paUnanticipatedHostError;
+ goto error;
+ }
+
+ *defaultSampleRate = sr;
+ }
+
+ *maxChannelCount = maxNumChannels;
+ /* TODO */
+ *defaultLowLatency = 512. / *defaultSampleRate;
+ *defaultHighLatency = 2048. / *defaultSampleRate;
+
+error:
+ if( devHandle >= 0 )
+ close( devHandle );
+
+ return result;
+}
+
+/** Query OSS device.
+ *
+ * This is where PaDeviceInfo objects are constructed and filled in with relevant information.
+ *
+ * Aspect DeviceCapabilities: The inferred device capabilities are recorded in a PaDeviceInfo object that is constructed
+ * in place.
+ */
+static PaError QueryDevice( char *deviceName, PaOSSHostApiRepresentation *ossApi, PaDeviceInfo **deviceInfo )
+{
+ PaError result = paNoError;
+ double sampleRate = -1.;
+ int maxInputChannels, maxOutputChannels;
+ PaTime defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency;
+ PaError tmpRes = paNoError;
+ int busy = 0;
+ *deviceInfo = NULL;
+
+ /* douglas:
+ we have to do this querying in a slightly different order. apparently
+ some sound cards will give you different info based on their settins.
+ e.g. a card might give you stereo at 22kHz but only mono at 44kHz.
+ the correct order for OSS is: format, channels, sample rate
+ */
+
+ /* Aspect StreamChannels: The number of channels supported for a device may depend on the mode it is
+ * opened in, it may have more channels available for capture than playback and vice versa. Therefore
+ * we will open the device in both read- and write-only mode to determine the supported number.
+ */
+ if( (tmpRes = QueryDirection( deviceName, StreamMode_In, &sampleRate, &maxInputChannels, &defaultLowInputLatency,
+ &defaultHighInputLatency )) != paNoError )
+ {
+ if( tmpRes != paDeviceUnavailable )
+ {
+ PA_DEBUG(( "%s: Querying device %s for capture failed!\n", __FUNCTION__, deviceName ));
+ /* PA_ENSURE( tmpRes ); */
+ }
+ ++busy;
+ }
+ if( (tmpRes = QueryDirection( deviceName, StreamMode_Out, &sampleRate, &maxOutputChannels, &defaultLowOutputLatency,
+ &defaultHighOutputLatency )) != paNoError )
+ {
+ if( tmpRes != paDeviceUnavailable )
+ {
+ PA_DEBUG(( "%s: Querying device %s for playback failed!\n", __FUNCTION__, deviceName ));
+ /* PA_ENSURE( tmpRes ); */
+ }
+ ++busy;
+ }
+ assert( 0 <= busy && busy <= 2 );
+ if( 2 == busy ) /* Both directions are unavailable to us */
+ {
+ result = paDeviceUnavailable;
+ goto error;
+ }
+
+ PA_UNLESS( *deviceInfo = PaUtil_GroupAllocateMemory( ossApi->allocations, sizeof (PaDeviceInfo) ), paInsufficientMemory );
+ PA_ENSURE( PaUtil_InitializeDeviceInfo( *deviceInfo, deviceName, ossApi->hostApiIndex, maxInputChannels, maxOutputChannels,
+ defaultLowInputLatency, defaultLowOutputLatency, defaultHighInputLatency, defaultHighOutputLatency, sampleRate,
+ ossApi->allocations ) );
+
+error:
+ return result;
+}
+
+/** Query host devices.
+ *
+ * Loop over host devices and query their capabilitiesu
+ *
+ * Aspect DeviceCapabilities: This function calls QueryDevice on each device entry and receives a filled in PaDeviceInfo object
+ * per device, these are placed in the host api representation's deviceInfos array.
+ */
+static PaError BuildDeviceList( PaOSSHostApiRepresentation *ossApi )
+{
+ PaError result = paNoError;
+ PaUtilHostApiRepresentation *commonApi = &ossApi->inheritedHostApiRep;
+ int i;
+ int numDevices = 0, maxDeviceInfos = 1;
+ PaDeviceInfo **deviceInfos = NULL;
+
+ /* These two will be set to the first working input and output device, respectively */
+ commonApi->info.defaultInputDevice = paNoDevice;
+ commonApi->info.defaultOutputDevice = paNoDevice;
+
+ /* Find devices by calling QueryDevice on each
+ * potential device names. When we find a valid one,
+ * add it to a linked list.
+ * A: Can there only be 10 devices? */
+
+ for( i = 0; i < 10; i++ )
+ {
+ char deviceName[32];
+ PaDeviceInfo *deviceInfo;
+ int testResult;
+ struct stat stbuf;
+
+ if( i == 0 )
+ snprintf(deviceName, sizeof (deviceName), "%s", DEVICE_NAME_BASE);
+ else
+ snprintf(deviceName, sizeof (deviceName), "%s%d", DEVICE_NAME_BASE, i);
+
+ /* PA_DEBUG(("PaOSS BuildDeviceList: trying device %s\n", deviceName )); */
+ if( stat( deviceName, &stbuf ) < 0 )
+ {
+ if( ENOENT != errno )
+ PA_DEBUG(( "%s: Error stat'ing %s: %s\n", __FUNCTION__, deviceName, strerror( errno ) ));
+ continue;
+ }
+ if( (testResult = QueryDevice( deviceName, ossApi, &deviceInfo )) != paNoError )
+ {
+ if( testResult != paDeviceUnavailable )
+ PA_ENSURE( testResult );
+
+ continue;
+ }
+
+ ++numDevices;
+ if( !deviceInfos || numDevices > maxDeviceInfos )
+ {
+ maxDeviceInfos *= 2;
+ PA_UNLESS( deviceInfos = (PaDeviceInfo **) realloc( deviceInfos, maxDeviceInfos * sizeof (PaDeviceInfo *) ),
+ paInsufficientMemory );
+ }
+ {
+ int devIdx = numDevices - 1;
+ deviceInfos[devIdx] = deviceInfo;
+
+ if( commonApi->info.defaultInputDevice == paNoDevice && deviceInfo->maxInputChannels > 0 )
+ commonApi->info.defaultInputDevice = devIdx;
+ if( commonApi->info.defaultOutputDevice == paNoDevice && deviceInfo->maxOutputChannels > 0 )
+ commonApi->info.defaultOutputDevice = devIdx;
+ }
+ }
+
+ /* Make an array of PaDeviceInfo pointers out of the linked list */
+
+ PA_DEBUG(("PaOSS %s: Total number of devices found: %d\n", __FUNCTION__, numDevices));
+
+ commonApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+ ossApi->allocations, sizeof(PaDeviceInfo*) * numDevices );
+ memcpy( commonApi->deviceInfos, deviceInfos, numDevices * sizeof (PaDeviceInfo *) );
+
+ commonApi->info.deviceCount = numDevices;
+
+error:
+ free( deviceInfos );
+
+ return result;
+}
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+ PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi;
+
+ if( ossHostApi->allocations )
+ {
+ PaUtil_FreeAllAllocations( ossHostApi->allocations );
+ PaUtil_DestroyAllocationGroup( ossHostApi->allocations );
+ }
+
+ PaUtil_FreeMemory( ossHostApi );
+}
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate )
+{
+ PaError result = paNoError;
+ PaDeviceIndex device;
+ PaDeviceInfo *deviceInfo;
+ char *deviceName;
+ int inputChannelCount, outputChannelCount;
+ int tempDevHandle = -1;
+ int flags;
+ PaSampleFormat inputSampleFormat, outputSampleFormat;
+
+ if( inputParameters )
+ {
+ inputChannelCount = inputParameters->channelCount;
+ inputSampleFormat = inputParameters->sampleFormat;
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+
+ if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ /* check that input device can support inputChannelCount */
+ if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
+ return paInvalidChannelCount;
+
+ /* validate inputStreamInfo */
+ if( inputParameters->hostApiSpecificStreamInfo )
+ return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+ }
+ else
+ {
+ inputChannelCount = 0;
+ }
+
+ if( outputParameters )
+ {
+ outputChannelCount = outputParameters->channelCount;
+ outputSampleFormat = outputParameters->sampleFormat;
+
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+
+ if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ /* check that output device can support inputChannelCount */
+ if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
+ return paInvalidChannelCount;
+
+ /* validate outputStreamInfo */
+ if( outputParameters->hostApiSpecificStreamInfo )
+ return paIncompatibleHostApiSpecificStreamInfo; /* this implementation doesn't use custom stream info */
+ }
+ else
+ {
+ outputChannelCount = 0;
+ }
+
+ if (inputChannelCount == 0 && outputChannelCount == 0)
+ return paInvalidChannelCount;
+
+ /* if full duplex, make sure that they're the same device */
+
+ if (inputChannelCount > 0 && outputChannelCount > 0 &&
+ inputParameters->device != outputParameters->device)
+ return paInvalidDevice;
+
+ /* if full duplex, also make sure that they're the same number of channels */
+
+ if (inputChannelCount > 0 && outputChannelCount > 0 &&
+ inputChannelCount != outputChannelCount)
+ return paInvalidChannelCount;
+
+ /* open the device so we can do more tests */
+
+ if( inputChannelCount > 0 )
+ {
+ result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, inputParameters->device, hostApi);
+ if (result != paNoError)
+ return result;
+ }
+ else
+ {
+ result = PaUtil_DeviceIndexToHostApiDeviceIndex(&device, outputParameters->device, hostApi);
+ if (result != paNoError)
+ return result;
+ }
+
+ deviceInfo = hostApi->deviceInfos[device];
+ deviceName = (char *)deviceInfo->name;
+
+ flags = O_NONBLOCK;
+ if (inputChannelCount > 0 && outputChannelCount > 0)
+ flags |= O_RDWR;
+ else if (inputChannelCount > 0)
+ flags |= O_RDONLY;
+ else
+ flags |= O_WRONLY;
+
+ ENSURE_( tempDevHandle = open( deviceInfo->name, flags ), paDeviceUnavailable );
+
+ /* PaOssStream_Configure will do the rest of the checking for us */
+ /* PA_ENSURE( PaOssStream_Configure( tempDevHandle, deviceName, outputChannelCount, &sampleRate ) ); */
+
+ /* everything succeeded! */
+
+ error:
+ if( tempDevHandle >= 0 )
+ close( tempDevHandle );
+
+ return result;
+}
+
+/** Validate stream parameters.
+ *
+ * Aspect StreamChannels: We verify that the number of channels is within the allowed range for the device
+ */
+static PaError ValidateParameters( const PaStreamParameters *parameters, const PaDeviceInfo *deviceInfo, StreamMode mode )
+{
+ int maxChans;
+
+ assert( parameters );
+
+ if( parameters->device == paUseHostApiSpecificDeviceSpecification )
+ {
+ return paInvalidDevice;
+ }
+
+ maxChans = (mode == StreamMode_In ? deviceInfo->maxInputChannels :
+ deviceInfo->maxOutputChannels);
+ if( parameters->channelCount > maxChans )
+ {
+ return paInvalidChannelCount;
+ }
+
+ return paNoError;
+}
+
+static PaError PaOssStreamComponent_Initialize( PaOssStreamComponent *component, const PaStreamParameters *parameters,
+ int callbackMode, int fd, const char *deviceName )
+{
+ PaError result = paNoError;
+ assert( component );
+
+ memset( component, 0, sizeof (PaOssStreamComponent) );
+
+ component->fd = fd;
+ component->devName = deviceName;
+ component->userChannelCount = parameters->channelCount;
+ component->userFormat = parameters->sampleFormat;
+ component->latency = parameters->suggestedLatency;
+ component->userInterleaved = !(parameters->sampleFormat & paNonInterleaved);
+
+ if( !callbackMode && !component->userInterleaved )
+ {
+ /* Pre-allocate non-interleaved user provided buffers */
+ PA_UNLESS( component->userBuffers = PaUtil_AllocateMemory( sizeof (void *) * component->userChannelCount ),
+ paInsufficientMemory );
+ }
+
+error:
+ return result;
+}
+
+static void PaOssStreamComponent_Terminate( PaOssStreamComponent *component )
+{
+ assert( component );
+
+ if( component->fd >= 0 )
+ close( component->fd );
+ if( component->buffer )
+ PaUtil_FreeMemory( component->buffer );
+
+ if( component->userBuffers )
+ PaUtil_FreeMemory( component->userBuffers );
+
+ PaUtil_FreeMemory( component );
+}
+
+static PaError ModifyBlocking( int fd, int blocking )
+{
+ PaError result = paNoError;
+ int fflags;
+
+ ENSURE_( fflags = fcntl( fd, F_GETFL ), paUnanticipatedHostError );
+
+ if( blocking )
+ fflags &= ~O_NONBLOCK;
+ else
+ fflags |= O_NONBLOCK;
+
+ ENSURE_( fcntl( fd, F_SETFL, fflags ), paUnanticipatedHostError );
+
+error:
+ return result;
+}
+
+static PaError OpenDevices( const char *idevName, const char *odevName, int *idev, int *odev )
+{
+ PaError result = paNoError;
+ int flags = O_NONBLOCK, duplex = 0;
+ int enableBits = 0;
+ *idev = *odev = -1;
+
+ if( idevName && odevName )
+ {
+ duplex = 1;
+ flags |= O_RDWR;
+ }
+ else if( idevName )
+ flags |= O_RDONLY;
+ else
+ flags |= O_WRONLY;
+
+ /* open first in nonblocking mode, in case it's busy...
+ * A: then unset the non-blocking attribute */
+ assert( flags & O_NONBLOCK );
+ if( idevName )
+ {
+ ENSURE_( *idev = open( idevName, flags ), paDeviceUnavailable );
+ PA_ENSURE( ModifyBlocking( *idev, 1 ) ); /* Blocking */
+
+ /* Initially disable */
+ enableBits = ~PCM_ENABLE_INPUT;
+ ENSURE_( ioctl( *idev, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
+ }
+ if( odevName )
+ {
+ if( !idevName )
+ {
+ ENSURE_( *odev = open( odevName, flags ), paDeviceUnavailable );
+ PA_ENSURE( ModifyBlocking( *odev, 1 ) ); /* Blocking */
+
+ /* Initially disable */
+ enableBits = ~PCM_ENABLE_OUTPUT;
+ ENSURE_( ioctl( *odev, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
+ }
+ else
+ {
+ ENSURE_( *odev = dup( *idev ), paUnanticipatedHostError );
+ }
+ }
+
+error:
+ return result;
+}
+
+static PaError PaOssStream_Initialize( PaOssStream *stream, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters,
+ PaStreamCallback callback, void *userData, PaStreamFlags streamFlags,
+ PaOSSHostApiRepresentation *ossApi )
+{
+ PaError result = paNoError;
+ int idev, odev;
+ PaUtilHostApiRepresentation *hostApi = &ossApi->inheritedHostApiRep;
+ const char *idevName = NULL, *odevName = NULL;
+
+ assert( stream );
+
+ memset( stream, 0, sizeof (PaOssStream) );
+ stream->isStopped = 1;
+
+ PA_ENSURE( PaUtil_InitializeThreading( &stream->threading ) );
+
+ if( inputParameters && outputParameters )
+ {
+ if( inputParameters->device == outputParameters->device )
+ stream->sharedDevice = 1;
+ }
+
+ if( inputParameters )
+ idevName = hostApi->deviceInfos[inputParameters->device]->name;
+ if( outputParameters )
+ odevName = hostApi->deviceInfos[outputParameters->device]->name;
+ PA_ENSURE( OpenDevices( idevName, odevName, &idev, &odev ) );
+ if( inputParameters )
+ {
+ PA_UNLESS( stream->capture = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory );
+ PA_ENSURE( PaOssStreamComponent_Initialize( stream->capture, inputParameters, callback != NULL, idev, idevName ) );
+ }
+ if( outputParameters )
+ {
+ PA_UNLESS( stream->playback = PaUtil_AllocateMemory( sizeof (PaOssStreamComponent) ), paInsufficientMemory );
+ PA_ENSURE( PaOssStreamComponent_Initialize( stream->playback, outputParameters, callback != NULL, odev, odevName ) );
+ }
+
+ if( callback != NULL )
+ {
+ PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+ &ossApi->callbackStreamInterface, callback, userData );
+ stream->callbackMode = 1;
+ }
+ else
+ {
+ PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+ &ossApi->blockingStreamInterface, callback, userData );
+ }
+
+ ENSURE_( sem_init( &stream->semaphore, 0, 0 ), paInternalError );
+
+error:
+ return result;
+}
+
+static void PaOssStream_Terminate( PaOssStream *stream )
+{
+ assert( stream );
+
+ PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+ PaUtil_TerminateThreading( &stream->threading );
+
+ if( stream->capture )
+ PaOssStreamComponent_Terminate( stream->capture );
+ if( stream->playback )
+ PaOssStreamComponent_Terminate( stream->playback );
+
+ sem_destroy( &stream->semaphore );
+
+ PaUtil_FreeMemory( stream );
+}
+
+/** Translate from PA format to OSS native.
+ *
+ */
+static PaError Pa2OssFormat( PaSampleFormat paFormat, int *ossFormat )
+{
+ switch( paFormat )
+ {
+ case paUInt8:
+ *ossFormat = AFMT_U8;
+ break;
+ case paInt8:
+ *ossFormat = AFMT_S8;
+ break;
+ case paInt16:
+ *ossFormat = AFMT_S16_NE;
+ break;
+ default:
+ return paInternalError; /* This shouldn't happen */
+ }
+
+ return paNoError;
+}
+
+/** Return the PA-compatible formats that this device can support.
+ *
+ */
+static PaError GetAvailableFormats( PaOssStreamComponent *component, PaSampleFormat *availableFormats )
+{
+ PaError result = paNoError;
+ int mask = 0;
+ PaSampleFormat frmts = 0;
+
+ ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETFMTS, &mask ), paUnanticipatedHostError );
+ if( mask & AFMT_U8 )
+ frmts |= paUInt8;
+ if( mask & AFMT_S8 )
+ frmts |= paInt8;
+ if( mask & AFMT_S16_NE )
+ frmts |= paInt16;
+ else
+ result = paSampleFormatNotSupported;
+
+ *availableFormats = frmts;
+
+error:
+ return result;
+}
+
+static unsigned int PaOssStreamComponent_FrameSize( PaOssStreamComponent *component )
+{
+ return Pa_GetSampleSize( component->hostFormat ) * component->hostChannelCount;
+}
+
+/** Buffer size in bytes.
+ *
+ */
+static unsigned long PaOssStreamComponent_BufferSize( PaOssStreamComponent *component )
+{
+ return PaOssStreamComponent_FrameSize( component ) * component->hostFrames * component->numBufs;
+}
+
+static int CalcHigherLogTwo( int n )
+{
+ int log2 = 0;
+ while( (1<<log2) < n ) log2++;
+ return log2;
+}
+
+static PaError PaOssStreamComponent_Configure( PaOssStreamComponent *component, double sampleRate, unsigned long framesPerBuffer,
+ StreamMode streamMode, PaOssStreamComponent *master )
+{
+ PaError result = paNoError;
+ int temp, nativeFormat;
+ int sr = (int)sampleRate;
+ PaSampleFormat availableFormats = 0, hostFormat = 0;
+ int chans = component->userChannelCount;
+ int frgmt;
+ int numBufs;
+ int bytesPerBuf;
+ unsigned long bufSz;
+ unsigned long fragSz;
+ audio_buf_info bufInfo;
+
+ /* We may have a situation where only one component (the master) is configured, if both point to the same device.
+ * In that case, the second component will copy settings from the other */
+ if( !master )
+ {
+ /* Aspect BufferSettings: If framesPerBuffer is unspecified we have to infer a suitable fragment size.
+ * The hardware need not respect the requested fragment size, so we may have to adapt.
+ */
+ if( framesPerBuffer == paFramesPerBufferUnspecified )
+ {
+ bufSz = (unsigned long)(component->latency * sampleRate);
+ fragSz = bufSz / 4;
+ }
+ else
+ {
+ fragSz = framesPerBuffer;
+ bufSz = (unsigned long)(component->latency * sampleRate) + fragSz; /* Latency + 1 buffer */
+ }
+
+ PA_ENSURE( GetAvailableFormats( component, &availableFormats ) );
+ hostFormat = PaUtil_SelectClosestAvailableFormat( availableFormats, component->userFormat );
+
+ /* OSS demands at least 2 buffers, and 16 bytes per buffer */
+ numBufs = (int)PA_MAX( bufSz / fragSz, 2 );
+ bytesPerBuf = PA_MAX( fragSz * Pa_GetSampleSize( hostFormat ) * chans, 16 );
+
+ /* The fragment parameters are encoded like this:
+ * Most significant byte: number of fragments
+ * Least significant byte: exponent of fragment size (i.e., for 256, 8)
+ */
+ frgmt = (numBufs << 16) + (CalcHigherLogTwo( bytesPerBuf ) & 0xffff);
+ ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFRAGMENT, &frgmt ), paUnanticipatedHostError );
+
+ /* A: according to the OSS programmer's guide parameters should be set in this order:
+ * format, channels, rate */
+
+ /* This format should be deemed good before we get this far */
+ PA_ENSURE( Pa2OssFormat( hostFormat, &temp ) );
+ nativeFormat = temp;
+ ENSURE_( ioctl( component->fd, SNDCTL_DSP_SETFMT, &temp ), paUnanticipatedHostError );
+ PA_UNLESS( temp == nativeFormat, paInternalError );
+
+ /* try to set the number of channels */
+ ENSURE_( ioctl( component->fd, SNDCTL_DSP_CHANNELS, &chans ), paSampleFormatNotSupported ); /* XXX: Should be paInvalidChannelCount? */
+ /* It's possible that the minimum number of host channels is greater than what the user requested */
+ PA_UNLESS( chans >= component->userChannelCount, paInvalidChannelCount );
+
+ /* try to set the sample rate */
+ ENSURE_( ioctl( component->fd, SNDCTL_DSP_SPEED, &sr ), paInvalidSampleRate );
+
+ /* reject if there's no sample rate within 1% of the one requested */
+ if( (fabs( sampleRate - sr ) / sampleRate) > 0.01 )
+ {
+ PA_DEBUG(("%s: Wanted %f, closest sample rate was %d\n", __FUNCTION__, sampleRate, sr ));
+ PA_ENSURE( paInvalidSampleRate );
+ }
+
+ ENSURE_( ioctl( component->fd, streamMode == StreamMode_In ? SNDCTL_DSP_GETISPACE : SNDCTL_DSP_GETOSPACE, &bufInfo ),
+ paUnanticipatedHostError );
+ component->numBufs = bufInfo.fragstotal;
+
+ /* This needs to be the last ioctl call before the first read/write, according to the OSS programmer's guide */
+ ENSURE_( ioctl( component->fd, SNDCTL_DSP_GETBLKSIZE, &bytesPerBuf ), paUnanticipatedHostError );
+
+ component->hostFrames = bytesPerBuf / Pa_GetSampleSize( hostFormat ) / chans;
+ component->hostChannelCount = chans;
+ component->hostFormat = hostFormat;
+ }
+ else
+ {
+ component->hostFormat = master->hostFormat;
+ component->hostFrames = master->hostFrames;
+ component->hostChannelCount = master->hostChannelCount;
+ component->numBufs = master->numBufs;
+ }
+
+ PA_UNLESS( component->buffer = PaUtil_AllocateMemory( PaOssStreamComponent_BufferSize( component ) ),
+ paInsufficientMemory );
+
+error:
+ return result;
+}
+
+static PaError PaOssStreamComponent_Read( PaOssStreamComponent *component, unsigned long *frames )
+{
+ PaError result = paNoError;
+ size_t len = *frames * PaOssStreamComponent_FrameSize( component );
+ ssize_t bytesRead;
+
+ ENSURE_( bytesRead = read( component->fd, component->buffer, len ), paUnanticipatedHostError );
+ *frames = bytesRead / PaOssStreamComponent_FrameSize( component );
+ /* TODO: Handle condition where number of frames read doesn't equal number of frames requested */
+
+error:
+ return result;
+}
+
+static PaError PaOssStreamComponent_Write( PaOssStreamComponent *component, unsigned long *frames )
+{
+ PaError result = paNoError;
+ size_t len = *frames * PaOssStreamComponent_FrameSize( component );
+ ssize_t bytesWritten;
+
+ ENSURE_( bytesWritten = write( component->fd, component->buffer, len ), paUnanticipatedHostError );
+ *frames = bytesWritten / PaOssStreamComponent_FrameSize( component );
+ /* TODO: Handle condition where number of frames written doesn't equal number of frames requested */
+
+error:
+ return result;
+}
+
+/** Configure the stream according to input/output parameters.
+ *
+ * Aspect StreamChannels: The minimum number of channels supported by the device may exceed that requested by
+ * the user, if so we'll record the actual number of host channels and adapt later.
+ */
+static PaError PaOssStream_Configure( PaOssStream *stream, double sampleRate, unsigned long framesPerBuffer,
+ double *inputLatency, double *outputLatency )
+{
+ PaError result = paNoError;
+ int duplex = stream->capture && stream->playback;
+ unsigned long framesPerHostBuffer = 0;
+
+ /* We should request full duplex first thing after opening the device */
+ if( duplex && stream->sharedDevice )
+ ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETDUPLEX, 0 ), paUnanticipatedHostError );
+
+ if( stream->capture )
+ {
+ PaOssStreamComponent *component = stream->capture;
+ PA_ENSURE( PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_In,
+ NULL ) );
+
+ assert( component->hostChannelCount > 0 );
+ assert( component->hostFrames > 0 );
+
+ *inputLatency = component->hostFrames * (component->numBufs - 1) / sampleRate;
+ }
+ if( stream->playback )
+ {
+ PaOssStreamComponent *component = stream->playback, *master = stream->sharedDevice ? stream->capture : NULL;
+ PA_ENSURE( PaOssStreamComponent_Configure( component, sampleRate, framesPerBuffer, StreamMode_Out,
+ master ) );
+
+ assert( component->hostChannelCount > 0 );
+ assert( component->hostFrames > 0 );
+
+ *outputLatency = component->hostFrames * (component->numBufs - 1) / sampleRate;
+ }
+
+ if( duplex )
+ framesPerHostBuffer = PA_MIN( stream->capture->hostFrames, stream->playback->hostFrames );
+ else if( stream->capture )
+ framesPerHostBuffer = stream->capture->hostFrames;
+ else if( stream->playback )
+ framesPerHostBuffer = stream->playback->hostFrames;
+
+ stream->framesPerHostBuffer = framesPerHostBuffer;
+ stream->pollTimeout = (int) ceil( 1e6 * framesPerHostBuffer / sampleRate ); /* Period in usecs, rounded up */
+
+ stream->sampleRate = stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+error:
+ return result;
+}
+
+/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
+
+/** Open a PA OSS stream.
+ *
+ * Aspect StreamChannels: The number of channels is specified per direction (in/out), and can differ between the
+ * two. However, OSS doesn't support separate configuration spaces for capture and playback so if both
+ * directions are the same device we will demand the same number of channels. The number of channels can range
+ * from 1 to the maximum supported by the device.
+ *
+ * Aspect BufferSettings: If framesPerBuffer != paFramesPerBufferUnspecified the number of frames per callback
+ * must reflect this, in addition the host latency per device should approximate the corresponding
+ * suggestedLatency. Based on these constraints we need to determine a number of frames per host buffer that
+ * both capture and playback can agree on (they can be different devices), the buffer processor can adapt
+ * between host and user buffer size, but the ratio should preferably be integral.
+ */
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+ PaStream** s,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate,
+ unsigned long framesPerBuffer,
+ PaStreamFlags streamFlags,
+ PaStreamCallback *streamCallback,
+ void *userData )
+{
+ PaError result = paNoError;
+ PaOSSHostApiRepresentation *ossHostApi = (PaOSSHostApiRepresentation*)hostApi;
+ PaOssStream *stream = NULL;
+ int inputChannelCount = 0, outputChannelCount = 0;
+ PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0, inputHostFormat = 0, outputHostFormat = 0;
+ const PaDeviceInfo *inputDeviceInfo = 0, *outputDeviceInfo = 0;
+ int bpInitialized = 0;
+ double inLatency = 0., outLatency = 0.;
+
+ /* validate platform specific flags */
+ if( (streamFlags & paPlatformSpecificFlags) != 0 )
+ return paInvalidFlag; /* unexpected platform specific flag */
+
+ if( inputParameters )
+ {
+ /* unless alternate device specification is supported, reject the use of
+ paUseHostApiSpecificDeviceSpecification */
+ inputDeviceInfo = hostApi->deviceInfos[inputParameters->device];
+ PA_ENSURE( ValidateParameters( inputParameters, inputDeviceInfo, StreamMode_In ) );
+
+ inputChannelCount = inputParameters->channelCount;
+ inputSampleFormat = inputParameters->sampleFormat;
+ }
+ if( outputParameters )
+ {
+ outputDeviceInfo = hostApi->deviceInfos[outputParameters->device];
+ PA_ENSURE( ValidateParameters( outputParameters, outputDeviceInfo, StreamMode_Out ) );
+
+ outputChannelCount = outputParameters->channelCount;
+ outputSampleFormat = outputParameters->sampleFormat;
+ }
+
+ /* Aspect StreamChannels: We currently demand that number of input and output channels are the same, if the same
+ * device is opened for both directions
+ */
+ if( inputChannelCount > 0 && outputChannelCount > 0 )
+ {
+ if( inputParameters->device == outputParameters->device )
+ {
+ if( inputParameters->channelCount != outputParameters->channelCount )
+ return paInvalidChannelCount;
+ }
+ }
+
+ /* allocate and do basic initialization of the stream structure */
+ PA_UNLESS( stream = (PaOssStream*)PaUtil_AllocateMemory( sizeof(PaOssStream) ), paInsufficientMemory );
+ PA_ENSURE( PaOssStream_Initialize( stream, inputParameters, outputParameters, streamCallback, userData, streamFlags, ossHostApi ) );
+
+ PA_ENSURE( PaOssStream_Configure( stream, sampleRate, framesPerBuffer, &inLatency, &outLatency ) );
+
+ PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+
+ if( inputParameters )
+ {
+ inputHostFormat = stream->capture->hostFormat;
+ stream->streamRepresentation.streamInfo.inputLatency = inLatency +
+ PaUtil_GetBufferProcessorInputLatency( &stream->bufferProcessor ) / sampleRate;
+ }
+ if( outputParameters )
+ {
+ outputHostFormat = stream->playback->hostFormat;
+ stream->streamRepresentation.streamInfo.outputLatency = outLatency +
+ PaUtil_GetBufferProcessorOutputLatency( &stream->bufferProcessor ) / sampleRate;
+ }
+
+ /* Initialize buffer processor with fixed host buffer size.
+ * Aspect StreamSampleFormat: Here we commit the user and host sample formats, PA infrastructure will
+ * convert between the two.
+ */
+ PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+ inputChannelCount, inputSampleFormat, inputHostFormat, outputChannelCount, outputSampleFormat,
+ outputHostFormat, sampleRate, streamFlags, framesPerBuffer, stream->framesPerHostBuffer,
+ paUtilFixedHostBufferSize, streamCallback, userData ) );
+ bpInitialized = 1;
+
+ *s = (PaStream*)stream;
+
+ return result;
+
+error:
+ if( bpInitialized )
+ PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+ if( stream )
+ PaOssStream_Terminate( stream );
+
+ return result;
+}
+
+/*! Poll on I/O filedescriptors.
+
+ Poll till we've determined there's data for read or write. In the full-duplex case,
+ we don't want to hang around forever waiting for either input or output frames, so
+ whenever we have a timed out filedescriptor we check if we're nearing under/overrun
+ for the other direction (critical limit set at one buffer). If so, we exit the waiting
+ state, and go on with what we got. We align the number of frames on a host buffer
+ boundary because it is possible that the buffer size differs for the two directions and
+ the host buffer size is a compromise between the two.
+ */
+static PaError PaOssStream_WaitForFrames( PaOssStream *stream, unsigned long *frames )
+{
+ PaError result = paNoError;
+ int pollPlayback = 0, pollCapture = 0;
+ int captureAvail = INT_MAX, playbackAvail = INT_MAX, commonAvail;
+ audio_buf_info bufInfo;
+ /* int ofs = 0, nfds = stream->nfds; */
+ fd_set readFds, writeFds;
+ int nfds = 0;
+ struct timeval selectTimeval = {0, 0};
+ unsigned long timeout = stream->pollTimeout; /* In usecs */
+ int captureFd = -1, playbackFd = -1;
+
+ assert( stream );
+ assert( frames );
+
+ if( stream->capture )
+ {
+ pollCapture = 1;
+ captureFd = stream->capture->fd;
+ /* stream->capture->pfd->events = POLLIN; */
+ }
+ if( stream->playback )
+ {
+ pollPlayback = 1;
+ playbackFd = stream->playback->fd;
+ /* stream->playback->pfd->events = POLLOUT; */
+ }
+
+ FD_ZERO( &readFds );
+ FD_ZERO( &writeFds );
+
+ while( pollPlayback || pollCapture )
+ {
+ pthread_testcancel();
+
+ /* select may modify the timeout parameter */
+ selectTimeval.tv_usec = timeout;
+ nfds = 0;
+
+ if( pollCapture )
+ {
+ FD_SET( captureFd, &readFds );
+ nfds = captureFd + 1;
+ }
+ if( pollPlayback )
+ {
+ FD_SET( playbackFd, &writeFds );
+ nfds = PA_MAX( nfds, playbackFd + 1 );
+ }
+ ENSURE_( select( nfds, &readFds, &writeFds, NULL, &selectTimeval ), paUnanticipatedHostError );
+ /*
+ if( poll( stream->pfds + ofs, nfds, stream->pollTimeout ) < 0 )
+ {
+
+ ENSURE_( -1, paUnanticipatedHostError );
+ }
+ */
+ pthread_testcancel();
+
+ if( pollCapture )
+ {
+ if( FD_ISSET( captureFd, &readFds ) )
+ {
+ FD_CLR( captureFd, &readFds );
+ pollCapture = 0;
+ }
+ /*
+ if( stream->capture->pfd->revents & POLLIN )
+ {
+ --nfds;
+ ++ofs;
+ pollCapture = 0;
+ }
+ */
+ else if( stream->playback ) /* Timed out, go on with playback? */
+ {
+ /*PA_DEBUG(( "%s: Trying to poll again for capture frames, pollTimeout: %d\n",
+ __FUNCTION__, stream->pollTimeout ));*/
+ }
+ }
+ if( pollPlayback )
+ {
+ if( FD_ISSET( playbackFd, &writeFds ) )
+ {
+ FD_CLR( playbackFd, &writeFds );
+ pollPlayback = 0;
+ }
+ /*
+ if( stream->playback->pfd->revents & POLLOUT )
+ {
+ --nfds;
+ pollPlayback = 0;
+ }
+ */
+ else if( stream->capture ) /* Timed out, go on with capture? */
+ {
+ /*PA_DEBUG(( "%s: Trying to poll again for playback frames, pollTimeout: %d\n\n",
+ __FUNCTION__, stream->pollTimeout ));*/
+ }
+ }
+ }
+
+ if( stream->capture )
+ {
+ ENSURE_( ioctl( captureFd, SNDCTL_DSP_GETISPACE, &bufInfo ), paUnanticipatedHostError );
+ captureAvail = bufInfo.fragments * stream->capture->hostFrames;
+ if( !captureAvail )
+ PA_DEBUG(( "%s: captureAvail: 0\n", __FUNCTION__ ));
+
+ captureAvail = captureAvail == 0 ? INT_MAX : captureAvail; /* Disregard if zero */
+ }
+ if( stream->playback )
+ {
+ ENSURE_( ioctl( playbackFd, SNDCTL_DSP_GETOSPACE, &bufInfo ), paUnanticipatedHostError );
+ playbackAvail = bufInfo.fragments * stream->playback->hostFrames;
+ if( !playbackAvail )
+ {
+ PA_DEBUG(( "%s: playbackAvail: 0\n", __FUNCTION__ ));
+ }
+
+ playbackAvail = playbackAvail == 0 ? INT_MAX : playbackAvail; /* Disregard if zero */
+ }
+
+ commonAvail = PA_MIN( captureAvail, playbackAvail );
+ if( commonAvail == INT_MAX )
+ commonAvail = 0;
+ commonAvail -= commonAvail % stream->framesPerHostBuffer;
+
+ assert( commonAvail != INT_MAX );
+ assert( commonAvail >= 0 );
+ *frames = commonAvail;
+
+error:
+ return result;
+}
+
+/** Prepare stream for capture/playback.
+ *
+ * In order to synchronize capture and playback properly we use the SETTRIGGER command.
+ */
+static PaError PaOssStream_Prepare( PaOssStream *stream )
+{
+ PaError result = paNoError;
+ int enableBits = 0;
+
+ if( stream->triggered )
+ return result;
+
+ if( stream->playback )
+ {
+ size_t bufSz = PaOssStreamComponent_BufferSize( stream->playback );
+ memset( stream->playback->buffer, 0, bufSz );
+
+ /* Looks like we have to turn off blocking before we try this, but if we don't fill the buffer
+ * OSS will complain. */
+ PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) );
+ while (1)
+ {
+ if( write( stream->playback->fd, stream->playback->buffer, bufSz ) < 0 )
+ break;
+ }
+ PA_ENSURE( ModifyBlocking( stream->playback->fd, 1 ) );
+ }
+
+ if( stream->sharedDevice )
+ {
+ enableBits = PCM_ENABLE_INPUT | PCM_ENABLE_OUTPUT;
+ ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
+ }
+ else
+ {
+ if( stream->capture )
+ {
+ enableBits = PCM_ENABLE_INPUT;
+ ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
+ }
+ if( stream->playback )
+ {
+ enableBits = PCM_ENABLE_OUTPUT;
+ ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_SETTRIGGER, &enableBits ), paUnanticipatedHostError );
+ }
+ }
+
+ /* Ok, we have triggered the stream */
+ stream->triggered = 1;
+
+error:
+ return result;
+}
+
+/** Stop audio processing
+ *
+ */
+static PaError PaOssStream_Stop( PaOssStream *stream, int abort )
+{
+ PaError result = paNoError;
+
+ /* Looks like the only safe way to stop audio without reopening the device is SNDCTL_DSP_POST.
+ * Also disable capture/playback till the stream is started again */
+ if( stream->capture )
+ {
+ ENSURE_( ioctl( stream->capture->fd, SNDCTL_DSP_POST, 0 ), paUnanticipatedHostError );
+ }
+ if( stream->playback && !stream->sharedDevice )
+ {
+ ENSURE_( ioctl( stream->playback->fd, SNDCTL_DSP_POST, 0 ), paUnanticipatedHostError );
+ }
+
+error:
+ return result;
+}
+
+/** Clean up after thread exit.
+ *
+ * Aspect StreamState: If the user has registered a streamFinishedCallback it will be called here
+ */
+static void OnExit( void *data )
+{
+ PaOssStream *stream = (PaOssStream *) data;
+ assert( data );
+
+ PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
+
+ PaOssStream_Stop( stream, stream->callbackAbort );
+
+ PA_DEBUG(( "OnExit: Stoppage\n" ));
+
+ /* Eventually notify user all buffers have played */
+ if( stream->streamRepresentation.streamFinishedCallback )
+ stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+
+ stream->callbackAbort = 0; /* Clear state */
+ stream->isActive = 0;
+}
+
+static PaError SetUpBuffers( PaOssStream *stream, unsigned long framesAvail )
+{
+ PaError result = paNoError;
+
+ if( stream->capture )
+ {
+ PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer,
+ stream->capture->hostChannelCount );
+ PaUtil_SetInputFrameCount( &stream->bufferProcessor, framesAvail );
+ }
+ if( stream->playback )
+ {
+ PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer,
+ stream->playback->hostChannelCount );
+ PaUtil_SetOutputFrameCount( &stream->bufferProcessor, framesAvail );
+ }
+
+ return result;
+}
+
+/** Thread procedure for callback processing.
+ *
+ * Aspect StreamState: StartStream will wait on this to initiate audio processing, useful in case the
+ * callback should be used for buffer priming. When the stream is cancelled a separate function will
+ * take care of the transition to the Callback Finished state (the stream isn't considered Stopped
+ * before StopStream() or AbortStream() are called).
+ */
+static void *PaOSS_AudioThreadProc( void *userData )
+{
+ PaError result = paNoError;
+ PaOssStream *stream = (PaOssStream*)userData;
+ unsigned long framesAvail = 0, framesProcessed = 0;
+ int callbackResult = paContinue;
+ int triggered = stream->triggered; /* See if SNDCTL_DSP_TRIGGER has been issued already */
+ int initiateProcessing = triggered; /* Already triggered? */
+ PaStreamCallbackFlags cbFlags = 0; /* We might want to keep state across iterations */
+ PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /* TODO: IMPLEMENT ME */
+
+ /*
+#if ( SOUND_VERSION > 0x030904 )
+ audio_errinfo errinfo;
+#endif
+*/
+
+ assert( stream );
+
+ pthread_cleanup_push( &OnExit, stream ); /* Execute OnExit when exiting */
+
+ /* The first time the stream is started we use SNDCTL_DSP_TRIGGER to accurately start capture and
+ * playback in sync, when the stream is restarted after being stopped we simply start by reading/
+ * writing.
+ */
+ PA_ENSURE( PaOssStream_Prepare( stream ) );
+
+ /* If we are to initiate processing implicitly by reading/writing data, we start off in blocking mode */
+ if( initiateProcessing )
+ {
+ /* Make sure devices are in blocking mode */
+ if( stream->capture )
+ ModifyBlocking( stream->capture->fd, 1 );
+ if( stream->playback )
+ ModifyBlocking( stream->playback->fd, 1 );
+ }
+
+ while( 1 )
+ {
+ pthread_testcancel();
+
+ if( stream->callbackStop && callbackResult == paContinue )
+ {
+ PA_DEBUG(( "Setting callbackResult to paComplete\n" ));
+ callbackResult = paComplete;
+ }
+
+ /* Aspect StreamState: Because of the messy OSS scheme we can't explicitly trigger device start unless
+ * the stream has been recently started, we will have to go right ahead and read/write in blocking
+ * fashion to trigger operation. Therefore we begin with processing one host buffer before we switch
+ * to non-blocking mode.
+ */
+ if( !initiateProcessing )
+ {
+ /* Wait on available frames */
+ PA_ENSURE( PaOssStream_WaitForFrames( stream, &framesAvail ) );
+ assert( framesAvail % stream->framesPerHostBuffer == 0 );
+ }
+ else
+ {
+ framesAvail = stream->framesPerHostBuffer;
+ }
+
+ while( framesAvail > 0 )
+ {
+ unsigned long frames = framesAvail;
+
+ pthread_testcancel();
+
+ PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+
+ /* Read data */
+ if ( stream->capture )
+ {
+ PA_ENSURE( PaOssStreamComponent_Read( stream->capture, &frames ) );
+ if( frames < framesAvail )
+ {
+ PA_DEBUG(( "Read %lu less frames than requested\n", framesAvail - frames ));
+ framesAvail = frames;
+ }
+ }
+
+#if ( SOUND_VERSION >= 0x030904 )
+ /*
+ Check with OSS to see if there have been any under/overruns
+ since last time we checked.
+ */
+ /*
+ if( ioctl( stream->deviceHandle, SNDCTL_DSP_GETERROR, &errinfo ) >= 0 )
+ {
+ if( errinfo.play_underruns )
+ cbFlags |= paOutputUnderflow ;
+ if( errinfo.record_underruns )
+ cbFlags |= paInputUnderflow ;
+ }
+ else
+ PA_DEBUG(( "SNDCTL_DSP_GETERROR command failed: %s\n", strerror( errno ) ));
+ */
+#endif
+
+ PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo,
+ cbFlags );
+ cbFlags = 0;
+ PA_ENSURE( SetUpBuffers( stream, framesAvail ) );
+
+ framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor,
+ &callbackResult );
+ assert( framesProcessed == framesAvail );
+ PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
+
+ if ( stream->playback )
+ {
+ frames = framesAvail;
+
+ PA_ENSURE( PaOssStreamComponent_Write( stream->playback, &frames ) );
+ if( frames < framesAvail )
+ {
+ /* TODO: handle bytesWritten != bytesRequested (slippage?) */
+ PA_DEBUG(( "Wrote %lu less frames than requested\n", framesAvail - frames ));
+ }
+ }
+
+ framesAvail -= framesProcessed;
+ stream->framesProcessed += framesProcessed;
+
+ if( callbackResult != paContinue )
+ break;
+ }
+
+ if( initiateProcessing || !triggered )
+ {
+ /* Non-blocking */
+ if( stream->capture )
+ PA_ENSURE( ModifyBlocking( stream->capture->fd, 0 ) );
+ if( stream->playback && !stream->sharedDevice )
+ PA_ENSURE( ModifyBlocking( stream->playback->fd, 0 ) );
+
+ initiateProcessing = 0;
+ sem_post( &stream->semaphore );
+ }
+
+ if( callbackResult != paContinue )
+ {
+ stream->callbackAbort = callbackResult == paAbort;
+ if( stream->callbackAbort || PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) )
+ break;
+ }
+ }
+
+ pthread_cleanup_pop( 1 );
+
+error:
+ pthread_exit( NULL );
+}
+
+/** Close the stream.
+ *
+ */
+static PaError CloseStream( PaStream* s )
+{
+ PaError result = paNoError;
+ PaOssStream *stream = (PaOssStream*)s;
+
+ assert( stream );
+
+ PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+ PaOssStream_Terminate( stream );
+
+ return result;
+}
+
+/** Start the stream.
+ *
+ * Aspect StreamState: After returning, the stream shall be in the Active state, implying that an eventual
+ * callback will be repeatedly called in a separate thread. If a separate thread is started this function
+ * will block untill it has started processing audio, otherwise audio processing is started directly.
+ */
+static PaError StartStream( PaStream *s )
+{
+ PaError result = paNoError;
+ PaOssStream *stream = (PaOssStream*)s;
+
+ stream->isActive = 1;
+ stream->isStopped = 0;
+ stream->lastPosPtr = 0;
+ stream->lastStreamBytes = 0;
+ stream->framesProcessed = 0;
+
+ /* only use the thread for callback streams */
+ if( stream->bufferProcessor.streamCallback )
+ {
+ PA_ENSURE( PaUtil_StartThreading( &stream->threading, &PaOSS_AudioThreadProc, stream ) );
+ sem_wait( &stream->semaphore );
+ }
+ else
+ PA_ENSURE( PaOssStream_Prepare( stream ) );
+
+error:
+ return result;
+}
+
+static PaError RealStop( PaOssStream *stream, int abort )
+{
+ PaError result = paNoError;
+
+ if( stream->callbackMode )
+ {
+ if( abort )
+ stream->callbackAbort = 1;
+ else
+ stream->callbackStop = 1;
+
+ PA_ENSURE( PaUtil_CancelThreading( &stream->threading, !abort, NULL ) );
+
+ stream->callbackStop = stream->callbackAbort = 0;
+ }
+ else
+ PA_ENSURE( PaOssStream_Stop( stream, abort ) );
+
+ stream->isStopped = 1;
+
+error:
+ return result;
+}
+
+/** Stop the stream.
+ *
+ * Aspect StreamState: This will cause the stream to transition to the Stopped state, playing all enqueued
+ * buffers.
+ */
+static PaError StopStream( PaStream *s )
+{
+ return RealStop( (PaOssStream *)s, 0 );
+}
+
+/** Abort the stream.
+ *
+ * Aspect StreamState: This will cause the stream to transition to the Stopped state, discarding all enqueued
+ * buffers. Note that the buffers are not currently correctly discarded, this is difficult without closing
+ * the OSS device.
+ */
+static PaError AbortStream( PaStream *s )
+{
+ return RealStop( (PaOssStream *)s, 1 );
+}
+
+/** Is the stream in the Stopped state.
+ *
+ */
+static PaError IsStreamStopped( PaStream *s )
+{
+ PaOssStream *stream = (PaOssStream*)s;
+
+ return (stream->isStopped);
+}
+
+/** Is the stream in the Active state.
+ *
+ */
+static PaError IsStreamActive( PaStream *s )
+{
+ PaOssStream *stream = (PaOssStream*)s;
+
+ return (stream->isActive);
+}
+
+static PaTime GetStreamTime( PaStream *s )
+{
+ PaOssStream *stream = (PaOssStream*)s;
+ count_info info;
+ int delta;
+
+ if( stream->playback ) {
+ if( ioctl( stream->playback->fd, SNDCTL_DSP_GETOPTR, &info) == 0 ) {
+ delta = ( info.bytes - stream->lastPosPtr ) /* & 0x000FFFFF*/;
+ return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->playback ) / stream->sampleRate;
+ }
+ }
+ else {
+ if (ioctl( stream->capture->fd, SNDCTL_DSP_GETIPTR, &info) == 0) {
+ delta = (info.bytes - stream->lastPosPtr) /*& 0x000FFFFF*/;
+ return (float)(stream->lastStreamBytes + delta) / PaOssStreamComponent_FrameSize( stream->capture ) / stream->sampleRate;
+ }
+ }
+
+ /* the ioctl failed, but we can still give a coarse estimate */
+
+ return stream->framesProcessed / stream->sampleRate;
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+ PaOssStream *stream = (PaOssStream*)s;
+
+ return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+
+/*
+ As separate stream interfaces are used for blocking and callback
+ streams, the following functions can be guaranteed to only be called
+ for blocking streams.
+*/
+
+
+static PaError ReadStream( PaStream* s,
+ void *buffer,
+ unsigned long frames )
+{
+ PaOssStream *stream = (PaOssStream*)s;
+ int bytesRequested, bytesRead;
+ unsigned long framesRequested;
+ void *userBuffer;
+
+ /* If user input is non-interleaved, PaUtil_CopyInput will manipulate the channel pointers,
+ * so we copy the user provided pointers */
+ if( stream->bufferProcessor.userInputIsInterleaved )
+ userBuffer = buffer;
+ else /* Copy channels into local array */
+ {
+ userBuffer = stream->capture->userBuffers;
+ memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->capture->userChannelCount );
+ }
+
+ while( frames )
+ {
+ framesRequested = PA_MIN( frames, stream->capture->hostFrames );
+
+ bytesRequested = framesRequested * PaOssStreamComponent_FrameSize( stream->capture );
+ bytesRead = read( stream->capture->fd, stream->capture->buffer, bytesRequested );
+ if ( bytesRequested != bytesRead )
+ return paUnanticipatedHostError;
+
+ PaUtil_SetInputFrameCount( &stream->bufferProcessor, stream->capture->hostFrames );
+ PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, 0, stream->capture->buffer, stream->capture->hostChannelCount );
+ PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, framesRequested );
+ frames -= framesRequested;
+ }
+ return paNoError;
+}
+
+
+static PaError WriteStream( PaStream *s, const void *buffer, unsigned long frames )
+{
+ PaOssStream *stream = (PaOssStream*)s;
+ int bytesRequested, bytesWritten;
+ unsigned long framesConverted;
+ const void *userBuffer;
+
+ /* If user output is non-interleaved, PaUtil_CopyOutput will manipulate the channel pointers,
+ * so we copy the user provided pointers */
+ if( stream->bufferProcessor.userOutputIsInterleaved )
+ userBuffer = buffer;
+ else
+ {
+ /* Copy channels into local array */
+ userBuffer = stream->playback->userBuffers;
+ memcpy( (void *)userBuffer, buffer, sizeof (void *) * stream->playback->userChannelCount );
+ }
+
+ while( frames )
+ {
+ PaUtil_SetOutputFrameCount( &stream->bufferProcessor, stream->playback->hostFrames );
+ PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, 0, stream->playback->buffer, stream->playback->hostChannelCount );
+
+ framesConverted = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, frames );
+ frames -= framesConverted;
+
+ bytesRequested = framesConverted * PaOssStreamComponent_FrameSize( stream->playback );
+ bytesWritten = write( stream->playback->fd, stream->playback->buffer, bytesRequested );
+
+ if ( bytesRequested != bytesWritten )
+ return paUnanticipatedHostError;
+ }
+ return paNoError;
+}
+
+
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+ PaOssStream *stream = (PaOssStream*)s;
+ audio_buf_info info;
+
+ if( ioctl( stream->capture->fd, SNDCTL_DSP_GETISPACE, &info ) < 0 )
+ return paUnanticipatedHostError;
+ return info.fragments * stream->capture->hostFrames;
+}
+
+
+/* TODO: Compute number of allocated bytes somewhere else, can we use ODELAY with capture */
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+ PaOssStream *stream = (PaOssStream*)s;
+ int delay = 0;
+
+ if( ioctl( stream->playback->fd, SNDCTL_DSP_GETODELAY, &delay ) < 0 )
+ return paUnanticipatedHostError;
+
+ return (PaOssStreamComponent_BufferSize( stream->playback ) - delay) / PaOssStreamComponent_FrameSize( stream->playback );
+}
+
diff --git a/pd/portaudio/src/hostapi/oss/recplay.c b/pd/portaudio/src/hostapi/oss/recplay.c
new file mode 100644
index 00000000..9d4c78cf
--- /dev/null
+++ b/pd/portaudio/src/hostapi/oss/recplay.c
@@ -0,0 +1,114 @@
+/*
+ * recplay.c
+ * Phil Burk
+ * Minimal record and playback test.
+ *
+ */
+#include <stdio.h>
+#include <unistd.h>
+#include <stdlib.h>
+#ifndef __STDC__
+/* #include <getopt.h> */
+#endif /* __STDC__ */
+#include <fcntl.h>
+#ifdef __STDC__
+#include <string.h>
+#else /* __STDC__ */
+#include <strings.h>
+#endif /* __STDC__ */
+#include <sys/soundcard.h>
+
+#define NUM_BYTES (64*1024)
+#define BLOCK_SIZE (4*1024)
+
+#define AUDIO "/dev/dsp"
+
+char buffer[NUM_BYTES];
+
+int audioDev = 0;
+
+main (int argc, char *argv[])
+{
+ int numLeft;
+ char *ptr;
+ int num;
+ int samplesize;
+
+ /********** RECORD ********************/
+ /* Open audio device. */
+ audioDev = open (AUDIO, O_RDONLY, 0);
+ if (audioDev == -1)
+ {
+ perror (AUDIO);
+ exit (-1);
+ }
+
+ /* Set to 16 bit samples. */
+ samplesize = 16;
+ ioctl(audioDev, SNDCTL_DSP_SAMPLESIZE, &samplesize);
+ if (samplesize != 16)
+ {
+ perror("Unable to set the sample size.");
+ exit(-1);
+ }
+
+ /* Record in blocks */
+ printf("Begin recording.\n");
+ numLeft = NUM_BYTES;
+ ptr = buffer;
+ while( numLeft >= BLOCK_SIZE )
+ {
+ if ( (num = read (audioDev, ptr, BLOCK_SIZE)) < 0 )
+ {
+ perror (AUDIO);
+ exit (-1);
+ }
+ else
+ {
+ printf("Read %d bytes\n", num);
+ ptr += num;
+ numLeft -= num;
+ }
+ }
+
+ close( audioDev );
+
+ /********** PLAYBACK ********************/
+ /* Open audio device for writing. */
+ audioDev = open (AUDIO, O_WRONLY, 0);
+ if (audioDev == -1)
+ {
+ perror (AUDIO);
+ exit (-1);
+ }
+
+ /* Set to 16 bit samples. */
+ samplesize = 16;
+ ioctl(audioDev, SNDCTL_DSP_SAMPLESIZE, &samplesize);
+ if (samplesize != 16)
+ {
+ perror("Unable to set the sample size.");
+ exit(-1);
+ }
+
+ /* Play in blocks */
+ printf("Begin playing.\n");
+ numLeft = NUM_BYTES;
+ ptr = buffer;
+ while( numLeft >= BLOCK_SIZE )
+ {
+ if ( (num = write (audioDev, ptr, BLOCK_SIZE)) < 0 )
+ {
+ perror (AUDIO);
+ exit (-1);
+ }
+ else
+ {
+ printf("Wrote %d bytes\n", num);
+ ptr += num;
+ numLeft -= num;
+ }
+ }
+
+ close( audioDev );
+}
diff --git a/pd/portaudio/src/hostapi/wmme/pa_win_wmme.c b/pd/portaudio/src/hostapi/wmme/pa_win_wmme.c
new file mode 100644
index 00000000..77ad3703
--- /dev/null
+++ b/pd/portaudio/src/hostapi/wmme/pa_win_wmme.c
@@ -0,0 +1,3646 @@
+/*
+ * $Id: pa_win_wmme.c,v 1.1 2007-08-18 23:49:33 millerpuckette Exp $
+ * pa_win_wmme.c
+ * Implementation of PortAudio for Windows MultiMedia Extensions (WMME)
+ *
+ * PortAudio Portable Real-Time Audio Library
+ * Latest Version at: http://www.portaudio.com
+ *
+ * Authors: Ross Bencina and Phil Burk
+ * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/* Modification History:
+ PLB = Phil Burk
+ JM = Julien Maillard
+ RDB = Ross Bencina
+ PLB20010402 - sDevicePtrs now allocates based on sizeof(pointer)
+ PLB20010413 - check for excessive numbers of channels
+ PLB20010422 - apply Mike Berry's changes for CodeWarrior on PC
+ including conditional inclusion of memory.h,
+ and explicit typecasting on memory allocation
+ PLB20010802 - use GlobalAlloc for sDevicesPtr instead of PaHost_AllocFastMemory
+ PLB20010816 - pass process instead of thread to SetPriorityClass()
+ PLB20010927 - use number of frames instead of real-time for CPULoad calculation.
+ JM20020118 - prevent hung thread when buffers underflow.
+ PLB20020321 - detect Win XP versus NT, 9x; fix DBUG typo; removed init of CurrentCount
+ RDB20020411 - various renaming cleanups, factored streamData alloc and cpu usage init
+ RDB20020417 - stopped counting WAVE_MAPPER when there were no real devices
+ refactoring, renaming and fixed a few edge case bugs
+ RDB20020531 - converted to V19 framework
+ ** NOTE maintanance history is now stored in CVS **
+*/
+
+/** @file
+ @ingroup hostaip_src
+
+ @todo Fix buffer catch up code, can sometimes get stuck (perhaps fixed now,
+ needs to be reviewed and tested.)
+
+ @todo implement paInputUnderflow, paOutputOverflow streamCallback statusFlags, paNeverDropInput.
+
+ @todo BUG: PA_MME_SET_LAST_WAVEIN/OUT_ERROR is used in functions which may
+ be called asynchronously from the callback thread. this is bad.
+
+ @todo implement inputBufferAdcTime in callback thread
+
+ @todo review/fix error recovery and cleanup in marked functions
+
+ @todo implement timeInfo for stream priming
+
+ @todo handle the case where the callback returns paAbort or paComplete during stream priming.
+
+ @todo review input overflow and output underflow handling in ReadStream and WriteStream
+
+Non-critical stuff for the future:
+
+ @todo Investigate supporting host buffer formats > 16 bits
+
+ @todo define UNICODE and _UNICODE in the project settings and see what breaks
+
+*/
+
+/*
+ How it works:
+
+ For both callback and blocking read/write streams we open the MME devices
+ in CALLBACK_EVENT mode. In this mode, MME signals an Event object whenever
+ it has finished with a buffer (either filled it for input, or played it
+ for output). Where necessary we block waiting for Event objects using
+ WaitMultipleObjects().
+
+ When implementing a PA callback stream, we set up a high priority thread
+ which waits on the MME buffer Events and drains/fills the buffers when
+ they are ready.
+
+ When implementing a PA blocking read/write stream, we simply wait on these
+ Events (when necessary) inside the ReadStream() and WriteStream() functions.
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <math.h>
+#include <windows.h>
+#include <mmsystem.h>
+#ifndef UNDER_CE
+#include <process.h>
+#endif
+#include <assert.h>
+/* PLB20010422 - "memory.h" doesn't work on CodeWarrior for PC. Thanks Mike Berry for the mod. */
+#ifndef __MWERKS__
+#include <malloc.h>
+#include <memory.h>
+#endif /* __MWERKS__ */
+
+#include "portaudio.h"
+#include "pa_trace.h"
+#include "pa_util.h"
+#include "pa_allocation.h"
+#include "pa_hostapi.h"
+#include "pa_stream.h"
+#include "pa_cpuload.h"
+#include "pa_process.h"
+#include "pa_debugprint.h"
+
+#include "pa_win_wmme.h"
+
+#if (defined(UNDER_CE))
+#pragma comment(lib, "Coredll.lib")
+#elif (defined(WIN32) && (defined(_MSC_VER) && (_MSC_VER >= 1200))) /* MSC version 6 and above */
+#pragma comment(lib, "winmm.lib")
+#endif
+
+/*
+ provided in newer platform sdks
+ */
+#ifndef DWORD_PTR
+#define DWORD_PTR DWORD
+#endif
+
+/************************************************* Constants ********/
+
+#define PA_MME_USE_HIGH_DEFAULT_LATENCY_ (0) /* For debugging glitches. */
+
+#if PA_MME_USE_HIGH_DEFAULT_LATENCY_
+ #define PA_MME_WIN_9X_DEFAULT_LATENCY_ (0.4)
+ #define PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_ (4)
+ #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ (4)
+ #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_ (4)
+ #define PA_MME_MIN_HOST_BUFFER_FRAMES_WHEN_UNSPECIFIED_ (16)
+ #define PA_MME_MAX_HOST_BUFFER_SECS_ (0.3) /* Do not exceed unless user buffer exceeds */
+ #define PA_MME_MAX_HOST_BUFFER_BYTES_ (32 * 1024) /* Has precedence over PA_MME_MAX_HOST_BUFFER_SECS_, some drivers are known to crash with buffer sizes > 32k */
+#else
+ #define PA_MME_WIN_9X_DEFAULT_LATENCY_ (0.2)
+ #define PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_ (2)
+ #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ (3)
+ #define PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_ (2)
+ #define PA_MME_MIN_HOST_BUFFER_FRAMES_WHEN_UNSPECIFIED_ (16)
+ #define PA_MME_MAX_HOST_BUFFER_SECS_ (0.1) /* Do not exceed unless user buffer exceeds */
+ #define PA_MME_MAX_HOST_BUFFER_BYTES_ (32 * 1024) /* Has precedence over PA_MME_MAX_HOST_BUFFER_SECS_, some drivers are known to crash with buffer sizes > 32k */
+#endif
+
+/* Use higher latency for NT because it is even worse at real-time
+ operation than Win9x.
+*/
+#define PA_MME_WIN_NT_DEFAULT_LATENCY_ (PA_MME_WIN_9X_DEFAULT_LATENCY_ * 2)
+#define PA_MME_WIN_WDM_DEFAULT_LATENCY_ (PA_MME_WIN_9X_DEFAULT_LATENCY_)
+
+
+#define PA_MME_MIN_TIMEOUT_MSEC_ (1000)
+
+static const char constInputMapperSuffix_[] = " - Input";
+static const char constOutputMapperSuffix_[] = " - Output";
+
+/********************************************************************/
+
+typedef struct PaWinMmeStream PaWinMmeStream; /* forward declaration */
+
+/* prototypes for functions declared in this file */
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+ PaStream** stream,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate,
+ unsigned long framesPerBuffer,
+ PaStreamFlags streamFlags,
+ PaStreamCallback *streamCallback,
+ void *userData );
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate );
+static PaError CloseStream( PaStream* stream );
+static PaError StartStream( PaStream *stream );
+static PaError StopStream( PaStream *stream );
+static PaError AbortStream( PaStream *stream );
+static PaError IsStreamStopped( PaStream *s );
+static PaError IsStreamActive( PaStream *stream );
+static PaTime GetStreamTime( PaStream *stream );
+static double GetStreamCpuLoad( PaStream* stream );
+static PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames );
+static PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames );
+static signed long GetStreamReadAvailable( PaStream* stream );
+static signed long GetStreamWriteAvailable( PaStream* stream );
+
+
+/* macros for setting last host error information */
+
+#ifdef UNICODE
+
+#define PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ) \
+ { \
+ wchar_t mmeErrorTextWide[ MAXERRORLENGTH ]; \
+ char mmeErrorText[ MAXERRORLENGTH ]; \
+ waveInGetErrorText( mmresult, mmeErrorTextWide, MAXERRORLENGTH ); \
+ WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR,\
+ mmeErrorTextWide, -1, mmeErrorText, MAXERRORLENGTH, NULL, NULL ); \
+ PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText ); \
+ }
+
+#define PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ) \
+ { \
+ wchar_t mmeErrorTextWide[ MAXERRORLENGTH ]; \
+ char mmeErrorText[ MAXERRORLENGTH ]; \
+ waveOutGetErrorText( mmresult, mmeErrorTextWide, MAXERRORLENGTH ); \
+ WideCharToMultiByte( CP_ACP, WC_COMPOSITECHECK | WC_DEFAULTCHAR,\
+ mmeErrorTextWide, -1, mmeErrorText, MAXERRORLENGTH, NULL, NULL ); \
+ PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText ); \
+ }
+
+#else /* !UNICODE */
+
+#define PA_MME_SET_LAST_WAVEIN_ERROR( mmresult ) \
+ { \
+ char mmeErrorText[ MAXERRORLENGTH ]; \
+ waveInGetErrorText( mmresult, mmeErrorText, MAXERRORLENGTH ); \
+ PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText ); \
+ }
+
+#define PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult ) \
+ { \
+ char mmeErrorText[ MAXERRORLENGTH ]; \
+ waveOutGetErrorText( mmresult, mmeErrorText, MAXERRORLENGTH ); \
+ PaUtil_SetLastHostErrorInfo( paMME, mmresult, mmeErrorText ); \
+ }
+
+#endif /* UNICODE */
+
+
+static void PaMme_SetLastSystemError( DWORD errorCode )
+{
+ char *lpMsgBuf;
+ FormatMessage(
+ FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
+ NULL,
+ errorCode,
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPTSTR) &lpMsgBuf,
+ 0,
+ NULL
+ );
+ PaUtil_SetLastHostErrorInfo( paMME, errorCode, lpMsgBuf );
+ LocalFree( lpMsgBuf );
+}
+
+#define PA_MME_SET_LAST_SYSTEM_ERROR( errorCode ) \
+ PaMme_SetLastSystemError( errorCode )
+
+
+/* PaError returning wrappers for some commonly used win32 functions
+ note that we allow passing a null ptr to have no effect.
+*/
+
+static PaError CreateEventWithPaError( HANDLE *handle,
+ LPSECURITY_ATTRIBUTES lpEventAttributes,
+ BOOL bManualReset,
+ BOOL bInitialState,
+ LPCTSTR lpName )
+{
+ PaError result = paNoError;
+
+ *handle = NULL;
+
+ *handle = CreateEvent( lpEventAttributes, bManualReset, bInitialState, lpName );
+ if( *handle == NULL )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
+ }
+
+ return result;
+}
+
+
+static PaError ResetEventWithPaError( HANDLE handle )
+{
+ PaError result = paNoError;
+
+ if( handle )
+ {
+ if( ResetEvent( handle ) == 0 )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
+ }
+ }
+
+ return result;
+}
+
+
+static PaError CloseHandleWithPaError( HANDLE handle )
+{
+ PaError result = paNoError;
+
+ if( handle )
+ {
+ if( CloseHandle( handle ) == 0 )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
+ }
+ }
+
+ return result;
+}
+
+
+/* PaWinMmeHostApiRepresentation - host api datastructure specific to this implementation */
+
+typedef struct
+{
+ PaUtilHostApiRepresentation inheritedHostApiRep;
+ PaUtilStreamInterface callbackStreamInterface;
+ PaUtilStreamInterface blockingStreamInterface;
+
+ PaUtilAllocationGroup *allocations;
+
+ int inputDeviceCount, outputDeviceCount;
+
+ /** winMmeDeviceIds is an array of WinMme device ids.
+ fields in the range [0, inputDeviceCount) are input device ids,
+ and [inputDeviceCount, inputDeviceCount + outputDeviceCount) are output
+ device ids.
+ */
+ UINT *winMmeDeviceIds;
+}
+PaWinMmeHostApiRepresentation;
+
+
+typedef struct
+{
+ PaDeviceInfo inheritedDeviceInfo;
+ DWORD dwFormats; /**<< standard formats bitmask from the WAVEINCAPS and WAVEOUTCAPS structures */
+}
+PaWinMmeDeviceInfo;
+
+
+/*************************************************************************
+ * Returns recommended device ID.
+ * On the PC, the recommended device can be specified by the user by
+ * setting an environment variable. For example, to use device #1.
+ *
+ * set PA_RECOMMENDED_OUTPUT_DEVICE=1
+ *
+ * The user should first determine the available device ID by using
+ * the supplied application "pa_devs".
+ */
+#define PA_ENV_BUF_SIZE_ (32)
+#define PA_REC_IN_DEV_ENV_NAME_ ("PA_RECOMMENDED_INPUT_DEVICE")
+#define PA_REC_OUT_DEV_ENV_NAME_ ("PA_RECOMMENDED_OUTPUT_DEVICE")
+static PaDeviceIndex GetEnvDefaultDeviceID( char *envName )
+{
+ PaDeviceIndex recommendedIndex = paNoDevice;
+ DWORD hresult;
+ char envbuf[PA_ENV_BUF_SIZE_];
+
+#ifndef WIN32_PLATFORM_PSPC /* no GetEnvironmentVariable on PocketPC */
+
+ /* Let user determine default device by setting environment variable. */
+ hresult = GetEnvironmentVariable( envName, envbuf, PA_ENV_BUF_SIZE_ );
+ if( (hresult > 0) && (hresult < PA_ENV_BUF_SIZE_) )
+ {
+ recommendedIndex = atoi( envbuf );
+ }
+#endif
+
+ return recommendedIndex;
+}
+
+
+static void InitializeDefaultDeviceIdsFromEnv( PaWinMmeHostApiRepresentation *hostApi )
+{
+ PaDeviceIndex device;
+
+ /* input */
+ device = GetEnvDefaultDeviceID( PA_REC_IN_DEV_ENV_NAME_ );
+ if( device != paNoDevice &&
+ ( device >= 0 && device < hostApi->inheritedHostApiRep.info.deviceCount ) &&
+ hostApi->inheritedHostApiRep.deviceInfos[ device ]->maxInputChannels > 0 )
+ {
+ hostApi->inheritedHostApiRep.info.defaultInputDevice = device;
+ }
+
+ /* output */
+ device = GetEnvDefaultDeviceID( PA_REC_OUT_DEV_ENV_NAME_ );
+ if( device != paNoDevice &&
+ ( device >= 0 && device < hostApi->inheritedHostApiRep.info.deviceCount ) &&
+ hostApi->inheritedHostApiRep.deviceInfos[ device ]->maxOutputChannels > 0 )
+ {
+ hostApi->inheritedHostApiRep.info.defaultOutputDevice = device;
+ }
+}
+
+
+/** Convert external PA ID to a windows multimedia device ID
+*/
+static UINT LocalDeviceIndexToWinMmeDeviceId( PaWinMmeHostApiRepresentation *hostApi, PaDeviceIndex device )
+{
+ assert( device >= 0 && device < hostApi->inputDeviceCount + hostApi->outputDeviceCount );
+
+ return hostApi->winMmeDeviceIds[ device ];
+}
+
+
+static PaError QueryInputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx )
+{
+ MMRESULT mmresult;
+
+ switch( mmresult = waveInOpen( NULL, deviceId, waveFormatEx, 0, 0, WAVE_FORMAT_QUERY ) )
+ {
+ case MMSYSERR_NOERROR:
+ return paNoError;
+ case MMSYSERR_ALLOCATED: /* Specified resource is already allocated. */
+ return paDeviceUnavailable;
+ case MMSYSERR_NODRIVER: /* No device driver is present. */
+ return paDeviceUnavailable;
+ case MMSYSERR_NOMEM: /* Unable to allocate or lock memory. */
+ return paInsufficientMemory;
+ case WAVERR_BADFORMAT: /* Attempted to open with an unsupported waveform-audio format. */
+ return paSampleFormatNotSupported;
+
+ case MMSYSERR_BADDEVICEID: /* Specified device identifier is out of range. */
+ /* falls through */
+ default:
+ PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+ return paUnanticipatedHostError;
+ }
+}
+
+
+static PaError QueryOutputWaveFormatEx( int deviceId, WAVEFORMATEX *waveFormatEx )
+{
+ MMRESULT mmresult;
+
+ switch( mmresult = waveOutOpen( NULL, deviceId, waveFormatEx, 0, 0, WAVE_FORMAT_QUERY ) )
+ {
+ case MMSYSERR_NOERROR:
+ return paNoError;
+ case MMSYSERR_ALLOCATED: /* Specified resource is already allocated. */
+ return paDeviceUnavailable;
+ case MMSYSERR_NODRIVER: /* No device driver is present. */
+ return paDeviceUnavailable;
+ case MMSYSERR_NOMEM: /* Unable to allocate or lock memory. */
+ return paInsufficientMemory;
+ case WAVERR_BADFORMAT: /* Attempted to open with an unsupported waveform-audio format. */
+ return paSampleFormatNotSupported;
+
+ case MMSYSERR_BADDEVICEID: /* Specified device identifier is out of range. */
+ /* falls through */
+ default:
+ PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+ return paUnanticipatedHostError;
+ }
+}
+
+
+static PaError QueryFormatSupported( PaDeviceInfo *deviceInfo,
+ PaError (*waveFormatExQueryFunction)(int, WAVEFORMATEX*),
+ int winMmeDeviceId, int channels, double sampleRate )
+{
+ PaWinMmeDeviceInfo *winMmeDeviceInfo = (PaWinMmeDeviceInfo*)deviceInfo;
+ WAVEFORMATEX waveFormatEx;
+
+ if( sampleRate == 11025.0
+ && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1M16))
+ || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_1S16)) ) ){
+
+ return paNoError;
+ }
+
+ if( sampleRate == 22050.0
+ && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2M16))
+ || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_2S16)) ) ){
+
+ return paNoError;
+ }
+
+ if( sampleRate == 44100.0
+ && ( (channels == 1 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4M16))
+ || (channels == 2 && (winMmeDeviceInfo->dwFormats & WAVE_FORMAT_4S16)) ) ){
+
+ return paNoError;
+ }
+
+ waveFormatEx.wFormatTag = WAVE_FORMAT_PCM;
+ waveFormatEx.nChannels = (WORD)channels;
+ waveFormatEx.nSamplesPerSec = (DWORD)sampleRate;
+ waveFormatEx.nAvgBytesPerSec = waveFormatEx.nSamplesPerSec * channels * sizeof(short);
+ waveFormatEx.nBlockAlign = (WORD)(channels * sizeof(short));
+ waveFormatEx.wBitsPerSample = 16;
+ waveFormatEx.cbSize = 0;
+
+ return waveFormatExQueryFunction( winMmeDeviceId, &waveFormatEx );
+}
+
+
+#define PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_ (13) /* must match array length below */
+static double defaultSampleRateSearchOrder_[] =
+ { 44100.0, 48000.0, 32000.0, 24000.0, 22050.0, 88200.0, 96000.0, 192000.0,
+ 16000.0, 12000.0, 11025.0, 9600.0, 8000.0 };
+
+static void DetectDefaultSampleRate( PaWinMmeDeviceInfo *winMmeDeviceInfo, int winMmeDeviceId,
+ PaError (*waveFormatExQueryFunction)(int, WAVEFORMATEX*), int maxChannels )
+{
+ PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;
+ int i;
+
+ deviceInfo->defaultSampleRate = 0.;
+
+ for( i=0; i < PA_DEFAULTSAMPLERATESEARCHORDER_COUNT_; ++i )
+ {
+ double sampleRate = defaultSampleRateSearchOrder_[ i ];
+ PaError paerror = QueryFormatSupported( deviceInfo, waveFormatExQueryFunction, winMmeDeviceId, maxChannels, sampleRate );
+ if( paerror == paNoError )
+ {
+ deviceInfo->defaultSampleRate = sampleRate;
+ break;
+ }
+ }
+}
+
+
+static PaError InitializeInputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi,
+ PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeInputDeviceId, int *success )
+{
+ PaError result = paNoError;
+ char *deviceName; /* non-const ptr */
+ MMRESULT mmresult;
+ WAVEINCAPS wic;
+ PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;
+
+ *success = 0;
+
+ mmresult = waveInGetDevCaps( winMmeInputDeviceId, &wic, sizeof( WAVEINCAPS ) );
+ if( mmresult == MMSYSERR_NOMEM )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+ else if( mmresult != MMSYSERR_NOERROR )
+ {
+ /* instead of returning paUnanticipatedHostError we return
+ paNoError, but leave success set as 0. This allows
+ Pa_Initialize to just ignore this device, without failing
+ the entire initialisation process.
+ */
+ return paNoError;
+ }
+
+ if( winMmeInputDeviceId == WAVE_MAPPER )
+ {
+ /* Append I/O suffix to WAVE_MAPPER device. */
+ deviceName = (char *)PaUtil_GroupAllocateMemory(
+ winMmeHostApi->allocations, strlen( wic.szPname ) + 1 + sizeof(constInputMapperSuffix_) );
+ if( !deviceName )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+ strcpy( deviceName, wic.szPname );
+ strcat( deviceName, constInputMapperSuffix_ );
+ }
+ else
+ {
+ deviceName = (char*)PaUtil_GroupAllocateMemory(
+ winMmeHostApi->allocations, strlen( wic.szPname ) + 1 );
+ if( !deviceName )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+ strcpy( deviceName, wic.szPname );
+ }
+ deviceInfo->name = deviceName;
+
+ deviceInfo->maxInputChannels = wic.wChannels;
+ /* Sometimes a device can return a rediculously large number of channels.
+ * This happened with an SBLive card on a Windows ME box.
+ * If that happens, then force it to 2 channels. PLB20010413
+ */
+ if( (deviceInfo->maxInputChannels < 1) || (deviceInfo->maxInputChannels > 256) )
+ {
+ PA_DEBUG(("Pa_GetDeviceInfo: Num input channels reported as %d! Changed to 2.\n", deviceInfo->maxInputChannels ));
+ deviceInfo->maxInputChannels = 2;
+ }
+
+ winMmeDeviceInfo->dwFormats = wic.dwFormats;
+
+ DetectDefaultSampleRate( winMmeDeviceInfo, winMmeInputDeviceId,
+ QueryInputWaveFormatEx, deviceInfo->maxInputChannels );
+
+ *success = 1;
+
+error:
+ return result;
+}
+
+
+static PaError InitializeOutputDeviceInfo( PaWinMmeHostApiRepresentation *winMmeHostApi,
+ PaWinMmeDeviceInfo *winMmeDeviceInfo, UINT winMmeOutputDeviceId, int *success )
+{
+ PaError result = paNoError;
+ char *deviceName; /* non-const ptr */
+ MMRESULT mmresult;
+ WAVEOUTCAPS woc;
+ PaDeviceInfo *deviceInfo = &winMmeDeviceInfo->inheritedDeviceInfo;
+
+ *success = 0;
+
+ mmresult = waveOutGetDevCaps( winMmeOutputDeviceId, &woc, sizeof( WAVEOUTCAPS ) );
+ if( mmresult == MMSYSERR_NOMEM )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+ else if( mmresult != MMSYSERR_NOERROR )
+ {
+ /* instead of returning paUnanticipatedHostError we return
+ paNoError, but leave success set as 0. This allows
+ Pa_Initialize to just ignore this device, without failing
+ the entire initialisation process.
+ */
+ return paNoError;
+ }
+
+ if( winMmeOutputDeviceId == WAVE_MAPPER )
+ {
+ /* Append I/O suffix to WAVE_MAPPER device. */
+ deviceName = (char *)PaUtil_GroupAllocateMemory(
+ winMmeHostApi->allocations, strlen( woc.szPname ) + 1 + sizeof(constOutputMapperSuffix_) );
+ if( !deviceName )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+ strcpy( deviceName, woc.szPname );
+ strcat( deviceName, constOutputMapperSuffix_ );
+ }
+ else
+ {
+ deviceName = (char*)PaUtil_GroupAllocateMemory(
+ winMmeHostApi->allocations, strlen( woc.szPname ) + 1 );
+ if( !deviceName )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+ strcpy( deviceName, woc.szPname );
+ }
+ deviceInfo->name = deviceName;
+
+ deviceInfo->maxOutputChannels = woc.wChannels;
+ /* Sometimes a device can return a rediculously large number of channels.
+ * This happened with an SBLive card on a Windows ME box.
+ * It also happens on Win XP!
+ */
+ if( (deviceInfo->maxOutputChannels < 1) || (deviceInfo->maxOutputChannels > 256) )
+ {
+ PA_DEBUG(("Pa_GetDeviceInfo: Num output channels reported as %d! Changed to 2.\n", deviceInfo->maxOutputChannels ));
+ deviceInfo->maxOutputChannels = 2;
+ }
+
+ winMmeDeviceInfo->dwFormats = woc.dwFormats;
+
+ DetectDefaultSampleRate( winMmeDeviceInfo, winMmeOutputDeviceId,
+ QueryOutputWaveFormatEx, deviceInfo->maxOutputChannels );
+
+ *success = 1;
+
+error:
+ return result;
+}
+
+
+static void GetDefaultLatencies( PaTime *defaultLowLatency, PaTime *defaultHighLatency )
+{
+ OSVERSIONINFO osvi;
+ osvi.dwOSVersionInfoSize = sizeof( osvi );
+ GetVersionEx( &osvi );
+
+ /* Check for NT */
+ if( (osvi.dwMajorVersion == 4) && (osvi.dwPlatformId == 2) )
+ {
+ *defaultLowLatency = PA_MME_WIN_NT_DEFAULT_LATENCY_;
+ }
+ else if(osvi.dwMajorVersion >= 5)
+ {
+ *defaultLowLatency = PA_MME_WIN_WDM_DEFAULT_LATENCY_;
+ }
+ else
+ {
+ *defaultLowLatency = PA_MME_WIN_9X_DEFAULT_LATENCY_;
+ }
+
+ *defaultHighLatency = *defaultLowLatency * 2;
+}
+
+
+PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
+{
+ PaError result = paNoError;
+ int i;
+ PaWinMmeHostApiRepresentation *winMmeHostApi;
+ int inputDeviceCount, outputDeviceCount, maximumPossibleDeviceCount;
+ PaWinMmeDeviceInfo *deviceInfoArray;
+ int deviceInfoInitializationSucceeded;
+ PaTime defaultLowLatency, defaultHighLatency;
+
+ winMmeHostApi = (PaWinMmeHostApiRepresentation*)PaUtil_AllocateMemory( sizeof(PaWinMmeHostApiRepresentation) );
+ if( !winMmeHostApi )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ winMmeHostApi->allocations = PaUtil_CreateAllocationGroup();
+ if( !winMmeHostApi->allocations )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ *hostApi = &winMmeHostApi->inheritedHostApiRep;
+ (*hostApi)->info.structVersion = 1;
+ (*hostApi)->info.type = paMME;
+ (*hostApi)->info.name = "MME";
+
+
+ /* initialise device counts and default devices under the assumption that
+ there are no devices. These values are incremented below if and when
+ devices are successfully initialized.
+ */
+ (*hostApi)->info.deviceCount = 0;
+ (*hostApi)->info.defaultInputDevice = paNoDevice;
+ (*hostApi)->info.defaultOutputDevice = paNoDevice;
+ winMmeHostApi->inputDeviceCount = 0;
+ winMmeHostApi->outputDeviceCount = 0;
+
+
+ maximumPossibleDeviceCount = 0;
+
+ inputDeviceCount = waveInGetNumDevs();
+ if( inputDeviceCount > 0 )
+ maximumPossibleDeviceCount += inputDeviceCount + 1; /* assume there is a WAVE_MAPPER */
+
+ outputDeviceCount = waveOutGetNumDevs();
+ if( outputDeviceCount > 0 )
+ maximumPossibleDeviceCount += outputDeviceCount + 1; /* assume there is a WAVE_MAPPER */
+
+
+ if( maximumPossibleDeviceCount > 0 ){
+
+ (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
+ winMmeHostApi->allocations, sizeof(PaDeviceInfo*) * maximumPossibleDeviceCount );
+ if( !(*hostApi)->deviceInfos )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ /* allocate all device info structs in a contiguous block */
+ deviceInfoArray = (PaWinMmeDeviceInfo*)PaUtil_GroupAllocateMemory(
+ winMmeHostApi->allocations, sizeof(PaWinMmeDeviceInfo) * maximumPossibleDeviceCount );
+ if( !deviceInfoArray )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ winMmeHostApi->winMmeDeviceIds = (UINT*)PaUtil_GroupAllocateMemory(
+ winMmeHostApi->allocations, sizeof(int) * maximumPossibleDeviceCount );
+ if( !winMmeHostApi->winMmeDeviceIds )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ GetDefaultLatencies( &defaultLowLatency, &defaultHighLatency );
+
+ if( inputDeviceCount > 0 ){
+ /* -1 is the WAVE_MAPPER */
+ for( i = -1; i < inputDeviceCount; ++i ){
+ UINT winMmeDeviceId = (UINT)((i==-1) ? WAVE_MAPPER : i);
+ PaWinMmeDeviceInfo *wmmeDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];
+ PaDeviceInfo *deviceInfo = &wmmeDeviceInfo->inheritedDeviceInfo;
+ deviceInfo->structVersion = 2;
+ deviceInfo->hostApi = hostApiIndex;
+
+ deviceInfo->maxInputChannels = 0;
+ deviceInfo->maxOutputChannels = 0;
+
+ deviceInfo->defaultLowInputLatency = defaultLowLatency;
+ deviceInfo->defaultLowOutputLatency = defaultLowLatency;
+ deviceInfo->defaultHighInputLatency = defaultHighLatency;
+ deviceInfo->defaultHighOutputLatency = defaultHighLatency;
+
+ result = InitializeInputDeviceInfo( winMmeHostApi, wmmeDeviceInfo,
+ winMmeDeviceId, &deviceInfoInitializationSucceeded );
+ if( result != paNoError )
+ goto error;
+
+ if( deviceInfoInitializationSucceeded ){
+ if( (*hostApi)->info.defaultInputDevice == paNoDevice )
+ (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
+
+ winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId;
+ (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;
+
+ winMmeHostApi->inputDeviceCount++;
+ (*hostApi)->info.deviceCount++;
+ }
+ }
+ }
+
+ if( outputDeviceCount > 0 ){
+ /* -1 is the WAVE_MAPPER */
+ for( i = -1; i < outputDeviceCount; ++i ){
+ UINT winMmeDeviceId = (UINT)((i==-1) ? WAVE_MAPPER : i);
+ PaWinMmeDeviceInfo *wmmeDeviceInfo = &deviceInfoArray[ (*hostApi)->info.deviceCount ];
+ PaDeviceInfo *deviceInfo = &wmmeDeviceInfo->inheritedDeviceInfo;
+ deviceInfo->structVersion = 2;
+ deviceInfo->hostApi = hostApiIndex;
+
+ deviceInfo->maxInputChannels = 0;
+ deviceInfo->maxOutputChannels = 0;
+
+ deviceInfo->defaultLowInputLatency = defaultLowLatency;
+ deviceInfo->defaultLowOutputLatency = defaultLowLatency;
+ deviceInfo->defaultHighInputLatency = defaultHighLatency;
+ deviceInfo->defaultHighOutputLatency = defaultHighLatency;
+
+ result = InitializeOutputDeviceInfo( winMmeHostApi, wmmeDeviceInfo,
+ winMmeDeviceId, &deviceInfoInitializationSucceeded );
+ if( result != paNoError )
+ goto error;
+
+ if( deviceInfoInitializationSucceeded ){
+ if( (*hostApi)->info.defaultOutputDevice == paNoDevice )
+ (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
+
+ winMmeHostApi->winMmeDeviceIds[ (*hostApi)->info.deviceCount ] = winMmeDeviceId;
+ (*hostApi)->deviceInfos[ (*hostApi)->info.deviceCount ] = deviceInfo;
+
+ winMmeHostApi->outputDeviceCount++;
+ (*hostApi)->info.deviceCount++;
+ }
+ }
+ }
+ }
+
+
+ InitializeDefaultDeviceIdsFromEnv( winMmeHostApi );
+
+ (*hostApi)->Terminate = Terminate;
+ (*hostApi)->OpenStream = OpenStream;
+ (*hostApi)->IsFormatSupported = IsFormatSupported;
+
+ PaUtil_InitializeStreamInterface( &winMmeHostApi->callbackStreamInterface, CloseStream, StartStream,
+ StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+ GetStreamTime, GetStreamCpuLoad,
+ PaUtil_DummyRead, PaUtil_DummyWrite,
+ PaUtil_DummyGetReadAvailable, PaUtil_DummyGetWriteAvailable );
+
+ PaUtil_InitializeStreamInterface( &winMmeHostApi->blockingStreamInterface, CloseStream, StartStream,
+ StopStream, AbortStream, IsStreamStopped, IsStreamActive,
+ GetStreamTime, PaUtil_DummyGetCpuLoad,
+ ReadStream, WriteStream, GetStreamReadAvailable, GetStreamWriteAvailable );
+
+ return result;
+
+error:
+ if( winMmeHostApi )
+ {
+ if( winMmeHostApi->allocations )
+ {
+ PaUtil_FreeAllAllocations( winMmeHostApi->allocations );
+ PaUtil_DestroyAllocationGroup( winMmeHostApi->allocations );
+ }
+
+ PaUtil_FreeMemory( winMmeHostApi );
+ }
+
+ return result;
+}
+
+
+static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
+{
+ PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
+
+ if( winMmeHostApi->allocations )
+ {
+ PaUtil_FreeAllAllocations( winMmeHostApi->allocations );
+ PaUtil_DestroyAllocationGroup( winMmeHostApi->allocations );
+ }
+
+ PaUtil_FreeMemory( winMmeHostApi );
+}
+
+
+static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate )
+{
+ PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
+ PaDeviceInfo *inputDeviceInfo, *outputDeviceInfo;
+ int inputChannelCount, outputChannelCount;
+ int inputMultipleDeviceChannelCount, outputMultipleDeviceChannelCount;
+ PaSampleFormat inputSampleFormat, outputSampleFormat;
+ PaWinMmeStreamInfo *inputStreamInfo, *outputStreamInfo;
+ UINT winMmeInputDeviceId, winMmeOutputDeviceId;
+ unsigned int i;
+ PaError paerror;
+
+ /* The calls to QueryFormatSupported below are intended to detect invalid
+ sample rates. If we assume that the channel count and format are OK,
+ then the only thing that could fail is the sample rate. This isn't
+ strictly true, but I can't think of a better way to test that the
+ sample rate is valid.
+ */
+
+ if( inputParameters )
+ {
+ inputChannelCount = inputParameters->channelCount;
+ inputSampleFormat = inputParameters->sampleFormat;
+ inputStreamInfo = inputParameters->hostApiSpecificStreamInfo;
+
+ /* all standard sample formats are supported by the buffer adapter,
+ this implementation doesn't support any custom sample formats */
+ if( inputSampleFormat & paCustomFormat )
+ return paSampleFormatNotSupported;
+
+ if( inputParameters->device == paUseHostApiSpecificDeviceSpecification
+ && inputStreamInfo && (inputStreamInfo->flags & paWinMmeUseMultipleDevices) )
+ {
+ inputMultipleDeviceChannelCount = 0;
+ for( i=0; i< inputStreamInfo->deviceCount; ++i )
+ {
+ inputMultipleDeviceChannelCount += inputStreamInfo->devices[i].channelCount;
+
+ inputDeviceInfo = hostApi->deviceInfos[ inputStreamInfo->devices[i].device ];
+
+ /* check that input device can support inputChannelCount */
+ if( inputStreamInfo->devices[i].channelCount <= 0
+ || inputStreamInfo->devices[i].channelCount > inputDeviceInfo->maxInputChannels )
+ return paInvalidChannelCount;
+
+ /* test for valid sample rate, see comment above */
+ winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputStreamInfo->devices[i].device );
+ paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, winMmeInputDeviceId, inputStreamInfo->devices[i].channelCount, sampleRate );
+ if( paerror != paNoError )
+ return paInvalidSampleRate;
+ }
+
+ if( inputMultipleDeviceChannelCount != inputChannelCount )
+ return paIncompatibleHostApiSpecificStreamInfo;
+ }
+ else
+ {
+ if( inputStreamInfo && (inputStreamInfo->flags & paWinMmeUseMultipleDevices) )
+ return paIncompatibleHostApiSpecificStreamInfo; /* paUseHostApiSpecificDeviceSpecification was not supplied as the input device */
+
+ inputDeviceInfo = hostApi->deviceInfos[ inputParameters->device ];
+
+ /* check that input device can support inputChannelCount */
+ if( inputChannelCount > inputDeviceInfo->maxInputChannels )
+ return paInvalidChannelCount;
+
+ /* test for valid sample rate, see comment above */
+ winMmeInputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, inputParameters->device );
+ paerror = QueryFormatSupported( inputDeviceInfo, QueryInputWaveFormatEx, winMmeInputDeviceId, inputChannelCount, sampleRate );
+ if( paerror != paNoError )
+ return paInvalidSampleRate;
+ }
+ }
+
+ if( outputParameters )
+ {
+ outputChannelCount = outputParameters->channelCount;
+ outputSampleFormat = outputParameters->sampleFormat;
+ outputStreamInfo = outputParameters->hostApiSpecificStreamInfo;
+
+ /* all standard sample formats are supported by the buffer adapter,
+ this implementation doesn't support any custom sample formats */
+ if( outputSampleFormat & paCustomFormat )
+ return paSampleFormatNotSupported;
+
+ if( outputParameters->device == paUseHostApiSpecificDeviceSpecification
+ && outputStreamInfo && (outputStreamInfo->flags & paWinMmeUseMultipleDevices) )
+ {
+ outputMultipleDeviceChannelCount = 0;
+ for( i=0; i< outputStreamInfo->deviceCount; ++i )
+ {
+ outputMultipleDeviceChannelCount += outputStreamInfo->devices[i].channelCount;
+
+ outputDeviceInfo = hostApi->deviceInfos[ outputStreamInfo->devices[i].device ];
+
+ /* check that output device can support outputChannelCount */
+ if( outputStreamInfo->devices[i].channelCount <= 0
+ || outputStreamInfo->devices[i].channelCount > outputDeviceInfo->maxOutputChannels )
+ return paInvalidChannelCount;
+
+ /* test for valid sample rate, see comment above */
+ winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputStreamInfo->devices[i].device );
+ paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, winMmeOutputDeviceId, outputStreamInfo->devices[i].channelCount, sampleRate );
+ if( paerror != paNoError )
+ return paInvalidSampleRate;
+ }
+
+ if( outputMultipleDeviceChannelCount != outputChannelCount )
+ return paIncompatibleHostApiSpecificStreamInfo;
+ }
+ else
+ {
+ if( outputStreamInfo && (outputStreamInfo->flags & paWinMmeUseMultipleDevices) )
+ return paIncompatibleHostApiSpecificStreamInfo; /* paUseHostApiSpecificDeviceSpecification was not supplied as the output device */
+
+ outputDeviceInfo = hostApi->deviceInfos[ outputParameters->device ];
+
+ /* check that output device can support outputChannelCount */
+ if( outputChannelCount > outputDeviceInfo->maxOutputChannels )
+ return paInvalidChannelCount;
+
+ /* test for valid sample rate, see comment above */
+ winMmeOutputDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, outputParameters->device );
+ paerror = QueryFormatSupported( outputDeviceInfo, QueryOutputWaveFormatEx, winMmeOutputDeviceId, outputChannelCount, sampleRate );
+ if( paerror != paNoError )
+ return paInvalidSampleRate;
+ }
+ }
+
+ /*
+ - if a full duplex stream is requested, check that the combination
+ of input and output parameters is supported
+
+ - check that the device supports sampleRate
+
+ for mme all we can do is test that the input and output devices
+ support the requested sample rate and number of channels. we
+ cannot test for full duplex compatibility.
+ */
+
+ return paFormatIsSupported;
+}
+
+
+
+static void SelectBufferSizeAndCount( unsigned long baseBufferSize,
+ unsigned long requestedLatency,
+ unsigned long baseBufferCount, unsigned long minimumBufferCount,
+ unsigned long maximumBufferSize, unsigned long *hostBufferSize,
+ unsigned long *hostBufferCount )
+{
+ unsigned long sizeMultiplier, bufferCount, latency;
+ unsigned long nextLatency, nextBufferSize;
+ int baseBufferSizeIsPowerOfTwo;
+
+ sizeMultiplier = 1;
+ bufferCount = baseBufferCount;
+
+ /* count-1 below because latency is always determined by one less
+ than the total number of buffers.
+ */
+ latency = (baseBufferSize * sizeMultiplier) * (bufferCount-1);
+
+ if( latency > requestedLatency )
+ {
+
+ /* reduce number of buffers without falling below suggested latency */
+
+ nextLatency = (baseBufferSize * sizeMultiplier) * (bufferCount-2);
+ while( bufferCount > minimumBufferCount && nextLatency >= requestedLatency )
+ {
+ --bufferCount;
+ nextLatency = (baseBufferSize * sizeMultiplier) * (bufferCount-2);
+ }
+
+ }else if( latency < requestedLatency ){
+
+ baseBufferSizeIsPowerOfTwo = (! (baseBufferSize & (baseBufferSize - 1)));
+ if( baseBufferSizeIsPowerOfTwo ){
+
+ /* double size of buffers without exceeding requestedLatency */
+
+ nextBufferSize = (baseBufferSize * (sizeMultiplier*2));
+ nextLatency = nextBufferSize * (bufferCount-1);
+ while( nextBufferSize <= maximumBufferSize
+ && nextLatency < requestedLatency )
+ {
+ sizeMultiplier *= 2;
+ nextBufferSize = (baseBufferSize * (sizeMultiplier*2));
+ nextLatency = nextBufferSize * (bufferCount-1);
+ }
+
+ }else{
+
+ /* increase size of buffers upto first excess of requestedLatency */
+
+ nextBufferSize = (baseBufferSize * (sizeMultiplier+1));
+ nextLatency = nextBufferSize * (bufferCount-1);
+ while( nextBufferSize <= maximumBufferSize
+ && nextLatency < requestedLatency )
+ {
+ ++sizeMultiplier;
+ nextBufferSize = (baseBufferSize * (sizeMultiplier+1));
+ nextLatency = nextBufferSize * (bufferCount-1);
+ }
+
+ if( nextLatency < requestedLatency )
+ ++sizeMultiplier;
+ }
+
+ /* increase number of buffers until requestedLatency is reached */
+
+ latency = (baseBufferSize * sizeMultiplier) * (bufferCount-1);
+ while( latency < requestedLatency )
+ {
+ ++bufferCount;
+ latency = (baseBufferSize * sizeMultiplier) * (bufferCount-1);
+ }
+ }
+
+ *hostBufferSize = baseBufferSize * sizeMultiplier;
+ *hostBufferCount = bufferCount;
+}
+
+
+static void ReselectBufferCount( unsigned long bufferSize,
+ unsigned long requestedLatency,
+ unsigned long baseBufferCount, unsigned long minimumBufferCount,
+ unsigned long *hostBufferCount )
+{
+ unsigned long bufferCount, latency;
+ unsigned long nextLatency;
+
+ bufferCount = baseBufferCount;
+
+ /* count-1 below because latency is always determined by one less
+ than the total number of buffers.
+ */
+ latency = bufferSize * (bufferCount-1);
+
+ if( latency > requestedLatency )
+ {
+ /* reduce number of buffers without falling below suggested latency */
+
+ nextLatency = bufferSize * (bufferCount-2);
+ while( bufferCount > minimumBufferCount && nextLatency >= requestedLatency )
+ {
+ --bufferCount;
+ nextLatency = bufferSize * (bufferCount-2);
+ }
+
+ }else if( latency < requestedLatency ){
+
+ /* increase number of buffers until requestedLatency is reached */
+
+ latency = bufferSize * (bufferCount-1);
+ while( latency < requestedLatency )
+ {
+ ++bufferCount;
+ latency = bufferSize * (bufferCount-1);
+ }
+ }
+
+ *hostBufferCount = bufferCount;
+}
+
+
+/* CalculateBufferSettings() fills the framesPerHostInputBuffer, hostInputBufferCount,
+ framesPerHostOutputBuffer and hostOutputBufferCount parameters based on the values
+ of the other parameters.
+*/
+
+static PaError CalculateBufferSettings(
+ unsigned long *framesPerHostInputBuffer, unsigned long *hostInputBufferCount,
+ unsigned long *framesPerHostOutputBuffer, unsigned long *hostOutputBufferCount,
+ int inputChannelCount, PaSampleFormat hostInputSampleFormat,
+ PaTime suggestedInputLatency, PaWinMmeStreamInfo *inputStreamInfo,
+ int outputChannelCount, PaSampleFormat hostOutputSampleFormat,
+ PaTime suggestedOutputLatency, PaWinMmeStreamInfo *outputStreamInfo,
+ double sampleRate, unsigned long framesPerBuffer )
+{
+ PaError result = paNoError;
+ int effectiveInputChannelCount, effectiveOutputChannelCount;
+ int hostInputFrameSize = 0;
+ unsigned int i;
+
+ if( inputChannelCount > 0 )
+ {
+ int hostInputSampleSize = Pa_GetSampleSize( hostInputSampleFormat );
+ if( hostInputSampleSize < 0 )
+ {
+ result = hostInputSampleSize;
+ goto error;
+ }
+
+ if( inputStreamInfo
+ && ( inputStreamInfo->flags & paWinMmeUseMultipleDevices ) )
+ {
+ /* set effectiveInputChannelCount to the largest number of
+ channels on any one device.
+ */
+ effectiveInputChannelCount = 0;
+ for( i=0; i< inputStreamInfo->deviceCount; ++i )
+ {
+ if( inputStreamInfo->devices[i].channelCount > effectiveInputChannelCount )
+ effectiveInputChannelCount = inputStreamInfo->devices[i].channelCount;
+ }
+ }
+ else
+ {
+ effectiveInputChannelCount = inputChannelCount;
+ }
+
+ hostInputFrameSize = hostInputSampleSize * effectiveInputChannelCount;
+
+ if( inputStreamInfo
+ && ( inputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )
+ {
+ if( inputStreamInfo->bufferCount <= 0
+ || inputStreamInfo->framesPerBuffer <= 0 )
+ {
+ result = paIncompatibleHostApiSpecificStreamInfo;
+ goto error;
+ }
+
+ *framesPerHostInputBuffer = inputStreamInfo->framesPerBuffer;
+ *hostInputBufferCount = inputStreamInfo->bufferCount;
+ }
+ else
+ {
+ unsigned long hostBufferSizeBytes, hostBufferCount;
+ unsigned long minimumBufferCount = (outputChannelCount > 0)
+ ? PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_
+ : PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_HALF_DUPLEX_;
+
+ unsigned long maximumBufferSize = (long) ((PA_MME_MAX_HOST_BUFFER_SECS_ * sampleRate) * hostInputFrameSize);
+ if( maximumBufferSize > PA_MME_MAX_HOST_BUFFER_BYTES_ )
+ maximumBufferSize = PA_MME_MAX_HOST_BUFFER_BYTES_;
+
+ /* compute the following in bytes, then convert back to frames */
+
+ SelectBufferSizeAndCount(
+ ((framesPerBuffer == paFramesPerBufferUnspecified)
+ ? PA_MME_MIN_HOST_BUFFER_FRAMES_WHEN_UNSPECIFIED_
+ : framesPerBuffer ) * hostInputFrameSize, /* baseBufferSize */
+ ((unsigned long)(suggestedInputLatency * sampleRate)) * hostInputFrameSize, /* suggestedLatency */
+ 4, /* baseBufferCount */
+ minimumBufferCount, maximumBufferSize,
+ &hostBufferSizeBytes, &hostBufferCount );
+
+ *framesPerHostInputBuffer = hostBufferSizeBytes / hostInputFrameSize;
+ *hostInputBufferCount = hostBufferCount;
+ }
+ }
+ else
+ {
+ *framesPerHostInputBuffer = 0;
+ *hostInputBufferCount = 0;
+ }
+
+ if( outputChannelCount > 0 )
+ {
+ if( outputStreamInfo
+ && ( outputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )
+ {
+ if( outputStreamInfo->bufferCount <= 0
+ || outputStreamInfo->framesPerBuffer <= 0 )
+ {
+ result = paIncompatibleHostApiSpecificStreamInfo;
+ goto error;
+ }
+
+ *framesPerHostOutputBuffer = outputStreamInfo->framesPerBuffer;
+ *hostOutputBufferCount = outputStreamInfo->bufferCount;
+
+
+ if( inputChannelCount > 0 ) /* full duplex */
+ {
+ if( *framesPerHostInputBuffer != *framesPerHostOutputBuffer )
+ {
+ if( inputStreamInfo
+ && ( inputStreamInfo->flags & paWinMmeUseLowLevelLatencyParameters ) )
+ {
+ /* a custom StreamInfo was used for specifying both input
+ and output buffer sizes, the larger buffer size
+ must be a multiple of the smaller buffer size */
+
+ if( *framesPerHostInputBuffer < *framesPerHostOutputBuffer )
+ {
+ if( *framesPerHostOutputBuffer % *framesPerHostInputBuffer != 0 )
+ {
+ result = paIncompatibleHostApiSpecificStreamInfo;
+ goto error;
+ }
+ }
+ else
+ {
+ assert( *framesPerHostInputBuffer > *framesPerHostOutputBuffer );
+ if( *framesPerHostInputBuffer % *framesPerHostOutputBuffer != 0 )
+ {
+ result = paIncompatibleHostApiSpecificStreamInfo;
+ goto error;
+ }
+ }
+ }
+ else
+ {
+ /* a custom StreamInfo was not used for specifying the input buffer size,
+ so use the output buffer size, and approximately the same latency. */
+
+ *framesPerHostInputBuffer = *framesPerHostOutputBuffer;
+ *hostInputBufferCount = (((unsigned long)(suggestedInputLatency * sampleRate)) / *framesPerHostInputBuffer) + 1;
+
+ if( *hostInputBufferCount < PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_ )
+ *hostInputBufferCount = PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_;
+ }
+ }
+ }
+ }
+ else
+ {
+ unsigned long hostBufferSizeBytes, hostBufferCount;
+ unsigned long minimumBufferCount = PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_;
+ unsigned long maximumBufferSize;
+ int hostOutputFrameSize;
+ int hostOutputSampleSize;
+
+ hostOutputSampleSize = Pa_GetSampleSize( hostOutputSampleFormat );
+ if( hostOutputSampleSize < 0 )
+ {
+ result = hostOutputSampleSize;
+ goto error;
+ }
+
+ if( outputStreamInfo
+ && ( outputStreamInfo->flags & paWinMmeUseMultipleDevices ) )
+ {
+ /* set effectiveOutputChannelCount to the largest number of
+ channels on any one device.
+ */
+ effectiveOutputChannelCount = 0;
+ for( i=0; i< outputStreamInfo->deviceCount; ++i )
+ {
+ if( outputStreamInfo->devices[i].channelCount > effectiveOutputChannelCount )
+ effectiveOutputChannelCount = outputStreamInfo->devices[i].channelCount;
+ }
+ }
+ else
+ {
+ effectiveOutputChannelCount = outputChannelCount;
+ }
+
+ hostOutputFrameSize = hostOutputSampleSize * effectiveOutputChannelCount;
+
+ maximumBufferSize = (long) ((PA_MME_MAX_HOST_BUFFER_SECS_ * sampleRate) * hostOutputFrameSize);
+ if( maximumBufferSize > PA_MME_MAX_HOST_BUFFER_BYTES_ )
+ maximumBufferSize = PA_MME_MAX_HOST_BUFFER_BYTES_;
+
+
+ /* compute the following in bytes, then convert back to frames */
+
+ SelectBufferSizeAndCount(
+ ((framesPerBuffer == paFramesPerBufferUnspecified)
+ ? PA_MME_MIN_HOST_BUFFER_FRAMES_WHEN_UNSPECIFIED_
+ : framesPerBuffer ) * hostOutputFrameSize, /* baseBufferSize */
+ ((unsigned long)(suggestedOutputLatency * sampleRate)) * hostOutputFrameSize, /* suggestedLatency */
+ 4, /* baseBufferCount */
+ minimumBufferCount,
+ maximumBufferSize,
+ &hostBufferSizeBytes, &hostBufferCount );
+
+ *framesPerHostOutputBuffer = hostBufferSizeBytes / hostOutputFrameSize;
+ *hostOutputBufferCount = hostBufferCount;
+
+
+ if( inputChannelCount > 0 )
+ {
+ /* ensure that both input and output buffer sizes are the same.
+ if they don't match at this stage, choose the smallest one
+ and use that for input and output
+ */
+
+ if( *framesPerHostOutputBuffer != *framesPerHostInputBuffer )
+ {
+ if( framesPerHostInputBuffer < framesPerHostOutputBuffer )
+ {
+ unsigned long framesPerHostBuffer = *framesPerHostInputBuffer;
+
+ minimumBufferCount = PA_MME_MIN_HOST_OUTPUT_BUFFER_COUNT_;
+ ReselectBufferCount(
+ framesPerHostBuffer * hostOutputFrameSize, /* bufferSize */
+ ((unsigned long)(suggestedOutputLatency * sampleRate)) * hostOutputFrameSize, /* suggestedLatency */
+ 4, /* baseBufferCount */
+ minimumBufferCount,
+ &hostBufferCount );
+
+ *framesPerHostOutputBuffer = framesPerHostBuffer;
+ *hostOutputBufferCount = hostBufferCount;
+ }
+ else
+ {
+ unsigned long framesPerHostBuffer = *framesPerHostOutputBuffer;
+
+ minimumBufferCount = PA_MME_MIN_HOST_INPUT_BUFFER_COUNT_FULL_DUPLEX_;
+ ReselectBufferCount(
+ framesPerHostBuffer * hostInputFrameSize, /* bufferSize */
+ ((unsigned long)(suggestedInputLatency * sampleRate)) * hostInputFrameSize, /* suggestedLatency */
+ 4, /* baseBufferCount */
+ minimumBufferCount,
+ &hostBufferCount );
+
+ *framesPerHostInputBuffer = framesPerHostBuffer;
+ *hostInputBufferCount = hostBufferCount;
+ }
+ }
+ }
+ }
+ }
+ else
+ {
+ *framesPerHostOutputBuffer = 0;
+ *hostOutputBufferCount = 0;
+ }
+
+error:
+ return result;
+}
+
+
+typedef struct
+{
+ HANDLE bufferEvent;
+ void *waveHandles;
+ unsigned int deviceCount;
+ /* unsigned int channelCount; */
+ WAVEHDR **waveHeaders; /* waveHeaders[device][buffer] */
+ unsigned int bufferCount;
+ unsigned int currentBufferIndex;
+ unsigned int framesPerBuffer;
+ unsigned int framesUsedInCurrentBuffer;
+}PaWinMmeSingleDirectionHandlesAndBuffers;
+
+/* prototypes for functions operating on PaWinMmeSingleDirectionHandlesAndBuffers */
+
+static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers );
+static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi,
+ PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
+ unsigned long bytesPerHostSample,
+ double sampleRate, PaWinMmeDeviceAndChannelCount *devices,
+ unsigned int deviceCount, int isInput );
+static PaError TerminateWaveHandles( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput, int currentlyProcessingAnError );
+static PaError InitializeWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
+ unsigned long hostBufferCount,
+ PaSampleFormat hostSampleFormat,
+ unsigned long framesPerHostBuffer,
+ PaWinMmeDeviceAndChannelCount *devices,
+ int isInput );
+static void TerminateWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput );
+
+
+static void InitializeSingleDirectionHandlesAndBuffers( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )
+{
+ handlesAndBuffers->bufferEvent = 0;
+ handlesAndBuffers->waveHandles = 0;
+ handlesAndBuffers->deviceCount = 0;
+ handlesAndBuffers->waveHeaders = 0;
+ handlesAndBuffers->bufferCount = 0;
+}
+
+static PaError InitializeWaveHandles( PaWinMmeHostApiRepresentation *winMmeHostApi,
+ PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
+ unsigned long bytesPerHostSample,
+ double sampleRate, PaWinMmeDeviceAndChannelCount *devices,
+ unsigned int deviceCount, int isInput )
+{
+ PaError result;
+ MMRESULT mmresult;
+ unsigned long bytesPerFrame;
+ WAVEFORMATEX wfx;
+ signed int i;
+
+ /* for error cleanup we expect that InitializeSingleDirectionHandlesAndBuffers()
+ has already been called to zero some fields */
+
+ result = CreateEventWithPaError( &handlesAndBuffers->bufferEvent, NULL, FALSE, FALSE, NULL );
+ if( result != paNoError ) goto error;
+
+ if( isInput )
+ handlesAndBuffers->waveHandles = (void*)PaUtil_AllocateMemory( sizeof(HWAVEIN) * deviceCount );
+ else
+ handlesAndBuffers->waveHandles = (void*)PaUtil_AllocateMemory( sizeof(HWAVEOUT) * deviceCount );
+ if( !handlesAndBuffers->waveHandles )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ handlesAndBuffers->deviceCount = deviceCount;
+
+ for( i = 0; i < (signed int)deviceCount; ++i )
+ {
+ if( isInput )
+ ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] = 0;
+ else
+ ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] = 0;
+ }
+
+ wfx.wFormatTag = WAVE_FORMAT_PCM;
+ wfx.nSamplesPerSec = (DWORD) sampleRate;
+ wfx.cbSize = 0;
+
+ for( i = 0; i < (signed int)deviceCount; ++i )
+ {
+ UINT winMmeDeviceId;
+
+ winMmeDeviceId = LocalDeviceIndexToWinMmeDeviceId( winMmeHostApi, devices[i].device );
+ wfx.nChannels = (WORD)devices[i].channelCount;
+
+ bytesPerFrame = wfx.nChannels * bytesPerHostSample;
+
+ wfx.nAvgBytesPerSec = (DWORD)(bytesPerFrame * sampleRate);
+ wfx.nBlockAlign = (WORD)bytesPerFrame;
+ wfx.wBitsPerSample = (WORD)((bytesPerFrame/wfx.nChannels) * 8);
+
+ /* REVIEW: consider not firing an event for input when a full duplex
+ stream is being used. this would probably depend on the
+ neverDropInput flag. */
+
+ if( isInput )
+ mmresult = waveInOpen( &((HWAVEIN*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, &wfx,
+ (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT );
+ else
+ mmresult = waveOutOpen( &((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], winMmeDeviceId, &wfx,
+ (DWORD_PTR)handlesAndBuffers->bufferEvent, (DWORD_PTR)0, CALLBACK_EVENT );
+
+ if( mmresult != MMSYSERR_NOERROR )
+ {
+ switch( mmresult )
+ {
+ case MMSYSERR_ALLOCATED: /* Specified resource is already allocated. */
+ result = paDeviceUnavailable;
+ break;
+ case MMSYSERR_NODRIVER: /* No device driver is present. */
+ result = paDeviceUnavailable;
+ break;
+ case MMSYSERR_NOMEM: /* Unable to allocate or lock memory. */
+ result = paInsufficientMemory;
+ break;
+
+ case MMSYSERR_BADDEVICEID: /* Specified device identifier is out of range. */
+ /* falls through */
+ case WAVERR_BADFORMAT: /* Attempted to open with an unsupported waveform-audio format. */
+ /* falls through */
+ default:
+ result = paUnanticipatedHostError;
+ if( isInput )
+ {
+ PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+ }
+ else
+ {
+ PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+ }
+ }
+ goto error;
+ }
+ }
+
+ return result;
+
+error:
+ TerminateWaveHandles( handlesAndBuffers, isInput, 1 /* currentlyProcessingAnError */ );
+
+ return result;
+}
+
+
+static PaError TerminateWaveHandles( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput, int currentlyProcessingAnError )
+{
+ PaError result = paNoError;
+ MMRESULT mmresult;
+ signed int i;
+
+ if( handlesAndBuffers->waveHandles )
+ {
+ for( i = handlesAndBuffers->deviceCount-1; i >= 0; --i )
+ {
+ if( isInput )
+ {
+ if( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] )
+ mmresult = waveInClose( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i] );
+ else
+ mmresult = MMSYSERR_NOERROR;
+ }
+ else
+ {
+ if( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] )
+ mmresult = waveOutClose( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i] );
+ else
+ mmresult = MMSYSERR_NOERROR;
+ }
+
+ if( mmresult != MMSYSERR_NOERROR &&
+ !currentlyProcessingAnError ) /* don't update the error state if we're already processing an error */
+ {
+ result = paUnanticipatedHostError;
+ if( isInput )
+ {
+ PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+ }
+ else
+ {
+ PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+ }
+ /* note that we don't break here, we try to continue closing devices */
+ }
+ }
+
+ PaUtil_FreeMemory( handlesAndBuffers->waveHandles );
+ handlesAndBuffers->waveHandles = 0;
+ }
+
+ if( handlesAndBuffers->bufferEvent )
+ {
+ result = CloseHandleWithPaError( handlesAndBuffers->bufferEvent );
+ handlesAndBuffers->bufferEvent = 0;
+ }
+
+ return result;
+}
+
+
+static PaError InitializeWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers,
+ unsigned long hostBufferCount,
+ PaSampleFormat hostSampleFormat,
+ unsigned long framesPerHostBuffer,
+ PaWinMmeDeviceAndChannelCount *devices,
+ int isInput )
+{
+ PaError result = paNoError;
+ MMRESULT mmresult;
+ WAVEHDR *deviceWaveHeaders;
+ signed int i, j;
+
+ /* for error cleanup we expect that InitializeSingleDirectionHandlesAndBuffers()
+ has already been called to zero some fields */
+
+
+ /* allocate an array of pointers to arrays of wave headers, one array of
+ wave headers per device */
+ handlesAndBuffers->waveHeaders = (WAVEHDR**)PaUtil_AllocateMemory( sizeof(WAVEHDR*) * handlesAndBuffers->deviceCount );
+ if( !handlesAndBuffers->waveHeaders )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ for( i = 0; i < (signed int)handlesAndBuffers->deviceCount; ++i )
+ handlesAndBuffers->waveHeaders[i] = 0;
+
+ handlesAndBuffers->bufferCount = hostBufferCount;
+
+ for( i = 0; i < (signed int)handlesAndBuffers->deviceCount; ++i )
+ {
+ int bufferBytes = Pa_GetSampleSize( hostSampleFormat ) *
+ framesPerHostBuffer * devices[i].channelCount;
+ if( bufferBytes < 0 )
+ {
+ result = paInternalError;
+ goto error;
+ }
+
+ /* Allocate an array of wave headers for device i */
+ deviceWaveHeaders = (WAVEHDR *) PaUtil_AllocateMemory( sizeof(WAVEHDR)*hostBufferCount );
+ if( !deviceWaveHeaders )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ for( j=0; j < (signed int)hostBufferCount; ++j )
+ deviceWaveHeaders[j].lpData = 0;
+
+ handlesAndBuffers->waveHeaders[i] = deviceWaveHeaders;
+
+ /* Allocate a buffer for each wave header */
+ for( j=0; j < (signed int)hostBufferCount; ++j )
+ {
+ deviceWaveHeaders[j].lpData = (char *)PaUtil_AllocateMemory( bufferBytes );
+ if( !deviceWaveHeaders[j].lpData )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+ deviceWaveHeaders[j].dwBufferLength = bufferBytes;
+ deviceWaveHeaders[j].dwUser = 0xFFFFFFFF; /* indicates that *PrepareHeader() has not yet been called, for error clean up code */
+
+ if( isInput )
+ {
+ mmresult = waveInPrepareHeader( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
+ if( mmresult != MMSYSERR_NOERROR )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+ goto error;
+ }
+ }
+ else /* output */
+ {
+ mmresult = waveOutPrepareHeader( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
+ if( mmresult != MMSYSERR_NOERROR )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+ goto error;
+ }
+ }
+ deviceWaveHeaders[j].dwUser = devices[i].channelCount;
+ }
+ }
+
+ return result;
+
+error:
+ TerminateWaveHeaders( handlesAndBuffers, isInput );
+
+ return result;
+}
+
+
+static void TerminateWaveHeaders( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers, int isInput )
+{
+ signed int i, j;
+ WAVEHDR *deviceWaveHeaders;
+
+ if( handlesAndBuffers->waveHeaders )
+ {
+ for( i = handlesAndBuffers->deviceCount-1; i >= 0 ; --i )
+ {
+ deviceWaveHeaders = handlesAndBuffers->waveHeaders[i]; /* wave headers for device i */
+ if( deviceWaveHeaders )
+ {
+ for( j = handlesAndBuffers->bufferCount-1; j >= 0; --j )
+ {
+ if( deviceWaveHeaders[j].lpData )
+ {
+ if( deviceWaveHeaders[j].dwUser != 0xFFFFFFFF )
+ {
+ if( isInput )
+ waveInUnprepareHeader( ((HWAVEIN*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
+ else
+ waveOutUnprepareHeader( ((HWAVEOUT*)handlesAndBuffers->waveHandles)[i], &deviceWaveHeaders[j], sizeof(WAVEHDR) );
+ }
+
+ PaUtil_FreeMemory( deviceWaveHeaders[j].lpData );
+ }
+ }
+
+ PaUtil_FreeMemory( deviceWaveHeaders );
+ }
+ }
+
+ PaUtil_FreeMemory( handlesAndBuffers->waveHeaders );
+ handlesAndBuffers->waveHeaders = 0;
+ }
+}
+
+
+
+/* PaWinMmeStream - a stream data structure specifically for this implementation */
+/* note that struct PaWinMmeStream is typedeffed to PaWinMmeStream above. */
+struct PaWinMmeStream
+{
+ PaUtilStreamRepresentation streamRepresentation;
+ PaUtilCpuLoadMeasurer cpuLoadMeasurer;
+ PaUtilBufferProcessor bufferProcessor;
+
+ int primeStreamUsingCallback;
+
+ PaWinMmeSingleDirectionHandlesAndBuffers input;
+ PaWinMmeSingleDirectionHandlesAndBuffers output;
+
+ /* Processing thread management -------------- */
+ HANDLE abortEvent;
+ HANDLE processingThread;
+ DWORD processingThreadId;
+
+ char throttleProcessingThreadOnOverload; /* 0 -> don't throtte, non-0 -> throttle */
+ int processingThreadPriority;
+ int highThreadPriority;
+ int throttledThreadPriority;
+ unsigned long throttledSleepMsecs;
+
+ int isStopped;
+ volatile int isActive;
+ volatile int stopProcessing; /* stop thread once existing buffers have been returned */
+ volatile int abortProcessing; /* stop thread immediately */
+
+ DWORD allBuffersDurationMs; /* used to calculate timeouts */
+};
+
+/* updates deviceCount if PaWinMmeUseMultipleDevices is used */
+
+static PaError ValidateWinMmeSpecificStreamInfo(
+ const PaStreamParameters *streamParameters,
+ const PaWinMmeStreamInfo *streamInfo,
+ char *throttleProcessingThreadOnOverload,
+ unsigned long *deviceCount )
+{
+ if( streamInfo )
+ {
+ if( streamInfo->size != sizeof( PaWinMmeStreamInfo )
+ || streamInfo->version != 1 )
+ {
+ return paIncompatibleHostApiSpecificStreamInfo;
+ }
+
+ if( streamInfo->flags & paWinMmeDontThrottleOverloadedProcessingThread )
+ *throttleProcessingThreadOnOverload = 0;
+
+ if( streamInfo->flags & paWinMmeUseMultipleDevices )
+ {
+ if( streamParameters->device != paUseHostApiSpecificDeviceSpecification )
+ return paInvalidDevice;
+
+ *deviceCount = streamInfo->deviceCount;
+ }
+ }
+
+ return paNoError;
+}
+
+static PaError RetrieveDevicesFromStreamParameters(
+ struct PaUtilHostApiRepresentation *hostApi,
+ const PaStreamParameters *streamParameters,
+ const PaWinMmeStreamInfo *streamInfo,
+ PaWinMmeDeviceAndChannelCount *devices,
+ unsigned long deviceCount )
+{
+ PaError result = paNoError;
+ unsigned int i;
+ int totalChannelCount;
+ PaDeviceIndex hostApiDevice;
+
+ if( streamInfo && streamInfo->flags & paWinMmeUseMultipleDevices )
+ {
+ totalChannelCount = 0;
+ for( i=0; i < deviceCount; ++i )
+ {
+ /* validate that the device number is within range */
+ result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDevice,
+ streamInfo->devices[i].device, hostApi );
+ if( result != paNoError )
+ return result;
+
+ devices[i].device = hostApiDevice;
+ devices[i].channelCount = streamInfo->devices[i].channelCount;
+
+ totalChannelCount += devices[i].channelCount;
+ }
+
+ if( totalChannelCount != streamParameters->channelCount )
+ {
+ /* channelCount must match total channels specified by multiple devices */
+ return paInvalidChannelCount; /* REVIEW use of this error code */
+ }
+ }
+ else
+ {
+ devices[0].device = streamParameters->device;
+ devices[0].channelCount = streamParameters->channelCount;
+ }
+
+ return result;
+}
+
+static PaError ValidateInputChannelCounts(
+ struct PaUtilHostApiRepresentation *hostApi,
+ PaWinMmeDeviceAndChannelCount *devices,
+ unsigned long deviceCount )
+{
+ unsigned int i;
+
+ for( i=0; i < deviceCount; ++i )
+ {
+ if( devices[i].channelCount < 1 || devices[i].channelCount
+ > hostApi->deviceInfos[ devices[i].device ]->maxInputChannels )
+ return paInvalidChannelCount;
+ }
+
+ return paNoError;
+}
+
+static PaError ValidateOutputChannelCounts(
+ struct PaUtilHostApiRepresentation *hostApi,
+ PaWinMmeDeviceAndChannelCount *devices,
+ unsigned long deviceCount )
+{
+ unsigned int i;
+
+ for( i=0; i < deviceCount; ++i )
+ {
+ if( devices[i].channelCount < 1 || devices[i].channelCount
+ > hostApi->deviceInfos[ devices[i].device ]->maxOutputChannels )
+ return paInvalidChannelCount;
+ }
+
+ return paNoError;
+}
+
+
+/* the following macros are intended to improve the readability of the following code */
+#define PA_IS_INPUT_STREAM_( stream ) ( stream ->input.waveHandles )
+#define PA_IS_OUTPUT_STREAM_( stream ) ( stream ->output.waveHandles )
+#define PA_IS_FULL_DUPLEX_STREAM_( stream ) ( stream ->input.waveHandles && stream ->output.waveHandles )
+#define PA_IS_HALF_DUPLEX_STREAM_( stream ) ( !(stream ->input.waveHandles && stream ->output.waveHandles) )
+
+static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
+ PaStream** s,
+ const PaStreamParameters *inputParameters,
+ const PaStreamParameters *outputParameters,
+ double sampleRate,
+ unsigned long framesPerBuffer,
+ PaStreamFlags streamFlags,
+ PaStreamCallback *streamCallback,
+ void *userData )
+{
+ PaError result;
+ PaWinMmeHostApiRepresentation *winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
+ PaWinMmeStream *stream = 0;
+ int bufferProcessorIsInitialized = 0;
+ int streamRepresentationIsInitialized = 0;
+ PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
+ int inputChannelCount, outputChannelCount;
+ PaSampleFormat inputSampleFormat, outputSampleFormat;
+ double suggestedInputLatency, suggestedOutputLatency;
+ PaWinMmeStreamInfo *inputStreamInfo, *outputStreamInfo;
+ unsigned long framesPerHostInputBuffer;
+ unsigned long hostInputBufferCount;
+ unsigned long framesPerHostOutputBuffer;
+ unsigned long hostOutputBufferCount;
+ unsigned long framesPerBufferProcessorCall;
+ PaWinMmeDeviceAndChannelCount *inputDevices = 0; /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */
+ unsigned long inputDeviceCount = 0;
+ PaWinMmeDeviceAndChannelCount *outputDevices = 0;
+ unsigned long outputDeviceCount = 0; /* contains all devices and channel counts as local host api ids, even when PaWinMmeUseMultipleDevices is not used */
+ char throttleProcessingThreadOnOverload = 1;
+
+
+ if( inputParameters )
+ {
+ inputChannelCount = inputParameters->channelCount;
+ inputSampleFormat = inputParameters->sampleFormat;
+ suggestedInputLatency = inputParameters->suggestedLatency;
+
+ inputDeviceCount = 1;
+
+ /* validate input hostApiSpecificStreamInfo */
+ inputStreamInfo = (PaWinMmeStreamInfo*)inputParameters->hostApiSpecificStreamInfo;
+ result = ValidateWinMmeSpecificStreamInfo( inputParameters, inputStreamInfo,
+ &throttleProcessingThreadOnOverload,
+ &inputDeviceCount );
+ if( result != paNoError ) return result;
+
+ inputDevices = (PaWinMmeDeviceAndChannelCount*)alloca( sizeof(PaWinMmeDeviceAndChannelCount) * inputDeviceCount );
+ if( !inputDevices ) return paInsufficientMemory;
+
+ result = RetrieveDevicesFromStreamParameters( hostApi, inputParameters, inputStreamInfo, inputDevices, inputDeviceCount );
+ if( result != paNoError ) return result;
+
+ result = ValidateInputChannelCounts( hostApi, inputDevices, inputDeviceCount );
+ if( result != paNoError ) return result;
+
+ hostInputSampleFormat =
+ PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, inputSampleFormat );
+ }
+ else
+ {
+ inputChannelCount = 0;
+ inputSampleFormat = 0;
+ suggestedInputLatency = 0.;
+ inputStreamInfo = 0;
+ hostInputSampleFormat = 0;
+ }
+
+
+ if( outputParameters )
+ {
+ outputChannelCount = outputParameters->channelCount;
+ outputSampleFormat = outputParameters->sampleFormat;
+ suggestedOutputLatency = outputParameters->suggestedLatency;
+
+ outputDeviceCount = 1;
+
+ /* validate output hostApiSpecificStreamInfo */
+ outputStreamInfo = (PaWinMmeStreamInfo*)outputParameters->hostApiSpecificStreamInfo;
+ result = ValidateWinMmeSpecificStreamInfo( outputParameters, outputStreamInfo,
+ &throttleProcessingThreadOnOverload,
+ &outputDeviceCount );
+ if( result != paNoError ) return result;
+
+ outputDevices = (PaWinMmeDeviceAndChannelCount*)alloca( sizeof(PaWinMmeDeviceAndChannelCount) * outputDeviceCount );
+ if( !outputDevices ) return paInsufficientMemory;
+
+ result = RetrieveDevicesFromStreamParameters( hostApi, outputParameters, outputStreamInfo, outputDevices, outputDeviceCount );
+ if( result != paNoError ) return result;
+
+ result = ValidateOutputChannelCounts( hostApi, outputDevices, outputDeviceCount );
+ if( result != paNoError ) return result;
+
+ hostOutputSampleFormat =
+ PaUtil_SelectClosestAvailableFormat( paInt16 /* native formats */, outputSampleFormat );
+ }
+ else
+ {
+ outputChannelCount = 0;
+ outputSampleFormat = 0;
+ outputStreamInfo = 0;
+ hostOutputSampleFormat = 0;
+ suggestedOutputLatency = 0.;
+ }
+
+
+ /*
+ IMPLEMENT ME:
+ - alter sampleRate to a close allowable rate if possible / necessary
+ */
+
+
+ /* validate platform specific flags */
+ if( (streamFlags & paPlatformSpecificFlags) != 0 )
+ return paInvalidFlag; /* unexpected platform specific flag */
+
+
+ result = CalculateBufferSettings( &framesPerHostInputBuffer, &hostInputBufferCount,
+ &framesPerHostOutputBuffer, &hostOutputBufferCount,
+ inputChannelCount, hostInputSampleFormat, suggestedInputLatency, inputStreamInfo,
+ outputChannelCount, hostOutputSampleFormat, suggestedOutputLatency, outputStreamInfo,
+ sampleRate, framesPerBuffer );
+ if( result != paNoError ) goto error;
+
+
+ stream = (PaWinMmeStream*)PaUtil_AllocateMemory( sizeof(PaWinMmeStream) );
+ if( !stream )
+ {
+ result = paInsufficientMemory;
+ goto error;
+ }
+
+ InitializeSingleDirectionHandlesAndBuffers( &stream->input );
+ InitializeSingleDirectionHandlesAndBuffers( &stream->output );
+
+ stream->abortEvent = 0;
+ stream->processingThread = 0;
+
+ stream->throttleProcessingThreadOnOverload = throttleProcessingThreadOnOverload;
+
+ PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
+ ( (streamCallback)
+ ? &winMmeHostApi->callbackStreamInterface
+ : &winMmeHostApi->blockingStreamInterface ),
+ streamCallback, userData );
+ streamRepresentationIsInitialized = 1;
+
+ PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
+
+
+ if( inputParameters && outputParameters ) /* full duplex */
+ {
+ if( framesPerHostInputBuffer < framesPerHostOutputBuffer )
+ {
+ assert( (framesPerHostOutputBuffer % framesPerHostInputBuffer) == 0 ); /* CalculateBufferSettings() should guarantee this condition */
+
+ framesPerBufferProcessorCall = framesPerHostInputBuffer;
+ }
+ else
+ {
+ assert( (framesPerHostInputBuffer % framesPerHostOutputBuffer) == 0 ); /* CalculateBufferSettings() should guarantee this condition */
+
+ framesPerBufferProcessorCall = framesPerHostOutputBuffer;
+ }
+ }
+ else if( inputParameters )
+ {
+ framesPerBufferProcessorCall = framesPerHostInputBuffer;
+ }
+ else if( outputParameters )
+ {
+ framesPerBufferProcessorCall = framesPerHostOutputBuffer;
+ }
+
+ stream->input.framesPerBuffer = framesPerHostInputBuffer;
+ stream->output.framesPerBuffer = framesPerHostOutputBuffer;
+
+ result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
+ inputChannelCount, inputSampleFormat, hostInputSampleFormat,
+ outputChannelCount, outputSampleFormat, hostOutputSampleFormat,
+ sampleRate, streamFlags, framesPerBuffer,
+ framesPerBufferProcessorCall, paUtilFixedHostBufferSize,
+ streamCallback, userData );
+ if( result != paNoError ) goto error;
+
+ bufferProcessorIsInitialized = 1;
+
+ stream->streamRepresentation.streamInfo.inputLatency =
+ (double)(PaUtil_GetBufferProcessorInputLatency(&stream->bufferProcessor)
+ +(framesPerHostInputBuffer * (hostInputBufferCount-1))) / sampleRate;
+ stream->streamRepresentation.streamInfo.outputLatency =
+ (double)(PaUtil_GetBufferProcessorOutputLatency(&stream->bufferProcessor)
+ +(framesPerHostOutputBuffer * (hostOutputBufferCount-1))) / sampleRate;
+ stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
+
+ stream->primeStreamUsingCallback = ( (streamFlags&paPrimeOutputBuffersUsingStreamCallback) && streamCallback ) ? 1 : 0;
+
+ /* time to sleep when throttling due to >100% cpu usage.
+ -a quater of a buffer's duration */
+ stream->throttledSleepMsecs =
+ (unsigned long)(stream->bufferProcessor.framesPerHostBuffer *
+ stream->bufferProcessor.samplePeriod * .25 * 1000);
+
+ stream->isStopped = 1;
+ stream->isActive = 0;
+
+
+ /* for maximum compatibility with multi-device multichannel drivers,
+ we first open all devices, then we prepare all buffers, finally
+ we start all devices ( in StartStream() ). teardown in reverse order.
+ */
+
+ if( inputParameters )
+ {
+ result = InitializeWaveHandles( winMmeHostApi, &stream->input,
+ stream->bufferProcessor.bytesPerHostInputSample, sampleRate,
+ inputDevices, inputDeviceCount, 1 /* isInput */ );
+ if( result != paNoError ) goto error;
+ }
+
+ if( outputParameters )
+ {
+ result = InitializeWaveHandles( winMmeHostApi, &stream->output,
+ stream->bufferProcessor.bytesPerHostOutputSample, sampleRate,
+ outputDevices, outputDeviceCount, 0 /* isInput */ );
+ if( result != paNoError ) goto error;
+ }
+
+ if( inputParameters )
+ {
+ result = InitializeWaveHeaders( &stream->input, hostInputBufferCount,
+ hostInputSampleFormat, framesPerHostInputBuffer, inputDevices, 1 /* isInput */ );
+ if( result != paNoError ) goto error;
+ }
+
+ if( outputParameters )
+ {
+ result = InitializeWaveHeaders( &stream->output, hostOutputBufferCount,
+ hostOutputSampleFormat, framesPerHostOutputBuffer, outputDevices, 0 /* not isInput */ );
+ if( result != paNoError ) goto error;
+
+ stream->allBuffersDurationMs = (DWORD) (1000.0 * (framesPerHostOutputBuffer * stream->output.bufferCount) / sampleRate);
+ }
+ else
+ {
+ stream->allBuffersDurationMs = (DWORD) (1000.0 * (framesPerHostInputBuffer * stream->input.bufferCount) / sampleRate);
+ }
+
+
+ if( streamCallback )
+ {
+ /* abort event is only needed for callback streams */
+ result = CreateEventWithPaError( &stream->abortEvent, NULL, TRUE, FALSE, NULL );
+ if( result != paNoError ) goto error;
+ }
+
+ *s = (PaStream*)stream;
+
+ return result;
+
+error:
+
+ if( stream )
+ {
+ if( stream->abortEvent )
+ CloseHandle( stream->abortEvent );
+
+ TerminateWaveHeaders( &stream->output, 0 /* not isInput */ );
+ TerminateWaveHeaders( &stream->input, 1 /* isInput */ );
+
+ TerminateWaveHandles( &stream->output, 0 /* not isInput */, 1 /* currentlyProcessingAnError */ );
+ TerminateWaveHandles( &stream->input, 1 /* isInput */, 1 /* currentlyProcessingAnError */ );
+
+ if( bufferProcessorIsInitialized )
+ PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+
+ if( streamRepresentationIsInitialized )
+ PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+
+ PaUtil_FreeMemory( stream );
+ }
+
+ return result;
+}
+
+
+/* return non-zero if all current buffers are done */
+static int BuffersAreDone( WAVEHDR **waveHeaders, unsigned int deviceCount, int bufferIndex )
+{
+ unsigned int i;
+
+ for( i=0; i < deviceCount; ++i )
+ {
+ if( !(waveHeaders[i][ bufferIndex ].dwFlags & WHDR_DONE) )
+ {
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+static int CurrentInputBuffersAreDone( PaWinMmeStream *stream )
+{
+ return BuffersAreDone( stream->input.waveHeaders, stream->input.deviceCount, stream->input.currentBufferIndex );
+}
+
+static int CurrentOutputBuffersAreDone( PaWinMmeStream *stream )
+{
+ return BuffersAreDone( stream->output.waveHeaders, stream->output.deviceCount, stream->output.currentBufferIndex );
+}
+
+
+/* return non-zero if any buffers are queued */
+static int NoBuffersAreQueued( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )
+{
+ unsigned int i, j;
+
+ if( handlesAndBuffers->waveHandles )
+ {
+ for( i=0; i < handlesAndBuffers->bufferCount; ++i )
+ {
+ for( j=0; j < handlesAndBuffers->deviceCount; ++j )
+ {
+ if( !( handlesAndBuffers->waveHeaders[ j ][ i ].dwFlags & WHDR_DONE) )
+ {
+ return 0;
+ }
+ }
+ }
+ }
+
+ return 1;
+}
+
+
+#define PA_CIRCULAR_INCREMENT_( current, max )\
+ ( (((current) + 1) >= (max)) ? (0) : (current+1) )
+
+#define PA_CIRCULAR_DECREMENT_( current, max )\
+ ( ((current) == 0) ? ((max)-1) : (current-1) )
+
+
+static signed long GetAvailableFrames( PaWinMmeSingleDirectionHandlesAndBuffers *handlesAndBuffers )
+{
+ signed long result = 0;
+ unsigned int i;
+
+ if( BuffersAreDone( handlesAndBuffers->waveHeaders, handlesAndBuffers->deviceCount, handlesAndBuffers->currentBufferIndex ) )
+ {
+ /* we could calculate the following in O(1) if we kept track of the
+ last done buffer */
+ result = handlesAndBuffers->framesPerBuffer - handlesAndBuffers->framesUsedInCurrentBuffer;
+
+ i = PA_CIRCULAR_INCREMENT_( handlesAndBuffers->currentBufferIndex, handlesAndBuffers->bufferCount );
+ while( i != handlesAndBuffers->currentBufferIndex )
+ {
+ if( BuffersAreDone( handlesAndBuffers->waveHeaders, handlesAndBuffers->deviceCount, i ) )
+ {
+ result += handlesAndBuffers->framesPerBuffer;
+ i = PA_CIRCULAR_INCREMENT_( i, handlesAndBuffers->bufferCount );
+ }
+ else
+ break;
+ }
+ }
+
+ return result;
+}
+
+
+static PaError AdvanceToNextInputBuffer( PaWinMmeStream *stream )
+{
+ PaError result = paNoError;
+ MMRESULT mmresult;
+ unsigned int i;
+
+ for( i=0; i < stream->input.deviceCount; ++i )
+ {
+ mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[i],
+ &stream->input.waveHeaders[i][ stream->input.currentBufferIndex ],
+ sizeof(WAVEHDR) );
+ if( mmresult != MMSYSERR_NOERROR )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+ }
+ }
+
+ stream->input.currentBufferIndex =
+ PA_CIRCULAR_INCREMENT_( stream->input.currentBufferIndex, stream->input.bufferCount );
+
+ stream->input.framesUsedInCurrentBuffer = 0;
+
+ return result;
+}
+
+
+static PaError AdvanceToNextOutputBuffer( PaWinMmeStream *stream )
+{
+ PaError result = paNoError;
+ MMRESULT mmresult;
+ unsigned int i;
+
+ for( i=0; i < stream->output.deviceCount; ++i )
+ {
+ mmresult = waveOutWrite( ((HWAVEOUT*)stream->output.waveHandles)[i],
+ &stream->output.waveHeaders[i][ stream->output.currentBufferIndex ],
+ sizeof(WAVEHDR) );
+ if( mmresult != MMSYSERR_NOERROR )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+ }
+ }
+
+ stream->output.currentBufferIndex =
+ PA_CIRCULAR_INCREMENT_( stream->output.currentBufferIndex, stream->output.bufferCount );
+
+ stream->output.framesUsedInCurrentBuffer = 0;
+
+ return result;
+}
+
+
+/* requeue all but the most recent input with the driver. Used for catching
+ up after a total input buffer underrun */
+static PaError CatchUpInputBuffers( PaWinMmeStream *stream )
+{
+ PaError result = paNoError;
+ unsigned int i;
+
+ for( i=0; i < stream->input.bufferCount - 1; ++i )
+ {
+ result = AdvanceToNextInputBuffer( stream );
+ if( result != paNoError )
+ break;
+ }
+
+ return result;
+}
+
+
+/* take the most recent output and duplicate it to all other output buffers
+ and requeue them. Used for catching up after a total output buffer underrun.
+*/
+static PaError CatchUpOutputBuffers( PaWinMmeStream *stream )
+{
+ PaError result = paNoError;
+ unsigned int i, j;
+ unsigned int previousBufferIndex =
+ PA_CIRCULAR_DECREMENT_( stream->output.currentBufferIndex, stream->output.bufferCount );
+
+ for( i=0; i < stream->output.bufferCount - 1; ++i )
+ {
+ for( j=0; j < stream->output.deviceCount; ++j )
+ {
+ if( stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].lpData
+ != stream->output.waveHeaders[j][ previousBufferIndex ].lpData )
+ {
+ CopyMemory( stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].lpData,
+ stream->output.waveHeaders[j][ previousBufferIndex ].lpData,
+ stream->output.waveHeaders[j][ stream->output.currentBufferIndex ].dwBufferLength );
+ }
+ }
+
+ result = AdvanceToNextOutputBuffer( stream );
+ if( result != paNoError )
+ break;
+ }
+
+ return result;
+}
+
+
+static DWORD WINAPI ProcessingThreadProc( void *pArg )
+{
+ PaWinMmeStream *stream = (PaWinMmeStream *)pArg;
+ HANDLE events[3];
+ int eventCount = 0;
+ DWORD result = paNoError;
+ DWORD waitResult;
+ DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);
+ int hostBuffersAvailable;
+ signed int hostInputBufferIndex, hostOutputBufferIndex;
+ PaStreamCallbackFlags statusFlags;
+ int callbackResult;
+ int done = 0;
+ unsigned int channel, i;
+ unsigned long framesProcessed;
+
+ /* prepare event array for call to WaitForMultipleObjects() */
+ if( stream->input.bufferEvent )
+ events[eventCount++] = stream->input.bufferEvent;
+ if( stream->output.bufferEvent )
+ events[eventCount++] = stream->output.bufferEvent;
+ events[eventCount++] = stream->abortEvent;
+
+ statusFlags = 0; /** @todo support paInputUnderflow, paOutputOverflow and paNeverDropInput */
+
+ /* loop until something causes us to stop */
+ do{
+ /* wait for MME to signal that a buffer is available, or for
+ the PA abort event to be signaled.
+
+ When this indicates that one or more buffers are available
+ NoBuffersAreQueued() and Current*BuffersAreDone are used below to
+ poll for additional done buffers. NoBuffersAreQueued() will fail
+ to identify an underrun/overflow if the driver doesn't mark all done
+ buffers prior to signalling the event. Some drivers do this
+ (eg RME Digi96, and others don't eg VIA PC 97 input). This isn't a
+ huge problem, it just means that we won't always be able to detect
+ underflow/overflow.
+ */
+ waitResult = WaitForMultipleObjects( eventCount, events, FALSE /* wait all = FALSE */, timeout );
+ if( waitResult == WAIT_FAILED )
+ {
+ result = paUnanticipatedHostError;
+ /** @todo FIXME/REVIEW: can't return host error info from an asyncronous thread */
+ done = 1;
+ }
+ else if( waitResult == WAIT_TIMEOUT )
+ {
+ /* if a timeout is encountered, continue */
+ }
+
+ if( stream->abortProcessing )
+ {
+ /* Pa_AbortStream() has been called, stop processing immediately */
+ done = 1;
+ }
+ else if( stream->stopProcessing )
+ {
+ /* Pa_StopStream() has been called or the user callback returned
+ non-zero, processing will continue until all output buffers
+ are marked as done. The stream will stop immediately if it
+ is input-only.
+ */
+
+ if( PA_IS_OUTPUT_STREAM_(stream) )
+ {
+ if( NoBuffersAreQueued( &stream->output ) )
+ done = 1; /* Will cause thread to return. */
+ }
+ else
+ {
+ /* input only stream */
+ done = 1; /* Will cause thread to return. */
+ }
+ }
+ else
+ {
+ hostBuffersAvailable = 1;
+
+ /* process all available host buffers */
+ do
+ {
+ hostInputBufferIndex = -1;
+ hostOutputBufferIndex = -1;
+
+ if( PA_IS_INPUT_STREAM_(stream) )
+ {
+ if( CurrentInputBuffersAreDone( stream ) )
+ {
+ if( NoBuffersAreQueued( &stream->input ) )
+ {
+ /** @todo
+ if all of the other buffers are also ready then
+ we discard all but the most recent. This is an
+ input buffer overflow. FIXME: these buffers should
+ be passed to the callback in a paNeverDropInput
+ stream.
+
+ note that it is also possible for an input overflow
+ to happen while the callback is processing a buffer.
+ that is handled further down.
+ */
+ result = CatchUpInputBuffers( stream );
+ if( result != paNoError )
+ done = 1;
+
+ statusFlags |= paInputOverflow;
+ }
+
+ hostInputBufferIndex = stream->input.currentBufferIndex;
+ }
+ }
+
+ if( PA_IS_OUTPUT_STREAM_(stream) )
+ {
+ if( CurrentOutputBuffersAreDone( stream ) )
+ {
+ /* ok, we have an output buffer */
+
+ if( NoBuffersAreQueued( &stream->output ) )
+ {
+ /*
+ if all of the other buffers are also ready, catch up by copying
+ the most recently generated buffer into all but one of the output
+ buffers.
+
+ note that this catch up code only handles the case where all
+ buffers have been played out due to this thread not having
+ woken up at all. a more common case occurs when this thread
+ is woken up, processes one buffer, but takes too long, and as
+ a result all the other buffers have become un-queued. that
+ case is handled further down.
+ */
+
+ result = CatchUpOutputBuffers( stream );
+ if( result != paNoError )
+ done = 1;
+
+ statusFlags |= paOutputUnderflow;
+ }
+
+ hostOutputBufferIndex = stream->output.currentBufferIndex;
+ }
+ }
+
+
+ if( (PA_IS_FULL_DUPLEX_STREAM_(stream) && hostInputBufferIndex != -1 && hostOutputBufferIndex != -1) ||
+ (PA_IS_HALF_DUPLEX_STREAM_(stream) && ( hostInputBufferIndex != -1 || hostOutputBufferIndex != -1 ) ) )
+ {
+ PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement inputBufferAdcTime */
+
+
+ if( PA_IS_OUTPUT_STREAM_(stream) )
+ {
+ /* set timeInfo.currentTime and calculate timeInfo.outputBufferDacTime
+ from the current wave out position */
+ MMTIME mmtime;
+ double timeBeforeGetPosition, timeAfterGetPosition;
+ double time;
+ long framesInBufferRing;
+ long writePosition;
+ long playbackPosition;
+ HWAVEOUT firstWaveOutDevice = ((HWAVEOUT*)stream->output.waveHandles)[0];
+
+ mmtime.wType = TIME_SAMPLES;
+ timeBeforeGetPosition = PaUtil_GetTime();
+ waveOutGetPosition( firstWaveOutDevice, &mmtime, sizeof(MMTIME) );
+ timeAfterGetPosition = PaUtil_GetTime();
+
+ timeInfo.currentTime = timeAfterGetPosition;
+
+ /* approximate time at which wave out position was measured
+ as half way between timeBeforeGetPosition and timeAfterGetPosition */
+ time = timeBeforeGetPosition + (timeAfterGetPosition - timeBeforeGetPosition) * .5;
+
+ framesInBufferRing = stream->output.bufferCount * stream->bufferProcessor.framesPerHostBuffer;
+ playbackPosition = mmtime.u.sample % framesInBufferRing;
+
+ writePosition = stream->output.currentBufferIndex * stream->bufferProcessor.framesPerHostBuffer
+ + stream->output.framesUsedInCurrentBuffer;
+
+ if( playbackPosition >= writePosition ){
+ timeInfo.outputBufferDacTime =
+ time + ((double)( writePosition + (framesInBufferRing - playbackPosition) ) * stream->bufferProcessor.samplePeriod );
+ }else{
+ timeInfo.outputBufferDacTime =
+ time + ((double)( writePosition - playbackPosition ) * stream->bufferProcessor.samplePeriod );
+ }
+ }
+
+
+ PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
+
+ PaUtil_BeginBufferProcessing( &stream->bufferProcessor, &timeInfo, statusFlags );
+
+ /* reset status flags once they have been passed to the buffer processor */
+ statusFlags = 0;
+
+ if( PA_IS_INPUT_STREAM_(stream) )
+ {
+ PaUtil_SetInputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );
+
+ channel = 0;
+ for( i=0; i<stream->input.deviceCount; ++i )
+ {
+ /* we have stored the number of channels in the buffer in dwUser */
+ int channelCount = stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;
+
+ PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel,
+ stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData +
+ stream->input.framesUsedInCurrentBuffer * channelCount *
+ stream->bufferProcessor.bytesPerHostInputSample,
+ channelCount );
+
+
+ channel += channelCount;
+ }
+ }
+
+ if( PA_IS_OUTPUT_STREAM_(stream) )
+ {
+ PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );
+
+ channel = 0;
+ for( i=0; i<stream->output.deviceCount; ++i )
+ {
+ /* we have stored the number of channels in the buffer in dwUser */
+ int channelCount = stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
+
+ PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
+ stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
+ stream->output.framesUsedInCurrentBuffer * channelCount *
+ stream->bufferProcessor.bytesPerHostOutputSample,
+ channelCount );
+
+ channel += channelCount;
+ }
+ }
+
+ callbackResult = paContinue;
+ framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
+
+ stream->input.framesUsedInCurrentBuffer += framesProcessed;
+ stream->output.framesUsedInCurrentBuffer += framesProcessed;
+
+ PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
+
+ if( callbackResult == paContinue )
+ {
+ /* nothing special to do */
+ }
+ else if( callbackResult == paAbort )
+ {
+ stream->abortProcessing = 1;
+ done = 1;
+ /** @todo FIXME: should probably reset the output device immediately once the callback returns paAbort */
+ result = paNoError;
+ }
+ else
+ {
+ /* User callback has asked us to stop with paComplete or other non-zero value */
+ stream->stopProcessing = 1; /* stop once currently queued audio has finished */
+ result = paNoError;
+ }
+
+
+ if( PA_IS_INPUT_STREAM_(stream)
+ && stream->stopProcessing == 0 && stream->abortProcessing == 0
+ && stream->input.framesUsedInCurrentBuffer == stream->input.framesPerBuffer )
+ {
+ if( NoBuffersAreQueued( &stream->input ) )
+ {
+ /** @todo need to handle PaNeverDropInput here where necessary */
+ result = CatchUpInputBuffers( stream );
+ if( result != paNoError )
+ done = 1;
+
+ statusFlags |= paInputOverflow;
+ }
+
+ result = AdvanceToNextInputBuffer( stream );
+ if( result != paNoError )
+ done = 1;
+ }
+
+
+ if( PA_IS_OUTPUT_STREAM_(stream) && !stream->abortProcessing )
+ {
+ if( stream->stopProcessing &&
+ stream->output.framesUsedInCurrentBuffer < stream->output.framesPerBuffer )
+ {
+ /* zero remaining samples in output output buffer and flush */
+
+ stream->output.framesUsedInCurrentBuffer += PaUtil_ZeroOutput( &stream->bufferProcessor,
+ stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );
+
+ /* we send the entire buffer to the output devices, but we could
+ just send a partial buffer, rather than zeroing the unused
+ samples.
+ */
+ }
+
+ if( stream->output.framesUsedInCurrentBuffer == stream->output.framesPerBuffer )
+ {
+ /* check for underflow before enquing the just-generated buffer,
+ but recover from underflow after enquing it. This ensures
+ that the most recent audio segment is repeated */
+ int outputUnderflow = NoBuffersAreQueued( &stream->output );
+
+ result = AdvanceToNextOutputBuffer( stream );
+ if( result != paNoError )
+ done = 1;
+
+ if( outputUnderflow && !done && !stream->stopProcessing )
+ {
+ /* Recover from underflow in the case where the
+ underflow occured while processing the buffer
+ we just finished */
+
+ result = CatchUpOutputBuffers( stream );
+ if( result != paNoError )
+ done = 1;
+
+ statusFlags |= paOutputUnderflow;
+ }
+ }
+ }
+
+ if( stream->throttleProcessingThreadOnOverload != 0 )
+ {
+ if( stream->stopProcessing || stream->abortProcessing )
+ {
+ if( stream->processingThreadPriority != stream->highThreadPriority )
+ {
+ SetThreadPriority( stream->processingThread, stream->highThreadPriority );
+ stream->processingThreadPriority = stream->highThreadPriority;
+ }
+ }
+ else if( PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ) > 1. )
+ {
+ if( stream->processingThreadPriority != stream->throttledThreadPriority )
+ {
+ SetThreadPriority( stream->processingThread, stream->throttledThreadPriority );
+ stream->processingThreadPriority = stream->throttledThreadPriority;
+ }
+
+ /* sleep to give other processes a go */
+ Sleep( stream->throttledSleepMsecs );
+ }
+ else
+ {
+ if( stream->processingThreadPriority != stream->highThreadPriority )
+ {
+ SetThreadPriority( stream->processingThread, stream->highThreadPriority );
+ stream->processingThreadPriority = stream->highThreadPriority;
+ }
+ }
+ }
+ }
+ else
+ {
+ hostBuffersAvailable = 0;
+ }
+ }
+ while( hostBuffersAvailable &&
+ stream->stopProcessing == 0 &&
+ stream->abortProcessing == 0 &&
+ !done );
+ }
+ }
+ while( !done );
+
+ stream->isActive = 0;
+
+ if( stream->streamRepresentation.streamFinishedCallback != 0 )
+ stream->streamRepresentation.streamFinishedCallback( stream->streamRepresentation.userData );
+
+ PaUtil_ResetCpuLoadMeasurer( &stream->cpuLoadMeasurer );
+
+ return result;
+}
+
+
+/*
+ When CloseStream() is called, the multi-api layer ensures that
+ the stream has already been stopped or aborted.
+*/
+static PaError CloseStream( PaStream* s )
+{
+ PaError result;
+ PaWinMmeStream *stream = (PaWinMmeStream*)s;
+
+ result = CloseHandleWithPaError( stream->abortEvent );
+ if( result != paNoError ) goto error;
+
+ TerminateWaveHeaders( &stream->output, 0 /* not isInput */ );
+ TerminateWaveHeaders( &stream->input, 1 /* isInput */ );
+
+ TerminateWaveHandles( &stream->output, 0 /* not isInput */, 0 /* not currentlyProcessingAnError */ );
+ TerminateWaveHandles( &stream->input, 1 /* isInput */, 0 /* not currentlyProcessingAnError */ );
+
+ PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
+ PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
+ PaUtil_FreeMemory( stream );
+
+error:
+ /** @todo REVIEW: what is the best way to clean up a stream if an error is detected? */
+ return result;
+}
+
+
+static PaError StartStream( PaStream *s )
+{
+ PaError result;
+ PaWinMmeStream *stream = (PaWinMmeStream*)s;
+ MMRESULT mmresult;
+ unsigned int i, j;
+ int callbackResult;
+ unsigned int channel;
+ unsigned long framesProcessed;
+ PaStreamCallbackTimeInfo timeInfo = {0,0,0}; /** @todo implement this for stream priming */
+
+ PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
+
+ if( PA_IS_INPUT_STREAM_(stream) )
+ {
+ for( i=0; i<stream->input.bufferCount; ++i )
+ {
+ for( j=0; j<stream->input.deviceCount; ++j )
+ {
+ mmresult = waveInAddBuffer( ((HWAVEIN*)stream->input.waveHandles)[j], &stream->input.waveHeaders[j][i], sizeof(WAVEHDR) );
+ if( mmresult != MMSYSERR_NOERROR )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+ goto error;
+ }
+ }
+ }
+ stream->input.currentBufferIndex = 0;
+ stream->input.framesUsedInCurrentBuffer = 0;
+ }
+
+ if( PA_IS_OUTPUT_STREAM_(stream) )
+ {
+ for( i=0; i<stream->output.deviceCount; ++i )
+ {
+ if( (mmresult = waveOutPause( ((HWAVEOUT*)stream->output.waveHandles)[i] )) != MMSYSERR_NOERROR )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+ goto error;
+ }
+ }
+
+ for( i=0; i<stream->output.bufferCount; ++i )
+ {
+ if( stream->primeStreamUsingCallback )
+ {
+
+ stream->output.framesUsedInCurrentBuffer = 0;
+ do{
+
+ PaUtil_BeginBufferProcessing( &stream->bufferProcessor,
+ &timeInfo,
+ paPrimingOutput | ((stream->input.bufferCount > 0 ) ? paInputUnderflow : 0));
+
+ if( stream->input.bufferCount > 0 )
+ PaUtil_SetNoInput( &stream->bufferProcessor );
+
+ PaUtil_SetOutputFrameCount( &stream->bufferProcessor, 0 /* default to host buffer size */ );
+
+ channel = 0;
+ for( j=0; j<stream->output.deviceCount; ++j )
+ {
+ /* we have stored the number of channels in the buffer in dwUser */
+ int channelCount = stream->output.waveHeaders[j][i].dwUser;
+
+ PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
+ stream->output.waveHeaders[j][i].lpData +
+ stream->output.framesUsedInCurrentBuffer * channelCount *
+ stream->bufferProcessor.bytesPerHostOutputSample,
+ channelCount );
+
+ /* we have stored the number of channels in the buffer in dwUser */
+ channel += channelCount;
+ }
+
+ callbackResult = paContinue;
+ framesProcessed = PaUtil_EndBufferProcessing( &stream->bufferProcessor, &callbackResult );
+ stream->output.framesUsedInCurrentBuffer += framesProcessed;
+
+ if( callbackResult != paContinue )
+ {
+ /** @todo fix this, what do we do if callback result is non-zero during stream
+ priming?
+
+ for complete: play out primed waveHeaders as usual
+ for abort: clean up immediately.
+ */
+ }
+
+ }while( stream->output.framesUsedInCurrentBuffer != stream->output.framesPerBuffer );
+
+ }
+ else
+ {
+ for( j=0; j<stream->output.deviceCount; ++j )
+ {
+ ZeroMemory( stream->output.waveHeaders[j][i].lpData, stream->output.waveHeaders[j][i].dwBufferLength );
+ }
+ }
+
+ /* we queue all channels of a single buffer frame (accross all
+ devices, because some multidevice multichannel drivers work
+ better this way */
+ for( j=0; j<stream->output.deviceCount; ++j )
+ {
+ mmresult = waveOutWrite( ((HWAVEOUT*)stream->output.waveHandles)[j], &stream->output.waveHeaders[j][i], sizeof(WAVEHDR) );
+ if( mmresult != MMSYSERR_NOERROR )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+ goto error;
+ }
+ }
+ }
+ stream->output.currentBufferIndex = 0;
+ stream->output.framesUsedInCurrentBuffer = 0;
+ }
+
+
+ stream->isStopped = 0;
+ stream->isActive = 1;
+ stream->stopProcessing = 0;
+ stream->abortProcessing = 0;
+
+ result = ResetEventWithPaError( stream->input.bufferEvent );
+ if( result != paNoError ) goto error;
+
+ result = ResetEventWithPaError( stream->output.bufferEvent );
+ if( result != paNoError ) goto error;
+
+
+ if( stream->streamRepresentation.streamCallback )
+ {
+ /* callback stream */
+
+ result = ResetEventWithPaError( stream->abortEvent );
+ if( result != paNoError ) goto error;
+
+ /* Create thread that waits for audio buffers to be ready for processing. */
+ stream->processingThread = CreateThread( 0, 0, ProcessingThreadProc, stream, 0, &stream->processingThreadId );
+ if( !stream->processingThread )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
+ goto error;
+ }
+
+ /** @todo could have mme specific stream parameters to allow the user
+ to set the callback thread priorities */
+ stream->highThreadPriority = THREAD_PRIORITY_TIME_CRITICAL;
+ stream->throttledThreadPriority = THREAD_PRIORITY_NORMAL;
+
+ if( !SetThreadPriority( stream->processingThread, stream->highThreadPriority ) )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_SYSTEM_ERROR( GetLastError() );
+ goto error;
+ }
+ stream->processingThreadPriority = stream->highThreadPriority;
+ }
+ else
+ {
+ /* blocking read/write stream */
+
+ }
+
+ if( PA_IS_INPUT_STREAM_(stream) )
+ {
+ for( i=0; i < stream->input.deviceCount; ++i )
+ {
+ mmresult = waveInStart( ((HWAVEIN*)stream->input.waveHandles)[i] );
+ PA_DEBUG(("Pa_StartStream: waveInStart returned = 0x%X.\n", mmresult));
+ if( mmresult != MMSYSERR_NOERROR )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+ goto error;
+ }
+ }
+ }
+
+ if( PA_IS_OUTPUT_STREAM_(stream) )
+ {
+ for( i=0; i < stream->output.deviceCount; ++i )
+ {
+ if( (mmresult = waveOutRestart( ((HWAVEOUT*)stream->output.waveHandles)[i] )) != MMSYSERR_NOERROR )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+ goto error;
+ }
+ }
+ }
+
+ return result;
+
+error:
+ /** @todo FIXME: implement recovery as best we can
+ This should involve rolling back to a state as-if this function had never been called
+ */
+ return result;
+}
+
+
+static PaError StopStream( PaStream *s )
+{
+ PaError result = paNoError;
+ PaWinMmeStream *stream = (PaWinMmeStream*)s;
+ int timeout;
+ DWORD waitResult;
+ MMRESULT mmresult;
+ signed int hostOutputBufferIndex;
+ unsigned int channel, waitCount, i;
+
+ /** @todo
+ REVIEW: the error checking in this function needs review. the basic
+ idea is to return from this function in a known state - for example
+ there is no point avoiding calling waveInReset just because
+ the thread times out.
+ */
+
+ if( stream->processingThread )
+ {
+ /* callback stream */
+
+ /* Tell processing thread to stop generating more data and to let current data play out. */
+ stream->stopProcessing = 1;
+
+ /* Calculate timeOut longer than longest time it could take to return all buffers. */
+ timeout = (int)(stream->allBuffersDurationMs * 1.5);
+ if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )
+ timeout = PA_MME_MIN_TIMEOUT_MSEC_;
+
+ PA_DEBUG(("WinMME StopStream: waiting for background thread.\n"));
+
+ waitResult = WaitForSingleObject( stream->processingThread, timeout );
+ if( waitResult == WAIT_TIMEOUT )
+ {
+ /* try to abort */
+ stream->abortProcessing = 1;
+ SetEvent( stream->abortEvent );
+ waitResult = WaitForSingleObject( stream->processingThread, timeout );
+ if( waitResult == WAIT_TIMEOUT )
+ {
+ PA_DEBUG(("WinMME StopStream: timed out while waiting for background thread to finish.\n"));
+ result = paTimedOut;
+ }
+ }
+
+ CloseHandle( stream->processingThread );
+ stream->processingThread = NULL;
+ }
+ else
+ {
+ /* blocking read / write stream */
+
+ if( PA_IS_OUTPUT_STREAM_(stream) )
+ {
+ if( stream->output.framesUsedInCurrentBuffer > 0 )
+ {
+ /* there are still unqueued frames in the current buffer, so flush them */
+
+ hostOutputBufferIndex = stream->output.currentBufferIndex;
+
+ PaUtil_SetOutputFrameCount( &stream->bufferProcessor,
+ stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );
+
+ channel = 0;
+ for( i=0; i<stream->output.deviceCount; ++i )
+ {
+ /* we have stored the number of channels in the buffer in dwUser */
+ int channelCount = stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
+
+ PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
+ stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
+ stream->output.framesUsedInCurrentBuffer * channelCount *
+ stream->bufferProcessor.bytesPerHostOutputSample,
+ channelCount );
+
+ channel += channelCount;
+ }
+
+ PaUtil_ZeroOutput( &stream->bufferProcessor,
+ stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );
+
+ /* we send the entire buffer to the output devices, but we could
+ just send a partial buffer, rather than zeroing the unused
+ samples.
+ */
+ AdvanceToNextOutputBuffer( stream );
+ }
+
+
+ timeout = (stream->allBuffersDurationMs / stream->output.bufferCount) + 1;
+ if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )
+ timeout = PA_MME_MIN_TIMEOUT_MSEC_;
+
+ waitCount = 0;
+ while( !NoBuffersAreQueued( &stream->output ) && waitCount <= stream->output.bufferCount )
+ {
+ /* wait for MME to signal that a buffer is available */
+ waitResult = WaitForSingleObject( stream->output.bufferEvent, timeout );
+ if( waitResult == WAIT_FAILED )
+ {
+ break;
+ }
+ else if( waitResult == WAIT_TIMEOUT )
+ {
+ /* keep waiting */
+ }
+
+ ++waitCount;
+ }
+ }
+ }
+
+ if( PA_IS_OUTPUT_STREAM_(stream) )
+ {
+ for( i =0; i < stream->output.deviceCount; ++i )
+ {
+ mmresult = waveOutReset( ((HWAVEOUT*)stream->output.waveHandles)[i] );
+ if( mmresult != MMSYSERR_NOERROR )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+ }
+ }
+ }
+
+ if( PA_IS_INPUT_STREAM_(stream) )
+ {
+ for( i=0; i < stream->input.deviceCount; ++i )
+ {
+ mmresult = waveInReset( ((HWAVEIN*)stream->input.waveHandles)[i] );
+ if( mmresult != MMSYSERR_NOERROR )
+ {
+ result = paUnanticipatedHostError;
+ PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+ }
+ }
+ }
+
+ stream->isStopped = 1;
+ stream->isActive = 0;
+
+ return result;
+}
+
+
+static PaError AbortStream( PaStream *s )
+{
+ PaError result = paNoError;
+ PaWinMmeStream *stream = (PaWinMmeStream*)s;
+ int timeout;
+ DWORD waitResult;
+ MMRESULT mmresult;
+ unsigned int i;
+
+ /** @todo
+ REVIEW: the error checking in this function needs review. the basic
+ idea is to return from this function in a known state - for example
+ there is no point avoiding calling waveInReset just because
+ the thread times out.
+ */
+
+ if( stream->processingThread )
+ {
+ /* callback stream */
+
+ /* Tell processing thread to abort immediately */
+ stream->abortProcessing = 1;
+ SetEvent( stream->abortEvent );
+ }
+
+
+ if( PA_IS_OUTPUT_STREAM_(stream) )
+ {
+ for( i =0; i < stream->output.deviceCount; ++i )
+ {
+ mmresult = waveOutReset( ((HWAVEOUT*)stream->output.waveHandles)[i] );
+ if( mmresult != MMSYSERR_NOERROR )
+ {
+ PA_MME_SET_LAST_WAVEOUT_ERROR( mmresult );
+ return paUnanticipatedHostError;
+ }
+ }
+ }
+
+ if( PA_IS_INPUT_STREAM_(stream) )
+ {
+ for( i=0; i < stream->input.deviceCount; ++i )
+ {
+ mmresult = waveInReset( ((HWAVEIN*)stream->input.waveHandles)[i] );
+ if( mmresult != MMSYSERR_NOERROR )
+ {
+ PA_MME_SET_LAST_WAVEIN_ERROR( mmresult );
+ return paUnanticipatedHostError;
+ }
+ }
+ }
+
+
+ if( stream->processingThread )
+ {
+ /* callback stream */
+
+ PA_DEBUG(("WinMME AbortStream: waiting for background thread.\n"));
+
+ /* Calculate timeOut longer than longest time it could take to return all buffers. */
+ timeout = (int)(stream->allBuffersDurationMs * 1.5);
+ if( timeout < PA_MME_MIN_TIMEOUT_MSEC_ )
+ timeout = PA_MME_MIN_TIMEOUT_MSEC_;
+
+ waitResult = WaitForSingleObject( stream->processingThread, timeout );
+ if( waitResult == WAIT_TIMEOUT )
+ {
+ PA_DEBUG(("WinMME AbortStream: timed out while waiting for background thread to finish.\n"));
+ return paTimedOut;
+ }
+
+ CloseHandle( stream->processingThread );
+ stream->processingThread = NULL;
+ }
+
+ stream->isStopped = 1;
+ stream->isActive = 0;
+
+ return result;
+}
+
+
+static PaError IsStreamStopped( PaStream *s )
+{
+ PaWinMmeStream *stream = (PaWinMmeStream*)s;
+
+ return stream->isStopped;
+}
+
+
+static PaError IsStreamActive( PaStream *s )
+{
+ PaWinMmeStream *stream = (PaWinMmeStream*)s;
+
+ return stream->isActive;
+}
+
+
+static PaTime GetStreamTime( PaStream *s )
+{
+ (void) s; /* unused parameter */
+
+ return PaUtil_GetTime();
+}
+
+
+static double GetStreamCpuLoad( PaStream* s )
+{
+ PaWinMmeStream *stream = (PaWinMmeStream*)s;
+
+ return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
+}
+
+
+/*
+ As separate stream interfaces are used for blocking and callback
+ streams, the following functions can be guaranteed to only be called
+ for blocking streams.
+*/
+
+static PaError ReadStream( PaStream* s,
+ void *buffer,
+ unsigned long frames )
+{
+ PaError result = paNoError;
+ PaWinMmeStream *stream = (PaWinMmeStream*)s;
+ void *userBuffer;
+ unsigned long framesRead = 0;
+ unsigned long framesProcessed;
+ signed int hostInputBufferIndex;
+ DWORD waitResult;
+ DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);
+ unsigned int channel, i;
+
+ if( PA_IS_INPUT_STREAM_(stream) )
+ {
+ /* make a local copy of the user buffer pointer(s). this is necessary
+ because PaUtil_CopyInput() advances these pointers every time
+ it is called.
+ */
+ if( stream->bufferProcessor.userInputIsInterleaved )
+ {
+ userBuffer = buffer;
+ }
+ else
+ {
+ userBuffer = alloca( sizeof(void*) * stream->bufferProcessor.inputChannelCount );
+ if( !userBuffer )
+ return paInsufficientMemory;
+ for( i = 0; i<stream->bufferProcessor.inputChannelCount; ++i )
+ ((void**)userBuffer)[i] = ((void**)buffer)[i];
+ }
+
+ do{
+ if( CurrentInputBuffersAreDone( stream ) )
+ {
+ if( NoBuffersAreQueued( &stream->input ) )
+ {
+ /** @todo REVIEW: consider what to do if the input overflows.
+ do we requeue all of the buffers? should we be running
+ a thread to make sure they are always queued? */
+
+ result = paInputOverflowed;
+ }
+
+ hostInputBufferIndex = stream->input.currentBufferIndex;
+
+ PaUtil_SetInputFrameCount( &stream->bufferProcessor,
+ stream->input.framesPerBuffer - stream->input.framesUsedInCurrentBuffer );
+
+ channel = 0;
+ for( i=0; i<stream->input.deviceCount; ++i )
+ {
+ /* we have stored the number of channels in the buffer in dwUser */
+ int channelCount = stream->input.waveHeaders[i][ hostInputBufferIndex ].dwUser;
+
+ PaUtil_SetInterleavedInputChannels( &stream->bufferProcessor, channel,
+ stream->input.waveHeaders[i][ hostInputBufferIndex ].lpData +
+ stream->input.framesUsedInCurrentBuffer * channelCount *
+ stream->bufferProcessor.bytesPerHostInputSample,
+ channelCount );
+
+ channel += channelCount;
+ }
+
+ framesProcessed = PaUtil_CopyInput( &stream->bufferProcessor, &userBuffer, frames - framesRead );
+
+ stream->input.framesUsedInCurrentBuffer += framesProcessed;
+ if( stream->input.framesUsedInCurrentBuffer == stream->input.framesPerBuffer )
+ {
+ result = AdvanceToNextInputBuffer( stream );
+ if( result != paNoError )
+ break;
+ }
+
+ framesRead += framesProcessed;
+
+ }else{
+ /* wait for MME to signal that a buffer is available */
+ waitResult = WaitForSingleObject( stream->input.bufferEvent, timeout );
+ if( waitResult == WAIT_FAILED )
+ {
+ result = paUnanticipatedHostError;
+ break;
+ }
+ else if( waitResult == WAIT_TIMEOUT )
+ {
+ /* if a timeout is encountered, continue,
+ perhaps we should give up eventually
+ */
+ }
+ }
+ }while( framesRead < frames );
+ }
+ else
+ {
+ result = paCanNotReadFromAnOutputOnlyStream;
+ }
+
+ return result;
+}
+
+
+static PaError WriteStream( PaStream* s,
+ const void *buffer,
+ unsigned long frames )
+{
+ PaError result = paNoError;
+ PaWinMmeStream *stream = (PaWinMmeStream*)s;
+ const void *userBuffer;
+ unsigned long framesWritten = 0;
+ unsigned long framesProcessed;
+ signed int hostOutputBufferIndex;
+ DWORD waitResult;
+ DWORD timeout = (unsigned long)(stream->allBuffersDurationMs * 0.5);
+ unsigned int channel, i;
+
+
+ if( PA_IS_OUTPUT_STREAM_(stream) )
+ {
+ /* make a local copy of the user buffer pointer(s). this is necessary
+ because PaUtil_CopyOutput() advances these pointers every time
+ it is called.
+ */
+ if( stream->bufferProcessor.userOutputIsInterleaved )
+ {
+ userBuffer = buffer;
+ }
+ else
+ {
+ userBuffer = alloca( sizeof(void*) * stream->bufferProcessor.outputChannelCount );
+ if( !userBuffer )
+ return paInsufficientMemory;
+ for( i = 0; i<stream->bufferProcessor.outputChannelCount; ++i )
+ ((const void**)userBuffer)[i] = ((const void**)buffer)[i];
+ }
+
+ do{
+ if( CurrentOutputBuffersAreDone( stream ) )
+ {
+ if( NoBuffersAreQueued( &stream->output ) )
+ {
+ /** @todo REVIEW: consider what to do if the output
+ underflows. do we requeue all the existing buffers with
+ zeros? should we run a separate thread to keep the buffers
+ enqueued at all times? */
+
+ result = paOutputUnderflowed;
+ }
+
+ hostOutputBufferIndex = stream->output.currentBufferIndex;
+
+ PaUtil_SetOutputFrameCount( &stream->bufferProcessor,
+ stream->output.framesPerBuffer - stream->output.framesUsedInCurrentBuffer );
+
+ channel = 0;
+ for( i=0; i<stream->output.deviceCount; ++i )
+ {
+ /* we have stored the number of channels in the buffer in dwUser */
+ int channelCount = stream->output.waveHeaders[i][ hostOutputBufferIndex ].dwUser;
+
+ PaUtil_SetInterleavedOutputChannels( &stream->bufferProcessor, channel,
+ stream->output.waveHeaders[i][ hostOutputBufferIndex ].lpData +
+ stream->output.framesUsedInCurrentBuffer * channelCount *
+ stream->bufferProcessor.bytesPerHostOutputSample,
+ channelCount );
+
+ channel += channelCount;
+ }
+
+ framesProcessed = PaUtil_CopyOutput( &stream->bufferProcessor, &userBuffer, frames - framesWritten );
+
+ stream->output.framesUsedInCurrentBuffer += framesProcessed;
+ if( stream->output.framesUsedInCurrentBuffer == stream->output.framesPerBuffer )
+ {
+ result = AdvanceToNextOutputBuffer( stream );
+ if( result != paNoError )
+ break;
+ }
+
+ framesWritten += framesProcessed;
+ }
+ else
+ {
+ /* wait for MME to signal that a buffer is available */
+ waitResult = WaitForSingleObject( stream->output.bufferEvent, timeout );
+ if( waitResult == WAIT_FAILED )
+ {
+ result = paUnanticipatedHostError;
+ break;
+ }
+ else if( waitResult == WAIT_TIMEOUT )
+ {
+ /* if a timeout is encountered, continue,
+ perhaps we should give up eventually
+ */
+ }
+ }
+ }while( framesWritten < frames );
+ }
+ else
+ {
+ result = paCanNotWriteToAnInputOnlyStream;
+ }
+
+ return result;
+}
+
+
+static signed long GetStreamReadAvailable( PaStream* s )
+{
+ PaWinMmeStream *stream = (PaWinMmeStream*)s;
+
+ if( PA_IS_INPUT_STREAM_(stream) )
+ return GetAvailableFrames( &stream->input );
+ else
+ return paCanNotReadFromAnOutputOnlyStream;
+}
+
+
+static signed long GetStreamWriteAvailable( PaStream* s )
+{
+ PaWinMmeStream *stream = (PaWinMmeStream*)s;
+
+ if( PA_IS_OUTPUT_STREAM_(stream) )
+ return GetAvailableFrames( &stream->output );
+ else
+ return paCanNotWriteToAnInputOnlyStream;
+}
+
+
+/* NOTE: the following functions are MME-stream specific, and are called directly
+ by client code. We need to check for many more error conditions here because
+ we don't have the benefit of pa_front.c's parameter checking.
+*/
+
+static PaError GetWinMMEStreamPointer( PaWinMmeStream **stream, PaStream *s )
+{
+ PaError result;
+ PaUtilHostApiRepresentation *hostApi;
+ PaWinMmeHostApiRepresentation *winMmeHostApi;
+
+ result = PaUtil_ValidateStreamPointer( s );
+ if( result != paNoError )
+ return result;
+
+ result = PaUtil_GetHostApiRepresentation( &hostApi, paMME );
+ if( result != paNoError )
+ return result;
+
+ winMmeHostApi = (PaWinMmeHostApiRepresentation*)hostApi;
+
+ /* note, the following would be easier if there was a generic way of testing
+ that a stream belongs to a specific host API */
+
+ if( PA_STREAM_REP( s )->streamInterface == &winMmeHostApi->callbackStreamInterface
+ || PA_STREAM_REP( s )->streamInterface == &winMmeHostApi->blockingStreamInterface )
+ {
+ /* s is a WinMME stream */
+ *stream = (PaWinMmeStream *)s;
+ return paNoError;
+ }
+ else
+ {
+ return paIncompatibleStreamHostApi;
+ }
+}
+
+
+int PaWinMME_GetStreamInputHandleCount( PaStream* s )
+{
+ PaWinMmeStream *stream;
+ PaError result = GetWinMMEStreamPointer( &stream, s );
+
+ if( result == paNoError )
+ return (PA_IS_INPUT_STREAM_(stream)) ? stream->input.deviceCount : 0;
+ else
+ return result;
+}
+
+
+HWAVEIN PaWinMME_GetStreamInputHandle( PaStream* s, int handleIndex )
+{
+ PaWinMmeStream *stream;
+ PaError result = GetWinMMEStreamPointer( &stream, s );
+
+ if( result == paNoError
+ && PA_IS_INPUT_STREAM_(stream)
+ && handleIndex >= 0
+ && (unsigned int)handleIndex < stream->input.deviceCount )
+ return ((HWAVEIN*)stream->input.waveHandles)[handleIndex];
+ else
+ return 0;
+}
+
+
+int PaWinMME_GetStreamOutputHandleCount( PaStream* s)
+{
+ PaWinMmeStream *stream;
+ PaError result = GetWinMMEStreamPointer( &stream, s );
+
+ if( result == paNoError )
+ return (PA_IS_OUTPUT_STREAM_(stream)) ? stream->output.deviceCount : 0;
+ else
+ return result;
+}
+
+
+HWAVEOUT PaWinMME_GetStreamOutputHandle( PaStream* s, int handleIndex )
+{
+ PaWinMmeStream *stream;
+ PaError result = GetWinMMEStreamPointer( &stream, s );
+
+ if( result == paNoError
+ && PA_IS_OUTPUT_STREAM_(stream)
+ && handleIndex >= 0
+ && (unsigned int)handleIndex < stream->output.deviceCount )
+ return ((HWAVEOUT*)stream->output.waveHandles)[handleIndex];
+ else
+ return 0;
+}
+
+
+
+
+
diff --git a/pd/portaudio/src/os/mac_osx/pa_mac_hostapis.c b/pd/portaudio/src/os/mac_osx/pa_mac_hostapis.c
new file mode 100644
index 00000000..e3e45294
--- /dev/null
+++ b/pd/portaudio/src/os/mac_osx/pa_mac_hostapis.c
@@ -0,0 +1,87 @@
+/*
+ * $Id: pa_mac_hostapis.c,v 1.1 2007-08-18 23:49:33 millerpuckette Exp $
+ * Portable Audio I/O Library Macintosh initialization table
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup macosx_src
+Mac OS host API initialization function table.
+*/
+
+
+#include "pa_hostapi.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+ PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+ PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+ PaError PaMacSm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+ PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+ PaError PaMacAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+
+PaUtilHostApiInitializer *paHostApiInitializers[] =
+{
+#ifdef PA_USE_COREAUDIO
+ PaMacCore_Initialize,
+#endif
+
+#ifdef PA_USE_SM
+ PaMacSm_Initialize,
+#endif
+
+#ifdef PA_USE_JACK
+ PaJack_Initialize,
+#endif
+
+#ifdef PA_USE_ASIO
+ PaMacAsio_Initialize,
+#endif
+
+ PaSkeleton_Initialize, /* just for testing */
+
+ 0 /* NULL terminated array */
+};
+
+
+int paDefaultHostApiIndex = 0;
diff --git a/pd/portaudio/src/os/unix/pa_unix_hostapis.c b/pd/portaudio/src/os/unix/pa_unix_hostapis.c
new file mode 100644
index 00000000..f2439986
--- /dev/null
+++ b/pd/portaudio/src/os/unix/pa_unix_hostapis.c
@@ -0,0 +1,78 @@
+/*
+ * $Id: pa_unix_hostapis.c,v 1.1 2007-08-18 23:49:33 millerpuckette Exp $
+ * Portable Audio I/O Library UNIX initialization table
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup unix_src
+*/
+
+#include "pa_hostapi.h"
+
+PaError PaJack_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaAlsa_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaOSS_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+/* Added for IRIX, Pieter, oct 2, 2003: */
+PaError PaSGI_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+/* Linux AudioScience HPI */
+PaError PaAsiHpi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+
+PaUtilHostApiInitializer *paHostApiInitializers[] =
+ {
+#ifdef PA_USE_OSS
+ PaOSS_Initialize,
+#endif
+
+#ifdef PA_USE_ALSA
+ PaAlsa_Initialize,
+#endif
+
+#ifdef PA_USE_JACK
+ PaJack_Initialize,
+#endif
+ /* Added for IRIX, Pieter, oct 2, 2003: */
+#ifdef PA_USE_SGI
+ PaSGI_Initialize,
+#endif
+
+#ifdef PA_USE_ASIHPI
+ PaAsiHpi_Initialize,
+#endif
+ 0 /* NULL terminated array */
+ };
+
+int paDefaultHostApiIndex = 0;
diff --git a/pd/portaudio/src/os/unix/pa_unix_util.c b/pd/portaudio/src/os/unix/pa_unix_util.c
new file mode 100644
index 00000000..489b062e
--- /dev/null
+++ b/pd/portaudio/src/os/unix/pa_unix_util.c
@@ -0,0 +1,666 @@
+/*
+ * $Id: pa_unix_util.c,v 1.1 2007-08-18 23:49:33 millerpuckette Exp $
+ * Portable Audio I/O Library
+ * UNIX platform-specific support functions
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2000 Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup unix_src
+*/
+
+#include <pthread.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <time.h>
+#include <sys/time.h>
+#include <assert.h>
+#include <string.h> /* For memset */
+#include <math.h>
+#include <errno.h>
+
+#include "pa_util.h"
+#include "pa_unix_util.h"
+#include "pa_debugprint.h"
+
+/*
+ Track memory allocations to avoid leaks.
+ */
+
+#if PA_TRACK_MEMORY
+static int numAllocations_ = 0;
+#endif
+
+
+void *PaUtil_AllocateMemory( long size )
+{
+ void *result = malloc( size );
+
+#if PA_TRACK_MEMORY
+ if( result != NULL ) numAllocations_ += 1;
+#endif
+ return result;
+}
+
+
+void PaUtil_FreeMemory( void *block )
+{
+ if( block != NULL )
+ {
+ free( block );
+#if PA_TRACK_MEMORY
+ numAllocations_ -= 1;
+#endif
+
+ }
+}
+
+
+int PaUtil_CountCurrentlyAllocatedBlocks( void )
+{
+#if PA_TRACK_MEMORY
+ return numAllocations_;
+#else
+ return 0;
+#endif
+}
+
+
+void Pa_Sleep( long msec )
+{
+#ifdef HAVE_NANOSLEEP
+ struct timespec req = {0}, rem = {0};
+ PaTime time = msec / 1.e3;
+ req.tv_sec = (time_t)time;
+ assert(time - req.tv_sec < 1.0);
+ req.tv_nsec = (long)((time - req.tv_sec) * 1.e9);
+ nanosleep(&req, &rem);
+ /* XXX: Try sleeping the remaining time (contained in rem) if interrupted by a signal? */
+#else
+ while( msec > 999 ) /* For OpenBSD and IRIX, argument */
+ { /* to usleep must be < 1000000. */
+ usleep( 999000 );
+ msec -= 999;
+ }
+ usleep( msec * 1000 );
+#endif
+}
+
+/* *** NOT USED YET: ***
+static int usePerformanceCounter_;
+static double microsecondsPerTick_;
+*/
+
+void PaUtil_InitializeClock( void )
+{
+ /* TODO */
+}
+
+
+PaTime PaUtil_GetTime( void )
+{
+#ifdef HAVE_CLOCK_GETTIME
+ struct timespec tp;
+ clock_gettime(CLOCK_REALTIME, &tp);
+ return (PaTime)(tp.tv_sec + tp.tv_nsec / 1.e9);
+#else
+ struct timeval tv;
+ gettimeofday( &tv, NULL );
+ return (PaTime) tv.tv_usec / 1000000. + tv.tv_sec;
+#endif
+}
+
+PaError PaUtil_InitializeThreading( PaUtilThreading *threading )
+{
+ (void) paUtilErr_;
+ return paNoError;
+}
+
+void PaUtil_TerminateThreading( PaUtilThreading *threading )
+{
+}
+
+PaError PaUtil_StartThreading( PaUtilThreading *threading, void *(*threadRoutine)(void *), void *data )
+{
+ pthread_create( &threading->callbackThread, NULL, threadRoutine, data );
+ return paNoError;
+}
+
+PaError PaUtil_CancelThreading( PaUtilThreading *threading, int wait, PaError *exitResult )
+{
+ PaError result = paNoError;
+ void *pret;
+
+ if( exitResult )
+ *exitResult = paNoError;
+
+ /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */
+ if( !wait )
+ pthread_cancel( threading->callbackThread ); /* XXX: Safe to call this if the thread has exited on its own? */
+ pthread_join( threading->callbackThread, &pret );
+
+#ifdef PTHREAD_CANCELED
+ if( pret && PTHREAD_CANCELED != pret )
+#else
+ /* !wait means the thread may have been canceled */
+ if( pret && wait )
+#endif
+ {
+ if( exitResult )
+ *exitResult = *(PaError *) pret;
+ free( pret );
+ }
+
+ return result;
+}
+
+/* Threading */
+/* paUnixMainThread
+ * We have to be a bit careful with defining this global variable,
+ * as explained below. */
+#ifdef __apple__
+/* apple/gcc has a "problem" with global vars and dynamic libs.
+ Initializing it seems to fix the problem.
+ Described a bit in this thread:
+ http://gcc.gnu.org/ml/gcc/2005-06/msg00179.html
+*/
+pthread_t paUnixMainThread = 0;
+#else
+/*pthreads are opaque. We don't know that asigning it an int value
+ always makes sense, so we don't initialize it unless we have to.*/
+pthread_t paUnixMainThread = 0;
+#endif
+
+PaError PaUnixThreading_Initialize()
+{
+ paUnixMainThread = pthread_self();
+ return paNoError;
+}
+
+static PaError BoostPriority( PaUnixThread* self )
+{
+ PaError result = paNoError;
+ struct sched_param spm = { 0 };
+ /* Priority should only matter between contending FIFO threads? */
+ spm.sched_priority = 1;
+
+ assert( self );
+
+ if( pthread_setschedparam( self->thread, SCHED_FIFO, &spm ) != 0 )
+ {
+ PA_UNLESS( errno == EPERM, paInternalError ); /* Lack permission to raise priority */
+ PA_DEBUG(( "Failed bumping priority\n" ));
+ result = 0;
+ }
+ else
+ {
+ result = 1; /* Success */
+ }
+error:
+ return result;
+}
+
+PaError PaUnixThread_New( PaUnixThread* self, void* (*threadFunc)( void* ), void* threadArg, PaTime waitForChild,
+ int rtSched )
+{
+ PaError result = paNoError;
+ pthread_attr_t attr;
+ int started = 0;
+
+ memset( self, 0, sizeof (PaUnixThread) );
+ PaUnixMutex_Initialize( &self->mtx );
+ PA_ASSERT_CALL( pthread_cond_init( &self->cond, NULL ), 0 );
+
+ self->parentWaiting = 0 != waitForChild;
+
+ /* Spawn thread */
+
+/* Temporarily disabled since we should test during configuration for presence of required mman.h header */
+#if 0
+#if defined _POSIX_MEMLOCK && (_POSIX_MEMLOCK != -1)
+ if( rtSched )
+ {
+ if( mlockall( MCL_CURRENT | MCL_FUTURE ) < 0 )
+ {
+ int savedErrno = errno; /* In case errno gets overwritten */
+ assert( savedErrno != EINVAL ); /* Most likely a programmer error */
+ PA_UNLESS( (savedErrno == EPERM), paInternalError );
+ PA_DEBUG(( "%s: Failed locking memory\n", __FUNCTION__ ));
+ }
+ else
+ PA_DEBUG(( "%s: Successfully locked memory\n", __FUNCTION__ ));
+ }
+#endif
+#endif
+
+ PA_UNLESS( !pthread_attr_init( &attr ), paInternalError );
+ /* Priority relative to other processes */
+ PA_UNLESS( !pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ), paInternalError );
+
+ PA_UNLESS( !pthread_create( &self->thread, &attr, threadFunc, threadArg ), paInternalError );
+ started = 1;
+
+ if( rtSched )
+ {
+#if 0
+ if( self->useWatchdog )
+ {
+ int err;
+ struct sched_param wdSpm = { 0 };
+ /* Launch watchdog, watchdog sets callback thread priority */
+ int prio = PA_MIN( self->rtPrio + 4, sched_get_priority_max( SCHED_FIFO ) );
+ wdSpm.sched_priority = prio;
+
+ PA_UNLESS( !pthread_attr_init( &attr ), paInternalError );
+ PA_UNLESS( !pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED ), paInternalError );
+ PA_UNLESS( !pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ), paInternalError );
+ PA_UNLESS( !pthread_attr_setschedpolicy( &attr, SCHED_FIFO ), paInternalError );
+ PA_UNLESS( !pthread_attr_setschedparam( &attr, &wdSpm ), paInternalError );
+ if( (err = pthread_create( &self->watchdogThread, &attr, &WatchdogFunc, self )) )
+ {
+ PA_UNLESS( err == EPERM, paInternalError );
+ /* Permission error, go on without realtime privileges */
+ PA_DEBUG(( "Failed bumping priority\n" ));
+ }
+ else
+ {
+ int policy;
+ self->watchdogRunning = 1;
+ PA_ENSURE_SYSTEM( pthread_getschedparam( self->watchdogThread, &policy, &wdSpm ), 0 );
+ /* Check if priority is right, policy could potentially differ from SCHED_FIFO (but that's alright) */
+ if( wdSpm.sched_priority != prio )
+ {
+ PA_DEBUG(( "Watchdog priority not set correctly (%d)\n", wdSpm.sched_priority ));
+ PA_ENSURE( paInternalError );
+ }
+ }
+ }
+ else
+#endif
+ PA_ENSURE( BoostPriority( self ) );
+
+ {
+ int policy;
+ struct sched_param spm;
+ pthread_getschedparam(self->thread, &policy, &spm);
+ }
+ }
+
+ if( self->parentWaiting )
+ {
+ PaTime till;
+ struct timespec ts;
+ int res = 0;
+ PaTime now;
+
+ PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) );
+
+ /* Wait for stream to be started */
+ now = PaUtil_GetTime();
+ till = now + waitForChild;
+
+ while( self->parentWaiting && !res )
+ {
+ if( waitForChild > 0 )
+ {
+ ts.tv_sec = (time_t) floor( till );
+ ts.tv_nsec = (long) ((till - floor( till )) * 1e9);
+ res = pthread_cond_timedwait( &self->cond, &self->mtx.mtx, &ts );
+ }
+ else
+ {
+ res = pthread_cond_wait( &self->cond, &self->mtx.mtx );
+ }
+ }
+
+ PA_ENSURE( PaUnixMutex_Unlock( &self->mtx ) );
+
+ PA_UNLESS( !res || ETIMEDOUT == res, paInternalError );
+ PA_DEBUG(( "%s: Waited for %g seconds for stream to start\n", __FUNCTION__, PaUtil_GetTime() - now ));
+ if( ETIMEDOUT == res )
+ {
+ PA_ENSURE( paTimedOut );
+ }
+ }
+
+end:
+ return result;
+error:
+ if( started )
+ {
+ PaUnixThread_Terminate( self, 0, NULL );
+ }
+
+ goto end;
+}
+
+PaError PaUnixThread_Terminate( PaUnixThread* self, int wait, PaError* exitResult )
+{
+ PaError result = paNoError;
+ void* pret;
+
+ if( exitResult )
+ {
+ *exitResult = paNoError;
+ }
+#if 0
+ if( watchdogExitResult )
+ *watchdogExitResult = paNoError;
+
+ if( th->watchdogRunning )
+ {
+ pthread_cancel( th->watchdogThread );
+ PA_ENSURE_SYSTEM( pthread_join( th->watchdogThread, &pret ), 0 );
+
+ if( pret && pret != PTHREAD_CANCELED )
+ {
+ if( watchdogExitResult )
+ *watchdogExitResult = *(PaError *) pret;
+ free( pret );
+ }
+ }
+#endif
+
+ /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */
+ /* TODO: Make join time out */
+ self->stopRequested = wait;
+ if( !wait )
+ {
+ PA_DEBUG(( "%s: Canceling thread %d\n", __FUNCTION__, self->thread ));
+ /* XXX: Safe to call this if the thread has exited on its own? */
+ pthread_cancel( self->thread );
+ }
+ PA_DEBUG(( "%s: Joining thread %d\n", __FUNCTION__, self->thread ));
+ PA_ENSURE_SYSTEM( pthread_join( self->thread, &pret ), 0 );
+
+ if( pret && PTHREAD_CANCELED != pret )
+ {
+ if( exitResult )
+ {
+ *exitResult = *(PaError*)pret;
+ }
+ free( pret );
+ }
+
+error:
+ PA_ASSERT_CALL( PaUnixMutex_Terminate( &self->mtx ), paNoError );
+ PA_ASSERT_CALL( pthread_cond_destroy( &self->cond ), 0 );
+
+ return result;
+}
+
+PaError PaUnixThread_PrepareNotify( PaUnixThread* self )
+{
+ PaError result = paNoError;
+ PA_UNLESS( self->parentWaiting, paInternalError );
+
+ PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) );
+ self->locked = 1;
+
+error:
+ return result;
+}
+
+PaError PaUnixThread_NotifyParent( PaUnixThread* self )
+{
+ PaError result = paNoError;
+ PA_UNLESS( self->parentWaiting, paInternalError );
+
+ if( !self->locked )
+ {
+ PA_ENSURE( PaUnixMutex_Lock( &self->mtx ) );
+ self->locked = 1;
+ }
+ self->parentWaiting = 0;
+ pthread_cond_signal( &self->cond );
+ PA_ENSURE( PaUnixMutex_Unlock( &self->mtx ) );
+ self->locked = 0;
+
+error:
+ return result;
+}
+
+int PaUnixThread_StopRequested( PaUnixThread* self )
+{
+ return self->stopRequested;
+}
+
+PaError PaUnixMutex_Initialize( PaUnixMutex* self )
+{
+ PaError result = paNoError;
+ PA_ASSERT_CALL( pthread_mutex_init( &self->mtx, NULL ), 0 );
+ return result;
+}
+
+PaError PaUnixMutex_Terminate( PaUnixMutex* self )
+{
+ PaError result = paNoError;
+ PA_ASSERT_CALL( pthread_mutex_destroy( &self->mtx ), 0 );
+ return result;
+}
+
+/** Lock mutex.
+ *
+ * We're disabling thread cancellation while the thread is holding a lock, so mutexes are
+ * properly unlocked at termination time.
+ */
+PaError PaUnixMutex_Lock( PaUnixMutex* self )
+{
+ PaError result = paNoError;
+ int oldState;
+
+ PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, &oldState ), 0 );
+ PA_ENSURE_SYSTEM( pthread_mutex_lock( &self->mtx ), 0 );
+
+error:
+ return result;
+}
+
+/** Unlock mutex.
+ *
+ * Thread cancellation is enabled again after the mutex is properly unlocked.
+ */
+PaError PaUnixMutex_Unlock( PaUnixMutex* self )
+{
+ PaError result = paNoError;
+ int oldState;
+
+ PA_ENSURE_SYSTEM( pthread_mutex_unlock( &self->mtx ), 0 );
+ PA_ENSURE_SYSTEM( pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, &oldState ), 0 );
+
+error:
+ return result;
+}
+
+
+#if 0
+static void OnWatchdogExit( void *userData )
+{
+ PaAlsaThreading *th = (PaAlsaThreading *) userData;
+ struct sched_param spm = { 0 };
+ assert( th );
+
+ PA_ASSERT_CALL( pthread_setschedparam( th->callbackThread, SCHED_OTHER, &spm ), 0 ); /* Lower before exiting */
+ PA_DEBUG(( "Watchdog exiting\n" ));
+}
+
+static void *WatchdogFunc( void *userData )
+{
+ PaError result = paNoError, *pres = NULL;
+ int err;
+ PaAlsaThreading *th = (PaAlsaThreading *) userData;
+ unsigned intervalMsec = 500;
+ const PaTime maxSeconds = 3.; /* Max seconds between callbacks */
+ PaTime timeThen = PaUtil_GetTime(), timeNow, timeElapsed, cpuTimeThen, cpuTimeNow, cpuTimeElapsed;
+ double cpuLoad, avgCpuLoad = 0.;
+ int throttled = 0;
+
+ assert( th );
+
+ /* Execute OnWatchdogExit when exiting */
+ pthread_cleanup_push( &OnWatchdogExit, th );
+
+ /* Boost priority of callback thread */
+ PA_ENSURE( result = BoostPriority( th ) );
+ if( !result )
+ {
+ /* Boost failed, might as well exit */
+ pthread_exit( NULL );
+ }
+
+ cpuTimeThen = th->callbackCpuTime;
+ {
+ int policy;
+ struct sched_param spm = { 0 };
+ pthread_getschedparam( pthread_self(), &policy, &spm );
+ PA_DEBUG(( "%s: Watchdog priority is %d\n", __FUNCTION__, spm.sched_priority ));
+ }
+
+ while( 1 )
+ {
+ double lowpassCoeff = 0.9, lowpassCoeff1 = 0.99999 - lowpassCoeff;
+
+ /* Test before and after in case whatever underlying sleep call isn't interrupted by pthread_cancel */
+ pthread_testcancel();
+ Pa_Sleep( intervalMsec );
+ pthread_testcancel();
+
+ if( PaUtil_GetTime() - th->callbackTime > maxSeconds )
+ {
+ PA_DEBUG(( "Watchdog: Terminating callback thread\n" ));
+ /* Tell thread to terminate */
+ err = pthread_kill( th->callbackThread, SIGKILL );
+ pthread_exit( NULL );
+ }
+
+ PA_DEBUG(( "%s: PortAudio reports CPU load: %g\n", __FUNCTION__, PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) ));
+
+ /* Check if we should throttle, or unthrottle :P */
+ cpuTimeNow = th->callbackCpuTime;
+ cpuTimeElapsed = cpuTimeNow - cpuTimeThen;
+ cpuTimeThen = cpuTimeNow;
+
+ timeNow = PaUtil_GetTime();
+ timeElapsed = timeNow - timeThen;
+ timeThen = timeNow;
+ cpuLoad = cpuTimeElapsed / timeElapsed;
+ avgCpuLoad = avgCpuLoad * lowpassCoeff + cpuLoad * lowpassCoeff1;
+ /*
+ if( throttled )
+ PA_DEBUG(( "Watchdog: CPU load: %g, %g\n", avgCpuLoad, cpuTimeElapsed ));
+ */
+ if( PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) > .925 )
+ {
+ static int policy;
+ static struct sched_param spm = { 0 };
+ static const struct sched_param defaultSpm = { 0 };
+ PA_DEBUG(( "%s: Throttling audio thread, priority %d\n", __FUNCTION__, spm.sched_priority ));
+
+ pthread_getschedparam( th->callbackThread, &policy, &spm );
+ if( !pthread_setschedparam( th->callbackThread, SCHED_OTHER, &defaultSpm ) )
+ {
+ throttled = 1;
+ }
+ else
+ PA_DEBUG(( "Watchdog: Couldn't lower priority of audio thread: %s\n", strerror( errno ) ));
+
+ /* Give other processes a go, before raising priority again */
+ PA_DEBUG(( "%s: Watchdog sleeping for %lu msecs before unthrottling\n", __FUNCTION__, th->throttledSleepTime ));
+ Pa_Sleep( th->throttledSleepTime );
+
+ /* Reset callback priority */
+ if( pthread_setschedparam( th->callbackThread, SCHED_FIFO, &spm ) != 0 )
+ {
+ PA_DEBUG(( "%s: Couldn't raise priority of audio thread: %s\n", __FUNCTION__, strerror( errno ) ));
+ }
+
+ if( PaUtil_GetCpuLoad( th->cpuLoadMeasurer ) >= .99 )
+ intervalMsec = 50;
+ else
+ intervalMsec = 100;
+
+ /*
+ lowpassCoeff = .97;
+ lowpassCoeff1 = .99999 - lowpassCoeff;
+ */
+ }
+ else if( throttled && avgCpuLoad < .8 )
+ {
+ intervalMsec = 500;
+ throttled = 0;
+
+ /*
+ lowpassCoeff = .9;
+ lowpassCoeff1 = .99999 - lowpassCoeff;
+ */
+ }
+ }
+
+ pthread_cleanup_pop( 1 ); /* Execute cleanup on exit */
+
+error:
+ /* Shouldn't get here in the normal case */
+
+ /* Pass on error code */
+ pres = malloc( sizeof (PaError) );
+ *pres = result;
+
+ pthread_exit( pres );
+}
+
+static void CallbackUpdate( PaAlsaThreading *th )
+{
+ th->callbackTime = PaUtil_GetTime();
+ th->callbackCpuTime = PaUtil_GetCpuLoad( th->cpuLoadMeasurer );
+}
+
+/*
+static void *CanaryFunc( void *userData )
+{
+ const unsigned intervalMsec = 1000;
+ PaUtilThreading *th = (PaUtilThreading *) userData;
+
+ while( 1 )
+ {
+ th->canaryTime = PaUtil_GetTime();
+
+ pthread_testcancel();
+ Pa_Sleep( intervalMsec );
+ }
+
+ pthread_exit( NULL );
+}
+*/
+#endif
diff --git a/pd/portaudio/src/os/unix/pa_unix_util.h b/pd/portaudio/src/os/unix/pa_unix_util.h
new file mode 100644
index 00000000..bfcc802e
--- /dev/null
+++ b/pd/portaudio/src/os/unix/pa_unix_util.h
@@ -0,0 +1,224 @@
+/*
+ * $Id: pa_unix_util.h,v 1.1 2007-08-18 23:49:33 millerpuckette Exp $
+ * Portable Audio I/O Library
+ * UNIX platform-specific support functions
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2000 Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup unix_src
+*/
+
+#ifndef PA_UNIX_UTIL_H
+#define PA_UNIX_UTIL_H
+
+#include "pa_cpuload.h"
+#include <assert.h>
+#include <pthread.h>
+#include <signal.h>
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+#define PA_MIN(x,y) ( (x) < (y) ? (x) : (y) )
+#define PA_MAX(x,y) ( (x) > (y) ? (x) : (y) )
+
+/* Utilize GCC branch prediction for error tests */
+#if defined __GNUC__ && __GNUC__ >= 3
+#define UNLIKELY(expr) __builtin_expect( (expr), 0 )
+#else
+#define UNLIKELY(expr) (expr)
+#endif
+
+#define STRINGIZE_HELPER(expr) #expr
+#define STRINGIZE(expr) STRINGIZE_HELPER(expr)
+
+#define PA_UNLESS(expr, code) \
+ do { \
+ if( UNLIKELY( (expr) == 0 ) ) \
+ { \
+ PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
+ result = (code); \
+ goto error; \
+ } \
+ } while (0);
+
+static PaError paUtilErr_; /* Used with PA_ENSURE */
+
+/* Check PaError */
+#define PA_ENSURE(expr) \
+ do { \
+ if( UNLIKELY( (paUtilErr_ = (expr)) < paNoError ) ) \
+ { \
+ PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \
+ result = paUtilErr_; \
+ goto error; \
+ } \
+ } while (0);
+
+#define PA_ASSERT_CALL(expr, success) \
+ paUtilErr_ = (expr); \
+ assert( success == paUtilErr_ );
+
+#define PA_ENSURE_SYSTEM(expr, success) \
+ do { \
+ if( UNLIKELY( (paUtilErr_ = (expr)) != success ) ) \
+ { \
+ /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \
+ if( pthread_equal(pthread_self(), paUnixMainThread) ) \
+ { \
+ PaUtil_SetLastHostErrorInfo( paALSA, paUtilErr_, strerror( paUtilErr_ ) ); \
+ } \
+ PaUtil_DebugPrint( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" ); \
+ result = paUnanticipatedHostError; \
+ goto error; \
+ } \
+ } while( 0 );
+
+typedef struct {
+ pthread_t callbackThread;
+} PaUtilThreading;
+
+PaError PaUtil_InitializeThreading( PaUtilThreading *threading );
+void PaUtil_TerminateThreading( PaUtilThreading *threading );
+PaError PaUtil_StartThreading( PaUtilThreading *threading, void *(*threadRoutine)(void *), void *data );
+PaError PaUtil_CancelThreading( PaUtilThreading *threading, int wait, PaError *exitResult );
+
+/* State accessed by utility functions */
+
+/*
+void PaUnix_SetRealtimeScheduling( int rt );
+
+void PaUtil_InitializeThreading( PaUtilThreading *th, PaUtilCpuLoadMeasurer *clm );
+
+PaError PaUtil_CreateCallbackThread( PaUtilThreading *th, void *(*CallbackThreadFunc)( void * ), PaStream *s );
+
+PaError PaUtil_KillCallbackThread( PaUtilThreading *th, PaError *exitResult );
+
+void PaUtil_CallbackUpdate( PaUtilThreading *th );
+*/
+
+extern pthread_t paUnixMainThread;
+
+typedef struct
+{
+ pthread_mutex_t mtx;
+} PaUnixMutex;
+
+PaError PaUnixMutex_Initialize( PaUnixMutex* self );
+PaError PaUnixMutex_Terminate( PaUnixMutex* self );
+PaError PaUnixMutex_Lock( PaUnixMutex* self );
+PaError PaUnixMutex_Unlock( PaUnixMutex* self );
+
+typedef struct
+{
+ pthread_t thread;
+ int parentWaiting;
+ int stopRequested;
+ int locked;
+ PaUnixMutex mtx;
+ pthread_cond_t cond;
+ volatile sig_atomic_t stopRequest;
+} PaUnixThread;
+
+/** Initialize global threading state.
+ */
+PaError PaUnixThreading_Initialize();
+
+/** Perish, passing on eventual error code.
+ *
+ * A thin wrapper around pthread_exit, will automatically pass on any error code to the joining thread.
+ * If the result indicates an error, i.e. it is not equal to paNoError, this function will automatically
+ * allocate a pointer so the error is passed on with pthread_exit. If the result indicates that all is
+ * well however, only a NULL pointer will be handed to pthread_exit. Thus, the joining thread should
+ * check whether a non-NULL result pointer is obtained from pthread_join and make sure to free it.
+ * @param result: The error code to pass on to the joining thread.
+ */
+#define PaUnixThreading_EXIT(result) \
+ do { \
+ PaError* pres = NULL; \
+ if( paNoError != (result) ) \
+ { \
+ pres = malloc( sizeof (PaError) ); \
+ *pres = (result); \
+ } \
+ pthread_exit( pres ); \
+ } while (0);
+
+/** Spawn a thread.
+ *
+ * Intended for spawning the callback thread from the main thread. This function can even block (for a certain
+ * time or indefinitely) untill notified by the callback thread (using PaUnixThread_NotifyParent), which can be
+ * useful in order to make sure that callback has commenced before returning from Pa_StartStream.
+ * @param threadFunc: The function to be executed in the child thread.
+ * @param waitForChild: If not 0, wait for child thread to call PaUnixThread_NotifyParent. Less than 0 means
+ * wait for ever, greater than 0 wait for the specified time.
+ * @param rtSched: Enable realtime scheduling?
+ * @return: If timed out waiting on child, paTimedOut.
+ */
+PaError PaUnixThread_New( PaUnixThread* self, void* (*threadFunc)( void* ), void* threadArg, PaTime waitForChild,
+ int rtSched );
+
+/** Terminate thread.
+ *
+ * @param wait: If true, request that background thread stop and wait untill it does, else cancel it.
+ * @param exitResult: If non-null this will upon return contain the exit status of the thread.
+ */
+PaError PaUnixThread_Terminate( PaUnixThread* self, int wait, PaError* exitResult );
+
+/** Prepare to notify waiting parent thread.
+ *
+ * An internal lock must be held before the parent is notified in PaUnixThread_NotifyParent, call this to
+ * acquire it beforehand.
+ * @return: If parent is not waiting, paInternalError.
+ */
+PaError PaUnixThread_PrepareNotify( PaUnixThread* self );
+
+/** Notify waiting parent thread.
+ *
+ * @return: If parent timed out waiting, paTimedOut. If parent was never waiting, paInternalError.
+ */
+PaError PaUnixThread_NotifyParent( PaUnixThread* self );
+
+/** Has the parent thread requested this thread to stop?
+ */
+int PaUnixThread_StopRequested( PaUnixThread* self );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif
diff --git a/pd/portaudio/src/os/win/pa_win_hostapis.c b/pd/portaudio/src/os/win/pa_win_hostapis.c
new file mode 100644
index 00000000..8a902aa1
--- /dev/null
+++ b/pd/portaudio/src/os/win/pa_win_hostapis.c
@@ -0,0 +1,100 @@
+/*
+ * $Id: pa_win_hostapis.c,v 1.1 2007-08-18 23:49:33 millerpuckette Exp $
+ * Portable Audio I/O Library Windows initialization table
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup win_src
+
+ Win32 host API initialization function table.
+
+ @todo Consider using PA_USE_WMME etc instead of PA_NO_WMME. This is what
+ the Unix version does, we should consider being consistent.
+*/
+
+
+#include "pa_hostapi.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+PaError PaSkeleton_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaWinMme_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaWinDs_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaAsio_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaWinWdm_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+PaError PaWinWasapi_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+
+
+PaUtilHostApiInitializer *paHostApiInitializers[] =
+ {
+
+#ifndef PA_NO_WMME
+ PaWinMme_Initialize,
+#endif
+
+#ifndef PA_NO_DS
+ PaWinDs_Initialize,
+#endif
+
+#ifndef PA_NO_ASIO
+ PaAsio_Initialize,
+#endif
+
+/*
+#ifndef PA_NO_WASAPI
+ PaWinWasapi_Initialize,
+#endif
+
+#ifndef PA_NO_WDMKS
+ PaWinWdm_Initialize,
+#endif
+*/
+
+ PaSkeleton_Initialize, /* just for testing */
+
+ 0 /* NULL terminated array */
+ };
+
+
+int paDefaultHostApiIndex = 0;
+
diff --git a/pd/portaudio/src/os/win/pa_win_util.c b/pd/portaudio/src/os/win/pa_win_util.c
new file mode 100644
index 00000000..fe6167ac
--- /dev/null
+++ b/pd/portaudio/src/os/win/pa_win_util.c
@@ -0,0 +1,147 @@
+/*
+ * $Id: pa_win_util.c,v 1.1 2007-08-18 23:49:33 millerpuckette Exp $
+ * Portable Audio I/O Library
+ * Win32 platform-specific support functions
+ *
+ * Based on the Open Source API proposed by Ross Bencina
+ * Copyright (c) 1999-2000 Ross Bencina
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup win_src
+
+ Win32 platform-specific support functions.
+
+ @todo Implement workaround for QueryPerformanceCounter() skipping forward
+ bug. (see msdn kb Q274323).
+*/
+
+#include <windows.h>
+#include <mmsystem.h> /* for timeGetTime() */
+
+#include "pa_util.h"
+
+
+/*
+ Track memory allocations to avoid leaks.
+ */
+
+#if PA_TRACK_MEMORY
+static int numAllocations_ = 0;
+#endif
+
+
+void *PaUtil_AllocateMemory( long size )
+{
+ void *result = GlobalAlloc( GPTR, size );
+
+#if PA_TRACK_MEMORY
+ if( result != NULL ) numAllocations_ += 1;
+#endif
+ return result;
+}
+
+
+void PaUtil_FreeMemory( void *block )
+{
+ if( block != NULL )
+ {
+ GlobalFree( block );
+#if PA_TRACK_MEMORY
+ numAllocations_ -= 1;
+#endif
+
+ }
+}
+
+
+int PaUtil_CountCurrentlyAllocatedBlocks( void )
+{
+#if PA_TRACK_MEMORY
+ return numAllocations_;
+#else
+ return 0;
+#endif
+}
+
+
+void Pa_Sleep( long msec )
+{
+ Sleep( msec );
+}
+
+static int usePerformanceCounter_;
+static double secondsPerTick_;
+
+void PaUtil_InitializeClock( void )
+{
+ LARGE_INTEGER ticksPerSecond;
+
+ if( QueryPerformanceFrequency( &ticksPerSecond ) != 0 )
+ {
+ usePerformanceCounter_ = 1;
+ secondsPerTick_ = 1.0 / (double)ticksPerSecond.QuadPart;
+ }
+ else
+ {
+ usePerformanceCounter_ = 0;
+ }
+}
+
+
+double PaUtil_GetTime( void )
+{
+ LARGE_INTEGER time;
+
+ if( usePerformanceCounter_ )
+ {
+ /* FIXME:
+ according to this knowledge-base article, QueryPerformanceCounter
+ can skip forward by seconds!
+ http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q274323&
+
+ it may be better to use the rtdsc instruction using inline asm,
+ however then a method is needed to calculate a ticks/seconds ratio.
+ */
+ QueryPerformanceCounter( &time );
+ return time.QuadPart * secondsPerTick_;
+ }
+ else
+ {
+#ifndef UNDER_CE
+ return timeGetTime() * .001;
+#else
+ return GetTickCount() * .001;
+#endif
+ }
+}
diff --git a/pd/portaudio/src/os/win/pa_x86_plain_converters.c b/pd/portaudio/src/os/win/pa_x86_plain_converters.c
new file mode 100644
index 00000000..63b058df
--- /dev/null
+++ b/pd/portaudio/src/os/win/pa_x86_plain_converters.c
@@ -0,0 +1,1219 @@
+/*
+ * Plain Intel IA32 assembly implementations of PortAudio sample converter functions.
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup win_src
+*/
+
+#include "pa_x86_plain_converters.h"
+
+#include "pa_converters.h"
+#include "pa_dither.h"
+
+/*
+ the main reason these versions are faster than the equivalent C versions
+ is that float -> int casting is expensive in C on x86 because the rounding
+ mode needs to be changed for every cast. these versions only set
+ the rounding mode once outside the loop.
+
+ small additional speed gains are made by the way that clamping is
+ implemented.
+
+TODO:
+ o- inline dither code
+ o- implement Dither only (no-clip) versions
+ o- implement int8 and uint8 versions
+ o- test thouroughly
+
+ o- the packed 24 bit functions could benefit from unrolling and avoiding
+ byte and word sized register access.
+*/
+
+/* -------------------------------------------------------------------------- */
+
+/*
+#define PA_CLIP_( val, min, max )\
+ { val = ((val) < (min)) ? (min) : (((val) > (max)) ? (max) : (val)); }
+*/
+
+/*
+ the following notes were used to determine whether a floating point
+ value should be saturated (ie >1 or <-1) by loading it into an integer
+ register. these should be rewritten so that they make sense.
+
+ an ieee floating point value
+
+ 1.xxxxxxxxxxxxxxxxxxxx?
+
+
+ is less than or equal to 1 and greater than or equal to -1 either:
+
+ if the mantissa is 0 and the unbiased exponent is 0
+
+ OR
+
+ if the unbiased exponent < 0
+
+ this translates to:
+
+ if the mantissa is 0 and the biased exponent is 7F
+
+ or
+
+ if the biased exponent is less than 7F
+
+
+ therefore the value is greater than 1 or less than -1 if
+
+ the mantissa is not 0 and the biased exponent is 7F
+
+ or
+
+ if the biased exponent is greater than 7F
+
+
+ in other words, if we mask out the sign bit, the value is
+ greater than 1 or less than -1 if its integer representation is greater than:
+
+ 0 01111111 0000 0000 0000 0000 0000 000
+
+ 0011 1111 1000 0000 0000 0000 0000 0000 => 0x3F800000
+*/
+
+/* -------------------------------------------------------------------------- */
+
+static const short fpuControlWord_ = 0x033F; /*round to nearest, 64 bit precision, all exceptions masked*/
+static const double int32Scaler_ = 0x7FFFFFFF;
+static const double ditheredInt32Scaler_ = 0x7FFFFFFE;
+static const double int24Scaler_ = 0x7FFFFF;
+static const double ditheredInt24Scaler_ = 0x7FFFFE;
+static const double int16Scaler_ = 0x7FFF;
+static const double ditheredInt16Scaler_ = 0x7FFE;
+
+#define PA_DITHER_BITS_ (15)
+/* Multiply by PA_FLOAT_DITHER_SCALE_ to get a float between -2.0 and +1.99999 */
+#define PA_FLOAT_DITHER_SCALE_ (1.0 / ((1<<PA_DITHER_BITS_)-1))
+static const float const_float_dither_scale_ = PA_FLOAT_DITHER_SCALE_;
+#define PA_DITHER_SHIFT_ ((32 - PA_DITHER_BITS_) + 1)
+
+/* -------------------------------------------------------------------------- */
+
+#ifdef _WIN64
+
+/*
+ -EMT64/AMD64 uses different asm
+ -VC2005 doesnt allow _WIN64 with inline assembly either!
+ */
+void PaUtil_InitializeX86PlainConverters( void )
+{
+}
+
+#else
+
+
+static void Float32_To_Int32(
+ void *destinationBuffer, signed int destinationStride,
+ void *sourceBuffer, signed int sourceStride,
+ unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+ float *src = (float*)sourceBuffer;
+ signed long *dest = (signed long*)destinationBuffer;
+ (void)ditherGenerator; // unused parameter
+
+ while( count-- )
+ {
+ // REVIEW
+ double scaled = *src * 0x7FFFFFFF;
+ *dest = (signed long) scaled;
+
+ src += sourceStride;
+ dest += destinationStride;
+ }
+*/
+
+ short savedFpuControlWord;
+
+ (void) ditherGenerator; /* unused parameter */
+
+
+ __asm{
+ // esi -> source ptr
+ // eax -> source byte stride
+ // edi -> destination ptr
+ // ebx -> destination byte stride
+ // ecx -> source end ptr
+ // edx -> temp
+
+ mov esi, sourceBuffer
+
+ mov edx, 4 // sizeof float32 and int32
+ mov eax, sourceStride
+ imul eax, edx
+
+ mov ecx, count
+ imul ecx, eax
+ add ecx, esi
+
+ mov edi, destinationBuffer
+
+ mov ebx, destinationStride
+ imul ebx, edx
+
+ fwait
+ fstcw savedFpuControlWord
+ fldcw fpuControlWord_
+
+ fld int32Scaler_ // stack: (int)0x7FFFFFFF
+
+ Float32_To_Int32_loop:
+
+ // load unscaled value into st(0)
+ fld dword ptr [esi] // stack: value, (int)0x7FFFFFFF
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ fmul st(0), st(1) // st(0) *= st(1), stack: value*0x7FFFFFFF, (int)0x7FFFFFFF
+ /*
+ note: we could store to a temporary qword here which would cause
+ wraparound distortion instead of int indefinite 0x10. that would
+ be more work, and given that not enabling clipping is only advisable
+ when you know that your signal isn't going to clip it isn't worth it.
+ */
+ fistp dword ptr [edi] // pop st(0) into dest, stack: (int)0x7FFFFFFF
+
+ add edi, ebx // increment destination ptr
+ //lea edi, [edi+ebx]
+
+ cmp esi, ecx // has src ptr reached end?
+ jne Float32_To_Int32_loop
+
+ ffree st(0)
+ fincstp
+
+ fwait
+ fnclex
+ fldcw savedFpuControlWord
+ }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int32_Clip(
+ void *destinationBuffer, signed int destinationStride,
+ void *sourceBuffer, signed int sourceStride,
+ unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+ float *src = (float*)sourceBuffer;
+ signed long *dest = (signed long*)destinationBuffer;
+ (void) ditherGenerator; // unused parameter
+
+ while( count-- )
+ {
+ // REVIEW
+ double scaled = *src * 0x7FFFFFFF;
+ PA_CLIP_( scaled, -2147483648., 2147483647. );
+ *dest = (signed long) scaled;
+
+ src += sourceStride;
+ dest += destinationStride;
+ }
+*/
+
+ short savedFpuControlWord;
+
+ (void) ditherGenerator; /* unused parameter */
+
+ __asm{
+ // esi -> source ptr
+ // eax -> source byte stride
+ // edi -> destination ptr
+ // ebx -> destination byte stride
+ // ecx -> source end ptr
+ // edx -> temp
+
+ mov esi, sourceBuffer
+
+ mov edx, 4 // sizeof float32 and int32
+ mov eax, sourceStride
+ imul eax, edx
+
+ mov ecx, count
+ imul ecx, eax
+ add ecx, esi
+
+ mov edi, destinationBuffer
+
+ mov ebx, destinationStride
+ imul ebx, edx
+
+ fwait
+ fstcw savedFpuControlWord
+ fldcw fpuControlWord_
+
+ fld int32Scaler_ // stack: (int)0x7FFFFFFF
+
+ Float32_To_Int32_Clip_loop:
+
+ mov edx, dword ptr [esi] // load floating point value into integer register
+
+ and edx, 0x7FFFFFFF // mask off sign
+ cmp edx, 0x3F800000 // greater than 1.0 or less than -1.0
+
+ jg Float32_To_Int32_Clip_clamp
+
+ // load unscaled value into st(0)
+ fld dword ptr [esi] // stack: value, (int)0x7FFFFFFF
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ fmul st(0), st(1) // st(0) *= st(1), stack: value*0x7FFFFFFF, (int)0x7FFFFFFF
+ fistp dword ptr [edi] // pop st(0) into dest, stack: (int)0x7FFFFFFF
+ jmp Float32_To_Int32_Clip_stored
+
+ Float32_To_Int32_Clip_clamp:
+ mov edx, dword ptr [esi] // load floating point value into integer register
+ shr edx, 31 // move sign bit into bit 0
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ add edx, 0x7FFFFFFF // convert to maximum range integers
+ mov dword ptr [edi], edx
+
+ Float32_To_Int32_Clip_stored:
+
+ //add edi, ebx // increment destination ptr
+ lea edi, [edi+ebx]
+
+ cmp esi, ecx // has src ptr reached end?
+ jne Float32_To_Int32_Clip_loop
+
+ ffree st(0)
+ fincstp
+
+ fwait
+ fnclex
+ fldcw savedFpuControlWord
+ }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int32_DitherClip(
+ void *destinationBuffer, signed int destinationStride,
+ void *sourceBuffer, signed int sourceStride,
+ unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+ /*
+ float *src = (float*)sourceBuffer;
+ signed long *dest = (signed long*)destinationBuffer;
+
+ while( count-- )
+ {
+ // REVIEW
+ double dither = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+ // use smaller scaler to prevent overflow when we add the dither
+ double dithered = ((double)*src * (2147483646.0)) + dither;
+ PA_CLIP_( dithered, -2147483648., 2147483647. );
+ *dest = (signed long) dithered;
+
+
+ src += sourceStride;
+ dest += destinationStride;
+ }
+ */
+
+ short savedFpuControlWord;
+
+ // spill storage:
+ signed long sourceByteStride;
+ signed long highpassedDither;
+
+ // dither state:
+ unsigned long ditherPrevious = ditherGenerator->previous;
+ unsigned long ditherRandSeed1 = ditherGenerator->randSeed1;
+ unsigned long ditherRandSeed2 = ditherGenerator->randSeed2;
+
+ __asm{
+ // esi -> source ptr
+ // eax -> source byte stride
+ // edi -> destination ptr
+ // ebx -> destination byte stride
+ // ecx -> source end ptr
+ // edx -> temp
+
+ mov esi, sourceBuffer
+
+ mov edx, 4 // sizeof float32 and int32
+ mov eax, sourceStride
+ imul eax, edx
+
+ mov ecx, count
+ imul ecx, eax
+ add ecx, esi
+
+ mov edi, destinationBuffer
+
+ mov ebx, destinationStride
+ imul ebx, edx
+
+ fwait
+ fstcw savedFpuControlWord
+ fldcw fpuControlWord_
+
+ fld ditheredInt32Scaler_ // stack: int scaler
+
+ Float32_To_Int32_DitherClip_loop:
+
+ mov edx, dword ptr [esi] // load floating point value into integer register
+
+ and edx, 0x7FFFFFFF // mask off sign
+ cmp edx, 0x3F800000 // greater than 1.0 or less than -1.0
+
+ jg Float32_To_Int32_DitherClip_clamp
+
+ // load unscaled value into st(0)
+ fld dword ptr [esi] // stack: value, int scaler
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ fmul st(0), st(1) // st(0) *= st(1), stack: value*(int scaler), int scaler
+
+ /*
+ // call PaUtil_GenerateFloatTriangularDither with C calling convention
+ mov sourceByteStride, eax // save eax
+ mov sourceEnd, ecx // save ecx
+ push ditherGenerator // pass ditherGenerator parameter on stack
+ call PaUtil_GenerateFloatTriangularDither // stack: dither, value*(int scaler), int scaler
+ pop edx // clear parameter off stack
+ mov ecx, sourceEnd // restore ecx
+ mov eax, sourceByteStride // restore eax
+ */
+
+ // generate dither
+ mov sourceByteStride, eax // save eax
+ mov edx, 196314165
+ mov eax, ditherRandSeed1
+ mul edx // eax:edx = eax * 196314165
+ //add eax, 907633515
+ lea eax, [eax+907633515]
+ mov ditherRandSeed1, eax
+ mov edx, 196314165
+ mov eax, ditherRandSeed2
+ mul edx // eax:edx = eax * 196314165
+ //add eax, 907633515
+ lea eax, [eax+907633515]
+ mov edx, ditherRandSeed1
+ shr edx, PA_DITHER_SHIFT_
+ mov ditherRandSeed2, eax
+ shr eax, PA_DITHER_SHIFT_
+ //add eax, edx // eax -> current
+ lea eax, [eax+edx]
+ mov edx, ditherPrevious
+ neg edx
+ lea edx, [eax+edx] // highpass = current - previous
+ mov highpassedDither, edx
+ mov ditherPrevious, eax // previous = current
+ mov eax, sourceByteStride // restore eax
+ fild highpassedDither
+ fmul const_float_dither_scale_
+ // end generate dither, dither signal in st(0)
+
+ faddp st(1), st(0) // stack: dither + value*(int scaler), int scaler
+ fistp dword ptr [edi] // pop st(0) into dest, stack: int scaler
+ jmp Float32_To_Int32_DitherClip_stored
+
+ Float32_To_Int32_DitherClip_clamp:
+ mov edx, dword ptr [esi] // load floating point value into integer register
+ shr edx, 31 // move sign bit into bit 0
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ add edx, 0x7FFFFFFF // convert to maximum range integers
+ mov dword ptr [edi], edx
+
+ Float32_To_Int32_DitherClip_stored:
+
+ //add edi, ebx // increment destination ptr
+ lea edi, [edi+ebx]
+
+ cmp esi, ecx // has src ptr reached end?
+ jne Float32_To_Int32_DitherClip_loop
+
+ ffree st(0)
+ fincstp
+
+ fwait
+ fnclex
+ fldcw savedFpuControlWord
+ }
+
+ ditherGenerator->previous = ditherPrevious;
+ ditherGenerator->randSeed1 = ditherRandSeed1;
+ ditherGenerator->randSeed2 = ditherRandSeed2;
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int24(
+ void *destinationBuffer, signed int destinationStride,
+ void *sourceBuffer, signed int sourceStride,
+ unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+ float *src = (float*)sourceBuffer;
+ unsigned char *dest = (unsigned char*)destinationBuffer;
+ signed long temp;
+
+ (void) ditherGenerator; // unused parameter
+
+ while( count-- )
+ {
+ // convert to 32 bit and drop the low 8 bits
+ double scaled = *src * 0x7FFFFFFF;
+ temp = (signed long) scaled;
+
+ dest[0] = (unsigned char)(temp >> 8);
+ dest[1] = (unsigned char)(temp >> 16);
+ dest[2] = (unsigned char)(temp >> 24);
+
+ src += sourceStride;
+ dest += destinationStride * 3;
+ }
+*/
+
+ short savedFpuControlWord;
+
+ signed long tempInt32;
+
+ (void) ditherGenerator; /* unused parameter */
+
+ __asm{
+ // esi -> source ptr
+ // eax -> source byte stride
+ // edi -> destination ptr
+ // ebx -> destination byte stride
+ // ecx -> source end ptr
+ // edx -> temp
+
+ mov esi, sourceBuffer
+
+ mov edx, 4 // sizeof float32
+ mov eax, sourceStride
+ imul eax, edx
+
+ mov ecx, count
+ imul ecx, eax
+ add ecx, esi
+
+ mov edi, destinationBuffer
+
+ mov edx, 3 // sizeof int24
+ mov ebx, destinationStride
+ imul ebx, edx
+
+ fwait
+ fstcw savedFpuControlWord
+ fldcw fpuControlWord_
+
+ fld int24Scaler_ // stack: (int)0x7FFFFF
+
+ Float32_To_Int24_loop:
+
+ // load unscaled value into st(0)
+ fld dword ptr [esi] // stack: value, (int)0x7FFFFF
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ fmul st(0), st(1) // st(0) *= st(1), stack: value*0x7FFFFF, (int)0x7FFFFF
+ fistp tempInt32 // pop st(0) into tempInt32, stack: (int)0x7FFFFF
+ mov edx, tempInt32
+
+ mov byte ptr [edi], DL
+ shr edx, 8
+ //mov byte ptr [edi+1], DL
+ //mov byte ptr [edi+2], DH
+ mov word ptr [edi+1], DX
+
+ //add edi, ebx // increment destination ptr
+ lea edi, [edi+ebx]
+
+ cmp esi, ecx // has src ptr reached end?
+ jne Float32_To_Int24_loop
+
+ ffree st(0)
+ fincstp
+
+ fwait
+ fnclex
+ fldcw savedFpuControlWord
+ }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int24_Clip(
+ void *destinationBuffer, signed int destinationStride,
+ void *sourceBuffer, signed int sourceStride,
+ unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+ float *src = (float*)sourceBuffer;
+ unsigned char *dest = (unsigned char*)destinationBuffer;
+ signed long temp;
+
+ (void) ditherGenerator; // unused parameter
+
+ while( count-- )
+ {
+ // convert to 32 bit and drop the low 8 bits
+ double scaled = *src * 0x7FFFFFFF;
+ PA_CLIP_( scaled, -2147483648., 2147483647. );
+ temp = (signed long) scaled;
+
+ dest[0] = (unsigned char)(temp >> 8);
+ dest[1] = (unsigned char)(temp >> 16);
+ dest[2] = (unsigned char)(temp >> 24);
+
+ src += sourceStride;
+ dest += destinationStride * 3;
+ }
+*/
+
+ short savedFpuControlWord;
+
+ signed long tempInt32;
+
+ (void) ditherGenerator; /* unused parameter */
+
+ __asm{
+ // esi -> source ptr
+ // eax -> source byte stride
+ // edi -> destination ptr
+ // ebx -> destination byte stride
+ // ecx -> source end ptr
+ // edx -> temp
+
+ mov esi, sourceBuffer
+
+ mov edx, 4 // sizeof float32
+ mov eax, sourceStride
+ imul eax, edx
+
+ mov ecx, count
+ imul ecx, eax
+ add ecx, esi
+
+ mov edi, destinationBuffer
+
+ mov edx, 3 // sizeof int24
+ mov ebx, destinationStride
+ imul ebx, edx
+
+ fwait
+ fstcw savedFpuControlWord
+ fldcw fpuControlWord_
+
+ fld int24Scaler_ // stack: (int)0x7FFFFF
+
+ Float32_To_Int24_Clip_loop:
+
+ mov edx, dword ptr [esi] // load floating point value into integer register
+
+ and edx, 0x7FFFFFFF // mask off sign
+ cmp edx, 0x3F800000 // greater than 1.0 or less than -1.0
+
+ jg Float32_To_Int24_Clip_clamp
+
+ // load unscaled value into st(0)
+ fld dword ptr [esi] // stack: value, (int)0x7FFFFF
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ fmul st(0), st(1) // st(0) *= st(1), stack: value*0x7FFFFF, (int)0x7FFFFF
+ fistp tempInt32 // pop st(0) into tempInt32, stack: (int)0x7FFFFF
+ mov edx, tempInt32
+ jmp Float32_To_Int24_Clip_store
+
+ Float32_To_Int24_Clip_clamp:
+ mov edx, dword ptr [esi] // load floating point value into integer register
+ shr edx, 31 // move sign bit into bit 0
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ add edx, 0x7FFFFF // convert to maximum range integers
+
+ Float32_To_Int24_Clip_store:
+
+ mov byte ptr [edi], DL
+ shr edx, 8
+ //mov byte ptr [edi+1], DL
+ //mov byte ptr [edi+2], DH
+ mov word ptr [edi+1], DX
+
+ //add edi, ebx // increment destination ptr
+ lea edi, [edi+ebx]
+
+ cmp esi, ecx // has src ptr reached end?
+ jne Float32_To_Int24_Clip_loop
+
+ ffree st(0)
+ fincstp
+
+ fwait
+ fnclex
+ fldcw savedFpuControlWord
+ }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int24_DitherClip(
+ void *destinationBuffer, signed int destinationStride,
+ void *sourceBuffer, signed int sourceStride,
+ unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+ float *src = (float*)sourceBuffer;
+ unsigned char *dest = (unsigned char*)destinationBuffer;
+ signed long temp;
+
+ while( count-- )
+ {
+ // convert to 32 bit and drop the low 8 bits
+
+ // FIXME: the dither amplitude here appears to be too small by 8 bits
+ double dither = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+ // use smaller scaler to prevent overflow when we add the dither
+ double dithered = ((double)*src * (2147483646.0)) + dither;
+ PA_CLIP_( dithered, -2147483648., 2147483647. );
+
+ temp = (signed long) dithered;
+
+ dest[0] = (unsigned char)(temp >> 8);
+ dest[1] = (unsigned char)(temp >> 16);
+ dest[2] = (unsigned char)(temp >> 24);
+
+ src += sourceStride;
+ dest += destinationStride * 3;
+ }
+*/
+
+ short savedFpuControlWord;
+
+ // spill storage:
+ signed long sourceByteStride;
+ signed long highpassedDither;
+
+ // dither state:
+ unsigned long ditherPrevious = ditherGenerator->previous;
+ unsigned long ditherRandSeed1 = ditherGenerator->randSeed1;
+ unsigned long ditherRandSeed2 = ditherGenerator->randSeed2;
+
+ signed long tempInt32;
+
+ __asm{
+ // esi -> source ptr
+ // eax -> source byte stride
+ // edi -> destination ptr
+ // ebx -> destination byte stride
+ // ecx -> source end ptr
+ // edx -> temp
+
+ mov esi, sourceBuffer
+
+ mov edx, 4 // sizeof float32
+ mov eax, sourceStride
+ imul eax, edx
+
+ mov ecx, count
+ imul ecx, eax
+ add ecx, esi
+
+ mov edi, destinationBuffer
+
+ mov edx, 3 // sizeof int24
+ mov ebx, destinationStride
+ imul ebx, edx
+
+ fwait
+ fstcw savedFpuControlWord
+ fldcw fpuControlWord_
+
+ fld ditheredInt24Scaler_ // stack: int scaler
+
+ Float32_To_Int24_DitherClip_loop:
+
+ mov edx, dword ptr [esi] // load floating point value into integer register
+
+ and edx, 0x7FFFFFFF // mask off sign
+ cmp edx, 0x3F800000 // greater than 1.0 or less than -1.0
+
+ jg Float32_To_Int24_DitherClip_clamp
+
+ // load unscaled value into st(0)
+ fld dword ptr [esi] // stack: value, int scaler
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ fmul st(0), st(1) // st(0) *= st(1), stack: value*(int scaler), int scaler
+
+ /*
+ // call PaUtil_GenerateFloatTriangularDither with C calling convention
+ mov sourceByteStride, eax // save eax
+ mov sourceEnd, ecx // save ecx
+ push ditherGenerator // pass ditherGenerator parameter on stack
+ call PaUtil_GenerateFloatTriangularDither // stack: dither, value*(int scaler), int scaler
+ pop edx // clear parameter off stack
+ mov ecx, sourceEnd // restore ecx
+ mov eax, sourceByteStride // restore eax
+ */
+
+ // generate dither
+ mov sourceByteStride, eax // save eax
+ mov edx, 196314165
+ mov eax, ditherRandSeed1
+ mul edx // eax:edx = eax * 196314165
+ //add eax, 907633515
+ lea eax, [eax+907633515]
+ mov ditherRandSeed1, eax
+ mov edx, 196314165
+ mov eax, ditherRandSeed2
+ mul edx // eax:edx = eax * 196314165
+ //add eax, 907633515
+ lea eax, [eax+907633515]
+ mov edx, ditherRandSeed1
+ shr edx, PA_DITHER_SHIFT_
+ mov ditherRandSeed2, eax
+ shr eax, PA_DITHER_SHIFT_
+ //add eax, edx // eax -> current
+ lea eax, [eax+edx]
+ mov edx, ditherPrevious
+ neg edx
+ lea edx, [eax+edx] // highpass = current - previous
+ mov highpassedDither, edx
+ mov ditherPrevious, eax // previous = current
+ mov eax, sourceByteStride // restore eax
+ fild highpassedDither
+ fmul const_float_dither_scale_
+ // end generate dither, dither signal in st(0)
+
+ faddp st(1), st(0) // stack: dither * value*(int scaler), int scaler
+ fistp tempInt32 // pop st(0) into tempInt32, stack: int scaler
+ mov edx, tempInt32
+ jmp Float32_To_Int24_DitherClip_store
+
+ Float32_To_Int24_DitherClip_clamp:
+ mov edx, dword ptr [esi] // load floating point value into integer register
+ shr edx, 31 // move sign bit into bit 0
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ add edx, 0x7FFFFF // convert to maximum range integers
+
+ Float32_To_Int24_DitherClip_store:
+
+ mov byte ptr [edi], DL
+ shr edx, 8
+ //mov byte ptr [edi+1], DL
+ //mov byte ptr [edi+2], DH
+ mov word ptr [edi+1], DX
+
+ //add edi, ebx // increment destination ptr
+ lea edi, [edi+ebx]
+
+ cmp esi, ecx // has src ptr reached end?
+ jne Float32_To_Int24_DitherClip_loop
+
+ ffree st(0)
+ fincstp
+
+ fwait
+ fnclex
+ fldcw savedFpuControlWord
+ }
+
+ ditherGenerator->previous = ditherPrevious;
+ ditherGenerator->randSeed1 = ditherRandSeed1;
+ ditherGenerator->randSeed2 = ditherRandSeed2;
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int16(
+ void *destinationBuffer, signed int destinationStride,
+ void *sourceBuffer, signed int sourceStride,
+ unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+ float *src = (float*)sourceBuffer;
+ signed short *dest = (signed short*)destinationBuffer;
+ (void)ditherGenerator; // unused parameter
+
+ while( count-- )
+ {
+
+ short samp = (short) (*src * (32767.0f));
+ *dest = samp;
+
+ src += sourceStride;
+ dest += destinationStride;
+ }
+*/
+
+ short savedFpuControlWord;
+
+ (void) ditherGenerator; /* unused parameter */
+
+ __asm{
+ // esi -> source ptr
+ // eax -> source byte stride
+ // edi -> destination ptr
+ // ebx -> destination byte stride
+ // ecx -> source end ptr
+ // edx -> temp
+
+ mov esi, sourceBuffer
+
+ mov edx, 4 // sizeof float32
+ mov eax, sourceStride
+ imul eax, edx // source byte stride
+
+ mov ecx, count
+ imul ecx, eax
+ add ecx, esi // source end ptr = count * source byte stride + source ptr
+
+ mov edi, destinationBuffer
+
+ mov edx, 2 // sizeof int16
+ mov ebx, destinationStride
+ imul ebx, edx // destination byte stride
+
+ fwait
+ fstcw savedFpuControlWord
+ fldcw fpuControlWord_
+
+ fld int16Scaler_ // stack: (int)0x7FFF
+
+ Float32_To_Int16_loop:
+
+ // load unscaled value into st(0)
+ fld dword ptr [esi] // stack: value, (int)0x7FFF
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ fmul st(0), st(1) // st(0) *= st(1), stack: value*0x7FFF, (int)0x7FFF
+ fistp word ptr [edi] // store scaled int into dest, stack: (int)0x7FFF
+
+ add edi, ebx // increment destination ptr
+ //lea edi, [edi+ebx]
+
+ cmp esi, ecx // has src ptr reached end?
+ jne Float32_To_Int16_loop
+
+ ffree st(0)
+ fincstp
+
+ fwait
+ fnclex
+ fldcw savedFpuControlWord
+ }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int16_Clip(
+ void *destinationBuffer, signed int destinationStride,
+ void *sourceBuffer, signed int sourceStride,
+ unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+ float *src = (float*)sourceBuffer;
+ signed short *dest = (signed short*)destinationBuffer;
+ (void)ditherGenerator; // unused parameter
+
+ while( count-- )
+ {
+ long samp = (signed long) (*src * (32767.0f));
+ PA_CLIP_( samp, -0x8000, 0x7FFF );
+ *dest = (signed short) samp;
+
+ src += sourceStride;
+ dest += destinationStride;
+ }
+*/
+
+ short savedFpuControlWord;
+
+ (void) ditherGenerator; /* unused parameter */
+
+ __asm{
+ // esi -> source ptr
+ // eax -> source byte stride
+ // edi -> destination ptr
+ // ebx -> destination byte stride
+ // ecx -> source end ptr
+ // edx -> temp
+
+ mov esi, sourceBuffer
+
+ mov edx, 4 // sizeof float32
+ mov eax, sourceStride
+ imul eax, edx // source byte stride
+
+ mov ecx, count
+ imul ecx, eax
+ add ecx, esi // source end ptr = count * source byte stride + source ptr
+
+ mov edi, destinationBuffer
+
+ mov edx, 2 // sizeof int16
+ mov ebx, destinationStride
+ imul ebx, edx // destination byte stride
+
+ fwait
+ fstcw savedFpuControlWord
+ fldcw fpuControlWord_
+
+ fld int16Scaler_ // stack: (int)0x7FFF
+
+ Float32_To_Int16_Clip_loop:
+
+ mov edx, dword ptr [esi] // load floating point value into integer register
+
+ and edx, 0x7FFFFFFF // mask off sign
+ cmp edx, 0x3F800000 // greater than 1.0 or less than -1.0
+
+ jg Float32_To_Int16_Clip_clamp
+
+ // load unscaled value into st(0)
+ fld dword ptr [esi] // stack: value, (int)0x7FFF
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ fmul st(0), st(1) // st(0) *= st(1), stack: value*0x7FFF, (int)0x7FFF
+ fistp word ptr [edi] // store scaled int into dest, stack: (int)0x7FFF
+ jmp Float32_To_Int16_Clip_stored
+
+ Float32_To_Int16_Clip_clamp:
+ mov edx, dword ptr [esi] // load floating point value into integer register
+ shr edx, 31 // move sign bit into bit 0
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ add dx, 0x7FFF // convert to maximum range integers
+ mov word ptr [edi], dx // store clamped into into dest
+
+ Float32_To_Int16_Clip_stored:
+
+ add edi, ebx // increment destination ptr
+ //lea edi, [edi+ebx]
+
+ cmp esi, ecx // has src ptr reached end?
+ jne Float32_To_Int16_Clip_loop
+
+ ffree st(0)
+ fincstp
+
+ fwait
+ fnclex
+ fldcw savedFpuControlWord
+ }
+}
+
+/* -------------------------------------------------------------------------- */
+
+static void Float32_To_Int16_DitherClip(
+ void *destinationBuffer, signed int destinationStride,
+ void *sourceBuffer, signed int sourceStride,
+ unsigned int count, PaUtilTriangularDitherGenerator *ditherGenerator )
+{
+/*
+ float *src = (float*)sourceBuffer;
+ signed short *dest = (signed short*)destinationBuffer;
+ (void)ditherGenerator; // unused parameter
+
+ while( count-- )
+ {
+
+ float dither = PaUtil_GenerateFloatTriangularDither( ditherGenerator );
+ // use smaller scaler to prevent overflow when we add the dither
+ float dithered = (*src * (32766.0f)) + dither;
+ signed long samp = (signed long) dithered;
+ PA_CLIP_( samp, -0x8000, 0x7FFF );
+ *dest = (signed short) samp;
+
+ src += sourceStride;
+ dest += destinationStride;
+ }
+*/
+
+ short savedFpuControlWord;
+
+ // spill storage:
+ signed long sourceByteStride;
+ signed long highpassedDither;
+
+ // dither state:
+ unsigned long ditherPrevious = ditherGenerator->previous;
+ unsigned long ditherRandSeed1 = ditherGenerator->randSeed1;
+ unsigned long ditherRandSeed2 = ditherGenerator->randSeed2;
+
+ __asm{
+ // esi -> source ptr
+ // eax -> source byte stride
+ // edi -> destination ptr
+ // ebx -> destination byte stride
+ // ecx -> source end ptr
+ // edx -> temp
+
+ mov esi, sourceBuffer
+
+ mov edx, 4 // sizeof float32
+ mov eax, sourceStride
+ imul eax, edx // source byte stride
+
+ mov ecx, count
+ imul ecx, eax
+ add ecx, esi // source end ptr = count * source byte stride + source ptr
+
+ mov edi, destinationBuffer
+
+ mov edx, 2 // sizeof int16
+ mov ebx, destinationStride
+ imul ebx, edx // destination byte stride
+
+ fwait
+ fstcw savedFpuControlWord
+ fldcw fpuControlWord_
+
+ fld ditheredInt16Scaler_ // stack: int scaler
+
+ Float32_To_Int16_DitherClip_loop:
+
+ mov edx, dword ptr [esi] // load floating point value into integer register
+
+ and edx, 0x7FFFFFFF // mask off sign
+ cmp edx, 0x3F800000 // greater than 1.0 or less than -1.0
+
+ jg Float32_To_Int16_DitherClip_clamp
+
+ // load unscaled value into st(0)
+ fld dword ptr [esi] // stack: value, int scaler
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ fmul st(0), st(1) // st(0) *= st(1), stack: value*(int scaler), int scaler
+
+ /*
+ // call PaUtil_GenerateFloatTriangularDither with C calling convention
+ mov sourceByteStride, eax // save eax
+ mov sourceEnd, ecx // save ecx
+ push ditherGenerator // pass ditherGenerator parameter on stack
+ call PaUtil_GenerateFloatTriangularDither // stack: dither, value*(int scaler), int scaler
+ pop edx // clear parameter off stack
+ mov ecx, sourceEnd // restore ecx
+ mov eax, sourceByteStride // restore eax
+ */
+
+ // generate dither
+ mov sourceByteStride, eax // save eax
+ mov edx, 196314165
+ mov eax, ditherRandSeed1
+ mul edx // eax:edx = eax * 196314165
+ //add eax, 907633515
+ lea eax, [eax+907633515]
+ mov ditherRandSeed1, eax
+ mov edx, 196314165
+ mov eax, ditherRandSeed2
+ mul edx // eax:edx = eax * 196314165
+ //add eax, 907633515
+ lea eax, [eax+907633515]
+ mov edx, ditherRandSeed1
+ shr edx, PA_DITHER_SHIFT_
+ mov ditherRandSeed2, eax
+ shr eax, PA_DITHER_SHIFT_
+ //add eax, edx // eax -> current
+ lea eax, [eax+edx] // current = randSeed1>>x + randSeed2>>x
+ mov edx, ditherPrevious
+ neg edx
+ lea edx, [eax+edx] // highpass = current - previous
+ mov highpassedDither, edx
+ mov ditherPrevious, eax // previous = current
+ mov eax, sourceByteStride // restore eax
+ fild highpassedDither
+ fmul const_float_dither_scale_
+ // end generate dither, dither signal in st(0)
+
+ faddp st(1), st(0) // stack: dither * value*(int scaler), int scaler
+ fistp word ptr [edi] // store scaled int into dest, stack: int scaler
+ jmp Float32_To_Int16_DitherClip_stored
+
+ Float32_To_Int16_DitherClip_clamp:
+ mov edx, dword ptr [esi] // load floating point value into integer register
+ shr edx, 31 // move sign bit into bit 0
+ add esi, eax // increment source ptr
+ //lea esi, [esi+eax]
+ add dx, 0x7FFF // convert to maximum range integers
+ mov word ptr [edi], dx // store clamped into into dest
+
+ Float32_To_Int16_DitherClip_stored:
+
+ add edi, ebx // increment destination ptr
+ //lea edi, [edi+ebx]
+
+ cmp esi, ecx // has src ptr reached end?
+ jne Float32_To_Int16_DitherClip_loop
+
+ ffree st(0)
+ fincstp
+
+ fwait
+ fnclex
+ fldcw savedFpuControlWord
+ }
+
+ ditherGenerator->previous = ditherPrevious;
+ ditherGenerator->randSeed1 = ditherRandSeed1;
+ ditherGenerator->randSeed2 = ditherRandSeed2;
+}
+
+/* -------------------------------------------------------------------------- */
+
+void PaUtil_InitializeX86PlainConverters( void )
+{
+ paConverters.Float32_To_Int32 = Float32_To_Int32;
+ paConverters.Float32_To_Int32_Clip = Float32_To_Int32_Clip;
+ paConverters.Float32_To_Int32_DitherClip = Float32_To_Int32_DitherClip;
+
+ paConverters.Float32_To_Int24 = Float32_To_Int24;
+ paConverters.Float32_To_Int24_Clip = Float32_To_Int24_Clip;
+ paConverters.Float32_To_Int24_DitherClip = Float32_To_Int24_DitherClip;
+
+ paConverters.Float32_To_Int16 = Float32_To_Int16;
+ paConverters.Float32_To_Int16_Clip = Float32_To_Int16_Clip;
+ paConverters.Float32_To_Int16_DitherClip = Float32_To_Int16_DitherClip;
+}
+
+#endif
+
+/* -------------------------------------------------------------------------- */
diff --git a/pd/portaudio/src/os/win/pa_x86_plain_converters.h b/pd/portaudio/src/os/win/pa_x86_plain_converters.h
new file mode 100644
index 00000000..96b41b85
--- /dev/null
+++ b/pd/portaudio/src/os/win/pa_x86_plain_converters.h
@@ -0,0 +1,60 @@
+/*
+ * Plain Intel IA32 assembly implementations of PortAudio sample converter functions.
+ * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
+ * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/*
+ * The text above constitutes the entire PortAudio license; however,
+ * the PortAudio community also makes the following non-binding requests:
+ *
+ * Any person wishing to distribute modifications to the Software is
+ * requested to send the modifications to the original developer so that
+ * they can be incorporated into the canonical version. It is also
+ * requested that these non-binding requests be included along with the
+ * license above.
+ */
+
+/** @file
+ @ingroup win_src
+*/
+
+#ifndef PA_X86_PLAIN_CONVERTERS_H
+#define PA_X86_PLAIN_CONVERTERS_H
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif /* __cplusplus */
+
+
+/**
+ @brief Install optimised converter functions suitable for all IA32 processors
+
+ It is recommended to call PaUtil_InitializeX86PlainConverters prior to calling Pa_Initialize
+*/
+void PaUtil_InitializeX86PlainConverters( void );
+
+
+#ifdef __cplusplus
+}
+#endif /* __cplusplus */
+#endif /* PA_X86_PLAIN_CONVERTERS_H */