SDL_coreaudio.m 46 KB

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