SDL_coreaudio.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2013 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. #include "SDL_audio.h"
  20. #include "../SDL_audio_c.h"
  21. #include "../SDL_sysaudio.h"
  22. #include "SDL_coreaudio.h"
  23. #include "SDL_assert.h"
  24. #define DEBUG_COREAUDIO 0
  25. static void COREAUDIO_CloseDevice(_THIS);
  26. #define CHECK_RESULT(msg) \
  27. if (result != noErr) { \
  28. COREAUDIO_CloseDevice(this); \
  29. SDL_SetError("CoreAudio error (%s): %d", msg, (int) result); \
  30. return 0; \
  31. }
  32. #if MACOSX_COREAUDIO
  33. typedef void (*addDevFn)(const char *name, AudioDeviceID devId, void *data);
  34. static void
  35. addToDevList(const char *name, AudioDeviceID devId, void *data)
  36. {
  37. SDL_AddAudioDevice addfn = (SDL_AddAudioDevice) data;
  38. addfn(name);
  39. }
  40. typedef struct
  41. {
  42. const char *findname;
  43. AudioDeviceID devId;
  44. int found;
  45. } FindDevIdData;
  46. static void
  47. findDevId(const char *name, AudioDeviceID devId, void *_data)
  48. {
  49. FindDevIdData *data = (FindDevIdData *) _data;
  50. if (!data->found) {
  51. if (SDL_strcmp(name, data->findname) == 0) {
  52. data->found = 1;
  53. data->devId = devId;
  54. }
  55. }
  56. }
  57. static void
  58. build_device_list(int iscapture, addDevFn addfn, void *addfndata)
  59. {
  60. OSStatus result = noErr;
  61. UInt32 size = 0;
  62. AudioDeviceID *devs = NULL;
  63. UInt32 i = 0;
  64. UInt32 max = 0;
  65. AudioObjectPropertyAddress addr = {
  66. kAudioHardwarePropertyDevices,
  67. kAudioObjectPropertyScopeGlobal,
  68. kAudioObjectPropertyElementMaster
  69. };
  70. result = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &addr,
  71. 0, NULL, &size);
  72. if (result != kAudioHardwareNoError)
  73. return;
  74. devs = (AudioDeviceID *) alloca(size);
  75. if (devs == NULL)
  76. return;
  77. result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr,
  78. 0, NULL, &size, devs);
  79. if (result != kAudioHardwareNoError)
  80. return;
  81. max = size / sizeof (AudioDeviceID);
  82. for (i = 0; i < max; i++) {
  83. CFStringRef cfstr = NULL;
  84. char *ptr = NULL;
  85. AudioDeviceID dev = devs[i];
  86. AudioBufferList *buflist = NULL;
  87. int usable = 0;
  88. CFIndex len = 0;
  89. addr.mScope = iscapture ? kAudioDevicePropertyScopeInput :
  90. kAudioDevicePropertyScopeOutput;
  91. addr.mSelector = kAudioDevicePropertyStreamConfiguration;
  92. result = AudioObjectGetPropertyDataSize(dev, &addr, 0, NULL, &size);
  93. if (result != noErr)
  94. continue;
  95. buflist = (AudioBufferList *) SDL_malloc(size);
  96. if (buflist == NULL)
  97. continue;
  98. result = AudioObjectGetPropertyData(dev, &addr, 0, NULL,
  99. &size, buflist);
  100. if (result == noErr) {
  101. UInt32 j;
  102. for (j = 0; j < buflist->mNumberBuffers; j++) {
  103. if (buflist->mBuffers[j].mNumberChannels > 0) {
  104. usable = 1;
  105. break;
  106. }
  107. }
  108. }
  109. SDL_free(buflist);
  110. if (!usable)
  111. continue;
  112. addr.mSelector = kAudioObjectPropertyName;
  113. size = sizeof (CFStringRef);
  114. result = AudioObjectGetPropertyData(dev, &addr, 0, NULL, &size, &cfstr);
  115. if (result != kAudioHardwareNoError)
  116. continue;
  117. len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfstr),
  118. kCFStringEncodingUTF8);
  119. ptr = (char *) SDL_malloc(len + 1);
  120. usable = ((ptr != NULL) &&
  121. (CFStringGetCString
  122. (cfstr, ptr, len + 1, kCFStringEncodingUTF8)));
  123. CFRelease(cfstr);
  124. if (usable) {
  125. len = strlen(ptr);
  126. /* Some devices have whitespace at the end...trim it. */
  127. while ((len > 0) && (ptr[len - 1] == ' ')) {
  128. len--;
  129. }
  130. usable = (len > 0);
  131. }
  132. if (usable) {
  133. ptr[len] = '\0';
  134. #if DEBUG_COREAUDIO
  135. printf("COREAUDIO: Found %s device #%d: '%s' (devid %d)\n",
  136. ((iscapture) ? "capture" : "output"),
  137. (int) *devCount, ptr, (int) dev);
  138. #endif
  139. addfn(ptr, dev, addfndata);
  140. }
  141. SDL_free(ptr); /* addfn() would have copied the string. */
  142. }
  143. }
  144. static void
  145. COREAUDIO_DetectDevices(int iscapture, SDL_AddAudioDevice addfn)
  146. {
  147. build_device_list(iscapture, addToDevList, addfn);
  148. }
  149. static int
  150. find_device_by_name(_THIS, const char *devname, int iscapture)
  151. {
  152. AudioDeviceID devid = 0;
  153. OSStatus result = noErr;
  154. UInt32 size = 0;
  155. UInt32 alive = 0;
  156. pid_t pid = 0;
  157. AudioObjectPropertyAddress addr = {
  158. 0,
  159. kAudioObjectPropertyScopeGlobal,
  160. kAudioObjectPropertyElementMaster
  161. };
  162. if (devname == NULL) {
  163. size = sizeof (AudioDeviceID);
  164. addr.mSelector =
  165. ((iscapture) ? kAudioHardwarePropertyDefaultInputDevice :
  166. kAudioHardwarePropertyDefaultOutputDevice);
  167. result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr,
  168. 0, NULL, &size, &devid);
  169. CHECK_RESULT("AudioHardwareGetProperty (default device)");
  170. } else {
  171. FindDevIdData data;
  172. SDL_zero(data);
  173. data.findname = devname;
  174. build_device_list(iscapture, findDevId, &data);
  175. if (!data.found) {
  176. SDL_SetError("CoreAudio: No such audio device.");
  177. return 0;
  178. }
  179. devid = data.devId;
  180. }
  181. addr.mSelector = kAudioDevicePropertyDeviceIsAlive;
  182. addr.mScope = iscapture ? kAudioDevicePropertyScopeInput :
  183. kAudioDevicePropertyScopeOutput;
  184. size = sizeof (alive);
  185. result = AudioObjectGetPropertyData(devid, &addr, 0, NULL, &size, &alive);
  186. CHECK_RESULT
  187. ("AudioDeviceGetProperty (kAudioDevicePropertyDeviceIsAlive)");
  188. if (!alive) {
  189. SDL_SetError("CoreAudio: requested device exists, but isn't alive.");
  190. return 0;
  191. }
  192. addr.mSelector = kAudioDevicePropertyHogMode;
  193. size = sizeof (pid);
  194. result = AudioObjectGetPropertyData(devid, &addr, 0, NULL, &size, &pid);
  195. /* some devices don't support this property, so errors are fine here. */
  196. if ((result == noErr) && (pid != -1)) {
  197. SDL_SetError("CoreAudio: requested device is being hogged.");
  198. return 0;
  199. }
  200. this->hidden->deviceID = devid;
  201. return 1;
  202. }
  203. #endif
  204. /* The CoreAudio callback */
  205. static OSStatus
  206. outputCallback(void *inRefCon,
  207. AudioUnitRenderActionFlags * ioActionFlags,
  208. const AudioTimeStamp * inTimeStamp,
  209. UInt32 inBusNumber, UInt32 inNumberFrames,
  210. AudioBufferList * ioData)
  211. {
  212. SDL_AudioDevice *this = (SDL_AudioDevice *) inRefCon;
  213. AudioBuffer *abuf;
  214. UInt32 remaining, len;
  215. void *ptr;
  216. UInt32 i;
  217. /* Only do anything if audio is enabled and not paused */
  218. if (!this->enabled || this->paused) {
  219. for (i = 0; i < ioData->mNumberBuffers; i++) {
  220. abuf = &ioData->mBuffers[i];
  221. SDL_memset(abuf->mData, this->spec.silence, abuf->mDataByteSize);
  222. }
  223. return 0;
  224. }
  225. /* No SDL conversion should be needed here, ever, since we accept
  226. any input format in OpenAudio, and leave the conversion to CoreAudio.
  227. */
  228. /*
  229. SDL_assert(!this->convert.needed);
  230. SDL_assert(this->spec.channels == ioData->mNumberChannels);
  231. */
  232. for (i = 0; i < ioData->mNumberBuffers; i++) {
  233. abuf = &ioData->mBuffers[i];
  234. remaining = abuf->mDataByteSize;
  235. ptr = abuf->mData;
  236. while (remaining > 0) {
  237. if (this->hidden->bufferOffset >= this->hidden->bufferSize) {
  238. /* Generate the data */
  239. SDL_LockMutex(this->mixer_lock);
  240. (*this->spec.callback)(this->spec.userdata,
  241. this->hidden->buffer, this->hidden->bufferSize);
  242. SDL_UnlockMutex(this->mixer_lock);
  243. this->hidden->bufferOffset = 0;
  244. }
  245. len = this->hidden->bufferSize - this->hidden->bufferOffset;
  246. if (len > remaining)
  247. len = remaining;
  248. SDL_memcpy(ptr, (char *)this->hidden->buffer +
  249. this->hidden->bufferOffset, len);
  250. ptr = (char *)ptr + len;
  251. remaining -= len;
  252. this->hidden->bufferOffset += len;
  253. }
  254. }
  255. return 0;
  256. }
  257. static OSStatus
  258. inputCallback(void *inRefCon,
  259. AudioUnitRenderActionFlags * ioActionFlags,
  260. const AudioTimeStamp * inTimeStamp,
  261. UInt32 inBusNumber, UInt32 inNumberFrames,
  262. AudioBufferList * ioData)
  263. {
  264. /* err = AudioUnitRender(afr->fAudioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, afr->fAudioBuffer); */
  265. /* !!! FIXME: write me! */
  266. return noErr;
  267. }
  268. static void
  269. COREAUDIO_CloseDevice(_THIS)
  270. {
  271. if (this->hidden != NULL) {
  272. if (this->hidden->audioUnitOpened) {
  273. OSStatus result = noErr;
  274. AURenderCallbackStruct callback;
  275. const AudioUnitElement output_bus = 0;
  276. const AudioUnitElement input_bus = 1;
  277. const int iscapture = this->iscapture;
  278. const AudioUnitElement bus =
  279. ((iscapture) ? input_bus : output_bus);
  280. const AudioUnitScope scope =
  281. ((iscapture) ? kAudioUnitScope_Output :
  282. kAudioUnitScope_Input);
  283. /* stop processing the audio unit */
  284. result = AudioOutputUnitStop(this->hidden->audioUnit);
  285. /* Remove the input callback */
  286. SDL_memset(&callback, 0, sizeof(AURenderCallbackStruct));
  287. result = AudioUnitSetProperty(this->hidden->audioUnit,
  288. kAudioUnitProperty_SetRenderCallback,
  289. scope, bus, &callback,
  290. sizeof(callback));
  291. #if MACOSX_COREAUDIO
  292. CloseComponent(this->hidden->audioUnit);
  293. #else
  294. AudioComponentInstanceDispose(this->hidden->audioUnit);
  295. #endif
  296. this->hidden->audioUnitOpened = 0;
  297. }
  298. SDL_free(this->hidden->buffer);
  299. SDL_free(this->hidden);
  300. this->hidden = NULL;
  301. }
  302. }
  303. static int
  304. prepare_audiounit(_THIS, const char *devname, int iscapture,
  305. const AudioStreamBasicDescription * strdesc)
  306. {
  307. OSStatus result = noErr;
  308. AURenderCallbackStruct callback;
  309. #if MACOSX_COREAUDIO
  310. ComponentDescription desc;
  311. Component comp = NULL;
  312. #else
  313. AudioComponentDescription desc;
  314. AudioComponent comp = NULL;
  315. #endif
  316. const AudioUnitElement output_bus = 0;
  317. const AudioUnitElement input_bus = 1;
  318. const AudioUnitElement bus = ((iscapture) ? input_bus : output_bus);
  319. const AudioUnitScope scope = ((iscapture) ? kAudioUnitScope_Output :
  320. kAudioUnitScope_Input);
  321. #if MACOSX_COREAUDIO
  322. if (!find_device_by_name(this, devname, iscapture)) {
  323. SDL_SetError("Couldn't find requested CoreAudio device");
  324. return 0;
  325. }
  326. #endif
  327. SDL_zero(desc);
  328. desc.componentType = kAudioUnitType_Output;
  329. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  330. #if MACOSX_COREAUDIO
  331. desc.componentSubType = kAudioUnitSubType_DefaultOutput;
  332. comp = FindNextComponent(NULL, &desc);
  333. #else
  334. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  335. comp = AudioComponentFindNext(NULL, &desc);
  336. #endif
  337. if (comp == NULL) {
  338. SDL_SetError("Couldn't find requested CoreAudio component");
  339. return 0;
  340. }
  341. /* Open & initialize the audio unit */
  342. #if MACOSX_COREAUDIO
  343. result = OpenAComponent(comp, &this->hidden->audioUnit);
  344. CHECK_RESULT("OpenAComponent");
  345. #else
  346. /*
  347. AudioComponentInstanceNew only available on iPhone OS 2.0 and Mac OS X 10.6
  348. We can't use OpenAComponent on iPhone because it is not present
  349. */
  350. result = AudioComponentInstanceNew(comp, &this->hidden->audioUnit);
  351. CHECK_RESULT("AudioComponentInstanceNew");
  352. #endif
  353. this->hidden->audioUnitOpened = 1;
  354. #if MACOSX_COREAUDIO
  355. result = AudioUnitSetProperty(this->hidden->audioUnit,
  356. kAudioOutputUnitProperty_CurrentDevice,
  357. kAudioUnitScope_Global, 0,
  358. &this->hidden->deviceID,
  359. sizeof(AudioDeviceID));
  360. CHECK_RESULT
  361. ("AudioUnitSetProperty (kAudioOutputUnitProperty_CurrentDevice)");
  362. #endif
  363. /* Set the data format of the audio unit. */
  364. result = AudioUnitSetProperty(this->hidden->audioUnit,
  365. kAudioUnitProperty_StreamFormat,
  366. scope, bus, strdesc, sizeof(*strdesc));
  367. CHECK_RESULT("AudioUnitSetProperty (kAudioUnitProperty_StreamFormat)");
  368. /* Set the audio callback */
  369. SDL_memset(&callback, 0, sizeof(AURenderCallbackStruct));
  370. callback.inputProc = ((iscapture) ? inputCallback : outputCallback);
  371. callback.inputProcRefCon = this;
  372. result = AudioUnitSetProperty(this->hidden->audioUnit,
  373. kAudioUnitProperty_SetRenderCallback,
  374. scope, bus, &callback, sizeof(callback));
  375. CHECK_RESULT
  376. ("AudioUnitSetProperty (kAudioUnitProperty_SetRenderCallback)");
  377. /* Calculate the final parameters for this audio specification */
  378. SDL_CalculateAudioSpec(&this->spec);
  379. /* Allocate a sample buffer */
  380. this->hidden->bufferOffset = this->hidden->bufferSize = this->spec.size;
  381. this->hidden->buffer = SDL_malloc(this->hidden->bufferSize);
  382. result = AudioUnitInitialize(this->hidden->audioUnit);
  383. CHECK_RESULT("AudioUnitInitialize");
  384. /* Finally, start processing of the audio unit */
  385. result = AudioOutputUnitStart(this->hidden->audioUnit);
  386. CHECK_RESULT("AudioOutputUnitStart");
  387. /* We're running! */
  388. return 1;
  389. }
  390. static int
  391. COREAUDIO_OpenDevice(_THIS, const char *devname, int iscapture)
  392. {
  393. AudioStreamBasicDescription strdesc;
  394. SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format);
  395. int valid_datatype = 0;
  396. /* Initialize all variables that we clean on shutdown */
  397. this->hidden = (struct SDL_PrivateAudioData *)
  398. SDL_malloc((sizeof *this->hidden));
  399. if (this->hidden == NULL) {
  400. return SDL_OutOfMemory();
  401. }
  402. SDL_memset(this->hidden, 0, (sizeof *this->hidden));
  403. /* Setup a AudioStreamBasicDescription with the requested format */
  404. SDL_memset(&strdesc, '\0', sizeof(AudioStreamBasicDescription));
  405. strdesc.mFormatID = kAudioFormatLinearPCM;
  406. strdesc.mFormatFlags = kLinearPCMFormatFlagIsPacked;
  407. strdesc.mChannelsPerFrame = this->spec.channels;
  408. strdesc.mSampleRate = this->spec.freq;
  409. strdesc.mFramesPerPacket = 1;
  410. while ((!valid_datatype) && (test_format)) {
  411. this->spec.format = test_format;
  412. /* Just a list of valid SDL formats, so people don't pass junk here. */
  413. switch (test_format) {
  414. case AUDIO_U8:
  415. case AUDIO_S8:
  416. case AUDIO_U16LSB:
  417. case AUDIO_S16LSB:
  418. case AUDIO_U16MSB:
  419. case AUDIO_S16MSB:
  420. case AUDIO_S32LSB:
  421. case AUDIO_S32MSB:
  422. case AUDIO_F32LSB:
  423. case AUDIO_F32MSB:
  424. valid_datatype = 1;
  425. strdesc.mBitsPerChannel = SDL_AUDIO_BITSIZE(this->spec.format);
  426. if (SDL_AUDIO_ISBIGENDIAN(this->spec.format))
  427. strdesc.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian;
  428. if (SDL_AUDIO_ISFLOAT(this->spec.format))
  429. strdesc.mFormatFlags |= kLinearPCMFormatFlagIsFloat;
  430. else if (SDL_AUDIO_ISSIGNED(this->spec.format))
  431. strdesc.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
  432. break;
  433. }
  434. }
  435. if (!valid_datatype) { /* shouldn't happen, but just in case... */
  436. COREAUDIO_CloseDevice(this);
  437. return SDL_SetError("Unsupported audio format");
  438. }
  439. strdesc.mBytesPerFrame =
  440. strdesc.mBitsPerChannel * strdesc.mChannelsPerFrame / 8;
  441. strdesc.mBytesPerPacket =
  442. strdesc.mBytesPerFrame * strdesc.mFramesPerPacket;
  443. if (!prepare_audiounit(this, devname, iscapture, &strdesc)) {
  444. COREAUDIO_CloseDevice(this);
  445. return -1; /* prepare_audiounit() will call SDL_SetError()... */
  446. }
  447. return 0; /* good to go. */
  448. }
  449. static int
  450. COREAUDIO_Init(SDL_AudioDriverImpl * impl)
  451. {
  452. /* Set the function pointers */
  453. impl->OpenDevice = COREAUDIO_OpenDevice;
  454. impl->CloseDevice = COREAUDIO_CloseDevice;
  455. #if MACOSX_COREAUDIO
  456. impl->DetectDevices = COREAUDIO_DetectDevices;
  457. #else
  458. impl->OnlyHasDefaultOutputDevice = 1;
  459. /* Set category to ambient sound so that other music continues playing.
  460. You can change this at runtime in your own code if you need different
  461. behavior. If this is common, we can add an SDL hint for this.
  462. */
  463. AudioSessionInitialize(NULL, NULL, NULL, nil);
  464. UInt32 category = kAudioSessionCategory_AmbientSound;
  465. AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(UInt32), &category);
  466. #endif
  467. impl->ProvidesOwnCallbackThread = 1;
  468. return 1; /* this audio target is available. */
  469. }
  470. AudioBootStrap COREAUDIO_bootstrap = {
  471. "coreaudio", "CoreAudio", COREAUDIO_Init, 0
  472. };
  473. /* vi: set ts=4 sw=4 expandtab: */