2 Copyright (C) 2008 Grame
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 #include "JackCoreAudioAdapter.h"
21 #include "JackError.h"
24 #include <CoreServices/CoreServices.h>
29 static void PrintStreamDesc(AudioStreamBasicDescription *inDesc)
31 jack_log("- - - - - - - - - - - - - - - - - - - -");
32 jack_log(" Sample Rate:%f", inDesc->mSampleRate);
33 jack_log(" Format ID:%.*s", (int) sizeof(inDesc->mFormatID), (char*)&inDesc->mFormatID);
34 jack_log(" Format Flags:%lX", inDesc->mFormatFlags);
35 jack_log(" Bytes per Packet:%ld", inDesc->mBytesPerPacket);
36 jack_log(" Frames per Packet:%ld", inDesc->mFramesPerPacket);
37 jack_log(" Bytes per Frame:%ld", inDesc->mBytesPerFrame);
38 jack_log(" Channels per Frame:%ld", inDesc->mChannelsPerFrame);
39 jack_log(" Bits per Channel:%ld", inDesc->mBitsPerChannel);
40 jack_log("- - - - - - - - - - - - - - - - - - - -");
43 static OSStatus DisplayDeviceNames()
51 err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
56 deviceNum = size / sizeof(AudioDeviceID);
57 AudioDeviceID devices[deviceNum];
59 err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
64 for (i = 0; i < deviceNum; i++) {
65 char device_name[256];
66 char internal_name[256];
68 size = sizeof(CFStringRef);
70 err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
72 CFStringGetCString(UIname, internal_name, 256, CFStringGetSystemEncoding());
78 err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &size, device_name);
83 jack_info("Device name = \'%s\', internal_name = \'%s\' (to be used as -C, -P, or -d parameter)", device_name, internal_name);
95 static void printError(OSStatus err)
98 case kAudioHardwareNoError:
99 jack_log("error code : kAudioHardwareNoError");
101 case kAudioConverterErr_FormatNotSupported:
102 jack_log("error code : kAudioConverterErr_FormatNotSupported");
104 case kAudioConverterErr_OperationNotSupported:
105 jack_log("error code : kAudioConverterErr_OperationNotSupported");
107 case kAudioConverterErr_PropertyNotSupported:
108 jack_log("error code : kAudioConverterErr_PropertyNotSupported");
110 case kAudioConverterErr_InvalidInputSize:
111 jack_log("error code : kAudioConverterErr_InvalidInputSize");
113 case kAudioConverterErr_InvalidOutputSize:
114 jack_log("error code : kAudioConverterErr_InvalidOutputSize");
116 case kAudioConverterErr_UnspecifiedError:
117 jack_log("error code : kAudioConverterErr_UnspecifiedError");
119 case kAudioConverterErr_BadPropertySizeError:
120 jack_log("error code : kAudioConverterErr_BadPropertySizeError");
122 case kAudioConverterErr_RequiresPacketDescriptionsError:
123 jack_log("error code : kAudioConverterErr_RequiresPacketDescriptionsError");
125 case kAudioConverterErr_InputSampleRateOutOfRange:
126 jack_log("error code : kAudioConverterErr_InputSampleRateOutOfRange");
128 case kAudioConverterErr_OutputSampleRateOutOfRange:
129 jack_log("error code : kAudioConverterErr_OutputSampleRateOutOfRange");
131 case kAudioHardwareNotRunningError:
132 jack_log("error code : kAudioHardwareNotRunningError");
134 case kAudioHardwareUnknownPropertyError:
135 jack_log("error code : kAudioHardwareUnknownPropertyError");
137 case kAudioHardwareIllegalOperationError:
138 jack_log("error code : kAudioHardwareIllegalOperationError");
140 case kAudioHardwareBadDeviceError:
141 jack_log("error code : kAudioHardwareBadDeviceError");
143 case kAudioHardwareBadStreamError:
144 jack_log("error code : kAudioHardwareBadStreamError");
146 case kAudioDeviceUnsupportedFormatError:
147 jack_log("error code : kAudioDeviceUnsupportedFormatError");
149 case kAudioDevicePermissionsError:
150 jack_log("error code : kAudioDevicePermissionsError");
152 case kAudioHardwareBadObjectError:
153 jack_log("error code : kAudioHardwareBadObjectError");
155 case kAudioHardwareUnsupportedOperationError:
156 jack_log("error code : kAudioHardwareUnsupportedOperationError");
159 jack_log("error code : unknown");
164 OSStatus JackCoreAudioAdapter::AudioHardwareNotificationCallback(AudioHardwarePropertyID inPropertyID, void* inClientData)
166 JackCoreAudioAdapter* driver = (JackCoreAudioAdapter*)inClientData;
168 switch (inPropertyID) {
170 case kAudioHardwarePropertyDevices: {
171 jack_log("JackCoreAudioAdapter::AudioHardwareNotificationCallback kAudioHardwarePropertyDevices");
172 DisplayDeviceNames();
180 OSStatus JackCoreAudioAdapter::SRNotificationCallback(AudioDeviceID inDevice,
183 AudioDevicePropertyID inPropertyID,
186 JackCoreAudioAdapter* driver = static_cast<JackCoreAudioAdapter*>(inClientData);
188 switch (inPropertyID) {
190 case kAudioDevicePropertyNominalSampleRate: {
191 jack_log("JackCoreAudioAdapter::SRNotificationCallback kAudioDevicePropertyNominalSampleRate");
192 driver->fState = true;
200 // A better implementation would try to recover in case of hardware device change (see HALLAB HLFilePlayerWindowControllerAudioDevicePropertyListenerProc code)
201 OSStatus JackCoreAudioAdapter::DeviceNotificationCallback(AudioDeviceID inDevice,
204 AudioDevicePropertyID inPropertyID,
208 switch (inPropertyID) {
210 case kAudioDeviceProcessorOverload: {
211 jack_error("JackCoreAudioAdapter::DeviceNotificationCallback kAudioDeviceProcessorOverload");
215 case kAudioDevicePropertyStreamConfiguration: {
216 jack_error("Cannot handle kAudioDevicePropertyStreamConfiguration");
217 return kAudioHardwareUnsupportedOperationError;
220 case kAudioDevicePropertyNominalSampleRate: {
221 jack_error("Cannot handle kAudioDevicePropertyNominalSampleRate");
222 return kAudioHardwareUnsupportedOperationError;
229 int JackCoreAudioAdapter::AddListeners()
231 OSStatus err = noErr;
234 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback, this);
236 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDeviceProcessorOverload");
241 err = AudioHardwareAddPropertyListener(kAudioHardwarePropertyDevices, AudioHardwareNotificationCallback, this);
243 jack_error("Error calling AudioHardwareAddPropertyListener with kAudioHardwarePropertyDevices");
248 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback, this);
250 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
255 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback, this);
257 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsRunning");
262 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
264 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
269 err = AudioDeviceAddPropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
271 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
279 void JackCoreAudioAdapter::RemoveListeners()
281 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback);
282 AudioHardwareRemovePropertyListener(kAudioHardwarePropertyDevices, AudioHardwareNotificationCallback);
283 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback);
284 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback);
285 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
286 AudioDeviceRemovePropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
289 OSStatus JackCoreAudioAdapter::Render(void *inRefCon,
290 AudioUnitRenderActionFlags *ioActionFlags,
291 const AudioTimeStamp *inTimeStamp,
293 UInt32 inNumberFrames,
294 AudioBufferList *ioData)
296 return static_cast<JackCoreAudioAdapter*>(inRefCon)->Render(ioActionFlags, inTimeStamp, inNumberFrames, ioData);
299 OSStatus JackCoreAudioAdapter::Render(AudioUnitRenderActionFlags *ioActionFlags,
300 const AudioTimeStamp *inTimeStamp,
301 UInt32 inNumberFrames,
302 AudioBufferList *ioData)
304 OSStatus err = AudioUnitRender(fAUHAL, ioActionFlags, inTimeStamp, 1, inNumberFrames, fInputData);
307 jack_default_audio_sample_t* inputBuffer[fCaptureChannels];
308 jack_default_audio_sample_t* outputBuffer[fPlaybackChannels];
310 for (int i = 0; i < fCaptureChannels; i++) {
311 inputBuffer[i] = (jack_default_audio_sample_t*)fInputData->mBuffers[i].mData;
313 for (int i = 0; i < fPlaybackChannels; i++) {
314 outputBuffer[i] = (jack_default_audio_sample_t*)ioData->mBuffers[i].mData;
317 PushAndPull((jack_default_audio_sample_t**)inputBuffer, (jack_default_audio_sample_t**)outputBuffer, inNumberFrames);
324 JackCoreAudioAdapter::JackCoreAudioAdapter(jack_nframes_t buffer_size, jack_nframes_t sample_rate, const JSList* params)
325 :JackAudioAdapterInterface(buffer_size, sample_rate), fInputData(0), fCapturing(false), fPlaying(false), fState(false)
328 const jack_driver_param_t* param;
329 int in_nChannels = 0;
330 int out_nChannels = 0;
331 char captureName[256];
332 char playbackName[256];
335 fClockDriftCompensate = false;
338 fCaptureChannels = -1;
339 fPlaybackChannels = -1;
343 Gestalt(gestaltSystemVersionMajor, &major);
344 Gestalt(gestaltSystemVersionMinor, &minor);
346 // Starting with 10.6 systems, the HAL notification thread is created internally
347 if (major == 10 && minor >= 6) {
348 CFRunLoopRef theRunLoop = NULL;
349 AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
350 OSStatus theError = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
351 if (theError != noErr) {
352 jack_error("JackCoreAudioAdapter::Open kAudioHardwarePropertyRunLoop error");
356 for (node = params; node; node = jack_slist_next(node)) {
357 param = (const jack_driver_param_t*) node->data;
359 switch (param->character) {
362 fCaptureChannels = param->value.ui;
366 fPlaybackChannels = param->value.ui;
371 strncpy(fCaptureUID, param->value.str, 256);
376 strncpy(fPlaybackUID, param->value.str, 256);
380 strncpy(fCaptureUID, param->value.str, 256);
381 strncpy(fPlaybackUID, param->value.str, 256);
385 fCapturing = fPlaying = true;
389 SetAdaptedSampleRate(param->value.ui);
393 SetAdaptedBufferSize(param->value.ui);
397 DisplayDeviceNames();
401 fQuality = param->value.ui;
405 fRingbufferCurSize = param->value.ui;
410 fClockDriftCompensate = true;
415 /* duplex is the default */
416 if (!fCapturing && !fPlaying) {
421 if (SetupDevices(fCaptureUID, fPlaybackUID, captureName, playbackName, fAdaptedSampleRate) < 0) {
422 throw std::bad_alloc();
425 if (SetupChannels(fCapturing, fPlaying, fCaptureChannels, fPlaybackChannels, in_nChannels, out_nChannels, true) < 0) {
426 throw std::bad_alloc();
429 if (SetupBufferSize(fAdaptedBufferSize) < 0) {
430 throw std::bad_alloc();
433 if (SetupSampleRate(fAdaptedSampleRate) < 0) {
434 throw std::bad_alloc();
437 if (OpenAUHAL(fCapturing, fPlaying, fCaptureChannels, fPlaybackChannels, in_nChannels, out_nChannels, fAdaptedBufferSize, fAdaptedSampleRate) < 0) {
438 throw std::bad_alloc();
441 if (fCapturing && fCaptureChannels > 0) {
442 if (SetupBuffers(fCaptureChannels) < 0) {
443 throw std::bad_alloc();
447 if (AddListeners() < 0) {
448 throw std::bad_alloc();
451 GetStreamLatencies(fDeviceID, true, fInputLatencies);
452 GetStreamLatencies(fDeviceID, false, fOutputLatencies);
455 OSStatus JackCoreAudioAdapter::GetDefaultDevice(AudioDeviceID* id)
458 UInt32 theSize = sizeof(UInt32);
459 AudioDeviceID inDefault;
460 AudioDeviceID outDefault;
462 if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr) {
466 if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr) {
470 jack_log("GetDefaultDevice: input = %ld output = %ld", inDefault, outDefault);
472 // Get the device only if default input and output are the same
473 if (inDefault != outDefault) {
474 jack_error("Default input and output devices are not the same !!");
475 return kAudioHardwareBadDeviceError;
476 } else if (inDefault == 0) {
477 jack_error("Default input and output devices are null !!");
478 return kAudioHardwareBadDeviceError;
485 OSStatus JackCoreAudioAdapter::GetTotalChannels(AudioDeviceID device, int& channelCount, bool isInput)
487 OSStatus err = noErr;
492 err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, &outWritable);
494 AudioBufferList bufferList[outSize];
495 err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, bufferList);
497 for (unsigned int i = 0; i < bufferList->mNumberBuffers; i++) {
498 channelCount += bufferList->mBuffers[i].mNumberChannels;
506 OSStatus JackCoreAudioAdapter::GetDeviceIDFromUID(const char* UID, AudioDeviceID* id)
508 UInt32 size = sizeof(AudioValueTranslation);
509 CFStringRef inIUD = CFStringCreateWithCString(NULL, UID, CFStringGetSystemEncoding());
510 AudioValueTranslation value = { &inIUD, sizeof(CFStringRef), id, sizeof(AudioDeviceID) };
513 return kAudioHardwareUnspecifiedError;
515 OSStatus res = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, &size, &value);
517 jack_log("GetDeviceIDFromUID %s %ld", UID, *id);
518 return (*id == kAudioDeviceUnknown) ? kAudioHardwareBadDeviceError : res;
522 OSStatus JackCoreAudioAdapter::GetDefaultInputDevice(AudioDeviceID* id)
525 UInt32 theSize = sizeof(UInt32);
526 AudioDeviceID inDefault;
528 if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr) {
532 if (inDefault == 0) {
533 jack_error("Error: default input device is 0, please select a correct one !!");
536 jack_log("GetDefaultInputDevice: input = %ld ", inDefault);
541 OSStatus JackCoreAudioAdapter::GetDefaultOutputDevice(AudioDeviceID* id)
544 UInt32 theSize = sizeof(UInt32);
545 AudioDeviceID outDefault;
547 if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr) {
551 if (outDefault == 0) {
552 jack_error("Error: default output device is 0, please select a correct one !!");
555 jack_log("GetDefaultOutputDevice: output = %ld", outDefault);
560 OSStatus JackCoreAudioAdapter::GetDeviceNameFromID(AudioDeviceID id, char* name)
563 return AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceName, &size, name);
566 AudioDeviceID JackCoreAudioAdapter::GetDeviceIDFromName(const char* name)
572 OSStatus err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
577 deviceNum = size / sizeof(AudioDeviceID);
578 AudioDeviceID devices[deviceNum];
580 err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
585 for (i = 0; i < deviceNum; i++) {
586 char device_name[256];
588 err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &size, device_name);
591 } else if (strcmp(device_name, name) == 0) {
600 int JackCoreAudioAdapter::SetupDevices(const char* capture_driver_uid,
601 const char* playback_driver_uid,
602 char* capture_driver_name,
603 char* playback_driver_name,
604 jack_nframes_t samplerate)
606 capture_driver_name[0] = 0;
607 playback_driver_name[0] = 0;
610 if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
611 jack_log("JackCoreAudioDriver::Open duplex");
613 // Same device for capture and playback...
614 if (strcmp(capture_driver_uid, playback_driver_uid) == 0) {
616 if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
617 jack_log("Will take default in/out");
618 if (GetDefaultDevice(&fDeviceID) != noErr) {
619 jack_error("Cannot open default device");
623 if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
624 jack_error("Cannot get device name from device ID");
630 // Creates aggregate device
631 AudioDeviceID captureID, playbackID;
633 if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
634 jack_log("Will take default input");
635 if (GetDefaultInputDevice(&captureID) != noErr) {
636 jack_error("Cannot open default input device");
641 if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
642 jack_log("Will take default output");
643 if (GetDefaultOutputDevice(&playbackID) != noErr) {
644 jack_error("Cannot open default output device");
649 if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr) {
655 } else if (strcmp(capture_driver_uid, "") != 0) {
656 jack_log("JackCoreAudioAdapter::Open capture only");
657 if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
658 if (GetDefaultInputDevice(&fDeviceID) != noErr) {
659 jack_error("Cannot open default input device");
663 if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
664 jack_error("Cannot get device name from device ID");
669 } else if (strcmp(playback_driver_uid, "") != 0) {
670 jack_log("JackCoreAudioAdapter::Open playback only");
671 if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
672 if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
673 jack_error("Cannot open default output device");
677 if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
678 jack_error("Cannot get device name from device ID");
682 // Use default driver in duplex mode
684 jack_log("JackCoreAudioAdapter::Open default driver");
685 if (GetDefaultDevice(&fDeviceID) != noErr) {
686 jack_error("Cannot open default device in duplex mode, so aggregate default input and default output");
688 // Creates aggregate device
689 AudioDeviceID captureID = -1, playbackID = -1;
691 if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
692 jack_log("Will take default input");
693 if (GetDefaultInputDevice(&captureID) != noErr) {
694 jack_error("Cannot open default input device");
699 if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
700 jack_log("Will take default output");
701 if (GetDefaultOutputDevice(&playbackID) != noErr) {
702 jack_error("Cannot open default output device");
707 if (captureID > 0 && playbackID > 0) {
708 if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr) {
712 jack_error("Cannot use default input/output");
722 // Aggregate built-in input and output
723 AudioDeviceID captureID = GetDeviceIDFromName("Built-in Input");
724 AudioDeviceID playbackID = GetDeviceIDFromName("Built-in Output");
726 if (captureID > 0 && playbackID > 0) {
727 if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr) {
731 jack_error("Cannot aggregate built-in input and output");
738 int JackCoreAudioAdapter::SetupChannels(bool capturing,
746 OSStatus err = noErr;
749 err = GetTotalChannels(fDeviceID, in_nChannels, true);
751 jack_error("Cannot get input channel number");
755 jack_log("Max input channels : %d", in_nChannels);
760 err = GetTotalChannels(fDeviceID, out_nChannels, false);
762 jack_error("Cannot get output channel number");
766 jack_log("Max output channels : %d", out_nChannels);
770 if (inchannels > in_nChannels) {
771 jack_error("This device hasn't required input channels inchannels = %ld in_nChannels = %ld", inchannels, in_nChannels);
777 if (outchannels > out_nChannels) {
778 jack_error("This device hasn't required output channels outchannels = %ld out_nChannels = %ld", outchannels, out_nChannels);
784 if (inchannels == -1) {
785 jack_log("Setup max in channels = %ld", in_nChannels);
786 inchannels = in_nChannels;
789 if (outchannels == -1) {
790 jack_log("Setup max out channels = %ld", out_nChannels);
791 outchannels = out_nChannels;
797 int JackCoreAudioAdapter::SetupBufferSize(jack_nframes_t buffer_size)
799 // Setting buffer size
800 UInt32 outSize = sizeof(UInt32);
801 OSStatus err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
803 jack_error("Cannot set buffer size %ld", buffer_size);
811 int JackCoreAudioAdapter::SetupSampleRate(jack_nframes_t samplerate)
813 return SetupSampleRateAux(fDeviceID, samplerate);
816 int JackCoreAudioAdapter::SetupSampleRateAux(AudioDeviceID inDevice, jack_nframes_t samplerate)
818 OSStatus err = noErr;
823 outSize = sizeof(Float64);
824 err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
826 jack_error("Cannot get current sample rate");
830 jack_log("Current sample rate = %f", sampleRate);
833 // If needed, set new sample rate
834 if (samplerate != (jack_nframes_t)sampleRate) {
835 sampleRate = (Float64)samplerate;
837 // To get SR change notification
838 err = AudioDeviceAddPropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback, this);
840 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
844 err = AudioDeviceSetProperty(inDevice, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &sampleRate);
846 jack_error("Cannot set sample rate = %ld", samplerate);
851 // Waiting for SR change notification
853 while (!fState && count++ < WAIT_COUNTER) {
855 jack_log("Wait count = %d", count);
858 // Remove SR change notification
859 AudioDeviceRemovePropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
865 int JackCoreAudioAdapter::SetupBuffers(int inchannels)
867 jack_log("JackCoreAudioAdapter::SetupBuffers: input = %ld", inchannels);
870 fInputData = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
871 fInputData->mNumberBuffers = inchannels;
872 for (int i = 0; i < fCaptureChannels; i++) {
873 fInputData->mBuffers[i].mNumberChannels = 1;
874 fInputData->mBuffers[i].mDataByteSize = fAdaptedBufferSize * sizeof(jack_default_audio_sample_t);
875 fInputData->mBuffers[i].mData = malloc(fAdaptedBufferSize * sizeof(jack_default_audio_sample_t));
880 void JackCoreAudioAdapter::DisposeBuffers()
883 for (int i = 0; i < fCaptureChannels; i++) {
884 free(fInputData->mBuffers[i].mData);
891 int JackCoreAudioAdapter::OpenAUHAL(bool capturing,
897 jack_nframes_t buffer_size,
898 jack_nframes_t samplerate)
900 ComponentResult err1;
902 AudioStreamBasicDescription srcFormat, dstFormat;
903 AudioDeviceID currAudioDeviceID;
906 jack_log("OpenAUHAL capturing = %d playing = %d inchannels = %d outchannels = %d in_nChannels = %d out_nChannels = %d", capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels);
908 if (inchannels == 0 && outchannels == 0) {
909 jack_error("No input and output channels...");
914 #if (defined(MAC_OS_X_VERSION_10_5) && (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5))
915 AudioComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
916 AudioComponent HALOutput = AudioComponentFindNext(NULL, &cd);
917 err1 = AudioComponentInstanceNew(HALOutput, &fAUHAL);
919 jack_error("Error calling AudioComponentInstanceNew");
924 ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
925 Component HALOutput = FindNextComponent(NULL, &cd);
926 err1 = OpenAComponent(HALOutput, &fAUHAL);
928 jack_error("Error calling OpenAComponent");
934 err1 = AudioUnitInitialize(fAUHAL);
936 jack_error("Cannot initialize AUHAL unit");
942 if (capturing && inchannels > 0) {
944 jack_log("Setup AUHAL input on");
947 jack_log("Setup AUHAL input off");
950 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
952 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
957 if (playing && outchannels > 0) {
959 jack_log("Setup AUHAL output on");
962 jack_log("Setup AUHAL output off");
965 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
967 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
972 size = sizeof(AudioDeviceID);
973 err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
975 jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
979 jack_log("AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
982 // Setup up chosen device, in both input and output cases
983 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
985 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
991 if (capturing && inchannels > 0) {
992 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*)&buffer_size, sizeof(UInt32));
994 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
1000 if (playing && outchannels > 0) {
1001 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*)&buffer_size, sizeof(UInt32));
1002 if (err1 != noErr) {
1003 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
1009 // Setup channel map
1010 if (capturing && inchannels > 0 && inchannels <= in_nChannels) {
1011 SInt32 chanArr[in_nChannels];
1012 for (int i = 0; i < in_nChannels; i++) {
1015 for (int i = 0; i < inchannels; i++) {
1018 AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
1019 if (err1 != noErr) {
1020 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 1");
1026 if (playing && outchannels > 0 && outchannels <= out_nChannels) {
1027 SInt32 chanArr[out_nChannels];
1028 for (int i = 0; i < out_nChannels; i++) {
1031 for (int i = 0; i < outchannels; i++) {
1034 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
1035 if (err1 != noErr) {
1036 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 0");
1042 // Setup stream converters
1043 if (capturing && inchannels > 0) {
1045 size = sizeof(AudioStreamBasicDescription);
1046 err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &srcFormat, &size);
1047 if (err1 != noErr) {
1048 jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
1052 PrintStreamDesc(&srcFormat);
1054 jack_log("Setup AUHAL input stream converter SR = %ld", samplerate);
1055 srcFormat.mSampleRate = samplerate;
1056 srcFormat.mFormatID = kAudioFormatLinearPCM;
1057 srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
1058 srcFormat.mBytesPerPacket = sizeof(jack_default_audio_sample_t);
1059 srcFormat.mFramesPerPacket = 1;
1060 srcFormat.mBytesPerFrame = sizeof(jack_default_audio_sample_t);
1061 srcFormat.mChannelsPerFrame = inchannels;
1062 srcFormat.mBitsPerChannel = 32;
1063 PrintStreamDesc(&srcFormat);
1065 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &srcFormat, sizeof(AudioStreamBasicDescription));
1067 if (err1 != noErr) {
1068 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
1074 if (playing && outchannels > 0) {
1076 size = sizeof(AudioStreamBasicDescription);
1077 err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 1, &dstFormat, &size);
1078 if (err1 != noErr) {
1079 jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
1083 PrintStreamDesc(&dstFormat);
1085 jack_log("Setup AUHAL output stream converter SR = %ld", samplerate);
1086 dstFormat.mSampleRate = samplerate;
1087 dstFormat.mFormatID = kAudioFormatLinearPCM;
1088 dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
1089 dstFormat.mBytesPerPacket = sizeof(jack_default_audio_sample_t);
1090 dstFormat.mFramesPerPacket = 1;
1091 dstFormat.mBytesPerFrame = sizeof(jack_default_audio_sample_t);
1092 dstFormat.mChannelsPerFrame = outchannels;
1093 dstFormat.mBitsPerChannel = 32;
1094 PrintStreamDesc(&dstFormat);
1096 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &dstFormat, sizeof(AudioStreamBasicDescription));
1098 if (err1 != noErr) {
1099 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
1106 if (inchannels > 0 && outchannels == 0) {
1107 AURenderCallbackStruct output;
1108 output.inputProc = Render;
1109 output.inputProcRefCon = this;
1110 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
1111 if (err1 != noErr) {
1112 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
1117 AURenderCallbackStruct output;
1118 output.inputProc = Render;
1119 output.inputProcRefCon = this;
1120 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
1121 if (err1 != noErr) {
1122 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
1135 OSStatus JackCoreAudioAdapter::DestroyAggregateDevice()
1137 OSStatus osErr = noErr;
1138 AudioObjectPropertyAddress pluginAOPA;
1139 pluginAOPA.mSelector = kAudioPlugInDestroyAggregateDevice;
1140 pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
1141 pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
1144 osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
1145 if (osErr != noErr) {
1146 jack_error("JackCoreAudioAdapter::DestroyAggregateDevice : AudioObjectGetPropertyDataSize error");
1151 osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, 0, NULL, &outDataSize, &fDeviceID);
1152 if (osErr != noErr) {
1153 jack_error("JackCoreAudioAdapter::DestroyAggregateDevice : AudioObjectGetPropertyData error");
1161 static CFStringRef GetDeviceName(AudioDeviceID id)
1163 UInt32 size = sizeof(CFStringRef);
1165 OSStatus err = AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
1166 return (err == noErr) ? UIname : NULL;
1169 OSStatus JackCoreAudioAdapter::CreateAggregateDevice(AudioDeviceID captureDeviceID, AudioDeviceID playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
1171 OSStatus err = noErr;
1172 AudioObjectID sub_device[32];
1173 UInt32 outSize = sizeof(sub_device);
1175 err = AudioDeviceGetProperty(captureDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
1176 vector<AudioDeviceID> captureDeviceIDArray;
1179 jack_log("Input device does not have subdevices");
1180 captureDeviceIDArray.push_back(captureDeviceID);
1182 int num_devices = outSize / sizeof(AudioObjectID);
1183 jack_log("Input device has %d subdevices", num_devices);
1184 for (int i = 0; i < num_devices; i++) {
1185 captureDeviceIDArray.push_back(sub_device[i]);
1189 outSize = sizeof(sub_device);
1190 err = AudioDeviceGetProperty(playbackDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
1191 vector<AudioDeviceID> playbackDeviceIDArray;
1194 jack_log("Output device does not have subdevices");
1195 playbackDeviceIDArray.push_back(playbackDeviceID);
1197 int num_devices = outSize / sizeof(AudioObjectID);
1198 jack_log("Output device has %d subdevices", num_devices);
1199 for (int i = 0; i < num_devices; i++) {
1200 playbackDeviceIDArray.push_back(sub_device[i]);
1204 return CreateAggregateDeviceAux(captureDeviceIDArray, playbackDeviceIDArray, samplerate, outAggregateDevice);
1207 OSStatus JackCoreAudioAdapter::CreateAggregateDeviceAux(vector<AudioDeviceID> captureDeviceID, vector<AudioDeviceID> playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
1209 OSStatus osErr = noErr;
1211 Boolean outWritable;
1213 // Prepare sub-devices for clock drift compensation
1214 // Workaround for bug in the HAL : until 10.6.2
1215 AudioObjectPropertyAddress theAddressOwned = { kAudioObjectPropertyOwnedObjects, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1216 AudioObjectPropertyAddress theAddressDrift = { kAudioSubDevicePropertyDriftCompensation, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1217 UInt32 theQualifierDataSize = sizeof(AudioObjectID);
1218 AudioClassID inClass = kAudioSubDeviceClassID;
1219 void* theQualifierData = &inClass;
1220 UInt32 subDevicesNum = 0;
1222 //---------------------------------------------------------------------------
1223 // Setup SR of both devices otherwise creating AD may fail...
1224 //---------------------------------------------------------------------------
1225 UInt32 keptclockdomain = 0;
1226 UInt32 clockdomain = 0;
1227 outSize = sizeof(UInt32);
1228 bool need_clock_drift_compensation = false;
1230 for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
1231 if (SetupSampleRateAux(captureDeviceID[i], samplerate) < 0) {
1232 jack_error("JackCoreAudioAdapter::CreateAggregateDevice : cannot set SR of input device");
1234 // Check clock domain
1235 osErr = AudioDeviceGetProperty(captureDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
1237 jack_error("JackCoreAudioAdapter::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
1240 keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
1241 jack_log("JackCoreAudioAdapter::CreateAggregateDevice : input clockdomain = %d", clockdomain);
1242 if (clockdomain != 0 && clockdomain != keptclockdomain) {
1243 jack_error("JackCoreAudioAdapter::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
1244 need_clock_drift_compensation = true;
1250 for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
1251 if (SetupSampleRateAux(playbackDeviceID[i], samplerate) < 0) {
1252 jack_error("JackCoreAudioAdapter::CreateAggregateDevice : cannot set SR of output device");
1254 // Check clock domain
1255 osErr = AudioDeviceGetProperty(playbackDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
1257 jack_error("JackCoreAudioAdapter::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
1260 keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
1261 jack_log("JackCoreAudioAdapter::CreateAggregateDevice : output clockdomain = %d", clockdomain);
1262 if (clockdomain != 0 && clockdomain != keptclockdomain) {
1263 jack_error("JackCoreAudioAdapter::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
1264 need_clock_drift_compensation = true;
1270 // If no valid clock domain was found, then assume we have to compensate...
1271 if (keptclockdomain == 0) {
1272 need_clock_drift_compensation = true;
1275 //---------------------------------------------------------------------------
1276 // Start to create a new aggregate by getting the base audio hardware plugin
1277 //---------------------------------------------------------------------------
1279 char device_name[256];
1280 for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
1281 GetDeviceNameFromID(captureDeviceID[i], device_name);
1282 jack_info("Separated input = '%s' ", device_name);
1285 for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
1286 GetDeviceNameFromID(playbackDeviceID[i], device_name);
1287 jack_info("Separated output = '%s' ", device_name);
1290 osErr = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyPlugInForBundleID, &outSize, &outWritable);
1291 if (osErr != noErr) {
1292 jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioHardwareGetPropertyInfo kAudioHardwarePropertyPlugInForBundleID error");
1297 AudioValueTranslation pluginAVT;
1299 CFStringRef inBundleRef = CFSTR("com.apple.audio.CoreAudio");
1301 pluginAVT.mInputData = &inBundleRef;
1302 pluginAVT.mInputDataSize = sizeof(inBundleRef);
1303 pluginAVT.mOutputData = &fPluginID;
1304 pluginAVT.mOutputDataSize = sizeof(fPluginID);
1306 osErr = AudioHardwareGetProperty(kAudioHardwarePropertyPlugInForBundleID, &outSize, &pluginAVT);
1307 if (osErr != noErr) {
1308 jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioHardwareGetProperty kAudioHardwarePropertyPlugInForBundleID error");
1313 //-------------------------------------------------
1314 // Create a CFDictionary for our aggregate device
1315 //-------------------------------------------------
1317 CFMutableDictionaryRef aggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1319 CFStringRef AggregateDeviceNameRef = CFSTR("JackDuplex");
1320 CFStringRef AggregateDeviceUIDRef = CFSTR("com.grame.JackDuplex");
1322 // add the name of the device to the dictionary
1323 CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceNameKey), AggregateDeviceNameRef);
1325 // add our choice of UID for the aggregate device to the dictionary
1326 CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceUIDKey), AggregateDeviceUIDRef);
1328 // add a "private aggregate key" to the dictionary
1330 CFNumberRef AggregateDeviceNumberRef = CFNumberCreate(NULL, kCFNumberIntType, &value);
1333 Gestalt(gestaltSystemVersion, &system);
1335 jack_log("JackCoreAudioAdapter::CreateAggregateDevice : system version = %x limit = %x", system, 0x00001054);
1337 // Starting with 10.5.4 systems, the AD can be internal... (better)
1338 if (system < 0x00001054) {
1339 jack_log("JackCoreAudioAdapter::CreateAggregateDevice : public aggregate device....");
1341 jack_log("JackCoreAudioAdapter::CreateAggregateDevice : private aggregate device....");
1342 CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceIsPrivateKey), AggregateDeviceNumberRef);
1345 // Prepare sub-devices for clock drift compensation
1346 CFMutableArrayRef subDevicesArrayClock = NULL;
1349 if (fClockDriftCompensate) {
1350 if (need_clock_drift_compensation) {
1351 jack_info("Clock drift compensation activated...");
1352 subDevicesArrayClock = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
1354 for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
1355 CFStringRef UID = GetDeviceName(captureDeviceID[i]);
1357 CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1358 CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
1359 CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
1361 CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
1365 for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
1366 CFStringRef UID = GetDeviceName(playbackDeviceID[i]);
1368 CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
1369 CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
1370 CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
1372 CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
1376 // add sub-device clock array for the aggregate device to the dictionary
1377 CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceSubDeviceListKey), subDevicesArrayClock);
1379 jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
1384 //-------------------------------------------------
1385 // Create a CFMutableArray for our sub-device list
1386 //-------------------------------------------------
1388 // we need to append the UID for each device to a CFMutableArray, so create one here
1389 CFMutableArrayRef subDevicesArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
1391 vector<CFStringRef> captureDeviceUID;
1392 for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
1393 CFStringRef ref = GetDeviceName(captureDeviceID[i]);
1397 captureDeviceUID.push_back(ref);
1398 // input sub-devices in this example, so append the sub-device's UID to the CFArray
1399 CFArrayAppendValue(subDevicesArray, ref);
1402 vector<CFStringRef> playbackDeviceUID;
1403 for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
1404 CFStringRef ref = GetDeviceName(playbackDeviceID[i]);
1408 playbackDeviceUID.push_back(ref);
1409 // output sub-devices in this example, so append the sub-device's UID to the CFArray
1410 CFArrayAppendValue(subDevicesArray, ref);
1413 //-----------------------------------------------------------------------
1414 // Feed the dictionary to the plugin, to create a blank aggregate device
1415 //-----------------------------------------------------------------------
1417 AudioObjectPropertyAddress pluginAOPA;
1418 pluginAOPA.mSelector = kAudioPlugInCreateAggregateDevice;
1419 pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
1420 pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
1423 osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
1424 if (osErr != noErr) {
1425 jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioObjectGetPropertyDataSize error");
1430 osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, sizeof(aggDeviceDict), &aggDeviceDict, &outDataSize, outAggregateDevice);
1431 if (osErr != noErr) {
1432 jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioObjectGetPropertyData error");
1437 // pause for a bit to make sure that everything completed correctly
1438 // this is to work around a bug in the HAL where a new aggregate device seems to disappear briefly after it is created
1439 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
1441 //-------------------------
1442 // Set the sub-device list
1443 //-------------------------
1445 pluginAOPA.mSelector = kAudioAggregateDevicePropertyFullSubDeviceList;
1446 pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
1447 pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
1448 outDataSize = sizeof(CFMutableArrayRef);
1449 osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &subDevicesArray);
1450 if (osErr != noErr) {
1451 jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioObjectSetPropertyData for sub-device list error");
1456 // pause again to give the changes time to take effect
1457 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
1459 //-----------------------
1460 // Set the master device
1461 //-----------------------
1463 // set the master device manually (this is the device which will act as the master clock for the aggregate device)
1464 // pass in the UID of the device you want to use
1465 pluginAOPA.mSelector = kAudioAggregateDevicePropertyMasterSubDevice;
1466 pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
1467 pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
1468 outDataSize = sizeof(CFStringRef);
1469 osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &playbackDeviceUID[0]); // First playback is master...
1470 if (osErr != noErr) {
1471 jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioObjectSetPropertyData for master device error");
1476 // pause again to give the changes time to take effect
1477 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
1479 // Prepare sub-devices for clock drift compensation
1480 // Workaround for bug in the HAL : until 10.6.2
1482 if (fClockDriftCompensate) {
1483 if (need_clock_drift_compensation) {
1484 jack_info("Clock drift compensation activated...");
1486 // Get the property data size
1487 osErr = AudioObjectGetPropertyDataSize(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize);
1488 if (osErr != noErr) {
1489 jack_error("JackCoreAudioAdapter::CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
1493 // Calculate the number of object IDs
1494 subDevicesNum = outSize / sizeof(AudioObjectID);
1495 jack_info("JackCoreAudioAdapter::CreateAggregateDevice clock drift compensation, number of sub-devices = %d", subDevicesNum);
1496 AudioObjectID subDevices[subDevicesNum];
1497 outSize = sizeof(subDevices);
1499 osErr = AudioObjectGetPropertyData(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize, subDevices);
1500 if (osErr != noErr) {
1501 jack_error("JackCoreAudioAdapter::CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
1505 // Set kAudioSubDevicePropertyDriftCompensation property...
1506 for (UInt32 index = 0; index < subDevicesNum; ++index) {
1507 UInt32 theDriftCompensationValue = 1;
1508 osErr = AudioObjectSetPropertyData(subDevices[index], &theAddressDrift, 0, NULL, sizeof(UInt32), &theDriftCompensationValue);
1509 if (osErr != noErr) {
1510 jack_error("JackCoreAudioAdapter::CreateAggregateDevice kAudioSubDevicePropertyDriftCompensation error");
1515 jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
1519 // pause again to give the changes time to take effect
1520 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
1526 // release the private AD key
1527 CFRelease(AggregateDeviceNumberRef);
1529 // release the CF objects we have created - we don't need them any more
1530 CFRelease(aggDeviceDict);
1531 CFRelease(subDevicesArray);
1533 if (subDevicesArrayClock) {
1534 CFRelease(subDevicesArrayClock);
1537 // release the device UID
1538 for (UInt32 i = 0; i < captureDeviceUID.size(); i++) {
1539 CFRelease(captureDeviceUID[i]);
1542 for (UInt32 i = 0; i < playbackDeviceUID.size(); i++) {
1543 CFRelease(playbackDeviceUID[i]);
1546 jack_log("New aggregate device %ld", *outAggregateDevice);
1550 DestroyAggregateDevice();
1555 bool JackCoreAudioAdapter::IsAggregateDevice(AudioDeviceID device)
1557 OSStatus err = noErr;
1558 AudioObjectID sub_device[32];
1559 UInt32 outSize = sizeof(sub_device);
1560 err = AudioDeviceGetProperty(device, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
1563 jack_log("Device does not have subdevices");
1566 int num_devices = outSize / sizeof(AudioObjectID);
1567 jack_log("Device does has %d subdevices", num_devices);
1572 void JackCoreAudioAdapter::CloseAUHAL()
1574 AudioUnitUninitialize(fAUHAL);
1575 CloseComponent(fAUHAL);
1578 int JackCoreAudioAdapter::Open()
1580 return (AudioOutputUnitStart(fAUHAL) != noErr) ? -1 : 0;
1583 int JackCoreAudioAdapter::Close()
1586 fTable.Save(fHostBufferSize, fHostSampleRate, fAdaptedSampleRate, fAdaptedBufferSize);
1588 AudioOutputUnitStop(fAUHAL);
1592 if (fPluginID > 0) {
1593 DestroyAggregateDevice();
1598 int JackCoreAudioAdapter::SetSampleRate(jack_nframes_t sample_rate)
1600 JackAudioAdapterInterface::SetHostSampleRate(sample_rate);
1605 int JackCoreAudioAdapter::SetBufferSize(jack_nframes_t buffer_size)
1607 JackAudioAdapterInterface::SetHostBufferSize(buffer_size);
1612 OSStatus JackCoreAudioAdapter::GetStreamLatencies(AudioDeviceID device, bool isInput, vector<int>& latencies)
1614 OSStatus err = noErr;
1615 UInt32 outSize1, outSize2, outSize3;
1616 Boolean outWritable;
1618 err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreams, &outSize1, &outWritable);
1620 int stream_count = outSize1 / sizeof(UInt32);
1621 AudioStreamID streamIDs[stream_count];
1622 AudioBufferList bufferList[stream_count];
1623 UInt32 streamLatency;
1624 outSize2 = sizeof(UInt32);
1626 err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreams, &outSize1, streamIDs);
1628 jack_error("GetStreamLatencies kAudioDevicePropertyStreams err = %d", err);
1632 err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize3, &outWritable);
1634 jack_error("GetStreamLatencies kAudioDevicePropertyStreamConfiguration err = %d", err);
1638 for (int i = 0; i < stream_count; i++) {
1639 err = AudioStreamGetProperty(streamIDs[i], 0, kAudioStreamPropertyLatency, &outSize2, &streamLatency);
1641 jack_error("GetStreamLatencies kAudioStreamPropertyLatency err = %d", err);
1644 err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize3, bufferList);
1646 jack_error("GetStreamLatencies kAudioDevicePropertyStreamConfiguration err = %d", err);
1649 // Push 'channel' time the stream latency
1650 for (uint k = 0; k < bufferList->mBuffers[i].mNumberChannels; k++) {
1651 latencies.push_back(streamLatency);
1658 int JackCoreAudioAdapter::GetLatency(int port_index, bool input)
1660 UInt32 size = sizeof(UInt32);
1664 OSStatus err = AudioDeviceGetProperty(fDeviceID, 0, input, kAudioDevicePropertyLatency, &size, &value1);
1666 jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error");
1668 err = AudioDeviceGetProperty(fDeviceID, 0, input, kAudioDevicePropertySafetyOffset, &size, &value2);
1670 jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error");
1673 // TODO : add stream latency
1675 return value1 + value2 + fAdaptedBufferSize;
1678 int JackCoreAudioAdapter::GetInputLatency(int port_index)
1680 if (port_index < int(fInputLatencies.size())) {
1681 return GetLatency(port_index, true) + fInputLatencies[port_index];
1683 // No stream latency
1684 return GetLatency(port_index, true);
1688 int JackCoreAudioAdapter::GetOutputLatency(int port_index)
1690 if (port_index < int(fOutputLatencies.size())) {
1691 return GetLatency(port_index, false) + fOutputLatencies[port_index];
1693 // No stream latency
1694 return GetLatency(port_index, false);
1705 SERVER_EXPORT jack_driver_desc_t* jack_get_descriptor()
1707 jack_driver_desc_t * desc;
1708 jack_driver_desc_filler_t filler;
1709 jack_driver_param_value_t value;
1711 desc = jack_driver_descriptor_construct("audioadapter", JackDriverNone, "netjack audio <==> net backend adapter", &filler);
1714 jack_driver_descriptor_add_parameter(desc, &filler, "in-channels", 'i', JackDriverParamInt, &value, NULL, "Maximum number of input channels", "Maximum number of input channels. If -1, max possible number of input channels will be used");
1715 jack_driver_descriptor_add_parameter(desc, &filler, "out-channels", 'o', JackDriverParamInt, &value, NULL, "Maximum number of output channels", "Maximum number of output channels. If -1, max possible number of output channels will be used");
1718 jack_driver_descriptor_add_parameter(desc, &filler, "capture", 'C', JackDriverParamString, &value, NULL, "Input CoreAudio device name", NULL);
1719 jack_driver_descriptor_add_parameter(desc, &filler, "playback", 'P', JackDriverParamString, &value, NULL, "Output CoreAudio device name", NULL);
1722 jack_driver_descriptor_add_parameter(desc, &filler, "rate", 'r', JackDriverParamUInt, &value, NULL, "Sample rate", NULL);
1725 jack_driver_descriptor_add_parameter(desc, &filler, "period", 'p', JackDriverParamUInt, &value, NULL, "Frames per period", NULL);
1728 jack_driver_descriptor_add_parameter(desc, &filler, "duplex", 'D', JackDriverParamBool, &value, NULL, "Provide both capture and playback ports", NULL);
1731 jack_driver_descriptor_add_parameter(desc, &filler, "device", 'd', JackDriverParamString, &value, NULL, "CoreAudio device name", NULL);
1734 jack_driver_descriptor_add_parameter(desc, &filler, "list-devices", 'l', JackDriverParamBool, &value, NULL, "Display available CoreAudio devices", NULL);
1737 jack_driver_descriptor_add_parameter(desc, &filler, "quality", 'q', JackDriverParamInt, &value, NULL, "Resample algorithm quality (0 - 4)", NULL);
1740 jack_driver_descriptor_add_parameter(desc, &filler, "ring-buffer", 'g', JackDriverParamInt, &value, NULL, "Fixed ringbuffer size", "Fixed ringbuffer size (if not set => automatic adaptative)");
1743 jack_driver_descriptor_add_parameter(desc, &filler, "clock-drift", 's', JackDriverParamBool, &value, NULL, "Clock drift compensation", "Whether to compensate clock drift in dynamically created aggregate device");
1746 jack_driver_descriptor_add_parameter(desc, &filler, "auto-connect", 'c', JackDriverParamBool, &value, NULL, "Auto connect audioadapter to system ports", NULL);