SDL_coreaudio.m 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2022 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "../../SDL_internal.h"
  19. #if SDL_AUDIO_DRIVER_COREAUDIO
  20. /* !!! FIXME: clean out some of the macro salsa in here. */
  21. #include "SDL_audio.h"
  22. #include "SDL_hints.h"
  23. #include "../SDL_audio_c.h"
  24. #include "../SDL_sysaudio.h"
  25. #include "SDL_coreaudio.h"
  26. #include "../../thread/SDL_systhread.h"
  27. #define DEBUG_COREAUDIO 0
  28. #if DEBUG_COREAUDIO
  29. #define CHECK_RESULT(msg) \
  30. if (result != noErr) { \
  31. printf("COREAUDIO: Got error %d from '%s'!\n", (int) result, msg); \
  32. SDL_SetError("CoreAudio error (%s): %d", msg, (int) result); \
  33. return 0; \
  34. }
  35. #else
  36. #define CHECK_RESULT(msg) \
  37. if (result != noErr) { \
  38. SDL_SetError("CoreAudio error (%s): %d", msg, (int) result); \
  39. return 0; \
  40. }
  41. #endif
  42. #if MACOSX_COREAUDIO
  43. static const AudioObjectPropertyAddress devlist_address = {
  44. kAudioHardwarePropertyDevices,
  45. kAudioObjectPropertyScopeGlobal,
  46. kAudioObjectPropertyElementMaster
  47. };
  48. typedef void (*addDevFn)(const char *name, SDL_AudioSpec *spec, const int iscapture, AudioDeviceID devId, void *data);
  49. typedef struct AudioDeviceList
  50. {
  51. AudioDeviceID devid;
  52. SDL_bool alive;
  53. struct AudioDeviceList *next;
  54. } AudioDeviceList;
  55. static AudioDeviceList *output_devs = NULL;
  56. static AudioDeviceList *capture_devs = NULL;
  57. static SDL_bool
  58. add_to_internal_dev_list(const int iscapture, AudioDeviceID devId)
  59. {
  60. AudioDeviceList *item = (AudioDeviceList *) SDL_malloc(sizeof (AudioDeviceList));
  61. if (item == NULL) {
  62. return SDL_FALSE;
  63. }
  64. item->devid = devId;
  65. item->alive = SDL_TRUE;
  66. item->next = iscapture ? capture_devs : output_devs;
  67. if (iscapture) {
  68. capture_devs = item;
  69. } else {
  70. output_devs = item;
  71. }
  72. return SDL_TRUE;
  73. }
  74. static void
  75. addToDevList(const char *name, SDL_AudioSpec *spec, const int iscapture, AudioDeviceID devId, void *data)
  76. {
  77. if (add_to_internal_dev_list(iscapture, devId)) {
  78. SDL_AddAudioDevice(iscapture, name, spec, (void *) ((size_t) devId));
  79. }
  80. }
  81. static void
  82. build_device_list(int iscapture, addDevFn addfn, void *addfndata)
  83. {
  84. OSStatus result = noErr;
  85. UInt32 size = 0;
  86. AudioDeviceID *devs = NULL;
  87. UInt32 i = 0;
  88. UInt32 max = 0;
  89. result = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject,
  90. &devlist_address, 0, NULL, &size);
  91. if (result != kAudioHardwareNoError)
  92. return;
  93. devs = (AudioDeviceID *) alloca(size);
  94. if (devs == NULL)
  95. return;
  96. result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
  97. &devlist_address, 0, NULL, &size, devs);
  98. if (result != kAudioHardwareNoError)
  99. return;
  100. max = size / sizeof (AudioDeviceID);
  101. for (i = 0; i < max; i++) {
  102. CFStringRef cfstr = NULL;
  103. char *ptr = NULL;
  104. AudioDeviceID dev = devs[i];
  105. AudioBufferList *buflist = NULL;
  106. int usable = 0;
  107. CFIndex len = 0;
  108. double sampleRate = 0;
  109. SDL_AudioSpec spec;
  110. const AudioObjectPropertyAddress addr = {
  111. kAudioDevicePropertyStreamConfiguration,
  112. iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput,
  113. kAudioObjectPropertyElementMaster
  114. };
  115. const AudioObjectPropertyAddress nameaddr = {
  116. kAudioObjectPropertyName,
  117. iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput,
  118. kAudioObjectPropertyElementMaster
  119. };
  120. const AudioObjectPropertyAddress freqaddr = {
  121. kAudioDevicePropertyNominalSampleRate,
  122. iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput,
  123. kAudioObjectPropertyElementMaster
  124. };
  125. result = AudioObjectGetPropertyDataSize(dev, &addr, 0, NULL, &size);
  126. if (result != noErr)
  127. continue;
  128. buflist = (AudioBufferList *) SDL_malloc(size);
  129. if (buflist == NULL)
  130. continue;
  131. result = AudioObjectGetPropertyData(dev, &addr, 0, NULL,
  132. &size, buflist);
  133. SDL_zero(spec);
  134. if (result == noErr) {
  135. UInt32 j;
  136. for (j = 0; j < buflist->mNumberBuffers; j++) {
  137. spec.channels += buflist->mBuffers[j].mNumberChannels;
  138. }
  139. }
  140. SDL_free(buflist);
  141. if (spec.channels == 0)
  142. continue;
  143. size = sizeof (sampleRate);
  144. result = AudioObjectGetPropertyData(dev, &freqaddr, 0, NULL, &size, &sampleRate);
  145. if (result == noErr) {
  146. spec.freq = (int) sampleRate;
  147. }
  148. size = sizeof (CFStringRef);
  149. result = AudioObjectGetPropertyData(dev, &nameaddr, 0, NULL, &size, &cfstr);
  150. if (result != kAudioHardwareNoError)
  151. continue;
  152. len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfstr),
  153. kCFStringEncodingUTF8);
  154. ptr = (char *) SDL_malloc(len + 1);
  155. usable = ((ptr != NULL) &&
  156. (CFStringGetCString
  157. (cfstr, ptr, len + 1, kCFStringEncodingUTF8)));
  158. CFRelease(cfstr);
  159. if (usable) {
  160. len = strlen(ptr);
  161. /* Some devices have whitespace at the end...trim it. */
  162. while ((len > 0) && (ptr[len - 1] == ' ')) {
  163. len--;
  164. }
  165. usable = (len > 0);
  166. }
  167. if (usable) {
  168. ptr[len] = '\0';
  169. #if DEBUG_COREAUDIO
  170. printf("COREAUDIO: Found %s device #%d: '%s' (devid %d)\n",
  171. ((iscapture) ? "capture" : "output"),
  172. (int) i, ptr, (int) dev);
  173. #endif
  174. addfn(ptr, &spec, iscapture, dev, addfndata);
  175. }
  176. SDL_free(ptr); /* addfn() would have copied the string. */
  177. }
  178. }
  179. static void
  180. free_audio_device_list(AudioDeviceList **list)
  181. {
  182. AudioDeviceList *item = *list;
  183. while (item) {
  184. AudioDeviceList *next = item->next;
  185. SDL_free(item);
  186. item = next;
  187. }
  188. *list = NULL;
  189. }
  190. static void
  191. COREAUDIO_DetectDevices(void)
  192. {
  193. build_device_list(SDL_TRUE, addToDevList, NULL);
  194. build_device_list(SDL_FALSE, addToDevList, NULL);
  195. }
  196. static void
  197. build_device_change_list(const char *name, SDL_AudioSpec *spec, const int iscapture, AudioDeviceID devId, void *data)
  198. {
  199. AudioDeviceList **list = (AudioDeviceList **) data;
  200. AudioDeviceList *item;
  201. for (item = *list; item != NULL; item = item->next) {
  202. if (item->devid == devId) {
  203. item->alive = SDL_TRUE;
  204. return;
  205. }
  206. }
  207. add_to_internal_dev_list(iscapture, devId); /* new device, add it. */
  208. SDL_AddAudioDevice(iscapture, name, spec, (void *) ((size_t) devId));
  209. }
  210. static void
  211. reprocess_device_list(const int iscapture, AudioDeviceList **list)
  212. {
  213. AudioDeviceList *item;
  214. AudioDeviceList *prev = NULL;
  215. for (item = *list; item != NULL; item = item->next) {
  216. item->alive = SDL_FALSE;
  217. }
  218. build_device_list(iscapture, build_device_change_list, list);
  219. /* free items in the list that aren't still alive. */
  220. item = *list;
  221. while (item != NULL) {
  222. AudioDeviceList *next = item->next;
  223. if (item->alive) {
  224. prev = item;
  225. } else {
  226. SDL_RemoveAudioDevice(iscapture, (void *) ((size_t) item->devid));
  227. if (prev) {
  228. prev->next = item->next;
  229. } else {
  230. *list = item->next;
  231. }
  232. SDL_free(item);
  233. }
  234. item = next;
  235. }
  236. }
  237. /* this is called when the system's list of available audio devices changes. */
  238. static OSStatus
  239. device_list_changed(AudioObjectID systemObj, UInt32 num_addr, const AudioObjectPropertyAddress *addrs, void *data)
  240. {
  241. reprocess_device_list(SDL_TRUE, &capture_devs);
  242. reprocess_device_list(SDL_FALSE, &output_devs);
  243. return 0;
  244. }
  245. #endif
  246. static int open_playback_devices;
  247. static int open_capture_devices;
  248. static int num_open_devices;
  249. static SDL_AudioDevice **open_devices;
  250. #if !MACOSX_COREAUDIO
  251. static BOOL session_active = NO;
  252. static void pause_audio_devices()
  253. {
  254. int i;
  255. if (!open_devices) {
  256. return;
  257. }
  258. for (i = 0; i < num_open_devices; ++i) {
  259. SDL_AudioDevice *device = open_devices[i];
  260. if (device->hidden->audioQueue && !device->hidden->interrupted) {
  261. AudioQueuePause(device->hidden->audioQueue);
  262. }
  263. }
  264. }
  265. static void resume_audio_devices()
  266. {
  267. int i;
  268. if (!open_devices) {
  269. return;
  270. }
  271. for (i = 0; i < num_open_devices; ++i) {
  272. SDL_AudioDevice *device = open_devices[i];
  273. if (device->hidden->audioQueue && !device->hidden->interrupted) {
  274. AudioQueueStart(device->hidden->audioQueue, NULL);
  275. }
  276. }
  277. }
  278. static void interruption_begin(_THIS)
  279. {
  280. if (this != NULL && this->hidden->audioQueue != NULL) {
  281. this->hidden->interrupted = SDL_TRUE;
  282. AudioQueuePause(this->hidden->audioQueue);
  283. }
  284. }
  285. static void interruption_end(_THIS)
  286. {
  287. if (this != NULL && this->hidden != NULL && this->hidden->audioQueue != NULL
  288. && this->hidden->interrupted
  289. && AudioQueueStart(this->hidden->audioQueue, NULL) == AVAudioSessionErrorCodeNone) {
  290. this->hidden->interrupted = SDL_FALSE;
  291. }
  292. }
  293. @interface SDLInterruptionListener : NSObject
  294. @property (nonatomic, assign) SDL_AudioDevice *device;
  295. @end
  296. @implementation SDLInterruptionListener
  297. - (void)audioSessionInterruption:(NSNotification *)note
  298. {
  299. @synchronized (self) {
  300. NSNumber *type = note.userInfo[AVAudioSessionInterruptionTypeKey];
  301. if (type.unsignedIntegerValue == AVAudioSessionInterruptionTypeBegan) {
  302. interruption_begin(self.device);
  303. } else {
  304. interruption_end(self.device);
  305. }
  306. }
  307. }
  308. - (void)applicationBecameActive:(NSNotification *)note
  309. {
  310. @synchronized (self) {
  311. interruption_end(self.device);
  312. }
  313. }
  314. @end
  315. static BOOL update_audio_session(_THIS, SDL_bool open, SDL_bool allow_playandrecord)
  316. {
  317. @autoreleasepool {
  318. AVAudioSession *session = [AVAudioSession sharedInstance];
  319. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  320. NSString *category = AVAudioSessionCategoryPlayback;
  321. NSString *mode = AVAudioSessionModeDefault;
  322. NSUInteger options = AVAudioSessionCategoryOptionMixWithOthers;
  323. NSError *err = nil;
  324. const char *hint;
  325. hint = SDL_GetHint(SDL_HINT_AUDIO_CATEGORY);
  326. if (hint) {
  327. if (SDL_strcasecmp(hint, "AVAudioSessionCategoryAmbient") == 0) {
  328. category = AVAudioSessionCategoryAmbient;
  329. } else if (SDL_strcasecmp(hint, "AVAudioSessionCategorySoloAmbient") == 0) {
  330. category = AVAudioSessionCategorySoloAmbient;
  331. options &= ~AVAudioSessionCategoryOptionMixWithOthers;
  332. } else if (SDL_strcasecmp(hint, "AVAudioSessionCategoryPlayback") == 0 ||
  333. SDL_strcasecmp(hint, "playback") == 0) {
  334. category = AVAudioSessionCategoryPlayback;
  335. options &= ~AVAudioSessionCategoryOptionMixWithOthers;
  336. } else if (SDL_strcasecmp(hint, "AVAudioSessionCategoryPlayAndRecord") == 0 ||
  337. SDL_strcasecmp(hint, "playandrecord") == 0) {
  338. if (allow_playandrecord) {
  339. category = AVAudioSessionCategoryPlayAndRecord;
  340. }
  341. }
  342. } else if (open_playback_devices && open_capture_devices) {
  343. category = AVAudioSessionCategoryPlayAndRecord;
  344. } else if (open_capture_devices) {
  345. category = AVAudioSessionCategoryRecord;
  346. }
  347. #if !TARGET_OS_TV
  348. if (category == AVAudioSessionCategoryPlayAndRecord) {
  349. options |= AVAudioSessionCategoryOptionDefaultToSpeaker;
  350. }
  351. #endif
  352. if (category == AVAudioSessionCategoryRecord ||
  353. category == AVAudioSessionCategoryPlayAndRecord) {
  354. /* AVAudioSessionCategoryOptionAllowBluetooth isn't available in the SDK for
  355. Apple TV but is still needed in order to output to Bluetooth devices.
  356. */
  357. options |= 0x4; /* AVAudioSessionCategoryOptionAllowBluetooth; */
  358. }
  359. if (category == AVAudioSessionCategoryPlayAndRecord) {
  360. options |= AVAudioSessionCategoryOptionAllowBluetoothA2DP |
  361. AVAudioSessionCategoryOptionAllowAirPlay;
  362. }
  363. if (category == AVAudioSessionCategoryPlayback ||
  364. category == AVAudioSessionCategoryPlayAndRecord) {
  365. options |= AVAudioSessionCategoryOptionDuckOthers;
  366. }
  367. if ([session respondsToSelector:@selector(setCategory:mode:options:error:)]) {
  368. if (![session.category isEqualToString:category] || session.categoryOptions != options) {
  369. /* Stop the current session so we don't interrupt other application audio */
  370. pause_audio_devices();
  371. [session setActive:NO error:nil];
  372. session_active = NO;
  373. if (![session setCategory:category mode:mode options:options error:&err]) {
  374. NSString *desc = err.description;
  375. SDL_SetError("Could not set Audio Session category: %s", desc.UTF8String);
  376. return NO;
  377. }
  378. }
  379. } else {
  380. if (![session.category isEqualToString:category]) {
  381. /* Stop the current session so we don't interrupt other application audio */
  382. pause_audio_devices();
  383. [session setActive:NO error:nil];
  384. session_active = NO;
  385. if (![session setCategory:category error:&err]) {
  386. NSString *desc = err.description;
  387. SDL_SetError("Could not set Audio Session category: %s", desc.UTF8String);
  388. return NO;
  389. }
  390. }
  391. }
  392. if ((open_playback_devices || open_capture_devices) && !session_active) {
  393. if (![session setActive:YES error:&err]) {
  394. if ([err code] == AVAudioSessionErrorCodeResourceNotAvailable &&
  395. category == AVAudioSessionCategoryPlayAndRecord) {
  396. return update_audio_session(this, open, SDL_FALSE);
  397. }
  398. NSString *desc = err.description;
  399. SDL_SetError("Could not activate Audio Session: %s", desc.UTF8String);
  400. return NO;
  401. }
  402. session_active = YES;
  403. resume_audio_devices();
  404. } else if (!open_playback_devices && !open_capture_devices && session_active) {
  405. pause_audio_devices();
  406. [session setActive:NO error:nil];
  407. session_active = NO;
  408. }
  409. if (open) {
  410. SDLInterruptionListener *listener = [SDLInterruptionListener new];
  411. listener.device = this;
  412. [center addObserver:listener
  413. selector:@selector(audioSessionInterruption:)
  414. name:AVAudioSessionInterruptionNotification
  415. object:session];
  416. /* An interruption end notification is not guaranteed to be sent if
  417. we were previously interrupted... resuming if needed when the app
  418. becomes active seems to be the way to go. */
  419. // Note: object: below needs to be nil, as otherwise it filters by the object, and session doesn't send foreground / active notifications. johna
  420. [center addObserver:listener
  421. selector:@selector(applicationBecameActive:)
  422. name:UIApplicationDidBecomeActiveNotification
  423. object:nil];
  424. [center addObserver:listener
  425. selector:@selector(applicationBecameActive:)
  426. name:UIApplicationWillEnterForegroundNotification
  427. object:nil];
  428. this->hidden->interruption_listener = CFBridgingRetain(listener);
  429. } else {
  430. SDLInterruptionListener *listener = nil;
  431. listener = (SDLInterruptionListener *) CFBridgingRelease(this->hidden->interruption_listener);
  432. [center removeObserver:listener];
  433. @synchronized (listener) {
  434. listener.device = NULL;
  435. }
  436. }
  437. }
  438. return YES;
  439. }
  440. #endif
  441. /* The AudioQueue callback */
  442. static void
  443. outputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer)
  444. {
  445. SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData;
  446. SDL_LockMutex(this->mixer_lock);
  447. if (SDL_AtomicGet(&this->hidden->shutdown)) {
  448. SDL_UnlockMutex(this->mixer_lock);
  449. return; /* don't do anything, since we don't even want to enqueue this buffer again. */
  450. }
  451. if (!SDL_AtomicGet(&this->enabled) || SDL_AtomicGet(&this->paused)) {
  452. /* Supply silence if audio is not enabled or paused */
  453. SDL_memset(inBuffer->mAudioData, this->spec.silence, inBuffer->mAudioDataBytesCapacity);
  454. } else if (this->stream) {
  455. UInt32 remaining = inBuffer->mAudioDataBytesCapacity;
  456. Uint8 *ptr = (Uint8 *) inBuffer->mAudioData;
  457. while (remaining > 0) {
  458. if (SDL_AudioStreamAvailable(this->stream) == 0) {
  459. /* Generate the data */
  460. (*this->callbackspec.callback)(this->callbackspec.userdata,
  461. this->hidden->buffer, this->hidden->bufferSize);
  462. this->hidden->bufferOffset = 0;
  463. SDL_AudioStreamPut(this->stream, this->hidden->buffer, this->hidden->bufferSize);
  464. }
  465. if (SDL_AudioStreamAvailable(this->stream) > 0) {
  466. int got;
  467. UInt32 len = SDL_AudioStreamAvailable(this->stream);
  468. if (len > remaining)
  469. len = remaining;
  470. got = SDL_AudioStreamGet(this->stream, ptr, len);
  471. SDL_assert((got < 0) || (got == len));
  472. if (got != len) {
  473. SDL_memset(ptr, this->spec.silence, len);
  474. }
  475. ptr = ptr + len;
  476. remaining -= len;
  477. }
  478. }
  479. } else {
  480. UInt32 remaining = inBuffer->mAudioDataBytesCapacity;
  481. Uint8 *ptr = (Uint8 *) inBuffer->mAudioData;
  482. while (remaining > 0) {
  483. UInt32 len;
  484. if (this->hidden->bufferOffset >= this->hidden->bufferSize) {
  485. /* Generate the data */
  486. (*this->callbackspec.callback)(this->callbackspec.userdata,
  487. this->hidden->buffer, this->hidden->bufferSize);
  488. this->hidden->bufferOffset = 0;
  489. }
  490. len = this->hidden->bufferSize - this->hidden->bufferOffset;
  491. if (len > remaining) {
  492. len = remaining;
  493. }
  494. SDL_memcpy(ptr, (char *)this->hidden->buffer +
  495. this->hidden->bufferOffset, len);
  496. ptr = ptr + len;
  497. remaining -= len;
  498. this->hidden->bufferOffset += len;
  499. }
  500. }
  501. AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
  502. inBuffer->mAudioDataByteSize = inBuffer->mAudioDataBytesCapacity;
  503. SDL_UnlockMutex(this->mixer_lock);
  504. }
  505. static void
  506. inputCallback(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer,
  507. const AudioTimeStamp *inStartTime, UInt32 inNumberPacketDescriptions,
  508. const AudioStreamPacketDescription *inPacketDescs)
  509. {
  510. SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData;
  511. if (SDL_AtomicGet(&this->shutdown)) {
  512. return; /* don't do anything. */
  513. }
  514. /* ignore unless we're active. */
  515. if (!SDL_AtomicGet(&this->paused) && SDL_AtomicGet(&this->enabled)) {
  516. const Uint8 *ptr = (const Uint8 *) inBuffer->mAudioData;
  517. UInt32 remaining = inBuffer->mAudioDataByteSize;
  518. while (remaining > 0) {
  519. UInt32 len = this->hidden->bufferSize - this->hidden->bufferOffset;
  520. if (len > remaining) {
  521. len = remaining;
  522. }
  523. SDL_memcpy((char *)this->hidden->buffer + this->hidden->bufferOffset, ptr, len);
  524. ptr += len;
  525. remaining -= len;
  526. this->hidden->bufferOffset += len;
  527. if (this->hidden->bufferOffset >= this->hidden->bufferSize) {
  528. SDL_LockMutex(this->mixer_lock);
  529. (*this->callbackspec.callback)(this->callbackspec.userdata, this->hidden->buffer, this->hidden->bufferSize);
  530. SDL_UnlockMutex(this->mixer_lock);
  531. this->hidden->bufferOffset = 0;
  532. }
  533. }
  534. }
  535. AudioQueueEnqueueBuffer(this->hidden->audioQueue, inBuffer, 0, NULL);
  536. }
  537. #if MACOSX_COREAUDIO
  538. static const AudioObjectPropertyAddress alive_address =
  539. {
  540. kAudioDevicePropertyDeviceIsAlive,
  541. kAudioObjectPropertyScopeGlobal,
  542. kAudioObjectPropertyElementMaster
  543. };
  544. static OSStatus
  545. device_unplugged(AudioObjectID devid, UInt32 num_addr, const AudioObjectPropertyAddress *addrs, void *data)
  546. {
  547. SDL_AudioDevice *this = (SDL_AudioDevice *) data;
  548. SDL_bool dead = SDL_FALSE;
  549. UInt32 isAlive = 1;
  550. UInt32 size = sizeof (isAlive);
  551. OSStatus error;
  552. if (!SDL_AtomicGet(&this->enabled)) {
  553. return 0; /* already known to be dead. */
  554. }
  555. error = AudioObjectGetPropertyData(this->hidden->deviceID, &alive_address,
  556. 0, NULL, &size, &isAlive);
  557. if (error == kAudioHardwareBadDeviceError) {
  558. dead = SDL_TRUE; /* device was unplugged. */
  559. } else if ((error == kAudioHardwareNoError) && (!isAlive)) {
  560. dead = SDL_TRUE; /* device died in some other way. */
  561. }
  562. if (dead) {
  563. SDL_OpenedAudioDeviceDisconnected(this);
  564. }
  565. return 0;
  566. }
  567. /* macOS calls this when the default device changed (if we have a default device open). */
  568. static OSStatus
  569. default_device_changed(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses, void *inUserData)
  570. {
  571. SDL_AudioDevice *this = (SDL_AudioDevice *) inUserData;
  572. #if DEBUG_COREAUDIO
  573. printf("COREAUDIO: default device changed for SDL audio device %p!\n", this);
  574. #endif
  575. SDL_AtomicSet(&this->hidden->device_change_flag, 1); /* let the audioqueue thread pick up on this when safe to do so. */
  576. return noErr;
  577. }
  578. #endif
  579. static void
  580. COREAUDIO_CloseDevice(_THIS)
  581. {
  582. const SDL_bool iscapture = this->iscapture;
  583. int i;
  584. /* !!! FIXME: what does iOS do when a bluetooth audio device vanishes? Headphones unplugged? */
  585. /* !!! FIXME: (we only do a "default" device on iOS right now...can we do more?) */
  586. #if MACOSX_COREAUDIO
  587. if (this->handle != NULL) { /* we don't register this listener for default devices. */
  588. AudioObjectRemovePropertyListener(this->hidden->deviceID, &alive_address, device_unplugged, this);
  589. }
  590. #endif
  591. if (iscapture) {
  592. open_capture_devices--;
  593. } else {
  594. open_playback_devices--;
  595. }
  596. #if !MACOSX_COREAUDIO
  597. update_audio_session(this, SDL_FALSE, SDL_TRUE);
  598. #endif
  599. for (i = 0; i < num_open_devices; ++i) {
  600. if (open_devices[i] == this) {
  601. --num_open_devices;
  602. if (i < num_open_devices) {
  603. SDL_memmove(&open_devices[i], &open_devices[i+1], sizeof(open_devices[i])*(num_open_devices - i));
  604. }
  605. break;
  606. }
  607. }
  608. if (num_open_devices == 0) {
  609. SDL_free(open_devices);
  610. open_devices = NULL;
  611. }
  612. /* if callback fires again, feed silence; don't call into the app. */
  613. SDL_AtomicSet(&this->paused, 1);
  614. if (this->hidden->audioQueue) {
  615. AudioQueueDispose(this->hidden->audioQueue, 1);
  616. }
  617. if (this->hidden->thread) {
  618. SDL_AtomicSet(&this->hidden->shutdown, 1);
  619. SDL_WaitThread(this->hidden->thread, NULL);
  620. }
  621. if (this->hidden->ready_semaphore) {
  622. SDL_DestroySemaphore(this->hidden->ready_semaphore);
  623. }
  624. /* AudioQueueDispose() frees the actual buffer objects. */
  625. SDL_free(this->hidden->audioBuffer);
  626. SDL_free(this->hidden->thread_error);
  627. SDL_free(this->hidden->buffer);
  628. SDL_free(this->hidden);
  629. }
  630. #if MACOSX_COREAUDIO
  631. static int
  632. prepare_device(_THIS)
  633. {
  634. void *handle = this->handle;
  635. SDL_bool iscapture = this->iscapture;
  636. AudioDeviceID devid = (AudioDeviceID) ((size_t) handle);
  637. OSStatus result = noErr;
  638. UInt32 size = 0;
  639. UInt32 alive = 0;
  640. pid_t pid = 0;
  641. AudioObjectPropertyAddress addr = {
  642. 0,
  643. kAudioObjectPropertyScopeGlobal,
  644. kAudioObjectPropertyElementMaster
  645. };
  646. if (handle == NULL) {
  647. size = sizeof (AudioDeviceID);
  648. addr.mSelector =
  649. ((iscapture) ? kAudioHardwarePropertyDefaultInputDevice :
  650. kAudioHardwarePropertyDefaultOutputDevice);
  651. result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr,
  652. 0, NULL, &size, &devid);
  653. CHECK_RESULT("AudioHardwareGetProperty (default device)");
  654. }
  655. addr.mSelector = kAudioDevicePropertyDeviceIsAlive;
  656. addr.mScope = iscapture ? kAudioDevicePropertyScopeInput :
  657. kAudioDevicePropertyScopeOutput;
  658. size = sizeof (alive);
  659. result = AudioObjectGetPropertyData(devid, &addr, 0, NULL, &size, &alive);
  660. CHECK_RESULT
  661. ("AudioDeviceGetProperty (kAudioDevicePropertyDeviceIsAlive)");
  662. if (!alive) {
  663. SDL_SetError("CoreAudio: requested device exists, but isn't alive.");
  664. return 0;
  665. }
  666. addr.mSelector = kAudioDevicePropertyHogMode;
  667. size = sizeof (pid);
  668. result = AudioObjectGetPropertyData(devid, &addr, 0, NULL, &size, &pid);
  669. /* some devices don't support this property, so errors are fine here. */
  670. if ((result == noErr) && (pid != -1)) {
  671. SDL_SetError("CoreAudio: requested device is being hogged.");
  672. return 0;
  673. }
  674. this->hidden->deviceID = devid;
  675. return 1;
  676. }
  677. static int
  678. assign_device_to_audioqueue(_THIS)
  679. {
  680. const AudioObjectPropertyAddress prop = {
  681. kAudioDevicePropertyDeviceUID,
  682. this->iscapture ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput,
  683. kAudioObjectPropertyElementMaster
  684. };
  685. OSStatus result;
  686. CFStringRef devuid;
  687. UInt32 devuidsize = sizeof (devuid);
  688. result = AudioObjectGetPropertyData(this->hidden->deviceID, &prop, 0, NULL, &devuidsize, &devuid);
  689. CHECK_RESULT("AudioObjectGetPropertyData (kAudioDevicePropertyDeviceUID)");
  690. result = AudioQueueSetProperty(this->hidden->audioQueue, kAudioQueueProperty_CurrentDevice, &devuid, devuidsize);
  691. CHECK_RESULT("AudioQueueSetProperty (kAudioQueueProperty_CurrentDevice)");
  692. return 1;
  693. }
  694. #endif
  695. static int
  696. prepare_audioqueue(_THIS)
  697. {
  698. const AudioStreamBasicDescription *strdesc = &this->hidden->strdesc;
  699. const int iscapture = this->iscapture;
  700. OSStatus result;
  701. int i, numAudioBuffers = 2;
  702. AudioChannelLayout layout;
  703. double MINIMUM_AUDIO_BUFFER_TIME_MS;
  704. const double msecs = (this->spec.samples / ((double) this->spec.freq)) * 1000.0;;
  705. SDL_assert(CFRunLoopGetCurrent() != NULL);
  706. if (iscapture) {
  707. result = AudioQueueNewInput(strdesc, inputCallback, this, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, 0, &this->hidden->audioQueue);
  708. CHECK_RESULT("AudioQueueNewInput");
  709. } else {
  710. result = AudioQueueNewOutput(strdesc, outputCallback, this, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode, 0, &this->hidden->audioQueue);
  711. CHECK_RESULT("AudioQueueNewOutput");
  712. }
  713. #if MACOSX_COREAUDIO
  714. if (!assign_device_to_audioqueue(this)) {
  715. return 0;
  716. }
  717. /* only listen for unplugging on specific devices, not the default device, as that should
  718. switch to a different device (or hang out silently if there _is_ no other device). */
  719. if (this->handle != NULL) {
  720. /* !!! FIXME: what does iOS do when a bluetooth audio device vanishes? Headphones unplugged? */
  721. /* !!! FIXME: (we only do a "default" device on iOS right now...can we do more?) */
  722. /* Fire a callback if the device stops being "alive" (disconnected, etc). */
  723. /* If this fails, oh well, we won't notice a device had an extraordinary event take place. */
  724. AudioObjectAddPropertyListener(this->hidden->deviceID, &alive_address, device_unplugged, this);
  725. }
  726. #endif
  727. /* Calculate the final parameters for this audio specification */
  728. SDL_CalculateAudioSpec(&this->spec);
  729. /* Set the channel layout for the audio queue */
  730. SDL_zero(layout);
  731. switch (this->spec.channels) {
  732. case 1:
  733. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Mono;
  734. break;
  735. case 2:
  736. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  737. break;
  738. case 3:
  739. layout.mChannelLayoutTag = kAudioChannelLayoutTag_DVD_4;
  740. break;
  741. case 4:
  742. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Quadraphonic;
  743. break;
  744. case 5:
  745. layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_5_0_A;
  746. break;
  747. case 6:
  748. layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_5_1_A;
  749. break;
  750. case 7:
  751. /* FIXME: Need to move channel[4] (BC) to channel[6] */
  752. layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_6_1_A;
  753. break;
  754. case 8:
  755. layout.mChannelLayoutTag = kAudioChannelLayoutTag_MPEG_7_1_A;
  756. break;
  757. }
  758. if (layout.mChannelLayoutTag != 0) {
  759. result = AudioQueueSetProperty(this->hidden->audioQueue, kAudioQueueProperty_ChannelLayout, &layout, sizeof(layout));
  760. CHECK_RESULT("AudioQueueSetProperty(kAudioQueueProperty_ChannelLayout)");
  761. }
  762. /* Allocate a sample buffer */
  763. this->hidden->bufferSize = this->spec.size;
  764. this->hidden->bufferOffset = iscapture ? 0 : this->hidden->bufferSize;
  765. this->hidden->buffer = SDL_malloc(this->hidden->bufferSize);
  766. if (this->hidden->buffer == NULL) {
  767. SDL_OutOfMemory();
  768. return 0;
  769. }
  770. /* Make sure we can feed the device a minimum amount of time */
  771. MINIMUM_AUDIO_BUFFER_TIME_MS = 15.0;
  772. #if defined(__IPHONEOS__)
  773. if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
  774. /* Older iOS hardware, use 40 ms as a minimum time */
  775. MINIMUM_AUDIO_BUFFER_TIME_MS = 40.0;
  776. }
  777. #endif
  778. if (msecs < MINIMUM_AUDIO_BUFFER_TIME_MS) { /* use more buffers if we have a VERY small sample set. */
  779. numAudioBuffers = ((int)SDL_ceil(MINIMUM_AUDIO_BUFFER_TIME_MS / msecs) * 2);
  780. }
  781. this->hidden->numAudioBuffers = numAudioBuffers;
  782. this->hidden->audioBuffer = SDL_calloc(1, sizeof (AudioQueueBufferRef) * numAudioBuffers);
  783. if (this->hidden->audioBuffer == NULL) {
  784. SDL_OutOfMemory();
  785. return 0;
  786. }
  787. #if DEBUG_COREAUDIO
  788. printf("COREAUDIO: numAudioBuffers == %d\n", numAudioBuffers);
  789. #endif
  790. for (i = 0; i < numAudioBuffers; i++) {
  791. result = AudioQueueAllocateBuffer(this->hidden->audioQueue, this->spec.size, &this->hidden->audioBuffer[i]);
  792. CHECK_RESULT("AudioQueueAllocateBuffer");
  793. SDL_memset(this->hidden->audioBuffer[i]->mAudioData, this->spec.silence, this->hidden->audioBuffer[i]->mAudioDataBytesCapacity);
  794. this->hidden->audioBuffer[i]->mAudioDataByteSize = this->hidden->audioBuffer[i]->mAudioDataBytesCapacity;
  795. /* !!! FIXME: should we use AudioQueueEnqueueBufferWithParameters and specify all frames be "trimmed" so these are immediately ready to refill with SDL callback data? */
  796. result = AudioQueueEnqueueBuffer(this->hidden->audioQueue, this->hidden->audioBuffer[i], 0, NULL);
  797. CHECK_RESULT("AudioQueueEnqueueBuffer");
  798. }
  799. result = AudioQueueStart(this->hidden->audioQueue, NULL);
  800. CHECK_RESULT("AudioQueueStart");
  801. /* We're running! */
  802. return 1;
  803. }
  804. static int
  805. audioqueue_thread(void *arg)
  806. {
  807. SDL_AudioDevice *this = (SDL_AudioDevice *) arg;
  808. int rc;
  809. #if MACOSX_COREAUDIO
  810. const AudioObjectPropertyAddress default_device_address = {
  811. this->iscapture ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice,
  812. kAudioObjectPropertyScopeGlobal,
  813. kAudioObjectPropertyElementMaster
  814. };
  815. if (this->handle == NULL) { /* opened the default device? Register to know if the user picks a new default. */
  816. /* we don't care if this fails; we just won't change to new default devices, but we still otherwise function in this case. */
  817. AudioObjectAddPropertyListener(kAudioObjectSystemObject, &default_device_address, default_device_changed, this);
  818. }
  819. #endif
  820. rc = prepare_audioqueue(this);
  821. if (!rc) {
  822. this->hidden->thread_error = SDL_strdup(SDL_GetError());
  823. SDL_SemPost(this->hidden->ready_semaphore);
  824. return 0;
  825. }
  826. SDL_SetThreadPriority(SDL_THREAD_PRIORITY_HIGH);
  827. /* init was successful, alert parent thread and start running... */
  828. SDL_SemPost(this->hidden->ready_semaphore);
  829. while (!SDL_AtomicGet(&this->hidden->shutdown)) {
  830. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.10, 1);
  831. #if MACOSX_COREAUDIO
  832. if ((this->handle == NULL) && SDL_AtomicGet(&this->hidden->device_change_flag)) {
  833. const AudioDeviceID prev_devid = this->hidden->deviceID;
  834. SDL_AtomicSet(&this->hidden->device_change_flag, 0);
  835. #if DEBUG_COREAUDIO
  836. printf("COREAUDIO: audioqueue_thread is trying to switch to new default device!\n");
  837. #endif
  838. /* if any of this fails, there's not much to do but wait to see if the user gives up
  839. and quits (flagging the audioqueue for shutdown), or toggles to some other system
  840. output device (in which case we'll try again). */
  841. if (prepare_device(this) && (prev_devid != this->hidden->deviceID)) {
  842. AudioQueueStop(this->hidden->audioQueue, 1);
  843. if (assign_device_to_audioqueue(this)) {
  844. int i;
  845. for (i = 0; i < this->hidden->numAudioBuffers; i++) {
  846. SDL_memset(this->hidden->audioBuffer[i]->mAudioData, this->spec.silence, this->hidden->audioBuffer[i]->mAudioDataBytesCapacity);
  847. /* !!! FIXME: should we use AudioQueueEnqueueBufferWithParameters and specify all frames be "trimmed" so these are immediately ready to refill with SDL callback data? */
  848. AudioQueueEnqueueBuffer(this->hidden->audioQueue, this->hidden->audioBuffer[i], 0, NULL);
  849. }
  850. AudioQueueStart(this->hidden->audioQueue, NULL);
  851. }
  852. }
  853. }
  854. #endif
  855. }
  856. if (!this->iscapture) { /* Drain off any pending playback. */
  857. const CFTimeInterval secs = (((this->spec.size / (SDL_AUDIO_BITSIZE(this->spec.format) / 8)) / this->spec.channels) / ((CFTimeInterval) this->spec.freq)) * 2.0;
  858. CFRunLoopRunInMode(kCFRunLoopDefaultMode, secs, 0);
  859. }
  860. #if MACOSX_COREAUDIO
  861. if (this->handle == NULL) {
  862. /* we don't care if this fails; we just won't change to new default devices, but we still otherwise function in this case. */
  863. AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &default_device_address, default_device_changed, this);
  864. }
  865. #endif
  866. return 0;
  867. }
  868. static int
  869. COREAUDIO_OpenDevice(_THIS, const char *devname)
  870. {
  871. AudioStreamBasicDescription *strdesc;
  872. SDL_AudioFormat test_format;
  873. SDL_bool iscapture = this->iscapture;
  874. SDL_AudioDevice **new_open_devices;
  875. /* Initialize all variables that we clean on shutdown */
  876. this->hidden = (struct SDL_PrivateAudioData *)
  877. SDL_malloc((sizeof *this->hidden));
  878. if (this->hidden == NULL) {
  879. return SDL_OutOfMemory();
  880. }
  881. SDL_zerop(this->hidden);
  882. strdesc = &this->hidden->strdesc;
  883. if (iscapture) {
  884. open_capture_devices++;
  885. } else {
  886. open_playback_devices++;
  887. }
  888. new_open_devices = (SDL_AudioDevice **)SDL_realloc(open_devices, sizeof(open_devices[0]) * (num_open_devices + 1));
  889. if (new_open_devices) {
  890. open_devices = new_open_devices;
  891. open_devices[num_open_devices++] = this;
  892. }
  893. #if !MACOSX_COREAUDIO
  894. if (!update_audio_session(this, SDL_TRUE, SDL_TRUE)) {
  895. return -1;
  896. }
  897. /* Stop CoreAudio from doing expensive audio rate conversion */
  898. @autoreleasepool {
  899. AVAudioSession* session = [AVAudioSession sharedInstance];
  900. [session setPreferredSampleRate:this->spec.freq error:nil];
  901. this->spec.freq = (int)session.sampleRate;
  902. #if TARGET_OS_TV
  903. if (iscapture) {
  904. [session setPreferredInputNumberOfChannels:this->spec.channels error:nil];
  905. this->spec.channels = session.preferredInputNumberOfChannels;
  906. } else {
  907. [session setPreferredOutputNumberOfChannels:this->spec.channels error:nil];
  908. this->spec.channels = session.preferredOutputNumberOfChannels;
  909. }
  910. #else
  911. /* Calling setPreferredOutputNumberOfChannels seems to break audio output on iOS */
  912. #endif /* TARGET_OS_TV */
  913. }
  914. #endif
  915. /* Setup a AudioStreamBasicDescription with the requested format */
  916. SDL_zerop(strdesc);
  917. strdesc->mFormatID = kAudioFormatLinearPCM;
  918. strdesc->mFormatFlags = kLinearPCMFormatFlagIsPacked;
  919. strdesc->mChannelsPerFrame = this->spec.channels;
  920. strdesc->mSampleRate = this->spec.freq;
  921. strdesc->mFramesPerPacket = 1;
  922. for (test_format = SDL_FirstAudioFormat(this->spec.format); test_format; test_format = SDL_NextAudioFormat()) {
  923. /* CoreAudio handles most of SDL's formats natively, but not U16, apparently. */
  924. switch (test_format) {
  925. case AUDIO_U8:
  926. case AUDIO_S8:
  927. case AUDIO_S16LSB:
  928. case AUDIO_S16MSB:
  929. case AUDIO_S32LSB:
  930. case AUDIO_S32MSB:
  931. case AUDIO_F32LSB:
  932. case AUDIO_F32MSB:
  933. break;
  934. default:
  935. continue;
  936. }
  937. break;
  938. }
  939. if (!test_format) { /* shouldn't happen, but just in case... */
  940. return SDL_SetError("%s: Unsupported audio format", "coreaudio");
  941. }
  942. this->spec.format = test_format;
  943. strdesc->mBitsPerChannel = SDL_AUDIO_BITSIZE(test_format);
  944. if (SDL_AUDIO_ISBIGENDIAN(test_format))
  945. strdesc->mFormatFlags |= kLinearPCMFormatFlagIsBigEndian;
  946. if (SDL_AUDIO_ISFLOAT(test_format))
  947. strdesc->mFormatFlags |= kLinearPCMFormatFlagIsFloat;
  948. else if (SDL_AUDIO_ISSIGNED(test_format))
  949. strdesc->mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
  950. strdesc->mBytesPerFrame = strdesc->mChannelsPerFrame * strdesc->mBitsPerChannel / 8;
  951. strdesc->mBytesPerPacket = strdesc->mBytesPerFrame * strdesc->mFramesPerPacket;
  952. #if MACOSX_COREAUDIO
  953. if (!prepare_device(this)) {
  954. return -1;
  955. }
  956. #endif
  957. /* This has to init in a new thread so it can get its own CFRunLoop. :/ */
  958. SDL_AtomicSet(&this->hidden->shutdown, 0);
  959. this->hidden->ready_semaphore = SDL_CreateSemaphore(0);
  960. if (!this->hidden->ready_semaphore) {
  961. return -1; /* oh well. */
  962. }
  963. this->hidden->thread = SDL_CreateThreadInternal(audioqueue_thread, "AudioQueue thread", 512 * 1024, this);
  964. if (!this->hidden->thread) {
  965. return -1;
  966. }
  967. SDL_SemWait(this->hidden->ready_semaphore);
  968. SDL_DestroySemaphore(this->hidden->ready_semaphore);
  969. this->hidden->ready_semaphore = NULL;
  970. if ((this->hidden->thread != NULL) && (this->hidden->thread_error != NULL)) {
  971. return SDL_SetError("%s", this->hidden->thread_error);
  972. }
  973. return (this->hidden->thread != NULL) ? 0 : -1;
  974. }
  975. static void
  976. COREAUDIO_Deinitialize(void)
  977. {
  978. #if MACOSX_COREAUDIO
  979. AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &devlist_address, device_list_changed, NULL);
  980. free_audio_device_list(&capture_devs);
  981. free_audio_device_list(&output_devs);
  982. #endif
  983. }
  984. static SDL_bool
  985. COREAUDIO_Init(SDL_AudioDriverImpl * impl)
  986. {
  987. /* Set the function pointers */
  988. impl->OpenDevice = COREAUDIO_OpenDevice;
  989. impl->CloseDevice = COREAUDIO_CloseDevice;
  990. impl->Deinitialize = COREAUDIO_Deinitialize;
  991. #if MACOSX_COREAUDIO
  992. impl->DetectDevices = COREAUDIO_DetectDevices;
  993. AudioObjectAddPropertyListener(kAudioObjectSystemObject, &devlist_address, device_list_changed, NULL);
  994. #else
  995. impl->OnlyHasDefaultOutputDevice = SDL_TRUE;
  996. impl->OnlyHasDefaultCaptureDevice = SDL_TRUE;
  997. #endif
  998. impl->ProvidesOwnCallbackThread = SDL_TRUE;
  999. impl->HasCaptureSupport = SDL_TRUE;
  1000. return SDL_TRUE; /* this audio target is available. */
  1001. }
  1002. AudioBootStrap COREAUDIO_bootstrap = {
  1003. "coreaudio", "CoreAudio", COREAUDIO_Init, SDL_FALSE
  1004. };
  1005. #endif /* SDL_AUDIO_DRIVER_COREAUDIO */
  1006. /* vi: set ts=4 sw=4 expandtab: */