In JackCoreAudio driver, (possibly) clock drift compensation when needed in aggregate...
[jack2.git] / macosx / coreaudio / JackCoreAudioDriver.cpp
blob6e23ceca1f92d655f3203c8bb546a4870e278be6
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)
415 JackCoreAudioDriver::~JackCoreAudioDriver()
418 OSStatus JackCoreAudioDriver::DestroyAggregateDevice()
420 OSStatus osErr = noErr;
421 AudioObjectPropertyAddress pluginAOPA;
422 pluginAOPA.mSelector = kAudioPlugInDestroyAggregateDevice;
423 pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
424 pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
425 UInt32 outDataSize;
427 if (fPluginID > 0) {
429 osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
430 if (osErr != noErr) {
431 jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyDataSize error");
432 printError(osErr);
433 return osErr;
436 osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, 0, NULL, &outDataSize, &fDeviceID);
437 if (osErr != noErr) {
438 jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyData error");
439 printError(osErr);
440 return osErr;
445 return noErr;
448 OSStatus JackCoreAudioDriver::CreateAggregateDevice(AudioDeviceID captureDeviceID, AudioDeviceID playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
450 OSStatus err = noErr;
451 AudioObjectID sub_device[32];
452 UInt32 outSize = sizeof(sub_device);
454 err = AudioDeviceGetProperty(captureDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
455 vector<AudioDeviceID> captureDeviceIDArray;
457 if (err != noErr) {
458 jack_log("Input device does not have subdevices");
459 captureDeviceIDArray.push_back(captureDeviceID);
460 } else {
461 int num_devices = outSize / sizeof(AudioObjectID);
462 jack_log("Input device has %d subdevices", num_devices);
463 for (int i = 0; i < num_devices; i++) {
464 captureDeviceIDArray.push_back(sub_device[i]);
468 err = AudioDeviceGetProperty(playbackDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
469 vector<AudioDeviceID> playbackDeviceIDArray;
471 if (err != noErr) {
472 jack_log("Output device does not have subdevices");
473 playbackDeviceIDArray.push_back(playbackDeviceID);
474 } else {
475 int num_devices = outSize / sizeof(AudioObjectID);
476 jack_log("Output device has %d subdevices", num_devices);
477 for (int i = 0; i < num_devices; i++) {
478 playbackDeviceIDArray.push_back(sub_device[i]);
482 return CreateAggregateDeviceAux(captureDeviceIDArray, playbackDeviceIDArray, samplerate, outAggregateDevice);
485 OSStatus JackCoreAudioDriver::CreateAggregateDeviceAux(vector<AudioDeviceID> captureDeviceID, vector<AudioDeviceID> playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
487 OSStatus osErr = noErr;
488 UInt32 outSize;
489 Boolean outWritable;
491 //---------------------------------------------------------------------------
492 // Setup SR of both devices otherwise creating AD may fail...
493 //---------------------------------------------------------------------------
494 UInt32 keptclockdomain = 0;
495 UInt32 clockdomain = 0;
496 outSize = sizeof(UInt32);
497 bool clock_drift = false;
499 for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
500 if (SetupSampleRateAux(captureDeviceID[i], samplerate) < 0) {
501 jack_error("JackCoreAudioDriver::CreateAggregateDevice : cannot set SR of input device");
502 } else {
503 // Check clock domain
504 osErr = AudioDeviceGetProperty(captureDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
505 if (osErr != 0) {
506 jack_error("JackCoreAudioDriver::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
507 printError(osErr);
508 } else {
509 keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
510 jack_log("JackCoreAudioDriver::CreateAggregateDevice : input clockdomain = %d", clockdomain);
511 if (clockdomain != 0 && clockdomain != keptclockdomain) {
512 jack_error("JackCoreAudioDriver::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
513 clock_drift = true;
519 for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
520 if (SetupSampleRateAux(playbackDeviceID[i], samplerate) < 0) {
521 jack_error("JackCoreAudioDriver::CreateAggregateDevice : cannot set SR of output device");
522 } else {
523 // Check clock domain
524 osErr = AudioDeviceGetProperty(playbackDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
525 if (osErr != 0) {
526 jack_error("JackCoreAudioDriver::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
527 printError(osErr);
528 } else {
529 keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
530 jack_log("JackCoreAudioDriver::CreateAggregateDevice : output clockdomain = %d", clockdomain);
531 if (clockdomain != 0 && clockdomain != keptclockdomain) {
532 jack_error("JackCoreAudioDriver::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
533 clock_drift = true;
539 //---------------------------------------------------------------------------
540 // Start to create a new aggregate by getting the base audio hardware plugin
541 //---------------------------------------------------------------------------
543 char device_name[256];
544 for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
545 GetDeviceNameFromID(captureDeviceID[i], device_name);
546 jack_info("Separated input = '%s' ", device_name);
549 for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
550 GetDeviceNameFromID(playbackDeviceID[i], device_name);
551 jack_info("Separated output = '%s' ", device_name);
554 osErr = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyPlugInForBundleID, &outSize, &outWritable);
555 if (osErr != noErr) {
556 jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioHardwareGetPropertyInfo kAudioHardwarePropertyPlugInForBundleID error");
557 printError(osErr);
558 return osErr;
561 AudioValueTranslation pluginAVT;
563 CFStringRef inBundleRef = CFSTR("com.apple.audio.CoreAudio");
565 pluginAVT.mInputData = &inBundleRef;
566 pluginAVT.mInputDataSize = sizeof(inBundleRef);
567 pluginAVT.mOutputData = &fPluginID;
568 pluginAVT.mOutputDataSize = sizeof(fPluginID);
570 osErr = AudioHardwareGetProperty(kAudioHardwarePropertyPlugInForBundleID, &outSize, &pluginAVT);
571 if (osErr != noErr) {
572 jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioHardwareGetProperty kAudioHardwarePropertyPlugInForBundleID error");
573 printError(osErr);
574 return osErr;
577 //-------------------------------------------------
578 // Create a CFDictionary for our aggregate device
579 //-------------------------------------------------
581 CFMutableDictionaryRef aggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
583 CFStringRef AggregateDeviceNameRef = CFSTR("JackDuplex");
584 CFStringRef AggregateDeviceUIDRef = CFSTR("com.grame.JackDuplex");
586 // add the name of the device to the dictionary
587 CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceNameKey), AggregateDeviceNameRef);
589 // add our choice of UID for the aggregate device to the dictionary
590 CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceUIDKey), AggregateDeviceUIDRef);
592 // add a "private aggregate key" to the dictionary
593 int value = 1;
594 CFNumberRef AggregateDeviceNumberRef = CFNumberCreate(NULL, kCFNumberIntType, &value);
596 SInt32 system;
597 Gestalt(gestaltSystemVersion, &system);
599 jack_log("JackCoreAudioDriver::CreateAggregateDevice : system version = %x limit = %x", system, 0x00001054);
601 // Starting with 10.5.4 systems, the AD can be internal... (better)
602 if (system < 0x00001054) {
603 jack_log("JackCoreAudioDriver::CreateAggregateDevice : public aggregate device....");
604 } else {
605 jack_log("JackCoreAudioDriver::CreateAggregateDevice : private aggregate device....");
606 CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceIsPrivateKey), AggregateDeviceNumberRef);
609 CFMutableDictionaryRef aggDeviceDict1 = NULL;
610 // Prepare sub-devices for clock drift compensation
611 if (clock_drift) {
612 if (fClockDriftCompensate) {
613 aggDeviceDict1 = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
614 for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
615 CFStringRef UI = GetDeviceName(captureDeviceID[i]);
616 if (UI) {
617 jack_info("JackCoreAudioDriver::CreateAggregateDevice : IN kAudioSubDeviceDriftCompensationKey");
618 CFDictionaryAddValue(aggDeviceDict1, CFSTR(kAudioSubDeviceUIDKey), UI);
619 CFDictionaryAddValue(aggDeviceDict1, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
620 CFRelease(UI);
623 for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
624 CFStringRef UI = GetDeviceName(playbackDeviceID[i]);
625 if (UI) {
626 jack_info("JackCoreAudioDriver::CreateAggregateDevice : OUT kAudioSubDeviceDriftCompensationKey");
627 CFDictionaryAddValue(aggDeviceDict1, CFSTR(kAudioSubDeviceUIDKey), UI);
628 CFDictionaryAddValue(aggDeviceDict1, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
629 CFRelease(UI);
632 } else {
633 jack_error("JackCoreAudioDriver::CreateAggregateDevice : devices do not share the same clock and -s is not used...");
634 return -1;
638 //-------------------------------------------------
639 // Create a CFMutableArray for our sub-device list
640 //-------------------------------------------------
642 // we need to append the UID for each device to a CFMutableArray, so create one here
643 CFMutableArrayRef subDevicesArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
645 vector<CFStringRef> captureDeviceUID;
646 for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
647 CFStringRef ref = GetDeviceName(captureDeviceID[i]);
648 if (ref == NULL)
649 return -1;
650 captureDeviceUID.push_back(ref);
651 // input sub-devices in this example, so append the sub-device's UID to the CFArray
652 CFArrayAppendValue(subDevicesArray, ref);
655 vector<CFStringRef> playbackDeviceUID;
656 for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
657 CFStringRef ref = GetDeviceName(playbackDeviceID[i]);
658 if (ref == NULL)
659 return -1;
660 playbackDeviceUID.push_back(ref);
661 // output sub-devices in this example, so append the sub-device's UID to the CFArray
662 CFArrayAppendValue(subDevicesArray, ref);
665 //-----------------------------------------------------------------------
666 // Feed the dictionary to the plugin, to create a blank aggregate device
667 //-----------------------------------------------------------------------
669 AudioObjectPropertyAddress pluginAOPA;
670 pluginAOPA.mSelector = kAudioPlugInCreateAggregateDevice;
671 pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
672 pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
673 UInt32 outDataSize;
675 osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
676 if (osErr != noErr) {
677 jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectGetPropertyDataSize error");
678 printError(osErr);
679 goto error;
682 osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, sizeof(aggDeviceDict), &aggDeviceDict, &outDataSize, outAggregateDevice);
683 if (osErr != noErr) {
684 jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectGetPropertyData error");
685 printError(osErr);
686 goto error;
689 // pause for a bit to make sure that everything completed correctly
690 // this is to work around a bug in the HAL where a new aggregate device seems to disappear briefly after it is created
691 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
693 //-------------------------
694 // Set the sub-device list
695 //-------------------------
697 pluginAOPA.mSelector = kAudioAggregateDevicePropertyFullSubDeviceList;
698 pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
699 pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
700 outDataSize = sizeof(CFMutableArrayRef);
701 osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &subDevicesArray);
702 if (osErr != noErr) {
703 jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectSetPropertyData for sub-device list error");
704 printError(osErr);
705 goto error;
708 // pause again to give the changes time to take effect
709 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
711 //-----------------------
712 // Set the master device
713 //-----------------------
715 // set the master device manually (this is the device which will act as the master clock for the aggregate device)
716 // pass in the UID of the device you want to use
717 pluginAOPA.mSelector = kAudioAggregateDevicePropertyMasterSubDevice;
718 pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
719 pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
720 outDataSize = sizeof(CFStringRef);
721 osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &captureDeviceUID[0]); // First apture is master...
722 if (osErr != noErr) {
723 jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectSetPropertyData for master device error");
724 printError(osErr);
725 goto error;
728 // pause again to give the changes time to take effect
729 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
731 //----------
732 // Clean up
733 //----------
735 // release the private AD key
736 CFRelease(AggregateDeviceNumberRef);
738 // release the CF objects we have created - we don't need them any more
739 CFRelease(aggDeviceDict);
740 CFRelease(subDevicesArray);
742 // release the device UID
743 for (UInt32 i = 0; i < captureDeviceUID.size(); i++) {
744 CFRelease(captureDeviceUID[i]);
747 for (UInt32 i = 0; i < playbackDeviceUID.size(); i++) {
748 CFRelease(playbackDeviceUID[i]);
751 jack_log("New aggregate device %ld", *outAggregateDevice);
752 return noErr;
754 error:
755 DestroyAggregateDevice();
756 return -1;
759 int JackCoreAudioDriver::SetupDevices(const char* capture_driver_uid,
760 const char* playback_driver_uid,
761 char* capture_driver_name,
762 char* playback_driver_name,
763 jack_nframes_t samplerate)
765 capture_driver_name[0] = 0;
766 playback_driver_name[0] = 0;
768 // Duplex
769 if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
770 jack_log("JackCoreAudioDriver::Open duplex");
772 // Same device for capture and playback...
773 if (strcmp(capture_driver_uid, playback_driver_uid) == 0) {
775 if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
776 jack_log("Will take default in/out");
777 if (GetDefaultDevice(&fDeviceID) != noErr) {
778 jack_error("Cannot open default device");
779 return -1;
782 if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
783 jack_error("Cannot get device name from device ID");
784 return -1;
787 } else {
789 // Creates aggregate device
790 AudioDeviceID captureID, playbackID;
792 if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
793 jack_log("Will take default input");
794 if (GetDefaultInputDevice(&captureID) != noErr) {
795 jack_error("Cannot open default device");
796 return -1;
800 if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
801 jack_log("Will take default output");
802 if (GetDefaultOutputDevice(&playbackID) != noErr) {
803 jack_error("Cannot open default device");
804 return -1;
808 if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr)
809 return -1;
812 // Capture only
813 } else if (strcmp(capture_driver_uid, "") != 0) {
814 jack_log("JackCoreAudioDriver::Open capture only");
815 if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
816 jack_log("Will take default input");
817 if (GetDefaultInputDevice(&fDeviceID) != noErr) {
818 jack_error("Cannot open default device");
819 return -1;
822 if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
823 jack_error("Cannot get device name from device ID");
824 return -1;
827 // Playback only
828 } else if (strcmp(playback_driver_uid, "") != 0) {
829 jack_log("JackCoreAudioDriver::Open playback only");
830 if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
831 jack_log("Will take default output");
832 if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
833 jack_error("Cannot open default device");
834 return -1;
837 if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
838 jack_error("Cannot get device name from device ID");
839 return -1;
842 // Use default driver in duplex mode
843 } else {
844 jack_log("JackCoreAudioDriver::Open default driver");
845 if (GetDefaultDevice(&fDeviceID) != noErr) {
846 jack_error("Cannot open default device");
847 return -1;
849 if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
850 jack_error("Cannot get device name from device ID");
851 return -1;
855 if (fHogged) {
856 if (TakeHog()) {
857 jack_info("Device = %ld has been hogged", fDeviceID);
858 } else {
859 jack_error("Cannot hog device = %ld", fDeviceID);
863 return 0;
867 Return the max possible input channels in in_nChannels and output channels in out_nChannels.
869 int JackCoreAudioDriver::SetupChannels(bool capturing, bool playing, int& inchannels, int& outchannels, int& in_nChannels, int& out_nChannels, bool strict)
871 OSStatus err = noErr;
873 if (capturing) {
874 err = GetTotalChannels(fDeviceID, in_nChannels, true);
875 if (err != noErr) {
876 jack_error("Cannot get input channel number");
877 printError(err);
878 return -1;
879 } else {
880 jack_log("Max input channels : %d", in_nChannels);
884 if (playing) {
885 err = GetTotalChannels(fDeviceID, out_nChannels, false);
886 if (err != noErr) {
887 jack_error("Cannot get output channel number");
888 printError(err);
889 return -1;
890 } else {
891 jack_log("Max output channels : %d", out_nChannels);
895 if (inchannels > in_nChannels) {
896 jack_error("This device hasn't required input channels inchannels = %d in_nChannels = %d", inchannels, in_nChannels);
897 if (strict)
898 return -1;
901 if (outchannels > out_nChannels) {
902 jack_error("This device hasn't required output channels outchannels = %d out_nChannels = %d", outchannels, out_nChannels);
903 if (strict)
904 return -1;
907 if (inchannels == -1) {
908 jack_log("Setup max in channels = %d", in_nChannels);
909 inchannels = in_nChannels;
912 if (outchannels == -1) {
913 jack_log("Setup max out channels = %d", out_nChannels);
914 outchannels = out_nChannels;
917 return 0;
920 int JackCoreAudioDriver::SetupBufferSize(jack_nframes_t buffer_size)
922 // Setting buffer size
923 UInt32 outSize = sizeof(UInt32);
924 OSStatus err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
925 if (err != noErr) {
926 jack_error("Cannot set buffer size %ld", buffer_size);
927 printError(err);
928 return -1;
931 return 0;
934 int JackCoreAudioDriver::SetupSampleRate(jack_nframes_t samplerate)
936 return SetupSampleRateAux(fDeviceID, samplerate);
939 int JackCoreAudioDriver::SetupSampleRateAux(AudioDeviceID inDevice, jack_nframes_t samplerate)
941 OSStatus err = noErr;
942 UInt32 outSize;
943 Float64 sampleRate;
945 // Get sample rate
946 outSize = sizeof(Float64);
947 err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
948 if (err != noErr) {
949 jack_error("Cannot get current sample rate");
950 printError(err);
951 return -1;
954 // If needed, set new sample rate
955 if (samplerate != (jack_nframes_t)sampleRate) {
956 sampleRate = (Float64)samplerate;
958 // To get SR change notification
959 err = AudioDeviceAddPropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback, this);
960 if (err != noErr) {
961 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
962 printError(err);
963 return -1;
965 err = AudioDeviceSetProperty(inDevice, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &sampleRate);
966 if (err != noErr) {
967 jack_error("Cannot set sample rate = %ld", samplerate);
968 printError(err);
969 return -1;
972 // Waiting for SR change notification
973 int count = 0;
974 while (!fState && count++ < WAIT_COUNTER) {
975 usleep(100000);
976 jack_log("Wait count = %d", count);
979 // Remove SR change notification
980 AudioDeviceRemovePropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
983 return 0;
986 int JackCoreAudioDriver::OpenAUHAL(bool capturing,
987 bool playing,
988 int inchannels,
989 int outchannels,
990 int in_nChannels,
991 int out_nChannels,
992 jack_nframes_t buffer_size,
993 jack_nframes_t samplerate)
995 ComponentResult err1;
996 UInt32 enableIO;
997 AudioStreamBasicDescription srcFormat, dstFormat;
998 AudioDeviceID currAudioDeviceID;
999 UInt32 size;
1001 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);
1003 if (inchannels == 0 && outchannels == 0) {
1004 jack_error("No input and output channels...");
1005 return -1;
1008 // AUHAL
1009 ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
1010 Component HALOutput = FindNextComponent(NULL, &cd);
1012 err1 = OpenAComponent(HALOutput, &fAUHAL);
1013 if (err1 != noErr) {
1014 jack_error("Error calling OpenAComponent");
1015 printError(err1);
1016 goto error;
1019 err1 = AudioUnitInitialize(fAUHAL);
1020 if (err1 != noErr) {
1021 jack_error("Cannot initialize AUHAL unit");
1022 printError(err1);
1023 goto error;
1026 // Start I/O
1027 if (capturing && inchannels > 0) {
1028 enableIO = 1;
1029 jack_log("Setup AUHAL input on");
1030 } else {
1031 enableIO = 0;
1032 jack_log("Setup AUHAL input off");
1035 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
1036 if (err1 != noErr) {
1037 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
1038 printError(err1);
1039 goto error;
1042 if (playing && outchannels > 0) {
1043 enableIO = 1;
1044 jack_log("Setup AUHAL output on");
1045 } else {
1046 enableIO = 0;
1047 jack_log("Setup AUHAL output off");
1050 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
1051 if (err1 != noErr) {
1052 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
1053 printError(err1);
1054 goto error;
1057 size = sizeof(AudioDeviceID);
1058 err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
1059 if (err1 != noErr) {
1060 jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
1061 printError(err1);
1062 goto error;
1063 } else {
1064 jack_log("AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
1067 // Setup up choosen device, in both input and output cases
1068 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
1069 if (err1 != noErr) {
1070 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
1071 printError(err1);
1072 goto error;
1075 // Set buffer size
1076 if (capturing && inchannels > 0) {
1077 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*)&buffer_size, sizeof(UInt32));
1078 if (err1 != noErr) {
1079 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
1080 printError(err1);
1081 goto error;
1085 if (playing && outchannels > 0) {
1086 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*)&buffer_size, sizeof(UInt32));
1087 if (err1 != noErr) {
1088 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
1089 printError(err1);
1090 goto error;
1094 // Setup channel map
1095 if (capturing && inchannels > 0 && inchannels < in_nChannels) {
1096 SInt32 chanArr[in_nChannels];
1097 for (int i = 0; i < in_nChannels; i++) {
1098 chanArr[i] = -1;
1100 for (int i = 0; i < inchannels; i++) {
1101 chanArr[i] = i;
1103 AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
1104 if (err1 != noErr) {
1105 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 1");
1106 printError(err1);
1107 goto error;
1111 if (playing && outchannels > 0 && outchannels < out_nChannels) {
1112 SInt32 chanArr[out_nChannels];
1113 for (int i = 0; i < out_nChannels; i++) {
1114 chanArr[i] = -1;
1116 for (int i = 0; i < outchannels; i++) {
1117 chanArr[i] = i;
1119 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
1120 if (err1 != noErr) {
1121 jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 0");
1122 printError(err1);
1123 goto error;
1127 // Setup stream converters
1128 if (capturing && inchannels > 0) {
1130 size = sizeof(AudioStreamBasicDescription);
1131 err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &srcFormat, &size);
1132 if (err1 != noErr) {
1133 jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
1134 printError(err1);
1135 goto error;
1137 PrintStreamDesc(&srcFormat);
1139 jack_log("Setup AUHAL input stream converter SR = %ld", samplerate);
1140 srcFormat.mSampleRate = samplerate;
1141 srcFormat.mFormatID = kAudioFormatLinearPCM;
1142 srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
1143 srcFormat.mBytesPerPacket = sizeof(float);
1144 srcFormat.mFramesPerPacket = 1;
1145 srcFormat.mBytesPerFrame = sizeof(float);
1146 srcFormat.mChannelsPerFrame = inchannels;
1147 srcFormat.mBitsPerChannel = 32;
1148 PrintStreamDesc(&srcFormat);
1150 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &srcFormat, sizeof(AudioStreamBasicDescription));
1152 if (err1 != noErr) {
1153 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
1154 printError(err1);
1155 goto error;
1159 if (playing && outchannels > 0) {
1161 size = sizeof(AudioStreamBasicDescription);
1162 err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 1, &dstFormat, &size);
1163 if (err1 != noErr) {
1164 jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
1165 printError(err1);
1166 goto error;
1168 PrintStreamDesc(&dstFormat);
1170 jack_log("Setup AUHAL output stream converter SR = %ld", samplerate);
1171 dstFormat.mSampleRate = samplerate;
1172 dstFormat.mFormatID = kAudioFormatLinearPCM;
1173 dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
1174 dstFormat.mBytesPerPacket = sizeof(float);
1175 dstFormat.mFramesPerPacket = 1;
1176 dstFormat.mBytesPerFrame = sizeof(float);
1177 dstFormat.mChannelsPerFrame = outchannels;
1178 dstFormat.mBitsPerChannel = 32;
1179 PrintStreamDesc(&dstFormat);
1181 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &dstFormat, sizeof(AudioStreamBasicDescription));
1183 if (err1 != noErr) {
1184 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
1185 printError(err1);
1186 goto error;
1190 // Setup callbacks
1191 if (inchannels > 0 && outchannels == 0) {
1192 AURenderCallbackStruct output;
1193 output.inputProc = Render;
1194 output.inputProcRefCon = this;
1195 err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
1196 if (err1 != noErr) {
1197 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
1198 printError(err1);
1199 goto error;
1201 } else {
1202 AURenderCallbackStruct output;
1203 output.inputProc = Render;
1204 output.inputProcRefCon = this;
1205 err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
1206 if (err1 != noErr) {
1207 jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
1208 printError(err1);
1209 goto error;
1213 return 0;
1215 error:
1216 CloseAUHAL();
1217 return -1;
1220 int JackCoreAudioDriver::SetupBuffers(int inchannels)
1222 // Prepare buffers
1223 fJackInputData = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
1224 fJackInputData->mNumberBuffers = inchannels;
1225 for (int i = 0; i < fCaptureChannels; i++) {
1226 fJackInputData->mBuffers[i].mNumberChannels = 1;
1227 fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(float);
1229 return 0;
1232 void JackCoreAudioDriver::DisposeBuffers()
1234 if (fJackInputData) {
1235 free(fJackInputData);
1236 fJackInputData = 0;
1240 void JackCoreAudioDriver::CloseAUHAL()
1242 AudioUnitUninitialize(fAUHAL);
1243 CloseComponent(fAUHAL);
1246 int JackCoreAudioDriver::AddListeners()
1248 OSStatus err = noErr;
1250 // Add listeners
1251 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback, this);
1252 if (err != noErr) {
1253 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDeviceProcessorOverload");
1254 printError(err);
1255 return -1;
1258 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback, this);
1259 if (err != noErr) {
1260 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioHardwarePropertyDevices");
1261 printError(err);
1262 return -1;
1265 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback, this);
1266 if (err != noErr) {
1267 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
1268 printError(err);
1269 return -1;
1272 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback, this);
1273 if (err != noErr) {
1274 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsRunning");
1275 printError(err);
1276 return -1;
1279 err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
1280 if (err != noErr) {
1281 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
1282 printError(err);
1283 return -1;
1286 err = AudioDeviceAddPropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
1287 if (err != noErr) {
1288 jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
1289 printError(err);
1290 return -1;
1293 if (!fEngineControl->fSyncMode && fIOUsage != 1.f) {
1294 UInt32 outSize = sizeof(float);
1295 err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyIOCycleUsage, outSize, &fIOUsage);
1296 if (err != noErr) {
1297 jack_error("Error calling AudioDeviceSetProperty kAudioDevicePropertyIOCycleUsage");
1298 printError(err);
1302 return 0;
1305 void JackCoreAudioDriver::RemoveListeners()
1307 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback);
1308 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback);
1309 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback);
1310 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback);
1311 AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
1312 AudioDeviceRemovePropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
1315 int JackCoreAudioDriver::Open(jack_nframes_t buffer_size,
1316 jack_nframes_t samplerate,
1317 bool capturing,
1318 bool playing,
1319 int inchannels,
1320 int outchannels,
1321 bool monitor,
1322 const char* capture_driver_uid,
1323 const char* playback_driver_uid,
1324 jack_nframes_t capture_latency,
1325 jack_nframes_t playback_latency,
1326 int async_output_latency,
1327 int computation_grain,
1328 bool hogged,
1329 bool clock_drift)
1331 int in_nChannels = 0;
1332 int out_nChannels = 0;
1333 char capture_driver_name[256];
1334 char playback_driver_name[256];
1336 // Keep initial state
1337 fCapturing = capturing;
1338 fPlaying = playing;
1339 fInChannels = inchannels;
1340 fOutChannels = outchannels;
1341 fMonitor = monitor;
1342 strcpy(fCaptureUID, capture_driver_uid);
1343 strcpy(fPlaybackUID, playback_driver_uid);
1344 fCaptureLatency = capture_latency;
1345 fPlaybackLatency = playback_latency;
1346 fIOUsage = float(async_output_latency) / 100.f;
1347 fComputationGrain = float(computation_grain) / 100.f;
1348 fHogged = hogged;
1349 fClockDriftCompensate = clock_drift;
1351 SInt32 major;
1352 SInt32 minor;
1353 Gestalt(gestaltSystemVersionMajor, &major);
1354 Gestalt(gestaltSystemVersionMinor, &minor);
1356 // Starting with 10.6 systems, the HAL notification thread is created internally
1357 if (major == 10 && minor >= 6) {
1358 CFRunLoopRef theRunLoop = NULL;
1359 AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
1360 OSStatus theError = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
1361 if (theError != noErr) {
1362 jack_error("JackCoreAudioDriver::Open kAudioHardwarePropertyRunLoop error");
1366 if (SetupDevices(capture_driver_uid, playback_driver_uid, capture_driver_name, playback_driver_name, samplerate) < 0)
1367 goto error;
1369 // Generic JackAudioDriver Open
1370 if (JackAudioDriver::Open(buffer_size, samplerate, capturing, playing, inchannels, outchannels, monitor, capture_driver_name, playback_driver_name, capture_latency, playback_latency) != 0)
1371 goto error;
1373 if (SetupChannels(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, true) < 0)
1374 goto error;
1376 if (SetupBufferSize(buffer_size) < 0)
1377 goto error;
1379 if (SetupSampleRate(samplerate) < 0)
1380 goto error;
1382 if (OpenAUHAL(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, buffer_size, samplerate) < 0)
1383 goto error;
1385 if (capturing && inchannels > 0)
1386 if (SetupBuffers(inchannels) < 0)
1387 goto error;
1389 if (AddListeners() < 0)
1390 goto error;
1392 // Core driver may have changed the in/out values
1393 fCaptureChannels = inchannels;
1394 fPlaybackChannels = outchannels;
1395 return noErr;
1397 error:
1398 Close();
1399 return -1;
1402 int JackCoreAudioDriver::Close()
1404 jack_log("JackCoreAudioDriver::Close");
1405 Stop();
1406 JackAudioDriver::Close();
1407 RemoveListeners();
1408 DisposeBuffers();
1409 CloseAUHAL();
1410 DestroyAggregateDevice();
1411 return 0;
1414 int JackCoreAudioDriver::Attach()
1416 OSStatus err;
1417 JackPort* port;
1418 jack_port_id_t port_index;
1419 UInt32 size;
1420 Boolean isWritable;
1421 char channel_name[64];
1422 char name[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
1423 char alias[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
1424 unsigned long port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
1426 jack_log("JackCoreAudioDriver::Attach fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
1428 for (int i = 0; i < fCaptureChannels; i++) {
1430 err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, &isWritable);
1431 if (err != noErr)
1432 jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error ");
1433 if (err == noErr && size > 0) {
1434 err = AudioDeviceGetProperty(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, channel_name);
1435 if (err != noErr)
1436 jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error ");
1437 snprintf(alias, sizeof(alias) - 1, "%s:%s:out_%s%u", fAliasName, fCaptureDriverName, channel_name, i + 1);
1438 } else {
1439 snprintf(alias, sizeof(alias) - 1, "%s:%s:out%u", fAliasName, fCaptureDriverName, i + 1);
1442 snprintf(name, sizeof(name) - 1, "%s:capture_%d", fClientControl.fName, i + 1);
1444 if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
1445 jack_error("Cannot register port for %s", name);
1446 return -1;
1449 size = sizeof(UInt32);
1450 UInt32 value1 = 0;
1451 UInt32 value2 = 0;
1452 err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertyLatency, &size, &value1);
1453 if (err != noErr)
1454 jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error ");
1455 err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertySafetyOffset, &size, &value2);
1456 if (err != noErr)
1457 jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error ");
1459 port = fGraphManager->GetPort(port_index);
1460 port->SetAlias(alias);
1461 port->SetLatency(fEngineControl->fBufferSize + value1 + value2 + fCaptureLatency);
1462 fCapturePortList[i] = port_index;
1465 port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
1467 for (int i = 0; i < fPlaybackChannels; i++) {
1469 err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, &isWritable);
1470 if (err != noErr)
1471 jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error ");
1472 if (err == noErr && size > 0) {
1473 err = AudioDeviceGetProperty(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, channel_name);
1474 if (err != noErr)
1475 jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error ");
1476 snprintf(alias, sizeof(alias) - 1, "%s:%s:in_%s%u", fAliasName, fPlaybackDriverName, channel_name, i + 1);
1477 } else {
1478 snprintf(alias, sizeof(alias) - 1, "%s:%s:in%u", fAliasName, fPlaybackDriverName, i + 1);
1481 snprintf(name, sizeof(name) - 1, "%s:playback_%d", fClientControl.fName, i + 1);
1483 if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
1484 jack_error("Cannot register port for %s", name);
1485 return -1;
1488 size = sizeof(UInt32);
1489 UInt32 value1 = 0;
1490 UInt32 value2 = 0;
1491 err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertyLatency, &size, &value1);
1492 if (err != noErr)
1493 jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error ");
1494 err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertySafetyOffset, &size, &value2);
1495 if (err != noErr)
1496 jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error ");
1498 port = fGraphManager->GetPort(port_index);
1499 port->SetAlias(alias);
1500 // Add more latency if "async" mode is used...
1501 port->SetLatency(fEngineControl->fBufferSize + ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize * fIOUsage) + value1 + value2 + fPlaybackLatency);
1502 fPlaybackPortList[i] = port_index;
1504 // Monitor ports
1505 if (fWithMonitorPorts) {
1506 jack_log("Create monitor port ");
1507 snprintf(name, sizeof(name) - 1, "%s:monitor_%u", fClientControl.fName, i + 1);
1508 if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, fEngineControl->fBufferSize)) == NO_PORT) {
1509 jack_error("Cannot register monitor port for %s", name);
1510 return -1;
1511 } else {
1512 port = fGraphManager->GetPort(port_index);
1513 port->SetAlias(alias);
1514 port->SetLatency(fEngineControl->fBufferSize);
1515 fMonitorPortList[i] = port_index;
1520 // Input buffers do no change : prepare them only once
1521 for (int i = 0; i < fCaptureChannels; i++) {
1522 fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
1525 return 0;
1528 int JackCoreAudioDriver::Start()
1530 jack_log("JackCoreAudioDriver::Start");
1531 JackAudioDriver::Start();
1533 #ifdef MAC_OS_X_VERSION_10_5
1534 OSStatus err = AudioDeviceCreateIOProcID(fDeviceID, MeasureCallback, this, &fMesureCallbackID);
1535 #else
1536 OSStatus err = AudioDeviceAddIOProc(fDeviceID, MeasureCallback, this);
1537 #endif
1539 OSStatus err = AudioDeviceAddIOProc(fDeviceID, MeasureCallback, this);
1541 if (err != noErr)
1542 return -1;
1544 err = AudioOutputUnitStart(fAUHAL);
1545 if (err != noErr)
1546 return -1;
1548 if ((err = AudioDeviceStart(fDeviceID, MeasureCallback)) != noErr) {
1549 jack_error("Cannot start MeasureCallback");
1550 printError(err);
1551 return -1;
1554 // Waiting for Measure callback to be called ( = driver has started)
1555 fState = false;
1556 int count = 0;
1557 while (!fState && count++ < WAIT_COUNTER) {
1558 usleep(100000);
1559 jack_log("JackCoreAudioDriver::Start wait count = %d", count);
1562 if (count < WAIT_COUNTER) {
1563 jack_info("CoreAudio driver is running...");
1564 return 0;
1565 } else {
1566 jack_error("CoreAudio driver cannot start...");
1567 return -1;
1571 int JackCoreAudioDriver::Stop()
1573 jack_log("JackCoreAudioDriver::Stop");
1574 AudioDeviceStop(fDeviceID, MeasureCallback);
1576 #ifdef MAC_OS_X_VERSION_10_5
1577 AudioDeviceDestroyIOProcID(fDeviceID, fMesureCallbackID);
1578 #else
1579 AudioDeviceRemoveIOProc(fDeviceID, MeasureCallback);
1580 #endif
1582 AudioDeviceRemoveIOProc(fDeviceID, MeasureCallback);
1583 return (AudioOutputUnitStop(fAUHAL) == noErr) ? 0 : -1;
1586 int JackCoreAudioDriver::SetBufferSize(jack_nframes_t buffer_size)
1588 OSStatus err;
1589 UInt32 outSize = sizeof(UInt32);
1591 err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
1592 if (err != noErr) {
1593 jack_error("Cannot set buffer size %ld", buffer_size);
1594 printError(err);
1595 return -1;
1598 JackAudioDriver::SetBufferSize(buffer_size); // never fails
1600 // Input buffers do no change : prepare them only once
1601 for (int i = 0; i < fCaptureChannels; i++) {
1602 fJackInputData->mBuffers[i].mNumberChannels = 1;
1603 fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(float);
1604 fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
1607 return 0;
1610 bool JackCoreAudioDriver::TakeHogAux(AudioDeviceID deviceID, bool isInput)
1612 pid_t hog_pid;
1613 OSStatus err;
1615 UInt32 propSize = sizeof(hog_pid);
1616 err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyHogMode, &propSize, &hog_pid);
1617 if (err) {
1618 jack_error("Cannot read hog state...");
1619 printError(err);
1622 if (hog_pid != getpid()) {
1623 hog_pid = getpid();
1624 err = AudioDeviceSetProperty(deviceID, 0, 0, isInput, kAudioDevicePropertyHogMode, propSize, &hog_pid);
1625 if (err != noErr) {
1626 jack_error("Can't hog device = %d because it's being hogged by another program", deviceID);
1627 return false;
1631 return true;
1634 bool JackCoreAudioDriver::TakeHog()
1636 OSStatus err = noErr;
1637 AudioObjectID sub_device[32];
1638 UInt32 outSize = sizeof(sub_device);
1639 err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
1641 if (err != noErr) {
1642 jack_log("Device does not have subdevices");
1643 return TakeHogAux(fDeviceID, true);
1644 } else {
1645 int num_devices = outSize / sizeof(AudioObjectID);
1646 jack_log("Device does has %d subdevices", num_devices);
1647 for (int i = 0; i < num_devices; i++) {
1648 if (!TakeHogAux(sub_device[i], true)) {
1649 return false;
1652 return true;
1656 bool JackCoreAudioDriver::IsAggregateDevice(AudioDeviceID device)
1658 UInt32 deviceType, outSize = sizeof(UInt32);
1659 OSStatus err = AudioDeviceGetProperty(device, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyTransportType, &outSize, &deviceType);
1661 if (err != noErr) {
1662 jack_log("JackCoreAudioDriver::IsAggregateDevice kAudioDevicePropertyTransportType error");
1663 return false;
1664 } else {
1665 return (deviceType == kAudioDeviceTransportTypeAggregate);
1670 } // end of namespace
1673 #ifdef __cplusplus
1674 extern "C"
1676 #endif
1678 SERVER_EXPORT jack_driver_desc_t* driver_get_descriptor()
1680 jack_driver_desc_t *desc;
1681 unsigned int i;
1682 desc = (jack_driver_desc_t*)calloc(1, sizeof(jack_driver_desc_t));
1684 strcpy(desc->name, "coreaudio"); // size MUST be less then JACK_DRIVER_NAME_MAX + 1
1685 strcpy(desc->desc, "Apple CoreAudio API based audio backend"); // size MUST be less then JACK_DRIVER_PARAM_DESC + 1
1687 desc->nparams = 17;
1688 desc->params = (jack_driver_param_desc_t*)calloc(desc->nparams, sizeof(jack_driver_param_desc_t));
1690 i = 0;
1691 strcpy(desc->params[i].name, "channels");
1692 desc->params[i].character = 'c';
1693 desc->params[i].type = JackDriverParamInt;
1694 desc->params[i].value.ui = -1;
1695 strcpy(desc->params[i].short_desc, "Maximum number of channels");
1696 strcpy(desc->params[i].long_desc, "Maximum number of channels. If -1, max possible number of channels will be used");
1698 i++;
1699 strcpy(desc->params[i].name, "inchannels");
1700 desc->params[i].character = 'i';
1701 desc->params[i].type = JackDriverParamInt;
1702 desc->params[i].value.ui = -1;
1703 strcpy(desc->params[i].short_desc, "Maximum number of input channels");
1704 strcpy(desc->params[i].long_desc, "Maximum number of input channels. If -1, max possible number of input channels will be used");
1706 i++;
1707 strcpy(desc->params[i].name, "outchannels");
1708 desc->params[i].character = 'o';
1709 desc->params[i].type = JackDriverParamInt;
1710 desc->params[i].value.ui = -1;
1711 strcpy(desc->params[i].short_desc, "Maximum number of output channels");
1712 strcpy(desc->params[i].long_desc, "Maximum number of output channels. If -1, max possible number of output channels will be used");
1714 i++;
1715 strcpy(desc->params[i].name, "capture");
1716 desc->params[i].character = 'C';
1717 desc->params[i].type = JackDriverParamString;
1718 strcpy(desc->params[i].short_desc, "Input CoreAudio device name");
1719 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1721 i++;
1722 strcpy(desc->params[i].name, "playback");
1723 desc->params[i].character = 'P';
1724 desc->params[i].type = JackDriverParamString;
1725 strcpy(desc->params[i].short_desc, "Output CoreAudio device name");
1726 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1728 i++;
1729 strcpy (desc->params[i].name, "monitor");
1730 desc->params[i].character = 'm';
1731 desc->params[i].type = JackDriverParamBool;
1732 desc->params[i].value.i = 0;
1733 strcpy(desc->params[i].short_desc, "Provide monitor ports for the output");
1734 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1736 i++;
1737 strcpy(desc->params[i].name, "duplex");
1738 desc->params[i].character = 'D';
1739 desc->params[i].type = JackDriverParamBool;
1740 desc->params[i].value.i = TRUE;
1741 strcpy(desc->params[i].short_desc, "Provide both capture and playback ports");
1742 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1744 i++;
1745 strcpy(desc->params[i].name, "rate");
1746 desc->params[i].character = 'r';
1747 desc->params[i].type = JackDriverParamUInt;
1748 desc->params[i].value.ui = 44100U;
1749 strcpy(desc->params[i].short_desc, "Sample rate");
1750 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1752 i++;
1753 strcpy(desc->params[i].name, "period");
1754 desc->params[i].character = 'p';
1755 desc->params[i].type = JackDriverParamUInt;
1756 desc->params[i].value.ui = 128U;
1757 strcpy(desc->params[i].short_desc, "Frames per period");
1758 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1760 i++;
1761 strcpy(desc->params[i].name, "device");
1762 desc->params[i].character = 'd';
1763 desc->params[i].type = JackDriverParamString;
1764 strcpy(desc->params[i].short_desc, "CoreAudio device name");
1765 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1767 i++;
1768 strcpy(desc->params[i].name, "input-latency");
1769 desc->params[i].character = 'I';
1770 desc->params[i].type = JackDriverParamUInt;
1771 desc->params[i].value.i = 0;
1772 strcpy(desc->params[i].short_desc, "Extra input latency (frames)");
1773 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1775 i++;
1776 strcpy(desc->params[i].name, "output-latency");
1777 desc->params[i].character = 'O';
1778 desc->params[i].type = JackDriverParamUInt;
1779 desc->params[i].value.i = 0;
1780 strcpy(desc->params[i].short_desc, "Extra output latency (frames)");
1781 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1783 i++;
1784 strcpy(desc->params[i].name, "list-devices");
1785 desc->params[i].character = 'l';
1786 desc->params[i].type = JackDriverParamBool;
1787 desc->params[i].value.i = FALSE;
1788 strcpy(desc->params[i].short_desc, "Display available CoreAudio devices");
1789 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1791 i++;
1792 strcpy(desc->params[i].name, "hog");
1793 desc->params[i].character = 'H';
1794 desc->params[i].type = JackDriverParamBool;
1795 desc->params[i].value.i = FALSE;
1796 strcpy(desc->params[i].short_desc, "Take exclusive access of the audio device");
1797 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1799 i++;
1800 strcpy(desc->params[i].name, "async-latency");
1801 desc->params[i].character = 'L';
1802 desc->params[i].type = JackDriverParamUInt;
1803 desc->params[i].value.i = 100;
1804 strcpy(desc->params[i].short_desc, "Extra output latency in asynchronous mode (percent)");
1805 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1807 i++;
1808 strcpy(desc->params[i].name, "grain");
1809 desc->params[i].character = 'G';
1810 desc->params[i].type = JackDriverParamUInt;
1811 desc->params[i].value.i = 100;
1812 strcpy(desc->params[i].short_desc, "Computation grain in RT thread (percent)");
1813 strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
1815 i++;
1816 strcpy(desc->params[i].name, "clock-drift");
1817 desc->params[i].character = 's';
1818 desc->params[i].type = JackDriverParamBool;
1819 desc->params[i].value.i = FALSE;
1820 strcpy(desc->params[i].short_desc, "Clock drift compensation");
1821 strcpy(desc->params[i].long_desc, "Whether to compensate clock drift in dynamically created aggregate device");
1823 return desc;
1826 SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
1828 jack_nframes_t srate = 44100;
1829 jack_nframes_t frames_per_interrupt = 128;
1830 bool capture = false;
1831 bool playback = false;
1832 int chan_in = -1; // Default: if not explicitely set, then max possible will be used...
1833 int chan_out = -1; // Default: ifĂ  not explicitely set, then max possible will be used...
1834 bool monitor = false;
1835 const char* capture_driver_uid = "";
1836 const char* playback_driver_uid = "";
1837 const JSList *node;
1838 const jack_driver_param_t *param;
1839 jack_nframes_t systemic_input_latency = 0;
1840 jack_nframes_t systemic_output_latency = 0;
1841 int async_output_latency = 100;
1842 int computation_grain = -1;
1843 bool hogged = false;
1844 bool clock_drift = false;
1846 for (node = params; node; node = jack_slist_next(node)) {
1847 param = (const jack_driver_param_t *) node->data;
1849 switch (param->character) {
1851 case 'd':
1852 capture_driver_uid = strdup(param->value.str);
1853 playback_driver_uid = strdup(param->value.str);
1854 break;
1856 case 'D':
1857 capture = true;
1858 playback = true;
1859 break;
1861 case 'c':
1862 chan_in = chan_out = (int)param->value.ui;
1863 break;
1865 case 'i':
1866 chan_in = (int)param->value.ui;
1867 break;
1869 case 'o':
1870 chan_out = (int)param->value.ui;
1871 break;
1873 case 'C':
1874 capture = true;
1875 if (strcmp(param->value.str, "none") != 0) {
1876 capture_driver_uid = strdup(param->value.str);
1878 break;
1880 case 'P':
1881 playback = true;
1882 if (strcmp(param->value.str, "none") != 0) {
1883 playback_driver_uid = strdup(param->value.str);
1885 break;
1887 case 'm':
1888 monitor = param->value.i;
1889 break;
1891 case 'r':
1892 srate = param->value.ui;
1893 break;
1895 case 'p':
1896 frames_per_interrupt = (unsigned int)param->value.ui;
1897 break;
1899 case 'I':
1900 systemic_input_latency = param->value.ui;
1901 break;
1903 case 'O':
1904 systemic_output_latency = param->value.ui;
1905 break;
1907 case 'l':
1908 Jack::DisplayDeviceNames();
1909 break;
1911 case 'H':
1912 hogged = true;
1913 break;
1915 case 'L':
1916 async_output_latency = param->value.ui;
1917 break;
1919 case 'G':
1920 computation_grain = param->value.ui;
1921 break;
1923 case 's':
1924 clock_drift = true;
1925 break;
1929 /* duplex is the default */
1930 if (!capture && !playback) {
1931 capture = true;
1932 playback = true;
1935 Jack::JackCoreAudioDriver* driver = new Jack::JackCoreAudioDriver("system", "coreaudio", engine, table);
1936 if (driver->Open(frames_per_interrupt, srate, capture, playback, chan_in, chan_out, monitor, capture_driver_uid,
1937 playback_driver_uid, systemic_input_latency, systemic_output_latency, async_output_latency, computation_grain, hogged, clock_drift) == 0) {
1938 return driver;
1939 } else {
1940 delete driver;
1941 return NULL;
1945 #ifdef __cplusplus
1947 #endif