From 79932a5919177172d10ca673542f04f3148a9153 Mon Sep 17 00:00:00 2001 From: Ross Bencina Date: Thu, 18 Feb 2021 12:11:14 +1100 Subject: [PATCH] Clean up whitespace in src/hostapi/coreaudio in preparation for .editorconfig. (#502) * Clean up whitespace in src/hostapi/coreaudio in preparation for .editorconfig. Convert tabs to 4 spaces. Indent by 4 spaces. Strip trailing whitespace. Ensure only one EOL at EOF. --- src/hostapi/coreaudio/pa_mac_core.c | 2805 ++++++++--------- src/hostapi/coreaudio/pa_mac_core_blocking.c | 729 ++--- src/hostapi/coreaudio/pa_mac_core_blocking.h | 22 +- src/hostapi/coreaudio/pa_mac_core_internal.h | 37 +- src/hostapi/coreaudio/pa_mac_core_utilities.c | 837 ++--- src/hostapi/coreaudio/pa_mac_core_utilities.h | 68 +- 6 files changed, 2259 insertions(+), 2239 deletions(-) diff --git a/src/hostapi/coreaudio/pa_mac_core.c b/src/hostapi/coreaudio/pa_mac_core.c index 2d98a3b..26b814c 100644 --- a/src/hostapi/coreaudio/pa_mac_core.c +++ b/src/hostapi/coreaudio/pa_mac_core.c @@ -15,7 +15,7 @@ * 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 @@ -41,13 +41,13 @@ */ /* - * The text above constitutes the entire PortAudio license; however, + * 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 + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the * license above. */ @@ -80,10 +80,10 @@ extern "C" { #endif /* __cplusplus */ - + /* This is a reasonable size for a small buffer based on experience. */ #define PA_MAC_SMALL_BUFFER_SIZE (64) - + /* prototypes for functions declared in this file */ PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); @@ -93,13 +93,13 @@ PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIn */ 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; + bzero( data, sizeof( PaMacCoreStreamInfo ) ); + data->size = sizeof( PaMacCoreStreamInfo ); + data->hostApiType = paCoreAudio; + data->version = 0x01; + data->flags = flags; + data->channelMap = NULL; + data->channelMapSize = 0; } /* @@ -107,110 +107,110 @@ void PaMacCore_SetupStreamInfo( PaMacCoreStreamInfo *data, const unsigned long */ void PaMacCore_SetupChannelMap( PaMacCoreStreamInfo *data, const SInt32 * const channelMap, const unsigned long channelMapSize ) { - data->channelMap = channelMap; - data->channelMapSize = 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; + 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. retrieves 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); - if( err != paNoError ) - return NULL; - PaMacAUHAL *macCoreHostApi = (PaMacAUHAL*)hostApi; - AudioDeviceID hostApiDevice = macCoreHostApi->devIds[device]; - CFStringRef nameRef; - - /* First try with CFString */ - UInt32 size = sizeof(nameRef); - error = PaMacCore_AudioDeviceGetProperty( hostApiDevice, - channelIndex + 1, - input, - kAudioDevicePropertyChannelNameCFString, - &size, - &nameRef ); - if( error ) - { - /* try the C String */ - size = 0; - error = PaMacCore_AudioDeviceGetPropertySize( hostApiDevice, - channelIndex + 1, - input, - kAudioDevicePropertyChannelName, - &size); - if( !error ) - { - if( !ensureChannelNameSize( size ) ) - return NULL; - - error = PaMacCore_AudioDeviceGetProperty( hostApiDevice, - channelIndex + 1, - input, - kAudioDevicePropertyChannelName, - &size, - channelName ); - - - if( !error ) - return channelName; - } - - /* as a last-ditch effort, we use the device name and append the channel number. */ - nameRef = CFStringCreateWithFormat( NULL, NULL, CFSTR( "%s: %d"), hostApi->deviceInfos[device]->name, channelIndex + 1 ); - - - size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef), kCFStringEncodingUTF8);; - if( !ensureChannelNameSize( size ) ) - { - CFRelease( nameRef ); - return NULL; - } - CFStringGetCString( nameRef, channelName, size+1, kCFStringEncodingUTF8 ); - CFRelease( nameRef ); - } - else - { - size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef), kCFStringEncodingUTF8);; - if( !ensureChannelNameSize( size ) ) - { - CFRelease( nameRef ); - return NULL; - } - CFStringGetCString( nameRef, channelName, size+1, kCFStringEncodingUTF8 ); - CFRelease( nameRef ); - } - - return channelName; + struct PaUtilHostApiRepresentation *hostApi; + PaError err; + OSStatus error; + err = PaUtil_GetHostApiRepresentation( &hostApi, paCoreAudio ); + assert(err == paNoError); + if( err != paNoError ) + return NULL; + PaMacAUHAL *macCoreHostApi = (PaMacAUHAL*)hostApi; + AudioDeviceID hostApiDevice = macCoreHostApi->devIds[device]; + CFStringRef nameRef; + + /* First try with CFString */ + UInt32 size = sizeof(nameRef); + error = PaMacCore_AudioDeviceGetProperty( hostApiDevice, + channelIndex + 1, + input, + kAudioDevicePropertyChannelNameCFString, + &size, + &nameRef ); + if( error ) + { + /* try the C String */ + size = 0; + error = PaMacCore_AudioDeviceGetPropertySize( hostApiDevice, + channelIndex + 1, + input, + kAudioDevicePropertyChannelName, + &size ); + if( !error ) + { + if( !ensureChannelNameSize( size ) ) + return NULL; + + error = PaMacCore_AudioDeviceGetProperty( hostApiDevice, + channelIndex + 1, + input, + kAudioDevicePropertyChannelName, + &size, + channelName ); + + + if( !error ) + return channelName; + } + + /* as a last-ditch effort, we use the device name and append the channel number. */ + nameRef = CFStringCreateWithFormat( NULL, NULL, CFSTR( "%s: %d"), hostApi->deviceInfos[device]->name, channelIndex + 1 ); + + + size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef), kCFStringEncodingUTF8);; + if( !ensureChannelNameSize( size ) ) + { + CFRelease( nameRef ); + return NULL; + } + CFStringGetCString( nameRef, channelName, size+1, kCFStringEncodingUTF8 ); + CFRelease( nameRef ); + } + else + { + size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef), kCFStringEncodingUTF8);; + if( !ensureChannelNameSize( size ) ) + { + CFRelease( nameRef ); + return NULL; + } + CFStringGetCString( nameRef, channelName, size+1, kCFStringEncodingUTF8 ); + CFRelease( nameRef ); + } + + return channelName; } - + PaError PaMacCore_GetBufferSizeRange( PaDeviceIndex device, long *minBufferSizeFrames, long *maxBufferSizeFrames ) { PaError result; PaUtilHostApiRepresentation *hostApi; - + result = PaUtil_GetHostApiRepresentation( &hostApi, paCoreAudio ); - + if( result == paNoError ) { PaDeviceIndex hostApiDeviceIndex; @@ -221,7 +221,7 @@ PaError PaMacCore_GetBufferSizeRange( PaDeviceIndex device, AudioDeviceID macCoreDeviceId = macCoreHostApi->devIds[hostApiDeviceIndex]; AudioValueRange audioRange; UInt32 propSize = sizeof( audioRange ); - + // return the size range for the output scope unless we only have inputs Boolean isInput = 0; if( macCoreHostApi->inheritedHostApiRep.deviceInfos[hostApiDeviceIndex]->maxOutputChannels == 0 ) @@ -233,7 +233,7 @@ PaError PaMacCore_GetBufferSizeRange( PaDeviceIndex device, *maxBufferSizeFrames = audioRange.mMaximum; } } - + return result; } @@ -282,11 +282,11 @@ static PaError IsStreamStopped( PaStream *s ); static PaError IsStreamActive( PaStream *stream ); static PaTime GetStreamTime( PaStream *stream ); static OSStatus AudioIOProc( void *inRefCon, - AudioUnitRenderActionFlags *ioActionFlags, - const AudioTimeStamp *inTimeStamp, - UInt32 inBusNumber, - UInt32 inNumberFrames, - AudioBufferList *ioData ); + AudioUnitRenderActionFlags *ioActionFlags, + const AudioTimeStamp *inTimeStamp, + UInt32 inBusNumber, + UInt32 inNumberFrames, + AudioBufferList *ioData ); static double GetStreamCpuLoad( PaStream* stream ); static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi, @@ -294,19 +294,18 @@ static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi, AudioDeviceID macCoreDeviceId, int isInput); -static PaError OpenAndSetupOneAudioUnit( - const PaMacCoreStream *stream, - const PaStreamParameters *inStreamParams, - const PaStreamParameters *outStreamParams, - const UInt32 requestedFramesPerBuffer, - UInt32 *actualInputFramesPerBuffer, - UInt32 *actualOutputFramesPerBuffer, - const PaMacAUHAL *auhalHostApi, - AudioUnit *audioUnit, - AudioConverterRef *srConverter, - AudioDeviceID *audioDevice, - const double sampleRate, - void *refCon ); +static PaError OpenAndSetupOneAudioUnit( const PaMacCoreStream *stream, + const PaStreamParameters *inStreamParams, + const PaStreamParameters *outStreamParams, + const UInt32 requestedFramesPerBuffer, + UInt32 *actualInputFramesPerBuffer, + UInt32 *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 ) \ @@ -316,30 +315,30 @@ static PaError OpenAndSetupOneAudioUnit( * Callback called when starting or stopping a stream. */ static void startStopCallback( - void * inRefCon, - AudioUnit ci, - AudioUnitPropertyID inID, - AudioUnitScope inScope, - AudioUnitElement inElement ) + void * inRefCon, + AudioUnit ci, + AudioUnitPropertyID inID, + AudioUnitScope inScope, + AudioUnitElement inElement ) { - PaMacCoreStream *stream = (PaMacCoreStream *) inRefCon; - UInt32 isRunning; - UInt32 size = sizeof( isRunning ); - OSStatus err; - err = AudioUnitGetProperty( ci, kAudioOutputUnitProperty_IsRunning, inScope, inElement, &isRunning, &size ); - assert( !err ); - if( err ) - isRunning = false; //it's very unclear what to do in case of error here. There's no real way to notify the user, and crashing seems unreasonable. - if( isRunning ) - return; //We are only interested in when we are stopping - // -- if we are using 2 I/O units, we only need one notification! - if( stream->inputUnit && stream->outputUnit && stream->inputUnit != stream->outputUnit && ci == stream->inputUnit ) - return; - PaStreamFinishedCallback *sfc = stream->streamRepresentation.streamFinishedCallback; - if( stream->state == STOPPING ) - stream->state = STOPPED ; - if( sfc ) - sfc( stream->streamRepresentation.userData ); + PaMacCoreStream *stream = (PaMacCoreStream *) inRefCon; + UInt32 isRunning; + UInt32 size = sizeof( isRunning ); + OSStatus err; + err = AudioUnitGetProperty( ci, kAudioOutputUnitProperty_IsRunning, inScope, inElement, &isRunning, &size ); + assert( !err ); + if( err ) + isRunning = false; //it's very unclear what to do in case of error here. There's no real way to notify the user, and crashing seems unreasonable. + if( isRunning ) + return; //We are only interested in when we are stopping + // -- if we are using 2 I/O units, we only need one notification! + if( stream->inputUnit && stream->outputUnit && stream->inputUnit != stream->outputUnit && ci == stream->inputUnit ) + return; + PaStreamFinishedCallback *sfc = stream->streamRepresentation.streamFinishedCallback; + if( stream->state == STOPPING ) + stream->state = STOPPED ; + if( sfc ) + sfc( stream->streamRepresentation.userData ); } @@ -357,25 +356,25 @@ static PaError gatherDeviceInfo(PaMacAUHAL *auhalHostApi) /* -- figure out how many devices there are -- */ PaMacCore_AudioHardwareGetPropertySize( kAudioHardwarePropertyDevices, - &propsize); + &propsize); 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 ); + auhalHostApi->allocations, + propsize ); if( !auhalHostApi->devIds ) return paInsufficientMemory; PaMacCore_AudioHardwareGetProperty( kAudioHardwarePropertyDevices, - &propsize, - auhalHostApi->devIds ); + &propsize, + auhalHostApi->devIds ); #ifdef MAC_CORE_VERBOSE_DEBUG { - int i; - for( i=0; idevCount; ++i ) - printf( "Device %d\t: %ld\n", i, (long)auhalHostApi->devIds[i] ); + int i; + for( i=0; idevCount; ++i ) + printf( "Device %d\t: %ld\n", i, (long)auhalHostApi->devIds[i] ); } #endif @@ -388,39 +387,39 @@ static PaError gatherDeviceInfo(PaMacAUHAL *auhalHostApi) could fail, but in case they do, we use the first available device as the default. */ if( 0 != PaMacCore_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; idevCount; ++i ) { - PaDeviceInfo devInfo; - if( 0 != GetChannelInfo( auhalHostApi, &devInfo, - auhalHostApi->devIds[i], TRUE ) ) - if( devInfo.maxInputChannels ) { - auhalHostApi->defaultIn = auhalHostApi->devIds[i]; - break; - } - } + &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; idevCount; ++i ) { + PaDeviceInfo devInfo; + if( 0 != GetChannelInfo( auhalHostApi, &devInfo, + auhalHostApi->devIds[i], TRUE ) ) + if( devInfo.maxInputChannels ) { + auhalHostApi->defaultIn = auhalHostApi->devIds[i]; + break; + } + } } if( 0 != PaMacCore_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; idevCount; ++i ) { - PaDeviceInfo devInfo; - if( 0 != GetChannelInfo( auhalHostApi, &devInfo, - auhalHostApi->devIds[i], FALSE ) ) - if( devInfo.maxOutputChannels ) { - auhalHostApi->defaultOut = auhalHostApi->devIds[i]; - break; - } - } - } + &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; idevCount; ++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", (long)auhalHostApi->defaultIn ) ); VDBUG( ( "Default out: %ld\n", (long)auhalHostApi->defaultOut ) ); @@ -434,22 +433,22 @@ static PaError gatherDeviceInfo(PaMacAUHAL *auhalHostApi) * @brief Clip the desired size against the allowed IO buffer size range for the device. */ static PaError ClipToDeviceBufferSize( AudioDeviceID macCoreDeviceId, - int isInput, UInt32 desiredSize, UInt32 *allowedSize ) + int isInput, UInt32 desiredSize, UInt32 *allowedSize ) { - UInt32 resultSize = desiredSize; - AudioValueRange audioRange; - UInt32 propSize = sizeof( audioRange ); - PaError err = WARNING(PaMacCore_AudioDeviceGetProperty( macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &audioRange ) ); - resultSize = MAX( resultSize, audioRange.mMinimum ); - resultSize = MIN( resultSize, audioRange.mMaximum ); - *allowedSize = resultSize; - return err; + UInt32 resultSize = desiredSize; + AudioValueRange audioRange; + UInt32 propSize = sizeof( audioRange ); + PaError err = WARNING(PaMacCore_AudioDeviceGetProperty( macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &audioRange ) ); + resultSize = MAX( resultSize, audioRange.mMinimum ); + resultSize = MIN( resultSize, audioRange.mMaximum ); + *allowedSize = resultSize; + return err; } /* =================================================================================================== */ #if 0 static void DumpDeviceProperties( AudioDeviceID macCoreDeviceId, - int isInput ) + int isInput ) { PaError err; int i; @@ -459,27 +458,27 @@ static void DumpDeviceProperties( AudioDeviceID macCoreDeviceId, UInt32 bufferFrames; UInt32 safetyOffset; AudioStreamID streamIDs[128]; - - printf("\n======= latency query : macCoreDeviceId = %d, isInput %d =======\n", (int)macCoreDeviceId, isInput ); - + + printf("\n======= latency query : macCoreDeviceId = %d, isInput %d =======\n", (int)macCoreDeviceId, isInput ); + propSize = sizeof(UInt32); err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSize, &propSize, &bufferFrames)); printf("kAudioDevicePropertyBufferFrameSize: err = %d, propSize = %d, value = %d\n", err, propSize, bufferFrames ); - + propSize = sizeof(UInt32); err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertySafetyOffset, &propSize, &safetyOffset)); printf("kAudioDevicePropertySafetyOffset: err = %d, propSize = %d, value = %d\n", err, propSize, safetyOffset ); - + propSize = sizeof(UInt32); err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &deviceLatency)); printf("kAudioDevicePropertyLatency: err = %d, propSize = %d, value = %d\n", err, propSize, deviceLatency ); - + AudioValueRange audioRange; propSize = sizeof( audioRange ); err = WARNING(AudioDeviceGetProperty( macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &audioRange ) ); printf("kAudioDevicePropertyBufferFrameSizeRange: err = %d, propSize = %u, minimum = %g\n", err, propSize, audioRange.mMinimum); printf("kAudioDevicePropertyBufferFrameSizeRange: err = %d, propSize = %u, maximum = %g\n", err, propSize, audioRange.mMaximum ); - + /* Get the streams from the device and query their latency. */ propSize = sizeof(streamIDs); err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreams, &propSize, &streamIDs[0])); @@ -487,7 +486,7 @@ static void DumpDeviceProperties( AudioDeviceID macCoreDeviceId, for( i=0; imaxInputChannels = numChannels; else deviceInfo->maxOutputChannels = numChannels; - + if (numChannels > 0) /* do not try to retrieve the latency if there are no channels. */ { /* Get the latency. Don't fail if we can't get this. */ @@ -617,13 +616,13 @@ static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi, deviceInfo->defaultLowInputLatency = .01; deviceInfo->defaultHighInputLatency = .10; deviceInfo->defaultLowOutputLatency = .01; - deviceInfo->defaultHighOutputLatency = .10; + deviceInfo->defaultHighOutputLatency = .10; UInt32 lowLatencyFrames = 0; UInt32 highLatencyFrames = 0; err = CalculateDefaultDeviceLatencies( macCoreDeviceId, isInput, &lowLatencyFrames, &highLatencyFrames ); if( err == 0 ) { - + double lowLatencySeconds = lowLatencyFrames / deviceInfo->defaultSampleRate; double highLatencySeconds = highLatencyFrames / deviceInfo->defaultSampleRate; if (isInput) @@ -640,7 +639,7 @@ static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi, } PaUtil_FreeMemory( buflist ); return paNoError; - error: +error: PaUtil_FreeMemory( buflist ); return err; } @@ -654,7 +653,7 @@ static PaError InitializeDeviceInfo( PaMacAUHAL *auhalHostApi, Float64 sampleRate; char *name; PaError err = paNoError; - CFStringRef nameRef; + CFStringRef nameRef; UInt32 propSize; VVDBUG(("InitializeDeviceInfo(): macCoreDeviceId=%ld\n", macCoreDeviceId)); @@ -663,37 +662,37 @@ static PaError InitializeDeviceInfo( PaMacAUHAL *auhalHostApi, deviceInfo->structVersion = 2; deviceInfo->hostApi = hostApiIndex; - + /* Get the device name using CFString */ - propSize = sizeof(nameRef); + propSize = sizeof(nameRef); err = ERR(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceNameCFString, &propSize, &nameRef)); if (err) { - /* Get the device name using c string. Fail if we can't get it. */ - err = ERR(PaMacCore_AudioDeviceGetPropertySize(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize)); - if (err) - return err; - - name = PaUtil_GroupAllocateMemory(auhalHostApi->allocations,propSize+1); - if ( !name ) - return paInsufficientMemory; - err = ERR(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, name)); - if (err) - return err; - } - else - { - /* valid CFString so we just allocate a c string big enough to contain the data */ - propSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef), kCFStringEncodingUTF8); - name = PaUtil_GroupAllocateMemory(auhalHostApi->allocations, propSize+1); - if ( !name ) - { - CFRelease(nameRef); - return paInsufficientMemory; - } - CFStringGetCString(nameRef, name, propSize+1, kCFStringEncodingUTF8); - CFRelease(nameRef); - } + /* Get the device name using c string. Fail if we can't get it. */ + err = ERR(PaMacCore_AudioDeviceGetPropertySize(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize)); + if (err) + return err; + + name = PaUtil_GroupAllocateMemory(auhalHostApi->allocations,propSize+1); + if ( !name ) + return paInsufficientMemory; + err = ERR(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, name)); + if (err) + return err; + } + else + { + /* valid CFString so we just allocate a c string big enough to contain the data */ + propSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef), kCFStringEncodingUTF8); + name = PaUtil_GroupAllocateMemory(auhalHostApi->allocations, propSize+1); + if ( !name ) + { + CFRelease(nameRef); + return paInsufficientMemory; + } + CFStringGetCString(nameRef, name, propSize+1, kCFStringEncodingUTF8); + CFRelease(nameRef); + } deviceInfo->name = name; /* Try to get the default sample rate. Don't fail if we can't get this. */ @@ -726,25 +725,25 @@ PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIn int unixErr; VVDBUG(("PaMacCore_Initialize(): hostApiIndex=%d\n", hostApiIndex)); - - SInt32 major; - SInt32 minor; - Gestalt(gestaltSystemVersionMajor, &major); - Gestalt(gestaltSystemVersionMinor, &minor); - - // Starting with 10.6 systems, the HAL notification thread is created internally - if ( major > 10 || (major == 10 && minor >= 6) ) { - CFRunLoopRef theRunLoop = NULL; - AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; - OSStatus osErr = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop); - if (osErr != noErr) { - goto error; - } - } - + + SInt32 major; + SInt32 minor; + Gestalt(gestaltSystemVersionMajor, &major); + Gestalt(gestaltSystemVersionMinor, &minor); + + // Starting with 10.6 systems, the HAL notification thread is created internally + if ( major > 10 || (major == 10 && minor >= 6) ) { + CFRunLoopRef theRunLoop = NULL; + AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; + OSStatus osErr = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop); + if (osErr != noErr) { + goto error; + } + } + unixErr = initializeXRunListenerList(); if( 0 != unixErr ) { - return UNIX_ERR(unixErr); + return UNIX_ERR(unixErr); } auhalHostApi = (PaMacAUHAL*)PaUtil_AllocateMemory( sizeof(PaMacAUHAL) ); @@ -767,7 +766,7 @@ PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIn /* get the info we need about the devices */ result = gatherDeviceInfo( auhalHostApi ); if( result != paNoError ) - goto error; + goto error; *hostApi = &auhalHostApi->inheritedHostApiRep; (*hostApi)->info.structVersion = 1; @@ -777,7 +776,7 @@ PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIn (*hostApi)->info.defaultInputDevice = paNoDevice; (*hostApi)->info.defaultOutputDevice = paNoDevice; - (*hostApi)->info.deviceCount = 0; + (*hostApi)->info.deviceCount = 0; if( auhalHostApi->devCount > 0 ) { @@ -802,10 +801,10 @@ PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIn { int err; err = InitializeDeviceInfo( auhalHostApi, &deviceInfoArray[i], - auhalHostApi->devIds[i], - hostApiIndex ); + auhalHostApi->devIds[i], + hostApiIndex ); if (err == paNoError) - { /* copy some info and set the defaults */ + { /* 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; @@ -814,11 +813,11 @@ PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIn (*hostApi)->info.deviceCount++; } else - { /* there was an error. we need to shift the devices down, so we ignore this one */ + { /* there was an error. we need to shift the devices down, so we ignore this one */ int j; auhalHostApi->devCount--; for( j=i; jdevCount; ++j ) - auhalHostApi->devIds[j] = auhalHostApi->devIds[j+1]; + auhalHostApi->devIds[j] = auhalHostApi->devIds[j+1]; i--; } } @@ -856,7 +855,7 @@ error: PaUtil_FreeAllAllocations( auhalHostApi->allocations ); PaUtil_DestroyAllocationGroup( auhalHostApi->allocations ); } - + PaUtil_FreeMemory( auhalHostApi ); } return result; @@ -873,7 +872,7 @@ static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) unixErr = destroyXRunListenerList(); if( 0 != unixErr ) - UNIX_ERR(unixErr); + UNIX_ERR(unixErr); /* IMPLEMENT ME: @@ -900,12 +899,12 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, 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 )); - + 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 ) @@ -917,7 +916,7 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, 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 */ @@ -942,7 +941,7 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, 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 */ @@ -958,7 +957,7 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, { 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? */ @@ -969,21 +968,21 @@ static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, /* 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 ) ) ); - } + 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; @@ -1018,45 +1017,47 @@ static void UpdateTimeStampOffsets( PaMacCoreStream *stream ) Float64 inputHardwareLatency = 0.0; Float64 outputSoftwareLatency = 0.0; Float64 outputHardwareLatency = 0.0; - + if( stream->inputUnit != NULL ) { inputSoftwareLatency = CalculateSoftwareLatencyFromProperties( stream, &stream->inputProperties ); inputHardwareLatency = CalculateHardwareLatencyFromProperties( stream, &stream->inputProperties ); - } + } if( stream->outputUnit != NULL ) { outputSoftwareLatency = CalculateSoftwareLatencyFromProperties( stream, &stream->outputProperties ); outputHardwareLatency = CalculateHardwareLatencyFromProperties( stream, &stream->outputProperties ); - } - + } + /* We only need a mutex around setting these variables as a group. */ - pthread_mutex_lock( &stream->timingInformationMutex ); + pthread_mutex_lock( &stream->timingInformationMutex ); stream->timestampOffsetCombined = inputSoftwareLatency + outputSoftwareLatency; stream->timestampOffsetInputDevice = inputHardwareLatency; stream->timestampOffsetOutputDevice = outputHardwareLatency; - pthread_mutex_unlock( &stream->timingInformationMutex ); + pthread_mutex_unlock( &stream->timingInformationMutex ); } /* ================================================================================= */ /* can be used to update from nominal or actual sample rate */ -static OSStatus UpdateSampleRateFromDeviceProperty( PaMacCoreStream *stream, AudioDeviceID deviceID, Boolean isInput, AudioDevicePropertyID sampleRatePropertyID ) +static OSStatus UpdateSampleRateFromDeviceProperty( PaMacCoreStream *stream, AudioDeviceID deviceID, + Boolean isInput, AudioDevicePropertyID sampleRatePropertyID ) { PaMacCoreDeviceProperties * deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties; - - Float64 sampleRate = 0.0; - UInt32 propSize = sizeof(Float64); + + Float64 sampleRate = 0.0; + UInt32 propSize = sizeof(Float64); OSStatus osErr = PaMacCore_AudioDeviceGetProperty( deviceID, 0, isInput, sampleRatePropertyID, &propSize, &sampleRate); - if( (osErr == noErr) && (sampleRate > 1000.0) ) /* avoid divide by zero if there's an error */ - { + if( (osErr == noErr) && (sampleRate > 1000.0) ) /* avoid divide by zero if there's an error */ + { deviceProperties->sampleRate = sampleRate; deviceProperties->samplePeriod = 1.0 / sampleRate; } return osErr; } -static OSStatus AudioDevicePropertyActualSampleRateListenerProc(AudioObjectID inDevice, UInt32 inNumberAddresses, const AudioObjectPropertyAddress * inAddresses, void * inClientData) +static OSStatus AudioDevicePropertyActualSampleRateListenerProc( AudioObjectID inDevice, UInt32 inNumberAddresses, + const AudioObjectPropertyAddress * inAddresses, void * inClientData ) { PaMacCoreStream *stream = (PaMacCoreStream*)inClientData; bool isInput = inAddresses->mScope == kAudioDevicePropertyScopeInput; @@ -1075,17 +1076,18 @@ static OSStatus AudioDevicePropertyActualSampleRateListenerProc(AudioObjectID in /* ================================================================================= */ static OSStatus QueryUInt32DeviceProperty( AudioDeviceID deviceID, Boolean isInput, AudioDevicePropertyID propertyID, UInt32 *outValue ) { - UInt32 propertyValue = 0; - UInt32 propertySize = sizeof(UInt32); - OSStatus osErr = PaMacCore_AudioDeviceGetProperty( deviceID, 0, isInput, propertyID, &propertySize, &propertyValue); - if( osErr == noErr ) - { + UInt32 propertyValue = 0; + UInt32 propertySize = sizeof(UInt32); + OSStatus osErr = PaMacCore_AudioDeviceGetProperty( deviceID, 0, isInput, propertyID, &propertySize, &propertyValue); + if( osErr == noErr ) + { *outValue = propertyValue; - } + } return osErr; } -static OSStatus AudioDevicePropertyGenericListenerProc(AudioObjectID inDevice, UInt32 inNumberAddresses, const AudioObjectPropertyAddress * inAddresses, void * inClientData) +static OSStatus AudioDevicePropertyGenericListenerProc( AudioObjectID inDevice, UInt32 inNumberAddresses, + const AudioObjectPropertyAddress * inAddresses, void * inClientData ) { OSStatus osErr = noErr; PaMacCoreStream *stream = (PaMacCoreStream*)inClientData; @@ -1094,22 +1096,22 @@ static OSStatus AudioDevicePropertyGenericListenerProc(AudioObjectID inDevice, U // Make sure the callback is operating on a stream that is still valid! assert( stream->streamRepresentation.magic == PA_STREAM_MAGIC ); - + PaMacCoreDeviceProperties *deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties; UInt32 *valuePtr = NULL; switch( inPropertyID ) { - case kAudioDevicePropertySafetyOffset: - valuePtr = &deviceProperties->safetyOffset; - break; - - case kAudioDevicePropertyLatency: - valuePtr = &deviceProperties->deviceLatency; - break; - - case kAudioDevicePropertyBufferFrameSize: - valuePtr = &deviceProperties->bufferFrameSize; - break; + case kAudioDevicePropertySafetyOffset: + valuePtr = &deviceProperties->safetyOffset; + break; + + case kAudioDevicePropertyLatency: + valuePtr = &deviceProperties->deviceLatency; + break; + + case kAudioDevicePropertyBufferFrameSize: + valuePtr = &deviceProperties->bufferFrameSize; + break; } if( valuePtr != NULL ) { @@ -1129,23 +1131,23 @@ static OSStatus SetupDevicePropertyListeners( PaMacCoreStream *stream, AudioDevi { OSStatus osErr = noErr; PaMacCoreDeviceProperties *deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties; - + if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput, - kAudioDevicePropertyLatency, &deviceProperties->deviceLatency )) != noErr ) return osErr; + kAudioDevicePropertyLatency, &deviceProperties->deviceLatency )) != noErr ) return osErr; if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput, - kAudioDevicePropertyBufferFrameSize, &deviceProperties->bufferFrameSize )) != noErr ) return osErr; + kAudioDevicePropertyBufferFrameSize, &deviceProperties->bufferFrameSize )) != noErr ) return osErr; if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput, - kAudioDevicePropertySafetyOffset, &deviceProperties->safetyOffset )) != noErr ) return osErr; + kAudioDevicePropertySafetyOffset, &deviceProperties->safetyOffset )) != noErr ) return osErr; PaMacCore_AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertyActualSampleRate, - AudioDevicePropertyActualSampleRateListenerProc, stream ); + AudioDevicePropertyActualSampleRateListenerProc, stream ); PaMacCore_AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioStreamPropertyLatency, - AudioDevicePropertyGenericListenerProc, stream ); + AudioDevicePropertyGenericListenerProc, stream ); PaMacCore_AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertyBufferFrameSize, - AudioDevicePropertyGenericListenerProc, stream ); + AudioDevicePropertyGenericListenerProc, stream ); PaMacCore_AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertySafetyOffset, - AudioDevicePropertyGenericListenerProc, stream ); + AudioDevicePropertyGenericListenerProc, stream ); return osErr; } @@ -1153,30 +1155,30 @@ static OSStatus SetupDevicePropertyListeners( PaMacCoreStream *stream, AudioDevi static void CleanupDevicePropertyListeners( PaMacCoreStream *stream, AudioDeviceID deviceID, Boolean isInput ) { PaMacCore_AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyActualSampleRate, - AudioDevicePropertyActualSampleRateListenerProc, stream ); + AudioDevicePropertyActualSampleRateListenerProc, stream ); PaMacCore_AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyLatency, - AudioDevicePropertyGenericListenerProc, stream ); + AudioDevicePropertyGenericListenerProc, stream ); PaMacCore_AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyBufferFrameSize, - AudioDevicePropertyGenericListenerProc, stream ); + AudioDevicePropertyGenericListenerProc, stream ); PaMacCore_AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertySafetyOffset, - AudioDevicePropertyGenericListenerProc, stream ); + AudioDevicePropertyGenericListenerProc, stream ); } /* ================================================================================= */ static PaError OpenAndSetupOneAudioUnit( - const PaMacCoreStream *stream, - const PaStreamParameters *inStreamParams, - const PaStreamParameters *outStreamParams, - const UInt32 requestedFramesPerBuffer, - UInt32 *actualInputFramesPerBuffer, - UInt32 *actualOutputFramesPerBuffer, - const PaMacAUHAL *auhalHostApi, - AudioUnit *audioUnit, - AudioConverterRef *srConverter, - AudioDeviceID *audioDevice, - const double sampleRate, - void *refCon ) + const PaMacCoreStream *stream, + const PaStreamParameters *inStreamParams, + const PaStreamParameters *outStreamParams, + const UInt32 requestedFramesPerBuffer, + UInt32 *actualInputFramesPerBuffer, + UInt32 *actualOutputFramesPerBuffer, + const PaMacAUHAL *auhalHostApi, + AudioUnit *audioUnit, + AudioConverterRef *srConverter, + AudioDeviceID *audioDevice, + const double sampleRate, + void *refCon ) { #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6 AudioComponentDescription desc; @@ -1200,39 +1202,35 @@ static PaError OpenAndSetupOneAudioUnit( 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 )); + 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; + *audioUnit = NULL; + *audioDevice = kAudioDeviceUnknown; + return paNoError; } /* -- get the user's api specific info, if they set any -- */ if( inStreamParams && inStreamParams->hostApiSpecificStreamInfo ) { - macInputStreamFlags= + macInputStreamFlags= ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo) - ->flags; - inChannelMap = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo) - ->channelMap; - inChannelMapSize = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo) - ->channelMapSize; + ->flags; + inChannelMap = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)->channelMap; + inChannelMapSize = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)->channelMapSize; } if( outStreamParams && outStreamParams->hostApiSpecificStreamInfo ) { - macOutputStreamFlags= + macOutputStreamFlags= ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo) - ->flags; - outChannelMap = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo) - ->channelMap; - outChannelMapSize = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo) - ->channelMapSize; + ->flags; + outChannelMap = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)->channelMap; + outChannelMapSize = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)->channelMapSize; } /* Override user's flags here, if desired for testing. */ @@ -1262,10 +1260,10 @@ static PaError OpenAndSetupOneAudioUnit( #endif if( !comp ) { - DBUG( ( "AUHAL component not found." ) ); - *audioUnit = NULL; - *audioDevice = kAudioDeviceUnknown; - return paUnanticipatedHostError; + DBUG( ( "AUHAL component not found." ) ); + *audioUnit = NULL; + *audioDevice = kAudioDeviceUnknown; + return paUnanticipatedHostError; } /* -- open it -- */ #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6 @@ -1275,10 +1273,10 @@ static PaError OpenAndSetupOneAudioUnit( #endif if( result ) { - DBUG( ( "Failed to open AUHAL component." ) ); - *audioUnit = NULL; - *audioDevice = kAudioDeviceUnknown; - return ERR( 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) @@ -1286,24 +1284,24 @@ static PaError OpenAndSetupOneAudioUnit( /* -- 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) ) ); + 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) ) ); + UInt32 enableIO = 0; + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioOutputUnitProperty_EnableIO, + kAudioUnitScope_Output, + OUTPUT_ELEMENT, + &enableIO, + sizeof(enableIO) ) ); } /* -- set the devices -- */ @@ -1311,40 +1309,40 @@ static PaError OpenAndSetupOneAudioUnit( output. */ if( inStreamParams && outStreamParams ) { - assert( outStreamParams->device == inStreamParams->device ); + 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) ) ); + *audioDevice = auhalHostApi->devIds[inStreamParams->device] ; + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioOutputUnitProperty_CurrentDevice, + kAudioUnitScope_Global, + INPUT_ELEMENT, + audioDevice, + sizeof(AudioDeviceID) ) ); } if( outStreamParams && outStreamParams != inStreamParams ) { - *audioDevice = auhalHostApi->devIds[outStreamParams->device] ; - ERR_WRAP( AudioUnitSetProperty( *audioUnit, - kAudioOutputUnitProperty_CurrentDevice, - kAudioUnitScope_Global, - OUTPUT_ELEMENT, - audioDevice, - sizeof(AudioDeviceID) ) ); + *audioDevice = auhalHostApi->devIds[outStreamParams->device] ; + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioOutputUnitProperty_CurrentDevice, + kAudioUnitScope_Global, + OUTPUT_ELEMENT, + audioDevice, + sizeof(AudioDeviceID) ) ); } /* -- add listener for dropouts -- */ result = PaMacCore_AudioDeviceAddPropertyListener( *audioDevice, - 0, - outStreamParams ? false : true, - kAudioDeviceProcessorOverload, - xrunCallback, - addToXRunListenerList( (void *)stream ) ) ; + 0, + outStreamParams ? false : true, + kAudioDeviceProcessorOverload, + xrunCallback, + addToXRunListenerList( (void *)stream ) ) ; if( result == kAudioHardwareIllegalOperationError ) { - // -- already registered, we're good + // -- already registered, we're good } else { - // -- not already registered, just check for errors - ERR_WRAP( result ); + // -- not already registered, just check for errors + ERR_WRAP( result ); } /* -- listen for stream start and stop -- */ ERR_WRAP( AudioUnitAddPropertyListener( *audioUnit, @@ -1362,100 +1360,100 @@ static PaError OpenAndSetupOneAudioUnit( 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 weird, 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 ; + /*The callback never calls back if we don't set the FPB */ + /*This seems weird, 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 weird, 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; - } + /*The callback never calls back if we don't set the FPB */ + /*This seems weird, 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) ) ); + 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) ) ); + 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) ) ); + 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 @@ -1464,36 +1462,36 @@ static PaError OpenAndSetupOneAudioUnit( 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(*actualOutputFramesPerBuffer) ) ); - ERR_WRAP( AudioUnitGetProperty( *audioUnit, - kAudioUnitProperty_MaximumFramesPerSlice, - kAudioUnitScope_Global, - OUTPUT_ELEMENT, - actualOutputFramesPerBuffer, - &size ) ); + UInt32 size = sizeof( *actualOutputFramesPerBuffer ); + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioUnitProperty_MaximumFramesPerSlice, + kAudioUnitScope_Input, + OUTPUT_ELEMENT, + actualOutputFramesPerBuffer, + sizeof(*actualOutputFramesPerBuffer) ) ); + 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(*actualInputFramesPerBuffer) ) ); -/* Don't know why this causes problems - ERR_WRAP( AudioUnitGetProperty( *audioUnit, - kAudioUnitProperty_MaximumFramesPerSlice, - kAudioUnitScope_Global, //Output, - INPUT_ELEMENT, - actualInputFramesPerBuffer, - &size ) ); -*/ + /*UInt32 size = sizeof( *actualInputFramesPerBuffer );*/ + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioUnitProperty_MaximumFramesPerSlice, + kAudioUnitScope_Output, + INPUT_ELEMENT, + actualInputFramesPerBuffer, + sizeof(*actualInputFramesPerBuffer) ) ); + /* 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 -- */ @@ -1501,83 +1499,78 @@ static PaError OpenAndSetupOneAudioUnit( 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 ) ); - } + 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 ; + : kAudioOutputUnitProperty_SetInputCallback ; rcbs.inputProc = AudioIOProc; rcbs.inputProcRefCon = refCon; - ERR_WRAP( AudioUnitSetProperty( - *audioUnit, - callbackKey, - kAudioUnitScope_Output, - outStreamParams ? OUTPUT_ELEMENT : INPUT_ELEMENT, - &rcbs, - sizeof(rcbs)) ); + 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)) ); + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioOutputUnitProperty_SetInputCallback, + kAudioUnitScope_Output, + INPUT_ELEMENT, + &rcbs, + sizeof(rcbs)) ); /* channel mapping. */ if(inChannelMap) @@ -1586,12 +1579,12 @@ static PaError OpenAndSetupOneAudioUnit( //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)); + ERR_WRAP( AudioUnitSetProperty( *audioUnit, + kAudioOutputUnitProperty_ChannelMap, + kAudioUnitScope_Output, + INPUT_ELEMENT, + inChannelMap, + mapSize) ); } if(outChannelMap) { @@ -1599,12 +1592,12 @@ static PaError OpenAndSetupOneAudioUnit( //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)); + ERR_WRAP(AudioUnitSetProperty( *audioUnit, + kAudioOutputUnitProperty_ChannelMap, + kAudioUnitScope_Output, + OUTPUT_ELEMENT, + outChannelMap, + mapSize) ); } /* initialize the audio unit */ ERR_WRAP( AudioUnitInitialize(*audioUnit) ); @@ -1624,30 +1617,30 @@ static PaError OpenAndSetupOneAudioUnit( return paNoError; #undef ERR_WRAP - error: +error: #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6 - AudioComponentInstanceDispose( *audioUnit ); + AudioComponentInstanceDispose( *audioUnit ); #else - CloseComponent( *audioUnit ); + CloseComponent( *audioUnit ); #endif - *audioUnit = NULL; - if( result ) - return PaMacCore_SetError( result, line, 1 ); - return paResult; + *audioUnit = NULL; + if( result ) + return PaMacCore_SetError( result, line, 1 ); + return paResult; } /* =================================================================================================== */ static UInt32 CalculateOptimalBufferSize( PaMacAUHAL *auhalHostApi, - const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, - UInt32 fixedInputLatency, - UInt32 fixedOutputLatency, - double sampleRate, - UInt32 requestedFramesPerBuffer ) + const PaStreamParameters *inputParameters, + const PaStreamParameters *outputParameters, + UInt32 fixedInputLatency, + UInt32 fixedOutputLatency, + double sampleRate, + UInt32 requestedFramesPerBuffer ) { - UInt32 resultBufferSizeFrames = 0; + UInt32 resultBufferSizeFrames = 0; // Use maximum of suggested input and output latencies. if( inputParameters ) { @@ -1655,46 +1648,46 @@ static UInt32 CalculateOptimalBufferSize( PaMacAUHAL *auhalHostApi, // Calculate a buffer size assuming we are double buffered. SInt32 variableLatencyFrames = suggestedLatencyFrames - fixedInputLatency; // Prevent negative latency. - variableLatencyFrames = MAX( variableLatencyFrames, 0 ); + variableLatencyFrames = MAX( variableLatencyFrames, 0 ); resultBufferSizeFrames = MAX( resultBufferSizeFrames, (UInt32) variableLatencyFrames ); } if( outputParameters ) - { + { UInt32 suggestedLatencyFrames = outputParameters->suggestedLatency * sampleRate; SInt32 variableLatencyFrames = suggestedLatencyFrames - fixedOutputLatency; variableLatencyFrames = MAX( variableLatencyFrames, 0 ); resultBufferSizeFrames = MAX( resultBufferSizeFrames, (UInt32) variableLatencyFrames ); } - + // can't have zero frames. code to round up to next user buffer requires non-zero resultBufferSizeFrames = MAX( resultBufferSizeFrames, 1 ); - + if( requestedFramesPerBuffer != paFramesPerBufferUnspecified ) { // make host buffer the next highest integer multiple of user frames per buffer UInt32 n = (resultBufferSizeFrames + requestedFramesPerBuffer - 1) / requestedFramesPerBuffer; resultBufferSizeFrames = n * requestedFramesPerBuffer; - + // FIXME: really we should be searching for a multiple of requestedFramesPerBuffer // that is >= suggested latency and also fits within device buffer min/max - - }else{ - VDBUG( ("Block Size unspecified. Based on Latency, the user wants a Block Size near: %ld.\n", - (long)resultBufferSizeFrames ) ); + + } else { + VDBUG( ("Block Size unspecified. Based on Latency, the user wants a Block Size near: %ld.\n", + (long)resultBufferSizeFrames ) ); } - + // Clip to the capabilities of the device. if( inputParameters ) { ClipToDeviceBufferSize( auhalHostApi->devIds[inputParameters->device], - true, // In the old code isInput was false! - resultBufferSizeFrames, &resultBufferSizeFrames ); + true, // In the old code isInput was false! + resultBufferSizeFrames, &resultBufferSizeFrames ); } if( outputParameters ) { ClipToDeviceBufferSize( auhalHostApi->devIds[outputParameters->device], - false, resultBufferSizeFrames, &resultBufferSizeFrames ); + false, resultBufferSizeFrames, &resultBufferSizeFrames ); } VDBUG(("After querying hardware, setting block size to %ld.\n", (long)resultBufferSizeFrames)); @@ -1725,28 +1718,28 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, UInt32 inputLatencyFrames = 0; UInt32 outputLatencyFrames = 0; UInt32 suggestedLatencyFramesPerBuffer = requestedFramesPerBuffer; - + 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, - requestedFramesPerBuffer )); + inputParameters ? inputParameters->channelCount : -1, + inputParameters ? inputParameters->sampleFormat : -1, + outputParameters ? outputParameters->channelCount : -1, + outputParameters ? outputParameters->sampleFormat : -1, + (float) sampleRate, + requestedFramesPerBuffer )); VDBUG( ("Opening Stream.\n") ); - + /* These first few bits of code are from paSkeleton with few modifications. */ if( inputParameters ) { inputChannelCount = inputParameters->channelCount; inputSampleFormat = inputParameters->sampleFormat; - /* @todo Blocking read/write on Mac is not yet supported. */ - if( !streamCallback && inputSampleFormat & paNonInterleaved ) - { - return paSampleFormatNotSupported; - } - + /* @todo Blocking read/write on Mac is not yet supported. */ + if( !streamCallback && inputSampleFormat & paNonInterleaved ) + { + return paSampleFormatNotSupported; + } + /* unless alternate device specification is supported, reject the use of paUseHostApiSpecificDeviceSpecification */ @@ -1770,13 +1763,13 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, { outputChannelCount = outputParameters->channelCount; outputSampleFormat = outputParameters->sampleFormat; - - /* @todo Blocking read/write on Mac is not yet supported. */ - if( !streamCallback && outputSampleFormat & paNonInterleaved ) - { - return paSampleFormatNotSupported; - } - + + /* @todo Blocking read/write on Mac is not yet supported. */ + if( !streamCallback && outputSampleFormat & paNonInterleaved ) + { + return paSampleFormatNotSupported; + } + /* unless alternate device specification is supported, reject the use of paUseHostApiSpecificDeviceSpecification */ @@ -1813,7 +1806,7 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, been touched. */ bzero( stream, sizeof( PaMacCoreStream ) ); - + /* stream->blio.inputRingBuffer.buffer = NULL; stream->blio.outputRingBuffer.buffer = NULL; @@ -1827,223 +1820,223 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, if( streamCallback ) { PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, - &auhalHostApi->callbackStreamInterface, - streamCallback, userData ); + &auhalHostApi->callbackStreamInterface, + streamCallback, userData ); } else { PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, - &auhalHostApi->blockingStreamInterface, - BlioCallback, &stream->blio ); + &auhalHostApi->blockingStreamInterface, + BlioCallback, &stream->blio ); } PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); - + if( inputParameters ) { CalculateFixedDeviceLatency( auhalHostApi->devIds[inputParameters->device], true, &fixedInputLatency ); inputLatencyFrames += fixedInputLatency; } if( outputParameters ) - { + { CalculateFixedDeviceLatency( auhalHostApi->devIds[outputParameters->device], false, &fixedOutputLatency ); outputLatencyFrames += fixedOutputLatency; } - + suggestedLatencyFramesPerBuffer = CalculateOptimalBufferSize( auhalHostApi, inputParameters, outputParameters, - fixedInputLatency, fixedOutputLatency, - sampleRate, requestedFramesPerBuffer ); + fixedInputLatency, fixedOutputLatency, + sampleRate, requestedFramesPerBuffer ); if( requestedFramesPerBuffer == paFramesPerBufferUnspecified ) - { + { requestedFramesPerBuffer = suggestedLatencyFramesPerBuffer; } /* -- Now we actually open and setup streams. -- */ if( inputParameters && outputParameters && outputParameters->device == inputParameters->device ) - { /* full duplex. One device. */ - UInt32 inputFramesPerBuffer = (UInt32) stream->inputFramesPerBuffer; - UInt32 outputFramesPerBuffer = (UInt32) stream->outputFramesPerBuffer; - result = OpenAndSetupOneAudioUnit( stream, - inputParameters, - outputParameters, - suggestedLatencyFramesPerBuffer, - &inputFramesPerBuffer, - &outputFramesPerBuffer, - auhalHostApi, - &(stream->inputUnit), - &(stream->inputSRConverter), - &(stream->inputDevice), - sampleRate, - stream ); - stream->inputFramesPerBuffer = inputFramesPerBuffer; - stream->outputFramesPerBuffer = outputFramesPerBuffer; - stream->outputUnit = stream->inputUnit; - stream->outputDevice = stream->inputDevice; - if( result != paNoError ) - goto error; + { /* full duplex. One device. */ + UInt32 inputFramesPerBuffer = (UInt32) stream->inputFramesPerBuffer; + UInt32 outputFramesPerBuffer = (UInt32) stream->outputFramesPerBuffer; + result = OpenAndSetupOneAudioUnit( stream, + inputParameters, + outputParameters, + suggestedLatencyFramesPerBuffer, + &inputFramesPerBuffer, + &outputFramesPerBuffer, + auhalHostApi, + &(stream->inputUnit), + &(stream->inputSRConverter), + &(stream->inputDevice), + sampleRate, + stream ); + stream->inputFramesPerBuffer = inputFramesPerBuffer; + stream->outputFramesPerBuffer = outputFramesPerBuffer; + stream->outputUnit = stream->inputUnit; + stream->outputDevice = stream->inputDevice; + if( result != paNoError ) + goto error; } else - { /* full duplex, different devices OR simplex */ - UInt32 outputFramesPerBuffer = (UInt32) stream->outputFramesPerBuffer; - UInt32 inputFramesPerBuffer = (UInt32) stream->inputFramesPerBuffer; - result = OpenAndSetupOneAudioUnit( stream, - NULL, - outputParameters, - suggestedLatencyFramesPerBuffer, - NULL, - &outputFramesPerBuffer, - auhalHostApi, - &(stream->outputUnit), - NULL, - &(stream->outputDevice), - sampleRate, - stream ); - if( result != paNoError ) - goto error; - result = OpenAndSetupOneAudioUnit( stream, - inputParameters, - NULL, - suggestedLatencyFramesPerBuffer, - &inputFramesPerBuffer, - NULL, - auhalHostApi, - &(stream->inputUnit), - &(stream->inputSRConverter), - &(stream->inputDevice), - sampleRate, - stream ); - if( result != paNoError ) - goto error; - stream->inputFramesPerBuffer = inputFramesPerBuffer; - stream->outputFramesPerBuffer = outputFramesPerBuffer; - } - + { /* full duplex, different devices OR simplex */ + UInt32 outputFramesPerBuffer = (UInt32) stream->outputFramesPerBuffer; + UInt32 inputFramesPerBuffer = (UInt32) stream->inputFramesPerBuffer; + result = OpenAndSetupOneAudioUnit( stream, + NULL, + outputParameters, + suggestedLatencyFramesPerBuffer, + NULL, + &outputFramesPerBuffer, + auhalHostApi, + &(stream->outputUnit), + NULL, + &(stream->outputDevice), + sampleRate, + stream ); + if( result != paNoError ) + goto error; + result = OpenAndSetupOneAudioUnit( stream, + inputParameters, + NULL, + suggestedLatencyFramesPerBuffer, + &inputFramesPerBuffer, + NULL, + auhalHostApi, + &(stream->inputUnit), + &(stream->inputSRConverter), + &(stream->inputDevice), + sampleRate, + stream ); + if( result != paNoError ) + goto error; + stream->inputFramesPerBuffer = inputFramesPerBuffer; + stream->outputFramesPerBuffer = outputFramesPerBuffer; + } + inputLatencyFrames += stream->inputFramesPerBuffer; outputLatencyFrames += stream->outputFramesPerBuffer; - + 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 input data while waiting for - * output data. - */ - if( (stream->outputUnit && (stream->inputUnit != stream->outputUnit)) - || stream->inputSRConverter ) - { - /* May want the ringSize or 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*inputParameters->channelCount ); - if( !data ) - { - result = paInsufficientMemory; - goto error; - } - - /* now we can initialize the ring buffer */ - result = PaUtil_InitializeRingBuffer( &stream->inputRingBuffer, szfl*inputParameters->channelCount, ringSize, data ); - if( result != 0 ) - { - /* The only reason this should fail is if ringSize is not a power of 2, which we do not anticipate happening. */ - result = paUnanticipatedHostError; - free(data); - goto error; - } - - /* advance the read point a little, so we are reading from the - middle of the buffer */ - if( stream->outputUnit ) - PaUtil_AdvanceRingBufferWriteIndex( &stream->inputRingBuffer, ringSize / RING_BUFFER_ADVANCE_DENOMINATOR ); - - // Just adds to input latency between input device and PA full duplex callback. - inputLatencyFrames += ringSize; - } + 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 input data while waiting for + * output data. + */ + if( (stream->outputUnit && (stream->inputUnit != stream->outputUnit)) + || stream->inputSRConverter ) + { + /* May want the ringSize or 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*inputParameters->channelCount ); + if( !data ) + { + result = paInsufficientMemory; + goto error; + } + + /* now we can initialize the ring buffer */ + result = PaUtil_InitializeRingBuffer( &stream->inputRingBuffer, szfl*inputParameters->channelCount, ringSize, data ); + if( result != 0 ) + { + /* The only reason this should fail is if ringSize is not a power of 2, which we do not anticipate happening. */ + result = paUnanticipatedHostError; + free(data); + goto error; + } + + /* advance the read point a little, so we are reading from the + middle of the buffer */ + if( stream->outputUnit ) + PaUtil_AdvanceRingBufferWriteIndex( &stream->inputRingBuffer, ringSize / RING_BUFFER_ADVANCE_DENOMINATOR ); + + // Just adds to input latency between input device and PA full duplex callback. + inputLatencyFrames += ringSize; + } } /* -- 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, - ringSize, - inputParameters ? inputChannelCount : 0, - outputParameters ? outputChannelCount : 0 ) ; - if( result != paNoError ) - goto error; - + long ringSize; + + ringSize = computeRingBufferSize( inputParameters, + outputParameters, + stream->inputFramesPerBuffer, + stream->outputFramesPerBuffer, + sampleRate ); + result = initializeBlioRingBuffers( &stream->blio, + inputParameters ? inputParameters->sampleFormat : 0, + outputParameters ? outputParameters->sampleFormat : 0, + ringSize, + inputParameters ? inputChannelCount : 0, + outputParameters ? outputChannelCount : 0 ); + if( result != paNoError ) + goto error; + inputLatencyFrames += ringSize; outputLatencyFrames += ringSize; - + } /* -- 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, - requestedFramesPerBuffer, - /* 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; + 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, + requestedFramesPerBuffer, + /* 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; // Calculate actual latency from the sum of individual latencies. - if( inputParameters ) + if( inputParameters ) { inputLatencyFrames += PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor); stream->streamRepresentation.streamInfo.inputLatency = inputLatencyFrames / sampleRate; @@ -2052,8 +2045,8 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, { stream->streamRepresentation.streamInfo.inputLatency = 0.0; } - - if( outputParameters ) + + if( outputParameters ) { outputLatencyFrames += PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor); stream->streamRepresentation.streamInfo.outputLatency = outputLatencyFrames / sampleRate; @@ -2062,49 +2055,49 @@ static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, { stream->streamRepresentation.streamInfo.outputLatency = 0.0; } - + stream->streamRepresentation.streamInfo.sampleRate = sampleRate; stream->sampleRate = sampleRate; - + stream->userInChan = inputChannelCount; stream->userOutChan = outputChannelCount; // Setup property listeners for timestamp and latency calculations. - pthread_mutex_init( &stream->timingInformationMutex, NULL ); - stream->timingInformationMutexIsInitialized = 1; + pthread_mutex_init( &stream->timingInformationMutex, NULL ); + stream->timingInformationMutexIsInitialized = 1; InitializeDeviceProperties( &stream->inputProperties ); // zeros the struct. doesn't actually init it to useful values InitializeDeviceProperties( &stream->outputProperties ); // zeros the struct. doesn't actually init it to useful values - if( stream->outputUnit ) + if( stream->outputUnit ) { Boolean isInput = FALSE; - + // Start with the current values for the device properties. // Init with nominal sample rate. Use actual sample rate where available - - result = ERR( UpdateSampleRateFromDeviceProperty( - stream, stream->outputDevice, isInput, kAudioDevicePropertyNominalSampleRate ) ); + + result = ERR( UpdateSampleRateFromDeviceProperty( + stream, stream->outputDevice, isInput, kAudioDevicePropertyNominalSampleRate ) ); if( result ) goto error; /* fail if we can't even get a nominal device sample rate */ - + UpdateSampleRateFromDeviceProperty( stream, stream->outputDevice, isInput, kAudioDevicePropertyActualSampleRate ); - + SetupDevicePropertyListeners( stream, stream->outputDevice, isInput ); } - if( stream->inputUnit ) + if( stream->inputUnit ) { Boolean isInput = TRUE; - + // as above - result = ERR( UpdateSampleRateFromDeviceProperty( - stream, stream->inputDevice, isInput, kAudioDevicePropertyNominalSampleRate ) ); + result = ERR( UpdateSampleRateFromDeviceProperty( + stream, stream->inputDevice, isInput, kAudioDevicePropertyNominalSampleRate ) ); if( result ) goto error; - + UpdateSampleRateFromDeviceProperty( stream, stream->inputDevice, isInput, kAudioDevicePropertyActualSampleRate ); - + SetupDevicePropertyListeners( stream, stream->inputDevice, isInput ); - } + } UpdateTimeStampOffsets( stream ); // Setup timestamp copies to be used by audio callback. stream->timestampOffsetCombined_ioProcCopy = stream->timestampOffsetCombined; @@ -2128,7 +2121,7 @@ error: PaTime GetStreamTime( PaStream *s ) { - return HOST_TIME_TO_PA_TIME( AudioGetCurrentHostTime() ); + return HOST_TIME_TO_PA_TIME( AudioGetCurrentHostTime() ); } #define RING_BUFFER_EMPTY (1000) @@ -2140,37 +2133,37 @@ static OSStatus ringBufferIOProc( AudioStreamPacketDescription** outDataPacketDescription, void* inUserData) { - VVDBUG(("ringBufferIOProc()\n")); - - PaUtilRingBuffer *rb = (PaUtilRingBuffer *) inUserData; - - if( PaUtil_GetRingBufferReadAvailable( rb ) == 0 ) { - ioData->mBuffers[0].mData = NULL; - ioData->mBuffers[0].mDataByteSize = 0; - *ioNumberDataPackets = 0; - VVDBUG(("Ring buffer empty!\n")); - return RING_BUFFER_EMPTY; - } - - UInt32 packetSize = sizeof(float) * ioData->mBuffers[0].mNumberChannels; - UInt32 dataSize = *ioNumberDataPackets * packetSize; - assert(dataSize % rb->elementSizeBytes == 0); - UInt32 rbElements = dataSize / rb->elementSizeBytes; - ring_buffer_size_t rbElementsRead = rbElements; - void *dummyData; - ring_buffer_size_t dummySize; - PaUtil_GetRingBufferReadRegions( rb, rbElements, - &ioData->mBuffers[0].mData, &rbElementsRead, - &dummyData, &dummySize ); - assert(rbElementsRead > 0); - VVDBUG(("RingBuffer read elements %u of %u\n", rbElementsRead, rbElements)); - PaUtil_AdvanceRingBufferReadIndex( rb, rbElementsRead ); - - UInt32 bytesRead = rbElementsRead * rb->elementSizeBytes; - ioData->mBuffers[0].mDataByteSize = bytesRead; - *ioNumberDataPackets = bytesRead / packetSize; - - return noErr; + VVDBUG(("ringBufferIOProc()\n")); + + PaUtilRingBuffer *rb = (PaUtilRingBuffer *) inUserData; + + if( PaUtil_GetRingBufferReadAvailable( rb ) == 0 ) { + ioData->mBuffers[0].mData = NULL; + ioData->mBuffers[0].mDataByteSize = 0; + *ioNumberDataPackets = 0; + VVDBUG(("Ring buffer empty!\n")); + return RING_BUFFER_EMPTY; + } + + UInt32 packetSize = sizeof(float) * ioData->mBuffers[0].mNumberChannels; + UInt32 dataSize = *ioNumberDataPackets * packetSize; + assert(dataSize % rb->elementSizeBytes == 0); + UInt32 rbElements = dataSize / rb->elementSizeBytes; + ring_buffer_size_t rbElementsRead = rbElements; + void *dummyData; + ring_buffer_size_t dummySize; + PaUtil_GetRingBufferReadRegions( rb, rbElements, + &ioData->mBuffers[0].mData, &rbElementsRead, + &dummyData, &dummySize ); + assert(rbElementsRead > 0); + VVDBUG(("RingBuffer read elements %u of %u\n", rbElementsRead, rbElements)); + PaUtil_AdvanceRingBufferReadIndex( rb, rbElementsRead ); + + UInt32 bytesRead = rbElementsRead * rb->elementSizeBytes; + ioData->mBuffers[0].mDataByteSize = bytesRead; + *ioNumberDataPackets = bytesRead / packetSize; + + return noErr; } /* @@ -2179,446 +2172,446 @@ static OSStatus ringBufferIOProc( */ /* 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 ) + 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 ; - double hostTimeStampInPaTime = HOST_TIME_TO_PA_TIME(inTimeStamp->mHostTime); - - VVDBUG(("AudioIOProc()\n")); - - PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); - - /* -----------------------------------------------------------------*\ - This output may be useful for debugging, - But printing during the callback is a bad enough idea that - this is not enabled by enabling the usual debugging calls. - \* -----------------------------------------------------------------*/ - /* - static int renderCount = 0; - static int inputCount = 0; - printf( "------------------- starting render/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; imNumberBuffers; ++i ) - printf( "--- ioData buffer %d size: %lu.\n", i, ioData->mBuffers[i].mDataByteSize ); - } - ----------------------------------------------------------------- */ - - /* compute PaStreamCallbackTimeInfo */ - - if( pthread_mutex_trylock( &stream->timingInformationMutex ) == 0 ){ - /* snapshot the ioproc copy of timing information */ - stream->timestampOffsetCombined_ioProcCopy = stream->timestampOffsetCombined; - stream->timestampOffsetInputDevice_ioProcCopy = stream->timestampOffsetInputDevice; - stream->timestampOffsetOutputDevice_ioProcCopy = stream->timestampOffsetOutputDevice; - pthread_mutex_unlock( &stream->timingInformationMutex ); - } - - /* For timeInfo.currentTime we could calculate current time backwards from the HAL audio - output time to give a more accurate impression of the current timeslice but it doesn't - seem worth it at the moment since other PA host APIs don't do any better. - */ - timeInfo.currentTime = HOST_TIME_TO_PA_TIME( AudioGetCurrentHostTime() ); - - /* - For an input HAL AU, inTimeStamp is the time the samples are received from the hardware, - for an output HAL AU inTimeStamp is the time the samples are sent to the hardware. - PA expresses timestamps in terms of when the samples enter the ADC or leave the DAC - so we add or subtract kAudioDevicePropertyLatency below. - */ - - /* FIXME: not sure what to do below if the host timestamps aren't valid (kAudioTimeStampHostTimeValid isn't set) - Could ask on CA mailing list if it is possible for it not to be set. If so, could probably grab a now timestamp - at the top and compute from there (modulo scheduling jitter) or ask on mailing list for other options. */ - - if( isRender ) - { - if( stream->inputUnit ) /* full duplex */ - { - if( stream->inputUnit == stream->outputUnit ) /* full duplex AUHAL IOProc */ - { + unsigned long framesProcessed = 0; + PaStreamCallbackTimeInfo timeInfo = {0,0,0}; + PaMacCoreStream *stream = (PaMacCoreStream*)inRefCon; + const bool isRender = inBusNumber == OUTPUT_ELEMENT; + int callbackResult = paContinue ; + double hostTimeStampInPaTime = HOST_TIME_TO_PA_TIME(inTimeStamp->mHostTime); + + VVDBUG(("AudioIOProc()\n")); + + PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer ); + + /* -----------------------------------------------------------------*\ + This output may be useful for debugging, + But printing during the callback is a bad enough idea that + this is not enabled by enabling the usual debugging calls. + \* -----------------------------------------------------------------*/ + /* + static int renderCount = 0; + static int inputCount = 0; + printf( "------------------- starting render/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; imNumberBuffers; ++i ) + printf( "--- ioData buffer %d size: %lu.\n", i, ioData->mBuffers[i].mDataByteSize ); + } + ----------------------------------------------------------------- */ + + /* compute PaStreamCallbackTimeInfo */ + + if( pthread_mutex_trylock( &stream->timingInformationMutex ) == 0 ) { + /* snapshot the ioproc copy of timing information */ + stream->timestampOffsetCombined_ioProcCopy = stream->timestampOffsetCombined; + stream->timestampOffsetInputDevice_ioProcCopy = stream->timestampOffsetInputDevice; + stream->timestampOffsetOutputDevice_ioProcCopy = stream->timestampOffsetOutputDevice; + pthread_mutex_unlock( &stream->timingInformationMutex ); + } + + /* For timeInfo.currentTime we could calculate current time backwards from the HAL audio + output time to give a more accurate impression of the current timeslice but it doesn't + seem worth it at the moment since other PA host APIs don't do any better. + */ + timeInfo.currentTime = HOST_TIME_TO_PA_TIME( AudioGetCurrentHostTime() ); + + /* + For an input HAL AU, inTimeStamp is the time the samples are received from the hardware, + for an output HAL AU inTimeStamp is the time the samples are sent to the hardware. + PA expresses timestamps in terms of when the samples enter the ADC or leave the DAC + so we add or subtract kAudioDevicePropertyLatency below. + */ + + /* FIXME: not sure what to do below if the host timestamps aren't valid (kAudioTimeStampHostTimeValid isn't set) + Could ask on CA mailing list if it is possible for it not to be set. If so, could probably grab a now timestamp + at the top and compute from there (modulo scheduling jitter) or ask on mailing list for other options. */ + + if( isRender ) + { + if( stream->inputUnit ) /* full duplex */ + { + if( stream->inputUnit == stream->outputUnit ) /* full duplex AUHAL IOProc */ + { // Ross and Phil agreed that the following calculation is correct based on an email from Jeff Moore: // http://osdir.com/ml/coreaudio-api/2009-07/msg00140.html // Basically the difference between the Apple output timestamp and the PA timestamp is kAudioDevicePropertyLatency. - timeInfo.inputBufferAdcTime = hostTimeStampInPaTime - - (stream->timestampOffsetCombined_ioProcCopy + stream->timestampOffsetInputDevice_ioProcCopy); - timeInfo.outputBufferDacTime = hostTimeStampInPaTime + stream->timestampOffsetOutputDevice_ioProcCopy; - } - else /* full duplex with ring-buffer from a separate input AUHAL ioproc */ - { - /* FIXME: take the ring buffer latency into account */ - timeInfo.inputBufferAdcTime = hostTimeStampInPaTime - - (stream->timestampOffsetCombined_ioProcCopy + stream->timestampOffsetInputDevice_ioProcCopy); - timeInfo.outputBufferDacTime = hostTimeStampInPaTime + stream->timestampOffsetOutputDevice_ioProcCopy; - } - } - else /* output only */ - { - timeInfo.inputBufferAdcTime = 0; - timeInfo.outputBufferDacTime = hostTimeStampInPaTime + stream->timestampOffsetOutputDevice_ioProcCopy; - } - } - else /* input only */ - { - timeInfo.inputBufferAdcTime = hostTimeStampInPaTime - stream->timestampOffsetInputDevice_ioProcCopy; - timeInfo.outputBufferDacTime = 0; - } - - //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. - * - */ - OSStatus err = 0; - unsigned long frames; - long bytesPerFrame = sizeof( float ) * ioData->mBuffers[0].mNumberChannels; - - /* -- start processing -- */ - PaUtil_BeginBufferProcessing( &(stream->bufferProcessor), - &timeInfo, - stream->xrunFlags ); - stream->xrunFlags = 0; //FIXME: this flag also gets set outside by a callback, which calls the xrunCallback function. It should be in the same thread as the main audio callback, but the apple docs just use the word "usually" so it may be possible to loose an xrun notification, if that callback happens here. - - /* -- compute frames. do some checks -- */ - assert( ioData->mNumberBuffers == 1 ); - assert( ioData->mBuffers[0].mNumberChannels == stream->userOutChan ); - - frames = ioData->mBuffers[0].mDataByteSize / bytesPerFrame; - /* -- copy and process input data -- */ - err= AudioUnitRender(stream->inputUnit, - ioActionFlags, - inTimeStamp, - INPUT_ELEMENT, - inNumberFrames, - &stream->inputAudioBufferList ); - if(err != noErr) - { - goto stop_stream; - } - - 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; - long bytesPerFrame = sizeof( float ) * ioData->mBuffers[0].mNumberChannels; - - /* 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 / bytesPerFrame; - 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; - long bytesPerFrame = flsz * inChan; - - if( stream->inputSRConverter ) - { - OSStatus err; - float data[ inChan * frames ]; - AudioBufferList bufferList; - bufferList.mNumberBuffers = 1; - bufferList.mBuffers[0].mNumberChannels = inChan; - bufferList.mBuffers[0].mDataByteSize = sizeof( data ); - bufferList.mBuffers[0].mData = data; - UInt32 packets = frames; - err = AudioConverterFillComplexBuffer( - stream->inputSRConverter, - ringBufferIOProc, - &stream->inputRingBuffer, - &packets, - &bufferList, - NULL); - if( err == RING_BUFFER_EMPTY ) - { /* the ring buffer callback underflowed */ - err = 0; - UInt32 size = packets * bytesPerFrame; - bzero( ((char *)data) + size, sizeof(data)-size ); - /* The ring buffer can underflow normally when the stream is stopping. - * So only report an error if the stream is active. */ - if( stream->state == ACTIVE ) - { - stream->xrunFlags |= paInputUnderflow; - } - } - ERR( err ); - if(err != noErr) - { - goto stop_stream; - } - - 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; - ring_buffer_size_t size1, size2; - ring_buffer_size_t framesReadable = PaUtil_GetRingBufferReadRegions( &stream->inputRingBuffer, - frames, - &data1, &size1, - &data2, &size2 ); - if( size1 == 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( framesReadable < frames ) { - - long sizeBytes1 = size1 * bytesPerFrame; - long sizeBytes2 = size2 * bytesPerFrame; - /*we underflowed. take what data we can, zero the rest.*/ - unsigned char data[ frames * bytesPerFrame ]; - if( size1 > 0 ) - { - memcpy( data, data1, sizeBytes1 ); - } - if( size2 > 0 ) - { - memcpy( data+sizeBytes1, data2, sizeBytes2 ); - } - bzero( data+sizeBytes1+sizeBytes2, (frames*bytesPerFrame) - sizeBytes1 - sizeBytes2 ); - - PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames ); - PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor), - 0, - data, - inChan ); - framesProcessed = - PaUtil_EndBufferProcessing( &(stream->bufferProcessor), - &callbackResult ); - PaUtil_AdvanceRingBufferReadIndex( &stream->inputRingBuffer, - framesReadable ); - /* flag underflow */ - stream->xrunFlags |= paInputUnderflow; - } else { - /*we got all the data, but split between buffers*/ - PaUtil_SetInputFrameCount( &(stream->bufferProcessor), size1 ); - PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor), - 0, - data1, - inChan ); - PaUtil_Set2ndInputFrameCount( &(stream->bufferProcessor), size2 ); - PaUtil_Set2ndInterleavedInputChannels( &(stream->bufferProcessor), - 0, - data2, - inChan ); - framesProcessed = - PaUtil_EndBufferProcessing( &(stream->bufferProcessor), - &callbackResult ); - PaUtil_AdvanceRingBufferReadIndex(&stream->inputRingBuffer, framesReadable ); + timeInfo.inputBufferAdcTime = hostTimeStampInPaTime - + (stream->timestampOffsetCombined_ioProcCopy + stream->timestampOffsetInputDevice_ioProcCopy); + timeInfo.outputBufferDacTime = hostTimeStampInPaTime + stream->timestampOffsetOutputDevice_ioProcCopy; } - } - } 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. - */ - OSStatus 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 ); - ERR( err ); - if(err != noErr) - { - goto stop_stream; - } - - if( stream->inputSRConverter || stream->outputUnit ) - { - /* If this is duplex or we use a converter, put the data - into the ring buffer. */ - ring_buffer_size_t framesWritten = PaUtil_WriteRingBuffer( &stream->inputRingBuffer, - stream->inputAudioBufferList.mBuffers[0].mData, - inNumberFrames ); - if( framesWritten != inNumberFrames ) - { - 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. */ - AudioBufferList bufferList; - bufferList.mNumberBuffers = 1; - bufferList.mBuffers[0].mNumberChannels = chan; - bufferList.mBuffers[0].mDataByteSize = sizeof( data ); - bufferList.mBuffers[0].mData = data; - UInt32 packets = inNumberFrames; - err = AudioConverterFillComplexBuffer( - stream->inputSRConverter, - ringBufferIOProc, - &stream->inputRingBuffer, - &packets, - &bufferList, - NULL); - if( err != RING_BUFFER_EMPTY ) - ERR( err ); - if( err != noErr && err != RING_BUFFER_EMPTY ) + else /* full duplex with ring-buffer from a separate input AUHAL ioproc */ { - goto stop_stream; + /* FIXME: take the ring buffer latency into account */ + timeInfo.inputBufferAdcTime = hostTimeStampInPaTime - + (stream->timestampOffsetCombined_ioProcCopy + stream->timestampOffsetInputDevice_ioProcCopy); + timeInfo.outputBufferDacTime = hostTimeStampInPaTime + stream->timestampOffsetOutputDevice_ioProcCopy; } + } + else /* output only */ + { + timeInfo.inputBufferAdcTime = 0; + timeInfo.outputBufferDacTime = hostTimeStampInPaTime + stream->timestampOffsetOutputDevice_ioProcCopy; + } + } + else /* input only */ + { + timeInfo.inputBufferAdcTime = hostTimeStampInPaTime - stream->timestampOffsetInputDevice_ioProcCopy; + timeInfo.outputBufferDacTime = 0; + } - PaUtil_SetInputFrameCount( &(stream->bufferProcessor), packets ); - if( packets > 0 ) + //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. + * + */ + OSStatus err = 0; + unsigned long frames; + long bytesPerFrame = sizeof( float ) * ioData->mBuffers[0].mNumberChannels; + + /* -- start processing -- */ + PaUtil_BeginBufferProcessing( &(stream->bufferProcessor), + &timeInfo, + stream->xrunFlags ); + stream->xrunFlags = 0; //FIXME: this flag also gets set outside by a callback, which calls the xrunCallback function. It should be in the same thread as the main audio callback, but the apple docs just use the word "usually" so it may be possible to loose an xrun notification, if that callback happens here. + + /* -- compute frames. do some checks -- */ + assert( ioData->mNumberBuffers == 1 ); + assert( ioData->mBuffers[0].mNumberChannels == stream->userOutChan ); + + frames = ioData->mBuffers[0].mDataByteSize / bytesPerFrame; + /* -- copy and process input data -- */ + err= AudioUnitRender( stream->inputUnit, + ioActionFlags, + inTimeStamp, + INPUT_ELEMENT, + inNumberFrames, + &stream->inputAudioBufferList ); + if(err != noErr) + { + goto stop_stream; + } + + 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; + long bytesPerFrame = sizeof( float ) * ioData->mBuffers[0].mNumberChannels; + + /* 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 / bytesPerFrame; + 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; + long bytesPerFrame = flsz * inChan; + + if( stream->inputSRConverter ) { - PaUtil_BeginBufferProcessing( &(stream->bufferProcessor), - &timeInfo, - stream->xrunFlags ); - stream->xrunFlags = 0; - - PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor), - 0, - data, - chan ); - framesProcessed = + OSStatus err; + float data[ inChan * frames ]; + AudioBufferList bufferList; + bufferList.mNumberBuffers = 1; + bufferList.mBuffers[0].mNumberChannels = inChan; + bufferList.mBuffers[0].mDataByteSize = sizeof( data ); + bufferList.mBuffers[0].mData = data; + UInt32 packets = frames; + err = AudioConverterFillComplexBuffer( + stream->inputSRConverter, + ringBufferIOProc, + &stream->inputRingBuffer, + &packets, + &bufferList, + NULL); + if( err == RING_BUFFER_EMPTY ) + { /* the ring buffer callback underflowed */ + err = 0; + UInt32 size = packets * bytesPerFrame; + bzero( ((char *)data) + size, sizeof(data)-size ); + /* The ring buffer can underflow normally when the stream is stopping. + * So only report an error if the stream is active. */ + if( stream->state == ACTIVE ) + { + stream->xrunFlags |= paInputUnderflow; + } + } + ERR( err ); + if(err != noErr) + { + goto stop_stream; + } + + PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames ); + PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor), + 0, + data, + inChan ); + framesProcessed = PaUtil_EndBufferProcessing( &(stream->bufferProcessor), &callbackResult ); } - } while( callbackResult == paContinue && !err ); - } - } + 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; + ring_buffer_size_t size1, size2; + ring_buffer_size_t framesReadable = PaUtil_GetRingBufferReadRegions( &stream->inputRingBuffer, + frames, + &data1, &size1, + &data2, &size2 ); + if( size1 == 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( framesReadable < frames ) { + + long sizeBytes1 = size1 * bytesPerFrame; + long sizeBytes2 = size2 * bytesPerFrame; + /*we underflowed. take what data we can, zero the rest.*/ + unsigned char data[ frames * bytesPerFrame ]; + if( size1 > 0 ) + { + memcpy( data, data1, sizeBytes1 ); + } + if( size2 > 0 ) + { + memcpy( data+sizeBytes1, data2, sizeBytes2 ); + } + bzero( data+sizeBytes1+sizeBytes2, (frames*bytesPerFrame) - sizeBytes1 - sizeBytes2 ); + + PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames ); + PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor), + 0, + data, + inChan ); + framesProcessed = + PaUtil_EndBufferProcessing( &(stream->bufferProcessor), + &callbackResult ); + PaUtil_AdvanceRingBufferReadIndex( &stream->inputRingBuffer, + framesReadable ); + /* flag underflow */ + stream->xrunFlags |= paInputUnderflow; + } else { + /*we got all the data, but split between buffers*/ + PaUtil_SetInputFrameCount( &(stream->bufferProcessor), size1 ); + PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor), + 0, + data1, + inChan ); + PaUtil_Set2ndInputFrameCount( &(stream->bufferProcessor), size2 ); + PaUtil_Set2ndInterleavedInputChannels( &(stream->bufferProcessor), + 0, + data2, + inChan ); + framesProcessed = + PaUtil_EndBufferProcessing( &(stream->bufferProcessor), + &callbackResult ); + PaUtil_AdvanceRingBufferReadIndex(&stream->inputRingBuffer, framesReadable ); + } + } + } 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. + */ + OSStatus 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 ); + ERR( err ); + if(err != noErr) + { + goto stop_stream; + } + + if( stream->inputSRConverter || stream->outputUnit ) + { + /* If this is duplex or we use a converter, put the data + into the ring buffer. */ + ring_buffer_size_t framesWritten = PaUtil_WriteRingBuffer( &stream->inputRingBuffer, + stream->inputAudioBufferList.mBuffers[0].mData, + inNumberFrames ); + if( framesWritten != inNumberFrames ) + { + 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. */ + AudioBufferList bufferList; + bufferList.mNumberBuffers = 1; + bufferList.mBuffers[0].mNumberChannels = chan; + bufferList.mBuffers[0].mDataByteSize = sizeof( data ); + bufferList.mBuffers[0].mData = data; + UInt32 packets = inNumberFrames; + err = AudioConverterFillComplexBuffer( + stream->inputSRConverter, + ringBufferIOProc, + &stream->inputRingBuffer, + &packets, + &bufferList, + NULL); + if( err != RING_BUFFER_EMPTY ) + ERR( err ); + if( err != noErr && err != RING_BUFFER_EMPTY ) + { + goto stop_stream; + } + + PaUtil_SetInputFrameCount( &(stream->bufferProcessor), packets ); + if( packets > 0 ) + { + 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 ); + } + } // Should we return successfully or fall through to stopping the stream? if( callbackResult == paContinue ) @@ -2653,79 +2646,79 @@ static PaError CloseStream( PaStream* s ) VDBUG( ( "Closing stream.\n" ) ); if( stream ) { - - if( stream->outputUnit ) + + if( stream->outputUnit ) { Boolean isInput = FALSE; CleanupDevicePropertyListeners( stream, stream->outputDevice, isInput ); - } - - if( stream->inputUnit ) + } + + if( stream->inputUnit ) { Boolean isInput = TRUE; CleanupDevicePropertyListeners( stream, stream->inputDevice, isInput ); - } - - if( stream->outputUnit ) { - int count = removeFromXRunListenerList( stream ); - if( count == 0 ) - PaMacCore_AudioDeviceRemovePropertyListener( stream->outputDevice, - 0, - false, - kAudioDeviceProcessorOverload, - xrunCallback, NULL ); //no need to pass actual node - } - if( stream->inputUnit && stream->outputUnit != stream->inputUnit ) { - int count = removeFromXRunListenerList( stream ); - if( count == 0 ) - PaMacCore_AudioDeviceRemovePropertyListener( stream->inputDevice, - 0, - true, - kAudioDeviceProcessorOverload, - xrunCallback, NULL ); //no need to pass actual node - } - if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) { - AudioUnitUninitialize( stream->outputUnit ); + } + + if( stream->outputUnit ) { + int count = removeFromXRunListenerList( stream ); + if( count == 0 ) + PaMacCore_AudioDeviceRemovePropertyListener( stream->outputDevice, + 0, + false, + kAudioDeviceProcessorOverload, + xrunCallback, NULL ); //no need to pass actual node + } + if( stream->inputUnit && stream->outputUnit != stream->inputUnit ) { + int count = removeFromXRunListenerList( stream ); + if( count == 0 ) + PaMacCore_AudioDeviceRemovePropertyListener( stream->inputDevice, + 0, + true, + kAudioDeviceProcessorOverload, + xrunCallback, NULL ); //no need to pass actual node + } + if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) { + AudioUnitUninitialize( stream->outputUnit ); #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6 - AudioComponentInstanceDispose( stream->outputUnit ); + AudioComponentInstanceDispose( stream->outputUnit ); #else - CloseComponent( stream->outputUnit ); + CloseComponent( stream->outputUnit ); #endif - } - stream->outputUnit = NULL; - if( stream->inputUnit ) - { - AudioUnitUninitialize( stream->inputUnit ); + } + stream->outputUnit = NULL; + if( stream->inputUnit ) + { + AudioUnitUninitialize( stream->inputUnit ); #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6 - AudioComponentInstanceDispose( stream->inputUnit ); + AudioComponentInstanceDispose( stream->inputUnit ); #else - CloseComponent( stream->inputUnit ); + CloseComponent( stream->inputUnit ); #endif - 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 ); - - if( stream->timingInformationMutexIsInitialized ) - pthread_mutex_destroy( &stream->timingInformationMutex ); - - PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); - PaUtil_FreeMemory( stream ); + 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 ); + + if( stream->timingInformationMutexIsInitialized ) + pthread_mutex_destroy( &stream->timingInformationMutex ); + + PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation ); + PaUtil_FreeMemory( stream ); } return result; @@ -2743,17 +2736,17 @@ static PaError StartStream( PaStream *s ) /*FIXME: maybe want to do this on close/abort for faster start? */ PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); if( stream->inputSRConverter ) - ERR_WRAP( AudioConverterReset( stream->inputSRConverter ) ); + ERR_WRAP( AudioConverterReset( stream->inputSRConverter ) ); /* -- start -- */ stream->state = ACTIVE; if( stream->inputUnit ) { - ERR_WRAP( AudioOutputUnitStart(stream->inputUnit) ); + ERR_WRAP( AudioOutputUnitStart(stream->inputUnit) ); } if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) { - ERR_WRAP( AudioOutputUnitStart(stream->outputUnit) ); + ERR_WRAP( AudioOutputUnitStart(stream->outputUnit) ); } - + return paNoError; #undef ERR_WRAP } @@ -2764,11 +2757,11 @@ static ComponentResult BlockWhileAudioUnitIsRunning( AudioUnit audioUnit, AudioU { 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 ); + UInt32 s = sizeof( isRunning ); + ComponentResult err = AudioUnitGetProperty( audioUnit, kAudioOutputUnitProperty_IsRunning, kAudioUnitScope_Global, element, &isRunning, &s ); + if( err ) + return err; + Pa_Sleep( 100 ); } return noErr; } @@ -2782,38 +2775,38 @@ static PaError FinishStoppingStream( PaMacCoreStream *stream ) /* -- 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) ); + 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->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 ); + 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; @@ -2821,7 +2814,7 @@ static PaError FinishStoppingStream( PaMacCoreStream *stream ) paErr = resetBlioRingBuffers( &stream->blio ); if( paErr ) - return paErr; + return paErr; VDBUG( ( "Stream Stopped.\n" ) ); return paNoError; @@ -2843,7 +2836,7 @@ static PaError StopStream( PaStream *s ) size_t maxHostFrames = MAX( stream->inputFramesPerBuffer, stream->outputFramesPerBuffer ); VDBUG( ("Waiting for write buffer to be drained.\n") ); paErr = waitUntilBlioWriteBufferIsEmpty( &stream->blio, stream->sampleRate, - maxHostFrames ); + maxHostFrames ); VDBUG( ( "waitUntilBlioWriteBufferIsEmpty returned %d\n", paErr ) ); } return FinishStoppingStream( stream ); diff --git a/src/hostapi/coreaudio/pa_mac_core_blocking.c b/src/hostapi/coreaudio/pa_mac_core_blocking.c index e99d55e..70515f9 100644 --- a/src/hostapi/coreaudio/pa_mac_core_blocking.c +++ b/src/hostapi/coreaudio/pa_mac_core_blocking.c @@ -15,7 +15,7 @@ * 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 @@ -41,13 +41,13 @@ */ /* - * The text above constitutes the entire PortAudio license; however, + * 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 + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the * license above. */ @@ -76,33 +76,35 @@ */ static size_t computeSampleSizeFromFormat( PaSampleFormat format ) { - switch( format & (~paNonInterleaved) ) { - 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; - } + switch( format & (~paNonInterleaved) ) { + 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; + } } + /* * Same as computeSampleSizeFromFormat, except that if * the size is not a power of two, it returns the next power of two up */ static size_t computeSampleSizeFromFormatPow2( PaSampleFormat format ) { - switch( format & (~paNonInterleaved) ) { - case paFloat32: return 4; - case paInt32: return 4; - case paInt24: return 4; - case paInt16: return 2; - case paInt8: case paUInt8: return 1; - default: return 0; - } + switch( format & (~paNonInterleaved) ) { + case paFloat32: return 4; + case paInt32: return 4; + case paInt24: return 4; + case paInt16: return 2; + case paInt8: + case paUInt8: return 1; + default: return 0; + } } - /* * Functions for initializing, resetting, and destroying BLIO structures. * @@ -114,149 +116,149 @@ static size_t computeSampleSizeFromFormatPow2( PaSampleFormat format ) * @param ringBufferSizeInFrames must be a power of 2 */ PaError initializeBlioRingBuffers( - PaMacBlio *blio, - PaSampleFormat inputSampleFormat, - PaSampleFormat outputSampleFormat, - long ringBufferSizeInFrames, - int inChan, - int outChan ) + PaMacBlio *blio, + PaSampleFormat inputSampleFormat, + PaSampleFormat outputSampleFormat, + long ringBufferSizeInFrames, + int inChan, + int outChan ) { - void *data; - int result; - OSStatus err; - - /* zeroify things */ - bzero( blio, sizeof( PaMacBlio ) ); - /* this is redundant, but the buffers are used to check - if the buffers have been initialized, so we do it explicitly. */ - blio->inputRingBuffer.buffer = NULL; - blio->outputRingBuffer.buffer = NULL; - - /* initialize simple data */ - blio->ringBufferFrames = ringBufferSizeInFrames; - blio->inputSampleFormat = inputSampleFormat; - blio->inputSampleSizeActual = computeSampleSizeFromFormat(inputSampleFormat); - blio->inputSampleSizePow2 = computeSampleSizeFromFormatPow2(inputSampleFormat); // FIXME: WHY? - blio->outputSampleFormat = outputSampleFormat; - blio->outputSampleSizeActual = computeSampleSizeFromFormat(outputSampleFormat); - blio->outputSampleSizePow2 = computeSampleSizeFromFormatPow2(outputSampleFormat); - - blio->inChan = inChan; - blio->outChan = outChan; - blio->statusFlags = 0; - blio->errors = paNoError; + void *data; + int result; + OSStatus err; + + /* zeroify things */ + bzero( blio, sizeof( PaMacBlio ) ); + /* this is redundant, but the buffers are used to check + if the buffers have been initialized, so we do it explicitly. */ + blio->inputRingBuffer.buffer = NULL; + blio->outputRingBuffer.buffer = NULL; + + /* initialize simple data */ + blio->ringBufferFrames = ringBufferSizeInFrames; + blio->inputSampleFormat = inputSampleFormat; + blio->inputSampleSizeActual = computeSampleSizeFromFormat(inputSampleFormat); + blio->inputSampleSizePow2 = computeSampleSizeFromFormatPow2(inputSampleFormat); // FIXME: WHY? + blio->outputSampleFormat = outputSampleFormat; + blio->outputSampleSizeActual = computeSampleSizeFromFormat(outputSampleFormat); + blio->outputSampleSizePow2 = computeSampleSizeFromFormatPow2(outputSampleFormat); + + blio->inChan = inChan; + blio->outChan = outChan; + blio->statusFlags = 0; + blio->errors = paNoError; #ifdef PA_MAC_BLIO_MUTEX - blio->isInputEmpty = false; - blio->isOutputFull = false; + blio->isInputEmpty = false; + blio->isOutputFull = false; #endif - /* setup ring buffers */ + /* 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 ) ); + 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( ringBufferSizeInFrames, blio->inputSampleSizePow2 * inChan ); - if( !data ) - { - result = paInsufficientMemory; - goto error; - } - - err = PaUtil_InitializeRingBuffer( - &blio->inputRingBuffer, - blio->inputSampleSizePow2 * inChan, - ringBufferSizeInFrames, - data ); - assert( !err ); - } - if( outChan ) { - data = calloc( ringBufferSizeInFrames, blio->outputSampleSizePow2 * outChan ); - if( !data ) - { - result = paInsufficientMemory; - goto error; - } - - err = PaUtil_InitializeRingBuffer( - &blio->outputRingBuffer, - blio->outputSampleSizePow2 * outChan, - ringBufferSizeInFrames, - data ); - assert( !err ); - } - - result = resetBlioRingBuffers( blio ); - if( result ) - goto error; - - return 0; - - error: - destroyBlioRingBuffers( blio ); - return result; + if( inChan ) { + data = calloc( ringBufferSizeInFrames, blio->inputSampleSizePow2 * inChan ); + if( !data ) + { + result = paInsufficientMemory; + goto error; + } + + err = PaUtil_InitializeRingBuffer( + &blio->inputRingBuffer, + blio->inputSampleSizePow2 * inChan, + ringBufferSizeInFrames, + data ); + assert( !err ); + } + if( outChan ) { + data = calloc( ringBufferSizeInFrames, blio->outputSampleSizePow2 * outChan ); + if( !data ) + { + result = paInsufficientMemory; + goto error; + } + + err = PaUtil_InitializeRingBuffer( + &blio->outputRingBuffer, + blio->outputSampleSizePow2 * outChan, + ringBufferSizeInFrames, + data ); + assert( !err ); + } + + 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 no one 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 result = paNoError; + if( isEmpty == blio->isInputEmpty ) + goto done; + + /* we need to update the value. Here's what we do: + * - Lock the mutex, so no one 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 no one 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; + PaError result = paNoError; + if( isFull == blio->isOutputFull ) + goto done; + + /* we need to update the value. Here's what we do: + * - Lock the mutex, so no one 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 @@ -265,42 +267,42 @@ PaError blioSetIsOutputFull( PaMacBlio *blio, bool isFull ) PaError resetBlioRingBuffers( PaMacBlio *blio ) { #ifdef PA_MAC__BLIO_MUTEX - int result; + int result; #endif - blio->statusFlags = 0; - if( blio->outputRingBuffer.buffer ) { - PaUtil_FlushRingBuffer( &blio->outputRingBuffer ); - /* Fill the buffer with zeros. */ - bzero( blio->outputRingBuffer.buffer, - blio->outputRingBuffer.bufferSize * blio->outputRingBuffer.elementSizeBytes ); - PaUtil_AdvanceRingBufferWriteIndex( &blio->outputRingBuffer, blio->ringBufferFrames ); - - /* Update isOutputFull. */ + blio->statusFlags = 0; + if( blio->outputRingBuffer.buffer ) { + PaUtil_FlushRingBuffer( &blio->outputRingBuffer ); + /* Fill the buffer with zeros. */ + bzero( blio->outputRingBuffer.buffer, + blio->outputRingBuffer.bufferSize * blio->outputRingBuffer.elementSizeBytes ); + PaUtil_AdvanceRingBufferWriteIndex( &blio->outputRingBuffer, blio->ringBufferFrames ); + + /* Update isOutputFull. */ #ifdef PA_MAC__BLIO_MUTEX - result = blioSetIsOutputFull( blio, toAdvance == blio->outputRingBuffer.bufferSize ); - if( result ) - goto error; + result = blioSetIsOutputFull( blio, toAdvance == blio->outputRingBuffer.bufferSize ); + if( result ) + goto error; #endif -/* - printf( "------%d\n" , blio->outChan ); - printf( "------%d\n" , blio->outputSampleSize ); -*/ - } - if( blio->inputRingBuffer.buffer ) { - PaUtil_FlushRingBuffer( &blio->inputRingBuffer ); - bzero( blio->inputRingBuffer.buffer, - blio->inputRingBuffer.bufferSize * blio->inputRingBuffer.elementSizeBytes ); - /* Update isInputEmpty. */ + /* + printf( "------%d\n" , blio->outChan ); + printf( "------%d\n" , blio->outputSampleSize ); + */ + } + if( blio->inputRingBuffer.buffer ) { + PaUtil_FlushRingBuffer( &blio->inputRingBuffer ); + bzero( blio->inputRingBuffer.buffer, + blio->inputRingBuffer.bufferSize * blio->inputRingBuffer.elementSizeBytes ); + /* Update isInputEmpty. */ #ifdef PA_MAC__BLIO_MUTEX - result = blioSetIsInputEmpty( blio, true ); - if( result ) - goto error; + result = blioSetIsInputEmpty( blio, true ); + if( result ) + goto error; #endif - } - return paNoError; + } + return paNoError; #ifdef PA_MAC__BLIO_MUTEX - error: - return result; +error: + return result; #endif } @@ -308,29 +310,29 @@ PaError resetBlioRingBuffers( PaMacBlio *blio ) multiple times if there are no exceptions. */ PaError destroyBlioRingBuffers( PaMacBlio *blio ) { - PaError result = paNoError; - if( blio->inputRingBuffer.buffer ) { - free( blio->inputRingBuffer.buffer ); + 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; + 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 ); + } + 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; + 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; + } + blio->outputRingBuffer.buffer = NULL; - return result; + return result; } /* @@ -339,86 +341,86 @@ PaError destroyBlioRingBuffers( PaMacBlio *blio ) * */ int BlioCallback( const void *input, void *output, unsigned long frameCount, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ) + const PaStreamCallbackTimeInfo* timeInfo, + PaStreamCallbackFlags statusFlags, + void *userData ) { - PaMacBlio *blio = (PaMacBlio*)userData; - ring_buffer_size_t framesAvailable; - ring_buffer_size_t framesToTransfer; - ring_buffer_size_t framesTransferred; - - /* set flags returned by OS: */ - OSAtomicOr32( statusFlags, &blio->statusFlags ) ; - - /* --- Handle Input Buffer --- */ - if( blio->inChan ) { - framesAvailable = PaUtil_GetRingBufferWriteAvailable( &blio->inputRingBuffer ); - - /* check for underflow */ - if( framesAvailable < frameCount ) - { - OSAtomicOr32( paInputOverflow, &blio->statusFlags ); - framesToTransfer = framesAvailable; - } - else - { - framesToTransfer = (ring_buffer_size_t)frameCount; - } - - /* Copy the data from the audio input to the application ring buffer. */ - /*printf( "reading %d\n", toRead );*/ - framesTransferred = PaUtil_WriteRingBuffer( &blio->inputRingBuffer, input, framesToTransfer ); - assert( framesToTransfer == framesTransferred ); + PaMacBlio *blio = (PaMacBlio*)userData; + ring_buffer_size_t framesAvailable; + ring_buffer_size_t framesToTransfer; + ring_buffer_size_t framesTransferred; + + /* set flags returned by OS: */ + OSAtomicOr32( statusFlags, &blio->statusFlags ) ; + + /* --- Handle Input Buffer --- */ + if( blio->inChan ) { + framesAvailable = PaUtil_GetRingBufferWriteAvailable( &blio->inputRingBuffer ); + + /* check for underflow */ + if( framesAvailable < frameCount ) + { + OSAtomicOr32( paInputOverflow, &blio->statusFlags ); + framesToTransfer = framesAvailable; + } + else + { + framesToTransfer = (ring_buffer_size_t)frameCount; + } + + /* Copy the data from the audio input to the application ring buffer. */ + /*printf( "reading %d\n", toRead );*/ + framesTransferred = PaUtil_WriteRingBuffer( &blio->inputRingBuffer, input, framesToTransfer ); + assert( framesToTransfer == framesTransferred ); #ifdef PA_MAC__BLIO_MUTEX - /* Priority inversion. See notes below. */ - blioSetIsInputEmpty( blio, false ); + /* Priority inversion. See notes below. */ + blioSetIsInputEmpty( blio, false ); #endif - } - - - /* --- Handle Output Buffer --- */ - if( blio->outChan ) { - framesAvailable = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer ); - - /* check for underflow */ - if( framesAvailable < frameCount ) - { - /* zero out the end of the output buffer that we do not have data for */ - framesToTransfer = framesAvailable; - - size_t bytesPerFrame = blio->outputSampleSizeActual * blio->outChan; - size_t offsetInBytes = framesToTransfer * bytesPerFrame; - size_t countInBytes = (frameCount - framesToTransfer) * bytesPerFrame; - bzero( ((char *)output) + offsetInBytes, countInBytes ); - - OSAtomicOr32( paOutputUnderflow, &blio->statusFlags ); - framesToTransfer = framesAvailable; - } - else - { - framesToTransfer = (ring_buffer_size_t)frameCount; - } - - /* copy the data */ - /*printf( "writing %d\n", toWrite );*/ - framesTransferred = PaUtil_ReadRingBuffer( &blio->outputRingBuffer, output, framesToTransfer ); - assert( framesToTransfer == framesTransferred ); + } + + + /* --- Handle Output Buffer --- */ + if( blio->outChan ) { + framesAvailable = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer ); + + /* check for underflow */ + if( framesAvailable < frameCount ) + { + /* zero out the end of the output buffer that we do not have data for */ + framesToTransfer = framesAvailable; + + size_t bytesPerFrame = blio->outputSampleSizeActual * blio->outChan; + size_t offsetInBytes = framesToTransfer * bytesPerFrame; + size_t countInBytes = (frameCount - framesToTransfer) * bytesPerFrame; + bzero( ((char *)output) + offsetInBytes, countInBytes ); + + OSAtomicOr32( paOutputUnderflow, &blio->statusFlags ); + framesToTransfer = framesAvailable; + } + else + { + framesToTransfer = (ring_buffer_size_t)frameCount; + } + + /* copy the data */ + /*printf( "writing %d\n", toWrite );*/ + framesTransferred = PaUtil_ReadRingBuffer( &blio->outputRingBuffer, output, framesToTransfer ); + assert( framesToTransfer == framesTransferred ); #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 ); + /* 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; + return paContinue; } PaError ReadStream( PaStream* stream, - void *buffer, - unsigned long framesRequested ) + void *buffer, + unsigned long framesRequested ) { PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio; char *cbuf = (char *) buffer; @@ -426,58 +428,58 @@ PaError ReadStream( PaStream* stream, VVDBUG(("ReadStream()\n")); while( framesRequested > 0 ) { - ring_buffer_size_t framesAvailable; - ring_buffer_size_t framesToTransfer; - ring_buffer_size_t framesTransferred; - do { - framesAvailable = PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer ); -/* - printf( "Read Buffer is %%%g full: %ld of %ld.\n", - 100 * (float)avail / (float) blio->inputRingBuffer.bufferSize, - framesAvailable, blio->inputRingBuffer.bufferSize ); -*/ - if( framesAvailable == 0 ) { + ring_buffer_size_t framesAvailable; + ring_buffer_size_t framesToTransfer; + ring_buffer_size_t framesTransferred; + do { + framesAvailable = PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer ); + /* + printf( "Read Buffer is %%%g full: %ld of %ld.\n", + 100 * (float)avail / (float) blio->inputRingBuffer.bufferSize, + framesAvailable, blio->inputRingBuffer.bufferSize ); + */ + if( framesAvailable == 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 ) ); + /**block when empty*/ + ret = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) ); if( ret ) - return ret; - } - ret = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) ); - if( ret ) - return 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 ); + Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL ); #endif - } - } while( framesAvailable == 0 ); - framesToTransfer = (ring_buffer_size_t) MIN( framesAvailable, framesRequested ); - framesTransferred = PaUtil_ReadRingBuffer( &blio->inputRingBuffer, (void *)cbuf, framesToTransfer ); - cbuf += framesTransferred * blio->inputSampleSizeActual * blio->inChan; - framesRequested -= framesTransferred; - - if( framesToTransfer == framesAvailable ) { + } + } while( framesAvailable == 0 ); + framesToTransfer = (ring_buffer_size_t) MIN( framesAvailable, framesRequested ); + framesTransferred = PaUtil_ReadRingBuffer( &blio->inputRingBuffer, (void *)cbuf, framesToTransfer ); + cbuf += framesTransferred * blio->inputSampleSizeActual * blio->inChan; + framesRequested -= framesTransferred; + + if( framesToTransfer == framesAvailable ) { #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. */ - /* FIXME - this does not seem to fix any race condition. */ - if( PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer ) ) { - blioSetIsInputEmpty( blio, false ); - /* FIXME - why check? ret has not been set? */ - if( ret ) + /* 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. */ + /* FIXME - this does not seem to fix any race condition. */ + if( PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer ) ) { + blioSetIsInputEmpty( blio, false ); + /* FIXME - why check? ret has not been set? */ + if( ret ) + return ret; + } #endif - } + } } /* Report either paNoError or paInputOverflowed. */ @@ -487,8 +489,8 @@ PaError ReadStream( PaStream* stream, /* report underflow only once: */ if( ret ) { - OSAtomicAnd32( (uint32_t)(~paInputOverflow), &blio->statusFlags ); - ret = paInputOverflowed; + OSAtomicAnd32( (uint32_t)(~paInputOverflow), &blio->statusFlags ); + ret = paInputOverflowed; } return ret; @@ -496,8 +498,8 @@ PaError ReadStream( PaStream* stream, PaError WriteStream( PaStream* stream, - const void *buffer, - unsigned long framesRequested ) + const void *buffer, + unsigned long framesRequested ) { PaMacCoreStream *macStream = (PaMacCoreStream*)stream; PaMacBlio *blio = &macStream->blio; @@ -510,58 +512,58 @@ PaError WriteStream( PaStream* stream, ring_buffer_size_t framesToTransfer; ring_buffer_size_t framesTransferred; - do { - framesAvailable = PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer ); -/* - printf( "Write Buffer is %%%g full: %ld of %ld.\n", - 100 - 100 * (float)avail / (float) blio->outputRingBuffer.bufferSize, - framesAvailable, blio->outputRingBuffer.bufferSize ); -*/ - if( framesAvailable == 0 ) { + do { + framesAvailable = PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer ); + /* + printf( "Write Buffer is %%%g full: %ld of %ld.\n", + 100 - 100 * (float)avail / (float) blio->outputRingBuffer.bufferSize, + framesAvailable, blio->outputRingBuffer.bufferSize ); + */ + if( framesAvailable == 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 ) ); + /*block while full*/ + ret = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) ); if( ret ) - return ret; - } - ret = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) ); - if( ret ) - return 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 ); + Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL ); #endif - } - } while( framesAvailable == 0 && macStream->state != STOPPING ); + } + } while( framesAvailable == 0 && macStream->state != STOPPING ); - if( macStream->state == STOPPING ) - { - break; - } + if( macStream->state == STOPPING ) + { + break; + } - framesToTransfer = MIN( framesAvailable, framesRequested ); - framesTransferred = PaUtil_WriteRingBuffer( &blio->outputRingBuffer, (void *)cbuf, framesToTransfer ); - cbuf += framesTransferred * blio->outputSampleSizeActual * blio->outChan; - framesRequested -= framesTransferred; + framesToTransfer = MIN( framesAvailable, framesRequested ); + framesTransferred = PaUtil_WriteRingBuffer( &blio->outputRingBuffer, (void *)cbuf, framesToTransfer ); + cbuf += framesTransferred * blio->outputSampleSizeActual * blio->outChan; + framesRequested -= framesTransferred; #ifdef PA_MAC_BLIO_MUTEX - if( framesToTransfer == framesAvailable ) { - /* 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 ); - /* FIXME remove or review this code, does not fix race, ret not set! */ - if( ret ) + if( framesToTransfer == framesAvailable ) { + /* 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 ); + /* FIXME remove or review this code, does not fix race, ret not set! */ + if( ret ) + return ret; + } + } #endif } @@ -589,7 +591,7 @@ PaError WriteStream( PaStream* stream, * Wait until the data in the buffer has finished playing. */ PaError waitUntilBlioWriteBufferIsEmpty( PaMacBlio *blio, double sampleRate, - size_t framesPerBuffer ) + size_t framesPerBuffer ) { PaError result = paNoError; if( blio->outputRingBuffer.buffer ) { @@ -603,7 +605,7 @@ PaError waitUntilBlioWriteBufferIsEmpty( PaMacBlio *blio, double sampleRate, long msecPerBuffer = 1 + (long)( 1000.0 * framesPerBuffer / sampleRate); while( framesLeft > 0 && now < timeoutTime ) { VDBUG(( "waitUntilBlioWriteBufferIsFlushed: framesLeft = %d, framesPerBuffer = %ld\n", - framesLeft, framesPerBuffer )); + framesLeft, framesPerBuffer )); Pa_Sleep( msecPerBuffer ); framesLeft = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer ); now = PaUtil_GetTime(); @@ -634,4 +636,3 @@ signed long GetStreamWriteAvailable( PaStream* stream ) return PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer ); } - diff --git a/src/hostapi/coreaudio/pa_mac_core_blocking.h b/src/hostapi/coreaudio/pa_mac_core_blocking.h index c994f09..c0e564a 100644 --- a/src/hostapi/coreaudio/pa_mac_core_blocking.h +++ b/src/hostapi/coreaudio/pa_mac_core_blocking.h @@ -15,7 +15,7 @@ * 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 @@ -41,13 +41,13 @@ */ /* - * The text above constitutes the entire PortAudio license; however, + * 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 + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the * license above. */ @@ -112,12 +112,12 @@ PaMacBlio; */ PaError initializeBlioRingBuffers( - PaMacBlio *blio, - PaSampleFormat inputSampleFormat, - PaSampleFormat outputSampleFormat, - long ringBufferSizeInFrames, - int inChan, - int outChan ); + PaMacBlio *blio, + PaSampleFormat inputSampleFormat, + PaSampleFormat outputSampleFormat, + long ringBufferSizeInFrames, + int inChan, + int outChan ); PaError destroyBlioRingBuffers( PaMacBlio *blio ); PaError resetBlioRingBuffers( PaMacBlio *blio ); @@ -129,6 +129,6 @@ int BlioCallback( void *userData ); PaError waitUntilBlioWriteBufferIsEmpty( PaMacBlio *blio, double sampleRate, - size_t framesPerBuffer ); + size_t framesPerBuffer ); #endif /*PA_MAC_CORE_BLOCKING_H_*/ diff --git a/src/hostapi/coreaudio/pa_mac_core_internal.h b/src/hostapi/coreaudio/pa_mac_core_internal.h index 14e3d07..d4a97e0 100644 --- a/src/hostapi/coreaudio/pa_mac_core_internal.h +++ b/src/hostapi/coreaudio/pa_mac_core_internal.h @@ -15,7 +15,7 @@ * 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 @@ -41,13 +41,13 @@ */ /* - * The text above constitutes the entire PortAudio license; however, + * 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 + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the * license above. */ @@ -120,10 +120,10 @@ typedef struct PaMacCoreDeviceProperties UInt32 bufferFrameSize; // UInt32 streamLatency; // Seems to be the same as deviceLatency!? UInt32 deviceLatency; - /* Current device sample rate. May change! - These are initialized to the nominal device sample rate, - and updated with the actual sample rate, when/where available. - Note that these are the *device* sample rates, prior to any required + /* Current device sample rate. May change! + These are initialized to the nominal device sample rate, + and updated with the actual sample rate, when/where available. + Note that these are the *device* sample rates, prior to any required SR conversion. */ Float64 sampleRate; Float64 samplePeriod; // reciprocal @@ -158,36 +158,35 @@ typedef struct PaMacCoreStream /* FIXME: instead of volatile, these should be properly memory barriered */ volatile uint32_t xrunFlags; /*PaStreamCallbackFlags*/ volatile enum { - STOPPED = 0, /* playback is completely stopped, + STOPPED = 0, /* playback is completely stopped, and the user has called StopStream(). */ - CALLBACK_STOPPED = 1, /* callback has requested stop, + CALLBACK_STOPPED = 1, /* callback has requested stop, but user has not yet called StopStream(). */ - STOPPING = 2, /* The stream is in the process of closing + STOPPING = 2, /* The stream is in the process of closing because the user has called StopStream. This state is just used internally; externally it is indistinguishable from ACTIVE.*/ - ACTIVE = 3 /* The stream is active and running. */ + ACTIVE = 3 /* The stream is active and running. */ } state; double sampleRate; PaMacCoreDeviceProperties inputProperties; PaMacCoreDeviceProperties outputProperties; - - /* data updated by main thread and notifications, protected by timingInformationMutex */ - int timingInformationMutexIsInitialized; - pthread_mutex_t timingInformationMutex; + + /* data updated by main thread and notifications, protected by timingInformationMutex */ + int timingInformationMutexIsInitialized; + pthread_mutex_t timingInformationMutex; /* These are written by the PA thread or from CoreAudio callbacks. Protected by the mutex. */ Float64 timestampOffsetCombined; Float64 timestampOffsetInputDevice; Float64 timestampOffsetOutputDevice; - - /* Offsets in seconds to be applied to Apple timestamps to convert them to PA timestamps. + + /* Offsets in seconds to be applied to Apple timestamps to convert them to PA timestamps. * While the io proc is active, the following values are only accessed and manipulated by the ioproc */ Float64 timestampOffsetCombined_ioProcCopy; Float64 timestampOffsetInputDevice_ioProcCopy; Float64 timestampOffsetOutputDevice_ioProcCopy; - } PaMacCoreStream; diff --git a/src/hostapi/coreaudio/pa_mac_core_utilities.c b/src/hostapi/coreaudio/pa_mac_core_utilities.c index 5d93706..0d3b183 100644 --- a/src/hostapi/coreaudio/pa_mac_core_utilities.c +++ b/src/hostapi/coreaudio/pa_mac_core_utilities.c @@ -15,7 +15,7 @@ * 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 @@ -41,13 +41,13 @@ */ /* - * The text above constitutes the entire PortAudio license; however, + * 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 + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the * license above. */ @@ -64,43 +64,43 @@ #include OSStatus PaMacCore_AudioHardwareGetProperty( - AudioHardwarePropertyID inPropertyID, - UInt32* ioPropertyDataSize, - void* outPropertyData) + AudioHardwarePropertyID inPropertyID, + UInt32* ioPropertyDataSize, + void* outPropertyData ) { AudioObjectPropertyAddress address = { inPropertyID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; return AudioObjectGetPropertyData(kAudioObjectSystemObject, &address, 0, NULL, ioPropertyDataSize, outPropertyData); } OSStatus PaMacCore_AudioHardwareGetPropertySize( - AudioHardwarePropertyID inPropertyID, - UInt32* outSize) + AudioHardwarePropertyID inPropertyID, + UInt32* outSize ) { AudioObjectPropertyAddress address = { inPropertyID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; return AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &address, 0, NULL, outSize); } OSStatus PaMacCore_AudioDeviceGetProperty( - AudioDeviceID inDevice, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - UInt32* ioPropertyDataSize, - void* outPropertyData) + AudioDeviceID inDevice, + UInt32 inChannel, + Boolean isInput, + AudioDevicePropertyID inPropertyID, + UInt32* ioPropertyDataSize, + void* outPropertyData ) { - AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; - AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel }; - return AudioObjectGetPropertyData(inDevice, &address, 0, NULL, ioPropertyDataSize, outPropertyData); + AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; + AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel }; + return AudioObjectGetPropertyData(inDevice, &address, 0, NULL, ioPropertyDataSize, outPropertyData); } OSStatus PaMacCore_AudioDeviceSetProperty( - AudioDeviceID inDevice, - const AudioTimeStamp* inWhen, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - UInt32 inPropertyDataSize, - const void* inPropertyData) + AudioDeviceID inDevice, + const AudioTimeStamp* inWhen, + UInt32 inChannel, + Boolean isInput, + AudioDevicePropertyID inPropertyID, + UInt32 inPropertyDataSize, + const void* inPropertyData ) { AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel }; @@ -108,11 +108,11 @@ OSStatus PaMacCore_AudioDeviceSetProperty( } OSStatus PaMacCore_AudioDeviceGetPropertySize( - AudioDeviceID inDevice, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - UInt32* outSize) + AudioDeviceID inDevice, + UInt32 inChannel, + Boolean isInput, + AudioDevicePropertyID inPropertyID, + UInt32* outSize ) { AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel }; @@ -120,12 +120,12 @@ OSStatus PaMacCore_AudioDeviceGetPropertySize( } OSStatus PaMacCore_AudioDeviceAddPropertyListener( - AudioDeviceID inDevice, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - AudioObjectPropertyListenerProc inProc, - void* inClientData) + AudioDeviceID inDevice, + UInt32 inChannel, + Boolean isInput, + AudioDevicePropertyID inPropertyID, + AudioObjectPropertyListenerProc inProc, + void* inClientData ) { AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel }; @@ -133,12 +133,12 @@ OSStatus PaMacCore_AudioDeviceAddPropertyListener( } OSStatus PaMacCore_AudioDeviceRemovePropertyListener( - AudioDeviceID inDevice, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - AudioObjectPropertyListenerProc inProc, - void* inClientData) + AudioDeviceID inDevice, + UInt32 inChannel, + Boolean isInput, + AudioDevicePropertyID inPropertyID, + AudioObjectPropertyListenerProc inProc, + void* inClientData ) { AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel }; @@ -146,11 +146,11 @@ OSStatus PaMacCore_AudioDeviceRemovePropertyListener( } OSStatus PaMacCore_AudioStreamGetProperty( - AudioStreamID inStream, - UInt32 inChannel, - AudioDevicePropertyID inPropertyID, - UInt32* ioPropertyDataSize, - void* outPropertyData) + AudioStreamID inStream, + UInt32 inChannel, + AudioDevicePropertyID inPropertyID, + UInt32* ioPropertyDataSize, + void* outPropertyData ) { AudioObjectPropertyAddress address = { inPropertyID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; return AudioObjectGetPropertyData(inStream, &address, 0, NULL, ioPropertyDataSize, outPropertyData); @@ -158,28 +158,28 @@ OSStatus PaMacCore_AudioStreamGetProperty( PaError PaMacCore_SetUnixError( int err, int line ) { - PaError ret; - const char *errorText; + PaError ret; + const char *errorText; - if( err == 0 ) - { - return paNoError; - } + if( err == 0 ) + { + return paNoError; + } - ret = paNoError; - errorText = strerror( err ); + 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; + /** 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 ); + DBUG(("%d on line %d: msg='%s'\n", err, line, errorText)); + PaUtil_SetLastHostErrorInfo( paCoreAudio, err, errorText ); - return ret; + return ret; } /* @@ -190,97 +190,125 @@ 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 *errorType; const char *errorText; - + switch (error) { case kAudioHardwareNoError: return paNoError; case kAudioHardwareNotRunningError: errorText = "Audio Hardware Not Running"; - result = paInternalError; break; - case kAudioHardwareUnspecifiedError: + result = paInternalError; + break; + case kAudioHardwareUnspecifiedError: errorText = "Unspecified Audio Hardware Error"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioHardwareUnknownPropertyError: errorText = "Audio Hardware: Unknown Property"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioHardwareBadPropertySizeError: errorText = "Audio Hardware: Bad Property Size"; - result = paInternalError; break; - case kAudioHardwareIllegalOperationError: + result = paInternalError; + break; + case kAudioHardwareIllegalOperationError: errorText = "Audio Hardware: Illegal Operation"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioHardwareBadDeviceError: errorText = "Audio Hardware: Bad Device"; - result = paInvalidDevice; break; + result = paInvalidDevice; + break; case kAudioHardwareBadStreamError: errorText = "Audio Hardware: BadStream"; - result = paBadStreamPtr; break; + result = paBadStreamPtr; + break; case kAudioHardwareUnsupportedOperationError: errorText = "Audio Hardware: Unsupported Operation"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioDeviceUnsupportedFormatError: errorText = "Audio Device: Unsupported Format"; - result = paSampleFormatNotSupported; break; + result = paSampleFormatNotSupported; + break; case kAudioDevicePermissionsError: errorText = "Audio Device: Permissions Error"; - result = paDeviceUnavailable; break; + 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; + result = paInternalError; + break; case kAudioUnitErr_InvalidParameter: errorText = "Audio Unit: Invalid Parameter"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_NoConnection: errorText = "Audio Unit: No Connection"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_FailedInitialization: errorText = "Audio Unit: Initialization Failed"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_TooManyFramesToProcess: errorText = "Audio Unit: Too Many Frames"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_InvalidFile: errorText = "Audio Unit: Invalid File"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_UnknownFileType: errorText = "Audio Unit: Unknown File Type"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_FileNotSpecified: errorText = "Audio Unit: File Not Specified"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_FormatNotSupported: errorText = "Audio Unit: Format Not Supported"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_Uninitialized: errorText = "Audio Unit: Uninitialized"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_InvalidScope: errorText = "Audio Unit: Invalid Scope"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_PropertyNotWritable: errorText = "Audio Unit: PropertyNotWritable"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_InvalidPropertyValue: errorText = "Audio Unit: Invalid Property Value"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_PropertyNotInUse: errorText = "Audio Unit: Property Not In Use"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_Initialized: errorText = "Audio Unit: Initialized"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_InvalidOfflineRender: errorText = "Audio Unit: Invalid Offline Render"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_Unauthorized: errorText = "Audio Unit: Unauthorized"; - result = paInternalError; break; + result = paInternalError; + break; case kAudioUnitErr_CannotDoInCurrentContext: errorText = "Audio Unit: cannot do in current context"; - result = paInternalError; break; + result = paInternalError; + break; default: errorText = "Unknown Error"; result = paInternalError; @@ -325,60 +353,60 @@ PaError PaMacCore_SetError(OSStatus error, int line, int isError) * FEEDBACK: too liberal/conservative/another way? */ long computeRingBufferSize( const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, - long inputFramesPerBuffer, - long outputFramesPerBuffer, - double sampleRate ) + const PaStreamParameters *outputParameters, + long inputFramesPerBuffer, + long outputFramesPerBuffer, + double sampleRate ) { - long ringSize; - int index; - int i; - double latency ; - long framesPerBuffer ; - - VVDBUG(( "computeRingBufferSize()\n" )); - - assert( inputParameters || outputParameters ); - - if( outputParameters && inputParameters ) - { - latency = MAX( inputParameters->suggestedLatency, outputParameters->suggestedLatency ); - framesPerBuffer = MAX( inputFramesPerBuffer, outputFramesPerBuffer ); - } - else if( outputParameters ) - { - latency = outputParameters->suggestedLatency; - framesPerBuffer = outputFramesPerBuffer ; - } - else /* we have inputParameters */ - { - latency = inputParameters->suggestedLatency; - framesPerBuffer = inputFramesPerBuffer ; - } - - ringSize = (long) ( latency * sampleRate * 2 + .5); - VDBUG( ( "suggested latency : %d\n", (int) (latency*sampleRate) ) ); - if( ringSize < framesPerBuffer * 3 ) - ringSize = framesPerBuffer * 3 ; - VDBUG(("framesPerBuffer:%d\n",(int)framesPerBuffer)); - 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> 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; + long ringSize; + int index; + int i; + double latency ; + long framesPerBuffer ; + + VVDBUG(( "computeRingBufferSize()\n" )); + + assert( inputParameters || outputParameters ); + + if( outputParameters && inputParameters ) + { + latency = MAX( inputParameters->suggestedLatency, outputParameters->suggestedLatency ); + framesPerBuffer = MAX( inputFramesPerBuffer, outputFramesPerBuffer ); + } + else if( outputParameters ) + { + latency = outputParameters->suggestedLatency; + framesPerBuffer = outputFramesPerBuffer ; + } + else /* we have inputParameters */ + { + latency = inputParameters->suggestedLatency; + framesPerBuffer = inputFramesPerBuffer ; + } + + ringSize = (long) ( latency * sampleRate * 2 + .5); + VDBUG( ( "suggested latency : %d\n", (int) (latency*sampleRate) ) ); + if( ringSize < framesPerBuffer * 3 ) + ringSize = framesPerBuffer * 3 ; + VDBUG(("framesPerBuffer:%d\n",(int)framesPerBuffer)); + 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> 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; } @@ -395,16 +423,16 @@ long computeRingBufferSize( const PaStreamParameters *inputParameters, */ OSStatus propertyProc( - AudioObjectID inObjectID, - UInt32 inNumberAddresses, - const AudioObjectPropertyAddress* inAddresses, - void* inClientData) + AudioObjectID inObjectID, + UInt32 inNumberAddresses, + const AudioObjectPropertyAddress* inAddresses, + void* inClientData ) { - // this is where we would set the condition variable - return noErr; + // this is where we would set the condition variable + return noErr; } -/* sets the value of the given property and waits for the change to +/* 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 @@ -414,82 +442,82 @@ OSStatus propertyProc( outPropertyData is zeroed, which may or may not be useful in determining if the property was read. */ PaError AudioDeviceSetPropertyNowAndWaitForChange( - AudioDeviceID inDevice, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - UInt32 inPropertyDataSize, - const void *inPropertyData, - void *outPropertyData ) + AudioDeviceID inDevice, + UInt32 inChannel, + Boolean isInput, + AudioDevicePropertyID inPropertyID, + UInt32 inPropertyDataSize, + const void *inPropertyData, + void *outPropertyData ) { - OSStatus macErr; - UInt32 outPropertyDataSize = inPropertyDataSize; - - /* First, see if it already has that value. If so, return. */ - macErr = PaMacCore_AudioDeviceGetProperty( inDevice, inChannel, - isInput, inPropertyID, - &outPropertyDataSize, outPropertyData ); - if( macErr ) { - memset( outPropertyData, 0, inPropertyDataSize ); - goto failMac; - } - if( inPropertyDataSize!=outPropertyDataSize ) - return paInternalError; - if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) ) - return paNoError; - - /* Ideally, we'd use a condition variable to determine changes. - we could set that up here. */ - - /* If we were using a cond variable, we'd do something useful here, - but for now, this is just to make 10.6 happy. */ - macErr = PaMacCore_AudioDeviceAddPropertyListener( inDevice, inChannel, isInput, - inPropertyID, propertyProc, - NULL ); - if( macErr ) - /* we couldn't add a listener. */ - goto failMac; - - /* set property */ - macErr = PaMacCore_AudioDeviceSetProperty( inDevice, NULL, inChannel, - isInput, inPropertyID, - inPropertyDataSize, inPropertyData ); - if( macErr ) - goto failMac; - - /* busy-wait up to 30 seconds for the property to change */ - /* busy-wait is justified here only because the correct alternative (condition variable) - was hard to test, since most of the waiting ended up being for setting rather than - getting in OS X 10.5. This was not the case in earlier OS versions. */ - struct timeval tv1, tv2; - gettimeofday( &tv1, NULL ); - memcpy( &tv2, &tv1, sizeof( struct timeval ) ); - while( tv2.tv_sec - tv1.tv_sec < 30 ) { - /* now read the property back out */ - macErr = PaMacCore_AudioDeviceGetProperty( inDevice, inChannel, - isInput, inPropertyID, - &outPropertyDataSize, outPropertyData ); - if( macErr ) { - memset( outPropertyData, 0, inPropertyDataSize ); - goto failMac; - } - /* and compare... */ - if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) ) { - PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL); - return paNoError; - } - /* No match yet, so let's sleep and try again. */ - Pa_Sleep( 100 ); - gettimeofday( &tv2, NULL ); - } - DBUG( ("Timeout waiting for device setting.\n" ) ); - - PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL ); - return paNoError; - - failMac: - PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL ); - return ERR( macErr ); + OSStatus macErr; + UInt32 outPropertyDataSize = inPropertyDataSize; + + /* First, see if it already has that value. If so, return. */ + macErr = PaMacCore_AudioDeviceGetProperty( inDevice, inChannel, + isInput, inPropertyID, + &outPropertyDataSize, outPropertyData ); + if( macErr ) { + memset( outPropertyData, 0, inPropertyDataSize ); + goto failMac; + } + if( inPropertyDataSize!=outPropertyDataSize ) + return paInternalError; + if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) ) + return paNoError; + + /* Ideally, we'd use a condition variable to determine changes. + we could set that up here. */ + + /* If we were using a cond variable, we'd do something useful here, + but for now, this is just to make 10.6 happy. */ + macErr = PaMacCore_AudioDeviceAddPropertyListener( inDevice, inChannel, isInput, + inPropertyID, propertyProc, + NULL ); + if( macErr ) + /* we couldn't add a listener. */ + goto failMac; + + /* set property */ + macErr = PaMacCore_AudioDeviceSetProperty( inDevice, NULL, inChannel, + isInput, inPropertyID, + inPropertyDataSize, inPropertyData ); + if( macErr ) + goto failMac; + + /* busy-wait up to 30 seconds for the property to change */ + /* busy-wait is justified here only because the correct alternative (condition variable) + was hard to test, since most of the waiting ended up being for setting rather than + getting in OS X 10.5. This was not the case in earlier OS versions. */ + struct timeval tv1, tv2; + gettimeofday( &tv1, NULL ); + memcpy( &tv2, &tv1, sizeof( struct timeval ) ); + while( tv2.tv_sec - tv1.tv_sec < 30 ) { + /* now read the property back out */ + macErr = PaMacCore_AudioDeviceGetProperty( inDevice, inChannel, + isInput, inPropertyID, + &outPropertyDataSize, outPropertyData ); + if( macErr ) { + memset( outPropertyData, 0, inPropertyDataSize ); + goto failMac; + } + /* and compare... */ + if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) ) { + PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL); + return paNoError; + } + /* No match yet, so let's sleep and try again. */ + Pa_Sleep( 100 ); + gettimeofday( &tv2, NULL ); + } + DBUG( ("Timeout waiting for device setting.\n" ) ); + + PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL ); + return paNoError; + +failMac: + PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL ); + return ERR( macErr ); } /* @@ -506,93 +534,93 @@ PaError setBestSampleRateForDevice( const AudioDeviceID device, const bool requireExact, const Float64 desiredSrate ) { - 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",(long)device,(float)desiredSrate)); - - /* -- try setting the sample rate -- */ - srate = 0; - err = AudioDeviceSetPropertyNowAndWaitForChange( - device, 0, isInput, - kAudioDevicePropertyNominalSampleRate, - propsize, &desiredSrate, &srate ); - - /* -- if the rate agrees, and was changed, we are done -- */ - if( srate != 0 && srate == desiredSrate ) - return paNoError; - /* -- 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 = PaMacCore_AudioDeviceGetPropertySize( device, 0, isInput, - kAudioDevicePropertyAvailableNominalSampleRates, - &propsize ); - if( err ) - return ERR( err ); - ranges = (AudioValueRange *)calloc( 1, propsize ); - if( !ranges ) - return paInsufficientMemory; - err = PaMacCore_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))); + 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",(long)device,(float)desiredSrate)); + + /* -- try setting the sample rate -- */ + srate = 0; + err = AudioDeviceSetPropertyNowAndWaitForChange( + device, 0, isInput, + kAudioDevicePropertyNominalSampleRate, + propsize, &desiredSrate, &srate ); + + /* -- if the rate agrees, and was changed, we are done -- */ + if( srate != 0 && srate == desiredSrate ) + return paNoError; + /* -- 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 = PaMacCore_AudioDeviceGetPropertySize( device, 0, isInput, + kAudioDevicePropertyAvailableNominalSampleRates, + &propsize ); + if( err ) + return ERR( err ); + ranges = (AudioValueRange *)calloc( 1, propsize ); + if( !ranges ) + return paInsufficientMemory; + err = PaMacCore_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 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 ); - srate = 0; - err = AudioDeviceSetPropertyNowAndWaitForChange( - device, 0, isInput, - kAudioDevicePropertyNominalSampleRate, - propsize, &best, &srate ); - - /* -- if the set rate matches, we are done -- */ - if( srate != 0 && srate == best ) - return paNoError; - - if( err ) - return ERR( err ); - - /* -- otherwise, something weird happened: we didn't set the rate, and we got no errors. Just bail. */ - return paInternalError; + VDBUG(("-----\n")); + + /* -- now pick the best available sample rate -- */ + for( i=0; i 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 ); + srate = 0; + err = AudioDeviceSetPropertyNowAndWaitForChange( + device, 0, isInput, + kAudioDevicePropertyNominalSampleRate, + propsize, &best, &srate ); + + /* -- if the set rate matches, we are done -- */ + if( srate != 0 && srate == best ) + return paNoError; + + if( err ) + return ERR( err ); + + /* -- otherwise, something weird happened: we didn't set the rate, and we got no errors. Just bail. */ + return paInternalError; } @@ -607,7 +635,7 @@ PaError setBestSampleRateForDevice( const AudioDeviceID device, */ PaError setBestFramesPerBuffer( const AudioDeviceID device, const bool isOutput, - UInt32 requestedFramesPerBuffer, + UInt32 requestedFramesPerBuffer, UInt32 *actualFramesPerBuffer ) { UInt32 afpb; @@ -623,11 +651,11 @@ PaError setBestFramesPerBuffer( const AudioDeviceID device, /* -- try and set exact FPB -- */ err = PaMacCore_AudioDeviceSetProperty( device, NULL, 0, isInput, - kAudioDevicePropertyBufferFrameSize, - propsize, &requestedFramesPerBuffer); + kAudioDevicePropertyBufferFrameSize, + propsize, &requestedFramesPerBuffer); err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput, - kAudioDevicePropertyBufferFrameSize, - &propsize, actualFramesPerBuffer); + kAudioDevicePropertyBufferFrameSize, + &propsize, actualFramesPerBuffer); if( err ) { return ERR( err ); @@ -637,15 +665,15 @@ PaError setBestFramesPerBuffer( const AudioDeviceID device, { return paNoError; /* we are done */ } - + // Clip requested value against legal range for the device. propsize = sizeof(AudioValueRange); err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput, - kAudioDevicePropertyBufferFrameSizeRange, - &propsize, &range ); + kAudioDevicePropertyBufferFrameSizeRange, + &propsize, &range ); if( err ) { - return ERR( err ); + return ERR( err ); } if( requestedFramesPerBuffer < range.mMinimum ) { @@ -655,21 +683,21 @@ PaError setBestFramesPerBuffer( const AudioDeviceID device, { requestedFramesPerBuffer = range.mMaximum; } - - /* --- set the buffer size (ignore errors) -- */ + + /* --- set the buffer size (ignore errors) -- */ propsize = sizeof( UInt32 ); - err = PaMacCore_AudioDeviceSetProperty( device, NULL, 0, isInput, - kAudioDevicePropertyBufferFrameSize, - propsize, &requestedFramesPerBuffer ); - /* --- read the property to check that it was set -- */ - err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput, - kAudioDevicePropertyBufferFrameSize, - &propsize, actualFramesPerBuffer ); - - if( err ) - return ERR( err ); - - return paNoError; + err = PaMacCore_AudioDeviceSetProperty( device, NULL, 0, isInput, + kAudioDevicePropertyBufferFrameSize, + propsize, &requestedFramesPerBuffer ); + /* --- read the property to check that it was set -- */ + err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput, + kAudioDevicePropertyBufferFrameSize, + &propsize, actualFramesPerBuffer ); + + if( err ) + return ERR( err ); + + return paNoError; } /********************** @@ -679,8 +707,8 @@ PaError setBestFramesPerBuffer( const AudioDeviceID device, **********************/ struct PaMacXRunListNode_s { - PaMacCoreStream *stream; - struct PaMacXRunListNode_s *next; + PaMacCoreStream *stream; + struct PaMacXRunListNode_s *next; } ; typedef struct PaMacXRunListNode_s PaMacXRunListNode; @@ -697,91 +725,90 @@ OSStatus xrunCallback( const AudioObjectPropertyAddress* inAddresses, void * inClientData) { - PaMacXRunListNode *node = (PaMacXRunListNode *) inClientData; - bool isInput = inAddresses->mScope == kAudioDevicePropertyScopeInput; + PaMacXRunListNode *node = (PaMacXRunListNode *) inClientData; + bool isInput = inAddresses->mScope == kAudioDevicePropertyScopeInput; - int ret = pthread_mutex_trylock( &xrunMutex ) ; + int ret = pthread_mutex_trylock( &xrunMutex ) ; - if( ret == 0 ) { + if( ret == 0 ) { - node = node->next ; //skip the first node + node = node->next ; //skip the first node - for( ; node; node=node->next ) { - PaMacCoreStream *stream = node->stream; + for( ; node; node=node->next ) { + PaMacCoreStream *stream = node->stream; - if( stream->state != ACTIVE ) - continue; //if the stream isn't active, we don't care if the device is dropping + if( stream->state != ACTIVE ) + continue; //if the stream isn't active, we don't care if the device is dropping - if( isInput ) { - if( stream->inputDevice == inDevice ) - OSAtomicOr32( paInputOverflow, &stream->xrunFlags ); - } else { - if( stream->outputDevice == inDevice ) - OSAtomicOr32( paOutputUnderflow, &stream->xrunFlags ); - } - } + if( isInput ) { + if( stream->inputDevice == inDevice ) + OSAtomicOr32( paInputOverflow, &stream->xrunFlags ); + } else { + if( stream->outputDevice == inDevice ) + OSAtomicOr32( paOutputUnderflow, &stream->xrunFlags ); + } + } - pthread_mutex_unlock( &xrunMutex ); - } + pthread_mutex_unlock( &xrunMutex ); + } - return 0; + return 0; } int initializeXRunListenerList( void ) { - xRunListSize = 0; - bzero( (void *) &firstXRunListNode, sizeof(firstXRunListNode) ); - return pthread_mutex_init( &xrunMutex, NULL ); + xRunListSize = 0; + bzero( (void *) &firstXRunListNode, sizeof(firstXRunListNode) ); + return pthread_mutex_init( &xrunMutex, NULL ); } int destroyXRunListenerList( void ) { - PaMacXRunListNode *node; - node = firstXRunListNode.next; - while( node ) { - PaMacXRunListNode *tmp = node; - node = node->next; - free( tmp ); - } - xRunListSize = 0; - return pthread_mutex_destroy( &xrunMutex ); + PaMacXRunListNode *node; + node = firstXRunListNode.next; + while( node ) { + PaMacXRunListNode *tmp = node; + node = node->next; + free( tmp ); + } + xRunListSize = 0; + return pthread_mutex_destroy( &xrunMutex ); } void *addToXRunListenerList( void *stream ) { - pthread_mutex_lock( &xrunMutex ); - PaMacXRunListNode *newNode; - // setup new node: - newNode = (PaMacXRunListNode *) malloc( sizeof( PaMacXRunListNode ) ); - newNode->stream = (PaMacCoreStream *) stream; - newNode->next = firstXRunListNode.next; - // insert: - firstXRunListNode.next = newNode; - pthread_mutex_unlock( &xrunMutex ); - - return &firstXRunListNode; + pthread_mutex_lock( &xrunMutex ); + PaMacXRunListNode *newNode; + // setup new node: + newNode = (PaMacXRunListNode *) malloc( sizeof( PaMacXRunListNode ) ); + newNode->stream = (PaMacCoreStream *) stream; + newNode->next = firstXRunListNode.next; + // insert: + firstXRunListNode.next = newNode; + pthread_mutex_unlock( &xrunMutex ); + + return &firstXRunListNode; } int removeFromXRunListenerList( void *stream ) { - pthread_mutex_lock( &xrunMutex ); - PaMacXRunListNode *node, *prev; - prev = &firstXRunListNode; - node = firstXRunListNode.next; - while( node ) { - if( node->stream == stream ) { - //found it: - --xRunListSize; - prev->next = node->next; - free( node ); - pthread_mutex_unlock( &xrunMutex ); - return xRunListSize; - } - prev = prev->next; - node = node->next; - } - - pthread_mutex_unlock( &xrunMutex ); - // failure - return xRunListSize; -} + pthread_mutex_lock( &xrunMutex ); + PaMacXRunListNode *node, *prev; + prev = &firstXRunListNode; + node = firstXRunListNode.next; + while( node ) { + if( node->stream == stream ) { + //found it: + --xRunListSize; + prev->next = node->next; + free( node ); + pthread_mutex_unlock( &xrunMutex ); + return xRunListSize; + } + prev = prev->next; + node = node->next; + } + pthread_mutex_unlock( &xrunMutex ); + // failure + return xRunListSize; +} diff --git a/src/hostapi/coreaudio/pa_mac_core_utilities.h b/src/hostapi/coreaudio/pa_mac_core_utilities.h index 091ee65..c305f17 100644 --- a/src/hostapi/coreaudio/pa_mac_core_utilities.h +++ b/src/hostapi/coreaudio/pa_mac_core_utilities.h @@ -15,7 +15,7 @@ * 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 @@ -41,13 +41,13 @@ */ /* - * The text above constitutes the entire PortAudio license; however, + * 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 + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the * license above. */ @@ -73,7 +73,7 @@ #define MAX(a, b) (((a)<(b))?(b):(a)) #endif -#define ERR(mac_error) PaMacCore_SetError(mac_error, __LINE__, 1 ) +#define ERR(mac_error) PaMacCore_SetError(mac_error, __LINE__, 1 ) #define WARNING(mac_error) PaMacCore_SetError(mac_error, __LINE__, 0 ) @@ -114,11 +114,11 @@ OSStatus PaMacCore_AudioHardwareGetProperty( AudioHardwarePropertyID inPropertyID, UInt32* ioPropertyDataSize, - void* outPropertyData); + void* outPropertyData ); OSStatus PaMacCore_AudioHardwareGetPropertySize( AudioHardwarePropertyID inPropertyID, - UInt32* outSize); + UInt32* outSize ); OSStatus PaMacCore_AudioDeviceGetProperty( AudioDeviceID inDevice, @@ -126,7 +126,7 @@ OSStatus PaMacCore_AudioDeviceGetProperty( Boolean isInput, AudioDevicePropertyID inPropertyID, UInt32* ioPropertyDataSize, - void* outPropertyData); + void* outPropertyData ); OSStatus PaMacCore_AudioDeviceSetProperty( AudioDeviceID inDevice, @@ -135,14 +135,14 @@ OSStatus PaMacCore_AudioDeviceSetProperty( Boolean isInput, AudioDevicePropertyID inPropertyID, UInt32 inPropertyDataSize, - const void* inPropertyData); + const void* inPropertyData ); OSStatus PaMacCore_AudioDeviceGetPropertySize( AudioDeviceID inDevice, UInt32 inChannel, Boolean isInput, AudioDevicePropertyID inPropertyID, - UInt32* outSize); + UInt32* outSize ); OSStatus PaMacCore_AudioDeviceAddPropertyListener( AudioDeviceID inDevice, @@ -150,7 +150,7 @@ OSStatus PaMacCore_AudioDeviceAddPropertyListener( Boolean isInput, AudioDevicePropertyID inPropertyID, AudioObjectPropertyListenerProc inProc, - void* inClientData); + void* inClientData ); OSStatus PaMacCore_AudioDeviceRemovePropertyListener( AudioDeviceID inDevice, @@ -158,14 +158,14 @@ OSStatus PaMacCore_AudioDeviceRemovePropertyListener( Boolean isInput, AudioDevicePropertyID inPropertyID, AudioObjectPropertyListenerProc inProc, - void* inClientData); + void* inClientData ); OSStatus PaMacCore_AudioStreamGetProperty( AudioStreamID inStream, UInt32 inChannel, AudioDevicePropertyID inPropertyID, UInt32* ioPropertyDataSize, - void* outPropertyData); + void* outPropertyData ); #define UNIX_ERR(err) PaMacCore_SetUnixError( err, __LINE__ ) @@ -190,30 +190,30 @@ PaError PaMacCore_SetError(OSStatus error, int line, int isError); * */ long computeRingBufferSize( const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, - long inputFramesPerBuffer, - long outputFramesPerBuffer, - double sampleRate ); + const PaStreamParameters *outputParameters, + long inputFramesPerBuffer, + long outputFramesPerBuffer, + double sampleRate ); OSStatus propertyProc( - AudioObjectID inObjectID, - UInt32 inNumberAddresses, - const AudioObjectPropertyAddress* inAddresses, - void* inClientData); + AudioObjectID inObjectID, + UInt32 inNumberAddresses, + const AudioObjectPropertyAddress* inAddresses, + void* inClientData ); -/* sets the value of the given property and waits for the change to +/* 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 ); + AudioDeviceID inDevice, + UInt32 inChannel, + Boolean isInput, + AudioDevicePropertyID inPropertyID, + UInt32 inPropertyDataSize, + const void *inPropertyData, + void *outPropertyData ); /* * Sets the sample rate the HAL device. @@ -239,7 +239,7 @@ PaError setBestSampleRateForDevice( const AudioDeviceID device, */ PaError setBestFramesPerBuffer( const AudioDeviceID device, const bool isOutput, - UInt32 requestedFramesPerBuffer, + UInt32 requestedFramesPerBuffer, UInt32 *actualFramesPerBuffer ); @@ -250,10 +250,10 @@ PaError setBestFramesPerBuffer( const AudioDeviceID device, *********************/ OSStatus xrunCallback( - AudioObjectID inObjectID, - UInt32 inNumberAddresses, - const AudioObjectPropertyAddress* inAddresses, - void * inClientData ); + AudioObjectID inObjectID, + UInt32 inNumberAddresses, + const AudioObjectPropertyAddress* inAddresses, + void * inClientData ); /** returns zero on success or a unix style error code. */ int initializeXRunListenerList( void ); -- 2.43.0