diff options
author | sanine <sanine.not@pm.me> | 2022-08-27 23:52:56 -0500 |
---|---|---|
committer | sanine <sanine.not@pm.me> | 2022-08-27 23:52:56 -0500 |
commit | a4dd0ad63c00f4dee3b86dfd3075d1d61b2b3180 (patch) | |
tree | 13bd5bfa15e6fea2a12f176bae79adf9c6fd0933 /portaudio/src/hostapi/coreaudio | |
parent | bde3e4f1bb7b8f8abca0884a7d994ee1c17a66b1 (diff) |
add plibsys
Diffstat (limited to 'portaudio/src/hostapi/coreaudio')
-rw-r--r-- | portaudio/src/hostapi/coreaudio/notes.txt | 196 | ||||
-rw-r--r-- | portaudio/src/hostapi/coreaudio/pa_mac_core.c | 2878 | ||||
-rw-r--r-- | portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c | 638 | ||||
-rw-r--r-- | portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h | 134 | ||||
-rw-r--r-- | portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h | 193 | ||||
-rw-r--r-- | portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c | 814 | ||||
-rw-r--r-- | portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h | 268 |
7 files changed, 0 insertions, 5121 deletions
diff --git a/portaudio/src/hostapi/coreaudio/notes.txt b/portaudio/src/hostapi/coreaudio/notes.txt deleted file mode 100644 index 281cf01..0000000 --- a/portaudio/src/hostapi/coreaudio/notes.txt +++ /dev/null @@ -1,196 +0,0 @@ -Notes on status of CoreAudio Implementation of PortAudio - -Document Last Updated December 9, 2005 - -There are currently two implementations of PortAudio for Mac Core Audio. - -The original is in pa_mac_core_old.c, and the newer, default implementation -is in pa_mac_core.c. -Only pa_mac_core.c is currently developed and supported as it uses apple's -current core audio technology. To select use the old implementation, replace -pa_mac_core.c with pa_mac_core_old.c (eg. "cp pa_mac_core_auhal.c -pa_mac_core.c"), then run configure and make as usual. - -------------------------------------------- - -Notes on Newer/Default AUHAL implementation: - -by Bjorn Roche - -Last Updated December 9, 2005 - -Principle of Operation: - -This implementation uses AUHAL for audio I/O. To some extent, it also -operates at the "HAL" Layer, though this behavior can be limited by -platform specific flags (see pa_mac_core.h for details). The default -settings should be reasonable: they don't change the SR of the device and -don't cause interruptions if other devices are using the device. - -Major Software Elements Used: Apple's HAL AUs provide output SR -conversion transparently, however, only on output, so this -implementation uses AudioConverters to convert the sample rate on input. -A PortAudio ring buffer is used to buffer input when sample rate -conversion is required or when separate audio units are used for duplex -IO. Finally, a PortAudio buffer processor is used to convert formats and -provide additional buffers if needed. Internally, interleaved floating -point data streams are used exclusively - the audio unit converts from -the audio hardware's native format to interleaved float PCM and -PortAudio's Buffer processor is used for conversion to user formats. - -Simplex Input: Simplex input uses a single callback. If sample rate -conversion is required, a ring buffer and AudioConverter are used as -well. - -Simplex output: Simplex output uses a single callback. No ring buffer or -audio converter is used because AUHAL does its own output SR conversion. - -Duplex, one device (no SR conversion): When one device is used, a single -callback is used. This achieves very low latency. - -Duplex, separate devices or SR conversion: When SR conversion is -required, data must be buffered before it is converted and data is not -always available at the same times on input and output, so SR conversion -requires the same treatment as separate devices. The input callback -reads data and puts it in the ring buffer. The output callback reads the -data off the ring buffer, into an audio converter and finally to the -buffer processor. - -Platform Specific Options: - -By using the flags in pa_mac_core.h, the user may specify several options. -For example, the user can specify the sample-rate conversion quality, and -the extent to which PA will attempt to "play nice" and to what extent it -will interrupt other apps to improve performance. For example, if 44100 Hz -sample rate is requested but the device is set at 48000 Hz, PA can either -change the device for optimal playback ("Pro" mode), which may interrupt -other programs playing back audio, or simple use a sample-rate conversion, -which allows for friendlier sharing of the device ("Play Nice" mode). - -Additionally, the user may define a "channel mapping" by calling -paSetupMacCoreChannelMap() on their stream info structure before opening -the stream with it. See below for creating a channel map. - -Known issues: - -- Buffering: No buffering beyond that provided by core audio is provided -except where absolutely needed for the implementation to work. This may cause -issues with large framesPerBuffer settings and it also means that no additional -latency will be provided even if a large latency setting is selected. - -- Latency: Latency settings are generally ignored. They may be used as a -hint for buffer size in paHostFramesPerBufferUnspecified, or the value may -be used in cases where additional buffering is needed, such as doing input and -output on separate devices. Latency settings are always automatically bound -to "safe" values, however, so setting extreme values here should not be -an issue. - -- Buffer Size: paHostFramesPerBufferUnspecified and specific host buffer sizes -are supported. paHostFramesPerBufferUnspecified works best in "pro" mode, -where the buffer size and sample rate of the audio device is most likely -to match the expected values. In the case of paHostFramesPerBuffer, an -appropriate framesPerBuffer value will be used that guarantees minimum -requested latency if that's possible. - -- Timing info. It reports on stream time, but I'm probably doing something -wrong since patest_sine_time often reports negative latency numbers. Also, -there are currently issues with some devices whehn plugging/unplugging -devices. - -- xrun detection: The only xrun detection performed is when reading -and writing the ring buffer. There is probably more that can be done. - -- abort/stop issues: stopping a stream is always a complete operation, -but latency should be low enough to make the lack of a separate abort -unnecessary. Apple clarifies its AudioOutputUnitStop() call here: -http://lists.apple.com/archives/coreaudio-api/2005/Dec/msg00055.html - -- blocking interface: should work fine. - -- multichannel: It has been tested successfully on multichannel hardware -from MOTU: traveler and 896HD. Also Presonus firepod and others. It is -believed to work with all Core Audio devices, including virtual devices -such as soundflower. - -- sample rate conversion quality: By default, SR conversion is the maximum -available. This can be tweaked using flags pa_mac_core.h. Note that the AU -render quyality property is used to set the sample rate conversion quality -as "documented" here: -http://lists.apple.com/archives/coreaudio-api/2004/Jan/msg00141.html - -- x86/Universal Binary: Universal binaries can be build. - - - -Creating a channel map: - -How to create the map array - Text taken From AUHAL.rtfd : -[3] Channel Maps -Clients can tell the AUHAL units which channels of the device they are interested in. For example, the client may be processing stereo data, but outputting to a six-channel device. This is done by using the kAudioOutputUnitProperty_ChannelMap property. To use this property: - -For Output: -Create an array of SInt32 that is the size of the number of channels of the device (Get the Format of the AUHAL's output Element == 0) -Initialize each of the array's values to -1 (-1 indicates that that channel is NOT to be presented in the conversion.) - -Next, for each channel of your app's output, set: -channelMapArray[deviceOutputChannel] = desiredAppOutputChannel. - -For example: we have a 6 channel output device and our application has a stereo source it wants to provide to the device. Suppose we want that stereo source to go to the 3rd and 4th channels of the device. The channel map would look like this: { -1, -1, 0, 1, -1, -1 } - -Where the formats are: -Input Element == 0: 2 channels (- client format - settable) -Output Element == 0: 6 channels (- device format - NOT settable) - -So channel 2 (zero-based) of the device will take the first channel of output and channel 3 will take the second channel of output. (This translates to the 3rd and 4th plugs of the 6 output plugs of the device of course!) - -For Input: -Create an array of SInt32 that is the size of the number of channels of the format you require for input. Get (or Set in this case as needed) the AUHAL's output Element == 1. - -Next, for each channel of input you require, set: -channelMapArray[desiredAppInputChannel] = deviceOutputChannel; - -For example: we have a 6 channel input device from which we wish to receive stereo input from the 3rd and 4th channels. The channel map looks like this: { 2, 3 } - -Where the formats are: -Input Element == 0: 2 channels (- device format - NOT settable) -Output Element == 0: 6 channels (- client format - settable) - - - ----------------------------------------- - -Notes on Original implementation: - -by Phil Burk and Darren Gibbs - -Last updated March 20, 2002 - -WHAT WORKS - -Output with very low latency, <10 msec. -Half duplex input or output. -Full duplex on the same CoreAudio device. -The paFLoat32, paInt16, paInt8, paUInt8 sample formats. -Pa_GetCPULoad() -Pa_StreamTime() - -KNOWN BUGS OR LIMITATIONS - -We do not yet support simultaneous input and output on different -devices. Note that some CoreAudio devices like the Roland UH30 look -like one device but are actually two different CoreAudio devices. The -Built-In audio is typically one CoreAudio device. - -Mono doesn't work. - -DEVICE MAPPING - -CoreAudio devices can support both input and output. But the sample -rates supported may be different. So we have map one or two PortAudio -device to each CoreAudio device depending on whether it supports -input, output or both. - -When we query devices, we first get a list of CoreAudio devices. Then -we scan the list and add a PortAudio device for each CoreAudio device -that supports input. Then we make a scan for output devices. - diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core.c b/portaudio/src/hostapi/coreaudio/pa_mac_core.c deleted file mode 100644 index 26b814c..0000000 --- a/portaudio/src/hostapi/coreaudio/pa_mac_core.c +++ /dev/null @@ -1,2878 +0,0 @@ -/* - * Implementation of the PortAudio API for Apple AUHAL - * - * PortAudio Portable Real-Time Audio Library - * Latest Version at: http://www.portaudio.com - * - * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code. - * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation) - * - * Dominic's code was based on code by Phil Burk, Darren Gibbs, - * Gord Peters, Stephane Letz, and Greg Pfiel. - * - * The following people also deserve acknowledgements: - * - * Olivier Tristan for feedback and testing - * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O - * interface. - * - * - * Based on the Open Source API proposed by Ross Bencina - * Copyright (c) 1999-2002 Ross Bencina, Phil Burk - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files - * (the "Software"), to deal in the Software without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -/* - * The text above constitutes the entire PortAudio license; however, - * the PortAudio community also makes the following non-binding requests: - * - * Any person wishing to distribute modifications to the Software is - * requested to send the modifications to the original developer so that - * they can be incorporated into the canonical version. It is also - * requested that these non-binding requests be included along with the - * license above. - */ - -/** - @file pa_mac_core - @ingroup hostapi_src - @author Bjorn Roche - @brief AUHAL implementation of PortAudio -*/ - -/* FIXME: not all error conditions call PaUtil_SetLastHostErrorInfo() - * PaMacCore_SetError() will do this. - */ - -#include "pa_mac_core_internal.h" - -#include <string.h> /* strlen(), memcmp() etc. */ -#include <libkern/OSAtomic.h> - -#include "pa_mac_core.h" -#include "pa_mac_core_utilities.h" -#include "pa_mac_core_blocking.h" - -#ifndef MAC_OS_X_VERSION_10_6 -#define MAC_OS_X_VERSION_10_6 1060 -#endif - - -#ifdef __cplusplus -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 ); - -/* - * Function declared in pa_mac_core.h. Sets up a PaMacCoreStreamInfoStruct - * with the requested flags and initializes channel map. - */ -void PaMacCore_SetupStreamInfo( PaMacCoreStreamInfo *data, const unsigned long flags ) -{ - bzero( data, sizeof( PaMacCoreStreamInfo ) ); - data->size = sizeof( PaMacCoreStreamInfo ); - data->hostApiType = paCoreAudio; - data->version = 0x01; - data->flags = flags; - data->channelMap = NULL; - data->channelMapSize = 0; -} - -/* - * Function declared in pa_mac_core.h. Adds channel mapping to a PaMacCoreStreamInfoStruct - */ -void PaMacCore_SetupChannelMap( PaMacCoreStreamInfo *data, const SInt32 * const channelMap, const unsigned long channelMapSize ) -{ - data->channelMap = channelMap; - data->channelMapSize = channelMapSize; -} -static char *channelName = NULL; -static int channelNameSize = 0; -static bool ensureChannelNameSize( int size ) -{ - if( size >= channelNameSize ) { - free( channelName ); - channelName = (char *) malloc( ( channelNameSize = size ) + 1 ); - if( !channelName ) { - channelNameSize = 0; - return false; - } - } - return true; -} -/* - * Function declared in pa_mac_core.h. 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; -} - - -PaError PaMacCore_GetBufferSizeRange( PaDeviceIndex device, - long *minBufferSizeFrames, long *maxBufferSizeFrames ) -{ - PaError result; - PaUtilHostApiRepresentation *hostApi; - - result = PaUtil_GetHostApiRepresentation( &hostApi, paCoreAudio ); - - if( result == paNoError ) - { - PaDeviceIndex hostApiDeviceIndex; - result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDeviceIndex, device, hostApi ); - if( result == paNoError ) - { - PaMacAUHAL *macCoreHostApi = (PaMacAUHAL*)hostApi; - 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 ) - isInput = 1; - - result = WARNING(PaMacCore_AudioDeviceGetProperty( macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &audioRange ) ); - - *minBufferSizeFrames = audioRange.mMinimum; - *maxBufferSizeFrames = audioRange.mMaximum; - } - } - - return result; -} - - -AudioDeviceID PaMacCore_GetStreamInputDevice( PaStream* s ) -{ - PaMacCoreStream *stream = (PaMacCoreStream*)s; - VVDBUG(("PaMacCore_GetStreamInputHandle()\n")); - - return ( stream->inputDevice ); -} - -AudioDeviceID PaMacCore_GetStreamOutputDevice( PaStream* s ) -{ - PaMacCoreStream *stream = (PaMacCoreStream*)s; - VVDBUG(("PaMacCore_GetStreamOutputHandle()\n")); - - return ( stream->outputDevice ); -} - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#define RING_BUFFER_ADVANCE_DENOMINATOR (4) - -static void Terminate( struct PaUtilHostApiRepresentation *hostApi ); -static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, - const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, - double sampleRate ); -static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, - PaStream** s, - const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, - double sampleRate, - unsigned long framesPerBuffer, - PaStreamFlags streamFlags, - PaStreamCallback *streamCallback, - void *userData ); -static PaError CloseStream( PaStream* stream ); -static PaError StartStream( PaStream *stream ); -static PaError StopStream( PaStream *stream ); -static PaError AbortStream( PaStream *stream ); -static PaError IsStreamStopped( PaStream *s ); -static PaError IsStreamActive( PaStream *stream ); -static PaTime GetStreamTime( PaStream *stream ); -static OSStatus AudioIOProc( void *inRefCon, - AudioUnitRenderActionFlags *ioActionFlags, - const AudioTimeStamp *inTimeStamp, - UInt32 inBusNumber, - UInt32 inNumberFrames, - AudioBufferList *ioData ); -static double GetStreamCpuLoad( PaStream* stream ); - -static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi, - PaDeviceInfo *deviceInfo, - AudioDeviceID macCoreDeviceId, - int isInput); - -static PaError OpenAndSetupOneAudioUnit( const 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 ) \ - PaUtil_SetLastHostErrorInfo( paCoreAudio, errorCode, errorText ) - -/* - * Callback called when starting or stopping a stream. - */ -static void startStopCallback( - 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 ); -} - - -/*currently, this is only used in initialization, but it might be modified - to be used when the list of devices changes.*/ -static PaError gatherDeviceInfo(PaMacAUHAL *auhalHostApi) -{ - UInt32 size; - UInt32 propsize; - VVDBUG(("gatherDeviceInfo()\n")); - /* -- free any previous allocations -- */ - if( auhalHostApi->devIds ) - PaUtil_GroupFreeMemory(auhalHostApi->allocations, auhalHostApi->devIds); - auhalHostApi->devIds = NULL; - - /* -- figure out how many devices there are -- */ - PaMacCore_AudioHardwareGetPropertySize( kAudioHardwarePropertyDevices, - &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 ); - if( !auhalHostApi->devIds ) - return paInsufficientMemory; - PaMacCore_AudioHardwareGetProperty( kAudioHardwarePropertyDevices, - &propsize, - auhalHostApi->devIds ); -#ifdef MAC_CORE_VERBOSE_DEBUG - { - int i; - for( i=0; i<auhalHostApi->devCount; ++i ) - printf( "Device %d\t: %ld\n", i, (long)auhalHostApi->devIds[i] ); - } -#endif - - size = sizeof(AudioDeviceID); - auhalHostApi->defaultIn = kAudioDeviceUnknown; - auhalHostApi->defaultOut = kAudioDeviceUnknown; - - /* determine the default device. */ - /* I am not sure how these calls to AudioHardwareGetProperty() - could fail, but in case they do, we use the first available - device as the default. */ - if( 0 != 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; i<auhalHostApi->devCount; ++i ) { - PaDeviceInfo devInfo; - if( 0 != GetChannelInfo( auhalHostApi, &devInfo, - auhalHostApi->devIds[i], TRUE ) ) - if( devInfo.maxInputChannels ) { - auhalHostApi->defaultIn = auhalHostApi->devIds[i]; - break; - } - } - } - if( 0 != 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; i<auhalHostApi->devCount; ++i ) { - PaDeviceInfo devInfo; - if( 0 != GetChannelInfo( auhalHostApi, &devInfo, - auhalHostApi->devIds[i], FALSE ) ) - if( devInfo.maxOutputChannels ) { - auhalHostApi->defaultOut = auhalHostApi->devIds[i]; - break; - } - } - } - - VDBUG( ( "Default in : %ld\n", (long)auhalHostApi->defaultIn ) ); - VDBUG( ( "Default out: %ld\n", (long)auhalHostApi->defaultOut ) ); - - return paNoError; -} - -/* =================================================================================================== */ -/** - * @internal - * @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 ) -{ - 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 ) -{ - PaError err; - int i; - UInt32 propSize; - UInt32 deviceLatency; - UInt32 streamLatency; - UInt32 bufferFrames; - UInt32 safetyOffset; - AudioStreamID streamIDs[128]; - - 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])); - int numStreams = propSize / sizeof(AudioStreamID); - for( i=0; i<numStreams; i++ ) - { - printf("Stream #%d = %d---------------------- \n", i, streamIDs[i] ); - - propSize = sizeof(UInt32); - err = WARNING(PaMacCore_AudioStreamGetProperty(streamIDs[i], 0, kAudioStreamPropertyLatency, &propSize, &streamLatency)); - printf(" kAudioStreamPropertyLatency: err = %d, propSize = %d, value = %d\n", err, propSize, streamLatency ); - } -} -#endif - -/* =================================================================================================== */ -/** - * @internal - * Calculate the fixed latency from the system and the device. - * Sum of kAudioStreamPropertyLatency + - * kAudioDevicePropertySafetyOffset + - * kAudioDevicePropertyLatency - * - * Some useful info from Jeff Moore on latency. - * http://osdir.com/ml/coreaudio-api/2010-01/msg00046.html - * http://osdir.com/ml/coreaudio-api/2009-07/msg00140.html - */ -static PaError CalculateFixedDeviceLatency( AudioDeviceID macCoreDeviceId, int isInput, UInt32 *fixedLatencyPtr ) -{ - PaError err; - UInt32 propSize; - UInt32 deviceLatency; - UInt32 streamLatency; - UInt32 safetyOffset; - AudioStreamID streamIDs[1]; - - // To get stream latency we have to get a streamID from the device. - // We are only going to look at the first stream so only fetch one stream. - propSize = sizeof(streamIDs); - err = WARNING(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreams, &propSize, &streamIDs[0])); - if( err != paNoError ) goto error; - if( propSize == sizeof(AudioStreamID) ) - { - propSize = sizeof(UInt32); - err = WARNING(PaMacCore_AudioStreamGetProperty(streamIDs[0], 0, kAudioStreamPropertyLatency, &propSize, &streamLatency)); - } - - propSize = sizeof(UInt32); - err = WARNING(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertySafetyOffset, &propSize, &safetyOffset)); - if( err != paNoError ) goto error; - - propSize = sizeof(UInt32); - err = WARNING(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &deviceLatency)); - if( err != paNoError ) goto error; - - *fixedLatencyPtr = deviceLatency + streamLatency + safetyOffset; - return err; -error: - return err; -} - -/* =================================================================================================== */ -static PaError CalculateDefaultDeviceLatencies( AudioDeviceID macCoreDeviceId, - int isInput, UInt32 *lowLatencyFramesPtr, - UInt32 *highLatencyFramesPtr ) -{ - UInt32 propSize; - UInt32 bufferFrames = 0; - UInt32 fixedLatency = 0; - UInt32 clippedMinBufferSize = 0; - - //DumpDeviceProperties( macCoreDeviceId, isInput ); - - PaError err = CalculateFixedDeviceLatency( macCoreDeviceId, isInput, &fixedLatency ); - if( err != paNoError ) goto error; - - // For low latency use a small fixed size buffer clipped to the device range. - err = ClipToDeviceBufferSize( macCoreDeviceId, isInput, PA_MAC_SMALL_BUFFER_SIZE, &clippedMinBufferSize ); - if( err != paNoError ) goto error; - - // For high latency use the default device buffer size. - propSize = sizeof(UInt32); - err = WARNING(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSize, &propSize, &bufferFrames)); - if( err != paNoError ) goto error; - - *lowLatencyFramesPtr = fixedLatency + clippedMinBufferSize; - *highLatencyFramesPtr = fixedLatency + bufferFrames; - - return err; -error: - return err; -} - -/* =================================================================================================== */ - -static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi, - PaDeviceInfo *deviceInfo, - AudioDeviceID macCoreDeviceId, - int isInput) -{ - UInt32 propSize; - PaError err = paNoError; - UInt32 i; - int numChannels = 0; - AudioBufferList *buflist = NULL; - - VVDBUG(("GetChannelInfo()\n")); - - /* Get the number of channels from the stream configuration. - Fail if we can't get this. */ - - err = ERR(PaMacCore_AudioDeviceGetPropertySize(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize)); - if (err) - return err; - - buflist = PaUtil_AllocateMemory(propSize); - if( !buflist ) - return paInsufficientMemory; - err = ERR(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, buflist)); - if (err) - goto error; - - for (i = 0; i < buflist->mNumberBuffers; ++i) - numChannels += buflist->mBuffers[i].mNumberChannels; - - if (isInput) - deviceInfo->maxInputChannels = numChannels; - else - deviceInfo->maxOutputChannels = numChannels; - - if (numChannels > 0) /* do not try to retrieve the latency if there are no channels. */ - { - /* Get the latency. Don't fail if we can't get this. */ - /* default to something reasonable */ - deviceInfo->defaultLowInputLatency = .01; - deviceInfo->defaultHighInputLatency = .10; - deviceInfo->defaultLowOutputLatency = .01; - deviceInfo->defaultHighOutputLatency = .10; - 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) - { - deviceInfo->defaultLowInputLatency = lowLatencySeconds; - deviceInfo->defaultHighInputLatency = highLatencySeconds; - } - else - { - deviceInfo->defaultLowOutputLatency = lowLatencySeconds; - deviceInfo->defaultHighOutputLatency = highLatencySeconds; - } - } - } - PaUtil_FreeMemory( buflist ); - return paNoError; -error: - PaUtil_FreeMemory( buflist ); - return err; -} - -/* =================================================================================================== */ -static PaError InitializeDeviceInfo( PaMacAUHAL *auhalHostApi, - PaDeviceInfo *deviceInfo, - AudioDeviceID macCoreDeviceId, - PaHostApiIndex hostApiIndex ) -{ - Float64 sampleRate; - char *name; - PaError err = paNoError; - CFStringRef nameRef; - UInt32 propSize; - - VVDBUG(("InitializeDeviceInfo(): macCoreDeviceId=%ld\n", macCoreDeviceId)); - - memset(deviceInfo, 0, sizeof(PaDeviceInfo)); - - deviceInfo->structVersion = 2; - deviceInfo->hostApi = hostApiIndex; - - /* Get the device name using CFString */ - 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); - } - deviceInfo->name = name; - - /* Try to get the default sample rate. Don't fail if we can't get this. */ - propSize = sizeof(Float64); - err = ERR(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &sampleRate)); - if (err) - deviceInfo->defaultSampleRate = 0.0; - else - deviceInfo->defaultSampleRate = sampleRate; - - /* Get the maximum number of input and output channels. Fail if we can't get this. */ - - err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 1); - if (err) - return err; - - err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 0); - if (err) - return err; - - return paNoError; -} - -PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex ) -{ - PaError result = paNoError; - int i; - PaMacAUHAL *auhalHostApi = NULL; - PaDeviceInfo *deviceInfoArray; - 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; - } - } - - unixErr = initializeXRunListenerList(); - if( 0 != unixErr ) { - return UNIX_ERR(unixErr); - } - - auhalHostApi = (PaMacAUHAL*)PaUtil_AllocateMemory( sizeof(PaMacAUHAL) ); - if( !auhalHostApi ) - { - result = paInsufficientMemory; - goto error; - } - - auhalHostApi->allocations = PaUtil_CreateAllocationGroup(); - if( !auhalHostApi->allocations ) - { - result = paInsufficientMemory; - goto error; - } - - auhalHostApi->devIds = NULL; - auhalHostApi->devCount = 0; - - /* get the info we need about the devices */ - result = gatherDeviceInfo( auhalHostApi ); - if( result != paNoError ) - goto error; - - *hostApi = &auhalHostApi->inheritedHostApiRep; - (*hostApi)->info.structVersion = 1; - (*hostApi)->info.type = paCoreAudio; - (*hostApi)->info.name = "Core Audio"; - - (*hostApi)->info.defaultInputDevice = paNoDevice; - (*hostApi)->info.defaultOutputDevice = paNoDevice; - - (*hostApi)->info.deviceCount = 0; - - if( auhalHostApi->devCount > 0 ) - { - (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory( - auhalHostApi->allocations, sizeof(PaDeviceInfo*) * auhalHostApi->devCount); - if( !(*hostApi)->deviceInfos ) - { - result = paInsufficientMemory; - goto error; - } - - /* allocate all device info structs in a contiguous block */ - deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory( - auhalHostApi->allocations, sizeof(PaDeviceInfo) * auhalHostApi->devCount ); - if( !deviceInfoArray ) - { - result = paInsufficientMemory; - goto error; - } - - for( i=0; i < auhalHostApi->devCount; ++i ) - { - int err; - err = InitializeDeviceInfo( auhalHostApi, &deviceInfoArray[i], - auhalHostApi->devIds[i], - hostApiIndex ); - if (err == paNoError) - { /* copy some info and set the defaults */ - (*hostApi)->deviceInfos[(*hostApi)->info.deviceCount] = &deviceInfoArray[i]; - if (auhalHostApi->devIds[i] == auhalHostApi->defaultIn) - (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount; - if (auhalHostApi->devIds[i] == auhalHostApi->defaultOut) - (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount; - (*hostApi)->info.deviceCount++; - } - else - { /* there was an error. we need to shift the devices down, so we ignore this one */ - int j; - auhalHostApi->devCount--; - for( j=i; j<auhalHostApi->devCount; ++j ) - auhalHostApi->devIds[j] = auhalHostApi->devIds[j+1]; - i--; - } - } - } - - (*hostApi)->Terminate = Terminate; - (*hostApi)->OpenStream = OpenStream; - (*hostApi)->IsFormatSupported = IsFormatSupported; - - PaUtil_InitializeStreamInterface( &auhalHostApi->callbackStreamInterface, - CloseStream, StartStream, - StopStream, AbortStream, IsStreamStopped, - IsStreamActive, - GetStreamTime, GetStreamCpuLoad, - PaUtil_DummyRead, PaUtil_DummyWrite, - PaUtil_DummyGetReadAvailable, - PaUtil_DummyGetWriteAvailable ); - - PaUtil_InitializeStreamInterface( &auhalHostApi->blockingStreamInterface, - CloseStream, StartStream, - StopStream, AbortStream, IsStreamStopped, - IsStreamActive, - GetStreamTime, PaUtil_DummyGetCpuLoad, - ReadStream, WriteStream, - GetStreamReadAvailable, - GetStreamWriteAvailable ); - - return result; - -error: - if( auhalHostApi ) - { - if( auhalHostApi->allocations ) - { - PaUtil_FreeAllAllocations( auhalHostApi->allocations ); - PaUtil_DestroyAllocationGroup( auhalHostApi->allocations ); - } - - PaUtil_FreeMemory( auhalHostApi ); - } - return result; -} - - -static void Terminate( struct PaUtilHostApiRepresentation *hostApi ) -{ - int unixErr; - - PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi; - - VVDBUG(("Terminate()\n")); - - unixErr = destroyXRunListenerList(); - if( 0 != unixErr ) - UNIX_ERR(unixErr); - - /* - IMPLEMENT ME: - - clean up any resources not handled by the allocation group - TODO: Double check that everything is handled by alloc group - */ - - if( auhalHostApi->allocations ) - { - PaUtil_FreeAllAllocations( auhalHostApi->allocations ); - PaUtil_DestroyAllocationGroup( auhalHostApi->allocations ); - } - - PaUtil_FreeMemory( auhalHostApi ); -} - - -static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi, - const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, - double sampleRate ) -{ - int inputChannelCount, outputChannelCount; - PaSampleFormat inputSampleFormat, outputSampleFormat; - - VVDBUG(("IsFormatSupported(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld sampleRate=%g\n", - inputParameters ? inputParameters->channelCount : -1, - inputParameters ? inputParameters->sampleFormat : -1, - outputParameters ? outputParameters->channelCount : -1, - outputParameters ? outputParameters->sampleFormat : -1, - (float) sampleRate )); - - /** These first checks are standard PA checks. We do some fancier checks - later. */ - if( inputParameters ) - { - inputChannelCount = inputParameters->channelCount; - inputSampleFormat = inputParameters->sampleFormat; - - /* all standard sample formats are supported by the buffer adapter, - this implementation doesn't support any custom sample formats */ - if( inputSampleFormat & paCustomFormat ) - return paSampleFormatNotSupported; - - /* unless alternate device specification is supported, reject the use of - paUseHostApiSpecificDeviceSpecification */ - - if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) - return paInvalidDevice; - - /* check that input device can support inputChannelCount */ - if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) - return paInvalidChannelCount; - } - else - { - inputChannelCount = 0; - } - - if( outputParameters ) - { - outputChannelCount = outputParameters->channelCount; - outputSampleFormat = outputParameters->sampleFormat; - - /* all standard sample formats are supported by the buffer adapter, - this implementation doesn't support any custom sample formats */ - if( outputSampleFormat & paCustomFormat ) - return paSampleFormatNotSupported; - - /* unless alternate device specification is supported, reject the use of - paUseHostApiSpecificDeviceSpecification */ - - if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) - return paInvalidDevice; - - /* check that output device can support outputChannelCount */ - if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) - return paInvalidChannelCount; - - } - else - { - outputChannelCount = 0; - } - - /* FEEDBACK */ - /* I think the only way to check a given format SR combo is */ - /* to try opening it. This could be disruptive, is that Okay? */ - /* The alternative is to just read off available sample rates, */ - /* but this will not work %100 of the time (eg, a device that */ - /* supports N output at one rate but only N/2 at a higher rate.)*/ - - /* The following code opens the device with the requested parameters to - see if it works. */ - { - PaError err; - PaStream *s; - err = OpenStream( hostApi, &s, inputParameters, outputParameters, - sampleRate, 1024, 0, (PaStreamCallback *)1, NULL ); - if( err != paNoError && err != paInvalidSampleRate ) - DBUG( ( "OpenStream @ %g returned: %d: %s\n", - (float) sampleRate, err, Pa_GetErrorText( err ) ) ); - if( err ) - return err; - err = CloseStream( s ); - if( err ) { - /* FEEDBACK: is this more serious? should we assert? */ - DBUG( ( "WARNING: could not close Stream. %d: %s\n", - err, Pa_GetErrorText( err ) ) ); - } - } - - return paFormatIsSupported; -} - -/* ================================================================================= */ -static void InitializeDeviceProperties( PaMacCoreDeviceProperties *deviceProperties ) -{ - memset( deviceProperties, 0, sizeof(PaMacCoreDeviceProperties) ); - deviceProperties->sampleRate = 1.0; // Better than random. Overwritten by actual values later on. - deviceProperties->samplePeriod = 1.0 / deviceProperties->sampleRate; -} - -static Float64 CalculateSoftwareLatencyFromProperties( PaMacCoreStream *stream, PaMacCoreDeviceProperties *deviceProperties ) -{ - UInt32 latencyFrames = deviceProperties->bufferFrameSize + deviceProperties->deviceLatency + deviceProperties->safetyOffset; - return latencyFrames * deviceProperties->samplePeriod; // same as dividing by sampleRate but faster -} - -static Float64 CalculateHardwareLatencyFromProperties( PaMacCoreStream *stream, PaMacCoreDeviceProperties *deviceProperties ) -{ - return deviceProperties->deviceLatency * deviceProperties->samplePeriod; // same as dividing by sampleRate but faster -} - -/* Calculate values used to convert Apple timestamps into PA timestamps - * from the device properties. The final results of this calculation - * will be used in the audio callback function. - */ -static void UpdateTimeStampOffsets( PaMacCoreStream *stream ) -{ - Float64 inputSoftwareLatency = 0.0; - 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 ); - stream->timestampOffsetCombined = inputSoftwareLatency + outputSoftwareLatency; - stream->timestampOffsetInputDevice = inputHardwareLatency; - stream->timestampOffsetOutputDevice = outputHardwareLatency; - 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 ) -{ - PaMacCoreDeviceProperties * deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties; - - 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 */ - { - deviceProperties->sampleRate = sampleRate; - deviceProperties->samplePeriod = 1.0 / sampleRate; - } - return osErr; -} - -static OSStatus AudioDevicePropertyActualSampleRateListenerProc( AudioObjectID inDevice, UInt32 inNumberAddresses, - const AudioObjectPropertyAddress * inAddresses, void * inClientData ) -{ - PaMacCoreStream *stream = (PaMacCoreStream*)inClientData; - bool isInput = inAddresses->mScope == kAudioDevicePropertyScopeInput; - - // Make sure the callback is operating on a stream that is still valid! - assert( stream->streamRepresentation.magic == PA_STREAM_MAGIC ); - - OSStatus osErr = UpdateSampleRateFromDeviceProperty( stream, inDevice, isInput, kAudioDevicePropertyActualSampleRate ); - if( osErr == noErr ) - { - UpdateTimeStampOffsets( stream ); - } - return osErr; -} - -/* ================================================================================= */ -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 ) - { - *outValue = propertyValue; - } - return osErr; -} - -static OSStatus AudioDevicePropertyGenericListenerProc( AudioObjectID inDevice, UInt32 inNumberAddresses, - const AudioObjectPropertyAddress * inAddresses, void * inClientData ) -{ - OSStatus osErr = noErr; - PaMacCoreStream *stream = (PaMacCoreStream*)inClientData; - bool isInput = inAddresses->mScope == kAudioDevicePropertyScopeInput; - AudioDevicePropertyID inPropertyID = inAddresses->mSelector; - - // 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; - } - if( valuePtr != NULL ) - { - osErr = QueryUInt32DeviceProperty( inDevice, isInput, inPropertyID, valuePtr ); - if( osErr == noErr ) - { - UpdateTimeStampOffsets( stream ); - } - } - return osErr; -} - -/* ================================================================================= */ -/* - * Setup listeners in case device properties change during the run. */ -static OSStatus SetupDevicePropertyListeners( PaMacCoreStream *stream, AudioDeviceID deviceID, Boolean isInput ) -{ - OSStatus osErr = noErr; - PaMacCoreDeviceProperties *deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties; - - if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput, - kAudioDevicePropertyLatency, &deviceProperties->deviceLatency )) != noErr ) return osErr; - if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput, - kAudioDevicePropertyBufferFrameSize, &deviceProperties->bufferFrameSize )) != noErr ) return osErr; - if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput, - kAudioDevicePropertySafetyOffset, &deviceProperties->safetyOffset )) != noErr ) return osErr; - - PaMacCore_AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertyActualSampleRate, - AudioDevicePropertyActualSampleRateListenerProc, stream ); - - PaMacCore_AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioStreamPropertyLatency, - AudioDevicePropertyGenericListenerProc, stream ); - PaMacCore_AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertyBufferFrameSize, - AudioDevicePropertyGenericListenerProc, stream ); - PaMacCore_AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertySafetyOffset, - AudioDevicePropertyGenericListenerProc, stream ); - - return osErr; -} - -static void CleanupDevicePropertyListeners( PaMacCoreStream *stream, AudioDeviceID deviceID, Boolean isInput ) -{ - PaMacCore_AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyActualSampleRate, - AudioDevicePropertyActualSampleRateListenerProc, stream ); - - PaMacCore_AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyLatency, - AudioDevicePropertyGenericListenerProc, stream ); - PaMacCore_AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyBufferFrameSize, - AudioDevicePropertyGenericListenerProc, stream ); - PaMacCore_AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertySafetyOffset, - 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 ) -{ -#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6 - AudioComponentDescription desc; - AudioComponent comp; -#else - ComponentDescription desc; - Component comp; -#endif - /*An Apple TN suggests using CAStreamBasicDescription, but that is C++*/ - AudioStreamBasicDescription desiredFormat; - OSStatus result = noErr; - PaError paResult = paNoError; - int line = 0; - UInt32 callbackKey; - AURenderCallbackStruct rcbs; - unsigned long macInputStreamFlags = paMacCorePlayNice; - unsigned long macOutputStreamFlags = paMacCorePlayNice; - SInt32 const *inChannelMap = NULL; - SInt32 const *outChannelMap = NULL; - unsigned long inChannelMapSize = 0; - unsigned long outChannelMapSize = 0; - - VVDBUG(("OpenAndSetupOneAudioUnit(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld, requestedFramesPerBuffer=%ld\n", - inStreamParams ? inStreamParams->channelCount : -1, - inStreamParams ? inStreamParams->sampleFormat : -1, - outStreamParams ? outStreamParams->channelCount : -1, - outStreamParams ? outStreamParams->sampleFormat : -1, - requestedFramesPerBuffer )); - - /* -- handle the degenerate case -- */ - if( !inStreamParams && !outStreamParams ) { - *audioUnit = NULL; - *audioDevice = kAudioDeviceUnknown; - return paNoError; - } - - /* -- get the user's api specific info, if they set any -- */ - if( inStreamParams && inStreamParams->hostApiSpecificStreamInfo ) - { - macInputStreamFlags= - ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo) - ->flags; - inChannelMap = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)->channelMap; - inChannelMapSize = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)->channelMapSize; - } - if( outStreamParams && outStreamParams->hostApiSpecificStreamInfo ) - { - macOutputStreamFlags= - ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo) - ->flags; - outChannelMap = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)->channelMap; - outChannelMapSize = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)->channelMapSize; - } - /* Override user's flags here, if desired for testing. */ - - /* - * The HAL AU is a Mac OS style "component". - * the first few steps deal with that. - * Later steps work on a combination of Mac OS - * components and the slightly lower level - * HAL. - */ - - /* -- describe the output type AudioUnit -- */ - /* Note: for the default AudioUnit, we could use the - * componentSubType value kAudioUnitSubType_DefaultOutput; - * but I don't think that's relevant here. - */ - desc.componentType = kAudioUnitType_Output; - desc.componentSubType = kAudioUnitSubType_HALOutput; - desc.componentManufacturer = kAudioUnitManufacturer_Apple; - desc.componentFlags = 0; - desc.componentFlagsMask = 0; - /* -- find the component -- */ -#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6 - comp = AudioComponentFindNext( NULL, &desc ); -#else - comp = FindNextComponent( NULL, &desc ); -#endif - if( !comp ) - { - 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 - result = AudioComponentInstanceNew( comp, audioUnit ); -#else - result = OpenAComponent( comp, audioUnit ); -#endif - if( result ) - { - DBUG( ( "Failed to open AUHAL component." ) ); - *audioUnit = NULL; - *audioDevice = kAudioDeviceUnknown; - return ERR( result ); - } - /* -- prepare a little error handling logic / hackery -- */ -#define ERR_WRAP(mac_err) do { result = mac_err ; line = __LINE__ ; if ( result != noErr ) goto error ; } while(0) - - /* -- if there is input, we have to explicitly enable input -- */ - if( inStreamParams ) - { - UInt32 enableIO = 1; - ERR_WRAP( AudioUnitSetProperty( *audioUnit, - kAudioOutputUnitProperty_EnableIO, - kAudioUnitScope_Input, - INPUT_ELEMENT, - &enableIO, - sizeof(enableIO) ) ); - } - /* -- if there is no output, we must explicitly disable output -- */ - if( !outStreamParams ) - { - UInt32 enableIO = 0; - ERR_WRAP( AudioUnitSetProperty( *audioUnit, - kAudioOutputUnitProperty_EnableIO, - kAudioUnitScope_Output, - OUTPUT_ELEMENT, - &enableIO, - sizeof(enableIO) ) ); - } - - /* -- set the devices -- */ - /* make sure input and output are the same device if we are doing input and - output. */ - if( inStreamParams && outStreamParams ) - { - assert( outStreamParams->device == inStreamParams->device ); - } - if( inStreamParams ) - { - *audioDevice = auhalHostApi->devIds[inStreamParams->device] ; - ERR_WRAP( AudioUnitSetProperty( *audioUnit, - kAudioOutputUnitProperty_CurrentDevice, - kAudioUnitScope_Global, - INPUT_ELEMENT, - audioDevice, - sizeof(AudioDeviceID) ) ); - } - if( outStreamParams && outStreamParams != inStreamParams ) - { - *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 ) ) ; - if( result == kAudioHardwareIllegalOperationError ) { - // -- already registered, we're good - } else { - // -- not already registered, just check for errors - ERR_WRAP( result ); - } - /* -- listen for stream start and stop -- */ - ERR_WRAP( AudioUnitAddPropertyListener( *audioUnit, - kAudioOutputUnitProperty_IsRunning, - startStopCallback, - (void *)stream ) ); - - /* -- set format -- */ - bzero( &desiredFormat, sizeof(desiredFormat) ); - desiredFormat.mFormatID = kAudioFormatLinearPCM ; - desiredFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked; - desiredFormat.mFramesPerPacket = 1; - desiredFormat.mBitsPerChannel = sizeof( float ) * 8; - - result = 0; - /* set device format first, but only touch the device if the user asked */ - if( inStreamParams ) { - /*The callback never calls back if we don't set the FPB */ - /*This seems 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; - } - } - - /* -- set the quality of the output converter -- */ - if( outStreamParams ) { - UInt32 value = kAudioConverterQuality_Max; - switch( macOutputStreamFlags & 0x0700 ) { - case 0x0100: /*paMacCore_ConversionQualityMin:*/ - value=kRenderQuality_Min; - break; - case 0x0200: /*paMacCore_ConversionQualityLow:*/ - value=kRenderQuality_Low; - break; - case 0x0300: /*paMacCore_ConversionQualityMedium:*/ - value=kRenderQuality_Medium; - break; - case 0x0400: /*paMacCore_ConversionQualityHigh:*/ - value=kRenderQuality_High; - break; - } - ERR_WRAP( AudioUnitSetProperty( *audioUnit, - kAudioUnitProperty_RenderQuality, - kAudioUnitScope_Global, - OUTPUT_ELEMENT, - &value, - sizeof(value) ) ); - } - /* now set the format on the Audio Units. */ - if( outStreamParams ) - { - desiredFormat.mSampleRate =sampleRate; - desiredFormat.mBytesPerPacket=sizeof(float)*outStreamParams->channelCount; - desiredFormat.mBytesPerFrame =sizeof(float)*outStreamParams->channelCount; - desiredFormat.mChannelsPerFrame = outStreamParams->channelCount; - ERR_WRAP( AudioUnitSetProperty( *audioUnit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Input, - OUTPUT_ELEMENT, - &desiredFormat, - sizeof(AudioStreamBasicDescription) ) ); - } - if( inStreamParams ) - { - AudioStreamBasicDescription sourceFormat; - UInt32 size = sizeof( AudioStreamBasicDescription ); - - /* keep the sample rate of the device, or we confuse AUHAL */ - ERR_WRAP( AudioUnitGetProperty( *audioUnit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Input, - INPUT_ELEMENT, - &sourceFormat, - &size ) ); - desiredFormat.mSampleRate = sourceFormat.mSampleRate; - desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount; - desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount; - desiredFormat.mChannelsPerFrame = inStreamParams->channelCount; - ERR_WRAP( AudioUnitSetProperty( *audioUnit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Output, - INPUT_ELEMENT, - &desiredFormat, - sizeof(AudioStreamBasicDescription) ) ); - } - /* set the maximumFramesPerSlice */ - /* not doing this causes real problems - (eg. the callback might not be called). The idea of setting both this - and the frames per buffer on the device is that we'll be most likely - to actually get the frame size we requested in the callback with the - minimum latency. */ - if( outStreamParams ) { - UInt32 size = sizeof( *actualOutputFramesPerBuffer ); - ERR_WRAP( AudioUnitSetProperty( *audioUnit, - kAudioUnitProperty_MaximumFramesPerSlice, - kAudioUnitScope_Input, - OUTPUT_ELEMENT, - actualOutputFramesPerBuffer, - sizeof(*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 ) ); - */ - } - - /* -- if we have input, we may need to setup an SR converter -- */ - /* even if we got the sample rate we asked for, we need to do - the conversion in case another program changes the underlying SR. */ - /* FIXME: I think we need to monitor stream and change the converter if the incoming format changes. */ - if( inStreamParams ) { - AudioStreamBasicDescription desiredFormat; - AudioStreamBasicDescription sourceFormat; - UInt32 sourceSize = sizeof( sourceFormat ); - bzero( &desiredFormat, sizeof(desiredFormat) ); - desiredFormat.mSampleRate = sampleRate; - desiredFormat.mFormatID = kAudioFormatLinearPCM ; - desiredFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked; - desiredFormat.mFramesPerPacket = 1; - desiredFormat.mBitsPerChannel = sizeof( float ) * 8; - desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount; - desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount; - desiredFormat.mChannelsPerFrame = inStreamParams->channelCount; - - /* get the source format */ - ERR_WRAP( AudioUnitGetProperty( *audioUnit, - kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Output, - INPUT_ELEMENT, - &sourceFormat, - &sourceSize ) ); - - if( desiredFormat.mSampleRate != sourceFormat.mSampleRate ) - { - UInt32 value = kAudioConverterQuality_Max; - switch( macInputStreamFlags & 0x0700 ) { - case 0x0100: /*paMacCore_ConversionQualityMin:*/ - value=kAudioConverterQuality_Min; - break; - case 0x0200: /*paMacCore_ConversionQualityLow:*/ - value=kAudioConverterQuality_Low; - break; - case 0x0300: /*paMacCore_ConversionQualityMedium:*/ - value=kAudioConverterQuality_Medium; - break; - case 0x0400: /*paMacCore_ConversionQualityHigh:*/ - value=kAudioConverterQuality_High; - break; - } - VDBUG(( "Creating sample rate converter for input" - " to convert from %g to %g\n", - (float)sourceFormat.mSampleRate, - (float)desiredFormat.mSampleRate ) ); - /* create our converter */ - ERR_WRAP( AudioConverterNew( &sourceFormat, - &desiredFormat, - srConverter ) ); - /* Set quality */ - ERR_WRAP( AudioConverterSetProperty( *srConverter, - kAudioConverterSampleRateConverterQuality, - sizeof( value ), - &value ) ); - } - } - /* -- set IOProc (callback) -- */ - callbackKey = outStreamParams ? kAudioUnitProperty_SetRenderCallback - : kAudioOutputUnitProperty_SetInputCallback ; - rcbs.inputProc = AudioIOProc; - rcbs.inputProcRefCon = refCon; - ERR_WRAP( AudioUnitSetProperty( *audioUnit, - callbackKey, - kAudioUnitScope_Output, - outStreamParams ? OUTPUT_ELEMENT : INPUT_ELEMENT, - &rcbs, - sizeof(rcbs)) ); - - if( inStreamParams && outStreamParams && *srConverter ) - ERR_WRAP( AudioUnitSetProperty( *audioUnit, - kAudioOutputUnitProperty_SetInputCallback, - kAudioUnitScope_Output, - INPUT_ELEMENT, - &rcbs, - sizeof(rcbs)) ); - - /* channel mapping. */ - if(inChannelMap) - { - UInt32 mapSize = inChannelMapSize *sizeof(SInt32); - - //for each channel of desired input, map the channel from - //the device's output channel. - ERR_WRAP( AudioUnitSetProperty( *audioUnit, - kAudioOutputUnitProperty_ChannelMap, - kAudioUnitScope_Output, - INPUT_ELEMENT, - inChannelMap, - mapSize) ); - } - if(outChannelMap) - { - UInt32 mapSize = outChannelMapSize *sizeof(SInt32); - - //for each channel of desired output, map the channel from - //the device's output channel. - ERR_WRAP(AudioUnitSetProperty( *audioUnit, - kAudioOutputUnitProperty_ChannelMap, - kAudioUnitScope_Output, - OUTPUT_ELEMENT, - outChannelMap, - mapSize) ); - } - /* initialize the audio unit */ - ERR_WRAP( AudioUnitInitialize(*audioUnit) ); - - if( inStreamParams && outStreamParams ) - { - VDBUG( ("Opened device %ld for input and output.\n", (long)*audioDevice ) ); - } - else if( inStreamParams ) - { - VDBUG( ("Opened device %ld for input.\n", (long)*audioDevice ) ); - } - else if( outStreamParams ) - { - VDBUG( ("Opened device %ld for output.\n", (long)*audioDevice ) ); - } - return paNoError; -#undef ERR_WRAP - -error: - -#if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6 - AudioComponentInstanceDispose( *audioUnit ); -#else - CloseComponent( *audioUnit ); -#endif - *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 ) -{ - UInt32 resultBufferSizeFrames = 0; - // Use maximum of suggested input and output latencies. - if( inputParameters ) - { - UInt32 suggestedLatencyFrames = inputParameters->suggestedLatency * sampleRate; - // Calculate a buffer size assuming we are double buffered. - SInt32 variableLatencyFrames = suggestedLatencyFrames - fixedInputLatency; - // Prevent negative latency. - 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 ) ); - } - - // Clip to the capabilities of the device. - if( inputParameters ) - { - ClipToDeviceBufferSize( auhalHostApi->devIds[inputParameters->device], - true, // In the old code isInput was false! - resultBufferSizeFrames, &resultBufferSizeFrames ); - } - if( outputParameters ) - { - ClipToDeviceBufferSize( auhalHostApi->devIds[outputParameters->device], - false, resultBufferSizeFrames, &resultBufferSizeFrames ); - } - VDBUG(("After querying hardware, setting block size to %ld.\n", (long)resultBufferSizeFrames)); - - return resultBufferSizeFrames; -} - -/* =================================================================================================== */ -/* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */ -static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi, - PaStream** s, - const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, - double sampleRate, - unsigned long requestedFramesPerBuffer, - PaStreamFlags streamFlags, - PaStreamCallback *streamCallback, - void *userData ) -{ - PaError result = paNoError; - PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi; - PaMacCoreStream *stream = 0; - int inputChannelCount, outputChannelCount; - PaSampleFormat inputSampleFormat, outputSampleFormat; - PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat; - UInt32 fixedInputLatency = 0; - UInt32 fixedOutputLatency = 0; - // Accumulate contributions to latency in these variables. - 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 )); - 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; - } - - /* unless alternate device specification is supported, reject the use of - paUseHostApiSpecificDeviceSpecification */ - - if( inputParameters->device == paUseHostApiSpecificDeviceSpecification ) - return paInvalidDevice; - - /* check that input device can support inputChannelCount */ - if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels ) - return paInvalidChannelCount; - - /* Host supports interleaved float32 */ - hostInputSampleFormat = paFloat32; - } - else - { - inputChannelCount = 0; - inputSampleFormat = hostInputSampleFormat = paFloat32; /* Suppress 'uninitialised var' warnings. */ - } - - if( outputParameters ) - { - outputChannelCount = outputParameters->channelCount; - outputSampleFormat = outputParameters->sampleFormat; - - /* @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 */ - - if( outputParameters->device == paUseHostApiSpecificDeviceSpecification ) - return paInvalidDevice; - - /* check that output device can support inputChannelCount */ - if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels ) - return paInvalidChannelCount; - - /* Host supports interleaved float32 */ - hostOutputSampleFormat = paFloat32; - } - else - { - outputChannelCount = 0; - outputSampleFormat = hostOutputSampleFormat = paFloat32; /* Suppress 'uninitialized var' warnings. */ - } - - /* validate platform specific flags */ - if( (streamFlags & paPlatformSpecificFlags) != 0 ) - return paInvalidFlag; /* unexpected platform specific flag */ - - stream = (PaMacCoreStream*)PaUtil_AllocateMemory( sizeof(PaMacCoreStream) ); - if( !stream ) - { - result = paInsufficientMemory; - goto error; - } - - /* If we fail after this point, we my be left in a bad state, with - some data structures setup and others not. So, first thing we - do is initialize everything so that if we fail, we know what hasn't - been touched. - */ - bzero( stream, sizeof( PaMacCoreStream ) ); - - /* - stream->blio.inputRingBuffer.buffer = NULL; - stream->blio.outputRingBuffer.buffer = NULL; - stream->blio.inputSampleFormat = inputParameters?inputParameters->sampleFormat:0; - stream->blio.inputSampleSize = computeSampleSizeFromFormat(stream->blio.inputSampleFormat); - stream->blio.outputSampleFormat=outputParameters?outputParameters->sampleFormat:0; - stream->blio.outputSampleSize = computeSampleSizeFromFormat(stream->blio.outputSampleFormat); - */ - - /* assert( streamCallback ) ; */ /* only callback mode is implemented */ - if( streamCallback ) - { - PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, - &auhalHostApi->callbackStreamInterface, - streamCallback, userData ); - } - else - { - PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation, - &auhalHostApi->blockingStreamInterface, - BlioCallback, &stream->blio ); - } - - PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate ); - - - 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 ); - 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; - } - 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; - } - - 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; - } - } - - /* -- 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; - - 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; - } - stream->bufferProcessorIsInitialized = TRUE; - - // Calculate actual latency from the sum of individual latencies. - if( inputParameters ) - { - inputLatencyFrames += PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor); - stream->streamRepresentation.streamInfo.inputLatency = inputLatencyFrames / sampleRate; - } - else - { - stream->streamRepresentation.streamInfo.inputLatency = 0.0; - } - - if( outputParameters ) - { - outputLatencyFrames += PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor); - stream->streamRepresentation.streamInfo.outputLatency = outputLatencyFrames / sampleRate; - } - else - { - 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; - 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 ) - { - 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 ) ); - 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 ) - { - Boolean isInput = TRUE; - - // as above - 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; - stream->timestampOffsetInputDevice_ioProcCopy = stream->timestampOffsetInputDevice; - stream->timestampOffsetOutputDevice_ioProcCopy = stream->timestampOffsetOutputDevice; - - stream->state = STOPPED; - stream->xrunFlags = 0; - - *s = (PaStream*)stream; - - return result; - -error: - CloseStream( stream ); - return result; -} - - -#define HOST_TIME_TO_PA_TIME( x ) ( AudioConvertHostTimeToNanos( (x) ) * 1.0E-09) /* convert to nanoseconds and then to seconds */ - -PaTime GetStreamTime( PaStream *s ) -{ - return HOST_TIME_TO_PA_TIME( AudioGetCurrentHostTime() ); -} - -#define RING_BUFFER_EMPTY (1000) - -static OSStatus ringBufferIOProc( - AudioConverterRef inAudioConverter, - UInt32* ioNumberDataPackets, - AudioBufferList* ioData, - 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; -} - -/* - * Called by the AudioUnit API to process audio from the sound card. - * This is where the magic happens. - */ -/* FEEDBACK: there is a lot of redundant code here because of how all the cases differ. This makes it hard to maintain, so if there are suggestinos for cleaning it up, I'm all ears. */ -static OSStatus AudioIOProc( void *inRefCon, - AudioUnitRenderActionFlags *ioActionFlags, - const AudioTimeStamp *inTimeStamp, - UInt32 inBusNumber, - UInt32 inNumberFrames, - AudioBufferList *ioData ) -{ - unsigned long framesProcessed = 0; - PaStreamCallbackTimeInfo timeInfo = {0,0,0}; - PaMacCoreStream *stream = (PaMacCoreStream*)inRefCon; - const bool isRender = inBusNumber == OUTPUT_ELEMENT; - int callbackResult = paContinue ; - 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; i<ioData->mNumberBuffers; ++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 ); - } - } - } 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 ) - { - PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed ); - return noErr; - } - -stop_stream: - stream->state = CALLBACK_STOPPED ; - if( stream->outputUnit ) - AudioOutputUnitStop(stream->outputUnit); - if( stream->inputUnit ) - AudioOutputUnitStop(stream->inputUnit); - - PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed ); - return noErr; -} - -/* - When CloseStream() is called, the multi-api layer ensures that - the stream has already been stopped or aborted. -*/ -static PaError CloseStream( PaStream* s ) -{ - /* This may be called from a failed OpenStream. - Therefore, each piece of info is treated separately. */ - PaError result = paNoError; - PaMacCoreStream *stream = (PaMacCoreStream*)s; - - VVDBUG(("CloseStream()\n")); - VDBUG( ( "Closing stream.\n" ) ); - - if( stream ) { - - if( stream->outputUnit ) - { - Boolean isInput = FALSE; - CleanupDevicePropertyListeners( stream, stream->outputDevice, isInput ); - } - - 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 MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6 - AudioComponentInstanceDispose( stream->outputUnit ); -#else - CloseComponent( stream->outputUnit ); -#endif - } - 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 ); -#else - 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 ); - } - - return result; -} - -static PaError StartStream( PaStream *s ) -{ - PaMacCoreStream *stream = (PaMacCoreStream*)s; - OSStatus result = noErr; - VVDBUG(("StartStream()\n")); - VDBUG( ( "Starting stream.\n" ) ); - -#define ERR_WRAP(mac_err) do { result = mac_err ; if ( result != noErr ) return ERR(result) ; } while(0) - - /*FIXME: maybe want to do this on close/abort for faster start? */ - PaUtil_ResetBufferProcessor( &stream->bufferProcessor ); - if( stream->inputSRConverter ) - ERR_WRAP( AudioConverterReset( stream->inputSRConverter ) ); - - /* -- start -- */ - stream->state = ACTIVE; - if( stream->inputUnit ) { - ERR_WRAP( AudioOutputUnitStart(stream->inputUnit) ); - } - if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) { - ERR_WRAP( AudioOutputUnitStart(stream->outputUnit) ); - } - - return paNoError; -#undef ERR_WRAP -} - -// it's not clear from appl's docs that this really waits -// until all data is flushed. -static ComponentResult BlockWhileAudioUnitIsRunning( AudioUnit audioUnit, AudioUnitElement element ) -{ - Boolean isRunning = 1; - while( isRunning ) { - UInt32 s = sizeof( isRunning ); - ComponentResult err = AudioUnitGetProperty( audioUnit, kAudioOutputUnitProperty_IsRunning, kAudioUnitScope_Global, element, &isRunning, &s ); - if( err ) - return err; - Pa_Sleep( 100 ); - } - return noErr; -} - -static PaError FinishStoppingStream( PaMacCoreStream *stream ) -{ - OSStatus result = noErr; - PaError paErr; - -#define ERR_WRAP(mac_err) do { result = mac_err ; if ( result != noErr ) return ERR(result) ; } while(0) - /* -- stop and reset -- */ - if( stream->inputUnit == stream->outputUnit && stream->inputUnit ) - { - ERR_WRAP( AudioOutputUnitStop(stream->inputUnit) ); - ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,0) ); - ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,1) ); - ERR_WRAP( AudioUnitReset(stream->inputUnit, kAudioUnitScope_Global, 1) ); - ERR_WRAP( AudioUnitReset(stream->inputUnit, kAudioUnitScope_Global, 0) ); - } - else - { - if( stream->inputUnit ) - { - ERR_WRAP(AudioOutputUnitStop(stream->inputUnit) ); - ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,1) ); - ERR_WRAP(AudioUnitReset(stream->inputUnit,kAudioUnitScope_Global,1)); - } - if( stream->outputUnit ) - { - ERR_WRAP(AudioOutputUnitStop(stream->outputUnit)); - ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->outputUnit,0) ); - ERR_WRAP(AudioUnitReset(stream->outputUnit,kAudioUnitScope_Global,0)); - } - } - if( stream->inputRingBuffer.buffer ) { - PaUtil_FlushRingBuffer( &stream->inputRingBuffer ); - bzero( (void *)stream->inputRingBuffer.buffer, - stream->inputRingBuffer.bufferSize ); - /* advance the write point a little, so we are reading from the - middle of the buffer. We'll need extra at the end because - testing has shown that this helps. */ - if( stream->outputUnit ) - PaUtil_AdvanceRingBufferWriteIndex( &stream->inputRingBuffer, - stream->inputRingBuffer.bufferSize - / RING_BUFFER_ADVANCE_DENOMINATOR ); - } - - stream->xrunFlags = 0; - stream->state = STOPPED; - - paErr = resetBlioRingBuffers( &stream->blio ); - if( paErr ) - return paErr; - - VDBUG( ( "Stream Stopped.\n" ) ); - return paNoError; -#undef ERR_WRAP -} - -/* Block until buffer is empty then stop the stream. */ -static PaError StopStream( PaStream *s ) -{ - PaError paErr; - PaMacCoreStream *stream = (PaMacCoreStream*)s; - VVDBUG(("StopStream()\n")); - - /* Tell WriteStream to stop filling the buffer. */ - stream->state = STOPPING; - - if( stream->userOutChan > 0 ) /* Does this stream do output? */ - { - size_t maxHostFrames = MAX( stream->inputFramesPerBuffer, stream->outputFramesPerBuffer ); - VDBUG( ("Waiting for write buffer to be drained.\n") ); - paErr = waitUntilBlioWriteBufferIsEmpty( &stream->blio, stream->sampleRate, - maxHostFrames ); - VDBUG( ( "waitUntilBlioWriteBufferIsEmpty returned %d\n", paErr ) ); - } - return FinishStoppingStream( stream ); -} - -/* Immediately stop the stream. */ -static PaError AbortStream( PaStream *s ) -{ - PaMacCoreStream *stream = (PaMacCoreStream*)s; - VDBUG( ( "AbortStream()\n" ) ); - stream->state = STOPPING; - return FinishStoppingStream( stream ); -} - - -static PaError IsStreamStopped( PaStream *s ) -{ - PaMacCoreStream *stream = (PaMacCoreStream*)s; - VVDBUG(("IsStreamStopped()\n")); - - return stream->state == STOPPED ? 1 : 0; -} - - -static PaError IsStreamActive( PaStream *s ) -{ - PaMacCoreStream *stream = (PaMacCoreStream*)s; - VVDBUG(("IsStreamActive()\n")); - return ( stream->state == ACTIVE || stream->state == STOPPING ); -} - - -static double GetStreamCpuLoad( PaStream* s ) -{ - PaMacCoreStream *stream = (PaMacCoreStream*)s; - VVDBUG(("GetStreamCpuLoad()\n")); - - return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer ); -} diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c b/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c deleted file mode 100644 index 70515f9..0000000 --- a/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.c +++ /dev/null @@ -1,638 +0,0 @@ -/* - * Implementation of the PortAudio API for Apple AUHAL - * - * PortAudio Portable Real-Time Audio Library - * Latest Version at: http://www.portaudio.com - * - * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code. - * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation) - * - * Dominic's code was based on code by Phil Burk, Darren Gibbs, - * Gord Peters, Stephane Letz, and Greg Pfiel. - * - * The following people also deserve acknowledgements: - * - * Olivier Tristan for feedback and testing - * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O - * interface. - * - * - * Based on the Open Source API proposed by Ross Bencina - * Copyright (c) 1999-2002 Ross Bencina, Phil Burk - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files - * (the "Software"), to deal in the Software without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -/* - * The text above constitutes the entire PortAudio license; however, - * the PortAudio community also makes the following non-binding requests: - * - * Any person wishing to distribute modifications to the Software is - * requested to send the modifications to the original developer so that - * they can be incorporated into the canonical version. It is also - * requested that these non-binding requests be included along with the - * license above. - */ - -/** - @file - @ingroup hostapi_src - - This file contains the implementation - required for blocking I/O. It is separated from pa_mac_core.c simply to ease - development. -*/ - -#include "pa_mac_core_blocking.h" -#include "pa_mac_core_internal.h" -#include <assert.h> -#ifdef MOSX_USE_NON_ATOMIC_FLAG_BITS -# define OSAtomicOr32( a, b ) ( (*(b)) |= (a) ) -# define OSAtomicAnd32( a, b ) ( (*(b)) &= (a) ) -#else -# include <libkern/OSAtomic.h> -#endif - -/* - * This function determines the size of a particular sample format. - * if the format is not recognized, this returns zero. - */ -static size_t computeSampleSizeFromFormat( PaSampleFormat format ) -{ - switch( format & (~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; - } -} - - -/* - * Functions for initializing, resetting, and destroying BLIO structures. - * - */ - -/** - * This should be called with the relevant info when initializing a stream for callback. - * - * @param ringBufferSizeInFrames must be a power of 2 - */ -PaError initializeBlioRingBuffers( - 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; -#ifdef PA_MAC_BLIO_MUTEX - blio->isInputEmpty = false; - blio->isOutputFull = false; -#endif - - /* setup ring buffers */ -#ifdef PA_MAC_BLIO_MUTEX - result = PaMacCore_SetUnixError( pthread_mutex_init(&(blio->inputMutex),NULL), 0 ); - if( result ) - goto error; - result = UNIX_ERR( pthread_cond_init( &(blio->inputCond), NULL ) ); - if( result ) - goto error; - result = UNIX_ERR( pthread_mutex_init(&(blio->outputMutex),NULL) ); - if( result ) - goto error; - result = UNIX_ERR( pthread_cond_init( &(blio->outputCond), NULL ) ); -#endif - if( inChan ) { - data = calloc( 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 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; -} -#endif - -/* This should be called after stopping or aborting the stream, so that on next - start, the buffers will be ready. */ -PaError resetBlioRingBuffers( PaMacBlio *blio ) -{ -#ifdef PA_MAC__BLIO_MUTEX - int result; -#endif - blio->statusFlags = 0; - if( blio->outputRingBuffer.buffer ) { - PaUtil_FlushRingBuffer( &blio->outputRingBuffer ); - /* 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; -#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. */ -#ifdef PA_MAC__BLIO_MUTEX - result = blioSetIsInputEmpty( blio, true ); - if( result ) - goto error; -#endif - } - return paNoError; -#ifdef PA_MAC__BLIO_MUTEX -error: - return result; -#endif -} - -/*This should be called when you are done with the blio. It can safely be called - multiple times if there are no exceptions. */ -PaError destroyBlioRingBuffers( PaMacBlio *blio ) -{ - PaError result = paNoError; - if( blio->inputRingBuffer.buffer ) { - free( blio->inputRingBuffer.buffer ); -#ifdef PA_MAC__BLIO_MUTEX - result = UNIX_ERR( pthread_mutex_destroy( & blio->inputMutex ) ); - if( result ) return result; - result = UNIX_ERR( pthread_cond_destroy( & blio->inputCond ) ); - if( result ) return result; -#endif - } - blio->inputRingBuffer.buffer = NULL; - if( blio->outputRingBuffer.buffer ) { - free( blio->outputRingBuffer.buffer ); -#ifdef PA_MAC__BLIO_MUTEX - result = UNIX_ERR( pthread_mutex_destroy( & blio->outputMutex ) ); - if( result ) return result; - result = UNIX_ERR( pthread_cond_destroy( & blio->outputCond ) ); - if( result ) return result; -#endif - } - blio->outputRingBuffer.buffer = NULL; - - return result; -} - -/* - * this is the BlioCallback function. It expects to receive a PaMacBlio Object - * pointer as userData. - * - */ -int BlioCallback( const void *input, void *output, unsigned long frameCount, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ) -{ - PaMacBlio *blio = (PaMacBlio*)userData; - 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 ); -#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 ); -#ifdef PA_MAC__BLIO_MUTEX - /* We have a priority inversion here. However, we will only have to - wait if this was true and is now false, which means we've got - some room in the buffer. - Hopefully problems will be minimized. */ - blioSetIsOutputFull( blio, false ); -#endif - } - - return paContinue; -} - -PaError ReadStream( PaStream* stream, - void *buffer, - unsigned long framesRequested ) -{ - PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio; - char *cbuf = (char *) buffer; - PaError ret = paNoError; - 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 ) { -#ifdef PA_MAC_BLIO_MUTEX - /**block when empty*/ - ret = UNIX_ERR( pthread_mutex_lock( &blio->inputMutex ) ); - if( ret ) - return ret; - while( blio->isInputEmpty ) { - ret = UNIX_ERR( pthread_cond_wait( &blio->inputCond, &blio->inputMutex ) ); - if( ret ) - return ret; - } - ret = UNIX_ERR( pthread_mutex_unlock( &blio->inputMutex ) ); - if( ret ) - return ret; -#else - Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL ); -#endif - } - } while( 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 ) - return ret; - } -#endif - } - } - - /* Report either paNoError or paInputOverflowed. */ - /* may also want to report other errors, but this is non-standard. */ - /* FIXME should not clobber ret, use if(blio->statusFlags & paInputOverflow) */ - ret = blio->statusFlags & paInputOverflow; - - /* report underflow only once: */ - if( ret ) { - OSAtomicAnd32( (uint32_t)(~paInputOverflow), &blio->statusFlags ); - ret = paInputOverflowed; - } - - return ret; -} - - -PaError WriteStream( PaStream* stream, - const void *buffer, - unsigned long framesRequested ) -{ - PaMacCoreStream *macStream = (PaMacCoreStream*)stream; - PaMacBlio *blio = &macStream->blio; - char *cbuf = (char *) buffer; - PaError ret = paNoError; - VVDBUG(("WriteStream()\n")); - - while( framesRequested > 0 && macStream->state != STOPPING ) { - ring_buffer_size_t framesAvailable; - 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 ) { -#ifdef PA_MAC_BLIO_MUTEX - /*block while full*/ - ret = UNIX_ERR( pthread_mutex_lock( &blio->outputMutex ) ); - if( ret ) - return ret; - while( blio->isOutputFull ) { - ret = UNIX_ERR( pthread_cond_wait( &blio->outputCond, &blio->outputMutex ) ); - if( ret ) - return ret; - } - ret = UNIX_ERR( pthread_mutex_unlock( &blio->outputMutex ) ); - if( ret ) - return ret; -#else - Pa_Sleep( PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL ); -#endif - } - } while( framesAvailable == 0 && macStream->state != STOPPING ); - - 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; - -#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 ) - return ret; - } - } -#endif - } - - if ( macStream->state == STOPPING ) - { - ret = paInternalError; - } - else if (ret == paNoError ) - { - /* Test for underflow. */ - ret = blio->statusFlags & paOutputUnderflow; - - /* report underflow only once: */ - if( ret ) - { - OSAtomicAnd32( (uint32_t)(~paOutputUnderflow), &blio->statusFlags ); - ret = paOutputUnderflowed; - } - } - - return ret; -} - -/* - * Wait until the data in the buffer has finished playing. - */ -PaError waitUntilBlioWriteBufferIsEmpty( PaMacBlio *blio, double sampleRate, - size_t framesPerBuffer ) -{ - PaError result = paNoError; - if( blio->outputRingBuffer.buffer ) { - ring_buffer_size_t framesLeft = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer ); - - /* Calculate when we should give up waiting. To be safe wait for two extra periods. */ - PaTime now = PaUtil_GetTime(); - PaTime startTime = now; - PaTime timeoutTime = startTime + (framesLeft + (2 * framesPerBuffer)) / sampleRate; - - long msecPerBuffer = 1 + (long)( 1000.0 * framesPerBuffer / sampleRate); - while( framesLeft > 0 && now < timeoutTime ) { - VDBUG(( "waitUntilBlioWriteBufferIsFlushed: framesLeft = %d, framesPerBuffer = %ld\n", - framesLeft, framesPerBuffer )); - Pa_Sleep( msecPerBuffer ); - framesLeft = PaUtil_GetRingBufferReadAvailable( &blio->outputRingBuffer ); - now = PaUtil_GetTime(); - } - - if( framesLeft > 0 ) - { - VDBUG(( "waitUntilBlioWriteBufferIsFlushed: TIMED OUT - framesLeft = %d\n", framesLeft )); - result = paTimedOut; - } - } - return result; -} - -signed long GetStreamReadAvailable( PaStream* stream ) -{ - PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio; - VVDBUG(("GetStreamReadAvailable()\n")); - - return PaUtil_GetRingBufferReadAvailable( &blio->inputRingBuffer ); -} - - -signed long GetStreamWriteAvailable( PaStream* stream ) -{ - PaMacBlio *blio = & ((PaMacCoreStream*)stream) -> blio; - VVDBUG(("GetStreamWriteAvailable()\n")); - - return PaUtil_GetRingBufferWriteAvailable( &blio->outputRingBuffer ); -} diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h b/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h deleted file mode 100644 index c0e564a..0000000 --- a/portaudio/src/hostapi/coreaudio/pa_mac_core_blocking.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Internal blocking interfaces for PortAudio Apple AUHAL implementation - * - * PortAudio Portable Real-Time Audio Library - * Latest Version at: http://www.portaudio.com - * - * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code. - * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation) - * - * Dominic's code was based on code by Phil Burk, Darren Gibbs, - * Gord Peters, Stephane Letz, and Greg Pfiel. - * - * The following people also deserve acknowledgements: - * - * Olivier Tristan for feedback and testing - * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O - * interface. - * - * - * Based on the Open Source API proposed by Ross Bencina - * Copyright (c) 1999-2002 Ross Bencina, Phil Burk - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files - * (the "Software"), to deal in the Software without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -/* - * The text above constitutes the entire PortAudio license; however, - * the PortAudio community also makes the following non-binding requests: - * - * Any person wishing to distribute modifications to the Software is - * requested to send the modifications to the original developer so that - * they can be incorporated into the canonical version. It is also - * requested that these non-binding requests be included along with the - * license above. - */ - -/** - @file - @ingroup hostapi_src -*/ - -#ifndef PA_MAC_CORE_BLOCKING_H_ -#define PA_MAC_CORE_BLOCKING_H_ - -#include "pa_ringbuffer.h" -#include "portaudio.h" -#include "pa_mac_core_utilities.h" - -/* - * Number of milliseconds to busy wait while waiting for data in blocking calls. - */ -#define PA_MAC_BLIO_BUSY_WAIT_SLEEP_INTERVAL (5) -/* - * Define exactly one of these blocking methods - * PA_MAC_BLIO_MUTEX is not actively maintained. - */ -#define PA_MAC_BLIO_BUSY_WAIT -/* -#define PA_MAC_BLIO_MUTEX -*/ - -typedef struct { - PaUtilRingBuffer inputRingBuffer; - PaUtilRingBuffer outputRingBuffer; - ring_buffer_size_t ringBufferFrames; - PaSampleFormat inputSampleFormat; - size_t inputSampleSizeActual; - size_t inputSampleSizePow2; - PaSampleFormat outputSampleFormat; - size_t outputSampleSizeActual; - size_t outputSampleSizePow2; - - int inChan; - int outChan; - - //PaStreamCallbackFlags statusFlags; - uint32_t statusFlags; - PaError errors; - - /* Here we handle blocking, using condition variables. */ -#ifdef PA_MAC_BLIO_MUTEX - volatile bool isInputEmpty; - pthread_mutex_t inputMutex; - pthread_cond_t inputCond; - - volatile bool isOutputFull; - pthread_mutex_t outputMutex; - pthread_cond_t outputCond; -#endif -} -PaMacBlio; - -/* - * These functions operate on condition and related variables. - */ - -PaError initializeBlioRingBuffers( - PaMacBlio *blio, - PaSampleFormat inputSampleFormat, - PaSampleFormat outputSampleFormat, - long ringBufferSizeInFrames, - int inChan, - int outChan ); -PaError destroyBlioRingBuffers( PaMacBlio *blio ); -PaError resetBlioRingBuffers( PaMacBlio *blio ); - -int BlioCallback( - const void *input, void *output, - unsigned long frameCount, - const PaStreamCallbackTimeInfo* timeInfo, - PaStreamCallbackFlags statusFlags, - void *userData ); - -PaError waitUntilBlioWriteBufferIsEmpty( PaMacBlio *blio, double sampleRate, - size_t framesPerBuffer ); - -#endif /*PA_MAC_CORE_BLOCKING_H_*/ diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h b/portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h deleted file mode 100644 index d4a97e0..0000000 --- a/portaudio/src/hostapi/coreaudio/pa_mac_core_internal.h +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Internal interfaces for PortAudio Apple AUHAL implementation - * - * PortAudio Portable Real-Time Audio Library - * Latest Version at: http://www.portaudio.com - * - * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code. - * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation) - * - * Dominic's code was based on code by Phil Burk, Darren Gibbs, - * Gord Peters, Stephane Letz, and Greg Pfiel. - * - * The following people also deserve acknowledgements: - * - * Olivier Tristan for feedback and testing - * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O - * interface. - * - * - * Based on the Open Source API proposed by Ross Bencina - * Copyright (c) 1999-2002 Ross Bencina, Phil Burk - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files - * (the "Software"), to deal in the Software without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -/* - * The text above constitutes the entire PortAudio license; however, - * the PortAudio community also makes the following non-binding requests: - * - * Any person wishing to distribute modifications to the Software is - * requested to send the modifications to the original developer so that - * they can be incorporated into the canonical version. It is also - * requested that these non-binding requests be included along with the - * license above. - */ - -/** - @file pa_mac_core - @ingroup hostapi_src - @author Bjorn Roche - @brief AUHAL implementation of PortAudio -*/ - -#ifndef PA_MAC_CORE_INTERNAL_H__ -#define PA_MAC_CORE_INTERNAL_H__ - -#include <CoreAudio/CoreAudio.h> -#include <CoreServices/CoreServices.h> -#include <AudioUnit/AudioUnit.h> -#include <AudioToolbox/AudioToolbox.h> - -#include "portaudio.h" -#include "pa_util.h" -#include "pa_hostapi.h" -#include "pa_stream.h" -#include "pa_allocation.h" -#include "pa_cpuload.h" -#include "pa_process.h" -#include "pa_ringbuffer.h" - -#include "pa_mac_core_blocking.h" - -/* function prototypes */ - -#ifdef __cplusplus -extern "C" -{ -#endif /* __cplusplus */ - -PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index ); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#define RING_BUFFER_ADVANCE_DENOMINATOR (4) - -PaError ReadStream( PaStream* stream, void *buffer, unsigned long frames ); -PaError WriteStream( PaStream* stream, const void *buffer, unsigned long frames ); -signed long GetStreamReadAvailable( PaStream* stream ); -signed long GetStreamWriteAvailable( PaStream* stream ); -/* PaMacAUHAL - host api datastructure specific to this implementation */ -typedef struct -{ - PaUtilHostApiRepresentation inheritedHostApiRep; - PaUtilStreamInterface callbackStreamInterface; - PaUtilStreamInterface blockingStreamInterface; - - PaUtilAllocationGroup *allocations; - - /* implementation specific data goes here */ - long devCount; - AudioDeviceID *devIds; /*array of all audio devices*/ - AudioDeviceID defaultIn; - AudioDeviceID defaultOut; -} -PaMacAUHAL; - -typedef struct PaMacCoreDeviceProperties -{ - /* Values in Frames from property queries. */ - UInt32 safetyOffset; - 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 - SR conversion. */ - Float64 sampleRate; - Float64 samplePeriod; // reciprocal -} -PaMacCoreDeviceProperties; - -/* stream data structure specifically for this implementation */ -typedef struct PaMacCoreStream -{ - PaUtilStreamRepresentation streamRepresentation; - PaUtilCpuLoadMeasurer cpuLoadMeasurer; - PaUtilBufferProcessor bufferProcessor; - - /* implementation specific data goes here */ - bool bufferProcessorIsInitialized; - AudioUnit inputUnit; - AudioUnit outputUnit; - AudioDeviceID inputDevice; - AudioDeviceID outputDevice; - size_t userInChan; - size_t userOutChan; - size_t inputFramesPerBuffer; - size_t outputFramesPerBuffer; - PaMacBlio blio; - /* We use this ring buffer when input and out devs are different. */ - PaUtilRingBuffer inputRingBuffer; - /* We may need to do SR conversion on input. */ - AudioConverterRef inputSRConverter; - /* We need to preallocate an inputBuffer for reading data. */ - AudioBufferList inputAudioBufferList; - AudioTimeStamp startTime; - /* FIXME: instead of volatile, these should be properly memory barriered */ - volatile uint32_t xrunFlags; /*PaStreamCallbackFlags*/ - volatile enum { - STOPPED = 0, /* playback is completely stopped, - and the user has called StopStream(). */ - CALLBACK_STOPPED = 1, /* callback has requested stop, - but user has not yet called StopStream(). */ - STOPPING = 2, /* The stream is in the process of closing - 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. */ - } state; - double sampleRate; - PaMacCoreDeviceProperties inputProperties; - PaMacCoreDeviceProperties outputProperties; - - /* 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. - * 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; - -#endif /* PA_MAC_CORE_INTERNAL_H__ */ diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c b/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c deleted file mode 100644 index 0d3b183..0000000 --- a/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.c +++ /dev/null @@ -1,814 +0,0 @@ -/* - * Helper and utility functions for pa_mac_core.c (Apple AUHAL implementation) - * - * PortAudio Portable Real-Time Audio Library - * Latest Version at: http://www.portaudio.com - * - * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code. - * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation) - * - * Dominic's code was based on code by Phil Burk, Darren Gibbs, - * Gord Peters, Stephane Letz, and Greg Pfiel. - * - * The following people also deserve acknowledgements: - * - * Olivier Tristan for feedback and testing - * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O - * interface. - * - * - * Based on the Open Source API proposed by Ross Bencina - * Copyright (c) 1999-2002 Ross Bencina, Phil Burk - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files - * (the "Software"), to deal in the Software without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -/* - * The text above constitutes the entire PortAudio license; however, - * the PortAudio community also makes the following non-binding requests: - * - * Any person wishing to distribute modifications to the Software is - * requested to send the modifications to the original developer so that - * they can be incorporated into the canonical version. It is also - * requested that these non-binding requests be included along with the - * license above. - */ - -/** - @file - @ingroup hostapi_src -*/ - -#include "pa_mac_core_utilities.h" -#include "pa_mac_core_internal.h" -#include <libkern/OSAtomic.h> -#include <strings.h> -#include <pthread.h> -#include <sys/time.h> - -OSStatus PaMacCore_AudioHardwareGetProperty( - 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 ) -{ - 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 ) -{ - 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 ) -{ - AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; - AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel }; - return AudioObjectSetPropertyData(inDevice, &address, 0, NULL, inPropertyDataSize, inPropertyData); -} - -OSStatus PaMacCore_AudioDeviceGetPropertySize( - AudioDeviceID inDevice, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - UInt32* outSize ) -{ - AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; - AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel }; - return AudioObjectGetPropertyDataSize(inDevice, &address, 0, NULL, outSize); -} - -OSStatus PaMacCore_AudioDeviceAddPropertyListener( - AudioDeviceID inDevice, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - AudioObjectPropertyListenerProc inProc, - void* inClientData ) -{ - AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; - AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel }; - return AudioObjectAddPropertyListener(inDevice, &address, inProc, inClientData); -} - -OSStatus PaMacCore_AudioDeviceRemovePropertyListener( - AudioDeviceID inDevice, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - AudioObjectPropertyListenerProc inProc, - void* inClientData ) -{ - AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput; - AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel }; - return AudioObjectRemovePropertyListener(inDevice, &address, inProc, inClientData); -} - -OSStatus PaMacCore_AudioStreamGetProperty( - AudioStreamID inStream, - UInt32 inChannel, - AudioDevicePropertyID inPropertyID, - UInt32* ioPropertyDataSize, - void* outPropertyData ) -{ - AudioObjectPropertyAddress address = { inPropertyID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster }; - return AudioObjectGetPropertyData(inStream, &address, 0, NULL, ioPropertyDataSize, outPropertyData); -} - -PaError PaMacCore_SetUnixError( int err, int line ) -{ - PaError ret; - const char *errorText; - - if( err == 0 ) - { - return paNoError; - } - - ret = paNoError; - errorText = strerror( err ); - - /** Map Unix error to PaError. Pretty much the only one that maps - is ENOMEM. */ - if( err == ENOMEM ) - ret = paInsufficientMemory; - else - ret = paInternalError; - - DBUG(("%d on line %d: msg='%s'\n", err, line, errorText)); - PaUtil_SetLastHostErrorInfo( paCoreAudio, err, errorText ); - - return ret; -} - -/* - * Translates MacOS generated errors into PaErrors - */ -PaError PaMacCore_SetError(OSStatus error, int line, int isError) -{ - /*FIXME: still need to handle possible ComponentResult values.*/ - /* unfortunately, they don't seem to be documented anywhere.*/ - PaError result; - const char *errorType; - const char *errorText; - - switch (error) { - case kAudioHardwareNoError: - return paNoError; - case kAudioHardwareNotRunningError: - errorText = "Audio Hardware Not Running"; - result = paInternalError; - break; - case kAudioHardwareUnspecifiedError: - errorText = "Unspecified Audio Hardware Error"; - result = paInternalError; - break; - case kAudioHardwareUnknownPropertyError: - errorText = "Audio Hardware: Unknown Property"; - result = paInternalError; - break; - case kAudioHardwareBadPropertySizeError: - errorText = "Audio Hardware: Bad Property Size"; - result = paInternalError; - break; - case kAudioHardwareIllegalOperationError: - errorText = "Audio Hardware: Illegal Operation"; - result = paInternalError; - break; - case kAudioHardwareBadDeviceError: - errorText = "Audio Hardware: Bad Device"; - result = paInvalidDevice; - break; - case kAudioHardwareBadStreamError: - errorText = "Audio Hardware: BadStream"; - result = paBadStreamPtr; - break; - case kAudioHardwareUnsupportedOperationError: - errorText = "Audio Hardware: Unsupported Operation"; - result = paInternalError; - break; - case kAudioDeviceUnsupportedFormatError: - errorText = "Audio Device: Unsupported Format"; - result = paSampleFormatNotSupported; - break; - case kAudioDevicePermissionsError: - errorText = "Audio Device: Permissions Error"; - result = paDeviceUnavailable; - break; - /* Audio Unit Errors: http://developer.apple.com/documentation/MusicAudio/Reference/CoreAudio/audio_units/chapter_5_section_3.html */ - case kAudioUnitErr_InvalidProperty: - errorText = "Audio Unit: Invalid Property"; - result = paInternalError; - break; - case kAudioUnitErr_InvalidParameter: - errorText = "Audio Unit: Invalid Parameter"; - result = paInternalError; - break; - case kAudioUnitErr_NoConnection: - errorText = "Audio Unit: No Connection"; - result = paInternalError; - break; - case kAudioUnitErr_FailedInitialization: - errorText = "Audio Unit: Initialization Failed"; - result = paInternalError; - break; - case kAudioUnitErr_TooManyFramesToProcess: - errorText = "Audio Unit: Too Many Frames"; - result = paInternalError; - break; - case kAudioUnitErr_InvalidFile: - errorText = "Audio Unit: Invalid File"; - result = paInternalError; - break; - case kAudioUnitErr_UnknownFileType: - errorText = "Audio Unit: Unknown File Type"; - result = paInternalError; - break; - case kAudioUnitErr_FileNotSpecified: - errorText = "Audio Unit: File Not Specified"; - result = paInternalError; - break; - case kAudioUnitErr_FormatNotSupported: - errorText = "Audio Unit: Format Not Supported"; - result = paInternalError; - break; - case kAudioUnitErr_Uninitialized: - errorText = "Audio Unit: Uninitialized"; - result = paInternalError; - break; - case kAudioUnitErr_InvalidScope: - errorText = "Audio Unit: Invalid Scope"; - result = paInternalError; - break; - case kAudioUnitErr_PropertyNotWritable: - errorText = "Audio Unit: PropertyNotWritable"; - result = paInternalError; - break; - case kAudioUnitErr_InvalidPropertyValue: - errorText = "Audio Unit: Invalid Property Value"; - result = paInternalError; - break; - case kAudioUnitErr_PropertyNotInUse: - errorText = "Audio Unit: Property Not In Use"; - result = paInternalError; - break; - case kAudioUnitErr_Initialized: - errorText = "Audio Unit: Initialized"; - result = paInternalError; - break; - case kAudioUnitErr_InvalidOfflineRender: - errorText = "Audio Unit: Invalid Offline Render"; - result = paInternalError; - break; - case kAudioUnitErr_Unauthorized: - errorText = "Audio Unit: Unauthorized"; - result = paInternalError; - break; - case kAudioUnitErr_CannotDoInCurrentContext: - errorText = "Audio Unit: cannot do in current context"; - result = paInternalError; - break; - default: - errorText = "Unknown Error"; - result = paInternalError; - } - - if (isError) - errorType = "Error"; - else - errorType = "Warning"; - - char str[20]; - // see if it appears to be a 4-char-code - *(UInt32 *)(str + 1) = CFSwapInt32HostToBig(error); - if (isprint(str[1]) && isprint(str[2]) && isprint(str[3]) && isprint(str[4])) - { - str[0] = str[5] = '\''; - str[6] = '\0'; - } else { - // no, format it as an integer - sprintf(str, "%d", (int)error); - } - - DBUG(("%s on line %d: err='%s', msg=%s\n", errorType, line, str, errorText)); - - PaUtil_SetLastHostErrorInfo( paCoreAudio, error, errorText ); - - return result; -} - -/* - * This function computes an appropriate ring buffer size given - * a requested latency (in seconds), sample rate and framesPerBuffer. - * - * The returned ringBufferSize is computed using the following - * constraints: - * - it must be at least 4. - * - it must be at least 3x framesPerBuffer. - * - it must be at least 2x the suggestedLatency. - * - it must be a power of 2. - * This function attempts to compute the minimum such size. - * - * FEEDBACK: too liberal/conservative/another way? - */ -long computeRingBufferSize( const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, - long inputFramesPerBuffer, - long outputFramesPerBuffer, - double sampleRate ) -{ - long ringSize; - int index; - int i; - double 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<sizeof(long)*8; ++i ) - if( ringSize >> i & 0x01 ) - index = i; - assert( index > 0 ); - if( ringSize <= ( 0x01 << index ) ) - ringSize = 0x01 << index ; - else - ringSize = 0x01 << ( index + 1 ); - - VDBUG(( "Final Ringbuffer size (2): %d\n", (int)ringSize )); - return ringSize; -} - - -/* - * During testing of core audio, I found that serious crashes could occur - * if properties such as sample rate were changed multiple times in rapid - * succession. The function below could be used to with a condition variable. - * to prevent propertychanges from happening until the last property - * change is acknowledged. Instead, I implemented a busy-wait, which is simpler - * to implement b/c in second round of testing (nov '09) property changes occurred - * quickly and so there was no real way to test the condition variable implementation. - * therefore, this function is not used, but it is aluded to in commented code below, - * since it represents a theoretically better implementation. - */ - -OSStatus propertyProc( - AudioObjectID inObjectID, - UInt32 inNumberAddresses, - const AudioObjectPropertyAddress* inAddresses, - void* inClientData ) -{ - // this is where we would set the condition variable - return noErr; -} - -/* sets the value of the given property and waits for the change to - be acknowledged, and returns the final value, which is not guaranteed - by this function to be the same as the desired value. Obviously, this - function can only be used for data whose input and output are the - same size and format, and their size and format are known in advance. - whether or not the call succeeds, if the data is successfully read, - it is returned in outPropertyData. If it is not read successfully, - 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 ) -{ - 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 ); -} - -/* - * Sets the sample rate the HAL device. - * if requireExact: set the sample rate or fail. - * - * otherwise : set the exact sample rate. - * If that fails, check for available sample rates, and choose one - * higher than the requested rate. If there isn't a higher one, - * just use the highest available. - */ -PaError setBestSampleRateForDevice( const AudioDeviceID device, - const bool isOutput, - const bool requireExact, - const Float64 desiredSrate ) -{ - 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<propsize/sizeof(AudioValueRange); ++i ) - VDBUG( ("\t%g-%g\n", - (float) ranges[i].mMinimum, - (float) ranges[i].mMaximum ) ); -#endif - VDBUG(("-----\n")); - - /* -- now pick the best available sample rate -- */ - for( i=0; i<propsize/sizeof(AudioValueRange); ++i ) - { - if( ranges[i].mMaximum > max ) max = ranges[i].mMaximum; - if( ranges[i].mMinimum > desiredSrate ) { - if( best < 0 ) - best = ranges[i].mMinimum; - else if( ranges[i].mMinimum < best ) - best = ranges[i].mMinimum; - } - } - if( best < 0 ) - best = max; - VDBUG( ("Maximum Rate %g. best is %g.\n", max, best ) ); - free( ranges ); - - /* -- set the sample rate -- */ - propsize = sizeof( best ); - 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; -} - - -/* - Attempts to set the requestedFramesPerBuffer. If it can't set the exact - value, it settles for something smaller if available. If nothing smaller - is available, it uses the smallest available size. - actualFramesPerBuffer will be set to the actual value on successful return. - OK to pass NULL to actualFramesPerBuffer. - The logic is very similar too setBestSampleRate only failure here is - not usually catastrophic. -*/ -PaError setBestFramesPerBuffer( const AudioDeviceID device, - const bool isOutput, - UInt32 requestedFramesPerBuffer, - UInt32 *actualFramesPerBuffer ) -{ - UInt32 afpb; - const bool isInput = !isOutput; - UInt32 propsize = sizeof(UInt32); - OSErr err; - AudioValueRange range; - - if( actualFramesPerBuffer == NULL ) - { - actualFramesPerBuffer = &afpb; - } - - /* -- try and set exact FPB -- */ - err = PaMacCore_AudioDeviceSetProperty( device, NULL, 0, isInput, - kAudioDevicePropertyBufferFrameSize, - propsize, &requestedFramesPerBuffer); - err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput, - kAudioDevicePropertyBufferFrameSize, - &propsize, actualFramesPerBuffer); - if( err ) - { - return ERR( err ); - } - // Did we get the size we asked for? - if( *actualFramesPerBuffer == requestedFramesPerBuffer ) - { - 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 ); - if( err ) - { - return ERR( err ); - } - if( requestedFramesPerBuffer < range.mMinimum ) - { - requestedFramesPerBuffer = range.mMinimum; - } - else if( requestedFramesPerBuffer > range.mMaximum ) - { - requestedFramesPerBuffer = range.mMaximum; - } - - /* --- 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; -} - -/********************** - * - * XRun stuff - * - **********************/ - -struct PaMacXRunListNode_s { - PaMacCoreStream *stream; - struct PaMacXRunListNode_s *next; -} ; - -typedef struct PaMacXRunListNode_s PaMacXRunListNode; - -/** Always empty, so that it can always be the one returned by - addToXRunListenerList. note that it's not a pointer. */ -static PaMacXRunListNode firstXRunListNode; -static int xRunListSize; -static pthread_mutex_t xrunMutex; - -OSStatus xrunCallback( - AudioObjectID inDevice, - UInt32 inNumberAddresses, - const AudioObjectPropertyAddress* inAddresses, - void * inClientData) -{ - PaMacXRunListNode *node = (PaMacXRunListNode *) inClientData; - bool isInput = inAddresses->mScope == kAudioDevicePropertyScopeInput; - - int ret = pthread_mutex_trylock( &xrunMutex ) ; - - if( ret == 0 ) { - - node = node->next ; //skip the first node - - 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( isInput ) { - if( stream->inputDevice == inDevice ) - OSAtomicOr32( paInputOverflow, &stream->xrunFlags ); - } else { - if( stream->outputDevice == inDevice ) - OSAtomicOr32( paOutputUnderflow, &stream->xrunFlags ); - } - } - - pthread_mutex_unlock( &xrunMutex ); - } - - return 0; -} - -int initializeXRunListenerList( void ) -{ - 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 ); -} - -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; -} - -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; -} diff --git a/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h b/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h deleted file mode 100644 index c305f17..0000000 --- a/portaudio/src/hostapi/coreaudio/pa_mac_core_utilities.h +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Helper and utility functions for pa_mac_core.c (Apple AUHAL implementation) - * - * PortAudio Portable Real-Time Audio Library - * Latest Version at: http://www.portaudio.com - * - * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code. - * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation) - * - * Dominic's code was based on code by Phil Burk, Darren Gibbs, - * Gord Peters, Stephane Letz, and Greg Pfiel. - * - * The following people also deserve acknowledgements: - * - * Olivier Tristan for feedback and testing - * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O - * interface. - * - * - * Based on the Open Source API proposed by Ross Bencina - * Copyright (c) 1999-2002 Ross Bencina, Phil Burk - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files - * (the "Software"), to deal in the Software without restriction, - * including without limitation the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice shall be - * included in all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR - * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -/* - * The text above constitutes the entire PortAudio license; however, - * the PortAudio community also makes the following non-binding requests: - * - * Any person wishing to distribute modifications to the Software is - * requested to send the modifications to the original developer so that - * they can be incorporated into the canonical version. It is also - * requested that these non-binding requests be included along with the - * license above. - */ - -/** - @file - @ingroup hostapi_src -*/ - -#ifndef PA_MAC_CORE_UTILITIES_H__ -#define PA_MAC_CORE_UTILITIES_H__ - -#include <pthread.h> -#include "portaudio.h" -#include "pa_util.h" -#include <AudioUnit/AudioUnit.h> -#include <AudioToolbox/AudioToolbox.h> - -#ifndef MIN -#define MIN(a, b) (((a)<(b))?(a):(b)) -#endif - -#ifndef MAX -#define MAX(a, b) (((a)<(b))?(b):(a)) -#endif - -#define ERR(mac_error) PaMacCore_SetError(mac_error, __LINE__, 1 ) -#define WARNING(mac_error) PaMacCore_SetError(mac_error, __LINE__, 0 ) - - -/* Help keep track of AUHAL element numbers */ -#define INPUT_ELEMENT (1) -#define OUTPUT_ELEMENT (0) - -/* Normal level of debugging: fine for most apps that don't mind the occasional warning being printf'ed */ -/* - */ -#define MAC_CORE_DEBUG -#ifdef MAC_CORE_DEBUG -# define DBUG(MSG) do { printf("||PaMacCore (AUHAL)|| "); printf MSG ; fflush(stdout); } while(0) -#else -# define DBUG(MSG) -#endif - -/* Verbose Debugging: useful for development */ -/* -#define MAC_CORE_VERBOSE_DEBUG -*/ -#ifdef MAC_CORE_VERBOSE_DEBUG -# define VDBUG(MSG) do { printf("||PaMacCore (v )|| "); printf MSG ; fflush(stdout); } while(0) -#else -# define VDBUG(MSG) -#endif - -/* Very Verbose Debugging: Traces every call. */ -/* -#define MAC_CORE_VERY_VERBOSE_DEBUG - */ -#ifdef MAC_CORE_VERY_VERBOSE_DEBUG -# define VVDBUG(MSG) do { printf("||PaMacCore (vv)|| "); printf MSG ; fflush(stdout); } while(0) -#else -# define VVDBUG(MSG) -#endif - -OSStatus PaMacCore_AudioHardwareGetProperty( - AudioHardwarePropertyID inPropertyID, - UInt32* ioPropertyDataSize, - void* outPropertyData ); - -OSStatus PaMacCore_AudioHardwareGetPropertySize( - AudioHardwarePropertyID inPropertyID, - UInt32* outSize ); - -OSStatus PaMacCore_AudioDeviceGetProperty( - AudioDeviceID inDevice, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - UInt32* ioPropertyDataSize, - void* outPropertyData ); - -OSStatus PaMacCore_AudioDeviceSetProperty( - AudioDeviceID inDevice, - const AudioTimeStamp* inWhen, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - UInt32 inPropertyDataSize, - const void* inPropertyData ); - -OSStatus PaMacCore_AudioDeviceGetPropertySize( - AudioDeviceID inDevice, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - UInt32* outSize ); - -OSStatus PaMacCore_AudioDeviceAddPropertyListener( - AudioDeviceID inDevice, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - AudioObjectPropertyListenerProc inProc, - void* inClientData ); - -OSStatus PaMacCore_AudioDeviceRemovePropertyListener( - AudioDeviceID inDevice, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - AudioObjectPropertyListenerProc inProc, - void* inClientData ); - -OSStatus PaMacCore_AudioStreamGetProperty( - AudioStreamID inStream, - UInt32 inChannel, - AudioDevicePropertyID inPropertyID, - UInt32* ioPropertyDataSize, - void* outPropertyData ); - -#define UNIX_ERR(err) PaMacCore_SetUnixError( err, __LINE__ ) - -PaError PaMacCore_SetUnixError( int err, int line ); - -/* - * Translates MacOS generated errors into PaErrors - */ -PaError PaMacCore_SetError(OSStatus error, int line, int isError); - -/* - * This function computes an appropriate ring buffer size given - * a requested latency (in seconds), sample rate and framesPerBuffer. - * - * The returned ringBufferSize is computed using the following - * constraints: - * - it must be at least 4. - * - it must be at least 3x framesPerBuffer. - * - it must be at least 2x the suggestedLatency. - * - it must be a power of 2. - * This function attempts to compute the minimum such size. - * - */ -long computeRingBufferSize( const PaStreamParameters *inputParameters, - const PaStreamParameters *outputParameters, - long inputFramesPerBuffer, - long outputFramesPerBuffer, - double sampleRate ); - -OSStatus propertyProc( - AudioObjectID inObjectID, - UInt32 inNumberAddresses, - const AudioObjectPropertyAddress* inAddresses, - void* inClientData ); - -/* sets the value of the given property and waits for the change to - be acknowledged, and returns the final value, which is not guaranteed - by this function to be the same as the desired value. Obviously, this - function can only be used for data whose input and output are the - same size and format, and their size and format are known in advance.*/ -PaError AudioDeviceSetPropertyNowAndWaitForChange( - AudioDeviceID inDevice, - UInt32 inChannel, - Boolean isInput, - AudioDevicePropertyID inPropertyID, - UInt32 inPropertyDataSize, - const void *inPropertyData, - void *outPropertyData ); - -/* - * Sets the sample rate the HAL device. - * if requireExact: set the sample rate or fail. - * - * otherwise : set the exact sample rate. - * If that fails, check for available sample rates, and choose one - * higher than the requested rate. If there isn't a higher one, - * just use the highest available. - */ -PaError setBestSampleRateForDevice( const AudioDeviceID device, - const bool isOutput, - const bool requireExact, - const Float64 desiredSrate ); -/* - Attempts to set the requestedFramesPerBuffer. If it can't set the exact - value, it settles for something smaller if available. If nothing smaller - is available, it uses the smallest available size. - actualFramesPerBuffer will be set to the actual value on successful return. - OK to pass NULL to actualFramesPerBuffer. - The logic is very similar too setBestSampleRate only failure here is - not usually catastrophic. -*/ -PaError setBestFramesPerBuffer( const AudioDeviceID device, - const bool isOutput, - UInt32 requestedFramesPerBuffer, - UInt32 *actualFramesPerBuffer ); - - -/********************* - * - * xrun handling - * - *********************/ - -OSStatus xrunCallback( - AudioObjectID inObjectID, - UInt32 inNumberAddresses, - const AudioObjectPropertyAddress* inAddresses, - void * inClientData ); - -/** returns zero on success or a unix style error code. */ -int initializeXRunListenerList( void ); -/** returns zero on success or a unix style error code. */ -int destroyXRunListenerList( void ); - -/**Returns the list, so that it can be passed to CorAudio.*/ -void *addToXRunListenerList( void *stream ); -/**Returns the number of Listeners in the list remaining.*/ -int removeFromXRunListenerList( void *stream ); - -#endif /* PA_MAC_CORE_UTILITIES_H__*/ |