2 SDL - Simple DirectMedia Layer
3 Copyright (C) 1997-2006 Sam Lantinga
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "SDL_config.h"
24 #include <CoreAudio/CoreAudio.h>
25 #include <AudioUnit/AudioUnit.h>
26 #ifdef AVAILABLE_MAC_OS_X_VERSION_10_5_AND_LATER
27 #include <AudioUnit/AUNTComponent.h>
30 #include "SDL_audio.h"
31 #include "../SDL_audio_c.h"
32 #include "../SDL_sysaudio.h"
33 #include "SDL_coreaudio.h"
35 #define DEBUG_COREAUDIO 0
37 typedef struct COREAUDIO_DeviceList
41 } COREAUDIO_DeviceList;
43 static COREAUDIO_DeviceList *inputDevices = NULL;
44 static int inputDeviceCount = 0;
45 static COREAUDIO_DeviceList *outputDevices = NULL;
46 static int outputDeviceCount = 0;
49 free_device_list(COREAUDIO_DeviceList ** devices, int *devCount)
54 SDL_free((void *) (*devices)[i].name);
63 build_device_list(int iscapture, COREAUDIO_DeviceList ** devices,
66 Boolean outWritable = 0;
67 OSStatus result = noErr;
69 AudioDeviceID *devs = NULL;
73 free_device_list(devices, devCount);
75 result = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices,
78 if (result != kAudioHardwareNoError)
81 devs = (AudioDeviceID *) alloca(size);
85 max = size / sizeof(AudioDeviceID);
86 *devices = (COREAUDIO_DeviceList *) SDL_malloc(max * sizeof(**devices));
90 result = AudioHardwareGetProperty(kAudioHardwarePropertyDevices,
92 if (result != kAudioHardwareNoError)
95 for (i = 0; i < max; i++) {
96 CFStringRef cfstr = NULL;
98 AudioDeviceID dev = devs[i];
99 AudioBufferList *buflist = NULL;
103 result = AudioDeviceGetPropertyInfo(dev, 0, iscapture,
104 kAudioDevicePropertyStreamConfiguration,
105 &size, &outWritable);
109 buflist = (AudioBufferList *) SDL_malloc(size);
113 result = AudioDeviceGetProperty(dev, 0, iscapture,
114 kAudioDevicePropertyStreamConfiguration,
117 if (result == noErr) {
119 for (j = 0; j < buflist->mNumberBuffers; j++) {
120 if (buflist->mBuffers[j].mNumberChannels > 0) {
132 size = sizeof(CFStringRef);
133 result = AudioDeviceGetProperty(dev, 0, iscapture,
134 kAudioDevicePropertyDeviceNameCFString,
137 if (result != kAudioHardwareNoError)
140 len = CFStringGetMaximumSizeForEncoding(CFStringGetLength(cfstr),
141 kCFStringEncodingUTF8);
143 ptr = (char *) SDL_malloc(len + 1);
144 usable = ((ptr != NULL) &&
146 (cfstr, ptr, len + 1, kCFStringEncodingUTF8)));
152 /* Some devices have whitespace at the end...trim it. */
153 while ((len > 0) && (ptr[len - 1] == ' ')) {
165 printf("COREAUDIO: Found %s device #%d: '%s' (devid %d)\n",
166 ((iscapture) ? "capture" : "output"),
167 (int) *devCount, ptr, (int) dev);
170 (*devices)[*devCount].id = dev;
171 (*devices)[*devCount].name = ptr;
178 build_device_lists(void)
180 build_device_list(0, &outputDevices, &outputDeviceCount);
181 build_device_list(1, &inputDevices, &inputDeviceCount);
186 free_device_lists(void)
188 free_device_list(&outputDevices, &outputDeviceCount);
189 free_device_list(&inputDevices, &inputDeviceCount);
194 find_device_id(const char *devname, int iscapture, AudioDeviceID * id)
196 int i = ((iscapture) ? inputDeviceCount : outputDeviceCount);
197 COREAUDIO_DeviceList *devs = ((iscapture) ? inputDevices : outputDevices);
199 if (SDL_strcmp(devname, devs->name) == 0) {
211 COREAUDIO_DetectDevices(int iscapture)
214 build_device_list(1, &inputDevices, &inputDeviceCount);
215 return inputDeviceCount;
217 build_device_list(0, &outputDevices, &outputDeviceCount);
218 return outputDeviceCount;
221 return 0; /* shouldn't ever hit this. */
226 COREAUDIO_GetDeviceName(int index, int iscapture)
228 if ((iscapture) && (index < inputDeviceCount)) {
229 return inputDevices[index].name;
230 } else if ((!iscapture) && (index < outputDeviceCount)) {
231 return outputDevices[index].name;
234 SDL_SetError("No such device");
240 COREAUDIO_Deinitialize(void)
246 /* The CoreAudio callback */
248 outputCallback(void *inRefCon,
249 AudioUnitRenderActionFlags * ioActionFlags,
250 const AudioTimeStamp * inTimeStamp,
251 UInt32 inBusNumber, UInt32 inNumberFrames,
252 AudioBufferList * ioDataList)
254 SDL_AudioDevice *this = (SDL_AudioDevice *) inRefCon;
255 AudioBuffer *ioData = &ioDataList->mBuffers[0];
256 UInt32 remaining, len;
259 /* Is there ever more than one buffer, and what do you do with it? */
260 if (ioDataList->mNumberBuffers != 1) {
264 /* Only do anything if audio is enabled and not paused */
265 if (!this->enabled || this->paused) {
266 SDL_memset(ioData->mData, this->spec.silence, ioData->mDataByteSize);
270 /* No SDL conversion should be needed here, ever, since we accept
271 any input format in OpenAudio, and leave the conversion to CoreAudio.
274 assert(!this->convert.needed);
275 assert(this->spec.channels == ioData->mNumberChannels);
278 remaining = ioData->mDataByteSize;
280 while (remaining > 0) {
281 if (this->hidden->bufferOffset >= this->hidden->bufferSize) {
282 /* Generate the data */
283 SDL_memset(this->hidden->buffer, this->spec.silence,
284 this->hidden->bufferSize);
285 SDL_mutexP(this->mixer_lock);
286 (*this->spec.callback) (this->spec.userdata, this->hidden->buffer,
287 this->hidden->bufferSize);
288 SDL_mutexV(this->mixer_lock);
289 this->hidden->bufferOffset = 0;
292 len = this->hidden->bufferSize - this->hidden->bufferOffset;
296 (char *) this->hidden->buffer + this->hidden->bufferOffset,
298 ptr = (char *) ptr + len;
300 this->hidden->bufferOffset += len;
307 inputCallback(void *inRefCon,
308 AudioUnitRenderActionFlags * ioActionFlags,
309 const AudioTimeStamp * inTimeStamp,
310 UInt32 inBusNumber, UInt32 inNumberFrames,
311 AudioBufferList * ioData)
313 //err = AudioUnitRender(afr->fAudioUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, afr->fAudioBuffer);
314 // !!! FIXME: write me!
320 COREAUDIO_CloseDevice(_THIS)
322 if (this->hidden != NULL) {
323 if (this->hidden->audioUnitOpened) {
324 OSStatus result = noErr;
325 AURenderCallbackStruct callback;
326 const AudioUnitElement output_bus = 0;
327 const AudioUnitElement input_bus = 1;
328 const int iscapture = this->iscapture;
329 const AudioUnitElement bus =
330 ((iscapture) ? input_bus : output_bus);
331 const AudioUnitScope scope =
332 ((iscapture) ? kAudioUnitScope_Output :
333 kAudioUnitScope_Input);
335 /* stop processing the audio unit */
336 result = AudioOutputUnitStop(this->hidden->audioUnit);
338 /* Remove the input callback */
339 SDL_memset(&callback, '\0', sizeof(AURenderCallbackStruct));
340 result = AudioUnitSetProperty(this->hidden->audioUnit,
341 kAudioUnitProperty_SetRenderCallback,
342 scope, bus, &callback,
345 CloseComponent(this->hidden->audioUnit);
346 this->hidden->audioUnitOpened = 0;
348 SDL_free(this->hidden->buffer);
349 SDL_free(this->hidden);
355 #define CHECK_RESULT(msg) \
356 if (result != noErr) { \
357 COREAUDIO_CloseDevice(this); \
358 SDL_SetError("CoreAudio error (%s): %d", msg, (int) result); \
363 find_device_by_name(_THIS, const char *devname, int iscapture)
365 AudioDeviceID devid = 0;
366 OSStatus result = noErr;
371 if (devname == NULL) {
372 size = sizeof(AudioDeviceID);
373 const AudioHardwarePropertyID propid =
374 ((iscapture) ? kAudioHardwarePropertyDefaultInputDevice :
375 kAudioHardwarePropertyDefaultOutputDevice);
377 result = AudioHardwareGetProperty(propid, &size, &devid);
378 CHECK_RESULT("AudioHardwareGetProperty (default device)");
380 if (!find_device_id(devname, iscapture, &devid)) {
381 SDL_SetError("CoreAudio: No such audio device.");
386 size = sizeof(alive);
387 result = AudioDeviceGetProperty(devid, 0, iscapture,
388 kAudioDevicePropertyDeviceIsAlive,
391 ("AudioDeviceGetProperty (kAudioDevicePropertyDeviceIsAlive)");
394 SDL_SetError("CoreAudio: requested device exists, but isn't alive.");
399 result = AudioDeviceGetProperty(devid, 0, iscapture,
400 kAudioDevicePropertyHogMode, &size, &pid);
402 /* some devices don't support this property, so errors are fine here. */
403 if ((result == noErr) && (pid != -1)) {
404 SDL_SetError("CoreAudio: requested device is being hogged.");
408 this->hidden->deviceID = devid;
414 prepare_audiounit(_THIS, const char *devname, int iscapture,
415 const AudioStreamBasicDescription * strdesc)
417 OSStatus result = noErr;
418 AURenderCallbackStruct callback;
419 ComponentDescription desc;
420 Component comp = NULL;
422 const AudioUnitElement output_bus = 0;
423 const AudioUnitElement input_bus = 1;
424 const AudioUnitElement bus = ((iscapture) ? input_bus : output_bus);
425 const AudioUnitScope scope = ((iscapture) ? kAudioUnitScope_Output :
426 kAudioUnitScope_Input);
428 if (!find_device_by_name(this, devname, iscapture)) {
429 SDL_SetError("Couldn't find requested CoreAudio device");
433 SDL_memset(&desc, '\0', sizeof(ComponentDescription));
434 desc.componentType = kAudioUnitType_Output;
435 desc.componentSubType = kAudioUnitSubType_HALOutput;
436 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
438 comp = FindNextComponent(NULL, &desc);
440 SDL_SetError("Couldn't find requested CoreAudio component");
444 /* Open & initialize the audio unit */
445 result = OpenAComponent(comp, &this->hidden->audioUnit);
446 CHECK_RESULT("OpenAComponent");
448 this->hidden->audioUnitOpened = 1;
450 // !!! FIXME: this is wrong?
451 enableIO = ((iscapture) ? 1 : 0);
452 result = AudioUnitSetProperty(this->hidden->audioUnit,
453 kAudioOutputUnitProperty_EnableIO,
454 kAudioUnitScope_Input, input_bus,
455 &enableIO, sizeof(enableIO));
456 CHECK_RESULT("AudioUnitSetProperty (kAudioUnitProperty_EnableIO input)");
458 // !!! FIXME: this is wrong?
459 enableIO = ((iscapture) ? 0 : 1);
460 result = AudioUnitSetProperty(this->hidden->audioUnit,
461 kAudioOutputUnitProperty_EnableIO,
462 kAudioUnitScope_Output, output_bus,
463 &enableIO, sizeof(enableIO));
464 CHECK_RESULT("AudioUnitSetProperty (kAudioUnitProperty_EnableIO output)");
466 result = AudioUnitSetProperty(this->hidden->audioUnit,
467 kAudioOutputUnitProperty_CurrentDevice,
468 kAudioUnitScope_Global, 0,
469 &this->hidden->deviceID,
470 sizeof(AudioDeviceID));
472 ("AudioUnitSetProperty (kAudioOutputUnitProperty_CurrentDevice)");
474 /* Set the data format of the audio unit. */
475 result = AudioUnitSetProperty(this->hidden->audioUnit,
476 kAudioUnitProperty_StreamFormat,
477 scope, bus, strdesc, sizeof(*strdesc));
478 CHECK_RESULT("AudioUnitSetProperty (kAudioUnitProperty_StreamFormat)");
480 /* Set the audio callback */
481 SDL_memset(&callback, '\0', sizeof(AURenderCallbackStruct));
482 callback.inputProc = ((iscapture) ? inputCallback : outputCallback);
483 callback.inputProcRefCon = this;
484 result = AudioUnitSetProperty(this->hidden->audioUnit,
485 kAudioUnitProperty_SetRenderCallback,
486 scope, bus, &callback, sizeof(callback));
488 ("AudioUnitSetProperty (kAudioUnitProperty_SetInputCallback)");
490 /* Calculate the final parameters for this audio specification */
491 SDL_CalculateAudioSpec(&this->spec);
493 /* Allocate a sample buffer */
494 this->hidden->bufferOffset = this->hidden->bufferSize = this->spec.size;
495 this->hidden->buffer = SDL_malloc(this->hidden->bufferSize);
497 result = AudioUnitInitialize(this->hidden->audioUnit);
498 CHECK_RESULT("AudioUnitInitialize");
500 /* Finally, start processing of the audio unit */
501 result = AudioOutputUnitStart(this->hidden->audioUnit);
502 CHECK_RESULT("AudioOutputUnitStart");
510 COREAUDIO_OpenDevice(_THIS, const char *devname, int iscapture)
512 AudioStreamBasicDescription strdesc;
513 SDL_AudioFormat test_format = SDL_FirstAudioFormat(this->spec.format);
514 int valid_datatype = 0;
516 /* Initialize all variables that we clean on shutdown */
517 this->hidden = (struct SDL_PrivateAudioData *)
518 SDL_malloc((sizeof *this->hidden));
519 if (this->hidden == NULL) {
523 SDL_memset(this->hidden, 0, (sizeof *this->hidden));
525 /* Setup a AudioStreamBasicDescription with the requested format */
526 SDL_memset(&strdesc, '\0', sizeof(AudioStreamBasicDescription));
527 strdesc.mFormatID = kAudioFormatLinearPCM;
528 strdesc.mFormatFlags = kLinearPCMFormatFlagIsPacked;
529 strdesc.mChannelsPerFrame = this->spec.channels;
530 strdesc.mSampleRate = this->spec.freq;
531 strdesc.mFramesPerPacket = 1;
533 while ((!valid_datatype) && (test_format)) {
534 this->spec.format = test_format;
535 /* Just a list of valid SDL formats, so people don't pass junk here. */
536 switch (test_format) {
548 strdesc.mBitsPerChannel = SDL_AUDIO_BITSIZE(this->spec.format);
549 if (SDL_AUDIO_ISBIGENDIAN(this->spec.format))
550 strdesc.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian;
552 if (SDL_AUDIO_ISFLOAT(this->spec.format))
553 strdesc.mFormatFlags |= kLinearPCMFormatFlagIsFloat;
554 else if (SDL_AUDIO_ISSIGNED(this->spec.format))
555 strdesc.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
560 if (!valid_datatype) { /* shouldn't happen, but just in case... */
561 COREAUDIO_CloseDevice(this);
562 SDL_SetError("Unsupported audio format");
566 strdesc.mBytesPerFrame =
567 strdesc.mBitsPerChannel * strdesc.mChannelsPerFrame / 8;
568 strdesc.mBytesPerPacket =
569 strdesc.mBytesPerFrame * strdesc.mFramesPerPacket;
571 if (!prepare_audiounit(this, devname, iscapture, &strdesc)) {
572 COREAUDIO_CloseDevice(this);
573 return 0; /* prepare_audiounit() will call SDL_SetError()... */
576 return 1; /* good to go. */
580 COREAUDIO_Init(SDL_AudioDriverImpl * impl)
582 /* Set the function pointers */
583 impl->DetectDevices = COREAUDIO_DetectDevices;
584 impl->GetDeviceName = COREAUDIO_GetDeviceName;
585 impl->OpenDevice = COREAUDIO_OpenDevice;
586 impl->CloseDevice = COREAUDIO_CloseDevice;
587 impl->Deinitialize = COREAUDIO_Deinitialize;
588 impl->ProvidesOwnCallbackThread = 1;
590 build_device_lists(); /* do an initial check for devices... */
595 AudioBootStrap COREAUDIO_bootstrap = {
596 "coreaudio", "Mac OS X CoreAudio", COREAUDIO_Init, 0
599 /* vi: set ts=4 sw=4 expandtab: */