Hopefully fix compilation issue introduced in r3823.
[jack2.git] / macosx / coreaudio / JackCoreAudioDriver.cpp
blob55f5d4d23688fe069a80eece501d5b0626d79fc6
1 /*
2 Copyright (C) 2004-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 "JackCoreAudioDriver.h"
21 #include "JackEngineControl.h"
22 #include "JackMachThread.h"
23 #include "JackGraphManager.h"
24 #include "JackError.h"
25 #include "JackClientControl.h"
26 #include "JackDriverLoader.h"
27 #include "JackGlobals.h"
28 #include "JackTools.h"
29 #include "JackCompilerDeps.h"
31 #include <iostream>
32 #include <CoreServices/CoreServices.h>
33 #include <CoreFoundation/CFNumber.h>
35 namespace Jack
38 static void Print4CharCode(const char* msg, long c)
40 UInt32 __4CC_number = (c);
41 char __4CC_string[5];
42 *((SInt32*)__4CC_string) = EndianU32_NtoB(__4CC_number);
43 __4CC_string[4] = 0;
44 jack_log("%s'%s'", (msg), __4CC_string);
47 static void PrintStreamDesc(AudioStreamBasicDescription *inDesc)
49 jack_log("- - - - - - - - - - - - - - - - - - - -");
50 jack_log(" Sample Rate:%f", inDesc->mSampleRate);
51 jack_log(" Format ID:%.*s", (int) sizeof(inDesc->mFormatID), (char*)&inDesc->mFormatID);
52 jack_log(" Format Flags:%lX", inDesc->mFormatFlags);
53 jack_log(" Bytes per Packet:%ld", inDesc->mBytesPerPacket);
54 jack_log(" Frames per Packet:%ld", inDesc->mFramesPerPacket);
55 jack_log(" Bytes per Frame:%ld", inDesc->mBytesPerFrame);
56 jack_log(" Channels per Frame:%ld", inDesc->mChannelsPerFrame);
57 jack_log(" Bits per Channel:%ld", inDesc->mBitsPerChannel);
58 jack_log("- - - - - - - - - - - - - - - - - - - -\n");
61 static void printError(OSStatus err)
63 switch (err) {
64 case kAudioHardwareNoError:
65 jack_log("error code : kAudioHardwareNoError");
66 break;
67 case kAudioConverterErr_FormatNotSupported:
68 jack_log("error code : kAudioConverterErr_FormatNotSupported");
69 break;
70 case kAudioConverterErr_OperationNotSupported:
71 jack_log("error code : kAudioConverterErr_OperationNotSupported");
72 break;
73 case kAudioConverterErr_PropertyNotSupported:
74 jack_log("error code : kAudioConverterErr_PropertyNotSupported");
75 break;
76 case kAudioConverterErr_InvalidInputSize:
77 jack_log("error code : kAudioConverterErr_InvalidInputSize");
78 break;
79 case kAudioConverterErr_InvalidOutputSize:
80 jack_log("error code : kAudioConverterErr_InvalidOutputSize");
81 break;
82 case kAudioConverterErr_UnspecifiedError:
83 jack_log("error code : kAudioConverterErr_UnspecifiedError");
84 break;
85 case kAudioConverterErr_BadPropertySizeError:
86 jack_log("error code : kAudioConverterErr_BadPropertySizeError");
87 break;
88 case kAudioConverterErr_RequiresPacketDescriptionsError:
89 jack_log("error code : kAudioConverterErr_RequiresPacketDescriptionsError");
90 break;
91 case kAudioConverterErr_InputSampleRateOutOfRange:
92 jack_log("error code : kAudioConverterErr_InputSampleRateOutOfRange");
93 break;
94 case kAudioConverterErr_OutputSampleRateOutOfRange:
95 jack_log("error code : kAudioConverterErr_OutputSampleRateOutOfRange");
96 break;
97 case kAudioHardwareNotRunningError:
98 jack_log("error code : kAudioHardwareNotRunningError");
99 break;
100 case kAudioHardwareUnknownPropertyError:
101 jack_log("error code : kAudioHardwareUnknownPropertyError");
102 break;
103 case kAudioHardwareIllegalOperationError:
104 jack_log("error code : kAudioHardwareIllegalOperationError");
105 break;
106 case kAudioHardwareBadDeviceError:
107 jack_log("error code : kAudioHardwareBadDeviceError");
108 break;
109 case kAudioHardwareBadStreamError:
110 jack_log("error code : kAudioHardwareBadStreamError");
111 break;
112 case kAudioDeviceUnsupportedFormatError:
113 jack_log("error code : kAudioDeviceUnsupportedFormatError");
114 break;
115 case kAudioDevicePermissionsError:
116 jack_log("error code : kAudioDevicePermissionsError");
117 break;
118 case kAudioHardwareBadObjectError:
119 jack_log("error code : kAudioHardwareBadObjectError");
120 break;
121 case kAudioHardwareUnsupportedOperationError:
122 jack_log("error code : kAudioHardwareUnsupportedOperationError");
123 break;
124 default:
125 Print4CharCode("error code : unknown", err);
126 break;
130 static OSStatus DisplayDeviceNames()
132 UInt32 size;
133 Boolean isWritable;
134 int i, deviceNum;
135 OSStatus err;
136 CFStringRef UIname;
138 err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
139 if (err != noErr)
140 return err;
142 deviceNum = size / sizeof(AudioDeviceID);
143 AudioDeviceID devices[deviceNum];
145 err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
146 if (err != noErr)
147 return err;
149 for (i = 0; i < deviceNum; i++) {
150 char device_name[256];
151 char internal_name[256];
153 size = sizeof(CFStringRef);
154 UIname = NULL;
155 err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
156 if (err == noErr) {
157 CFStringGetCString(UIname, internal_name, 256, CFStringGetSystemEncoding());
158 } else {
159 goto error;
162 size = 256;
163 err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &size, device_name);
164 if (err != noErr)
165 return err;
167 jack_info("Device name = \'%s\', internal_name = \'%s\' (to be used as -C, -P, or -d parameter)", device_name, internal_name);
170 return noErr;
172 error:
173 if (UIname != NULL)
174 CFRelease(UIname);
175 return err;
178 static CFStringRef GetDeviceName(AudioDeviceID id)
180 UInt32 size = sizeof(CFStringRef);
181 CFStringRef UIname;
182 OSStatus err = AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
183 return (err == noErr) ? UIname : NULL;
186 OSStatus JackCoreAudioDriver::Render(void *inRefCon,
187 AudioUnitRenderActionFlags *ioActionFlags,
188 const AudioTimeStamp *inTimeStamp,
189 UInt32 inBusNumber,
190 UInt32 inNumberFrames,
191 AudioBufferList *ioData)
193 JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inRefCon;
194 driver->fActionFags = ioActionFlags;
195 driver->fCurrentTime = (AudioTimeStamp *)inTimeStamp;
196 driver->fDriverOutputData = ioData;
197 driver->CycleTakeBeginTime();
198 return driver->Process();
201 int JackCoreAudioDriver::Read()
203 AudioUnitRender(fAUHAL, fActionFags, fCurrentTime, 1, fEngineControl->fBufferSize, fJackInputData);
204 return 0;
207 int JackCoreAudioDriver::Write()
209 for (int i = 0; i < fPlaybackChannels; i++) {
210 if (fGraphManager->GetConnectionsNum(fPlaybackPortList[i]) > 0) {
211 float* buffer = GetOutputBuffer(i);
212 int size = sizeof(float) * fEngineControl->fBufferSize;
213 memcpy((float*)fDriverOutputData->mBuffers[i].mData, buffer, size);
214 // Monitor ports
215 if (fWithMonitorPorts && fGraphManager->GetConnectionsNum(fMonitorPortList[i]) > 0)
216 memcpy(GetMonitorBuffer(i), buffer, size);
217 } else {
218 memset((float*)fDriverOutputData->mBuffers[i].mData, 0, sizeof(float) * fEngineControl->fBufferSize);
221 return 0;
224 // Will run only once
225 OSStatus JackCoreAudioDriver::MeasureCallback(AudioDeviceID inDevice,
226 const AudioTimeStamp* inNow,
227 const AudioBufferList* inInputData,
228 const AudioTimeStamp* inInputTime,
229 AudioBufferList* outOutputData,
230 const AudioTimeStamp* inOutputTime,
231 void* inClientData)
233 JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
234 AudioDeviceStop(driver->fDeviceID, MeasureCallback);
236 jack_log("JackCoreAudioDriver::MeasureCallback called");
237 JackMachThread::GetParams(pthread_self(), &driver->fEngineControl->fPeriod, &driver->fEngineControl->fComputation, &driver->fEngineControl->fConstraint);
239 if (driver->fComputationGrain > 0) {
240 jack_log("JackCoreAudioDriver::MeasureCallback : RT thread computation setup to %d percent of period", int(driver->fComputationGrain * 100));
241 driver->fEngineControl->fComputation = driver->fEngineControl->fPeriod * driver->fComputationGrain;
244 // Signal waiting start function...
245 driver->fState = true;
247 // Setup threadded based log function
248 set_threaded_log_function();
249 return noErr;
252 OSStatus JackCoreAudioDriver::SRNotificationCallback(AudioDeviceID inDevice,
253 UInt32 inChannel,
254 Boolean isInput,
255 AudioDevicePropertyID inPropertyID,
256 void* inClientData)
258 JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
260 switch (inPropertyID) {
262 case kAudioDevicePropertyNominalSampleRate: {
263 jack_log("JackCoreAudioDriver::SRNotificationCallback kAudioDevicePropertyNominalSampleRate");
264 driver->fState = true;
265 break;
269 return noErr;
272 // A better implementation would possibly try to recover in case of hardware device change (see HALLAB HLFilePlayerWindowControllerAudioDevicePropertyListenerProc code)
273 OSStatus JackCoreAudioDriver::DeviceNotificationCallback(AudioDeviceID inDevice,
274 UInt32 inChannel,
275 Boolean isInput,
276 AudioDevicePropertyID inPropertyID,
277 void* inClientData)
279 JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
281 switch (inPropertyID) {
283 case kAudioDeviceProcessorOverload: {
284 jack_error("JackCoreAudioDriver::DeviceNotificationCallback kAudioDeviceProcessorOverload");
285 jack_time_t cur_time = GetMicroSeconds();
286 driver->NotifyXRun(cur_time, float(cur_time - driver->fBeginDateUst)); // Better this value than nothing...
287 break;
290 case kAudioDevicePropertyStreamConfiguration: {
291 jack_error("Cannot handle kAudioDevicePropertyStreamConfiguration : server will quit...");
292 driver->NotifyFailure(JackBackendError, "Another application has changed the device configuration."); // Message length limited to JACK_MESSAGE_SIZE
293 driver->CloseAUHAL();
294 kill(JackTools::GetPID(), SIGINT);
295 return kAudioHardwareUnsupportedOperationError;
298 case kAudioDevicePropertyNominalSampleRate: {
299 jack_error("Cannot handle kAudioDevicePropertyNominalSampleRate : server will quit...");
300 driver->NotifyFailure(JackBackendError, "Another application has changed the sample rate."); // Message length limited to JACK_MESSAGE_SIZE
301 driver->CloseAUHAL();
302 kill(JackTools::GetPID(), SIGINT);
303 return kAudioHardwareUnsupportedOperationError;
307 return noErr;
310 OSStatus JackCoreAudioDriver::GetDeviceIDFromUID(const char* UID, AudioDeviceID* id)
312 UInt32 size = sizeof(AudioValueTranslation);
313 CFStringRef inIUD = CFStringCreateWithCString(NULL, UID, CFStringGetSystemEncoding());
314 AudioValueTranslation value = { &inIUD, sizeof(CFStringRef), id, sizeof(AudioDeviceID) };
316 if (inIUD == NULL) {
317 return kAudioHardwareUnspecifiedError;
318 } else {
319 OSStatus res = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, &size, &value);
320 CFRelease(inIUD);
321 jack_log("GetDeviceIDFromUID %s %ld", UID, *id);
322 return (*id == kAudioDeviceUnknown) ? kAudioHardwareBadDeviceError : res;
326 OSStatus JackCoreAudioDriver::GetDefaultDevice(AudioDeviceID* id)
328 OSStatus res;
329 UInt32 theSize = sizeof(UInt32);
330 AudioDeviceID inDefault;
331 AudioDeviceID outDefault;
333 if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
334 return res;
336 if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
337 return res;
339 jack_log("GetDefaultDevice: input = %ld output = %ld", inDefault, outDefault);
341 // Get the device only if default input and output are the same
342 if (inDefault == outDefault) {
343 *id = inDefault;
344 return noErr;
345 } else {
346 jack_error("Default input and output devices are not the same !!");
347 return kAudioHardwareBadDeviceError;
351 OSStatus JackCoreAudioDriver::GetDefaultInputDevice(AudioDeviceID* id)
353 OSStatus res;
354 UInt32 theSize = sizeof(UInt32);
355 AudioDeviceID inDefault;
357 if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
358 return res;
360 jack_log("GetDefaultInputDevice: input = %ld ", inDefault);
361 *id = inDefault;
362 return noErr;
365 OSStatus JackCoreAudioDriver::GetDefaultOutputDevice(AudioDeviceID* id)
367 OSStatus res;
368 UInt32 theSize = sizeof(UInt32);
369 AudioDeviceID outDefault;
371 if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
372 return res;
374 jack_log("GetDefaultOutputDevice: output = %ld", outDefault);
375 *id = outDefault;
376 return noErr;
379 OSStatus JackCoreAudioDriver::GetDeviceNameFromID(AudioDeviceID id, char* name)
381 UInt32 size = 256;
382 return AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceName, &size, name);
385 OSStatus JackCoreAudioDriver::GetTotalChannels(AudioDeviceID device, int& channelCount, bool isInput)
387 OSStatus err = noErr;
388 UInt32 outSize;
389 Boolean outWritable;
391 channelCount = 0;
392 err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, &outWritable);
393 if (err == noErr) {
394 AudioBufferList bufferList[outSize];
395 err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, bufferList);
396 if (err == noErr) {
397 for (unsigned int i = 0; i < bufferList->mNumberBuffers; i++)
398 channelCount += bufferList->mBuffers[i].mNumberChannels;
401 return err;
404 JackCoreAudioDriver::JackCoreAudioDriver(const char* name, const char* alias, JackLockedEngine* engine, JackSynchro* table)
405 : JackAudioDriver(name, alias, engine, table),
406 fJackInputData(NULL),
407 fDriverOutputData(NULL),
408 fPluginID(0),
409 fState(false),
410 fHogged(false),
411 fIOUsage(1.f),
412 fComputationGrain(-1.f),
413 fClockDriftCompensate(false)
416 JackCoreAudioDriver::~JackCoreAudioDriver()
419 OSStatus JackCoreAudioDriver::DestroyAggregateDevice()
421 OSStatus osErr = noErr;
422 AudioObjectPropertyAddress pluginAOPA;
423 pluginAOPA.mSelector = kAudioPlugInDestroyAggregateDevice;
424 pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
425 pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
426 UInt32 outDataSize;
428 if (fPluginID > 0) {
430 osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
431 if (osErr != noErr) {
432 jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyDataSize error");
433 printError(osErr);
434 return osErr;
437 osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, 0, NULL, &outDataSize, &fDeviceID);
438 if (osErr != noErr) {
439 jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyData error");
440 printError(osErr);
441 return osErr;
446 return noErr;
449 OSStatus JackCoreAudioDriver::CreateAggregateDevice(AudioDeviceID captureDeviceID, AudioDeviceID playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
451 OSStatus err = noErr;
452 AudioObjectID sub_device[32];
453 UInt32 outSize = sizeof(sub_device);
455 err = AudioDeviceGetProperty(captureDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
456 vector<AudioDeviceID> captureDeviceIDArray;
458 if (err != noErr) {
459 jack_log("Input device does not have subdevices");
460 captureDeviceIDArray.push_back(captureDeviceID);
461 } else {
462 int num_devices = outSize / sizeof(AudioObjectID);
463 jack_log("Input device has %d subdevices", num_devices);
464 for (int i = 0; i < num_devices; i++) {
465 captureDeviceIDArray.push_back(sub_device[i]);
469 err = AudioDeviceGetProperty(playbackDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
470 vector<AudioDeviceID> playbackDeviceIDArray;
472 if (err != noErr) {
473 jack_log("Output device does not have subdevices");
474 playbackDeviceIDArray.push_back(playbackDeviceID);
475 } else {
476 int num_devices = outSize / sizeof(AudioObjectID);
477 jack_log("Output device has %d subdevices", num_devices);
478 for (int i = 0; i < num_devices; i++) {
479 playbackDeviceIDArray.push_back(sub_device[i]);
483 return CreateAggregateDeviceAux(captureDeviceIDArray, playbackDeviceIDArray, samplerate, outAggregateDevice);
486 OSStatus JackCoreAudioDriver::CreateAggregateDeviceAux(vector<AudioDeviceID> captureDeviceID, vector<AudioDeviceID> playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
488 OSStatus osErr = noErr;
489 UInt32 outSize;
490 Boolean outWritable;
492 // Prepare sub-devices for clock drift compensation
493 // Workaround for bug in the HAL : until 10.6.2
494 AudioObjectPropertyAddress theAddressOwned = { kAudioObjectPropertyOwnedObjects, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
495 AudioObjectPropertyAddress theAddressDrift = { kAudioSubDevicePropertyDriftCompensation, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
496 UInt32 theQualifierDataSize = sizeof(AudioObjectID);
497 AudioClassID inClass = kAudioSubDeviceClassID;
498 void* theQualifierData = &inClass;
499 UInt32 subDevicesNum = 0;
501 //---------------------------------------------------------------------------
502 // Setup SR of both devices otherwise creating AD may fail...
503 //---------------------------------------------------------------------------
504 UInt32 keptclockdomain = 0;
505 UInt32 clockdomain = 0;
506 outSize = sizeof(UInt32);
507 bool need_clock_drift_compensation = false;
509 for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
510 if (SetupSampleRateAux(captureDeviceID[i], samplerate) < 0) {
511 jack_error("JackCoreAudioDriver::CreateAggregateDevice : cannot set SR of input device");
512 } else {
513 // Check clock domain
514 osErr = AudioDeviceGetProperty(captureDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
515 if (osErr != 0) {
516 jack_error("JackCoreAudioDriver::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
517 printError(osErr);
518 } else {
519 keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
520 jack_log("JackCoreAudioDriver::CreateAggregateDevice : input clockdomain = %d", clockdomain);
521 if (clockdomain != 0 && clockdomain != keptclockdomain) {
522 jack_error("JackCoreAudioDriver::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
523 need_clock_drift_compensation = true;
529 for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
530 if (SetupSampleRateAux(playbackDeviceID[i], samplerate) < 0) {
531 jack_error("JackCoreAudioDriver::CreateAggregateDevice : cannot set SR of output device");
532 } else {
533 // Check clock domain
534 osErr = AudioDeviceGetProperty(playbackDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
535 if (osErr != 0) {
536 jack_error("JackCoreAudioDriver::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
537 printError(osErr);
538 } else {
539 keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
540 jack_log("JackCoreAudioDriver::CreateAggregateDevice : output clockdomain = %d", clockdomain);
541 if (clockdomain != 0 && clockdomain != keptclockdomain) {
542 jack_error("JackCoreAudioDriver::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
543 need_clock_drift_compensation = true;
549 // If no valid clock domain was found, then assume we have to compensate...
550 if (keptclockdomain == 0) {
551 need_clock_drift_compensation = true;
554 //---------------------------------------------------------------------------
555 // Start to create a new aggregate by getting the base audio hardware plugin
556 //---------------------------------------------------------------------------
558 char device_name[256];
559 for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
560 GetDeviceNameFromID(captureDeviceID[i], device_name);
561 jack_info("Separated input = '%s' ", device_name);
564 for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
565 GetDeviceNameFromID(playbackDeviceID[i], device_name);
566 jack_info("Separated output = '%s' ", device_name);
569 osErr = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyPlugInForBundleID, &outSize, &outWritable);
570 if (osErr != noErr) {
571 jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioHardwareGetPropertyInfo kAudioHardwarePropertyPlugInForBundleID error");
572 printError(osErr);
573 return osErr;
576 AudioValueTranslation pluginAVT;
578 CFStringRef inBundleRef = CFSTR("com.apple.audio.CoreAudio");
580 pluginAVT.mInputData = &inBundleRef;
581 pluginAVT.mInputDataSize = sizeof(inBundleRef);
582 pluginAVT.mOutputData = &fPluginID;
583 pluginAVT.mOutputDataSize = sizeof(fPluginID);
585 osErr = AudioHardwareGetProperty(kAudioHardwarePropertyPlugInForBundleID, &outSize, &pluginAVT);
586 if (osErr != noErr) {
587 jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioHardwareGetProperty kAudioHardwarePropertyPlugInForBundleID error");
588 printError(osErr);
589 return osErr;
592 //-------------------------------------------------
593 // Create a CFDictionary for our aggregate device
594 //-------------------------------------------------
596 CFMutableDictionaryRef aggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
598 CFStringRef AggregateDeviceNameRef = CFSTR("JackDuplex");
599 CFStringRef AggregateDeviceUIDRef = CFSTR("com.grame.JackDuplex");
601 // add the name of the device to the dictionary
602 CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceNameKey), AggregateDeviceNameRef);
604 // add our choice of UID for the aggregate device to the dictionary
605 CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceUIDKey), AggregateDeviceUIDRef);
607 // add a "private aggregate key" to the dictionary
608 int value = 1;
609 CFNumberRef AggregateDeviceNumberRef = CFNumberCreate(NULL, kCFNumberIntType, &value);
611 SInt32 system;
612 Gestalt(gestaltSystemVersion, &system);
614 jack_log("JackCoreAudioDriver::CreateAggregateDevice : system version = %x limit = %x", system, 0x00001054);
616 // Starting with 10.5.4 systems, the AD can be internal... (better)
617 if (system < 0x00001054) {
618 jack_log("JackCoreAudioDriver::CreateAggregateDevice : public aggregate device....");
619 } else {
620 jack_log("JackCoreAudioDriver::CreateAggregateDevice : private aggregate device....");
621 CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceIsPrivateKey), AggregateDeviceNumberRef);
624 // Prepare sub-devices for clock drift compensation
625 CFMutableArrayRef subDevicesArrayClock = NULL;
628 if (fClockDriftCompensate) {
629 if (need_clock_drift_compensation) {
630 jack_info("Clock drift compensation activated...");
631 subDevicesArrayClock = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
633 for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
634 CFStringRef UID = GetDeviceName(captureDeviceID[i]);
635 if (UID) {
636 CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
637 CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
638 CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
639 //CFRelease(UID);
640 CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
644 for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
645 CFStringRef UID = GetDeviceName(playbackDeviceID[i]);
646 if (UID) {
647 CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
648 CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
649 CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
650 //CFRelease(UID);
651 CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
655 // add sub-device clock array for the aggregate device to the dictionary
656 CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceSubDeviceListKey), subDevicesArrayClock);
657 } else {
658 jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
663 //-------------------------------------------------
664 // Create a CFMutableArray for our sub-device list
665 //-------------------------------------------------
667 // we need to append the UID for each device to a CFMutableArray, so create one here
668 CFMutableArrayRef subDevicesArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
670 vector<CFStringRef> captureDeviceUID;
671 for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
672 CFStringRef ref = GetDeviceName(captureDeviceID[i]);
673 if (ref == NULL)
674 return -1;
675 captureDeviceUID.push_back(ref);
676 // input sub-devices in this example, so append the sub-device's UID to the CFArray
677 CFArrayAppendValue(subDevicesArray, ref);
680 vector<CFStringRef> playbackDeviceUID;
681 for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
682 CFStringRef ref = GetDeviceName(playbackDeviceID[i]);
683 if (ref == NULL)
684 return -1;
685 playbackDeviceUID.push_back(ref);
686 // output sub-devices in this example, so append the sub-device's UID to the CFArray
687 CFArrayAppendValue(subDevicesArray, ref);
690 //-----------------------------------------------------------------------
691 // Feed the dictionary to the plugin, to create a blank aggregate device
692 //-----------------------------------------------------------------------
694 AudioObjectPropertyAddress pluginAOPA;
695 pluginAOPA.mSelector = kAudioPlugInCreateAggregateDevice;
696 pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
697 pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
698 UInt32 outDataSize;
700 osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
701 if (osErr != noErr) {
702 jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectGetPropertyDataSize error");
703 printError(osErr);
704 goto error;
707 osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, sizeof(aggDeviceDict), &aggDeviceDict, &outDataSize, outAggregateDevice);
708 if (osErr != noErr) {
709 jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectGetPropertyData error");
710 printError(osErr);
711 goto error;
714 // pause for a bit to make sure that everything completed correctly
715 // this is to work around a bug in the HAL where a new aggregate device seems to disappear briefly after it is created
716 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
718 //-------------------------
719 // Set the sub-device list
720 //-------------------------
722 pluginAOPA.mSelector = kAudioAggregateDevicePropertyFullSubDeviceList;
723 pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
724 pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
725 outDataSize = sizeof(CFMutableArrayRef);
726 osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &subDevicesArray);
727 if (osErr != noErr) {
728 jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectSetPropertyData for sub-device list error");
729 printError(osErr);
730 goto error;
733 // pause again to give the changes time to take effect
734 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
736 //-----------------------
737 // Set the master device
738 //-----------------------
740 // set the master device manually (this is the device which will act as the master clock for the aggregate device)
741 // pass in the UID of the device you want to use
742 pluginAOPA.mSelector = kAudioAggregateDevicePropertyMasterSubDevice;
743 pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
744 pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
745 outDataSize = sizeof(CFStringRef);
746 osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &captureDeviceUID[0]); // First apture is master...
747 if (osErr != noErr) {
748 jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectSetPropertyData for master device error");
749 printError(osErr);
750 goto error;
753 // pause again to give the changes time to take effect
754 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
756 // Prepare sub-devices for clock drift compensation
757 // Workaround for bug in the HAL : until 10.6.2
759 if (fClockDriftCompensate) {
760 if (need_clock_drift_compensation) {
761 jack_info("Clock drift compensation activated...");
763 // Get the property data size
764 osErr = AudioObjectGetPropertyDataSize(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize);
765 if (osErr != noErr) {
766 jack_error("JackCoreAudioDriver::CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
767 printError(osErr);
770 // Calculate the number of object IDs
771 subDevicesNum = outSize / sizeof(AudioObjectID);
772 jack_info("JackCoreAudioDriver::CreateAggregateDevice clock drift compensation, number of sub-devices = %d", subDevicesNum);
773 AudioObjectID subDevices[subDevicesNum];
774 outSize = sizeof(subDevices);
776 osErr = AudioObjectGetPropertyData(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize, subDevices);
777 if (osErr != noErr) {
778 jack_error("JackCoreAudioDriver::CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
779 printError(osErr);
782 // Set kAudioSubDevicePropertyDriftCompensation property...
783 for (UInt32 index = 0; index < subDevicesNum; ++index) {
784 UInt32 theDriftCompensationValue = 1;
785 osErr = AudioObjectSetPropertyData(subDevices[index], &theAddressDrift, 0, NULL, sizeof(UInt32), &theDriftCompensationValue);
786 if (osErr != noErr) {
787 jack_error("JackCoreAudioDriver::CreateAggregateDevice kAudioSubDevicePropertyDriftCompensation error");
788 printError(osErr);
791 } else {
792 jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
796 // pause again to give the changes time to take effect
797 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
799 //----------
800 // Clean up
801 //----------
803 // release the private AD key
804 CFRelease(AggregateDeviceNumberRef);
806 // release the CF objects we have created - we don't need them any more
807 CFRelease(aggDeviceDict);
808 CFRelease(subDevicesArray);
810 if (subDevicesArrayClock)
811 CFRelease(subDevicesArrayClock);
813 // release the device UID
814 for (UInt32 i = 0; i < captureDeviceUID.size(); i++) {
815 CFRelease(captureDeviceUID[i]);
818 for (UInt32 i = 0; i < playbackDeviceUID.size(); i++) {
819 CFRelease(playbackDeviceUID[i]);
822 jack_log("New aggregate device %ld", *outAggregateDevice);
823 return noErr;
825 error:
826 DestroyAggregateDevice();
827 return -1;
830 int JackCoreAudioDriver::SetupDevices(const char* capture_driver_uid,
831 const char* playback_driver_uid,
832 char* capture_driver_name,
833 char* playback_driver_name,
834 jack_nframes_t samplerate)
836 capture_driver_name[0] = 0;
837 playback_driver_name[0] = 0;
839 // Duplex
840 if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
841 jack_log("JackCoreAudioDriver::Open duplex");
843 // Same device for capture and playback...
844 if (strcmp(capture_driver_uid, playback_driver_uid) == 0) {
846 if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
847 jack_log("Will take default in/out");
848 if (GetDefaultDevice(&fDeviceID) != noErr) {
849 jack_error("Cannot open default device");
850 return -1;
853 if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
854 jack_error("Cannot get device name from device ID");
855 return -1;
858 } else {
860 // Creates aggregate device
861 AudioDeviceID captureID, playbackID;
863 if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
864 jack_log("Will take default input");
865 if (GetDefaultInputDevice(&captureID) != noErr) {
866 jack_error("Cannot open default device");
867 return -1;
871 if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
872 jack_log("Will take default output");
873 if (GetDefaultOutputDevice(&playbackID) != noErr) {
874 jack_error("Cannot open default device");
875 return -1;
879 if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr)
880 return -1;
883 // Capture only
884 } else if (strcmp(capture_driver_uid, "") != 0) {
885 jack_log("JackCoreAudioDriver::Open capture only");
886 if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
887 jack_log("Will take default input");
888 if (GetDefaultInputDevice(&fDeviceID) != noErr) {
889 jack_error("Cannot open default device");
890 return -1;
893 if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
894 jack_error("Cannot get device name from device ID");
895 return -1;
898 // Playback only
899 } else if (strcmp(playback_driver_uid, "") != 0) {
900 jack_log("JackCoreAudioDriver::Open playback only");
901 if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
902 jack_log("Will take default output");
903 if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
904 jack_error("Cannot open default device");
905 return -1;
908 if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
909 jack_error("Cannot get device name from device ID");
910 return -1;
913 // Use default driver in duplex mode
914 } else {
915 jack_log("JackCoreAudioDriver::Open default driver");
916 if (GetDefaultDevice(&fDeviceID) != noErr) {
917 jack_error("Cannot open default device");
918 return -1;
920 if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
921 jack_error("Cannot get device name from device ID");
922 return -1;
926 if (fHogged) {
927 if (TakeHog()) {
928 jack_info("Device = %ld has been hogged", fDeviceID);
929 } else {
930 jack_error("Cannot hog device = %ld", fDeviceID);
934 return 0;
938 Return the max possible input channels in in_nChannels and output channels in out_nChannels.
940 int JackCoreAudioDriver::SetupChannels(bool capturing, bool playing, int& inchannels, int& outchannels, int& in_nChannels, int& out_nChannels, bool strict)
942 OSStatus err = noErr;
944 if (capturing) {
945 err = GetTotalChannels(fDeviceID, in_nChannels, true);
946 if (err != noErr) {
947 jack_error("Cannot get input channel number");
948 printError(err);
949 return -1;
950 } else {
951 jack_log("Max input channels : %d", in_nChannels);
955 if (playing) {
956 err = GetTotalChannels(fDeviceID, out_nChannels, false);
957 if (err != noErr) {
958 jack_error("Cannot get output channel number");
959 printError(err);
960 return -1;
961 } else {
962 jack_log("Max output channels : %d", out_nChannels);
966 if (inchannels > in_nChannels) {
967 jack_error("This device hasn't required input channels inchannels = %d in_nChannels = %d", inchannels, in_nChannels);
968 if (strict)
969 return -1;
972 if (outchannels > out_nChannels) {
973 jack_error("This device hasn't required output channels outchannels = %d out_nChannels = %d", outchannels, out_nChannels);
974 if (strict)
975 return -1;
978 if (inchannels == -1) {
979 jack_log("Setup max in channels = %d", in_nChannels);
980 inchannels = in_nChannels;
983 if (outchannels == -1) {
984 jack_log("Setup max out channels = %d", out_nChannels);
985 outchannels = out_nChannels;
988 return 0;
991 int JackCoreAudioDriver::SetupBufferSize(jack_nframes_t buffer_size)
993 // Setting buffer size
994 UInt32 outSize = sizeof(UInt32);
995 OSStatus err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
996 if (err != noErr) {
997 jack_error("Cannot set buffer size %ld", buffer_size);
998 printError(err);
999 return -1;
1002 return 0;
1005 int JackCoreAudioDriver::SetupSampleRate(jack_nframes_t samplerate)
1007 return SetupSampleRateAux(fDeviceID, samplerate);
1010 int JackCoreAudioDriver::SetupSampleRateAux(AudioDeviceID inDevice, jack_nframes_t samplerate)
1012 OSStatus err = noErr;
1013 UInt32 outSize;
1014 Float64 sampleRate;
1016 // Get sample rate
1017 outSize = sizeof(Float64);
1018 err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
1019 if (err != noErr) {
1020 jack_error("Cannot get current sample rate");
1021 printError(err);
1022 return -1;
1025 // If needed, set new sample rate
1026 if (samplerate != (jack_nframes_t)sampleRate) {
1027 sampleRate = (Float64)samplerate;
1029 // To get SR change notification
1030 err = AudioDeviceAddPropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback, this);
1031 if (err != noErr) {
1032 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
1033 printError(err);
1034 return -1;
1036 err = AudioDeviceSetProperty(inDevice, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &sampleRate);
1037 if (err != noErr) {
1038 jack_error("Cannot set sample rate = %ld", samplerate);
1039 printError(err);
1040 return -1;
1043 // Waiting for SR change notification
1044 int count = 0;
1045 while (!fState && count++ < WAIT_COUNTER) {
1046 usleep(100000);
1047 jack_log("Wait count = %d", count);
1050 // Remove SR change notification
1051 AudioDeviceRemovePropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
1054 return 0;
1057 int JackCoreAudioDriver::OpenAUHAL(bool capturing,
1058 bool playing,
1059 int inchannels,
1060 int outchannels,
1061 int in_nChannels,
1062 int out_nChannels,
1063 jack_nframes_t buffer_size,
1064 jack_nframes_t samplerate)
1066 ComponentResult err1;
1067 UInt32 enableIO;
1068 AudioStreamBasicDescription srcFormat, dstFormat;
1069 AudioDeviceID currAudioDeviceID;
1070 UInt32 size;
1072 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);
1074 if (inchannels == 0 && outchannels == 0) {
1075 jack_error("No input and output channels...");
1076 return -1;
1079 // AUHAL
1080 ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
1081 Component HALOutput = FindNextComponent(NULL, &cd);
1083 err1 = OpenAComponent(HALOutput, &fAUHAL);
1084 if (err1 != noErr) {
1085 jack_error("Error calling OpenAComponent");
1086 printError(err1);
1087 goto error;
1090 err1 = AudioUnitInitialize(fAUHAL);
1091 if (err1 != noErr) {
1092 jack_error("Cannot initialize AUHAL unit");
1093 printError(err1);
1094 goto error;
1097 // Start I/O
1098 if (capturing && inchannels > 0) {
1099 enableIO = 1;
1100 jack_log("Setup AUHAL input on");
1101 } else {
1102 enableIO = 0;
1103 jack_log("Setup AUHAL input off");
1106 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
1107 if (err1 != noErr) {
1108 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
1109 printError(err1);
1110 goto error;
1113 if (playing && outchannels > 0) {
1114 enableIO = 1;
1115 jack_log("Setup AUHAL output on");
1116 } else {
1117 enableIO = 0;
1118 jack_log("Setup AUHAL output off");
1121 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
1122 if (err1 != noErr) {
1123 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
1124 printError(err1);
1125 goto error;
1128 size = sizeof(AudioDeviceID);
1129 err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
1130 if (err1 != noErr) {
1131 jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
1132 printError(err1);
1133 goto error;
1134 } else {
1135 jack_log("AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
1138 // Setup up choosen device, in both input and output cases
1139 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
1140 if (err1 != noErr) {
1141 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
1142 printError(err1);
1143 goto error;
1146 // Set buffer size
1147 if (capturing && inchannels > 0) {
1148 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*)&buffer_size, sizeof(UInt32));
1149 if (err1 != noErr) {
1150 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
1151 printError(err1);
1152 goto error;
1156 if (playing && outchannels > 0) {
1157 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*)&buffer_size, sizeof(UInt32));
1158 if (err1 != noErr) {
1159 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
1160 printError(err1);
1161 goto error;
1165 // Setup channel map
1166 if (capturing && inchannels > 0 && inchannels < in_nChannels) {
1167 SInt32 chanArr[in_nChannels];
1168 for (int i = 0; i < in_nChannels; i++) {
1169 chanArr[i] = -1;
1171 for (int i = 0; i < inchannels; i++) {
1172 chanArr[i] = i;
1174 AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
1175 if (err1 != noErr) {
1176 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 1");
1177 printError(err1);
1178 goto error;
1182 if (playing && outchannels > 0 && outchannels < out_nChannels) {
1183 SInt32 chanArr[out_nChannels];
1184 for (int i = 0; i < out_nChannels; i++) {
1185 chanArr[i] = -1;
1187 for (int i = 0; i < outchannels; i++) {
1188 chanArr[i] = i;
1190 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
1191 if (err1 != noErr) {
1192 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 0");
1193 printError(err1);
1194 goto error;
1198 // Setup stream converters
1199 if (capturing && inchannels > 0) {
1201 size = sizeof(AudioStreamBasicDescription);
1202 err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &srcFormat, &size);
1203 if (err1 != noErr) {
1204 jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
1205 printError(err1);
1206 goto error;
1208 PrintStreamDesc(&srcFormat);
1210 jack_log("Setup AUHAL input stream converter SR = %ld", samplerate);
1211 srcFormat.mSampleRate = samplerate;
1212 srcFormat.mFormatID = kAudioFormatLinearPCM;
1213 srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
1214 srcFormat.mBytesPerPacket = sizeof(float);
1215 srcFormat.mFramesPerPacket = 1;
1216 srcFormat.mBytesPerFrame = sizeof(float);
1217 srcFormat.mChannelsPerFrame = inchannels;
1218 srcFormat.mBitsPerChannel = 32;
1219 PrintStreamDesc(&srcFormat);
1221 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &srcFormat, sizeof(AudioStreamBasicDescription));
1223 if (err1 != noErr) {
1224 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
1225 printError(err1);
1226 goto error;
1230 if (playing && outchannels > 0) {
1232 size = sizeof(AudioStreamBasicDescription);
1233 err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 1, &dstFormat, &size);
1234 if (err1 != noErr) {
1235 jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
1236 printError(err1);
1237 goto error;
1239 PrintStreamDesc(&dstFormat);
1241 jack_log("Setup AUHAL output stream converter SR = %ld", samplerate);
1242 dstFormat.mSampleRate = samplerate;
1243 dstFormat.mFormatID = kAudioFormatLinearPCM;
1244 dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
1245 dstFormat.mBytesPerPacket = sizeof(float);
1246 dstFormat.mFramesPerPacket = 1;
1247 dstFormat.mBytesPerFrame = sizeof(float);
1248 dstFormat.mChannelsPerFrame = outchannels;
1249 dstFormat.mBitsPerChannel = 32;
1250 PrintStreamDesc(&dstFormat);
1252 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &dstFormat, sizeof(AudioStreamBasicDescription));
1254 if (err1 != noErr) {
1255 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
1256 printError(err1);
1257 goto error;
1261 // Setup callbacks
1262 if (inchannels > 0 && outchannels == 0) {
1263 AURenderCallbackStruct output;
1264 output.inputProc = Render;
1265 output.inputProcRefCon = this;
1266 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
1267 if (err1 != noErr) {
1268 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
1269 printError(err1);
1270 goto error;
1272 } else {
1273 AURenderCallbackStruct output;
1274 output.inputProc = Render;
1275 output.inputProcRefCon = this;
1276 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
1277 if (err1 != noErr) {
1278 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
1279 printError(err1);
1280 goto error;
1284 return 0;
1286 error:
1287 CloseAUHAL();
1288 return -1;
1291 int JackCoreAudioDriver::SetupBuffers(int inchannels)
1293 // Prepare buffers
1294 fJackInputData = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
1295 fJackInputData->mNumberBuffers = inchannels;
1296 for (int i = 0; i < fCaptureChannels; i++) {
1297 fJackInputData->mBuffers[i].mNumberChannels = 1;
1298 fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(float);
1300 return 0;
1303 void JackCoreAudioDriver::DisposeBuffers()
1305 if (fJackInputData) {
1306 free(fJackInputData);
1307 fJackInputData = 0;
1311 void JackCoreAudioDriver::CloseAUHAL()
1313 AudioUnitUninitialize(fAUHAL);
1314 CloseComponent(fAUHAL);
1317 int JackCoreAudioDriver::AddListeners()
1319 OSStatus err = noErr;
1321 // Add listeners
1322 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback, this);
1323 if (err != noErr) {
1324 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDeviceProcessorOverload");
1325 printError(err);
1326 return -1;
1329 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback, this);
1330 if (err != noErr) {
1331 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioHardwarePropertyDevices");
1332 printError(err);
1333 return -1;
1336 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback, this);
1337 if (err != noErr) {
1338 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
1339 printError(err);
1340 return -1;
1343 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback, this);
1344 if (err != noErr) {
1345 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsRunning");
1346 printError(err);
1347 return -1;
1350 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
1351 if (err != noErr) {
1352 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
1353 printError(err);
1354 return -1;
1357 err = AudioDeviceAddPropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
1358 if (err != noErr) {
1359 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
1360 printError(err);
1361 return -1;
1364 if (!fEngineControl->fSyncMode && fIOUsage != 1.f) {
1365 UInt32 outSize = sizeof(float);
1366 err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyIOCycleUsage, outSize, &fIOUsage);
1367 if (err != noErr) {
1368 jack_error("Error calling AudioDeviceSetProperty kAudioDevicePropertyIOCycleUsage");
1369 printError(err);
1373 return 0;
1376 void JackCoreAudioDriver::RemoveListeners()
1378 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback);
1379 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback);
1380 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback);
1381 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback);
1382 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
1383 AudioDeviceRemovePropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
1386 int JackCoreAudioDriver::Open(jack_nframes_t buffer_size,
1387 jack_nframes_t samplerate,
1388 bool capturing,
1389 bool playing,
1390 int inchannels,
1391 int outchannels,
1392 bool monitor,
1393 const char* capture_driver_uid,
1394 const char* playback_driver_uid,
1395 jack_nframes_t capture_latency,
1396 jack_nframes_t playback_latency,
1397 int async_output_latency,
1398 int computation_grain,
1399 bool hogged,
1400 bool clock_drift)
1402 int in_nChannels = 0;
1403 int out_nChannels = 0;
1404 char capture_driver_name[256];
1405 char playback_driver_name[256];
1407 // Keep initial state
1408 fCapturing = capturing;
1409 fPlaying = playing;
1410 fInChannels = inchannels;
1411 fOutChannels = outchannels;
1412 fMonitor = monitor;
1413 strcpy(fCaptureUID, capture_driver_uid);
1414 strcpy(fPlaybackUID, playback_driver_uid);
1415 fCaptureLatency = capture_latency;
1416 fPlaybackLatency = playback_latency;
1417 fIOUsage = float(async_output_latency) / 100.f;
1418 fComputationGrain = float(computation_grain) / 100.f;
1419 fHogged = hogged;
1420 fClockDriftCompensate = clock_drift;
1422 SInt32 major;
1423 SInt32 minor;
1424 Gestalt(gestaltSystemVersionMajor, &major);
1425 Gestalt(gestaltSystemVersionMinor, &minor);
1427 // Starting with 10.6 systems, the HAL notification thread is created internally
1428 if (major == 10 && minor >= 6) {
1429 CFRunLoopRef theRunLoop = NULL;
1430 AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1431 OSStatus osErr = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
1432 if (osErr != noErr) {
1433 jack_error("JackCoreAudioDriver::Open kAudioHardwarePropertyRunLoop error");
1434 printError(osErr);
1438 if (SetupDevices(capture_driver_uid, playback_driver_uid, capture_driver_name, playback_driver_name, samplerate) < 0)
1439 goto error;
1441 // Generic JackAudioDriver Open
1442 if (JackAudioDriver::Open(buffer_size, samplerate, capturing, playing, inchannels, outchannels, monitor, capture_driver_name, playback_driver_name, capture_latency, playback_latency) != 0)
1443 goto error;
1445 if (SetupChannels(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, true) < 0)
1446 goto error;
1448 if (SetupBufferSize(buffer_size) < 0)
1449 goto error;
1451 if (SetupSampleRate(samplerate) < 0)
1452 goto error;
1454 if (OpenAUHAL(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, buffer_size, samplerate) < 0)
1455 goto error;
1457 if (capturing && inchannels > 0)
1458 if (SetupBuffers(inchannels) < 0)
1459 goto error;
1461 if (AddListeners() < 0)
1462 goto error;
1464 // Core driver may have changed the in/out values
1465 fCaptureChannels = inchannels;
1466 fPlaybackChannels = outchannels;
1467 return noErr;
1469 error:
1470 Close();
1471 return -1;
1474 int JackCoreAudioDriver::Close()
1476 jack_log("JackCoreAudioDriver::Close");
1477 Stop();
1478 JackAudioDriver::Close();
1479 RemoveListeners();
1480 DisposeBuffers();
1481 CloseAUHAL();
1482 DestroyAggregateDevice();
1483 return 0;
1486 int JackCoreAudioDriver::Attach()
1488 OSStatus err;
1489 JackPort* port;
1490 jack_port_id_t port_index;
1491 UInt32 size;
1492 Boolean isWritable;
1493 char channel_name[64];
1494 char name[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
1495 char alias[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
1496 unsigned long port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
1498 jack_log("JackCoreAudioDriver::Attach fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
1500 for (int i = 0; i < fCaptureChannels; i++) {
1502 err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, &isWritable);
1503 if (err != noErr)
1504 jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error ");
1505 if (err == noErr && size > 0) {
1506 err = AudioDeviceGetProperty(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, channel_name);
1507 if (err != noErr)
1508 jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error ");
1509 snprintf(alias, sizeof(alias) - 1, "%s:%s:out_%s%u", fAliasName, fCaptureDriverName, channel_name, i + 1);
1510 } else {
1511 snprintf(alias, sizeof(alias) - 1, "%s:%s:out%u", fAliasName, fCaptureDriverName, i + 1);
1514 snprintf(name, sizeof(name) - 1, "%s:capture_%d", fClientControl.fName, i + 1);
1516 if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
1517 jack_error("Cannot register port for %s", name);
1518 return -1;
1521 size = sizeof(UInt32);
1522 UInt32 value1 = 0;
1523 UInt32 value2 = 0;
1524 err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertyLatency, &size, &value1);
1525 if (err != noErr)
1526 jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error ");
1527 err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertySafetyOffset, &size, &value2);
1528 if (err != noErr)
1529 jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error ");
1531 port = fGraphManager->GetPort(port_index);
1532 port->SetAlias(alias);
1533 port->SetLatency(fEngineControl->fBufferSize + value1 + value2 + fCaptureLatency);
1534 fCapturePortList[i] = port_index;
1537 port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
1539 for (int i = 0; i < fPlaybackChannels; i++) {
1541 err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, &isWritable);
1542 if (err != noErr)
1543 jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error ");
1544 if (err == noErr && size > 0) {
1545 err = AudioDeviceGetProperty(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, channel_name);
1546 if (err != noErr)
1547 jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error ");
1548 snprintf(alias, sizeof(alias) - 1, "%s:%s:in_%s%u", fAliasName, fPlaybackDriverName, channel_name, i + 1);
1549 } else {
1550 snprintf(alias, sizeof(alias) - 1, "%s:%s:in%u", fAliasName, fPlaybackDriverName, i + 1);
1553 snprintf(name, sizeof(name) - 1, "%s:playback_%d", fClientControl.fName, i + 1);
1555 if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
1556 jack_error("Cannot register port for %s", name);
1557 return -1;
1560 size = sizeof(UInt32);
1561 UInt32 value1 = 0;
1562 UInt32 value2 = 0;
1563 err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertyLatency, &size, &value1);
1564 if (err != noErr)
1565 jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error ");
1566 err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertySafetyOffset, &size, &value2);
1567 if (err != noErr)
1568 jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error ");
1570 port = fGraphManager->GetPort(port_index);
1571 port->SetAlias(alias);
1572 // Add more latency if "async" mode is used...
1573 port->SetLatency(fEngineControl->fBufferSize + ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize * fIOUsage) + value1 + value2 + fPlaybackLatency);
1574 fPlaybackPortList[i] = port_index;
1576 // Monitor ports
1577 if (fWithMonitorPorts) {
1578 jack_log("Create monitor port ");
1579 snprintf(name, sizeof(name) - 1, "%s:monitor_%u", fClientControl.fName, i + 1);
1580 if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, fEngineControl->fBufferSize)) == NO_PORT) {
1581 jack_error("Cannot register monitor port for %s", name);
1582 return -1;
1583 } else {
1584 port = fGraphManager->GetPort(port_index);
1585 port->SetAlias(alias);
1586 port->SetLatency(fEngineControl->fBufferSize);
1587 fMonitorPortList[i] = port_index;
1592 // Input buffers do no change : prepare them only once
1593 for (int i = 0; i < fCaptureChannels; i++) {
1594 fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
1597 return 0;
1600 int JackCoreAudioDriver::Start()
1602 jack_log("JackCoreAudioDriver::Start");
1603 JackAudioDriver::Start();
1605 #ifdef MAC_OS_X_VERSION_10_5
1606 OSStatus err = AudioDeviceCreateIOProcID(fDeviceID, MeasureCallback, this, &fMesureCallbackID);
1607 #else
1608 OSStatus err = AudioDeviceAddIOProc(fDeviceID, MeasureCallback, this);
1609 #endif
1611 OSStatus err = AudioDeviceAddIOProc(fDeviceID, MeasureCallback, this);
1613 if (err != noErr)
1614 return -1;
1616 err = AudioOutputUnitStart(fAUHAL);
1617 if (err != noErr)
1618 return -1;
1620 if ((err = AudioDeviceStart(fDeviceID, MeasureCallback)) != noErr) {
1621 jack_error("Cannot start MeasureCallback");
1622 printError(err);
1623 return -1;
1626 // Waiting for Measure callback to be called (= driver has started)
1627 fState = false;
1628 int count = 0;
1629 while (!fState && count++ < WAIT_COUNTER) {
1630 usleep(100000);
1631 jack_log("JackCoreAudioDriver::Start wait count = %d", count);
1634 if (count < WAIT_COUNTER) {
1635 jack_info("CoreAudio driver is running...");
1636 return 0;
1637 } else {
1638 jack_error("CoreAudio driver cannot start...");
1639 return -1;
1643 int JackCoreAudioDriver::Stop()
1645 jack_log("JackCoreAudioDriver::Stop");
1646 AudioDeviceStop(fDeviceID, MeasureCallback);
1648 #ifdef MAC_OS_X_VERSION_10_5
1649 AudioDeviceDestroyIOProcID(fDeviceID, fMesureCallbackID);
1650 #else
1651 AudioDeviceRemoveIOProc(fDeviceID, MeasureCallback);
1652 #endif
1654 AudioDeviceRemoveIOProc(fDeviceID, MeasureCallback);
1655 return (AudioOutputUnitStop(fAUHAL) == noErr) ? 0 : -1;
1658 int JackCoreAudioDriver::SetBufferSize(jack_nframes_t buffer_size)
1660 OSStatus err;
1661 UInt32 outSize = sizeof(UInt32);
1663 err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
1664 if (err != noErr) {
1665 jack_error("Cannot set buffer size %ld", buffer_size);
1666 printError(err);
1667 return -1;
1670 JackAudioDriver::SetBufferSize(buffer_size); // never fails
1672 // Input buffers do no change : prepare them only once
1673 for (int i = 0; i < fCaptureChannels; i++) {
1674 fJackInputData->mBuffers[i].mNumberChannels = 1;
1675 fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(float);
1676 fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
1679 return 0;
1682 bool JackCoreAudioDriver::TakeHogAux(AudioDeviceID deviceID, bool isInput)
1684 pid_t hog_pid;
1685 OSStatus err;
1687 UInt32 propSize = sizeof(hog_pid);
1688 err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyHogMode, &propSize, &hog_pid);
1689 if (err) {
1690 jack_error("Cannot read hog state...");
1691 printError(err);
1694 if (hog_pid != getpid()) {
1695 hog_pid = getpid();
1696 err = AudioDeviceSetProperty(deviceID, 0, 0, isInput, kAudioDevicePropertyHogMode, propSize, &hog_pid);
1697 if (err != noErr) {
1698 jack_error("Can't hog device = %d because it's being hogged by another program", deviceID);
1699 return false;
1703 return true;
1706 bool JackCoreAudioDriver::TakeHog()
1708 OSStatus err = noErr;
1709 AudioObjectID sub_device[32];
1710 UInt32 outSize = sizeof(sub_device);
1711 err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
1713 if (err != noErr) {
1714 jack_log("Device does not have subdevices");
1715 return TakeHogAux(fDeviceID, true);
1716 } else {
1717 int num_devices = outSize / sizeof(AudioObjectID);
1718 jack_log("Device does has %d subdevices", num_devices);
1719 for (int i = 0; i < num_devices; i++) {
1720 if (!TakeHogAux(sub_device[i], true)) {
1721 return false;
1724 return true;
1728 bool JackCoreAudioDriver::IsAggregateDevice(AudioDeviceID device)
1730 UInt32 deviceType, outSize = sizeof(UInt32);
1731 OSStatus err = AudioDeviceGetProperty(device, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyTransportType, &outSize, &deviceType);
1733 if (err != noErr) {
1734 jack_log("JackCoreAudioDriver::IsAggregateDevice kAudioDevicePropertyTransportType error");
1735 return false;
1736 } else {
1737 return (deviceType == kAudioDeviceTransportTypeAggregate);
1742 } // end of namespace
1745 #ifdef __cplusplus
1746 extern "C"
1748 #endif
1750 SERVER_EXPORT jack_driver_desc_t* driver_get_descriptor()
1752 jack_driver_desc_t *desc;
1753 unsigned int i;
1754 desc = (jack_driver_desc_t*)calloc(1, sizeof(jack_driver_desc_t));
1756 strcpy(desc->name, "coreaudio"); // size MUST be less then JACK_DRIVER_NAME_MAX + 1
1757 strcpy(desc->desc, "Apple CoreAudio API based audio backend"); // size MUST be less then JACK_DRIVER_PARAM_DESC + 1
1759 desc->nparams = 17;
1760 desc->params = (jack_driver_param_desc_t*)calloc(desc->nparams, sizeof(jack_driver_param_desc_t));
1762 i = 0;
1763 strcpy(desc->params[i].name, "channels");
1764 desc->params[i].character = 'c';
1765 desc->params[i].type = JackDriverParamInt;
1766 desc->params[i].value.ui = -1;
1767 strcpy(desc->params[i].short_desc, "Maximum number of channels");
1768 strcpy(desc->params[i].long_desc, "Maximum number of channels. If -1, max possible number of channels will be used");
1770 i++;
1771 strcpy(desc->params[i].name, "inchannels");
1772 desc->params[i].character = 'i';
1773 desc->params[i].type = JackDriverParamInt;
1774 desc->params[i].value.ui = -1;
1775 strcpy(desc->params[i].short_desc, "Maximum number of input channels");
1776 strcpy(desc->params[i].long_desc, "Maximum number of input channels. If -1, max possible number of input channels will be used");
1778 i++;
1779 strcpy(desc->params[i].name, "outchannels");
1780 desc->params[i].character = 'o';
1781 desc->params[i].type = JackDriverParamInt;
1782 desc->params[i].value.ui = -1;
1783 strcpy(desc->params[i].short_desc, "Maximum number of output channels");
1784 strcpy(desc->params[i].long_desc, "Maximum number of output channels. If -1, max possible number of output channels will be used");
1786 i++;
1787 strcpy(desc->params[i].name, "capture");
1788 desc->params[i].character = 'C';
1789 desc->params[i].type = JackDriverParamString;
1790 strcpy(desc->params[i].short_desc, "Input CoreAudio device name");
1791 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1793 i++;
1794 strcpy(desc->params[i].name, "playback");
1795 desc->params[i].character = 'P';
1796 desc->params[i].type = JackDriverParamString;
1797 strcpy(desc->params[i].short_desc, "Output CoreAudio device name");
1798 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1800 i++;
1801 strcpy (desc->params[i].name, "monitor");
1802 desc->params[i].character = 'm';
1803 desc->params[i].type = JackDriverParamBool;
1804 desc->params[i].value.i = 0;
1805 strcpy(desc->params[i].short_desc, "Provide monitor ports for the output");
1806 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1808 i++;
1809 strcpy(desc->params[i].name, "duplex");
1810 desc->params[i].character = 'D';
1811 desc->params[i].type = JackDriverParamBool;
1812 desc->params[i].value.i = TRUE;
1813 strcpy(desc->params[i].short_desc, "Provide both capture and playback ports");
1814 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1816 i++;
1817 strcpy(desc->params[i].name, "rate");
1818 desc->params[i].character = 'r';
1819 desc->params[i].type = JackDriverParamUInt;
1820 desc->params[i].value.ui = 44100U;
1821 strcpy(desc->params[i].short_desc, "Sample rate");
1822 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1824 i++;
1825 strcpy(desc->params[i].name, "period");
1826 desc->params[i].character = 'p';
1827 desc->params[i].type = JackDriverParamUInt;
1828 desc->params[i].value.ui = 128U;
1829 strcpy(desc->params[i].short_desc, "Frames per period");
1830 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1832 i++;
1833 strcpy(desc->params[i].name, "device");
1834 desc->params[i].character = 'd';
1835 desc->params[i].type = JackDriverParamString;
1836 strcpy(desc->params[i].short_desc, "CoreAudio device name");
1837 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1839 i++;
1840 strcpy(desc->params[i].name, "input-latency");
1841 desc->params[i].character = 'I';
1842 desc->params[i].type = JackDriverParamUInt;
1843 desc->params[i].value.i = 0;
1844 strcpy(desc->params[i].short_desc, "Extra input latency (frames)");
1845 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1847 i++;
1848 strcpy(desc->params[i].name, "output-latency");
1849 desc->params[i].character = 'O';
1850 desc->params[i].type = JackDriverParamUInt;
1851 desc->params[i].value.i = 0;
1852 strcpy(desc->params[i].short_desc, "Extra output latency (frames)");
1853 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1855 i++;
1856 strcpy(desc->params[i].name, "list-devices");
1857 desc->params[i].character = 'l';
1858 desc->params[i].type = JackDriverParamBool;
1859 desc->params[i].value.i = FALSE;
1860 strcpy(desc->params[i].short_desc, "Display available CoreAudio devices");
1861 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1863 i++;
1864 strcpy(desc->params[i].name, "hog");
1865 desc->params[i].character = 'H';
1866 desc->params[i].type = JackDriverParamBool;
1867 desc->params[i].value.i = FALSE;
1868 strcpy(desc->params[i].short_desc, "Take exclusive access of the audio device");
1869 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1871 i++;
1872 strcpy(desc->params[i].name, "async-latency");
1873 desc->params[i].character = 'L';
1874 desc->params[i].type = JackDriverParamUInt;
1875 desc->params[i].value.i = 100;
1876 strcpy(desc->params[i].short_desc, "Extra output latency in asynchronous mode (percent)");
1877 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1879 i++;
1880 strcpy(desc->params[i].name, "grain");
1881 desc->params[i].character = 'G';
1882 desc->params[i].type = JackDriverParamUInt;
1883 desc->params[i].value.i = 100;
1884 strcpy(desc->params[i].short_desc, "Computation grain in RT thread (percent)");
1885 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1887 i++;
1888 strcpy(desc->params[i].name, "clock-drift");
1889 desc->params[i].character = 's';
1890 desc->params[i].type = JackDriverParamBool;
1891 desc->params[i].value.i = FALSE;
1892 strcpy(desc->params[i].short_desc, "Clock drift compensation");
1893 strcpy(desc->params[i].long_desc, "Whether to compensate clock drift in dynamically created aggregate device");
1895 return desc;
1898 SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
1900 jack_nframes_t srate = 44100;
1901 jack_nframes_t frames_per_interrupt = 128;
1902 bool capture = false;
1903 bool playback = false;
1904 int chan_in = -1; // Default: if not explicitely set, then max possible will be used...
1905 int chan_out = -1; // Default: ifĂ  not explicitely set, then max possible will be used...
1906 bool monitor = false;
1907 const char* capture_driver_uid = "";
1908 const char* playback_driver_uid = "";
1909 const JSList *node;
1910 const jack_driver_param_t *param;
1911 jack_nframes_t systemic_input_latency = 0;
1912 jack_nframes_t systemic_output_latency = 0;
1913 int async_output_latency = 100;
1914 int computation_grain = -1;
1915 bool hogged = false;
1916 bool clock_drift = false;
1918 for (node = params; node; node = jack_slist_next(node)) {
1919 param = (const jack_driver_param_t *) node->data;
1921 switch (param->character) {
1923 case 'd':
1924 capture_driver_uid = strdup(param->value.str);
1925 playback_driver_uid = strdup(param->value.str);
1926 break;
1928 case 'D':
1929 capture = true;
1930 playback = true;
1931 break;
1933 case 'c':
1934 chan_in = chan_out = (int)param->value.ui;
1935 break;
1937 case 'i':
1938 chan_in = (int)param->value.ui;
1939 break;
1941 case 'o':
1942 chan_out = (int)param->value.ui;
1943 break;
1945 case 'C':
1946 capture = true;
1947 if (strcmp(param->value.str, "none") != 0) {
1948 capture_driver_uid = strdup(param->value.str);
1950 break;
1952 case 'P':
1953 playback = true;
1954 if (strcmp(param->value.str, "none") != 0) {
1955 playback_driver_uid = strdup(param->value.str);
1957 break;
1959 case 'm':
1960 monitor = param->value.i;
1961 break;
1963 case 'r':
1964 srate = param->value.ui;
1965 break;
1967 case 'p':
1968 frames_per_interrupt = (unsigned int)param->value.ui;
1969 break;
1971 case 'I':
1972 systemic_input_latency = param->value.ui;
1973 break;
1975 case 'O':
1976 systemic_output_latency = param->value.ui;
1977 break;
1979 case 'l':
1980 Jack::DisplayDeviceNames();
1981 break;
1983 case 'H':
1984 hogged = true;
1985 break;
1987 case 'L':
1988 async_output_latency = param->value.ui;
1989 break;
1991 case 'G':
1992 computation_grain = param->value.ui;
1993 break;
1995 case 's':
1996 clock_drift = true;
1997 break;
2001 /* duplex is the default */
2002 if (!capture && !playback) {
2003 capture = true;
2004 playback = true;
2007 Jack::JackCoreAudioDriver* driver = new Jack::JackCoreAudioDriver("system", "coreaudio", engine, table);
2008 if (driver->Open(frames_per_interrupt, srate, capture, playback, chan_in, chan_out, monitor, capture_driver_uid,
2009 playback_driver_uid, systemic_input_latency, systemic_output_latency, async_output_latency, computation_grain, hogged, clock_drift) == 0) {
2010 return driver;
2011 } else {
2012 delete driver;
2013 return NULL;
2017 #ifdef __cplusplus
2019 #endif