From beb2211b63b4b80ee07a807e5ffdd441aeea6354 Mon Sep 17 00:00:00 2001 From: Miller Puckette Date: Sat, 3 Jun 2006 19:13:08 +0000 Subject: FFT package selection Zmoelnig's multi-'$' patch big-soundfile support Patch to set open directories (openpanel, savepanel) patch to allow funny characters in extern names fixed makefile.in to support intel mac svn path=/trunk/; revision=5164 --- pd/portaudio/pa_linux_alsa/pa_linux_alsa.c | 1150 +++++++++++++++++++--------- 1 file changed, 780 insertions(+), 370 deletions(-) (limited to 'pd/portaudio/pa_linux_alsa') diff --git a/pd/portaudio/pa_linux_alsa/pa_linux_alsa.c b/pd/portaudio/pa_linux_alsa/pa_linux_alsa.c index 0d0aa1ce..2f88fc2f 100644 --- a/pd/portaudio/pa_linux_alsa/pa_linux_alsa.c +++ b/pd/portaudio/pa_linux_alsa/pa_linux_alsa.c @@ -1,11 +1,11 @@ /* - * $Id: pa_linux_alsa.c,v 1.1.2.71 2005/04/15 18:20:18 aknudsen Exp $ + * $Id: pa_linux_alsa.c,v 1.1.2.92 2006/03/22 19:36:04 aknudsen 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 - * Copyright (c) 2005 Arve Knudsen + * Copyright (c) 2005-2006 Arve Knudsen * * Based on the Open Source API proposed by Ross Bencina * Copyright (c) 1999-2002 Ross Bencina, Phil Burk @@ -71,15 +71,32 @@ { \ PaUtil_SetLastHostErrorInfo( paALSA, aErr_, snd_strerror( aErr_ ) ); \ } \ - PaUtil_DebugPrint(( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" )); \ + 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 ENSURE_SYSTEM_(expr, success) \ + do { \ + if( UNLIKELY( (aErr_ = (expr)) != success ) ) \ + { \ + /* PaUtil_SetLastHostErrorInfo should only be used in the main thread */ \ + if( pthread_self() != callbackThread_ ) \ + { \ + PaUtil_SetLastHostErrorInfo( paALSA, aErr_, strerror( aErr_ ) ); \ + } \ + PaUtil_DebugPrint( "Expression '" #expr "' failed in '" __FILE__ "', line: " STRINGIZE( __LINE__ ) "\n" ); \ + result = paUnanticipatedHostError; \ + goto error; \ + } \ + } while( 0 ); + #define ASSERT_CALL_(expr, success) \ aErr_ = (expr); \ - assert( aErr_ == success ); + assert( success == aErr_ ); static int aErr_; /* Used with ENSURE_ */ static pthread_t callbackThread_; @@ -132,7 +149,7 @@ typedef struct PaAlsaStream PaUtilBufferProcessor bufferProcessor; PaAlsaThreading threading; - unsigned long framesPerUserBuffer; + unsigned long framesPerUserBuffer, maxFramesPerHostBuffer; int primeBuffers; int callbackMode; /* bool: are we running in callback mode? */ @@ -140,7 +157,7 @@ typedef struct PaAlsaStream /* the callback thread uses these to poll the sound device(s), waiting * for data to be ready/available */ - struct pollfd *pfds; + struct pollfd* pfds; int pollTimeout; /* Used in communication between threads */ @@ -165,7 +182,7 @@ PaAlsaStream; typedef struct PaAlsaHostApiRepresentation { - PaUtilHostApiRepresentation commonHostApiRep; + PaUtilHostApiRepresentation baseHostApiRep; PaUtilStreamInterface callbackStreamInterface; PaUtilStreamInterface blockingStreamInterface; @@ -177,7 +194,7 @@ PaAlsaHostApiRepresentation; typedef struct PaAlsaDeviceInfo { - PaDeviceInfo commonDeviceInfo; + PaDeviceInfo baseDeviceInfo; char *alsaName; int isPlug; int minInputChannels; @@ -214,7 +231,7 @@ static PaError KillCallbackThread( PaAlsaThreading *th, int wait, PaError *exitR if( th->watchdogRunning ) { pthread_cancel( th->watchdogThread ); - ASSERT_CALL_( pthread_join( th->watchdogThread, &pret ), 0 ); + ENSURE_SYSTEM_( pthread_join( th->watchdogThread, &pret ), 0 ); if( pret && pret != PTHREAD_CANCELED ) { @@ -227,8 +244,12 @@ static PaError KillCallbackThread( PaAlsaThreading *th, int wait, PaError *exitR /* Only kill the thread if it isn't in the process of stopping (flushing adaptation buffers) */ /* TODO: Make join time out */ if( !wait ) + { + PA_DEBUG(( "%s: Canceling thread %d\n", __FUNCTION__, th->callbackThread )); pthread_cancel( th->callbackThread ); /* XXX: Safe to call this if the thread has exited on its own? */ - ASSERT_CALL_( pthread_join( th->callbackThread, &pret ), 0 ); + } + PA_DEBUG(( "%s: Joining thread %d\n", __FUNCTION__, th->callbackThread )); + ENSURE_SYSTEM_( pthread_join( th->callbackThread, &pret ), 0 ); if( pret && pret != PTHREAD_CANCELED ) { @@ -237,6 +258,40 @@ static PaError KillCallbackThread( PaAlsaThreading *th, int wait, PaError *exitR free( pret ); } +error: + return result; +} + +/** Lock a pthread_mutex_t. + * + * @concern ThreadCancellation We're disabling thread cancellation while the thread is holding a lock, so mutexes are + * properly unlocked at termination time. + */ +static PaError LockMutex( pthread_mutex_t *mtx ) +{ + PaError result = paNoError; + int oldState; + + ENSURE_SYSTEM_( pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, &oldState ), 0 ); + ENSURE_SYSTEM_( pthread_mutex_lock( mtx ), 0 ); + +error: + return result; +} + +/** Unlock a pthread_mutex_t. + * + * @concern ThreadCancellation Thread cancellation is enabled again after the mutex is properly unlocked. + */ +static PaError UnlockMutex( pthread_mutex_t *mtx ) +{ + PaError result = paNoError; + int oldState; + + ENSURE_SYSTEM_( pthread_mutex_unlock( mtx ), 0 ); + ENSURE_SYSTEM_( pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, &oldState ), 0 ); + +error: return result; } @@ -283,13 +338,15 @@ static void *WatchdogFunc( void *userData ) assert( th ); - pthread_cleanup_push( &OnWatchdogExit, th ); /* Execute OnWatchdogExit when exiting */ + /* Execute OnWatchdogExit when exiting */ + pthread_cleanup_push( &OnWatchdogExit, th ); /* Boost priority of callback thread */ PA_ENSURE( result = BoostPriority( th ) ); if( !result ) { - pthread_exit( NULL ); /* Boost failed, might as well exit */ + /* Boost failed, might as well exit */ + pthread_exit( NULL ); } cpuTimeThen = th->callbackCpuTime; @@ -445,7 +502,7 @@ static PaError CreateCallbackThread( PaAlsaThreading *th, void *(*callbackThread { int policy; th->watchdogRunning = 1; - ASSERT_CALL_( pthread_getschedparam( th->watchdogThread, &policy, &wdSpm ), 0 ); + ENSURE_SYSTEM_( pthread_getschedparam( th->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 ) { @@ -516,6 +573,10 @@ static const PaAlsaDeviceInfo *GetDeviceInfo( const PaUtilHostApiRepresentation 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; @@ -535,6 +596,8 @@ PaError PaAlsa_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex (*hostApi)->OpenStream = OpenStream; (*hostApi)->IsFormatSupported = IsFormatSupported; + ENSURE_( snd_lib_error_set_handler(AlsaErrorHandler), paUnanticipatedHostError ); + PA_ENSURE( BuildDeviceList( alsaHostApi ) ); PaUtil_InitializeStreamInterface( &alsaHostApi->callbackStreamInterface, @@ -588,28 +651,49 @@ static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) snd_config_update_free_global(); } -/*! Determine max channels and default latencies. +/** 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 *minChannels, int *maxChannels, double *defaultLowLatency, - double *defaultHighLatency, double *defaultSampleRate, int isPlug ) +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, @@ -624,10 +708,14 @@ static PaError GropeDevice( snd_pcm_t *pcm, int *minChannels, int *maxChannels, if( defaultSr < 0. ) /* Default sample rate not set */ { unsigned int sampleRate = 44100; /* Will contain approximate rate returned by alsa-lib */ - ENSURE_( snd_pcm_hw_params_set_rate_near( pcm, hwParams, &sampleRate, NULL ), paUnanticipatedHostError ); + 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 ); @@ -723,22 +811,22 @@ error: return result; } -/* Disregard standard plugins - * XXX: Might want to make the "default" plugin available, if we can make it work +/* Disregard some standard plugins */ static int IgnorePlugin( const char *pluginId ) { -#define numIgnored 10 - static const char *ignoredPlugins[numIgnored] = {"hw", "plughw", "plug", "default", "dsnoop", "dmix", "tee", - "file", "null", "shm"}; - int i; - - for( i = 0; i < numIgnored; ++i ) + /* XXX: dmix and default ignored because after opening and closing, they seem to keep hogging resources. + */ + static const char *ignoredPlugins[] = {"hw", "plughw", "plug", "dsnoop", "tee", + "file", "null", "shm", "cards", "dmix", "default", NULL}; + int i = 0; + while( ignoredPlugins[i] ) { if( !strcmp( pluginId, ignoredPlugins[i] ) ) { return 1; } + ++i; } return 0; @@ -747,7 +835,7 @@ static int IgnorePlugin( const char *pluginId ) /* Build PaDeviceInfo list, ignore devices for which we cannot determine capabilities (possibly busy, sigh) */ static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi ) { - PaUtilHostApiRepresentation *commonApi = &alsaApi->commonHostApiRep; + PaUtilHostApiRepresentation *baseApi = &alsaApi->baseHostApiRep; PaAlsaDeviceInfo *deviceInfoArray; int cardIdx = -1, devIdx = 0; snd_ctl_card_info_t *cardInfo; @@ -763,8 +851,8 @@ static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi ) blocking = 0; /* These two will be set to the first working input and output device, respectively */ - commonApi->info.defaultInputDevice = paNoDevice; - commonApi->info.defaultOutputDevice = paNoDevice; + baseApi->info.defaultInputDevice = paNoDevice; + baseApi->info.defaultOutputDevice = paNoDevice; /* count the devices by enumerating all the card numbers */ @@ -788,7 +876,10 @@ static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi ) /* Acquire name of card */ if( snd_ctl_open( &ctl, alsaCardName, 0 ) < 0 ) - continue; /* Unable to open card :( */ + { + /* Unable to open card :( */ + continue; + } snd_ctl_card_info( ctl, cardInfo ); PA_ENSURE( PaAlsa_StrDup( alsaApi, &cardName, snd_ctl_card_info_get_name( cardInfo )) ); @@ -805,11 +896,15 @@ static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi ) 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 ) { @@ -843,29 +938,42 @@ static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi ) } /* Iterate over plugin devices */ - snd_config_update(); + 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 = NULL, *idStr = NULL; - char *alsaDeviceName, *deviceName; - snd_config_t *n = snd_config_iterator_entry( i ), *tp = NULL; - if( snd_config_get_type( n ) != SND_CONFIG_TYPE_COMPOUND ) - continue; + const char *tpStr = "unknown", *idStr = NULL; + int err = 0; - ENSURE_( snd_config_search( n, "type", &tp ), paUnanticipatedHostError ); - ENSURE_( snd_config_get_string( tp, &tpStr ), paUnanticipatedHostError ); + char *alsaDeviceName, *deviceName; + 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, @@ -894,7 +1002,7 @@ static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi ) 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( commonApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( + PA_UNLESS( baseApi->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( alsaApi->allocations, sizeof(PaDeviceInfo*) * (numDeviceNames) ), paInsufficientMemory ); /* allocate all device info structs in a contiguous block */ @@ -909,10 +1017,11 @@ static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi ) { snd_pcm_t *pcm; PaAlsaDeviceInfo *deviceInfo = &deviceInfoArray[devIdx]; - PaDeviceInfo *commonDeviceInfo = &deviceInfo->commonDeviceInfo; + PaDeviceInfo *baseDeviceInfo = &deviceInfo->baseDeviceInfo; + int canMmap = -1; /* Zero fields */ - InitializeDeviceInfo( commonDeviceInfo ); + InitializeDeviceInfo( baseDeviceInfo ); /* to determine device capabilities, we must open the device and query the * hardware parameter configuration space */ @@ -921,50 +1030,63 @@ static PaError BuildDeviceList( PaAlsaHostApiRepresentation *alsaApi ) if( deviceNames[i].hasCapture && snd_pcm_open( &pcm, deviceNames[i].alsaName, SND_PCM_STREAM_CAPTURE, blocking ) >= 0 ) { - if( GropeDevice( pcm, &deviceInfo->minInputChannels, &commonDeviceInfo->maxInputChannels, - &commonDeviceInfo->defaultLowInputLatency, &commonDeviceInfo->defaultHighInputLatency, - &commonDeviceInfo->defaultSampleRate, deviceNames[i].isPlug ) != paNoError ) - continue; /* Error */ + if( GropeDevice( pcm, deviceNames[i].isPlug, StreamDirection_In, blocking, deviceInfo, + &canMmap ) != paNoError ) + { + /* Error */ + PA_DEBUG(("%s: Failed groping %s for capture\n", __FUNCTION__, deviceNames[i].alsaName)); + continue; + } } /* Query playback */ if( deviceNames[i].hasPlayback && snd_pcm_open( &pcm, deviceNames[i].alsaName, SND_PCM_STREAM_PLAYBACK, blocking ) >= 0 ) { - if( GropeDevice( pcm, &deviceInfo->minOutputChannels, &commonDeviceInfo->maxOutputChannels, - &commonDeviceInfo->defaultLowOutputLatency, &commonDeviceInfo->defaultHighOutputLatency, - &commonDeviceInfo->defaultSampleRate, deviceNames[i].isPlug ) != paNoError ) - continue; /* Error */ + if( GropeDevice( pcm, deviceNames[i].isPlug, StreamDirection_Out, blocking, deviceInfo, + &canMmap ) != paNoError ) + { + /* Error */ + PA_DEBUG(("%s: Failed groping %s for playback\n", __FUNCTION__, deviceNames[i].alsaName)); + continue; + } + } + + if( 0 == canMmap ) + { + PA_DEBUG(("%s: Device %s doesn't support mmap\n", __FUNCTION__, deviceNames[i].alsaName)); + continue; } - commonDeviceInfo->structVersion = 2; - commonDeviceInfo->hostApi = alsaApi->hostApiIndex; - commonDeviceInfo->name = deviceNames[i].name; + baseDeviceInfo->structVersion = 2; + baseDeviceInfo->hostApi = alsaApi->hostApiIndex; + baseDeviceInfo->name = deviceNames[i].name; deviceInfo->alsaName = deviceNames[i].alsaName; deviceInfo->isPlug = deviceNames[i].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( commonDeviceInfo->maxInputChannels > 0 || commonDeviceInfo->maxOutputChannels > 0 ) + if( baseDeviceInfo->maxInputChannels > 0 || baseDeviceInfo->maxOutputChannels > 0 ) { - if( commonApi->info.defaultInputDevice == paNoDevice && commonDeviceInfo->maxInputChannels > 0 ) - commonApi->info.defaultInputDevice = devIdx; - if( commonApi->info.defaultOutputDevice == paNoDevice && commonDeviceInfo->maxOutputChannels > 0 ) - commonApi->info.defaultOutputDevice = devIdx; - - commonApi->deviceInfos[devIdx++] = (PaDeviceInfo *) deviceInfo; + if( baseApi->info.defaultInputDevice == paNoDevice && baseDeviceInfo->maxInputChannels > 0 ) + baseApi->info.defaultInputDevice = devIdx; + if( baseApi->info.defaultOutputDevice == paNoDevice && baseDeviceInfo->maxOutputChannels > 0 ) + baseApi->info.defaultOutputDevice = devIdx; + PA_DEBUG(("%s: Adding device %s\n", __FUNCTION__, deviceNames[i].name)); + baseApi->deviceInfos[devIdx++] = (PaDeviceInfo *) deviceInfo; } } free( deviceNames ); - commonApi->info.deviceCount = devIdx; /* Number of successfully queried devices */ + baseApi->info.deviceCount = devIdx; /* Number of successfully queried devices */ end: return result; error: - goto end; /* No particular action */ + /* No particular action */ + goto end; } /* Check against known device capabilities */ @@ -988,14 +1110,16 @@ static PaError ValidateParameters( const PaStreamParameters *parameters, PaUtilH PA_UNLESS( parameters->device == paUseHostApiSpecificDeviceSpecification, paInvalidDevice ); PA_UNLESS( streamInfo->size == sizeof (PaAlsaStreamInfo) && streamInfo->version == 1, paIncompatibleHostApiSpecificStreamInfo ); + PA_UNLESS( streamInfo->deviceString != NULL, paInvalidDevice ); - return paNoError; /* Skip further checking */ + /* Skip further checking */ + return paNoError; } assert( deviceInfo ); assert( parameters->hostApiSpecificStreamInfo == NULL ); - maxChans = (StreamDirection_In == mode ? deviceInfo->commonDeviceInfo.maxInputChannels : - deviceInfo->commonDeviceInfo.maxOutputChannels); + maxChans = (StreamDirection_In == mode ? deviceInfo->baseDeviceInfo.maxInputChannels : + deviceInfo->baseDeviceInfo.maxOutputChannels); PA_UNLESS( parameters->channelCount <= maxChans, paInvalidChannelCount ); error: @@ -1003,7 +1127,6 @@ error: } /* Given an open stream, what sample formats are available? */ - static PaSampleFormat GetAvailableFormats( snd_pcm_t *pcm ) { PaSampleFormat available = 0; @@ -1091,10 +1214,12 @@ static PaError AlsaOpen( const PaUtilHostApiRepresentation *hostApi, const PaStr else deviceName = streamInfo->deviceString; + PA_DEBUG(( "%s: Opening device %s\n", __FUNCTION__, deviceName )); if( (ret = snd_pcm_open( pcm, deviceName, streamDir == StreamDirection_In ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK )) < 0 ) { - *pcm = NULL; /* Not to be closed */ + /* Not to be closed */ + *pcm = NULL; ENSURE_( ret, ret == -EBUSY ? paDeviceUnavailable : paBadIODeviceCombination ); } ENSURE_( snd_pcm_nonblock( *pcm, 0 ), paUnanticipatedHostError ); @@ -1148,11 +1273,20 @@ static PaError TestParameters( const PaUtilHostApiRepresentation *hostApi, const PA_ENSURE( hostFormat = PaUtil_SelectClosestAvailableFormat( availableFormats, parameters->sampleFormat ) ); ENSURE_( snd_pcm_hw_params_set_format( pcm, hwParams, Pa2AlsaFormat( hostFormat ) ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_hw_params( pcm, hwParams ), paUnanticipatedHostError ); + { + /* It happens that this call fails because the device is busy */ + int ret = 0; + if( (ret = snd_pcm_hw_params( pcm, hwParams )) < 0) + { + ENSURE_( ret, ret == -EBUSY ? paDeviceUnavailable : paUnanticipatedHostError ); + } + } end: if( pcm ) + { snd_pcm_close( pcm ); + } return result; error: @@ -1215,7 +1349,7 @@ static PaError PaAlsaStreamComponent_Initialize( PaAlsaStreamComponent *self, Pa if( NULL == params->hostApiSpecificStreamInfo ) { - const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( &alsaApi->commonHostApiRep, params->device ); + const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( &alsaApi->baseHostApiRep, params->device ); self->numHostChannels = PA_MAX( params->channelCount, StreamDirection_In == streamDir ? devInfo->minInputChannels : devInfo->minOutputChannels ); } @@ -1225,7 +1359,7 @@ static PaError PaAlsaStreamComponent_Initialize( PaAlsaStreamComponent *self, Pa self->numHostChannels = params->channelCount; } - PA_ENSURE( AlsaOpen( &alsaApi->commonHostApiRep, params, streamDir, &self->pcm ) ); + 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 ); @@ -1253,25 +1387,18 @@ static void PaAlsaStreamComponent_Terminate( PaAlsaStreamComponent *self ) PaUtil_FreeMemory( self->userBuffers ); } -/** Configure the associated ALSA pcm. +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_Configure( PaAlsaStreamComponent *self, const PaStreamParameters *params, unsigned long - framesPerHostBuffer, int primeBuffers, int callbackMode, double *sampleRate, PaTime *returnedLatency ) +static PaError PaAlsaStreamComponent_InitialConfigure( PaAlsaStreamComponent *self, const PaStreamParameters *params, + int primeBuffers, snd_pcm_hw_params_t *hwParams, double *sampleRate ) { - /* - int numPeriods; - - if( getenv("PA_NUMPERIODS") != NULL ) - numPeriods = atoi( getenv("PA_NUMPERIODS") ); - else - numPeriods = ( (latency * sampleRate) / *framesPerBuffer ) + 1; - - PA_DEBUG(( "latency: %f, rate: %f, framesPerBuffer: %d\n", latency, sampleRate, *framesPerBuffer )); - if( numPeriods <= 1 ) - numPeriods = 2; - */ - /* Configuration consists of setting all of ALSA's parameters. * These parameters come in two flavors: hardware parameters * and software paramters. Hardware parameters will affect @@ -1279,28 +1406,23 @@ static PaError PaAlsaStreamComponent_Configure( PaAlsaStreamComponent *self, con * affect the way ALSA interacts with me, the user-level client. */ - snd_pcm_hw_params_t *hwParams; - snd_pcm_sw_params_t *swParams; PaError result = paNoError; snd_pcm_access_t accessMode, alternateAccessMode; - unsigned int numPeriods, minPeriods = 2; int dir = 0; snd_pcm_t *pcm = self->pcm; - PaTime latency = params->suggestedLatency; double sr = *sampleRate; - *returnedLatency = -1.; + unsigned int minPeriods = 2; - snd_pcm_hw_params_alloca( &hwParams ); - snd_pcm_sw_params_alloca( &swParams ); - - self->framesPerBuffer = framesPerHostBuffer; + /* 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 ); - ENSURE_( snd_pcm_hw_params_set_period_size_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 ) { @@ -1312,11 +1434,23 @@ static PaError PaAlsaStreamComponent_Configure( PaAlsaStreamComponent *self, con 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 ) { - ENSURE_( snd_pcm_hw_params_set_access( pcm, hwParams, alternateAccessMode ), paUnanticipatedHostError ); + 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; } @@ -1334,56 +1468,64 @@ static PaError PaAlsaStreamComponent_Configure( PaAlsaStreamComponent *self, con ENSURE_( snd_pcm_hw_params_set_channels( pcm, hwParams, self->numHostChannels ), paInvalidChannelCount ); - /* 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 ); - dir = 0; - ENSURE_( snd_pcm_hw_params_set_period_size_near( pcm, hwParams, &self->framesPerBuffer, &dir ), paUnanticipatedHostError ); - - /* Find an acceptable number of periods */ - numPeriods = (latency * sr) / self->framesPerBuffer + 1; - dir = 0; - ENSURE_( snd_pcm_hw_params_set_periods_near( pcm, hwParams, &numPeriods, &dir ), paUnanticipatedHostError ); - /* Minimum of periods should already be 2 */ - PA_UNLESS( numPeriods >= 2, paInternalError ); + *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) + self->framesPerBuffer; /* One period does not count as latency */ + ENSURE_( snd_pcm_hw_params_set_buffer_size_near( self->pcm, hwParams, &bufSz ), paUnanticipatedHostError ); /* Set the parameters! */ - ENSURE_( snd_pcm_hw_params( pcm, hwParams ), paUnanticipatedHostError ); + ENSURE_( snd_pcm_hw_params( self->pcm, hwParams ), paUnanticipatedHostError ); ENSURE_( snd_pcm_hw_params_get_buffer_size( hwParams, &self->bufferSize ), paUnanticipatedHostError ); - /* Latency in seconds, one period is not counted as latency */ - latency = (numPeriods - 1) * self->framesPerBuffer / sr; + *latency = (self->bufferSize - self->framesPerBuffer) / sampleRate; /* Now software parameters... */ - ENSURE_( snd_pcm_sw_params_current( pcm, swParams ), paUnanticipatedHostError ); + ENSURE_( snd_pcm_sw_params_current( self->pcm, swParams ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_sw_params_set_start_threshold( pcm, swParams, self->framesPerBuffer ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_sw_params_set_stop_threshold( pcm, swParams, self->bufferSize ), 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( pcm, swParams, 0 ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_sw_params_set_silence_size( pcm, 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( pcm, swParams, self->framesPerBuffer ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_sw_params_set_xfer_align( pcm, swParams, 1 ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_sw_params_set_tstamp_mode( pcm, swParams, SND_PCM_TSTAMP_MMAP ), 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( pcm, swParams ), paUnanticipatedHostError ); - - *sampleRate = sr; - *returnedLatency = latency; - -end: - return result; + ENSURE_( snd_pcm_sw_params( self->pcm, swParams ), paUnanticipatedHostError ); error: - goto end; /* No particular action */ + return result; } static PaError PaAlsaStream_Initialize( PaAlsaStream *self, PaAlsaHostApiRepresentation *alsaApi, const PaStreamParameters *inParams, @@ -1475,78 +1617,171 @@ static int CalculatePollTimeout( const PaAlsaStream *stream, unsigned long frame return (int)ceil( 1000 * frames / stream->streamRepresentation.streamInfo.sampleRate ); } -/** Set up ALSA stream parameters. +/** 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 PaAlsaStream_Configure( PaAlsaStream *self, const PaStreamParameters *inParams, const PaStreamParameters - *outParams, double sampleRate, unsigned long framesPerHostBuffer, double *inputLatency, double *outputLatency, - unsigned long *maxHostBufferSize ) +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; - double realSr = sampleRate; - - if( self->capture.pcm ) - PA_ENSURE( PaAlsaStreamComponent_Configure( &self->capture, inParams, framesPerHostBuffer, self->primeBuffers, - self->callbackMode, &realSr, inputLatency ) ); - if( self->playback.pcm ) - PA_ENSURE( PaAlsaStreamComponent_Configure( &self->playback, outParams, framesPerHostBuffer, self->primeBuffers, - self->callbackMode, &realSr, outputLatency ) ); + 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 ); + } - /* Should be exact now */ - self->streamRepresentation.streamInfo.sampleRate = realSr; + assert( bufferSize > 0 ); - /* 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 ) + if( framesPerUserBuffer != paFramesPerBufferUnspecified ) { - 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 ) )); - } + /* Preferably the host buffer size should be a multiple of the user buffer size */ - /* Frames per host buffer for the stream is set as a compromise between the two directions */ - framesPerHostBuffer = PA_MIN( self->capture.pcm ? self->capture.framesPerBuffer : ULONG_MAX, - self->playback.pcm ? self->playback.framesPerBuffer : ULONG_MAX ); - self->pollTimeout = CalculatePollTimeout( self, framesPerHostBuffer ); /* Period in msecs, rounded up */ + if( bufferSize > framesPerUserBuffer ) + { + snd_pcm_uframes_t remainder = bufferSize % framesPerUserBuffer; + if( remainder > framesPerUserBuffer / 2. ) + bufferSize += framesPerUserBuffer - remainder; + else + bufferSize -= remainder; - *maxHostBufferSize = PA_MAX( self->capture.pcm ? self->capture.bufferSize : 0, - self->playback.pcm ? self->playback.bufferSize : 0 ); + 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; + } - /* Time before watchdog unthrottles realtime thread == 1/4 of period time in msecs */ - self->threading.throttledSleepTime = (unsigned long) (framesPerHostBuffer / sampleRate / 4 * 1000); + assert( framesPerUserBuffer % bufferSize == 0 ); + } + } - if( self->callbackMode ) + /* Using 5 as a 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 */ { - /* 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 ) + unsigned numPeriods = 4, 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 ); + /* One period is not counted as latency */ + maxPeriods -= 1; + numPeriods = PA_MIN( maxPeriods, numPeriods ); + + if( framesPerUserBuffer != paFramesPerBufferUnspecified ) { - /* self->alignFrames = 1; */ + framesPerHostBuffer = framesPerUserBuffer; + if( framesPerHostBuffer < bufferSize ) + { + while( bufferSize / framesPerHostBuffer > numPeriods ) + { + framesPerHostBuffer *= 2; + } + } + else + { + while( bufferSize / framesPerHostBuffer < numPeriods ) + { + if( framesPerUserBuffer % (framesPerHostBuffer / 2) != 0 ) + { + /* Can't be divided any further */ + break; + } + framesPerHostBuffer /= 2; + } + } - /* 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; + 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 - self->alignFrames = 1; - */ + { + 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 ) + { + framesPerHostBuffer = min; + PA_DEBUG(( "%s: The determined period size (%lu) is less than minimum (%lu)\n", __FUNCTION__, + framesPerHostBuffer, min )); + } + else if( framesPerHostBuffer > max ) + { + framesPerHostBuffer = max; + PA_DEBUG(( "%s: The determined period size (%lu) is greater than maximum (%lu)\n", __FUNCTION__, + 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 to use. Our +/* 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 - * most closely honor the requested latency settings. Therefore this + * 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 @@ -1556,6 +1791,18 @@ error: * 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. * @@ -1563,175 +1810,273 @@ error: * 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 DetermineFramesPerBuffer( const PaAlsaStream *stream, double sampleRate, const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, unsigned long *determinedFrames, const PaUtilHostApiRepresentation *hostApi ) +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 framesPerBuffer = 0; - int numHostInputChannels = 0, numHostOutputChannels = 0; - - /* XXX: Clean this up */ - if( stream->capture.pcm ) - { - const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( hostApi, inputParameters->device ); - numHostInputChannels = PA_MAX( inputParameters->channelCount, devInfo->minInputChannels ); - } - if( stream->playback.pcm ) - { - const PaAlsaDeviceInfo *devInfo = GetDeviceInfo( hostApi, outputParameters->device ); - numHostOutputChannels = PA_MAX( outputParameters->channelCount, devInfo->minOutputChannels ); - } + unsigned long framesPerHostBuffer = 0; + int dir = 0; + int accurate = 1; - if( stream->capture.pcm && stream->playback.pcm ) + if( self->capture.pcm && self->playback.pcm ) { - snd_pcm_uframes_t desiredLatency, e; - snd_pcm_uframes_t minPeriodSize, minPlayback, minCapture, maxPeriodSize, maxPlayback, maxCapture, - optimalPeriodSize, periodSize; - int dir = 0; - unsigned int minPeriods = 2; + if( framesPerUserBuffer == paFramesPerBufferUnspecified ) + { + snd_pcm_uframes_t desiredLatency, e, minPeriodSize, maxPeriodSize, optimalPeriodSize, periodSize, + minCapture, minPlayback, maxCapture, maxPlayback; + + /* Come up with a common desired latency */ + + 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 ); + + desiredLatency = (snd_pcm_uframes_t)(PA_MIN( outputParameters->suggestedLatency, inputParameters->suggestedLatency ) + * sampleRate); + /* Clamp desiredLatency */ + { + 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 ); - snd_pcm_t *pcm; - snd_pcm_hw_params_t *hwParamsPlayback, *hwParamsCapture; + desiredLatency = PA_MIN( desiredLatency, maxBufferSize ); + } - snd_pcm_hw_params_alloca( &hwParamsPlayback ); - snd_pcm_hw_params_alloca( &hwParamsCapture ); + /* Find the closest power of 2 */ + e = ilogb( minPeriodSize ); + if( minPeriodSize & (minPeriodSize - 1) ) + e += 1; + periodSize = (snd_pcm_uframes_t)pow( 2, e ); - /* Come up with a common desired latency */ - pcm = stream->playback.pcm; - snd_pcm_hw_params_any( pcm, hwParamsPlayback ); - ENSURE_( SetApproximateSampleRate( pcm, hwParamsPlayback, sampleRate ), paInvalidSampleRate ); - ENSURE_( snd_pcm_hw_params_set_channels( pcm, hwParamsPlayback, numHostOutputChannels ), - paBadIODeviceCombination ); + 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 ) + break; /* Ok! */ - ENSURE_( snd_pcm_hw_params_set_period_size_integer( pcm, hwParamsPlayback ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_hw_params_set_periods_integer( pcm, hwParamsPlayback ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_hw_params_set_periods_min( pcm, hwParamsPlayback, &minPeriods, &dir ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParamsPlayback, &minPlayback, &dir ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParamsPlayback, &maxPlayback, &dir ), paUnanticipatedHostError ); + periodSize *= 2; + } - pcm = stream->capture.pcm; - ENSURE_( snd_pcm_hw_params_any( pcm, hwParamsCapture ), paUnanticipatedHostError ); - ENSURE_( SetApproximateSampleRate( pcm, hwParamsCapture, sampleRate ), paBadIODeviceCombination ); - ENSURE_( snd_pcm_hw_params_set_channels( pcm, hwParamsCapture, numHostInputChannels ), - paBadIODeviceCombination ); + /* 4 periods considered optimal */ + optimalPeriodSize = PA_MAX( desiredLatency / 4, minPeriodSize ); + optimalPeriodSize = PA_MIN( optimalPeriodSize, maxPeriodSize ); - ENSURE_( snd_pcm_hw_params_set_period_size_integer( pcm, hwParamsCapture ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_hw_params_set_periods_integer( pcm, hwParamsCapture ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_hw_params_set_periods_min( pcm, hwParamsCapture, &minPeriods, &dir ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_hw_params_get_period_size_min( hwParamsCapture, &minCapture, &dir ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_hw_params_get_period_size_max( hwParamsCapture, &maxCapture, &dir ), paUnanticipatedHostError ); + /* Find the closest power of 2 */ + e = ilogb( optimalPeriodSize ); + if( optimalPeriodSize & (optimalPeriodSize - 1) ) + e += 1; + optimalPeriodSize = (snd_pcm_uframes_t)pow( 2, e ); - minPeriodSize = PA_MAX( minPlayback, minCapture ); - maxPeriodSize = PA_MIN( maxPlayback, maxCapture ); + 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; - desiredLatency = (snd_pcm_uframes_t) (PA_MIN( outputParameters->suggestedLatency, inputParameters->suggestedLatency ) - * sampleRate); - /* Clamp desiredLatency */ + 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( desiredLatency / 4, 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 { - snd_pcm_uframes_t tmp, maxBufferSize = ULONG_MAX; - ENSURE_( snd_pcm_hw_params_get_buffer_size_max( hwParamsPlayback, &maxBufferSize ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_hw_params_get_buffer_size_max( hwParamsCapture, &tmp ), paUnanticipatedHostError ); - maxBufferSize = PA_MIN( maxBufferSize, tmp ); + /* 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!). + */ - desiredLatency = PA_MIN( desiredLatency, maxBufferSize ); - } + unsigned maxPeriods = 0; + PaAlsaStreamComponent* first = &self->capture, * second = &self->playback; + const PaStreamParameters* firstStreamParams = inputParameters; + snd_pcm_hw_params_t* firstHwParams = hwParamsCapture, * secondHwParams = hwParamsPlayback; - /* Find the closest power of 2 */ - e = ilogb( minPeriodSize ); - if( minPeriodSize & (minPeriodSize - 1) ) - e += 1; - periodSize = (snd_pcm_uframes_t) pow( 2, e ); + dir = 0; + ENSURE_( snd_pcm_hw_params_get_periods_max( hwParamsPlayback, &maxPeriods, &dir ), paUnanticipatedHostError ); + if( maxPeriods < 4 ) + { + /* The playback component is trickier to get right, try that first */ + first = &self->playback; + second = &self->capture; + firstStreamParams = outputParameters; + firstHwParams = hwParamsPlayback; + secondHwParams = hwParamsCapture; + } - while( periodSize <= maxPeriodSize ) - { - if( snd_pcm_hw_params_test_period_size( stream->playback.pcm, hwParamsPlayback, periodSize, 0 ) >= 0 && - snd_pcm_hw_params_test_period_size( stream->capture.pcm, hwParamsCapture, periodSize, 0 ) >= 0 ) - break; /* Ok! */ + PA_ENSURE( PaAlsaStreamComponent_DetermineFramesPerBuffer( first, firstStreamParams, framesPerUserBuffer, + sampleRate, firstHwParams, &accurate ) ); - periodSize *= 2; + 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; } + } - /* 4 periods considered optimal */ - optimalPeriodSize = PA_MAX( desiredLatency / 4, minPeriodSize ); - optimalPeriodSize = PA_MIN( optimalPeriodSize, maxPeriodSize ); + PA_UNLESS( framesPerHostBuffer != 0, paInternalError ); + self->maxFramesPerHostBuffer = framesPerHostBuffer; - /* Find the closest power of 2 */ - e = ilogb( optimalPeriodSize ); - if( optimalPeriodSize & (optimalPeriodSize - 1) ) - e += 1; - optimalPeriodSize = (snd_pcm_uframes_t) pow( 2, e ); + if( !accurate ) + { + /* Don't know the exact size per host buffer */ + *hostBufferSizeMode = paUtilBoundedHostBufferSize; + /* Raise upper bound */ + ++self->maxFramesPerHostBuffer; + } - while( optimalPeriodSize >= periodSize ) - { - pcm = stream->playback.pcm; - if( snd_pcm_hw_params_test_period_size( pcm, hwParamsPlayback, optimalPeriodSize, 0 ) < 0 ) - continue; +error: + return result; +} - pcm = stream->capture.pcm; - if( snd_pcm_hw_params_test_period_size( pcm, hwParamsCapture, optimalPeriodSize, 0 ) >= 0 ) - break; +/** 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; - optimalPeriodSize /= 2; - } + snd_pcm_hw_params_alloca( &hwParamsCapture ); + snd_pcm_hw_params_alloca( &hwParamsPlayback ); - if( optimalPeriodSize > periodSize ) - periodSize = optimalPeriodSize; + 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 ) ); - if( periodSize <= maxPeriodSize ) - { - /* Looks good */ - framesPerBuffer = periodSize; - } - else - { - /* Unable to find a common period size, oh well */ - optimalPeriodSize = PA_MAX( desiredLatency / 4, minPeriodSize ); - optimalPeriodSize = PA_MIN( optimalPeriodSize, maxPeriodSize ); + PA_ENSURE( PaAlsaStream_DetermineFramesPerBuffer( self, realSr, inParams, outParams, framesPerUserBuffer, + hwParamsCapture, hwParamsPlayback, hostBufferSizeMode ) ); - /* ConfigureStream should find individual period sizes acceptable for each device */ - framesPerBuffer = optimalPeriodSize; - /* PA_ENSURE( paBadIODeviceCombination ); */ - } + 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 )); } - else /* half-duplex is a slightly simpler case */ + if( self->playback.pcm ) { - unsigned long bufferSize, channels; - snd_pcm_t *pcm; - snd_pcm_hw_params_t *hwParams; + 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 )); + } - snd_pcm_hw_params_alloca( &hwParams ); + /* Should be exact now */ + self->streamRepresentation.streamInfo.sampleRate = realSr; - if( stream->capture.pcm ) - { - pcm = stream->capture.pcm; - bufferSize = inputParameters->suggestedLatency * sampleRate; - channels = numHostInputChannels; - } + /* 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 - { - pcm = stream->playback.pcm; - bufferSize = outputParameters->suggestedLatency * sampleRate; - channels = numHostOutputChannels; - } - - ENSURE_( snd_pcm_hw_params_any( pcm, hwParams ), paUnanticipatedHostError ); - ENSURE_( SetApproximateSampleRate( pcm, hwParams, sampleRate ), paInvalidSampleRate ); - ENSURE_( snd_pcm_hw_params_set_channels( pcm, hwParams, channels ), paBadIODeviceCombination ); + PA_DEBUG(( "%s: Unable to sync pcms: %s\n", __FUNCTION__, snd_strerror( err ) )); + } - ENSURE_( snd_pcm_hw_params_set_period_size_integer( pcm, hwParams ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_hw_params_set_periods_integer( pcm, hwParams ), paUnanticipatedHostError ); + { + 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 */ - /* Using 5 as a 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 */ - framesPerBuffer = bufferSize / 4; - bufferSize += framesPerBuffer; /* One period doesn't count as latency */ - ENSURE_( snd_pcm_hw_params_set_buffer_size_near( pcm, hwParams, &bufferSize ), paUnanticipatedHostError ); - ENSURE_( snd_pcm_hw_params_set_period_size_near( pcm, hwParams, &framesPerBuffer, NULL ), paUnanticipatedHostError ); + /* Time before watchdog unthrottles realtime thread == 1/4 of period time in msecs */ + self->threading.throttledSleepTime = (unsigned long) (minFramesPerHostBuffer / sampleRate / 4 * 1000); } - PA_UNLESS( framesPerBuffer != 0, paInternalError ); - *determinedFrames = framesPerBuffer; + 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; @@ -1744,7 +2089,7 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, double sampleRate, unsigned long framesPerBuffer, PaStreamFlags streamFlags, - PaStreamCallback *callback, + PaStreamCallback* callback, void *userData ) { PaError result = paNoError; @@ -1754,9 +2099,9 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, PaSampleFormat inputSampleFormat = 0, outputSampleFormat = 0; int numInputChannels = 0, numOutputChannels = 0; PaTime inputLatency, outputLatency; - unsigned long framesPerHostBuffer; - PaUtilHostBufferSizeMode hostBufferSizeMode = paUtilBoundedHostBufferSize; - unsigned long maxHostBufferSize; /* Upper bound of host buffer size */ + /* 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; @@ -1782,37 +2127,20 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, PA_DEBUG(( "%s: Getting framesPerBuffer from environment\n", __FUNCTION__ )); framesPerBuffer = atoi( getenv("PA_ALSA_PERIODSIZE") ); } - framesPerHostBuffer = framesPerBuffer; PA_UNLESS( stream = (PaAlsaStream*)PaUtil_AllocateMemory( sizeof(PaAlsaStream) ), paInsufficientMemory ); PA_ENSURE( PaAlsaStream_Initialize( stream, alsaHostApi, inputParameters, outputParameters, sampleRate, framesPerBuffer, callback, streamFlags, userData ) ); - /* If the number of frames per buffer is unspecified, we have to come up with - * one. This is both a blessing and a curse: a blessing because we can optimize - * the number to best meet the requirements, but a curse because that's really - * hard to do well. For this reason we also support an interface where the user - * specifies these by setting environment variables. */ - if( framesPerBuffer == paFramesPerBufferUnspecified ) - { - PA_ENSURE( DetermineFramesPerBuffer( stream, sampleRate, inputParameters, outputParameters, &framesPerHostBuffer, - hostApi ) ); - } - - PA_ENSURE( PaAlsaStream_Configure( stream, inputParameters, outputParameters, sampleRate, framesPerHostBuffer, - &inputLatency, &outputLatency, &maxHostBufferSize ) ); + PA_ENSURE( PaAlsaStream_Configure( stream, inputParameters, outputParameters, sampleRate, framesPerBuffer, + &inputLatency, &outputLatency, &hostBufferSizeMode ) ); hostInputSampleFormat = stream->capture.hostSampleFormat; hostOutputSampleFormat = stream->playback.hostSampleFormat; - if( framesPerHostBuffer != framesPerBuffer ) - { - PA_DEBUG(( "%s: Number of frames per user and host buffer differs\n", __FUNCTION__ )); - } - PA_ENSURE( PaUtil_InitializeBufferProcessor( &stream->bufferProcessor, numInputChannels, inputSampleFormat, hostInputSampleFormat, numOutputChannels, outputSampleFormat, hostOutputSampleFormat, - sampleRate, streamFlags, framesPerBuffer, maxHostBufferSize, + sampleRate, streamFlags, framesPerBuffer, stream->maxFramesPerHostBuffer, hostBufferSizeMode, callback, userData ) ); /* Ok, buffer processor is initialized, now we can deduce it's latency */ @@ -1829,7 +2157,10 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, error: if( stream ) + { + PA_DEBUG(( "%s: Stream in error, terminating\n", __FUNCTION__ )); PaAlsaStream_Terminate( stream ); + } return result; } @@ -1907,7 +2238,7 @@ static int IsRunning( PaAlsaStream *stream ) { int result = 0; - ASSERT_CALL_( pthread_mutex_lock( &stream->stateMtx ), 0 ); /* Synchronize access to pcm state */ + LockMutex( &stream->stateMtx ); if( stream->capture.pcm ) { snd_pcm_state_t capture_state = snd_pcm_state( stream->capture.pcm ); @@ -1933,7 +2264,7 @@ static int IsRunning( PaAlsaStream *stream ) } end: - ASSERT_CALL_( pthread_mutex_unlock( &stream->stateMtx ), 0 ); + ASSERT_CALL_( UnlockMutex( &stream->stateMtx ), paNoError ); return result; } @@ -1966,14 +2297,14 @@ static PaError StartStream( PaStream *s ) /* Since we'll be holding a lock on the startMtx (when not waiting on the condition), IsRunning won't be checking * stream state at the same time as the callback thread affects it. We also check IsStreamActive, in the unlikely * case the callback thread exits in the meantime (the stream will be considered inactive after the thread exits) */ - ASSERT_CALL_( pthread_mutex_lock( &stream->startMtx ), 0 ); + PA_ENSURE( LockMutex( &stream->startMtx ) ); /* Due to possible spurious wakeups, we enclose in a loop */ while( !IsRunning( stream ) && IsStreamActive( s ) && !res ) { res = pthread_cond_timedwait( &stream->startCond, &stream->startMtx, &ts ); } - ASSERT_CALL_( pthread_mutex_unlock( &stream->startMtx ), 0 ); + PA_ENSURE( UnlockMutex( &stream->startMtx ) ); PA_UNLESS( !res || res == ETIMEDOUT, paInternalError ); PA_DEBUG(( "%s: Waited for %g seconds for stream to start\n", __FUNCTION__, PaUtil_GetTime() - pt )); @@ -2006,18 +2337,34 @@ static PaError AlsaStop( PaAlsaStream *stream, int abort ) 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(( "Dropped frames\n" )); + PA_DEBUG(( "%s: Dropped frames\n", __FUNCTION__ )); } else { if( stream->playback.pcm ) - ENSURE_( snd_pcm_drain( stream->playback.pcm ), paUnanticipatedHostError ); + { + 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 ) - ENSURE_( snd_pcm_drain( stream->capture.pcm ), paUnanticipatedHostError ); + { + /* We don't need to retrieve any remaining frames */ + if( snd_pcm_drop( stream->capture.pcm ) < 0 ) + { + PA_DEBUG(( "%s: Draining capture handle failed!\n", __FUNCTION__ )); + } + } } end: @@ -2108,7 +2455,7 @@ static PaTime GetStreamTime( PaStream *s ) PaAlsaStream *stream = (PaAlsaStream*)s; snd_timestamp_t timestamp; - snd_pcm_status_t *status; + snd_pcm_status_t* status; snd_pcm_status_alloca( &status ); /* TODO: what if we have both? does it really matter? */ @@ -2127,7 +2474,7 @@ static PaTime GetStreamTime( PaStream *s ) } snd_pcm_status_get_tstamp( status, ×tamp ); - return timestamp.tv_sec + (PaTime)timestamp.tv_usec / 1000000.0; + return timestamp.tv_sec + (PaTime)timestamp.tv_usec / 1e6; } static double GetStreamCpuLoad( PaStream* s ) @@ -2180,14 +2527,15 @@ static PaError AlsaRestart( PaAlsaStream *stream ) { PaError result = paNoError; - ASSERT_CALL_( pthread_mutex_lock( &stream->stateMtx ), 0 ); + PA_ENSURE( LockMutex( &stream->stateMtx ) ); PA_ENSURE( AlsaStop( stream, 0 ) ); PA_ENSURE( AlsaStart( stream, 0 ) ); PA_DEBUG(( "%s: Restarted audio\n", __FUNCTION__ )); error: - ASSERT_CALL_( pthread_mutex_unlock( &stream->stateMtx ), 0 ); + PA_ENSURE( UnlockMutex( &stream->stateMtx ) ); + return result; } @@ -2300,10 +2648,11 @@ static void OnExit( void *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 ); stream->callbackAbort = 0; /* Clear state */ - PA_DEBUG(( "OnExit: Stoppage\n" )); + PA_DEBUG(( "%s: Stoppage\n", __FUNCTION__ )); /* Eventually notify user all buffers have played */ if( stream->streamRepresentation.streamFinishedCallback ) @@ -2516,10 +2865,11 @@ error: /** Fill in pollfd objects. */ -static PaError PaAlsaStreamComponent_BeginPolling( PaAlsaStreamComponent *self, struct pollfd *pfds ) +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; @@ -2533,7 +2883,7 @@ static PaError PaAlsaStreamComponent_BeginPolling( PaAlsaStreamComponent *self, * @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 ) +static PaError PaAlsaStreamComponent_EndPolling( PaAlsaStreamComponent* self, struct pollfd* pfds, int* shouldPoll, int* xrun ) { PaError result = paNoError; unsigned short revents; @@ -2592,6 +2942,7 @@ static PaError PaAlsaStream_GetAvailableFrames( PaAlsaStream *self, int queryCap if( queryCapture && queryPlayback ) { *available = PA_MIN( captureFrames, playbackFrames ); + /*PA_DEBUG(("capture: %lu, playback: %lu, combined: %lu\n", captureFrames, playbackFrames, *available));*/ } else if( queryCapture ) { @@ -2668,11 +3019,13 @@ static PaError PaAlsaStream_WaitForFrames( PaAlsaStream *self, unsigned long *fr 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 */ + if( errno == EINTR ) + { + /* gdb */ continue; } @@ -2715,8 +3068,8 @@ static PaError PaAlsaStream_WaitForFrames( PaAlsaStream *self, unsigned long *fr { /* 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. This under the assumption that input is dropped earlier if paNeverDropInput - * is not specified. + * 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; @@ -2726,9 +3079,18 @@ static PaError PaAlsaStream_WaitForFrames( PaAlsaStream *self, unsigned long *fr { if( !self->playback.ready && !self->neverDropInput ) { - /* TODO: Drop input */ + /* 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: @@ -2739,6 +3101,14 @@ error: 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; @@ -2751,8 +3121,8 @@ error: * * @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 ) +static PaError PaAlsaStreamComponent_RegisterChannels( PaAlsaStreamComponent* self, PaUtilBufferProcessor* bp, + unsigned long* numFrames, int* xrun ) { PaError result = paNoError; const snd_pcm_channel_area_t *areas, *area; @@ -2812,12 +3182,20 @@ error: * @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 ) +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. */ @@ -2841,7 +3219,24 @@ static PaError PaAlsaStream_SetUpBuffers( PaAlsaStream *self, unsigned long *num } commonFrames = PA_MIN( captureFrames, playbackFrames ); - assert( commonFrames <= *numFrames ); + /* 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 @@ -2869,7 +3264,9 @@ static PaError PaAlsaStream_SetUpBuffers( PaAlsaStream *self, unsigned long *num else { /* We have output underflow, but keeping input data (paNeverDropInput) */ - /* assert( self->neverDropInput ); */ + assert( self->neverDropInput ); + assert( self->capture.pcm != NULL ); + PA_DEBUG(( "%s: Setting output buffers to NULL\n", __FUNCTION__ )); PaUtil_SetNoOutput( &self->bufferProcessor ); } } @@ -2934,10 +3331,11 @@ static void *CallbackThreadFunc( void *userData ) } else { - ASSERT_CALL_( pthread_mutex_lock( &stream->startMtx ), 0 ); - PA_ENSURE( AlsaStart( stream, 0 ) ); /* Buffer will be zeroed */ - ASSERT_CALL_( pthread_cond_signal( &stream->startCond ), 0 ); - ASSERT_CALL_( pthread_mutex_unlock( &stream->startMtx ), 0 ); + PA_ENSURE( LockMutex( &stream->startMtx ) ); + /* Buffer will be zeroed */ + PA_ENSURE( AlsaStart( stream, 0 ) ); + ENSURE_SYSTEM_( pthread_cond_signal( &stream->startCond ), 0 ); + PA_ENSURE( UnlockMutex( &stream->startMtx ) ); streamStarted = 1; } @@ -2962,7 +3360,7 @@ static void *CallbackThreadFunc( void *userData ) { stream->callbackAbort = (paAbort == callbackResult); if( stream->callbackAbort || - /** @concern BlockAdaption Go on if adaption buffers are empty */ + /** @concern BlockAdaption: Go on if adaption buffers are empty */ PaUtil_IsBufferProcessorOutputEmpty( &stream->bufferProcessor ) ) goto end; @@ -3031,23 +3429,31 @@ static void *CallbackThreadFunc( void *userData ) 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( framesGot == 0 ) + if( 0 == framesGot ) { - if( !xrun ) - PA_DEBUG(( "%s: Received less frames than reported from ALSA!\n", __FUNCTION__ )); - /* Go back to polling for more frames */ break; @@ -3062,6 +3468,7 @@ static void *CallbackThreadFunc( void *userData ) pthread_cleanup_pop( 1 ); end: + PA_DEBUG(( "%s: Thread %d exiting\n ", __FUNCTION__, pthread_self() )); pthread_exit( pres ); error: @@ -3096,7 +3503,9 @@ static PaError ReadStream( PaStream* s, void *buffer, unsigned long frames ) } if( stream->capture.userInterleaved ) + { userBuffer = buffer; + } else { /* Copy channels into local array */ @@ -3178,12 +3587,13 @@ static PaError WriteStream( PaStream* s, const void *buffer, unsigned long frame 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; - /* Start stream after one period of samples worth */ if( snd_pcm_state( stream->playback.pcm ) == SND_PCM_STATE_PREPARED && hwAvail >= stream->playback.framesPerBuffer ) { -- cgit v1.2.1