Debian Codegraph @

external/portaudio/pa_mac_core_utilities.c

raw
1 /*
2 * Helper and utility functions for pa_mac_core.c (Apple AUHAL implementation)
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
56 @ingroup hostapi_src
57 */
58
59 #include "pa_mac_core_utilities.h"
60 #include "pa_mac_core_internal.h"
61 #include <libkern/OSAtomic.h>
62 #include <strings.h>
63 #include <pthread.h>
64 #include <sys/time.h>
65
66 OSStatus PaMacCore_AudioHardwareGetProperty(
67 AudioHardwarePropertyID inPropertyID,
68 UInt32* ioPropertyDataSize,
69 void* outPropertyData )
70 {
71 AudioObjectPropertyAddress address = { inPropertyID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
72 return AudioObjectGetPropertyData(kAudioObjectSystemObject, &address, 0, NULL, ioPropertyDataSize, outPropertyData);
73 }
74
75 OSStatus PaMacCore_AudioHardwareGetPropertySize(
76 AudioHardwarePropertyID inPropertyID,
77 UInt32* outSize )
78 {
79 AudioObjectPropertyAddress address = { inPropertyID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
80 return AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &address, 0, NULL, outSize);
81 }
82
83 OSStatus PaMacCore_AudioDeviceGetProperty(
84 AudioDeviceID inDevice,
85 UInt32 inChannel,
86 Boolean isInput,
87 AudioDevicePropertyID inPropertyID,
88 UInt32* ioPropertyDataSize,
89 void* outPropertyData )
90 {
91 AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
92 AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
93 return AudioObjectGetPropertyData(inDevice, &address, 0, NULL, ioPropertyDataSize, outPropertyData);
94 }
95
96 OSStatus PaMacCore_AudioDeviceSetProperty(
97 AudioDeviceID inDevice,
98 const AudioTimeStamp* inWhen,
99 UInt32 inChannel,
100 Boolean isInput,
101 AudioDevicePropertyID inPropertyID,
102 UInt32 inPropertyDataSize,
103 const void* inPropertyData )
104 {
105 AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
106 AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
107 return AudioObjectSetPropertyData(inDevice, &address, 0, NULL, inPropertyDataSize, inPropertyData);
108 }
109
110 OSStatus PaMacCore_AudioDeviceGetPropertySize(
111 AudioDeviceID inDevice,
112 UInt32 inChannel,
113 Boolean isInput,
114 AudioDevicePropertyID inPropertyID,
115 UInt32* outSize )
116 {
117 AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
118 AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
119 return AudioObjectGetPropertyDataSize(inDevice, &address, 0, NULL, outSize);
120 }
121
122 OSStatus PaMacCore_AudioDeviceAddPropertyListener(
123 AudioDeviceID inDevice,
124 UInt32 inChannel,
125 Boolean isInput,
126 AudioDevicePropertyID inPropertyID,
127 AudioObjectPropertyListenerProc inProc,
128 void* inClientData )
129 {
130 AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
131 AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
132 return AudioObjectAddPropertyListener(inDevice, &address, inProc, inClientData);
133 }
134
135 OSStatus PaMacCore_AudioDeviceRemovePropertyListener(
136 AudioDeviceID inDevice,
137 UInt32 inChannel,
138 Boolean isInput,
139 AudioDevicePropertyID inPropertyID,
140 AudioObjectPropertyListenerProc inProc,
141 void* inClientData )
142 {
143 AudioObjectPropertyScope scope = isInput ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
144 AudioObjectPropertyAddress address = { inPropertyID, scope, inChannel };
145 return AudioObjectRemovePropertyListener(inDevice, &address, inProc, inClientData);
146 }
147
148 OSStatus PaMacCore_AudioStreamGetProperty(
149 AudioStreamID inStream,
150 UInt32 inChannel,
151 AudioDevicePropertyID inPropertyID,
152 UInt32* ioPropertyDataSize,
153 void* outPropertyData )
154 {
155 AudioObjectPropertyAddress address = { inPropertyID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
156 return AudioObjectGetPropertyData(inStream, &address, 0, NULL, ioPropertyDataSize, outPropertyData);
157 }
158
159 PaError PaMacCore_SetUnixError( int err, int line )
160 {
161 PaError ret;
162 const char *errorText;
163
164 if( err == 0 )
165 {
166 return paNoError;
167 }
168
169 ret = paNoError;
170 errorText = strerror( err );
171
172 /** Map Unix error to PaError. Pretty much the only one that maps
173 is ENOMEM. */
174 if( err == ENOMEM )
175 ret = paInsufficientMemory;
176 else
177 ret = paInternalError;
178
179 DBUG(("%d on line %d: msg='%s'\n", err, line, errorText));
180 PaUtil_SetLastHostErrorInfo( paCoreAudio, err, errorText );
181
182 return ret;
183 }
184
185 /*
186 * Translates MacOS generated errors into PaErrors
187 */
188 PaError PaMacCore_SetError(OSStatus error, int line, int isError)
189 {
190 /*FIXME: still need to handle possible ComponentResult values.*/
191 /* unfortunately, they don't seem to be documented anywhere.*/
192 PaError result;
193 const char *errorType;
194 const char *errorText;
195
196 switch (error) {
197 case kAudioHardwareNoError:
198 return paNoError;
199 case kAudioHardwareNotRunningError:
200 errorText = "Audio Hardware Not Running";
201 result = paInternalError;
202 break;
203 case kAudioHardwareUnspecifiedError:
204 errorText = "Unspecified Audio Hardware Error";
205 result = paInternalError;
206 break;
207 case kAudioHardwareUnknownPropertyError:
208 errorText = "Audio Hardware: Unknown Property";
209 result = paInternalError;
210 break;
211 case kAudioHardwareBadPropertySizeError:
212 errorText = "Audio Hardware: Bad Property Size";
213 result = paInternalError;
214 break;
215 case kAudioHardwareIllegalOperationError:
216 errorText = "Audio Hardware: Illegal Operation";
217 result = paInternalError;
218 break;
219 case kAudioHardwareBadDeviceError:
220 errorText = "Audio Hardware: Bad Device";
221 result = paInvalidDevice;
222 break;
223 case kAudioHardwareBadStreamError:
224 errorText = "Audio Hardware: BadStream";
225 result = paBadStreamPtr;
226 break;
227 case kAudioHardwareUnsupportedOperationError:
228 errorText = "Audio Hardware: Unsupported Operation";
229 result = paInternalError;
230 break;
231 case kAudioDeviceUnsupportedFormatError:
232 errorText = "Audio Device: Unsupported Format";
233 result = paSampleFormatNotSupported;
234 break;
235 case kAudioDevicePermissionsError:
236 errorText = "Audio Device: Permissions Error";
237 result = paDeviceUnavailable;
238 break;
239 /* Audio Unit Errors: http://developer.apple.com/documentation/MusicAudio/Reference/CoreAudio/audio_units/chapter_5_section_3.html */
240 case kAudioUnitErr_InvalidProperty:
241 errorText = "Audio Unit: Invalid Property";
242 result = paInternalError;
243 break;
244 case kAudioUnitErr_InvalidParameter:
245 errorText = "Audio Unit: Invalid Parameter";
246 result = paInternalError;
247 break;
248 case kAudioUnitErr_NoConnection:
249 errorText = "Audio Unit: No Connection";
250 result = paInternalError;
251 break;
252 case kAudioUnitErr_FailedInitialization:
253 errorText = "Audio Unit: Initialization Failed";
254 result = paInternalError;
255 break;
256 case kAudioUnitErr_TooManyFramesToProcess:
257 errorText = "Audio Unit: Too Many Frames";
258 result = paInternalError;
259 break;
260 case kAudioUnitErr_InvalidFile:
261 errorText = "Audio Unit: Invalid File";
262 result = paInternalError;
263 break;
264 case kAudioUnitErr_UnknownFileType:
265 errorText = "Audio Unit: Unknown File Type";
266 result = paInternalError;
267 break;
268 case kAudioUnitErr_FileNotSpecified:
269 errorText = "Audio Unit: File Not Specified";
270 result = paInternalError;
271 break;
272 case kAudioUnitErr_FormatNotSupported:
273 errorText = "Audio Unit: Format Not Supported";
274 result = paInternalError;
275 break;
276 case kAudioUnitErr_Uninitialized:
277 errorText = "Audio Unit: Uninitialized";
278 result = paInternalError;
279 break;
280 case kAudioUnitErr_InvalidScope:
281 errorText = "Audio Unit: Invalid Scope";
282 result = paInternalError;
283 break;
284 case kAudioUnitErr_PropertyNotWritable:
285 errorText = "Audio Unit: PropertyNotWritable";
286 result = paInternalError;
287 break;
288 case kAudioUnitErr_InvalidPropertyValue:
289 errorText = "Audio Unit: Invalid Property Value";
290 result = paInternalError;
291 break;
292 case kAudioUnitErr_PropertyNotInUse:
293 errorText = "Audio Unit: Property Not In Use";
294 result = paInternalError;
295 break;
296 case kAudioUnitErr_Initialized:
297 errorText = "Audio Unit: Initialized";
298 result = paInternalError;
299 break;
300 case kAudioUnitErr_InvalidOfflineRender:
301 errorText = "Audio Unit: Invalid Offline Render";
302 result = paInternalError;
303 break;
304 case kAudioUnitErr_Unauthorized:
305 errorText = "Audio Unit: Unauthorized";
306 result = paInternalError;
307 break;
308 case kAudioUnitErr_CannotDoInCurrentContext:
309 errorText = "Audio Unit: cannot do in current context";
310 result = paInternalError;
311 break;
312 default:
313 errorText = "Unknown Error";
314 result = paInternalError;
315 }
316
317 if (isError)
318 errorType = "Error";
319 else
320 errorType = "Warning";
321
322 char str[20];
323 // see if it appears to be a 4-char-code
324 *(UInt32 *)(str + 1) = CFSwapInt32HostToBig(error);
325 if (isprint(str[1]) && isprint(str[2]) && isprint(str[3]) && isprint(str[4]))
326 {
327 str[0] = str[5] = '\'';
328 str[6] = '\0';
329 } else {
330 // no, format it as an integer
331 sprintf(str, "%d", (int)error);
332 }
333
334 DBUG(("%s on line %d: err='%s', msg=%s\n", errorType, line, str, errorText));
335
336 PaUtil_SetLastHostErrorInfo( paCoreAudio, error, errorText );
337
338 return result;
339 }
340
341 /*
342 * This function computes an appropriate ring buffer size given
343 * a requested latency (in seconds), sample rate and framesPerBuffer.
344 *
345 * The returned ringBufferSize is computed using the following
346 * constraints:
347 * - it must be at least 4.
348 * - it must be at least 3x framesPerBuffer.
349 * - it must be at least 2x the suggestedLatency.
350 * - it must be a power of 2.
351 * This function attempts to compute the minimum such size.
352 *
353 * FEEDBACK: too liberal/conservative/another way?
354 */
355 long computeRingBufferSize( const PaStreamParameters *inputParameters,
356 const PaStreamParameters *outputParameters,
357 long inputFramesPerBuffer,
358 long outputFramesPerBuffer,
359 double sampleRate )
360 {
361 long ringSize;
362 int index;
363 int i;
364 double latency ;
365 long framesPerBuffer ;
366
367 VVDBUG(( "computeRingBufferSize()\n" ));
368
369 assert( inputParameters || outputParameters );
370
371 if( outputParameters && inputParameters )
372 {
373 latency = MAX( inputParameters->suggestedLatency, outputParameters->suggestedLatency );
374 framesPerBuffer = MAX( inputFramesPerBuffer, outputFramesPerBuffer );
375 }
376 else if( outputParameters )
377 {
378 latency = outputParameters->suggestedLatency;
379 framesPerBuffer = outputFramesPerBuffer ;
380 }
381 else /* we have inputParameters */
382 {
383 latency = inputParameters->suggestedLatency;
384 framesPerBuffer = inputFramesPerBuffer ;
385 }
386
387 ringSize = (long) ( latency * sampleRate * 2 + .5);
388 VDBUG( ( "suggested latency : %d\n", (int) (latency*sampleRate) ) );
389 if( ringSize < framesPerBuffer * 3 )
390 ringSize = framesPerBuffer * 3 ;
391 VDBUG(("framesPerBuffer:%d\n",(int)framesPerBuffer));
392 VDBUG(("Ringbuffer size (1): %d\n", (int)ringSize ));
393
394 /* make sure it's at least 4 */
395 ringSize = MAX( ringSize, 4 );
396
397 /* round up to the next power of 2 */
398 index = -1;
399 for( i=0; i<sizeof(long)*8; ++i )
400 if( ringSize >> i & 0x01 )
401 index = i;
402 assert( index > 0 );
403 if( ringSize <= ( 0x01 << index ) )
404 ringSize = 0x01 << index ;
405 else
406 ringSize = 0x01 << ( index + 1 );
407
408 VDBUG(( "Final Ringbuffer size (2): %d\n", (int)ringSize ));
409 return ringSize;
410 }
411
412
413 /*
414 * During testing of core audio, I found that serious crashes could occur
415 * if properties such as sample rate were changed multiple times in rapid
416 * succession. The function below could be used to with a condition variable.
417 * to prevent propertychanges from happening until the last property
418 * change is acknowledged. Instead, I implemented a busy-wait, which is simpler
419 * to implement b/c in second round of testing (nov '09) property changes occurred
420 * quickly and so there was no real way to test the condition variable implementation.
421 * therefore, this function is not used, but it is aluded to in commented code below,
422 * since it represents a theoretically better implementation.
423 */
424
425 OSStatus propertyProc(
426 AudioObjectID inObjectID,
427 UInt32 inNumberAddresses,
428 const AudioObjectPropertyAddress* inAddresses,
429 void* inClientData )
430 {
431 // this is where we would set the condition variable
432 return noErr;
433 }
434
435 /* sets the value of the given property and waits for the change to
436 be acknowledged, and returns the final value, which is not guaranteed
437 by this function to be the same as the desired value. Obviously, this
438 function can only be used for data whose input and output are the
439 same size and format, and their size and format are known in advance.
440 whether or not the call succeeds, if the data is successfully read,
441 it is returned in outPropertyData. If it is not read successfully,
442 outPropertyData is zeroed, which may or may not be useful in
443 determining if the property was read. */
444 PaError AudioDeviceSetPropertyNowAndWaitForChange(
445 AudioDeviceID inDevice,
446 UInt32 inChannel,
447 Boolean isInput,
448 AudioDevicePropertyID inPropertyID,
449 UInt32 inPropertyDataSize,
450 const void *inPropertyData,
451 void *outPropertyData )
452 {
453 OSStatus macErr;
454 UInt32 outPropertyDataSize = inPropertyDataSize;
455
456 /* First, see if it already has that value. If so, return. */
457 macErr = PaMacCore_AudioDeviceGetProperty( inDevice, inChannel,
458 isInput, inPropertyID,
459 &outPropertyDataSize, outPropertyData );
460 if( macErr ) {
461 memset( outPropertyData, 0, inPropertyDataSize );
462 goto failMac;
463 }
464 if( inPropertyDataSize!=outPropertyDataSize )
465 return paInternalError;
466 if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) )
467 return paNoError;
468
469 /* Ideally, we'd use a condition variable to determine changes.
470 we could set that up here. */
471
472 /* If we were using a cond variable, we'd do something useful here,
473 but for now, this is just to make 10.6 happy. */
474 macErr = PaMacCore_AudioDeviceAddPropertyListener( inDevice, inChannel, isInput,
475 inPropertyID, propertyProc,
476 NULL );
477 if( macErr )
478 /* we couldn't add a listener. */
479 goto failMac;
480
481 /* set property */
482 macErr = PaMacCore_AudioDeviceSetProperty( inDevice, NULL, inChannel,
483 isInput, inPropertyID,
484 inPropertyDataSize, inPropertyData );
485 if( macErr )
486 goto failMac;
487
488 /* busy-wait up to 30 seconds for the property to change */
489 /* busy-wait is justified here only because the correct alternative (condition variable)
490 was hard to test, since most of the waiting ended up being for setting rather than
491 getting in OS X 10.5. This was not the case in earlier OS versions. */
492 struct timeval tv1, tv2;
493 gettimeofday( &tv1, NULL );
494 memcpy( &tv2, &tv1, sizeof( struct timeval ) );
495 while( tv2.tv_sec - tv1.tv_sec < 30 ) {
496 /* now read the property back out */
497 macErr = PaMacCore_AudioDeviceGetProperty( inDevice, inChannel,
498 isInput, inPropertyID,
499 &outPropertyDataSize, outPropertyData );
500 if( macErr ) {
501 memset( outPropertyData, 0, inPropertyDataSize );
502 goto failMac;
503 }
504 /* and compare... */
505 if( 0==memcmp( outPropertyData, inPropertyData, outPropertyDataSize ) ) {
506 PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL);
507 return paNoError;
508 }
509 /* No match yet, so let's sleep and try again. */
510 Pa_Sleep( 100 );
511 gettimeofday( &tv2, NULL );
512 }
513 DBUG( ("Timeout waiting for device setting.\n" ) );
514
515 PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL );
516 return paNoError;
517
518 failMac:
519 PaMacCore_AudioDeviceRemovePropertyListener( inDevice, inChannel, isInput, inPropertyID, propertyProc, NULL );
520 return ERR( macErr );
521 }
522
523 /*
524 * Sets the sample rate the HAL device.
525 * if requireExact: set the sample rate or fail.
526 *
527 * otherwise : set the exact sample rate.
528 * If that fails, check for available sample rates, and choose one
529 * higher than the requested rate. If there isn't a higher one,
530 * just use the highest available.
531 */
532 PaError setBestSampleRateForDevice( const AudioDeviceID device,
533 const bool isOutput,
534 const bool requireExact,
535 const Float64 desiredSrate )
536 {
537 const bool isInput = isOutput ? 0 : 1;
538 Float64 srate;
539 UInt32 propsize = sizeof( Float64 );
540 OSErr err;
541 AudioValueRange *ranges;
542 int i=0;
543 Float64 max = -1; /*the maximum rate available*/
544 Float64 best = -1; /*the lowest sample rate still greater than desired rate*/
545 VDBUG(("Setting sample rate for device %ld to %g.\n",(long)device,(float)desiredSrate));
546
547 /* -- try setting the sample rate -- */
548 srate = 0;
549 err = AudioDeviceSetPropertyNowAndWaitForChange(
550 device, 0, isInput,
551 kAudioDevicePropertyNominalSampleRate,
552 propsize, &desiredSrate, &srate );
553
554 /* -- if the rate agrees, and was changed, we are done -- */
555 if( srate != 0 && srate == desiredSrate )
556 return paNoError;
557 /* -- if the rate agrees, and we got no errors, we are done -- */
558 if( !err && srate == desiredSrate )
559 return paNoError;
560 /* -- we've failed if the rates disagree and we are setting input -- */
561 if( requireExact )
562 return paInvalidSampleRate;
563
564 /* -- generate a list of available sample rates -- */
565 err = PaMacCore_AudioDeviceGetPropertySize( device, 0, isInput,
566 kAudioDevicePropertyAvailableNominalSampleRates,
567 &propsize );
568 if( err )
569 return ERR( err );
570 ranges = (AudioValueRange *)calloc( 1, propsize );
571 if( !ranges )
572 return paInsufficientMemory;
573 err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput,
574 kAudioDevicePropertyAvailableNominalSampleRates,
575 &propsize, ranges );
576 if( err )
577 {
578 free( ranges );
579 return ERR( err );
580 }
581 VDBUG(("Requested sample rate of %g was not available.\n", (float)desiredSrate));
582 VDBUG(("%lu Available Sample Rates are:\n",propsize/sizeof(AudioValueRange)));
583 #ifdef MAC_CORE_VERBOSE_DEBUG
584 for( i=0; i<propsize/sizeof(AudioValueRange); ++i )
585 VDBUG( ("\t%g-%g\n",
586 (float) ranges[i].mMinimum,
587 (float) ranges[i].mMaximum ) );
588 #endif
589 VDBUG(("-----\n"));
590
591 /* -- now pick the best available sample rate -- */
592 for( i=0; i<propsize/sizeof(AudioValueRange); ++i )
593 {
594 if( ranges[i].mMaximum > max ) max = ranges[i].mMaximum;
595 if( ranges[i].mMinimum > desiredSrate ) {
596 if( best < 0 )
597 best = ranges[i].mMinimum;
598 else if( ranges[i].mMinimum < best )
599 best = ranges[i].mMinimum;
600 }
601 }
602 if( best < 0 )
603 best = max;
604 VDBUG( ("Maximum Rate %g. best is %g.\n", max, best ) );
605 free( ranges );
606
607 /* -- set the sample rate -- */
608 propsize = sizeof( best );
609 srate = 0;
610 err = AudioDeviceSetPropertyNowAndWaitForChange(
611 device, 0, isInput,
612 kAudioDevicePropertyNominalSampleRate,
613 propsize, &best, &srate );
614
615 /* -- if the set rate matches, we are done -- */
616 if( srate != 0 && srate == best )
617 return paNoError;
618
619 if( err )
620 return ERR( err );
621
622 /* -- otherwise, something weird happened: we didn't set the rate, and we got no errors. Just bail. */
623 return paInternalError;
624 }
625
626
627 /*
628 Attempts to set the requestedFramesPerBuffer. If it can't set the exact
629 value, it settles for something smaller if available. If nothing smaller
630 is available, it uses the smallest available size.
631 actualFramesPerBuffer will be set to the actual value on successful return.
632 OK to pass NULL to actualFramesPerBuffer.
633 The logic is very similar too setBestSampleRate only failure here is
634 not usually catastrophic.
635 */
636 PaError setBestFramesPerBuffer( const AudioDeviceID device,
637 const bool isOutput,
638 UInt32 requestedFramesPerBuffer,
639 UInt32 *actualFramesPerBuffer )
640 {
641 UInt32 afpb;
642 const bool isInput = !isOutput;
643 UInt32 propsize = sizeof(UInt32);
644 OSErr err;
645 AudioValueRange range;
646
647 if( actualFramesPerBuffer == NULL )
648 {
649 actualFramesPerBuffer = &afpb;
650 }
651
652 /* -- try and set exact FPB -- */
653 err = PaMacCore_AudioDeviceSetProperty( device, NULL, 0, isInput,
654 kAudioDevicePropertyBufferFrameSize,
655 propsize, &requestedFramesPerBuffer);
656 err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput,
657 kAudioDevicePropertyBufferFrameSize,
658 &propsize, actualFramesPerBuffer);
659 if( err )
660 {
661 return ERR( err );
662 }
663 // Did we get the size we asked for?
664 if( *actualFramesPerBuffer == requestedFramesPerBuffer )
665 {
666 return paNoError; /* we are done */
667 }
668
669 // Clip requested value against legal range for the device.
670 propsize = sizeof(AudioValueRange);
671 err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput,
672 kAudioDevicePropertyBufferFrameSizeRange,
673 &propsize, &range );
674 if( err )
675 {
676 return ERR( err );
677 }
678 if( requestedFramesPerBuffer < range.mMinimum )
679 {
680 requestedFramesPerBuffer = range.mMinimum;
681 }
682 else if( requestedFramesPerBuffer > range.mMaximum )
683 {
684 requestedFramesPerBuffer = range.mMaximum;
685 }
686
687 /* --- set the buffer size (ignore errors) -- */
688 propsize = sizeof( UInt32 );
689 err = PaMacCore_AudioDeviceSetProperty( device, NULL, 0, isInput,
690 kAudioDevicePropertyBufferFrameSize,
691 propsize, &requestedFramesPerBuffer );
692 /* --- read the property to check that it was set -- */
693 err = PaMacCore_AudioDeviceGetProperty( device, 0, isInput,
694 kAudioDevicePropertyBufferFrameSize,
695 &propsize, actualFramesPerBuffer );
696
697 if( err )
698 return ERR( err );
699
700 return paNoError;
701 }
702
703 /**********************
704 *
705 * XRun stuff
706 *
707 **********************/
708
709 struct PaMacXRunListNode_s {
710 PaMacCoreStream *stream;
711 struct PaMacXRunListNode_s *next;
712 } ;
713
714 typedef struct PaMacXRunListNode_s PaMacXRunListNode;
715
716 /** Always empty, so that it can always be the one returned by
717 addToXRunListenerList. note that it's not a pointer. */
718 static PaMacXRunListNode firstXRunListNode;
719 static int xRunListSize;
720 static pthread_mutex_t xrunMutex;
721
722 OSStatus xrunCallback(
723 AudioObjectID inDevice,
724 UInt32 inNumberAddresses,
725 const AudioObjectPropertyAddress* inAddresses,
726 void * inClientData)
727 {
728 PaMacXRunListNode *node = (PaMacXRunListNode *) inClientData;
729 bool isInput = inAddresses->mScope == kAudioDevicePropertyScopeInput;
730
731 int ret = pthread_mutex_trylock( &xrunMutex ) ;
732
733 if( ret == 0 ) {
734
735 node = node->next ; //skip the first node
736
737 for( ; node; node=node->next ) {
738 PaMacCoreStream *stream = node->stream;
739
740 if( stream->state != ACTIVE )
741 continue; //if the stream isn't active, we don't care if the device is dropping
742
743 if( isInput ) {
744 if( stream->inputDevice == inDevice )
745 OSAtomicOr32( paInputOverflow, &stream->xrunFlags );
746 } else {
747 if( stream->outputDevice == inDevice )
748 OSAtomicOr32( paOutputUnderflow, &stream->xrunFlags );
749 }
750 }
751
752 pthread_mutex_unlock( &xrunMutex );
753 }
754
755 return 0;
756 }
757
758 int initializeXRunListenerList( void )
759 {
760 xRunListSize = 0;
761 bzero( (void *) &firstXRunListNode, sizeof(firstXRunListNode) );
762 return pthread_mutex_init( &xrunMutex, NULL );
763 }
764 int destroyXRunListenerList( void )
765 {
766 PaMacXRunListNode *node;
767 node = firstXRunListNode.next;
768 while( node ) {
769 PaMacXRunListNode *tmp = node;
770 node = node->next;
771 free( tmp );
772 }
773 xRunListSize = 0;
774 return pthread_mutex_destroy( &xrunMutex );
775 }
776
777 void *addToXRunListenerList( void *stream )
778 {
779 pthread_mutex_lock( &xrunMutex );
780 PaMacXRunListNode *newNode;
781 // setup new node:
782 newNode = (PaMacXRunListNode *) malloc( sizeof( PaMacXRunListNode ) );
783 newNode->stream = (PaMacCoreStream *) stream;
784 newNode->next = firstXRunListNode.next;
785 // insert:
786 firstXRunListNode.next = newNode;
787 pthread_mutex_unlock( &xrunMutex );
788
789 return &firstXRunListNode;
790 }
791
792 int removeFromXRunListenerList( void *stream )
793 {
794 pthread_mutex_lock( &xrunMutex );
795 PaMacXRunListNode *node, *prev;
796 prev = &firstXRunListNode;
797 node = firstXRunListNode.next;
798 while( node ) {
799 if( node->stream == stream ) {
800 //found it:
801 --xRunListSize;
802 prev->next = node->next;
803 free( node );
804 pthread_mutex_unlock( &xrunMutex );
805 return xRunListSize;
806 }
807 prev = prev->next;
808 node = node->next;
809 }
810
811 pthread_mutex_unlock( &xrunMutex );
812 // failure
813 return xRunListSize;
814 }