Debian Codegraph @

external/portaudio/pa_mac_core.c

raw
1 /*
2 * Implementation of the PortAudio API for Apple AUHAL
3 *
4 * PortAudio Portable Real-Time Audio Library
5 * Latest Version at: http://www.portaudio.com
6 *
7 * Written by Bjorn Roche of XO Audio LLC, from PA skeleton code.
8 * Portions copied from code by Dominic Mazzoni (who wrote a HAL implementation)
9 *
10 * Dominic's code was based on code by Phil Burk, Darren Gibbs,
11 * Gord Peters, Stephane Letz, and Greg Pfiel.
12 *
13 * The following people also deserve acknowledgements:
14 *
15 * Olivier Tristan for feedback and testing
16 * Glenn Zelniker and Z-Systems engineering for sponsoring the Blocking I/O
17 * interface.
18 *
19 *
20 * Based on the Open Source API proposed by Ross Bencina
21 * Copyright (c) 1999-2002 Ross Bencina, Phil Burk
22 *
23 * Permission is hereby granted, free of charge, to any person obtaining
24 * a copy of this software and associated documentation files
25 * (the "Software"), to deal in the Software without restriction,
26 * including without limitation the rights to use, copy, modify, merge,
27 * publish, distribute, sublicense, and/or sell copies of the Software,
28 * and to permit persons to whom the Software is furnished to do so,
29 * subject to the following conditions:
30 *
31 * The above copyright notice and this permission notice shall be
32 * included in all copies or substantial portions of the Software.
33 *
34 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
35 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
36 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
37 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
38 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
39 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
40 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
41 */
42
43 /*
44 * The text above constitutes the entire PortAudio license; however,
45 * the PortAudio community also makes the following non-binding requests:
46 *
47 * Any person wishing to distribute modifications to the Software is
48 * requested to send the modifications to the original developer so that
49 * they can be incorporated into the canonical version. It is also
50 * requested that these non-binding requests be included along with the
51 * license above.
52 */
53
54 /**
55 @file pa_mac_core
56 @ingroup hostapi_src
57 @author Bjorn Roche
58 @brief AUHAL implementation of PortAudio
59 */
60
61 /* FIXME: not all error conditions call PaUtil_SetLastHostErrorInfo()
62 * PaMacCore_SetError() will do this.
63 */
64
65 #include "pa_mac_core_internal.h"
66
67 #include <string.h> /* strlen(), memcmp() etc. */
68 #include <libkern/OSAtomic.h>
69
70 #include "pa_mac_core.h"
71 #include "pa_mac_core_utilities.h"
72 #include "pa_mac_core_blocking.h"
73
74 #ifndef MAC_OS_X_VERSION_10_6
75 #define MAC_OS_X_VERSION_10_6 1060
76 #endif
77
78
79 #ifdef __cplusplus
80 extern "C"
81 {
82 #endif /* __cplusplus */
83
84 /* This is a reasonable size for a small buffer based on experience. */
85 #define PA_MAC_SMALL_BUFFER_SIZE (64)
86
87 /* prototypes for functions declared in this file */
88 PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex index );
89
90 /*
91 * Function declared in pa_mac_core.h. Sets up a PaMacCoreStreamInfoStruct
92 * with the requested flags and initializes channel map.
93 */
94 void PaMacCore_SetupStreamInfo( PaMacCoreStreamInfo *data, const unsigned long flags )
95 {
96 bzero( data, sizeof( PaMacCoreStreamInfo ) );
97 data->size = sizeof( PaMacCoreStreamInfo );
98 data->hostApiType = paCoreAudio;
99 data->version = 0x01;
100 data->flags = flags;
101 data->channelMap = NULL;
102 data->channelMapSize = 0;
103 }
104
105 /*
106 * Function declared in pa_mac_core.h. Adds channel mapping to a PaMacCoreStreamInfoStruct
107 */
108 void PaMacCore_SetupChannelMap( PaMacCoreStreamInfo *data, const SInt32 * const channelMap, const unsigned long channelMapSize )
109 {
110 data->channelMap = channelMap;
111 data->channelMapSize = channelMapSize;
112 }
113 static char *channelName = NULL;
114 static int channelNameSize = 0;
115 static bool ensureChannelNameSize( int size )
116 {
117 if( size >= channelNameSize ) {
118 free( channelName );
119 channelName = (char *) malloc( ( channelNameSize = size ) + 1 );
120 if( !channelName ) {
121 channelNameSize = 0;
122 return false;
123 }
124 }
125 return true;
126 }
127 /*
128 * Function declared in pa_mac_core.h. retrieves channel names.
129 */
130 const char *PaMacCore_GetChannelName( int device, int channelIndex, bool input )
131 {
132 struct PaUtilHostApiRepresentation *hostApi;
133 PaError err;
134 OSStatus error;
135 err = PaUtil_GetHostApiRepresentation( &hostApi, paCoreAudio );
136 assert(err == paNoError);
137 if( err != paNoError )
138 return NULL;
139 PaMacAUHAL *macCoreHostApi = (PaMacAUHAL*)hostApi;
140 AudioDeviceID hostApiDevice = macCoreHostApi->devIds[device];
141 CFStringRef nameRef;
142
143 /* First try with CFString */
144 UInt32 size = sizeof(nameRef);
145 error = PaMacCore_AudioDeviceGetProperty( hostApiDevice,
146 channelIndex + 1,
147 input,
148 kAudioDevicePropertyChannelNameCFString,
149 &size,
150 &nameRef );
151 if( error )
152 {
153 /* try the C String */
154 size = 0;
155 error = PaMacCore_AudioDeviceGetPropertySize( hostApiDevice,
156 channelIndex + 1,
157 input,
158 kAudioDevicePropertyChannelName,
159 &size );
160 if( !error )
161 {
162 if( !ensureChannelNameSize( size ) )
163 return NULL;
164
165 error = PaMacCore_AudioDeviceGetProperty( hostApiDevice,
166 channelIndex + 1,
167 input,
168 kAudioDevicePropertyChannelName,
169 &size,
170 channelName );
171
172
173 if( !error )
174 return channelName;
175 }
176
177 /* as a last-ditch effort, we use the device name and append the channel number. */
178 nameRef = CFStringCreateWithFormat( NULL, NULL, CFSTR( "%s: %d"), hostApi->deviceInfos[device]->name, channelIndex + 1 );
179
180
181 size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef), kCFStringEncodingUTF8);;
182 if( !ensureChannelNameSize( size ) )
183 {
184 CFRelease( nameRef );
185 return NULL;
186 }
187 CFStringGetCString( nameRef, channelName, size+1, kCFStringEncodingUTF8 );
188 CFRelease( nameRef );
189 }
190 else
191 {
192 size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef), kCFStringEncodingUTF8);;
193 if( !ensureChannelNameSize( size ) )
194 {
195 CFRelease( nameRef );
196 return NULL;
197 }
198 CFStringGetCString( nameRef, channelName, size+1, kCFStringEncodingUTF8 );
199 CFRelease( nameRef );
200 }
201
202 return channelName;
203 }
204
205
206 PaError PaMacCore_GetBufferSizeRange( PaDeviceIndex device,
207 long *minBufferSizeFrames, long *maxBufferSizeFrames )
208 {
209 PaError result;
210 PaUtilHostApiRepresentation *hostApi;
211
212 result = PaUtil_GetHostApiRepresentation( &hostApi, paCoreAudio );
213
214 if( result == paNoError )
215 {
216 PaDeviceIndex hostApiDeviceIndex;
217 result = PaUtil_DeviceIndexToHostApiDeviceIndex( &hostApiDeviceIndex, device, hostApi );
218 if( result == paNoError )
219 {
220 PaMacAUHAL *macCoreHostApi = (PaMacAUHAL*)hostApi;
221 AudioDeviceID macCoreDeviceId = macCoreHostApi->devIds[hostApiDeviceIndex];
222 AudioValueRange audioRange;
223 UInt32 propSize = sizeof( audioRange );
224
225 // return the size range for the output scope unless we only have inputs
226 Boolean isInput = 0;
227 if( macCoreHostApi->inheritedHostApiRep.deviceInfos[hostApiDeviceIndex]->maxOutputChannels == 0 )
228 isInput = 1;
229
230 result = WARNING(PaMacCore_AudioDeviceGetProperty( macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &audioRange ) );
231
232 *minBufferSizeFrames = audioRange.mMinimum;
233 *maxBufferSizeFrames = audioRange.mMaximum;
234 }
235 }
236
237 return result;
238 }
239
240
241 AudioDeviceID PaMacCore_GetStreamInputDevice( PaStream* s )
242 {
243 PaMacCoreStream *stream = (PaMacCoreStream*)s;
244 VVDBUG(("PaMacCore_GetStreamInputHandle()\n"));
245
246 return ( stream->inputDevice );
247 }
248
249 AudioDeviceID PaMacCore_GetStreamOutputDevice( PaStream* s )
250 {
251 PaMacCoreStream *stream = (PaMacCoreStream*)s;
252 VVDBUG(("PaMacCore_GetStreamOutputHandle()\n"));
253
254 return ( stream->outputDevice );
255 }
256
257 #ifdef __cplusplus
258 }
259 #endif /* __cplusplus */
260
261 #define RING_BUFFER_ADVANCE_DENOMINATOR (4)
262
263 static void Terminate( struct PaUtilHostApiRepresentation *hostApi );
264 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
265 const PaStreamParameters *inputParameters,
266 const PaStreamParameters *outputParameters,
267 double sampleRate );
268 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
269 PaStream** s,
270 const PaStreamParameters *inputParameters,
271 const PaStreamParameters *outputParameters,
272 double sampleRate,
273 unsigned long framesPerBuffer,
274 PaStreamFlags streamFlags,
275 PaStreamCallback *streamCallback,
276 void *userData );
277 static PaError CloseStream( PaStream* stream );
278 static PaError StartStream( PaStream *stream );
279 static PaError StopStream( PaStream *stream );
280 static PaError AbortStream( PaStream *stream );
281 static PaError IsStreamStopped( PaStream *s );
282 static PaError IsStreamActive( PaStream *stream );
283 static PaTime GetStreamTime( PaStream *stream );
284 static OSStatus AudioIOProc( void *inRefCon,
285 AudioUnitRenderActionFlags *ioActionFlags,
286 const AudioTimeStamp *inTimeStamp,
287 UInt32 inBusNumber,
288 UInt32 inNumberFrames,
289 AudioBufferList *ioData );
290 static double GetStreamCpuLoad( PaStream* stream );
291
292 static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi,
293 PaDeviceInfo *deviceInfo,
294 AudioDeviceID macCoreDeviceId,
295 int isInput);
296
297 static PaError OpenAndSetupOneAudioUnit( const PaMacCoreStream *stream,
298 const PaStreamParameters *inStreamParams,
299 const PaStreamParameters *outStreamParams,
300 const UInt32 requestedFramesPerBuffer,
301 UInt32 *actualInputFramesPerBuffer,
302 UInt32 *actualOutputFramesPerBuffer,
303 const PaMacAUHAL *auhalHostApi,
304 AudioUnit *audioUnit,
305 AudioConverterRef *srConverter,
306 AudioDeviceID *audioDevice,
307 const double sampleRate,
308 void *refCon );
309
310 /* for setting errors. */
311 #define PA_AUHAL_SET_LAST_HOST_ERROR( errorCode, errorText ) \
312 PaUtil_SetLastHostErrorInfo( paCoreAudio, errorCode, errorText )
313
314 /*
315 * Callback called when starting or stopping a stream.
316 */
317 static void startStopCallback(
318 void * inRefCon,
319 AudioUnit ci,
320 AudioUnitPropertyID inID,
321 AudioUnitScope inScope,
322 AudioUnitElement inElement )
323 {
324 PaMacCoreStream *stream = (PaMacCoreStream *) inRefCon;
325 UInt32 isRunning;
326 UInt32 size = sizeof( isRunning );
327 OSStatus err;
328 err = AudioUnitGetProperty( ci, kAudioOutputUnitProperty_IsRunning, inScope, inElement, &isRunning, &size );
329 assert( !err );
330 if( err )
331 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.
332 if( isRunning )
333 return; //We are only interested in when we are stopping
334 // -- if we are using 2 I/O units, we only need one notification!
335 if( stream->inputUnit && stream->outputUnit && stream->inputUnit != stream->outputUnit && ci == stream->inputUnit )
336 return;
337 PaStreamFinishedCallback *sfc = stream->streamRepresentation.streamFinishedCallback;
338 if( stream->state == STOPPING )
339 stream->state = STOPPED ;
340 if( sfc )
341 sfc( stream->streamRepresentation.userData );
342 }
343
344
345 /*currently, this is only used in initialization, but it might be modified
346 to be used when the list of devices changes.*/
347 static PaError gatherDeviceInfo(PaMacAUHAL *auhalHostApi)
348 {
349 UInt32 size;
350 UInt32 propsize;
351 VVDBUG(("gatherDeviceInfo()\n"));
352 /* -- free any previous allocations -- */
353 if( auhalHostApi->devIds )
354 PaUtil_GroupFreeMemory(auhalHostApi->allocations, auhalHostApi->devIds);
355 auhalHostApi->devIds = NULL;
356
357 /* -- figure out how many devices there are -- */
358 PaMacCore_AudioHardwareGetPropertySize( kAudioHardwarePropertyDevices,
359 &propsize);
360 auhalHostApi->devCount = propsize / sizeof( AudioDeviceID );
361
362 VDBUG( ( "Found %ld device(s).\n", auhalHostApi->devCount ) );
363
364 /* -- copy the device IDs -- */
365 auhalHostApi->devIds = (AudioDeviceID *)PaUtil_GroupAllocateMemory(
366 auhalHostApi->allocations,
367 propsize );
368 if( !auhalHostApi->devIds )
369 return paInsufficientMemory;
370 PaMacCore_AudioHardwareGetProperty( kAudioHardwarePropertyDevices,
371 &propsize,
372 auhalHostApi->devIds );
373 #ifdef MAC_CORE_VERBOSE_DEBUG
374 {
375 int i;
376 for( i=0; i<auhalHostApi->devCount; ++i )
377 printf( "Device %d\t: %ld\n", i, (long)auhalHostApi->devIds[i] );
378 }
379 #endif
380
381 size = sizeof(AudioDeviceID);
382 auhalHostApi->defaultIn = kAudioDeviceUnknown;
383 auhalHostApi->defaultOut = kAudioDeviceUnknown;
384
385 /* determine the default device. */
386 /* I am not sure how these calls to AudioHardwareGetProperty()
387 could fail, but in case they do, we use the first available
388 device as the default. */
389 if( 0 != PaMacCore_AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice,
390 &size,
391 &auhalHostApi->defaultIn) ) {
392 int i;
393 auhalHostApi->defaultIn = kAudioDeviceUnknown;
394 VDBUG(("Failed to get default input device from OS."));
395 VDBUG((" I will substitute the first available input Device."));
396 for( i=0; i<auhalHostApi->devCount; ++i ) {
397 PaDeviceInfo devInfo;
398 if( 0 != GetChannelInfo( auhalHostApi, &devInfo,
399 auhalHostApi->devIds[i], TRUE ) )
400 if( devInfo.maxInputChannels ) {
401 auhalHostApi->defaultIn = auhalHostApi->devIds[i];
402 break;
403 }
404 }
405 }
406 if( 0 != PaMacCore_AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
407 &size,
408 &auhalHostApi->defaultOut) ) {
409 int i;
410 auhalHostApi->defaultIn = kAudioDeviceUnknown;
411 VDBUG(("Failed to get default output device from OS."));
412 VDBUG((" I will substitute the first available output Device."));
413 for( i=0; i<auhalHostApi->devCount; ++i ) {
414 PaDeviceInfo devInfo;
415 if( 0 != GetChannelInfo( auhalHostApi, &devInfo,
416 auhalHostApi->devIds[i], FALSE ) )
417 if( devInfo.maxOutputChannels ) {
418 auhalHostApi->defaultOut = auhalHostApi->devIds[i];
419 break;
420 }
421 }
422 }
423
424 VDBUG( ( "Default in : %ld\n", (long)auhalHostApi->defaultIn ) );
425 VDBUG( ( "Default out: %ld\n", (long)auhalHostApi->defaultOut ) );
426
427 return paNoError;
428 }
429
430 /* =================================================================================================== */
431 /**
432 * @internal
433 * @brief Clip the desired size against the allowed IO buffer size range for the device.
434 */
435 static PaError ClipToDeviceBufferSize( AudioDeviceID macCoreDeviceId,
436 int isInput, UInt32 desiredSize, UInt32 *allowedSize )
437 {
438 UInt32 resultSize = desiredSize;
439 AudioValueRange audioRange;
440 UInt32 propSize = sizeof( audioRange );
441 PaError err = WARNING(PaMacCore_AudioDeviceGetProperty( macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &audioRange ) );
442 resultSize = MAX( resultSize, audioRange.mMinimum );
443 resultSize = MIN( resultSize, audioRange.mMaximum );
444 *allowedSize = resultSize;
445 return err;
446 }
447
448 /* =================================================================================================== */
449 #if 0
450 static void DumpDeviceProperties( AudioDeviceID macCoreDeviceId,
451 int isInput )
452 {
453 PaError err;
454 int i;
455 UInt32 propSize;
456 UInt32 deviceLatency;
457 UInt32 streamLatency;
458 UInt32 bufferFrames;
459 UInt32 safetyOffset;
460 AudioStreamID streamIDs[128];
461
462 printf("\n======= latency query : macCoreDeviceId = %d, isInput %d =======\n", (int)macCoreDeviceId, isInput );
463
464 propSize = sizeof(UInt32);
465 err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSize, &propSize, &bufferFrames));
466 printf("kAudioDevicePropertyBufferFrameSize: err = %d, propSize = %d, value = %d\n", err, propSize, bufferFrames );
467
468 propSize = sizeof(UInt32);
469 err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertySafetyOffset, &propSize, &safetyOffset));
470 printf("kAudioDevicePropertySafetyOffset: err = %d, propSize = %d, value = %d\n", err, propSize, safetyOffset );
471
472 propSize = sizeof(UInt32);
473 err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &deviceLatency));
474 printf("kAudioDevicePropertyLatency: err = %d, propSize = %d, value = %d\n", err, propSize, deviceLatency );
475
476 AudioValueRange audioRange;
477 propSize = sizeof( audioRange );
478 err = WARNING(AudioDeviceGetProperty( macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSizeRange, &propSize, &audioRange ) );
479 printf("kAudioDevicePropertyBufferFrameSizeRange: err = %d, propSize = %u, minimum = %g\n", err, propSize, audioRange.mMinimum);
480 printf("kAudioDevicePropertyBufferFrameSizeRange: err = %d, propSize = %u, maximum = %g\n", err, propSize, audioRange.mMaximum );
481
482 /* Get the streams from the device and query their latency. */
483 propSize = sizeof(streamIDs);
484 err = WARNING(AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreams, &propSize, &streamIDs[0]));
485 int numStreams = propSize / sizeof(AudioStreamID);
486 for( i=0; i<numStreams; i++ )
487 {
488 printf("Stream #%d = %d---------------------- \n", i, streamIDs[i] );
489
490 propSize = sizeof(UInt32);
491 err = WARNING(PaMacCore_AudioStreamGetProperty(streamIDs[i], 0, kAudioStreamPropertyLatency, &propSize, &streamLatency));
492 printf(" kAudioStreamPropertyLatency: err = %d, propSize = %d, value = %d\n", err, propSize, streamLatency );
493 }
494 }
495 #endif
496
497 /* =================================================================================================== */
498 /**
499 * @internal
500 * Calculate the fixed latency from the system and the device.
501 * Sum of kAudioStreamPropertyLatency +
502 * kAudioDevicePropertySafetyOffset +
503 * kAudioDevicePropertyLatency
504 *
505 * Some useful info from Jeff Moore on latency.
506 * http://osdir.com/ml/coreaudio-api/2010-01/msg00046.html
507 * http://osdir.com/ml/coreaudio-api/2009-07/msg00140.html
508 */
509 static PaError CalculateFixedDeviceLatency( AudioDeviceID macCoreDeviceId, int isInput, UInt32 *fixedLatencyPtr )
510 {
511 PaError err;
512 UInt32 propSize;
513 UInt32 deviceLatency;
514 UInt32 streamLatency;
515 UInt32 safetyOffset;
516 AudioStreamID streamIDs[1];
517
518 // To get stream latency we have to get a streamID from the device.
519 // We are only going to look at the first stream so only fetch one stream.
520 propSize = sizeof(streamIDs);
521 err = WARNING(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreams, &propSize, &streamIDs[0]));
522 if( err != paNoError ) goto error;
523 if( propSize == sizeof(AudioStreamID) )
524 {
525 propSize = sizeof(UInt32);
526 err = WARNING(PaMacCore_AudioStreamGetProperty(streamIDs[0], 0, kAudioStreamPropertyLatency, &propSize, &streamLatency));
527 }
528
529 propSize = sizeof(UInt32);
530 err = WARNING(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertySafetyOffset, &propSize, &safetyOffset));
531 if( err != paNoError ) goto error;
532
533 propSize = sizeof(UInt32);
534 err = WARNING(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyLatency, &propSize, &deviceLatency));
535 if( err != paNoError ) goto error;
536
537 *fixedLatencyPtr = deviceLatency + streamLatency + safetyOffset;
538 return err;
539 error:
540 return err;
541 }
542
543 /* =================================================================================================== */
544 static PaError CalculateDefaultDeviceLatencies( AudioDeviceID macCoreDeviceId,
545 int isInput, UInt32 *lowLatencyFramesPtr,
546 UInt32 *highLatencyFramesPtr )
547 {
548 UInt32 propSize;
549 UInt32 bufferFrames = 0;
550 UInt32 fixedLatency = 0;
551 UInt32 clippedMinBufferSize = 0;
552
553 //DumpDeviceProperties( macCoreDeviceId, isInput );
554
555 PaError err = CalculateFixedDeviceLatency( macCoreDeviceId, isInput, &fixedLatency );
556 if( err != paNoError ) goto error;
557
558 // For low latency use a small fixed size buffer clipped to the device range.
559 err = ClipToDeviceBufferSize( macCoreDeviceId, isInput, PA_MAC_SMALL_BUFFER_SIZE, &clippedMinBufferSize );
560 if( err != paNoError ) goto error;
561
562 // For high latency use the default device buffer size.
563 propSize = sizeof(UInt32);
564 err = WARNING(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyBufferFrameSize, &propSize, &bufferFrames));
565 if( err != paNoError ) goto error;
566
567 *lowLatencyFramesPtr = fixedLatency + clippedMinBufferSize;
568 *highLatencyFramesPtr = fixedLatency + bufferFrames;
569
570 return err;
571 error:
572 return err;
573 }
574
575 /* =================================================================================================== */
576
577 static PaError GetChannelInfo( PaMacAUHAL *auhalHostApi,
578 PaDeviceInfo *deviceInfo,
579 AudioDeviceID macCoreDeviceId,
580 int isInput)
581 {
582 UInt32 propSize;
583 PaError err = paNoError;
584 UInt32 i;
585 int numChannels = 0;
586 AudioBufferList *buflist = NULL;
587
588 VVDBUG(("GetChannelInfo()\n"));
589
590 /* Get the number of channels from the stream configuration.
591 Fail if we can't get this. */
592
593 err = ERR(PaMacCore_AudioDeviceGetPropertySize(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize));
594 if (err)
595 return err;
596
597 buflist = PaUtil_AllocateMemory(propSize);
598 if( !buflist )
599 return paInsufficientMemory;
600 err = ERR(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, isInput, kAudioDevicePropertyStreamConfiguration, &propSize, buflist));
601 if (err)
602 goto error;
603
604 for (i = 0; i < buflist->mNumberBuffers; ++i)
605 numChannels += buflist->mBuffers[i].mNumberChannels;
606
607 if (isInput)
608 deviceInfo->maxInputChannels = numChannels;
609 else
610 deviceInfo->maxOutputChannels = numChannels;
611
612 if (numChannels > 0) /* do not try to retrieve the latency if there are no channels. */
613 {
614 /* Get the latency. Don't fail if we can't get this. */
615 /* default to something reasonable */
616 deviceInfo->defaultLowInputLatency = .01;
617 deviceInfo->defaultHighInputLatency = .10;
618 deviceInfo->defaultLowOutputLatency = .01;
619 deviceInfo->defaultHighOutputLatency = .10;
620 UInt32 lowLatencyFrames = 0;
621 UInt32 highLatencyFrames = 0;
622 err = CalculateDefaultDeviceLatencies( macCoreDeviceId, isInput, &lowLatencyFrames, &highLatencyFrames );
623 if( err == 0 )
624 {
625
626 double lowLatencySeconds = lowLatencyFrames / deviceInfo->defaultSampleRate;
627 double highLatencySeconds = highLatencyFrames / deviceInfo->defaultSampleRate;
628 if (isInput)
629 {
630 deviceInfo->defaultLowInputLatency = lowLatencySeconds;
631 deviceInfo->defaultHighInputLatency = highLatencySeconds;
632 }
633 else
634 {
635 deviceInfo->defaultLowOutputLatency = lowLatencySeconds;
636 deviceInfo->defaultHighOutputLatency = highLatencySeconds;
637 }
638 }
639 }
640 PaUtil_FreeMemory( buflist );
641 return paNoError;
642 error:
643 PaUtil_FreeMemory( buflist );
644 return err;
645 }
646
647 /* =================================================================================================== */
648 static PaError InitializeDeviceInfo( PaMacAUHAL *auhalHostApi,
649 PaDeviceInfo *deviceInfo,
650 AudioDeviceID macCoreDeviceId,
651 PaHostApiIndex hostApiIndex )
652 {
653 Float64 sampleRate;
654 char *name;
655 PaError err = paNoError;
656 CFStringRef nameRef;
657 UInt32 propSize;
658
659 VVDBUG(("InitializeDeviceInfo(): macCoreDeviceId=%ld\n", macCoreDeviceId));
660
661 memset(deviceInfo, 0, sizeof(PaDeviceInfo));
662
663 deviceInfo->structVersion = 2;
664 deviceInfo->hostApi = hostApiIndex;
665
666 /* Get the device name using CFString */
667 propSize = sizeof(nameRef);
668 err = ERR(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceNameCFString, &propSize, &nameRef));
669 if (err)
670 {
671 /* Get the device name using c string. Fail if we can't get it. */
672 err = ERR(PaMacCore_AudioDeviceGetPropertySize(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize));
673 if (err)
674 return err;
675
676 name = PaUtil_GroupAllocateMemory(auhalHostApi->allocations,propSize+1);
677 if ( !name )
678 return paInsufficientMemory;
679 err = ERR(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyDeviceName, &propSize, name));
680 if (err)
681 return err;
682 }
683 else
684 {
685 /* valid CFString so we just allocate a c string big enough to contain the data */
686 propSize = CFStringGetMaximumSizeForEncoding(CFStringGetLength(nameRef), kCFStringEncodingUTF8);
687 name = PaUtil_GroupAllocateMemory(auhalHostApi->allocations, propSize+1);
688 if ( !name )
689 {
690 CFRelease(nameRef);
691 return paInsufficientMemory;
692 }
693 CFStringGetCString(nameRef, name, propSize+1, kCFStringEncodingUTF8);
694 CFRelease(nameRef);
695 }
696 deviceInfo->name = name;
697
698 /* Try to get the default sample rate. Don't fail if we can't get this. */
699 propSize = sizeof(Float64);
700 err = ERR(PaMacCore_AudioDeviceGetProperty(macCoreDeviceId, 0, 0, kAudioDevicePropertyNominalSampleRate, &propSize, &sampleRate));
701 if (err)
702 deviceInfo->defaultSampleRate = 0.0;
703 else
704 deviceInfo->defaultSampleRate = sampleRate;
705
706 /* Get the maximum number of input and output channels. Fail if we can't get this. */
707
708 err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 1);
709 if (err)
710 return err;
711
712 err = GetChannelInfo(auhalHostApi, deviceInfo, macCoreDeviceId, 0);
713 if (err)
714 return err;
715
716 return paNoError;
717 }
718
719 PaError PaMacCore_Initialize( PaUtilHostApiRepresentation **hostApi, PaHostApiIndex hostApiIndex )
720 {
721 PaError result = paNoError;
722 int i;
723 PaMacAUHAL *auhalHostApi = NULL;
724 PaDeviceInfo *deviceInfoArray;
725 int unixErr;
726
727 VVDBUG(("PaMacCore_Initialize(): hostApiIndex=%d\n", hostApiIndex));
728
729 SInt32 major;
730 SInt32 minor;
731 Gestalt(gestaltSystemVersionMajor, &major);
732 Gestalt(gestaltSystemVersionMinor, &minor);
733
734 // Starting with 10.6 systems, the HAL notification thread is created internally
735 if ( major > 10 || (major == 10 && minor >= 6) ) {
736 CFRunLoopRef theRunLoop = NULL;
737 AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
738 OSStatus osErr = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
739 if (osErr != noErr) {
740 goto error;
741 }
742 }
743
744 unixErr = initializeXRunListenerList();
745 if( 0 != unixErr ) {
746 return UNIX_ERR(unixErr);
747 }
748
749 auhalHostApi = (PaMacAUHAL*)PaUtil_AllocateMemory( sizeof(PaMacAUHAL) );
750 if( !auhalHostApi )
751 {
752 result = paInsufficientMemory;
753 goto error;
754 }
755
756 auhalHostApi->allocations = PaUtil_CreateAllocationGroup();
757 if( !auhalHostApi->allocations )
758 {
759 result = paInsufficientMemory;
760 goto error;
761 }
762
763 auhalHostApi->devIds = NULL;
764 auhalHostApi->devCount = 0;
765
766 /* get the info we need about the devices */
767 result = gatherDeviceInfo( auhalHostApi );
768 if( result != paNoError )
769 goto error;
770
771 *hostApi = &auhalHostApi->inheritedHostApiRep;
772 (*hostApi)->info.structVersion = 1;
773 (*hostApi)->info.type = paCoreAudio;
774 (*hostApi)->info.name = "Core Audio";
775
776 (*hostApi)->info.defaultInputDevice = paNoDevice;
777 (*hostApi)->info.defaultOutputDevice = paNoDevice;
778
779 (*hostApi)->info.deviceCount = 0;
780
781 if( auhalHostApi->devCount > 0 )
782 {
783 (*hostApi)->deviceInfos = (PaDeviceInfo**)PaUtil_GroupAllocateMemory(
784 auhalHostApi->allocations, sizeof(PaDeviceInfo*) * auhalHostApi->devCount);
785 if( !(*hostApi)->deviceInfos )
786 {
787 result = paInsufficientMemory;
788 goto error;
789 }
790
791 /* allocate all device info structs in a contiguous block */
792 deviceInfoArray = (PaDeviceInfo*)PaUtil_GroupAllocateMemory(
793 auhalHostApi->allocations, sizeof(PaDeviceInfo) * auhalHostApi->devCount );
794 if( !deviceInfoArray )
795 {
796 result = paInsufficientMemory;
797 goto error;
798 }
799
800 for( i=0; i < auhalHostApi->devCount; ++i )
801 {
802 int err;
803 err = InitializeDeviceInfo( auhalHostApi, &deviceInfoArray[i],
804 auhalHostApi->devIds[i],
805 hostApiIndex );
806 if (err == paNoError)
807 { /* copy some info and set the defaults */
808 (*hostApi)->deviceInfos[(*hostApi)->info.deviceCount] = &deviceInfoArray[i];
809 if (auhalHostApi->devIds[i] == auhalHostApi->defaultIn)
810 (*hostApi)->info.defaultInputDevice = (*hostApi)->info.deviceCount;
811 if (auhalHostApi->devIds[i] == auhalHostApi->defaultOut)
812 (*hostApi)->info.defaultOutputDevice = (*hostApi)->info.deviceCount;
813 (*hostApi)->info.deviceCount++;
814 }
815 else
816 { /* there was an error. we need to shift the devices down, so we ignore this one */
817 int j;
818 auhalHostApi->devCount--;
819 for( j=i; j<auhalHostApi->devCount; ++j )
820 auhalHostApi->devIds[j] = auhalHostApi->devIds[j+1];
821 i--;
822 }
823 }
824 }
825
826 (*hostApi)->Terminate = Terminate;
827 (*hostApi)->OpenStream = OpenStream;
828 (*hostApi)->IsFormatSupported = IsFormatSupported;
829
830 PaUtil_InitializeStreamInterface( &auhalHostApi->callbackStreamInterface,
831 CloseStream, StartStream,
832 StopStream, AbortStream, IsStreamStopped,
833 IsStreamActive,
834 GetStreamTime, GetStreamCpuLoad,
835 PaUtil_DummyRead, PaUtil_DummyWrite,
836 PaUtil_DummyGetReadAvailable,
837 PaUtil_DummyGetWriteAvailable );
838
839 PaUtil_InitializeStreamInterface( &auhalHostApi->blockingStreamInterface,
840 CloseStream, StartStream,
841 StopStream, AbortStream, IsStreamStopped,
842 IsStreamActive,
843 GetStreamTime, PaUtil_DummyGetCpuLoad,
844 ReadStream, WriteStream,
845 GetStreamReadAvailable,
846 GetStreamWriteAvailable );
847
848 return result;
849
850 error:
851 if( auhalHostApi )
852 {
853 if( auhalHostApi->allocations )
854 {
855 PaUtil_FreeAllAllocations( auhalHostApi->allocations );
856 PaUtil_DestroyAllocationGroup( auhalHostApi->allocations );
857 }
858
859 PaUtil_FreeMemory( auhalHostApi );
860 }
861 return result;
862 }
863
864
865 static void Terminate( struct PaUtilHostApiRepresentation *hostApi )
866 {
867 int unixErr;
868
869 PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi;
870
871 VVDBUG(("Terminate()\n"));
872
873 unixErr = destroyXRunListenerList();
874 if( 0 != unixErr )
875 UNIX_ERR(unixErr);
876
877 /*
878 IMPLEMENT ME:
879 - clean up any resources not handled by the allocation group
880 TODO: Double check that everything is handled by alloc group
881 */
882
883 if( auhalHostApi->allocations )
884 {
885 PaUtil_FreeAllAllocations( auhalHostApi->allocations );
886 PaUtil_DestroyAllocationGroup( auhalHostApi->allocations );
887 }
888
889 PaUtil_FreeMemory( auhalHostApi );
890 }
891
892
893 static PaError IsFormatSupported( struct PaUtilHostApiRepresentation *hostApi,
894 const PaStreamParameters *inputParameters,
895 const PaStreamParameters *outputParameters,
896 double sampleRate )
897 {
898 int inputChannelCount, outputChannelCount;
899 PaSampleFormat inputSampleFormat, outputSampleFormat;
900
901 VVDBUG(("IsFormatSupported(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld sampleRate=%g\n",
902 inputParameters ? inputParameters->channelCount : -1,
903 inputParameters ? inputParameters->sampleFormat : -1,
904 outputParameters ? outputParameters->channelCount : -1,
905 outputParameters ? outputParameters->sampleFormat : -1,
906 (float) sampleRate ));
907
908 /** These first checks are standard PA checks. We do some fancier checks
909 later. */
910 if( inputParameters )
911 {
912 inputChannelCount = inputParameters->channelCount;
913 inputSampleFormat = inputParameters->sampleFormat;
914
915 /* all standard sample formats are supported by the buffer adapter,
916 this implementation doesn't support any custom sample formats */
917 if( inputSampleFormat & paCustomFormat )
918 return paSampleFormatNotSupported;
919
920 /* unless alternate device specification is supported, reject the use of
921 paUseHostApiSpecificDeviceSpecification */
922
923 if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
924 return paInvalidDevice;
925
926 /* check that input device can support inputChannelCount */
927 if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
928 return paInvalidChannelCount;
929 }
930 else
931 {
932 inputChannelCount = 0;
933 }
934
935 if( outputParameters )
936 {
937 outputChannelCount = outputParameters->channelCount;
938 outputSampleFormat = outputParameters->sampleFormat;
939
940 /* all standard sample formats are supported by the buffer adapter,
941 this implementation doesn't support any custom sample formats */
942 if( outputSampleFormat & paCustomFormat )
943 return paSampleFormatNotSupported;
944
945 /* unless alternate device specification is supported, reject the use of
946 paUseHostApiSpecificDeviceSpecification */
947
948 if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
949 return paInvalidDevice;
950
951 /* check that output device can support outputChannelCount */
952 if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
953 return paInvalidChannelCount;
954
955 }
956 else
957 {
958 outputChannelCount = 0;
959 }
960
961 /* FEEDBACK */
962 /* I think the only way to check a given format SR combo is */
963 /* to try opening it. This could be disruptive, is that Okay? */
964 /* The alternative is to just read off available sample rates, */
965 /* but this will not work %100 of the time (eg, a device that */
966 /* supports N output at one rate but only N/2 at a higher rate.)*/
967
968 /* The following code opens the device with the requested parameters to
969 see if it works. */
970 {
971 PaError err;
972 PaStream *s;
973 err = OpenStream( hostApi, &s, inputParameters, outputParameters,
974 sampleRate, 1024, 0, (PaStreamCallback *)1, NULL );
975 if( err != paNoError && err != paInvalidSampleRate )
976 DBUG( ( "OpenStream @ %g returned: %d: %s\n",
977 (float) sampleRate, err, Pa_GetErrorText( err ) ) );
978 if( err )
979 return err;
980 err = CloseStream( s );
981 if( err ) {
982 /* FEEDBACK: is this more serious? should we assert? */
983 DBUG( ( "WARNING: could not close Stream. %d: %s\n",
984 err, Pa_GetErrorText( err ) ) );
985 }
986 }
987
988 return paFormatIsSupported;
989 }
990
991 /* ================================================================================= */
992 static void InitializeDeviceProperties( PaMacCoreDeviceProperties *deviceProperties )
993 {
994 memset( deviceProperties, 0, sizeof(PaMacCoreDeviceProperties) );
995 deviceProperties->sampleRate = 1.0; // Better than random. Overwritten by actual values later on.
996 deviceProperties->samplePeriod = 1.0 / deviceProperties->sampleRate;
997 }
998
999 static Float64 CalculateSoftwareLatencyFromProperties( PaMacCoreStream *stream, PaMacCoreDeviceProperties *deviceProperties )
1000 {
1001 UInt32 latencyFrames = deviceProperties->bufferFrameSize + deviceProperties->deviceLatency + deviceProperties->safetyOffset;
1002 return latencyFrames * deviceProperties->samplePeriod; // same as dividing by sampleRate but faster
1003 }
1004
1005 static Float64 CalculateHardwareLatencyFromProperties( PaMacCoreStream *stream, PaMacCoreDeviceProperties *deviceProperties )
1006 {
1007 return deviceProperties->deviceLatency * deviceProperties->samplePeriod; // same as dividing by sampleRate but faster
1008 }
1009
1010 /* Calculate values used to convert Apple timestamps into PA timestamps
1011 * from the device properties. The final results of this calculation
1012 * will be used in the audio callback function.
1013 */
1014 static void UpdateTimeStampOffsets( PaMacCoreStream *stream )
1015 {
1016 Float64 inputSoftwareLatency = 0.0;
1017 Float64 inputHardwareLatency = 0.0;
1018 Float64 outputSoftwareLatency = 0.0;
1019 Float64 outputHardwareLatency = 0.0;
1020
1021 if( stream->inputUnit != NULL )
1022 {
1023 inputSoftwareLatency = CalculateSoftwareLatencyFromProperties( stream, &stream->inputProperties );
1024 inputHardwareLatency = CalculateHardwareLatencyFromProperties( stream, &stream->inputProperties );
1025 }
1026 if( stream->outputUnit != NULL )
1027 {
1028 outputSoftwareLatency = CalculateSoftwareLatencyFromProperties( stream, &stream->outputProperties );
1029 outputHardwareLatency = CalculateHardwareLatencyFromProperties( stream, &stream->outputProperties );
1030 }
1031
1032 /* We only need a mutex around setting these variables as a group. */
1033 pthread_mutex_lock( &stream->timingInformationMutex );
1034 stream->timestampOffsetCombined = inputSoftwareLatency + outputSoftwareLatency;
1035 stream->timestampOffsetInputDevice = inputHardwareLatency;
1036 stream->timestampOffsetOutputDevice = outputHardwareLatency;
1037 pthread_mutex_unlock( &stream->timingInformationMutex );
1038 }
1039
1040 /* ================================================================================= */
1041
1042 /* can be used to update from nominal or actual sample rate */
1043 static OSStatus UpdateSampleRateFromDeviceProperty( PaMacCoreStream *stream, AudioDeviceID deviceID,
1044 Boolean isInput, AudioDevicePropertyID sampleRatePropertyID )
1045 {
1046 PaMacCoreDeviceProperties * deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties;
1047
1048 Float64 sampleRate = 0.0;
1049 UInt32 propSize = sizeof(Float64);
1050 OSStatus osErr = PaMacCore_AudioDeviceGetProperty( deviceID, 0, isInput, sampleRatePropertyID, &propSize, &sampleRate);
1051 if( (osErr == noErr) && (sampleRate > 1000.0) ) /* avoid divide by zero if there's an error */
1052 {
1053 deviceProperties->sampleRate = sampleRate;
1054 deviceProperties->samplePeriod = 1.0 / sampleRate;
1055 }
1056 return osErr;
1057 }
1058
1059 static OSStatus AudioDevicePropertyActualSampleRateListenerProc( AudioObjectID inDevice, UInt32 inNumberAddresses,
1060 const AudioObjectPropertyAddress * inAddresses, void * inClientData )
1061 {
1062 PaMacCoreStream *stream = (PaMacCoreStream*)inClientData;
1063 bool isInput = inAddresses->mScope == kAudioDevicePropertyScopeInput;
1064
1065 // Make sure the callback is operating on a stream that is still valid!
1066 assert( stream->streamRepresentation.magic == PA_STREAM_MAGIC );
1067
1068 OSStatus osErr = UpdateSampleRateFromDeviceProperty( stream, inDevice, isInput, kAudioDevicePropertyActualSampleRate );
1069 if( osErr == noErr )
1070 {
1071 UpdateTimeStampOffsets( stream );
1072 }
1073 return osErr;
1074 }
1075
1076 /* ================================================================================= */
1077 static OSStatus QueryUInt32DeviceProperty( AudioDeviceID deviceID, Boolean isInput, AudioDevicePropertyID propertyID, UInt32 *outValue )
1078 {
1079 UInt32 propertyValue = 0;
1080 UInt32 propertySize = sizeof(UInt32);
1081 OSStatus osErr = PaMacCore_AudioDeviceGetProperty( deviceID, 0, isInput, propertyID, &propertySize, &propertyValue);
1082 if( osErr == noErr )
1083 {
1084 *outValue = propertyValue;
1085 }
1086 return osErr;
1087 }
1088
1089 static OSStatus AudioDevicePropertyGenericListenerProc( AudioObjectID inDevice, UInt32 inNumberAddresses,
1090 const AudioObjectPropertyAddress * inAddresses, void * inClientData )
1091 {
1092 OSStatus osErr = noErr;
1093 PaMacCoreStream *stream = (PaMacCoreStream*)inClientData;
1094 bool isInput = inAddresses->mScope == kAudioDevicePropertyScopeInput;
1095 AudioDevicePropertyID inPropertyID = inAddresses->mSelector;
1096
1097 // Make sure the callback is operating on a stream that is still valid!
1098 assert( stream->streamRepresentation.magic == PA_STREAM_MAGIC );
1099
1100 PaMacCoreDeviceProperties *deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties;
1101 UInt32 *valuePtr = NULL;
1102 switch( inPropertyID )
1103 {
1104 case kAudioDevicePropertySafetyOffset:
1105 valuePtr = &deviceProperties->safetyOffset;
1106 break;
1107
1108 case kAudioDevicePropertyLatency:
1109 valuePtr = &deviceProperties->deviceLatency;
1110 break;
1111
1112 case kAudioDevicePropertyBufferFrameSize:
1113 valuePtr = &deviceProperties->bufferFrameSize;
1114 break;
1115 }
1116 if( valuePtr != NULL )
1117 {
1118 osErr = QueryUInt32DeviceProperty( inDevice, isInput, inPropertyID, valuePtr );
1119 if( osErr == noErr )
1120 {
1121 UpdateTimeStampOffsets( stream );
1122 }
1123 }
1124 return osErr;
1125 }
1126
1127 /* ================================================================================= */
1128 /*
1129 * Setup listeners in case device properties change during the run. */
1130 static OSStatus SetupDevicePropertyListeners( PaMacCoreStream *stream, AudioDeviceID deviceID, Boolean isInput )
1131 {
1132 OSStatus osErr = noErr;
1133 PaMacCoreDeviceProperties *deviceProperties = isInput ? &stream->inputProperties : &stream->outputProperties;
1134
1135 if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput,
1136 kAudioDevicePropertyLatency, &deviceProperties->deviceLatency )) != noErr ) return osErr;
1137 if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput,
1138 kAudioDevicePropertyBufferFrameSize, &deviceProperties->bufferFrameSize )) != noErr ) return osErr;
1139 if( (osErr = QueryUInt32DeviceProperty( deviceID, isInput,
1140 kAudioDevicePropertySafetyOffset, &deviceProperties->safetyOffset )) != noErr ) return osErr;
1141
1142 PaMacCore_AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertyActualSampleRate,
1143 AudioDevicePropertyActualSampleRateListenerProc, stream );
1144
1145 PaMacCore_AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioStreamPropertyLatency,
1146 AudioDevicePropertyGenericListenerProc, stream );
1147 PaMacCore_AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertyBufferFrameSize,
1148 AudioDevicePropertyGenericListenerProc, stream );
1149 PaMacCore_AudioDeviceAddPropertyListener( deviceID, 0, isInput, kAudioDevicePropertySafetyOffset,
1150 AudioDevicePropertyGenericListenerProc, stream );
1151
1152 return osErr;
1153 }
1154
1155 static void CleanupDevicePropertyListeners( PaMacCoreStream *stream, AudioDeviceID deviceID, Boolean isInput )
1156 {
1157 PaMacCore_AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyActualSampleRate,
1158 AudioDevicePropertyActualSampleRateListenerProc, stream );
1159
1160 PaMacCore_AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyLatency,
1161 AudioDevicePropertyGenericListenerProc, stream );
1162 PaMacCore_AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertyBufferFrameSize,
1163 AudioDevicePropertyGenericListenerProc, stream );
1164 PaMacCore_AudioDeviceRemovePropertyListener( deviceID, 0, isInput, kAudioDevicePropertySafetyOffset,
1165 AudioDevicePropertyGenericListenerProc, stream );
1166 }
1167
1168 /* ================================================================================= */
1169 static PaError OpenAndSetupOneAudioUnit(
1170 const PaMacCoreStream *stream,
1171 const PaStreamParameters *inStreamParams,
1172 const PaStreamParameters *outStreamParams,
1173 const UInt32 requestedFramesPerBuffer,
1174 UInt32 *actualInputFramesPerBuffer,
1175 UInt32 *actualOutputFramesPerBuffer,
1176 const PaMacAUHAL *auhalHostApi,
1177 AudioUnit *audioUnit,
1178 AudioConverterRef *srConverter,
1179 AudioDeviceID *audioDevice,
1180 const double sampleRate,
1181 void *refCon )
1182 {
1183 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
1184 AudioComponentDescription desc;
1185 AudioComponent comp;
1186 #else
1187 ComponentDescription desc;
1188 Component comp;
1189 #endif
1190 /*An Apple TN suggests using CAStreamBasicDescription, but that is C++*/
1191 AudioStreamBasicDescription desiredFormat;
1192 OSStatus result = noErr;
1193 PaError paResult = paNoError;
1194 int line = 0;
1195 UInt32 callbackKey;
1196 AURenderCallbackStruct rcbs;
1197 unsigned long macInputStreamFlags = paMacCorePlayNice;
1198 unsigned long macOutputStreamFlags = paMacCorePlayNice;
1199 SInt32 const *inChannelMap = NULL;
1200 SInt32 const *outChannelMap = NULL;
1201 unsigned long inChannelMapSize = 0;
1202 unsigned long outChannelMapSize = 0;
1203
1204 VVDBUG(("OpenAndSetupOneAudioUnit(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld, requestedFramesPerBuffer=%ld\n",
1205 inStreamParams ? inStreamParams->channelCount : -1,
1206 inStreamParams ? inStreamParams->sampleFormat : -1,
1207 outStreamParams ? outStreamParams->channelCount : -1,
1208 outStreamParams ? outStreamParams->sampleFormat : -1,
1209 requestedFramesPerBuffer ));
1210
1211 /* -- handle the degenerate case -- */
1212 if( !inStreamParams && !outStreamParams ) {
1213 *audioUnit = NULL;
1214 *audioDevice = kAudioDeviceUnknown;
1215 return paNoError;
1216 }
1217
1218 /* -- get the user's api specific info, if they set any -- */
1219 if( inStreamParams && inStreamParams->hostApiSpecificStreamInfo )
1220 {
1221 macInputStreamFlags=
1222 ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)
1223 ->flags;
1224 inChannelMap = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)->channelMap;
1225 inChannelMapSize = ((PaMacCoreStreamInfo*)inStreamParams->hostApiSpecificStreamInfo)->channelMapSize;
1226 }
1227 if( outStreamParams && outStreamParams->hostApiSpecificStreamInfo )
1228 {
1229 macOutputStreamFlags=
1230 ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)
1231 ->flags;
1232 outChannelMap = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)->channelMap;
1233 outChannelMapSize = ((PaMacCoreStreamInfo*)outStreamParams->hostApiSpecificStreamInfo)->channelMapSize;
1234 }
1235 /* Override user's flags here, if desired for testing. */
1236
1237 /*
1238 * The HAL AU is a Mac OS style "component".
1239 * the first few steps deal with that.
1240 * Later steps work on a combination of Mac OS
1241 * components and the slightly lower level
1242 * HAL.
1243 */
1244
1245 /* -- describe the output type AudioUnit -- */
1246 /* Note: for the default AudioUnit, we could use the
1247 * componentSubType value kAudioUnitSubType_DefaultOutput;
1248 * but I don't think that's relevant here.
1249 */
1250 desc.componentType = kAudioUnitType_Output;
1251 desc.componentSubType = kAudioUnitSubType_HALOutput;
1252 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
1253 desc.componentFlags = 0;
1254 desc.componentFlagsMask = 0;
1255 /* -- find the component -- */
1256 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
1257 comp = AudioComponentFindNext( NULL, &desc );
1258 #else
1259 comp = FindNextComponent( NULL, &desc );
1260 #endif
1261 if( !comp )
1262 {
1263 DBUG( ( "AUHAL component not found." ) );
1264 *audioUnit = NULL;
1265 *audioDevice = kAudioDeviceUnknown;
1266 return paUnanticipatedHostError;
1267 }
1268 /* -- open it -- */
1269 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
1270 result = AudioComponentInstanceNew( comp, audioUnit );
1271 #else
1272 result = OpenAComponent( comp, audioUnit );
1273 #endif
1274 if( result )
1275 {
1276 DBUG( ( "Failed to open AUHAL component." ) );
1277 *audioUnit = NULL;
1278 *audioDevice = kAudioDeviceUnknown;
1279 return ERR( result );
1280 }
1281 /* -- prepare a little error handling logic / hackery -- */
1282 #define ERR_WRAP(mac_err) do { result = mac_err ; line = __LINE__ ; if ( result != noErr ) goto error ; } while(0)
1283
1284 /* -- if there is input, we have to explicitly enable input -- */
1285 if( inStreamParams )
1286 {
1287 UInt32 enableIO = 1;
1288 ERR_WRAP( AudioUnitSetProperty( *audioUnit,
1289 kAudioOutputUnitProperty_EnableIO,
1290 kAudioUnitScope_Input,
1291 INPUT_ELEMENT,
1292 &enableIO,
1293 sizeof(enableIO) ) );
1294 }
1295 /* -- if there is no output, we must explicitly disable output -- */
1296 if( !outStreamParams )
1297 {
1298 UInt32 enableIO = 0;
1299 ERR_WRAP( AudioUnitSetProperty( *audioUnit,
1300 kAudioOutputUnitProperty_EnableIO,
1301 kAudioUnitScope_Output,
1302 OUTPUT_ELEMENT,
1303 &enableIO,
1304 sizeof(enableIO) ) );
1305 }
1306
1307 /* -- set the devices -- */
1308 /* make sure input and output are the same device if we are doing input and
1309 output. */
1310 if( inStreamParams && outStreamParams )
1311 {
1312 assert( outStreamParams->device == inStreamParams->device );
1313 }
1314 if( inStreamParams )
1315 {
1316 *audioDevice = auhalHostApi->devIds[inStreamParams->device] ;
1317 ERR_WRAP( AudioUnitSetProperty( *audioUnit,
1318 kAudioOutputUnitProperty_CurrentDevice,
1319 kAudioUnitScope_Global,
1320 INPUT_ELEMENT,
1321 audioDevice,
1322 sizeof(AudioDeviceID) ) );
1323 }
1324 if( outStreamParams && outStreamParams != inStreamParams )
1325 {
1326 *audioDevice = auhalHostApi->devIds[outStreamParams->device] ;
1327 ERR_WRAP( AudioUnitSetProperty( *audioUnit,
1328 kAudioOutputUnitProperty_CurrentDevice,
1329 kAudioUnitScope_Global,
1330 OUTPUT_ELEMENT,
1331 audioDevice,
1332 sizeof(AudioDeviceID) ) );
1333 }
1334 /* -- add listener for dropouts -- */
1335 result = PaMacCore_AudioDeviceAddPropertyListener( *audioDevice,
1336 0,
1337 outStreamParams ? false : true,
1338 kAudioDeviceProcessorOverload,
1339 xrunCallback,
1340 addToXRunListenerList( (void *)stream ) ) ;
1341 if( result == kAudioHardwareIllegalOperationError ) {
1342 // -- already registered, we're good
1343 } else {
1344 // -- not already registered, just check for errors
1345 ERR_WRAP( result );
1346 }
1347 /* -- listen for stream start and stop -- */
1348 ERR_WRAP( AudioUnitAddPropertyListener( *audioUnit,
1349 kAudioOutputUnitProperty_IsRunning,
1350 startStopCallback,
1351 (void *)stream ) );
1352
1353 /* -- set format -- */
1354 bzero( &desiredFormat, sizeof(desiredFormat) );
1355 desiredFormat.mFormatID = kAudioFormatLinearPCM ;
1356 desiredFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
1357 desiredFormat.mFramesPerPacket = 1;
1358 desiredFormat.mBitsPerChannel = sizeof( float ) * 8;
1359
1360 result = 0;
1361 /* set device format first, but only touch the device if the user asked */
1362 if( inStreamParams ) {
1363 /*The callback never calls back if we don't set the FPB */
1364 /*This seems weird, because I would think setting anything on the device
1365 would be disruptive.*/
1366 paResult = setBestFramesPerBuffer( *audioDevice, FALSE,
1367 requestedFramesPerBuffer,
1368 actualInputFramesPerBuffer );
1369 if( paResult ) goto error;
1370 if( macInputStreamFlags & paMacCoreChangeDeviceParameters ) {
1371 bool requireExact;
1372 requireExact=macInputStreamFlags & paMacCoreFailIfConversionRequired;
1373 paResult = setBestSampleRateForDevice( *audioDevice, FALSE,
1374 requireExact, sampleRate );
1375 if( paResult ) goto error;
1376 }
1377 if( actualInputFramesPerBuffer && actualOutputFramesPerBuffer )
1378 *actualOutputFramesPerBuffer = *actualInputFramesPerBuffer ;
1379 }
1380 if( outStreamParams && !inStreamParams ) {
1381 /*The callback never calls back if we don't set the FPB */
1382 /*This seems weird, because I would think setting anything on the device
1383 would be disruptive.*/
1384 paResult = setBestFramesPerBuffer( *audioDevice, TRUE,
1385 requestedFramesPerBuffer,
1386 actualOutputFramesPerBuffer );
1387 if( paResult ) goto error;
1388 if( macOutputStreamFlags & paMacCoreChangeDeviceParameters ) {
1389 bool requireExact;
1390 requireExact=macOutputStreamFlags & paMacCoreFailIfConversionRequired;
1391 paResult = setBestSampleRateForDevice( *audioDevice, TRUE,
1392 requireExact, sampleRate );
1393 if( paResult ) goto error;
1394 }
1395 }
1396
1397 /* -- set the quality of the output converter -- */
1398 if( outStreamParams ) {
1399 UInt32 value = kAudioConverterQuality_Max;
1400 switch( macOutputStreamFlags & 0x0700 ) {
1401 case 0x0100: /*paMacCore_ConversionQualityMin:*/
1402 value=kRenderQuality_Min;
1403 break;
1404 case 0x0200: /*paMacCore_ConversionQualityLow:*/
1405 value=kRenderQuality_Low;
1406 break;
1407 case 0x0300: /*paMacCore_ConversionQualityMedium:*/
1408 value=kRenderQuality_Medium;
1409 break;
1410 case 0x0400: /*paMacCore_ConversionQualityHigh:*/
1411 value=kRenderQuality_High;
1412 break;
1413 }
1414 ERR_WRAP( AudioUnitSetProperty( *audioUnit,
1415 kAudioUnitProperty_RenderQuality,
1416 kAudioUnitScope_Global,
1417 OUTPUT_ELEMENT,
1418 &value,
1419 sizeof(value) ) );
1420 }
1421 /* now set the format on the Audio Units. */
1422 if( outStreamParams )
1423 {
1424 desiredFormat.mSampleRate =sampleRate;
1425 desiredFormat.mBytesPerPacket=sizeof(float)*outStreamParams->channelCount;
1426 desiredFormat.mBytesPerFrame =sizeof(float)*outStreamParams->channelCount;
1427 desiredFormat.mChannelsPerFrame = outStreamParams->channelCount;
1428 ERR_WRAP( AudioUnitSetProperty( *audioUnit,
1429 kAudioUnitProperty_StreamFormat,
1430 kAudioUnitScope_Input,
1431 OUTPUT_ELEMENT,
1432 &desiredFormat,
1433 sizeof(AudioStreamBasicDescription) ) );
1434 }
1435 if( inStreamParams )
1436 {
1437 AudioStreamBasicDescription sourceFormat;
1438 UInt32 size = sizeof( AudioStreamBasicDescription );
1439
1440 /* keep the sample rate of the device, or we confuse AUHAL */
1441 ERR_WRAP( AudioUnitGetProperty( *audioUnit,
1442 kAudioUnitProperty_StreamFormat,
1443 kAudioUnitScope_Input,
1444 INPUT_ELEMENT,
1445 &sourceFormat,
1446 &size ) );
1447 desiredFormat.mSampleRate = sourceFormat.mSampleRate;
1448 desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount;
1449 desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount;
1450 desiredFormat.mChannelsPerFrame = inStreamParams->channelCount;
1451 ERR_WRAP( AudioUnitSetProperty( *audioUnit,
1452 kAudioUnitProperty_StreamFormat,
1453 kAudioUnitScope_Output,
1454 INPUT_ELEMENT,
1455 &desiredFormat,
1456 sizeof(AudioStreamBasicDescription) ) );
1457 }
1458 /* set the maximumFramesPerSlice */
1459 /* not doing this causes real problems
1460 (eg. the callback might not be called). The idea of setting both this
1461 and the frames per buffer on the device is that we'll be most likely
1462 to actually get the frame size we requested in the callback with the
1463 minimum latency. */
1464 if( outStreamParams ) {
1465 UInt32 size = sizeof( *actualOutputFramesPerBuffer );
1466 ERR_WRAP( AudioUnitSetProperty( *audioUnit,
1467 kAudioUnitProperty_MaximumFramesPerSlice,
1468 kAudioUnitScope_Input,
1469 OUTPUT_ELEMENT,
1470 actualOutputFramesPerBuffer,
1471 sizeof(*actualOutputFramesPerBuffer) ) );
1472 ERR_WRAP( AudioUnitGetProperty( *audioUnit,
1473 kAudioUnitProperty_MaximumFramesPerSlice,
1474 kAudioUnitScope_Global,
1475 OUTPUT_ELEMENT,
1476 actualOutputFramesPerBuffer,
1477 &size ) );
1478 }
1479 if( inStreamParams ) {
1480 /*UInt32 size = sizeof( *actualInputFramesPerBuffer );*/
1481 ERR_WRAP( AudioUnitSetProperty( *audioUnit,
1482 kAudioUnitProperty_MaximumFramesPerSlice,
1483 kAudioUnitScope_Output,
1484 INPUT_ELEMENT,
1485 actualInputFramesPerBuffer,
1486 sizeof(*actualInputFramesPerBuffer) ) );
1487 /* Don't know why this causes problems
1488 ERR_WRAP( AudioUnitGetProperty( *audioUnit,
1489 kAudioUnitProperty_MaximumFramesPerSlice,
1490 kAudioUnitScope_Global, //Output,
1491 INPUT_ELEMENT,
1492 actualInputFramesPerBuffer,
1493 &size ) );
1494 */
1495 }
1496
1497 /* -- if we have input, we may need to setup an SR converter -- */
1498 /* even if we got the sample rate we asked for, we need to do
1499 the conversion in case another program changes the underlying SR. */
1500 /* FIXME: I think we need to monitor stream and change the converter if the incoming format changes. */
1501 if( inStreamParams ) {
1502 AudioStreamBasicDescription desiredFormat;
1503 AudioStreamBasicDescription sourceFormat;
1504 UInt32 sourceSize = sizeof( sourceFormat );
1505 bzero( &desiredFormat, sizeof(desiredFormat) );
1506 desiredFormat.mSampleRate = sampleRate;
1507 desiredFormat.mFormatID = kAudioFormatLinearPCM ;
1508 desiredFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked;
1509 desiredFormat.mFramesPerPacket = 1;
1510 desiredFormat.mBitsPerChannel = sizeof( float ) * 8;
1511 desiredFormat.mBytesPerPacket=sizeof(float)*inStreamParams->channelCount;
1512 desiredFormat.mBytesPerFrame =sizeof(float)*inStreamParams->channelCount;
1513 desiredFormat.mChannelsPerFrame = inStreamParams->channelCount;
1514
1515 /* get the source format */
1516 ERR_WRAP( AudioUnitGetProperty( *audioUnit,
1517 kAudioUnitProperty_StreamFormat,
1518 kAudioUnitScope_Output,
1519 INPUT_ELEMENT,
1520 &sourceFormat,
1521 &sourceSize ) );
1522
1523 if( desiredFormat.mSampleRate != sourceFormat.mSampleRate )
1524 {
1525 UInt32 value = kAudioConverterQuality_Max;
1526 switch( macInputStreamFlags & 0x0700 ) {
1527 case 0x0100: /*paMacCore_ConversionQualityMin:*/
1528 value=kAudioConverterQuality_Min;
1529 break;
1530 case 0x0200: /*paMacCore_ConversionQualityLow:*/
1531 value=kAudioConverterQuality_Low;
1532 break;
1533 case 0x0300: /*paMacCore_ConversionQualityMedium:*/
1534 value=kAudioConverterQuality_Medium;
1535 break;
1536 case 0x0400: /*paMacCore_ConversionQualityHigh:*/
1537 value=kAudioConverterQuality_High;
1538 break;
1539 }
1540 VDBUG(( "Creating sample rate converter for input"
1541 " to convert from %g to %g\n",
1542 (float)sourceFormat.mSampleRate,
1543 (float)desiredFormat.mSampleRate ) );
1544 /* create our converter */
1545 ERR_WRAP( AudioConverterNew( &sourceFormat,
1546 &desiredFormat,
1547 srConverter ) );
1548 /* Set quality */
1549 ERR_WRAP( AudioConverterSetProperty( *srConverter,
1550 kAudioConverterSampleRateConverterQuality,
1551 sizeof( value ),
1552 &value ) );
1553 }
1554 }
1555 /* -- set IOProc (callback) -- */
1556 callbackKey = outStreamParams ? kAudioUnitProperty_SetRenderCallback
1557 : kAudioOutputUnitProperty_SetInputCallback ;
1558 rcbs.inputProc = AudioIOProc;
1559 rcbs.inputProcRefCon = refCon;
1560 ERR_WRAP( AudioUnitSetProperty( *audioUnit,
1561 callbackKey,
1562 kAudioUnitScope_Output,
1563 outStreamParams ? OUTPUT_ELEMENT : INPUT_ELEMENT,
1564 &rcbs,
1565 sizeof(rcbs)) );
1566
1567 if( inStreamParams && outStreamParams && *srConverter )
1568 ERR_WRAP( AudioUnitSetProperty( *audioUnit,
1569 kAudioOutputUnitProperty_SetInputCallback,
1570 kAudioUnitScope_Output,
1571 INPUT_ELEMENT,
1572 &rcbs,
1573 sizeof(rcbs)) );
1574
1575 /* channel mapping. */
1576 if(inChannelMap)
1577 {
1578 UInt32 mapSize = inChannelMapSize *sizeof(SInt32);
1579
1580 //for each channel of desired input, map the channel from
1581 //the device's output channel.
1582 ERR_WRAP( AudioUnitSetProperty( *audioUnit,
1583 kAudioOutputUnitProperty_ChannelMap,
1584 kAudioUnitScope_Output,
1585 INPUT_ELEMENT,
1586 inChannelMap,
1587 mapSize) );
1588 }
1589 if(outChannelMap)
1590 {
1591 UInt32 mapSize = outChannelMapSize *sizeof(SInt32);
1592
1593 //for each channel of desired output, map the channel from
1594 //the device's output channel.
1595 ERR_WRAP(AudioUnitSetProperty( *audioUnit,
1596 kAudioOutputUnitProperty_ChannelMap,
1597 kAudioUnitScope_Output,
1598 OUTPUT_ELEMENT,
1599 outChannelMap,
1600 mapSize) );
1601 }
1602 /* initialize the audio unit */
1603 ERR_WRAP( AudioUnitInitialize(*audioUnit) );
1604
1605 if( inStreamParams && outStreamParams )
1606 {
1607 VDBUG( ("Opened device %ld for input and output.\n", (long)*audioDevice ) );
1608 }
1609 else if( inStreamParams )
1610 {
1611 VDBUG( ("Opened device %ld for input.\n", (long)*audioDevice ) );
1612 }
1613 else if( outStreamParams )
1614 {
1615 VDBUG( ("Opened device %ld for output.\n", (long)*audioDevice ) );
1616 }
1617 return paNoError;
1618 #undef ERR_WRAP
1619
1620 error:
1621
1622 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
1623 AudioComponentInstanceDispose( *audioUnit );
1624 #else
1625 CloseComponent( *audioUnit );
1626 #endif
1627 *audioUnit = NULL;
1628 if( result )
1629 return PaMacCore_SetError( result, line, 1 );
1630 return paResult;
1631 }
1632
1633 /* =================================================================================================== */
1634
1635 static UInt32 CalculateOptimalBufferSize( PaMacAUHAL *auhalHostApi,
1636 const PaStreamParameters *inputParameters,
1637 const PaStreamParameters *outputParameters,
1638 UInt32 fixedInputLatency,
1639 UInt32 fixedOutputLatency,
1640 double sampleRate,
1641 UInt32 requestedFramesPerBuffer )
1642 {
1643 UInt32 resultBufferSizeFrames = 0;
1644 // Use maximum of suggested input and output latencies.
1645 if( inputParameters )
1646 {
1647 UInt32 suggestedLatencyFrames = inputParameters->suggestedLatency * sampleRate;
1648 // Calculate a buffer size assuming we are double buffered.
1649 SInt32 variableLatencyFrames = suggestedLatencyFrames - fixedInputLatency;
1650 // Prevent negative latency.
1651 variableLatencyFrames = MAX( variableLatencyFrames, 0 );
1652 resultBufferSizeFrames = MAX( resultBufferSizeFrames, (UInt32) variableLatencyFrames );
1653 }
1654 if( outputParameters )
1655 {
1656 UInt32 suggestedLatencyFrames = outputParameters->suggestedLatency * sampleRate;
1657 SInt32 variableLatencyFrames = suggestedLatencyFrames - fixedOutputLatency;
1658 variableLatencyFrames = MAX( variableLatencyFrames, 0 );
1659 resultBufferSizeFrames = MAX( resultBufferSizeFrames, (UInt32) variableLatencyFrames );
1660 }
1661
1662 // can't have zero frames. code to round up to next user buffer requires non-zero
1663 resultBufferSizeFrames = MAX( resultBufferSizeFrames, 1 );
1664
1665 if( requestedFramesPerBuffer != paFramesPerBufferUnspecified )
1666 {
1667 // make host buffer the next highest integer multiple of user frames per buffer
1668 UInt32 n = (resultBufferSizeFrames + requestedFramesPerBuffer - 1) / requestedFramesPerBuffer;
1669 resultBufferSizeFrames = n * requestedFramesPerBuffer;
1670
1671
1672 // FIXME: really we should be searching for a multiple of requestedFramesPerBuffer
1673 // that is >= suggested latency and also fits within device buffer min/max
1674
1675 } else {
1676 VDBUG( ("Block Size unspecified. Based on Latency, the user wants a Block Size near: %ld.\n",
1677 (long)resultBufferSizeFrames ) );
1678 }
1679
1680 // Clip to the capabilities of the device.
1681 if( inputParameters )
1682 {
1683 ClipToDeviceBufferSize( auhalHostApi->devIds[inputParameters->device],
1684 true, // In the old code isInput was false!
1685 resultBufferSizeFrames, &resultBufferSizeFrames );
1686 }
1687 if( outputParameters )
1688 {
1689 ClipToDeviceBufferSize( auhalHostApi->devIds[outputParameters->device],
1690 false, resultBufferSizeFrames, &resultBufferSizeFrames );
1691 }
1692 VDBUG(("After querying hardware, setting block size to %ld.\n", (long)resultBufferSizeFrames));
1693
1694 return resultBufferSizeFrames;
1695 }
1696
1697 /* =================================================================================================== */
1698 /* see pa_hostapi.h for a list of validity guarantees made about OpenStream parameters */
1699 static PaError OpenStream( struct PaUtilHostApiRepresentation *hostApi,
1700 PaStream** s,
1701 const PaStreamParameters *inputParameters,
1702 const PaStreamParameters *outputParameters,
1703 double sampleRate,
1704 unsigned long requestedFramesPerBuffer,
1705 PaStreamFlags streamFlags,
1706 PaStreamCallback *streamCallback,
1707 void *userData )
1708 {
1709 PaError result = paNoError;
1710 PaMacAUHAL *auhalHostApi = (PaMacAUHAL*)hostApi;
1711 PaMacCoreStream *stream = 0;
1712 int inputChannelCount, outputChannelCount;
1713 PaSampleFormat inputSampleFormat, outputSampleFormat;
1714 PaSampleFormat hostInputSampleFormat, hostOutputSampleFormat;
1715 UInt32 fixedInputLatency = 0;
1716 UInt32 fixedOutputLatency = 0;
1717 // Accumulate contributions to latency in these variables.
1718 UInt32 inputLatencyFrames = 0;
1719 UInt32 outputLatencyFrames = 0;
1720 UInt32 suggestedLatencyFramesPerBuffer = requestedFramesPerBuffer;
1721
1722 VVDBUG(("OpenStream(): in chan=%d, in fmt=%ld, out chan=%d, out fmt=%ld SR=%g, FPB=%ld\n",
1723 inputParameters ? inputParameters->channelCount : -1,
1724 inputParameters ? inputParameters->sampleFormat : -1,
1725 outputParameters ? outputParameters->channelCount : -1,
1726 outputParameters ? outputParameters->sampleFormat : -1,
1727 (float) sampleRate,
1728 requestedFramesPerBuffer ));
1729 VDBUG( ("Opening Stream.\n") );
1730
1731 /* These first few bits of code are from paSkeleton with few modifications. */
1732 if( inputParameters )
1733 {
1734 inputChannelCount = inputParameters->channelCount;
1735 inputSampleFormat = inputParameters->sampleFormat;
1736
1737 /* @todo Blocking read/write on Mac is not yet supported. */
1738 if( !streamCallback && inputSampleFormat & paNonInterleaved )
1739 {
1740 return paSampleFormatNotSupported;
1741 }
1742
1743 /* unless alternate device specification is supported, reject the use of
1744 paUseHostApiSpecificDeviceSpecification */
1745
1746 if( inputParameters->device == paUseHostApiSpecificDeviceSpecification )
1747 return paInvalidDevice;
1748
1749 /* check that input device can support inputChannelCount */
1750 if( inputChannelCount > hostApi->deviceInfos[ inputParameters->device ]->maxInputChannels )
1751 return paInvalidChannelCount;
1752
1753 /* Host supports interleaved float32 */
1754 hostInputSampleFormat = paFloat32;
1755 }
1756 else
1757 {
1758 inputChannelCount = 0;
1759 inputSampleFormat = hostInputSampleFormat = paFloat32; /* Suppress 'uninitialised var' warnings. */
1760 }
1761
1762 if( outputParameters )
1763 {
1764 outputChannelCount = outputParameters->channelCount;
1765 outputSampleFormat = outputParameters->sampleFormat;
1766
1767 /* @todo Blocking read/write on Mac is not yet supported. */
1768 if( !streamCallback && outputSampleFormat & paNonInterleaved )
1769 {
1770 return paSampleFormatNotSupported;
1771 }
1772
1773 /* unless alternate device specification is supported, reject the use of
1774 paUseHostApiSpecificDeviceSpecification */
1775
1776 if( outputParameters->device == paUseHostApiSpecificDeviceSpecification )
1777 return paInvalidDevice;
1778
1779 /* check that output device can support inputChannelCount */
1780 if( outputChannelCount > hostApi->deviceInfos[ outputParameters->device ]->maxOutputChannels )
1781 return paInvalidChannelCount;
1782
1783 /* Host supports interleaved float32 */
1784 hostOutputSampleFormat = paFloat32;
1785 }
1786 else
1787 {
1788 outputChannelCount = 0;
1789 outputSampleFormat = hostOutputSampleFormat = paFloat32; /* Suppress 'uninitialized var' warnings. */
1790 }
1791
1792 /* validate platform specific flags */
1793 if( (streamFlags & paPlatformSpecificFlags) != 0 )
1794 return paInvalidFlag; /* unexpected platform specific flag */
1795
1796 stream = (PaMacCoreStream*)PaUtil_AllocateMemory( sizeof(PaMacCoreStream) );
1797 if( !stream )
1798 {
1799 result = paInsufficientMemory;
1800 goto error;
1801 }
1802
1803 /* If we fail after this point, we my be left in a bad state, with
1804 some data structures setup and others not. So, first thing we
1805 do is initialize everything so that if we fail, we know what hasn't
1806 been touched.
1807 */
1808 bzero( stream, sizeof( PaMacCoreStream ) );
1809
1810 /*
1811 stream->blio.inputRingBuffer.buffer = NULL;
1812 stream->blio.outputRingBuffer.buffer = NULL;
1813 stream->blio.inputSampleFormat = inputParameters?inputParameters->sampleFormat:0;
1814 stream->blio.inputSampleSize = computeSampleSizeFromFormat(stream->blio.inputSampleFormat);
1815 stream->blio.outputSampleFormat=outputParameters?outputParameters->sampleFormat:0;
1816 stream->blio.outputSampleSize = computeSampleSizeFromFormat(stream->blio.outputSampleFormat);
1817 */
1818
1819 /* assert( streamCallback ) ; */ /* only callback mode is implemented */
1820 if( streamCallback )
1821 {
1822 PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
1823 &auhalHostApi->callbackStreamInterface,
1824 streamCallback, userData );
1825 }
1826 else
1827 {
1828 PaUtil_InitializeStreamRepresentation( &stream->streamRepresentation,
1829 &auhalHostApi->blockingStreamInterface,
1830 BlioCallback, &stream->blio );
1831 }
1832
1833 PaUtil_InitializeCpuLoadMeasurer( &stream->cpuLoadMeasurer, sampleRate );
1834
1835
1836 if( inputParameters )
1837 {
1838 CalculateFixedDeviceLatency( auhalHostApi->devIds[inputParameters->device], true, &fixedInputLatency );
1839 inputLatencyFrames += fixedInputLatency;
1840 }
1841 if( outputParameters )
1842 {
1843 CalculateFixedDeviceLatency( auhalHostApi->devIds[outputParameters->device], false, &fixedOutputLatency );
1844 outputLatencyFrames += fixedOutputLatency;
1845
1846 }
1847
1848 suggestedLatencyFramesPerBuffer = CalculateOptimalBufferSize( auhalHostApi, inputParameters, outputParameters,
1849 fixedInputLatency, fixedOutputLatency,
1850 sampleRate, requestedFramesPerBuffer );
1851 if( requestedFramesPerBuffer == paFramesPerBufferUnspecified )
1852 {
1853 requestedFramesPerBuffer = suggestedLatencyFramesPerBuffer;
1854 }
1855
1856 /* -- Now we actually open and setup streams. -- */
1857 if( inputParameters && outputParameters && outputParameters->device == inputParameters->device )
1858 { /* full duplex. One device. */
1859 UInt32 inputFramesPerBuffer = (UInt32) stream->inputFramesPerBuffer;
1860 UInt32 outputFramesPerBuffer = (UInt32) stream->outputFramesPerBuffer;
1861 result = OpenAndSetupOneAudioUnit( stream,
1862 inputParameters,
1863 outputParameters,
1864 suggestedLatencyFramesPerBuffer,
1865 &inputFramesPerBuffer,
1866 &outputFramesPerBuffer,
1867 auhalHostApi,
1868 &(stream->inputUnit),
1869 &(stream->inputSRConverter),
1870 &(stream->inputDevice),
1871 sampleRate,
1872 stream );
1873 stream->inputFramesPerBuffer = inputFramesPerBuffer;
1874 stream->outputFramesPerBuffer = outputFramesPerBuffer;
1875 stream->outputUnit = stream->inputUnit;
1876 stream->outputDevice = stream->inputDevice;
1877 if( result != paNoError )
1878 goto error;
1879 }
1880 else
1881 { /* full duplex, different devices OR simplex */
1882 UInt32 outputFramesPerBuffer = (UInt32) stream->outputFramesPerBuffer;
1883 UInt32 inputFramesPerBuffer = (UInt32) stream->inputFramesPerBuffer;
1884 result = OpenAndSetupOneAudioUnit( stream,
1885 NULL,
1886 outputParameters,
1887 suggestedLatencyFramesPerBuffer,
1888 NULL,
1889 &outputFramesPerBuffer,
1890 auhalHostApi,
1891 &(stream->outputUnit),
1892 NULL,
1893 &(stream->outputDevice),
1894 sampleRate,
1895 stream );
1896 if( result != paNoError )
1897 goto error;
1898 result = OpenAndSetupOneAudioUnit( stream,
1899 inputParameters,
1900 NULL,
1901 suggestedLatencyFramesPerBuffer,
1902 &inputFramesPerBuffer,
1903 NULL,
1904 auhalHostApi,
1905 &(stream->inputUnit),
1906 &(stream->inputSRConverter),
1907 &(stream->inputDevice),
1908 sampleRate,
1909 stream );
1910 if( result != paNoError )
1911 goto error;
1912 stream->inputFramesPerBuffer = inputFramesPerBuffer;
1913 stream->outputFramesPerBuffer = outputFramesPerBuffer;
1914 }
1915
1916 inputLatencyFrames += stream->inputFramesPerBuffer;
1917 outputLatencyFrames += stream->outputFramesPerBuffer;
1918
1919 if( stream->inputUnit ) {
1920 const size_t szfl = sizeof(float);
1921 /* setup the AudioBufferList used for input */
1922 bzero( &stream->inputAudioBufferList, sizeof( AudioBufferList ) );
1923 stream->inputAudioBufferList.mNumberBuffers = 1;
1924 stream->inputAudioBufferList.mBuffers[0].mNumberChannels
1925 = inputChannelCount;
1926 stream->inputAudioBufferList.mBuffers[0].mDataByteSize
1927 = stream->inputFramesPerBuffer*inputChannelCount*szfl;
1928 stream->inputAudioBufferList.mBuffers[0].mData
1929 = (float *) calloc(
1930 stream->inputFramesPerBuffer*inputChannelCount,
1931 szfl );
1932 if( !stream->inputAudioBufferList.mBuffers[0].mData )
1933 {
1934 result = paInsufficientMemory;
1935 goto error;
1936 }
1937
1938 /*
1939 * If input and output devs are different or we are doing SR conversion,
1940 * we also need a ring buffer to store input data while waiting for
1941 * output data.
1942 */
1943 if( (stream->outputUnit && (stream->inputUnit != stream->outputUnit))
1944 || stream->inputSRConverter )
1945 {
1946 /* May want the ringSize or initial position in
1947 ring buffer to depend somewhat on sample rate change */
1948
1949 void *data;
1950 long ringSize;
1951
1952 ringSize = computeRingBufferSize( inputParameters,
1953 outputParameters,
1954 stream->inputFramesPerBuffer,
1955 stream->outputFramesPerBuffer,
1956 sampleRate );
1957 /*ringSize <<= 4; *//*16x bigger, for testing */
1958
1959
1960 /*now, we need to allocate memory for the ring buffer*/
1961 data = calloc( ringSize, szfl*inputParameters->channelCount );
1962 if( !data )
1963 {
1964 result = paInsufficientMemory;
1965 goto error;
1966 }
1967
1968 /* now we can initialize the ring buffer */
1969 result = PaUtil_InitializeRingBuffer( &stream->inputRingBuffer, szfl*inputParameters->channelCount, ringSize, data );
1970 if( result != 0 )
1971 {
1972 /* The only reason this should fail is if ringSize is not a power of 2, which we do not anticipate happening. */
1973 result = paUnanticipatedHostError;
1974 free(data);
1975 goto error;
1976 }
1977
1978 /* advance the read point a little, so we are reading from the
1979 middle of the buffer */
1980 if( stream->outputUnit )
1981 PaUtil_AdvanceRingBufferWriteIndex( &stream->inputRingBuffer, ringSize / RING_BUFFER_ADVANCE_DENOMINATOR );
1982
1983 // Just adds to input latency between input device and PA full duplex callback.
1984 inputLatencyFrames += ringSize;
1985 }
1986 }
1987
1988 /* -- initialize Blio Buffer Processors -- */
1989 if( !streamCallback )
1990 {
1991 long ringSize;
1992
1993 ringSize = computeRingBufferSize( inputParameters,
1994 outputParameters,
1995 stream->inputFramesPerBuffer,
1996 stream->outputFramesPerBuffer,
1997 sampleRate );
1998 result = initializeBlioRingBuffers( &stream->blio,
1999 inputParameters ? inputParameters->sampleFormat : 0,
2000 outputParameters ? outputParameters->sampleFormat : 0,
2001 ringSize,
2002 inputParameters ? inputChannelCount : 0,
2003 outputParameters ? outputChannelCount : 0 );
2004 if( result != paNoError )
2005 goto error;
2006
2007 inputLatencyFrames += ringSize;
2008 outputLatencyFrames += ringSize;
2009
2010 }
2011
2012 /* -- initialize Buffer Processor -- */
2013 {
2014 unsigned long maxHostFrames = stream->inputFramesPerBuffer;
2015 if( stream->outputFramesPerBuffer > maxHostFrames )
2016 maxHostFrames = stream->outputFramesPerBuffer;
2017 result = PaUtil_InitializeBufferProcessor( &stream->bufferProcessor,
2018 inputChannelCount, inputSampleFormat,
2019 hostInputSampleFormat,
2020 outputChannelCount, outputSampleFormat,
2021 hostOutputSampleFormat,
2022 sampleRate,
2023 streamFlags,
2024 requestedFramesPerBuffer,
2025 /* If sample rate conversion takes place, the buffer size
2026 will not be known. */
2027 maxHostFrames,
2028 stream->inputSRConverter
2029 ? paUtilUnknownHostBufferSize
2030 : paUtilBoundedHostBufferSize,
2031 streamCallback ? streamCallback : BlioCallback,
2032 streamCallback ? userData : &stream->blio );
2033 if( result != paNoError )
2034 goto error;
2035 }
2036 stream->bufferProcessorIsInitialized = TRUE;
2037
2038 // Calculate actual latency from the sum of individual latencies.
2039 if( inputParameters )
2040 {
2041 inputLatencyFrames += PaUtil_GetBufferProcessorInputLatencyFrames(&stream->bufferProcessor);
2042 stream->streamRepresentation.streamInfo.inputLatency = inputLatencyFrames / sampleRate;
2043 }
2044 else
2045 {
2046 stream->streamRepresentation.streamInfo.inputLatency = 0.0;
2047 }
2048
2049 if( outputParameters )
2050 {
2051 outputLatencyFrames += PaUtil_GetBufferProcessorOutputLatencyFrames(&stream->bufferProcessor);
2052 stream->streamRepresentation.streamInfo.outputLatency = outputLatencyFrames / sampleRate;
2053 }
2054 else
2055 {
2056 stream->streamRepresentation.streamInfo.outputLatency = 0.0;
2057 }
2058
2059 stream->streamRepresentation.streamInfo.sampleRate = sampleRate;
2060
2061 stream->sampleRate = sampleRate;
2062
2063 stream->userInChan = inputChannelCount;
2064 stream->userOutChan = outputChannelCount;
2065
2066 // Setup property listeners for timestamp and latency calculations.
2067 pthread_mutex_init( &stream->timingInformationMutex, NULL );
2068 stream->timingInformationMutexIsInitialized = 1;
2069 InitializeDeviceProperties( &stream->inputProperties ); // zeros the struct. doesn't actually init it to useful values
2070 InitializeDeviceProperties( &stream->outputProperties ); // zeros the struct. doesn't actually init it to useful values
2071 if( stream->outputUnit )
2072 {
2073 Boolean isInput = FALSE;
2074
2075 // Start with the current values for the device properties.
2076 // Init with nominal sample rate. Use actual sample rate where available
2077
2078 result = ERR( UpdateSampleRateFromDeviceProperty(
2079 stream, stream->outputDevice, isInput, kAudioDevicePropertyNominalSampleRate ) );
2080 if( result )
2081 goto error; /* fail if we can't even get a nominal device sample rate */
2082
2083 UpdateSampleRateFromDeviceProperty( stream, stream->outputDevice, isInput, kAudioDevicePropertyActualSampleRate );
2084
2085 SetupDevicePropertyListeners( stream, stream->outputDevice, isInput );
2086 }
2087 if( stream->inputUnit )
2088 {
2089 Boolean isInput = TRUE;
2090
2091 // as above
2092 result = ERR( UpdateSampleRateFromDeviceProperty(
2093 stream, stream->inputDevice, isInput, kAudioDevicePropertyNominalSampleRate ) );
2094 if( result )
2095 goto error;
2096
2097 UpdateSampleRateFromDeviceProperty( stream, stream->inputDevice, isInput, kAudioDevicePropertyActualSampleRate );
2098
2099 SetupDevicePropertyListeners( stream, stream->inputDevice, isInput );
2100 }
2101 UpdateTimeStampOffsets( stream );
2102 // Setup timestamp copies to be used by audio callback.
2103 stream->timestampOffsetCombined_ioProcCopy = stream->timestampOffsetCombined;
2104 stream->timestampOffsetInputDevice_ioProcCopy = stream->timestampOffsetInputDevice;
2105 stream->timestampOffsetOutputDevice_ioProcCopy = stream->timestampOffsetOutputDevice;
2106
2107 stream->state = STOPPED;
2108 stream->xrunFlags = 0;
2109
2110 *s = (PaStream*)stream;
2111
2112 return result;
2113
2114 error:
2115 CloseStream( stream );
2116 return result;
2117 }
2118
2119
2120 #define HOST_TIME_TO_PA_TIME( x ) ( AudioConvertHostTimeToNanos( (x) ) * 1.0E-09) /* convert to nanoseconds and then to seconds */
2121
2122 PaTime GetStreamTime( PaStream *s )
2123 {
2124 return HOST_TIME_TO_PA_TIME( AudioGetCurrentHostTime() );
2125 }
2126
2127 #define RING_BUFFER_EMPTY (1000)
2128
2129 static OSStatus ringBufferIOProc(
2130 AudioConverterRef inAudioConverter,
2131 UInt32* ioNumberDataPackets,
2132 AudioBufferList* ioData,
2133 AudioStreamPacketDescription** outDataPacketDescription,
2134 void* inUserData)
2135 {
2136 VVDBUG(("ringBufferIOProc()\n"));
2137
2138 PaUtilRingBuffer *rb = (PaUtilRingBuffer *) inUserData;
2139
2140 if( PaUtil_GetRingBufferReadAvailable( rb ) == 0 ) {
2141 ioData->mBuffers[0].mData = NULL;
2142 ioData->mBuffers[0].mDataByteSize = 0;
2143 *ioNumberDataPackets = 0;
2144 VVDBUG(("Ring buffer empty!\n"));
2145 return RING_BUFFER_EMPTY;
2146 }
2147
2148 UInt32 packetSize = sizeof(float) * ioData->mBuffers[0].mNumberChannels;
2149 UInt32 dataSize = *ioNumberDataPackets * packetSize;
2150 assert(dataSize % rb->elementSizeBytes == 0);
2151 UInt32 rbElements = dataSize / rb->elementSizeBytes;
2152 ring_buffer_size_t rbElementsRead = rbElements;
2153 void *dummyData;
2154 ring_buffer_size_t dummySize;
2155 PaUtil_GetRingBufferReadRegions( rb, rbElements,
2156 &ioData->mBuffers[0].mData, &rbElementsRead,
2157 &dummyData, &dummySize );
2158 assert(rbElementsRead > 0);
2159 VVDBUG(("RingBuffer read elements %u of %u\n", rbElementsRead, rbElements));
2160 PaUtil_AdvanceRingBufferReadIndex( rb, rbElementsRead );
2161
2162 UInt32 bytesRead = rbElementsRead * rb->elementSizeBytes;
2163 ioData->mBuffers[0].mDataByteSize = bytesRead;
2164 *ioNumberDataPackets = bytesRead / packetSize;
2165
2166 return noErr;
2167 }
2168
2169 /*
2170 * Called by the AudioUnit API to process audio from the sound card.
2171 * This is where the magic happens.
2172 */
2173 /* 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. */
2174 static OSStatus AudioIOProc( void *inRefCon,
2175 AudioUnitRenderActionFlags *ioActionFlags,
2176 const AudioTimeStamp *inTimeStamp,
2177 UInt32 inBusNumber,
2178 UInt32 inNumberFrames,
2179 AudioBufferList *ioData )
2180 {
2181 unsigned long framesProcessed = 0;
2182 PaStreamCallbackTimeInfo timeInfo = {0,0,0};
2183 PaMacCoreStream *stream = (PaMacCoreStream*)inRefCon;
2184 const bool isRender = inBusNumber == OUTPUT_ELEMENT;
2185 int callbackResult = paContinue ;
2186 double hostTimeStampInPaTime = HOST_TIME_TO_PA_TIME(inTimeStamp->mHostTime);
2187
2188 VVDBUG(("AudioIOProc()\n"));
2189
2190 PaUtil_BeginCpuLoadMeasurement( &stream->cpuLoadMeasurer );
2191
2192 /* -----------------------------------------------------------------*\
2193 This output may be useful for debugging,
2194 But printing during the callback is a bad enough idea that
2195 this is not enabled by enabling the usual debugging calls.
2196 \* -----------------------------------------------------------------*/
2197 /*
2198 static int renderCount = 0;
2199 static int inputCount = 0;
2200 printf( "------------------- starting render/input\n" );
2201 if( isRender )
2202 printf("Render callback (%d):\t", ++renderCount);
2203 else
2204 printf("Input callback (%d):\t", ++inputCount);
2205 printf( "Call totals: %d (input), %d (render)\n", inputCount, renderCount );
2206
2207 printf( "--- inBusNumber: %lu\n", inBusNumber );
2208 printf( "--- inNumberFrames: %lu\n", inNumberFrames );
2209 printf( "--- %x ioData\n", (unsigned) ioData );
2210 if( ioData )
2211 {
2212 int i=0;
2213 printf( "--- ioData.mNumBuffers %lu: \n", ioData->mNumberBuffers );
2214 for( i=0; i<ioData->mNumberBuffers; ++i )
2215 printf( "--- ioData buffer %d size: %lu.\n", i, ioData->mBuffers[i].mDataByteSize );
2216 }
2217 ----------------------------------------------------------------- */
2218
2219 /* compute PaStreamCallbackTimeInfo */
2220
2221 if( pthread_mutex_trylock( &stream->timingInformationMutex ) == 0 ) {
2222 /* snapshot the ioproc copy of timing information */
2223 stream->timestampOffsetCombined_ioProcCopy = stream->timestampOffsetCombined;
2224 stream->timestampOffsetInputDevice_ioProcCopy = stream->timestampOffsetInputDevice;
2225 stream->timestampOffsetOutputDevice_ioProcCopy = stream->timestampOffsetOutputDevice;
2226 pthread_mutex_unlock( &stream->timingInformationMutex );
2227 }
2228
2229 /* For timeInfo.currentTime we could calculate current time backwards from the HAL audio
2230 output time to give a more accurate impression of the current timeslice but it doesn't
2231 seem worth it at the moment since other PA host APIs don't do any better.
2232 */
2233 timeInfo.currentTime = HOST_TIME_TO_PA_TIME( AudioGetCurrentHostTime() );
2234
2235 /*
2236 For an input HAL AU, inTimeStamp is the time the samples are received from the hardware,
2237 for an output HAL AU inTimeStamp is the time the samples are sent to the hardware.
2238 PA expresses timestamps in terms of when the samples enter the ADC or leave the DAC
2239 so we add or subtract kAudioDevicePropertyLatency below.
2240 */
2241
2242 /* FIXME: not sure what to do below if the host timestamps aren't valid (kAudioTimeStampHostTimeValid isn't set)
2243 Could ask on CA mailing list if it is possible for it not to be set. If so, could probably grab a now timestamp
2244 at the top and compute from there (modulo scheduling jitter) or ask on mailing list for other options. */
2245
2246 if( isRender )
2247 {
2248 if( stream->inputUnit ) /* full duplex */
2249 {
2250 if( stream->inputUnit == stream->outputUnit ) /* full duplex AUHAL IOProc */
2251 {
2252 // Ross and Phil agreed that the following calculation is correct based on an email from Jeff Moore:
2253 // http://osdir.com/ml/coreaudio-api/2009-07/msg00140.html
2254 // Basically the difference between the Apple output timestamp and the PA timestamp is kAudioDevicePropertyLatency.
2255 timeInfo.inputBufferAdcTime = hostTimeStampInPaTime -
2256 (stream->timestampOffsetCombined_ioProcCopy + stream->timestampOffsetInputDevice_ioProcCopy);
2257 timeInfo.outputBufferDacTime = hostTimeStampInPaTime + stream->timestampOffsetOutputDevice_ioProcCopy;
2258 }
2259 else /* full duplex with ring-buffer from a separate input AUHAL ioproc */
2260 {
2261 /* FIXME: take the ring buffer latency into account */
2262 timeInfo.inputBufferAdcTime = hostTimeStampInPaTime -
2263 (stream->timestampOffsetCombined_ioProcCopy + stream->timestampOffsetInputDevice_ioProcCopy);
2264 timeInfo.outputBufferDacTime = hostTimeStampInPaTime + stream->timestampOffsetOutputDevice_ioProcCopy;
2265 }
2266 }
2267 else /* output only */
2268 {
2269 timeInfo.inputBufferAdcTime = 0;
2270 timeInfo.outputBufferDacTime = hostTimeStampInPaTime + stream->timestampOffsetOutputDevice_ioProcCopy;
2271 }
2272 }
2273 else /* input only */
2274 {
2275 timeInfo.inputBufferAdcTime = hostTimeStampInPaTime - stream->timestampOffsetInputDevice_ioProcCopy;
2276 timeInfo.outputBufferDacTime = 0;
2277 }
2278
2279 //printf( "---%g, %g, %g\n", timeInfo.inputBufferAdcTime, timeInfo.currentTime, timeInfo.outputBufferDacTime );
2280
2281 if( isRender && stream->inputUnit == stream->outputUnit
2282 && !stream->inputSRConverter )
2283 {
2284 /* --------- Full Duplex, One Device, no SR Conversion -------
2285 *
2286 * This is the lowest latency case, and also the simplest.
2287 * Input data and output data are available at the same time.
2288 * we do not use the input SR converter or the input ring buffer.
2289 *
2290 */
2291 OSStatus err = 0;
2292 unsigned long frames;
2293 long bytesPerFrame = sizeof( float ) * ioData->mBuffers[0].mNumberChannels;
2294
2295 /* -- start processing -- */
2296 PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),
2297 &timeInfo,
2298 stream->xrunFlags );
2299 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.
2300
2301 /* -- compute frames. do some checks -- */
2302 assert( ioData->mNumberBuffers == 1 );
2303 assert( ioData->mBuffers[0].mNumberChannels == stream->userOutChan );
2304
2305 frames = ioData->mBuffers[0].mDataByteSize / bytesPerFrame;
2306 /* -- copy and process input data -- */
2307 err= AudioUnitRender( stream->inputUnit,
2308 ioActionFlags,
2309 inTimeStamp,
2310 INPUT_ELEMENT,
2311 inNumberFrames,
2312 &stream->inputAudioBufferList );
2313 if(err != noErr)
2314 {
2315 goto stop_stream;
2316 }
2317
2318 PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );
2319 PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
2320 0,
2321 stream->inputAudioBufferList.mBuffers[0].mData,
2322 stream->inputAudioBufferList.mBuffers[0].mNumberChannels );
2323 /* -- Copy and process output data -- */
2324 PaUtil_SetOutputFrameCount( &(stream->bufferProcessor), frames );
2325 PaUtil_SetInterleavedOutputChannels( &(stream->bufferProcessor),
2326 0,
2327 ioData->mBuffers[0].mData,
2328 ioData->mBuffers[0].mNumberChannels );
2329 /* -- complete processing -- */
2330 framesProcessed =
2331 PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
2332 &callbackResult );
2333 }
2334 else if( isRender )
2335 {
2336 /* -------- Output Side of Full Duplex (Separate Devices or SR Conversion)
2337 * -- OR Simplex Output
2338 *
2339 * This case handles output data as in the full duplex case,
2340 * and, if there is input data, reads it off the ring buffer
2341 * and into the PA buffer processor. If sample rate conversion
2342 * is required on input, that is done here as well.
2343 */
2344 unsigned long frames;
2345 long bytesPerFrame = sizeof( float ) * ioData->mBuffers[0].mNumberChannels;
2346
2347 /* Sometimes, when stopping a duplex stream we get erroneous
2348 xrun flags, so if this is our last run, clear the flags. */
2349 int xrunFlags = stream->xrunFlags;
2350 /*
2351 if( xrunFlags & paInputUnderflow )
2352 printf( "input underflow.\n" );
2353 if( xrunFlags & paInputOverflow )
2354 printf( "input overflow.\n" );
2355 */
2356 if( stream->state == STOPPING || stream->state == CALLBACK_STOPPED )
2357 xrunFlags = 0;
2358
2359 /* -- start processing -- */
2360 PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),
2361 &timeInfo,
2362 xrunFlags );
2363 stream->xrunFlags = 0; /* FEEDBACK: we only send flags to Buf Proc once */
2364
2365 /* -- Copy and process output data -- */
2366 assert( ioData->mNumberBuffers == 1 );
2367 frames = ioData->mBuffers[0].mDataByteSize / bytesPerFrame;
2368 assert( ioData->mBuffers[0].mNumberChannels == stream->userOutChan );
2369 PaUtil_SetOutputFrameCount( &(stream->bufferProcessor), frames );
2370 PaUtil_SetInterleavedOutputChannels( &(stream->bufferProcessor),
2371 0,
2372 ioData->mBuffers[0].mData,
2373 ioData->mBuffers[0].mNumberChannels );
2374
2375 /* -- copy and process input data, and complete processing -- */
2376 if( stream->inputUnit ) {
2377 const int flsz = sizeof( float );
2378 /* Here, we read the data out of the ring buffer, through the
2379 audio converter. */
2380 int inChan = stream->inputAudioBufferList.mBuffers[0].mNumberChannels;
2381 long bytesPerFrame = flsz * inChan;
2382
2383 if( stream->inputSRConverter )
2384 {
2385 OSStatus err;
2386 float data[ inChan * frames ];
2387 AudioBufferList bufferList;
2388 bufferList.mNumberBuffers = 1;
2389 bufferList.mBuffers[0].mNumberChannels = inChan;
2390 bufferList.mBuffers[0].mDataByteSize = sizeof( data );
2391 bufferList.mBuffers[0].mData = data;
2392 UInt32 packets = frames;
2393 err = AudioConverterFillComplexBuffer(
2394 stream->inputSRConverter,
2395 ringBufferIOProc,
2396 &stream->inputRingBuffer,
2397 &packets,
2398 &bufferList,
2399 NULL);
2400 if( err == RING_BUFFER_EMPTY )
2401 { /* the ring buffer callback underflowed */
2402 err = 0;
2403 UInt32 size = packets * bytesPerFrame;
2404 bzero( ((char *)data) + size, sizeof(data)-size );
2405 /* The ring buffer can underflow normally when the stream is stopping.
2406 * So only report an error if the stream is active. */
2407 if( stream->state == ACTIVE )
2408 {
2409 stream->xrunFlags |= paInputUnderflow;
2410 }
2411 }
2412 ERR( err );
2413 if(err != noErr)
2414 {
2415 goto stop_stream;
2416 }
2417
2418 PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );
2419 PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
2420 0,
2421 data,
2422 inChan );
2423 framesProcessed =
2424 PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
2425 &callbackResult );
2426 }
2427 else
2428 {
2429 /* Without the AudioConverter is actually a bit more complex
2430 because we have to do a little buffer processing that the
2431 AudioConverter would otherwise handle for us. */
2432 void *data1, *data2;
2433 ring_buffer_size_t size1, size2;
2434 ring_buffer_size_t framesReadable = PaUtil_GetRingBufferReadRegions( &stream->inputRingBuffer,
2435 frames,
2436 &data1, &size1,
2437 &data2, &size2 );
2438 if( size1 == frames ) {
2439 /* simplest case: all in first buffer */
2440 PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );
2441 PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
2442 0,
2443 data1,
2444 inChan );
2445 framesProcessed =
2446 PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
2447 &callbackResult );
2448 PaUtil_AdvanceRingBufferReadIndex(&stream->inputRingBuffer, size1 );
2449 } else if( framesReadable < frames ) {
2450
2451 long sizeBytes1 = size1 * bytesPerFrame;
2452 long sizeBytes2 = size2 * bytesPerFrame;
2453 /*we underflowed. take what data we can, zero the rest.*/
2454 unsigned char data[ frames * bytesPerFrame ];
2455 if( size1 > 0 )
2456 {
2457 memcpy( data, data1, sizeBytes1 );
2458 }
2459 if( size2 > 0 )
2460 {
2461 memcpy( data+sizeBytes1, data2, sizeBytes2 );
2462 }
2463 bzero( data+sizeBytes1+sizeBytes2, (frames*bytesPerFrame) - sizeBytes1 - sizeBytes2 );
2464
2465 PaUtil_SetInputFrameCount( &(stream->bufferProcessor), frames );
2466 PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
2467 0,
2468 data,
2469 inChan );
2470 framesProcessed =
2471 PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
2472 &callbackResult );
2473 PaUtil_AdvanceRingBufferReadIndex( &stream->inputRingBuffer,
2474 framesReadable );
2475 /* flag underflow */
2476 stream->xrunFlags |= paInputUnderflow;
2477 } else {
2478 /*we got all the data, but split between buffers*/
2479 PaUtil_SetInputFrameCount( &(stream->bufferProcessor), size1 );
2480 PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
2481 0,
2482 data1,
2483 inChan );
2484 PaUtil_Set2ndInputFrameCount( &(stream->bufferProcessor), size2 );
2485 PaUtil_Set2ndInterleavedInputChannels( &(stream->bufferProcessor),
2486 0,
2487 data2,
2488 inChan );
2489 framesProcessed =
2490 PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
2491 &callbackResult );
2492 PaUtil_AdvanceRingBufferReadIndex(&stream->inputRingBuffer, framesReadable );
2493 }
2494 }
2495 } else {
2496 framesProcessed =
2497 PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
2498 &callbackResult );
2499 }
2500
2501 }
2502 else
2503 {
2504 /* ------------------ Input
2505 *
2506 * First, we read off the audio data and put it in the ring buffer.
2507 * if this is an input-only stream, we need to process it more,
2508 * otherwise, we let the output case deal with it.
2509 */
2510 OSStatus err = 0;
2511 int chan = stream->inputAudioBufferList.mBuffers[0].mNumberChannels ;
2512 /* FIXME: looping here may not actually be necessary, but it was something I tried in testing. */
2513 do {
2514 err= AudioUnitRender( stream->inputUnit,
2515 ioActionFlags,
2516 inTimeStamp,
2517 INPUT_ELEMENT,
2518 inNumberFrames,
2519 &stream->inputAudioBufferList );
2520 if( err == -10874 )
2521 inNumberFrames /= 2;
2522 } while( err == -10874 && inNumberFrames > 1 );
2523 ERR( err );
2524 if(err != noErr)
2525 {
2526 goto stop_stream;
2527 }
2528
2529 if( stream->inputSRConverter || stream->outputUnit )
2530 {
2531 /* If this is duplex or we use a converter, put the data
2532 into the ring buffer. */
2533 ring_buffer_size_t framesWritten = PaUtil_WriteRingBuffer( &stream->inputRingBuffer,
2534 stream->inputAudioBufferList.mBuffers[0].mData,
2535 inNumberFrames );
2536 if( framesWritten != inNumberFrames )
2537 {
2538 stream->xrunFlags |= paInputOverflow ;
2539 }
2540 }
2541 else
2542 {
2543 /* for simplex input w/o SR conversion,
2544 just pop the data into the buffer processor.*/
2545 PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),
2546 &timeInfo,
2547 stream->xrunFlags );
2548 stream->xrunFlags = 0;
2549
2550 PaUtil_SetInputFrameCount( &(stream->bufferProcessor), inNumberFrames);
2551 PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
2552 0,
2553 stream->inputAudioBufferList.mBuffers[0].mData,
2554 chan );
2555 framesProcessed =
2556 PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
2557 &callbackResult );
2558 }
2559 if( !stream->outputUnit && stream->inputSRConverter )
2560 {
2561 /* ------------------ Simplex Input w/ SR Conversion
2562 *
2563 * if this is a simplex input stream, we need to read off the buffer,
2564 * do our sample rate conversion and pass the results to the buffer
2565 * processor.
2566 * The logic here is complicated somewhat by the fact that we don't
2567 * know how much data is available, so we loop on reasonably sized
2568 * chunks, and let the BufferProcessor deal with the rest.
2569 *
2570 */
2571 /* This might be too big or small depending on SR conversion. */
2572 float data[ chan * inNumberFrames ];
2573 OSStatus err;
2574 do
2575 { /* Run the buffer processor until we are out of data. */
2576 AudioBufferList bufferList;
2577 bufferList.mNumberBuffers = 1;
2578 bufferList.mBuffers[0].mNumberChannels = chan;
2579 bufferList.mBuffers[0].mDataByteSize = sizeof( data );
2580 bufferList.mBuffers[0].mData = data;
2581 UInt32 packets = inNumberFrames;
2582 err = AudioConverterFillComplexBuffer(
2583 stream->inputSRConverter,
2584 ringBufferIOProc,
2585 &stream->inputRingBuffer,
2586 &packets,
2587 &bufferList,
2588 NULL);
2589 if( err != RING_BUFFER_EMPTY )
2590 ERR( err );
2591 if( err != noErr && err != RING_BUFFER_EMPTY )
2592 {
2593 goto stop_stream;
2594 }
2595
2596 PaUtil_SetInputFrameCount( &(stream->bufferProcessor), packets );
2597 if( packets > 0 )
2598 {
2599 PaUtil_BeginBufferProcessing( &(stream->bufferProcessor),
2600 &timeInfo,
2601 stream->xrunFlags );
2602 stream->xrunFlags = 0;
2603
2604 PaUtil_SetInterleavedInputChannels( &(stream->bufferProcessor),
2605 0,
2606 data,
2607 chan );
2608 framesProcessed =
2609 PaUtil_EndBufferProcessing( &(stream->bufferProcessor),
2610 &callbackResult );
2611 }
2612 } while( callbackResult == paContinue && !err );
2613 }
2614 }
2615
2616 // Should we return successfully or fall through to stopping the stream?
2617 if( callbackResult == paContinue )
2618 {
2619 PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
2620 return noErr;
2621 }
2622
2623 stop_stream:
2624 stream->state = CALLBACK_STOPPED ;
2625 if( stream->outputUnit )
2626 AudioOutputUnitStop(stream->outputUnit);
2627 if( stream->inputUnit )
2628 AudioOutputUnitStop(stream->inputUnit);
2629
2630 PaUtil_EndCpuLoadMeasurement( &stream->cpuLoadMeasurer, framesProcessed );
2631 return noErr;
2632 }
2633
2634 /*
2635 When CloseStream() is called, the multi-api layer ensures that
2636 the stream has already been stopped or aborted.
2637 */
2638 static PaError CloseStream( PaStream* s )
2639 {
2640 /* This may be called from a failed OpenStream.
2641 Therefore, each piece of info is treated separately. */
2642 PaError result = paNoError;
2643 PaMacCoreStream *stream = (PaMacCoreStream*)s;
2644
2645 VVDBUG(("CloseStream()\n"));
2646 VDBUG( ( "Closing stream.\n" ) );
2647
2648 if( stream ) {
2649
2650 if( stream->outputUnit )
2651 {
2652 Boolean isInput = FALSE;
2653 CleanupDevicePropertyListeners( stream, stream->outputDevice, isInput );
2654 }
2655
2656 if( stream->inputUnit )
2657 {
2658 Boolean isInput = TRUE;
2659 CleanupDevicePropertyListeners( stream, stream->inputDevice, isInput );
2660 }
2661
2662 if( stream->outputUnit ) {
2663 int count = removeFromXRunListenerList( stream );
2664 if( count == 0 )
2665 PaMacCore_AudioDeviceRemovePropertyListener( stream->outputDevice,
2666 0,
2667 false,
2668 kAudioDeviceProcessorOverload,
2669 xrunCallback, NULL ); //no need to pass actual node
2670 }
2671 if( stream->inputUnit && stream->outputUnit != stream->inputUnit ) {
2672 int count = removeFromXRunListenerList( stream );
2673 if( count == 0 )
2674 PaMacCore_AudioDeviceRemovePropertyListener( stream->inputDevice,
2675 0,
2676 true,
2677 kAudioDeviceProcessorOverload,
2678 xrunCallback, NULL ); //no need to pass actual node
2679 }
2680 if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) {
2681 AudioUnitUninitialize( stream->outputUnit );
2682 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
2683 AudioComponentInstanceDispose( stream->outputUnit );
2684 #else
2685 CloseComponent( stream->outputUnit );
2686 #endif
2687 }
2688 stream->outputUnit = NULL;
2689 if( stream->inputUnit )
2690 {
2691 AudioUnitUninitialize( stream->inputUnit );
2692 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
2693 AudioComponentInstanceDispose( stream->inputUnit );
2694 #else
2695 CloseComponent( stream->inputUnit );
2696 #endif
2697 stream->inputUnit = NULL;
2698 }
2699 if( stream->inputRingBuffer.buffer )
2700 free( (void *) stream->inputRingBuffer.buffer );
2701 stream->inputRingBuffer.buffer = NULL;
2702 /*TODO: is there more that needs to be done on error
2703 from AudioConverterDispose?*/
2704 if( stream->inputSRConverter )
2705 ERR( AudioConverterDispose( stream->inputSRConverter ) );
2706 stream->inputSRConverter = NULL;
2707 if( stream->inputAudioBufferList.mBuffers[0].mData )
2708 free( stream->inputAudioBufferList.mBuffers[0].mData );
2709 stream->inputAudioBufferList.mBuffers[0].mData = NULL;
2710
2711 result = destroyBlioRingBuffers( &stream->blio );
2712 if( result )
2713 return result;
2714 if( stream->bufferProcessorIsInitialized )
2715 PaUtil_TerminateBufferProcessor( &stream->bufferProcessor );
2716
2717 if( stream->timingInformationMutexIsInitialized )
2718 pthread_mutex_destroy( &stream->timingInformationMutex );
2719
2720 PaUtil_TerminateStreamRepresentation( &stream->streamRepresentation );
2721 PaUtil_FreeMemory( stream );
2722 }
2723
2724 return result;
2725 }
2726
2727 static PaError StartStream( PaStream *s )
2728 {
2729 PaMacCoreStream *stream = (PaMacCoreStream*)s;
2730 OSStatus result = noErr;
2731 VVDBUG(("StartStream()\n"));
2732 VDBUG( ( "Starting stream.\n" ) );
2733
2734 #define ERR_WRAP(mac_err) do { result = mac_err ; if ( result != noErr ) return ERR(result) ; } while(0)
2735
2736 /*FIXME: maybe want to do this on close/abort for faster start? */
2737 PaUtil_ResetBufferProcessor( &stream->bufferProcessor );
2738 if( stream->inputSRConverter )
2739 ERR_WRAP( AudioConverterReset( stream->inputSRConverter ) );
2740
2741 /* -- start -- */
2742 stream->state = ACTIVE;
2743 if( stream->inputUnit ) {
2744 ERR_WRAP( AudioOutputUnitStart(stream->inputUnit) );
2745 }
2746 if( stream->outputUnit && stream->outputUnit != stream->inputUnit ) {
2747 ERR_WRAP( AudioOutputUnitStart(stream->outputUnit) );
2748 }
2749
2750 return paNoError;
2751 #undef ERR_WRAP
2752 }
2753
2754 // it's not clear from appl's docs that this really waits
2755 // until all data is flushed.
2756 static ComponentResult BlockWhileAudioUnitIsRunning( AudioUnit audioUnit, AudioUnitElement element )
2757 {
2758 Boolean isRunning = 1;
2759 while( isRunning ) {
2760 UInt32 s = sizeof( isRunning );
2761 ComponentResult err = AudioUnitGetProperty( audioUnit, kAudioOutputUnitProperty_IsRunning, kAudioUnitScope_Global, element, &isRunning, &s );
2762 if( err )
2763 return err;
2764 Pa_Sleep( 100 );
2765 }
2766 return noErr;
2767 }
2768
2769 static PaError FinishStoppingStream( PaMacCoreStream *stream )
2770 {
2771 OSStatus result = noErr;
2772 PaError paErr;
2773
2774 #define ERR_WRAP(mac_err) do { result = mac_err ; if ( result != noErr ) return ERR(result) ; } while(0)
2775 /* -- stop and reset -- */
2776 if( stream->inputUnit == stream->outputUnit && stream->inputUnit )
2777 {
2778 ERR_WRAP( AudioOutputUnitStop(stream->inputUnit) );
2779 ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,0) );
2780 ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,1) );
2781 ERR_WRAP( AudioUnitReset(stream->inputUnit, kAudioUnitScope_Global, 1) );
2782 ERR_WRAP( AudioUnitReset(stream->inputUnit, kAudioUnitScope_Global, 0) );
2783 }
2784 else
2785 {
2786 if( stream->inputUnit )
2787 {
2788 ERR_WRAP(AudioOutputUnitStop(stream->inputUnit) );
2789 ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->inputUnit,1) );
2790 ERR_WRAP(AudioUnitReset(stream->inputUnit,kAudioUnitScope_Global,1));
2791 }
2792 if( stream->outputUnit )
2793 {
2794 ERR_WRAP(AudioOutputUnitStop(stream->outputUnit));
2795 ERR_WRAP( BlockWhileAudioUnitIsRunning(stream->outputUnit,0) );
2796 ERR_WRAP(AudioUnitReset(stream->outputUnit,kAudioUnitScope_Global,0));
2797 }
2798 }
2799 if( stream->inputRingBuffer.buffer ) {
2800 PaUtil_FlushRingBuffer( &stream->inputRingBuffer );
2801 bzero( (void *)stream->inputRingBuffer.buffer,
2802 stream->inputRingBuffer.bufferSize );
2803 /* advance the write point a little, so we are reading from the
2804 middle of the buffer. We'll need extra at the end because
2805 testing has shown that this helps. */
2806 if( stream->outputUnit )
2807 PaUtil_AdvanceRingBufferWriteIndex( &stream->inputRingBuffer,
2808 stream->inputRingBuffer.bufferSize
2809 / RING_BUFFER_ADVANCE_DENOMINATOR );
2810 }
2811
2812 stream->xrunFlags = 0;
2813 stream->state = STOPPED;
2814
2815 paErr = resetBlioRingBuffers( &stream->blio );
2816 if( paErr )
2817 return paErr;
2818
2819 VDBUG( ( "Stream Stopped.\n" ) );
2820 return paNoError;
2821 #undef ERR_WRAP
2822 }
2823
2824 /* Block until buffer is empty then stop the stream. */
2825 static PaError StopStream( PaStream *s )
2826 {
2827 PaError paErr;
2828 PaMacCoreStream *stream = (PaMacCoreStream*)s;
2829 VVDBUG(("StopStream()\n"));
2830
2831 /* Tell WriteStream to stop filling the buffer. */
2832 stream->state = STOPPING;
2833
2834 if( stream->userOutChan > 0 ) /* Does this stream do output? */
2835 {
2836 size_t maxHostFrames = MAX( stream->inputFramesPerBuffer, stream->outputFramesPerBuffer );
2837 VDBUG( ("Waiting for write buffer to be drained.\n") );
2838 paErr = waitUntilBlioWriteBufferIsEmpty( &stream->blio, stream->sampleRate,
2839 maxHostFrames );
2840 VDBUG( ( "waitUntilBlioWriteBufferIsEmpty returned %d\n", paErr ) );
2841 }
2842 return FinishStoppingStream( stream );
2843 }
2844
2845 /* Immediately stop the stream. */
2846 static PaError AbortStream( PaStream *s )
2847 {
2848 PaMacCoreStream *stream = (PaMacCoreStream*)s;
2849 VDBUG( ( "AbortStream()\n" ) );
2850 stream->state = STOPPING;
2851 return FinishStoppingStream( stream );
2852 }
2853
2854
2855 static PaError IsStreamStopped( PaStream *s )
2856 {
2857 PaMacCoreStream *stream = (PaMacCoreStream*)s;
2858 VVDBUG(("IsStreamStopped()\n"));
2859
2860 return stream->state == STOPPED ? 1 : 0;
2861 }
2862
2863
2864 static PaError IsStreamActive( PaStream *s )
2865 {
2866 PaMacCoreStream *stream = (PaMacCoreStream*)s;
2867 VVDBUG(("IsStreamActive()\n"));
2868 return ( stream->state == ACTIVE || stream->state == STOPPING );
2869 }
2870
2871
2872 static double GetStreamCpuLoad( PaStream* s )
2873 {
2874 PaMacCoreStream *stream = (PaMacCoreStream*)s;
2875 VVDBUG(("GetStreamCpuLoad()\n"));
2876
2877 return PaUtil_GetCpuLoad( &stream->cpuLoadMeasurer );
2878 }