pa_mac_core_utilities.c 24 KB

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