jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1619 lines
61KB

  1. /*
  2. Copyright (C) 2004-2008 Grame
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  14. */
  15. #include "JackCoreAudioDriver.h"
  16. #include "JackEngineControl.h"
  17. #include "JackMachThread.h"
  18. #include "JackGraphManager.h"
  19. #include "JackError.h"
  20. #include "JackClientControl.h"
  21. #include "JackDriverLoader.h"
  22. #include "JackGlobals.h"
  23. #include "JackTools.h"
  24. #include "JackCompilerDeps.h"
  25. #include <iostream>
  26. #include <CoreServices/CoreServices.h>
  27. #include <CoreFoundation/CFNumber.h>
  28. namespace Jack
  29. {
  30. static void Print4CharCode(const char* msg, long c)
  31. {
  32. UInt32 __4CC_number = (c);
  33. char __4CC_string[5];
  34. *((SInt32*)__4CC_string) = EndianU32_NtoB(__4CC_number);
  35. __4CC_string[4] = 0;
  36. jack_log("%s'%s'", (msg), __4CC_string);
  37. }
  38. static void printError(OSStatus err)
  39. {
  40. switch (err) {
  41. case kAudioHardwareNoError:
  42. jack_log("error code : kAudioHardwareNoError");
  43. break;
  44. case kAudioConverterErr_FormatNotSupported:
  45. jack_log("error code : kAudioConverterErr_FormatNotSupported");
  46. break;
  47. case kAudioConverterErr_OperationNotSupported:
  48. jack_log("error code : kAudioConverterErr_OperationNotSupported");
  49. break;
  50. case kAudioConverterErr_PropertyNotSupported:
  51. jack_log("error code : kAudioConverterErr_PropertyNotSupported");
  52. break;
  53. case kAudioConverterErr_InvalidInputSize:
  54. jack_log("error code : kAudioConverterErr_InvalidInputSize");
  55. break;
  56. case kAudioConverterErr_InvalidOutputSize:
  57. jack_log("error code : kAudioConverterErr_InvalidOutputSize");
  58. break;
  59. case kAudioConverterErr_UnspecifiedError:
  60. jack_log("error code : kAudioConverterErr_UnspecifiedError");
  61. break;
  62. case kAudioConverterErr_BadPropertySizeError:
  63. jack_log("error code : kAudioConverterErr_BadPropertySizeError");
  64. break;
  65. case kAudioConverterErr_RequiresPacketDescriptionsError:
  66. jack_log("error code : kAudioConverterErr_RequiresPacketDescriptionsError");
  67. break;
  68. case kAudioConverterErr_InputSampleRateOutOfRange:
  69. jack_log("error code : kAudioConverterErr_InputSampleRateOutOfRange");
  70. break;
  71. case kAudioConverterErr_OutputSampleRateOutOfRange:
  72. jack_log("error code : kAudioConverterErr_OutputSampleRateOutOfRange");
  73. break;
  74. case kAudioHardwareNotRunningError:
  75. jack_log("error code : kAudioHardwareNotRunningError");
  76. break;
  77. case kAudioHardwareUnknownPropertyError:
  78. jack_log("error code : kAudioHardwareUnknownPropertyError");
  79. break;
  80. case kAudioHardwareIllegalOperationError:
  81. jack_log("error code : kAudioHardwareIllegalOperationError");
  82. break;
  83. case kAudioHardwareBadDeviceError:
  84. jack_log("error code : kAudioHardwareBadDeviceError");
  85. break;
  86. case kAudioHardwareBadStreamError:
  87. jack_log("error code : kAudioHardwareBadStreamError");
  88. break;
  89. case kAudioDeviceUnsupportedFormatError:
  90. jack_log("error code : kAudioDeviceUnsupportedFormatError");
  91. break;
  92. case kAudioDevicePermissionsError:
  93. jack_log("error code : kAudioDevicePermissionsError");
  94. break;
  95. case kAudioHardwareBadObjectError:
  96. jack_log("error code : kAudioHardwareBadObjectError");
  97. break;
  98. case kAudioHardwareUnsupportedOperationError:
  99. jack_log("error code : kAudioHardwareUnsupportedOperationError");
  100. break;
  101. default:
  102. Print4CharCode("error code : unknown", err);
  103. break;
  104. }
  105. }
  106. static OSStatus DisplayDeviceNames()
  107. {
  108. UInt32 size;
  109. Boolean isWritable;
  110. int i, deviceNum;
  111. OSStatus err;
  112. CFStringRef UIname;
  113. err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
  114. if (err != noErr)
  115. return err;
  116. deviceNum = size / sizeof(AudioDeviceID);
  117. AudioDeviceID devices[deviceNum];
  118. err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
  119. if (err != noErr)
  120. return err;
  121. for (i = 0; i < deviceNum; i++) {
  122. char device_name[256];
  123. char internal_name[256];
  124. size = sizeof(CFStringRef);
  125. UIname = NULL;
  126. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  127. if (err == noErr) {
  128. CFStringGetCString(UIname, internal_name, 256, CFStringGetSystemEncoding());
  129. } else {
  130. goto error;
  131. }
  132. size = 256;
  133. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &size, device_name);
  134. if (err != noErr)
  135. return err;
  136. jack_info("Device name = \'%s\', internal_name = \'%s\' (to be used as -C, -P, or -d parameter)", device_name, internal_name);
  137. }
  138. return noErr;
  139. error:
  140. if (UIname != NULL)
  141. CFRelease(UIname);
  142. return err;
  143. }
  144. static CFStringRef GetDeviceName(AudioDeviceID id)
  145. {
  146. UInt32 size = sizeof(CFStringRef);
  147. CFStringRef UIname;
  148. OSStatus err = AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  149. return (err == noErr) ? UIname : NULL;
  150. }
  151. OSStatus JackCoreAudioDriver::Render(void *inRefCon,
  152. AudioUnitRenderActionFlags *ioActionFlags,
  153. const AudioTimeStamp *inTimeStamp,
  154. UInt32 inBusNumber,
  155. UInt32 inNumberFrames,
  156. AudioBufferList *ioData)
  157. {
  158. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inRefCon;
  159. driver->fActionFags = ioActionFlags;
  160. driver->fCurrentTime = (AudioTimeStamp *)inTimeStamp;
  161. driver->fDriverOutputData = ioData;
  162. driver->CycleTakeBeginTime();
  163. return driver->Process();
  164. }
  165. int JackCoreAudioDriver::Read()
  166. {
  167. AudioUnitRender(fAUHAL, fActionFags, fCurrentTime, 1, fEngineControl->fBufferSize, fJackInputData);
  168. return 0;
  169. }
  170. int JackCoreAudioDriver::Write()
  171. {
  172. for (int i = 0; i < fPlaybackChannels; i++) {
  173. if (fGraphManager->GetConnectionsNum(fPlaybackPortList[i]) > 0) {
  174. float* buffer = GetOutputBuffer(i);
  175. int size = sizeof(float) * fEngineControl->fBufferSize;
  176. memcpy((float*)fDriverOutputData->mBuffers[i].mData, buffer, size);
  177. // Monitor ports
  178. if (fWithMonitorPorts && fGraphManager->GetConnectionsNum(fMonitorPortList[i]) > 0)
  179. memcpy(GetMonitorBuffer(i), buffer, size);
  180. } else {
  181. memset((float*)fDriverOutputData->mBuffers[i].mData, 0, sizeof(float) * fEngineControl->fBufferSize);
  182. }
  183. }
  184. return 0;
  185. }
  186. // Will run only once
  187. OSStatus JackCoreAudioDriver::MeasureCallback(AudioDeviceID inDevice,
  188. const AudioTimeStamp* inNow,
  189. const AudioBufferList* inInputData,
  190. const AudioTimeStamp* inInputTime,
  191. AudioBufferList* outOutputData,
  192. const AudioTimeStamp* inOutputTime,
  193. void* inClientData)
  194. {
  195. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  196. AudioDeviceStop(driver->fDeviceID, MeasureCallback);
  197. jack_log("JackCoreAudioDriver::MeasureCallback called");
  198. JackMachThread::GetParams(pthread_self(), &driver->fEngineControl->fPeriod, &driver->fEngineControl->fComputation, &driver->fEngineControl->fConstraint);
  199. if (driver->fComputationGrain > 0) {
  200. jack_log("JackCoreAudioDriver::MeasureCallback : RT thread computation setup to %d percent of period", int(driver->fComputationGrain * 100));
  201. driver->fEngineControl->fComputation = driver->fEngineControl->fPeriod * driver->fComputationGrain;
  202. }
  203. // Setup threadded based log function
  204. set_threaded_log_function();
  205. return noErr;
  206. }
  207. OSStatus JackCoreAudioDriver::SRNotificationCallback(AudioDeviceID inDevice,
  208. UInt32 inChannel,
  209. Boolean isInput,
  210. AudioDevicePropertyID inPropertyID,
  211. void* inClientData)
  212. {
  213. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  214. switch (inPropertyID) {
  215. case kAudioDevicePropertyNominalSampleRate: {
  216. jack_log("JackCoreAudioDriver::SRNotificationCallback kAudioDevicePropertyNominalSampleRate");
  217. driver->fState = true;
  218. break;
  219. }
  220. }
  221. return noErr;
  222. }
  223. // A better implementation would possibly try to recover in case of hardware device change (see HALLAB HLFilePlayerWindowControllerAudioDevicePropertyListenerProc code)
  224. OSStatus JackCoreAudioDriver::DeviceNotificationCallback(AudioDeviceID inDevice,
  225. UInt32 inChannel,
  226. Boolean isInput,
  227. AudioDevicePropertyID inPropertyID,
  228. void* inClientData)
  229. {
  230. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  231. switch (inPropertyID) {
  232. case kAudioDeviceProcessorOverload: {
  233. jack_error("JackCoreAudioDriver::DeviceNotificationCallback kAudioDeviceProcessorOverload");
  234. jack_time_t cur_time = GetMicroSeconds();
  235. driver->NotifyXRun(cur_time, float(cur_time - driver->fBeginDateUst)); // Better this value than nothing...
  236. break;
  237. }
  238. case kAudioDevicePropertyStreamConfiguration: {
  239. jack_error("Cannot handle kAudioDevicePropertyStreamConfiguration : server will quit...");
  240. driver->NotifyFailure(JackBackendError, "Another application has changed the device configuration."); // Message length limited to JACK_MESSAGE_SIZE
  241. driver->CloseAUHAL();
  242. kill(JackTools::GetPID(), SIGINT);
  243. return kAudioHardwareUnsupportedOperationError;
  244. }
  245. case kAudioDevicePropertyNominalSampleRate: {
  246. jack_error("Cannot handle kAudioDevicePropertyNominalSampleRate : server will quit...");
  247. driver->NotifyFailure(JackBackendError, "Another application has changed the sample rate."); // Message length limited to JACK_MESSAGE_SIZE
  248. driver->CloseAUHAL();
  249. kill(JackTools::GetPID(), SIGINT);
  250. return kAudioHardwareUnsupportedOperationError;
  251. }
  252. }
  253. return noErr;
  254. }
  255. OSStatus JackCoreAudioDriver::GetDeviceIDFromUID(const char* UID, AudioDeviceID* id)
  256. {
  257. UInt32 size = sizeof(AudioValueTranslation);
  258. CFStringRef inIUD = CFStringCreateWithCString(NULL, UID, CFStringGetSystemEncoding());
  259. AudioValueTranslation value = { &inIUD, sizeof(CFStringRef), id, sizeof(AudioDeviceID) };
  260. if (inIUD == NULL) {
  261. return kAudioHardwareUnspecifiedError;
  262. } else {
  263. OSStatus res = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, &size, &value);
  264. CFRelease(inIUD);
  265. jack_log("GetDeviceIDFromUID %s %ld", UID, *id);
  266. return (*id == kAudioDeviceUnknown) ? kAudioHardwareBadDeviceError : res;
  267. }
  268. }
  269. OSStatus JackCoreAudioDriver::GetDefaultDevice(AudioDeviceID* id)
  270. {
  271. OSStatus res;
  272. UInt32 theSize = sizeof(UInt32);
  273. AudioDeviceID inDefault;
  274. AudioDeviceID outDefault;
  275. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  276. return res;
  277. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  278. return res;
  279. jack_log("GetDefaultDevice: input = %ld output = %ld", inDefault, outDefault);
  280. // Get the device only if default input and output are the same
  281. if (inDefault == outDefault) {
  282. *id = inDefault;
  283. return noErr;
  284. } else {
  285. jack_error("Default input and output devices are not the same !!");
  286. return kAudioHardwareBadDeviceError;
  287. }
  288. }
  289. OSStatus JackCoreAudioDriver::GetDefaultInputDevice(AudioDeviceID* id)
  290. {
  291. OSStatus res;
  292. UInt32 theSize = sizeof(UInt32);
  293. AudioDeviceID inDefault;
  294. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  295. return res;
  296. jack_log("GetDefaultInputDevice: input = %ld ", inDefault);
  297. *id = inDefault;
  298. return noErr;
  299. }
  300. OSStatus JackCoreAudioDriver::GetDefaultOutputDevice(AudioDeviceID* id)
  301. {
  302. OSStatus res;
  303. UInt32 theSize = sizeof(UInt32);
  304. AudioDeviceID outDefault;
  305. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  306. return res;
  307. jack_log("GetDefaultOutputDevice: output = %ld", outDefault);
  308. *id = outDefault;
  309. return noErr;
  310. }
  311. OSStatus JackCoreAudioDriver::GetDeviceNameFromID(AudioDeviceID id, char* name)
  312. {
  313. UInt32 size = 256;
  314. return AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceName, &size, name);
  315. }
  316. OSStatus JackCoreAudioDriver::GetTotalChannels(AudioDeviceID device, int& channelCount, bool isInput)
  317. {
  318. OSStatus err = noErr;
  319. UInt32 outSize;
  320. Boolean outWritable;
  321. AudioBufferList* bufferList = 0;
  322. channelCount = 0;
  323. err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, &outWritable);
  324. if (err == noErr) {
  325. bufferList = (AudioBufferList*)malloc(outSize);
  326. err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, bufferList);
  327. if (err == noErr) {
  328. for (unsigned int i = 0; i < bufferList->mNumberBuffers; i++)
  329. channelCount += bufferList->mBuffers[i].mNumberChannels;
  330. }
  331. if (bufferList)
  332. free(bufferList);
  333. }
  334. return err;
  335. }
  336. JackCoreAudioDriver::JackCoreAudioDriver(const char* name, const char* alias, JackLockedEngine* engine, JackSynchro* table)
  337. : JackAudioDriver(name, alias, engine, table), fJackInputData(NULL), fDriverOutputData(NULL), fPluginID(0), fState(false), fIOUsage(1.f),fComputationGrain(-1.f)
  338. {}
  339. JackCoreAudioDriver::~JackCoreAudioDriver()
  340. {}
  341. OSStatus JackCoreAudioDriver::DestroyAggregateDevice()
  342. {
  343. OSStatus osErr = noErr;
  344. AudioObjectPropertyAddress pluginAOPA;
  345. pluginAOPA.mSelector = kAudioPlugInDestroyAggregateDevice;
  346. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  347. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  348. UInt32 outDataSize;
  349. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  350. if (osErr != noErr) {
  351. jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyDataSize error");
  352. printError(osErr);
  353. return osErr;
  354. }
  355. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, 0, NULL, &outDataSize, &fDeviceID);
  356. if (osErr != noErr) {
  357. jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyData error");
  358. printError(osErr);
  359. return osErr;
  360. }
  361. return noErr;
  362. }
  363. OSStatus JackCoreAudioDriver::CreateAggregateDevice(AudioDeviceID captureDeviceID, AudioDeviceID playbackDeviceID, AudioDeviceID* outAggregateDevice)
  364. {
  365. OSStatus osErr = noErr;
  366. UInt32 outSize;
  367. Boolean outWritable;
  368. //---------------------------------------------------------------------------
  369. // Start to create a new aggregate by getting the base audio hardware plugin
  370. //---------------------------------------------------------------------------
  371. char capture_name[256];
  372. char playback_name[256];
  373. GetDeviceNameFromID(captureDeviceID, capture_name);
  374. GetDeviceNameFromID(playbackDeviceID, playback_name);
  375. jack_info("Separated input = '%s' and output = '%s' devices, create a private aggregate device to handle them...", capture_name, playback_name);
  376. osErr = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyPlugInForBundleID, &outSize, &outWritable);
  377. if (osErr != noErr)
  378. return osErr;
  379. AudioValueTranslation pluginAVT;
  380. CFStringRef inBundleRef = CFSTR("com.apple.audio.CoreAudio");
  381. pluginAVT.mInputData = &inBundleRef;
  382. pluginAVT.mInputDataSize = sizeof(inBundleRef);
  383. pluginAVT.mOutputData = &fPluginID;
  384. pluginAVT.mOutputDataSize = sizeof(fPluginID);
  385. osErr = AudioHardwareGetProperty(kAudioHardwarePropertyPlugInForBundleID, &outSize, &pluginAVT);
  386. if (osErr != noErr)
  387. return osErr;
  388. //-------------------------------------------------
  389. // Create a CFDictionary for our aggregate device
  390. //-------------------------------------------------
  391. CFMutableDictionaryRef aggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  392. CFStringRef AggregateDeviceNameRef = CFSTR("JackDuplex");
  393. CFStringRef AggregateDeviceUIDRef = CFSTR("com.grame.JackDuplex");
  394. // add the name of the device to the dictionary
  395. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceNameKey), AggregateDeviceNameRef);
  396. // add our choice of UID for the aggregate device to the dictionary
  397. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceUIDKey), AggregateDeviceUIDRef);
  398. // add a "private aggregate key" to the dictionary
  399. int value = 1;
  400. CFNumberRef AggregateDeviceNumberRef = CFNumberCreate(NULL, kCFNumberIntType, &value);
  401. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceIsPrivateKey), AggregateDeviceNumberRef);
  402. //-------------------------------------------------
  403. // Create a CFMutableArray for our sub-device list
  404. //-------------------------------------------------
  405. CFStringRef captureDeviceUID = GetDeviceName(captureDeviceID);
  406. CFStringRef playbackDeviceUID = GetDeviceName(playbackDeviceID);
  407. if (captureDeviceUID == NULL || playbackDeviceUID == NULL)
  408. return -1;
  409. // we need to append the UID for each device to a CFMutableArray, so create one here
  410. CFMutableArrayRef subDevicesArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  411. // two sub-devices in this example, so append the sub-device's UID to the CFArray
  412. CFArrayAppendValue(subDevicesArray, captureDeviceUID);
  413. CFArrayAppendValue(subDevicesArray, playbackDeviceUID);
  414. //-----------------------------------------------------------------------
  415. // Feed the dictionary to the plugin, to create a blank aggregate device
  416. //-----------------------------------------------------------------------
  417. AudioObjectPropertyAddress pluginAOPA;
  418. pluginAOPA.mSelector = kAudioPlugInCreateAggregateDevice;
  419. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  420. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  421. UInt32 outDataSize;
  422. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  423. if (osErr != noErr)
  424. return osErr;
  425. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, sizeof(aggDeviceDict), &aggDeviceDict, &outDataSize, outAggregateDevice);
  426. if (osErr != noErr)
  427. return osErr;
  428. // pause for a bit to make sure that everything completed correctly
  429. // this is to work around a bug in the HAL where a new aggregate device seems to disappear briefly after it is created
  430. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  431. //-------------------------
  432. // Set the sub-device list
  433. //-------------------------
  434. pluginAOPA.mSelector = kAudioAggregateDevicePropertyFullSubDeviceList;
  435. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  436. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  437. outDataSize = sizeof(CFMutableArrayRef);
  438. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &subDevicesArray);
  439. if (osErr != noErr)
  440. return osErr;
  441. // pause again to give the changes time to take effect
  442. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  443. //-----------------------
  444. // Set the master device
  445. //-----------------------
  446. // set the master device manually (this is the device which will act as the master clock for the aggregate device)
  447. // pass in the UID of the device you want to use
  448. pluginAOPA.mSelector = kAudioAggregateDevicePropertyMasterSubDevice;
  449. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  450. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  451. outDataSize = sizeof(CFStringRef);
  452. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &captureDeviceUID); // capture is master...
  453. if (osErr != noErr)
  454. return osErr;
  455. // pause again to give the changes time to take effect
  456. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  457. //----------
  458. // Clean up
  459. //----------
  460. CFRelease(AggregateDeviceNumberRef);
  461. // release the CF objects we have created - we don't need them any more
  462. CFRelease(aggDeviceDict);
  463. CFRelease(subDevicesArray);
  464. // release the device UID
  465. CFRelease(captureDeviceUID);
  466. CFRelease(playbackDeviceUID);
  467. jack_log("New aggregate device %ld", *outAggregateDevice);
  468. return noErr;
  469. }
  470. int JackCoreAudioDriver::SetupDevices(const char* capture_driver_uid, const char* playback_driver_uid, char* capture_driver_name, char* playback_driver_name)
  471. {
  472. capture_driver_name[0] = 0;
  473. playback_driver_name[0] = 0;
  474. // Duplex
  475. if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
  476. jack_log("JackCoreAudioDriver::Open duplex");
  477. // Same device for capture and playback...
  478. if (strcmp(capture_driver_uid, playback_driver_uid) == 0) {
  479. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  480. jack_log("Will take default in/out");
  481. if (GetDefaultDevice(&fDeviceID) != noErr) {
  482. jack_error("Cannot open default device");
  483. return -1;
  484. }
  485. }
  486. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  487. jack_error("Cannot get device name from device ID");
  488. return -1;
  489. }
  490. } else {
  491. // Creates aggregate device
  492. AudioDeviceID captureID, playbackID;
  493. if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr)
  494. return -1;
  495. if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr)
  496. return -1;
  497. if (CreateAggregateDevice(captureID, playbackID, &fDeviceID) != noErr)
  498. return -1;
  499. }
  500. // Capture only
  501. } else if (strcmp(capture_driver_uid, "") != 0) {
  502. jack_log("JackCoreAudioDriver::Open capture only");
  503. if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
  504. jack_log("Will take default input");
  505. if (GetDefaultInputDevice(&fDeviceID) != noErr) {
  506. jack_error("Cannot open default device");
  507. return -1;
  508. }
  509. }
  510. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
  511. jack_error("Cannot get device name from device ID");
  512. return -1;
  513. }
  514. // Playback only
  515. } else if (strcmp(playback_driver_uid, "") != 0) {
  516. jack_log("JackCoreAudioDriver::Open playback only");
  517. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  518. jack_log("Will take default output");
  519. if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
  520. jack_error("Cannot open default device");
  521. return -1;
  522. }
  523. }
  524. if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  525. jack_error("Cannot get device name from device ID");
  526. return -1;
  527. }
  528. // Use default driver in duplex mode
  529. } else {
  530. jack_log("JackCoreAudioDriver::Open default driver");
  531. if (GetDefaultDevice(&fDeviceID) != noErr) {
  532. jack_error("Cannot open default device");
  533. return -1;
  534. }
  535. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  536. jack_error("Cannot get device name from device ID");
  537. return -1;
  538. }
  539. }
  540. return 0;
  541. }
  542. /*
  543. Return the max possible input channels in in_nChannels and output channels in out_nChannels.
  544. */
  545. int JackCoreAudioDriver::SetupChannels(bool capturing, bool playing, int& inchannels, int& outchannels, int& in_nChannels, int& out_nChannels, bool strict)
  546. {
  547. OSStatus err = noErr;
  548. if (capturing) {
  549. err = GetTotalChannels(fDeviceID, in_nChannels, true);
  550. if (err != noErr) {
  551. jack_error("Cannot get input channel number");
  552. printError(err);
  553. return -1;
  554. } else {
  555. jack_log("Max input channels : %d", in_nChannels);
  556. }
  557. }
  558. if (playing) {
  559. err = GetTotalChannels(fDeviceID, out_nChannels, false);
  560. if (err != noErr) {
  561. jack_error("Cannot get output channel number");
  562. printError(err);
  563. return -1;
  564. } else {
  565. jack_log("Max output channels : %d", out_nChannels);
  566. }
  567. }
  568. if (inchannels > in_nChannels) {
  569. jack_error("This device hasn't required input channels inchannels = %d in_nChannels = %d", inchannels, in_nChannels);
  570. if (strict)
  571. return -1;
  572. }
  573. if (outchannels > out_nChannels) {
  574. jack_error("This device hasn't required output channels outchannels = %d out_nChannels = %d", outchannels, out_nChannels);
  575. if (strict)
  576. return -1;
  577. }
  578. if (inchannels == 0) {
  579. jack_log("Setup max in channels = %d", in_nChannels);
  580. inchannels = in_nChannels;
  581. }
  582. if (outchannels == 0) {
  583. jack_log("Setup max out channels = %d", out_nChannels);
  584. outchannels = out_nChannels;
  585. }
  586. return 0;
  587. }
  588. int JackCoreAudioDriver::SetupBufferSizeAndSampleRate(jack_nframes_t buffer_size, jack_nframes_t samplerate)
  589. {
  590. OSStatus err = noErr;
  591. UInt32 outSize;
  592. Float64 sampleRate;
  593. // Setting buffer size
  594. outSize = sizeof(UInt32);
  595. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
  596. if (err != noErr) {
  597. jack_error("Cannot set buffer size %ld", buffer_size);
  598. printError(err);
  599. return -1;
  600. }
  601. // Get sample rate
  602. outSize = sizeof(Float64);
  603. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
  604. if (err != noErr) {
  605. jack_error("Cannot get current sample rate");
  606. printError(err);
  607. return -1;
  608. }
  609. // If needed, set new sample rate
  610. if (samplerate != (jack_nframes_t)sampleRate) {
  611. sampleRate = (Float64)samplerate;
  612. // To get SR change notification
  613. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback, this);
  614. if (err != noErr) {
  615. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  616. printError(err);
  617. return -1;
  618. }
  619. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &sampleRate);
  620. if (err != noErr) {
  621. jack_error("Cannot set sample rate = %ld", samplerate);
  622. printError(err);
  623. return -1;
  624. }
  625. // Waiting for SR change notification
  626. int count = 0;
  627. while (!fState && count++ < 100) {
  628. usleep(100000);
  629. jack_log("Wait count = %d", count);
  630. }
  631. // Remove SR change notification
  632. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
  633. }
  634. return 0;
  635. }
  636. int JackCoreAudioDriver::OpenAUHAL(bool capturing,
  637. bool playing,
  638. int inchannels,
  639. int outchannels,
  640. int in_nChannels,
  641. int out_nChannels,
  642. jack_nframes_t buffer_size,
  643. jack_nframes_t samplerate,
  644. bool strict)
  645. {
  646. ComponentResult err1;
  647. UInt32 enableIO;
  648. AudioStreamBasicDescription srcFormat, dstFormat;
  649. 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);
  650. if (inchannels == 0 && outchannels == 0) {
  651. jack_error("No input and output channels...");
  652. return -1;
  653. }
  654. // AUHAL
  655. ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
  656. Component HALOutput = FindNextComponent(NULL, &cd);
  657. err1 = OpenAComponent(HALOutput, &fAUHAL);
  658. if (err1 != noErr) {
  659. jack_error("Error calling OpenAComponent");
  660. printError(err1);
  661. return -1;
  662. }
  663. err1 = AudioUnitInitialize(fAUHAL);
  664. if (err1 != noErr) {
  665. jack_error("Cannot initialize AUHAL unit");
  666. printError(err1);
  667. return -1;
  668. }
  669. // Start I/O
  670. if (capturing && inchannels > 0) {
  671. enableIO = 1;
  672. jack_log("Setup AUHAL input on");
  673. } else {
  674. enableIO = 0;
  675. jack_log("Setup AUHAL input off");
  676. }
  677. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
  678. if (err1 != noErr) {
  679. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
  680. printError(err1);
  681. if (strict)
  682. return -1;
  683. }
  684. if (playing && outchannels > 0) {
  685. enableIO = 1;
  686. jack_log("Setup AUHAL output on");
  687. } else {
  688. enableIO = 0;
  689. jack_log("Setup AUHAL output off");
  690. }
  691. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
  692. if (err1 != noErr) {
  693. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
  694. printError(err1);
  695. if (strict)
  696. return -1;
  697. }
  698. AudioDeviceID currAudioDeviceID;
  699. UInt32 size = sizeof(AudioDeviceID);
  700. err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
  701. if (err1 != noErr) {
  702. jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
  703. printError(err1);
  704. if (strict)
  705. return -1;
  706. } else {
  707. jack_log("AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
  708. }
  709. // Setup up choosen device, in both input and output cases
  710. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
  711. if (err1 != noErr) {
  712. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
  713. printError(err1);
  714. if (strict)
  715. return -1;
  716. }
  717. // Set buffer size
  718. if (capturing && inchannels > 0) {
  719. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*)&buffer_size, sizeof(UInt32));
  720. if (err1 != noErr) {
  721. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  722. printError(err1);
  723. if (strict)
  724. return -1;
  725. }
  726. }
  727. if (playing && outchannels > 0) {
  728. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*)&buffer_size, sizeof(UInt32));
  729. if (err1 != noErr) {
  730. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  731. printError(err1);
  732. if (strict)
  733. return -1;
  734. }
  735. }
  736. // Setup channel map
  737. if (capturing && inchannels > 0 && inchannels < in_nChannels) {
  738. SInt32 chanArr[in_nChannels];
  739. for (int i = 0; i < in_nChannels; i++) {
  740. chanArr[i] = -1;
  741. }
  742. for (int i = 0; i < inchannels; i++) {
  743. chanArr[i] = i;
  744. }
  745. AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
  746. if (err1 != noErr) {
  747. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 1");
  748. printError(err1);
  749. }
  750. }
  751. if (playing && outchannels > 0 && outchannels < out_nChannels) {
  752. SInt32 chanArr[out_nChannels];
  753. for (int i = 0; i < out_nChannels; i++) {
  754. chanArr[i] = -1;
  755. }
  756. for (int i = 0; i < outchannels; i++) {
  757. chanArr[i] = i;
  758. }
  759. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
  760. if (err1 != noErr) {
  761. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 0");
  762. printError(err1);
  763. }
  764. }
  765. // Setup stream converters
  766. jack_log("Setup AUHAL input stream converter SR = %ld", samplerate);
  767. srcFormat.mSampleRate = samplerate;
  768. srcFormat.mFormatID = kAudioFormatLinearPCM;
  769. srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  770. srcFormat.mBytesPerPacket = sizeof(float);
  771. srcFormat.mFramesPerPacket = 1;
  772. srcFormat.mBytesPerFrame = sizeof(float);
  773. srcFormat.mChannelsPerFrame = outchannels;
  774. srcFormat.mBitsPerChannel = 32;
  775. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &srcFormat, sizeof(AudioStreamBasicDescription));
  776. if (err1 != noErr) {
  777. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  778. printError(err1);
  779. }
  780. jack_log("Setup AUHAL output stream converter SR = %ld", samplerate);
  781. dstFormat.mSampleRate = samplerate;
  782. dstFormat.mFormatID = kAudioFormatLinearPCM;
  783. dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  784. dstFormat.mBytesPerPacket = sizeof(float);
  785. dstFormat.mFramesPerPacket = 1;
  786. dstFormat.mBytesPerFrame = sizeof(float);
  787. dstFormat.mChannelsPerFrame = inchannels;
  788. dstFormat.mBitsPerChannel = 32;
  789. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &dstFormat, sizeof(AudioStreamBasicDescription));
  790. if (err1 != noErr) {
  791. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  792. printError(err1);
  793. }
  794. // Setup callbacks
  795. if (inchannels > 0 && outchannels == 0) {
  796. AURenderCallbackStruct output;
  797. output.inputProc = Render;
  798. output.inputProcRefCon = this;
  799. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
  800. if (err1 != noErr) {
  801. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
  802. printError(err1);
  803. return -1;
  804. }
  805. } else {
  806. AURenderCallbackStruct output;
  807. output.inputProc = Render;
  808. output.inputProcRefCon = this;
  809. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
  810. if (err1 != noErr) {
  811. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
  812. printError(err1);
  813. return -1;
  814. }
  815. }
  816. return 0;
  817. }
  818. int JackCoreAudioDriver::SetupBuffers(int inchannels)
  819. {
  820. // Prepare buffers
  821. fJackInputData = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
  822. if (fJackInputData == 0) {
  823. jack_error("Cannot allocate memory for input buffers");
  824. return -1;
  825. }
  826. fJackInputData->mNumberBuffers = inchannels;
  827. for (int i = 0; i < fCaptureChannels; i++) {
  828. fJackInputData->mBuffers[i].mNumberChannels = 1;
  829. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(float);
  830. }
  831. return 0;
  832. }
  833. void JackCoreAudioDriver::DisposeBuffers()
  834. {
  835. if (fJackInputData) {
  836. free(fJackInputData);
  837. fJackInputData = 0;
  838. }
  839. }
  840. void JackCoreAudioDriver::CloseAUHAL()
  841. {
  842. AudioUnitUninitialize(fAUHAL);
  843. CloseComponent(fAUHAL);
  844. }
  845. int JackCoreAudioDriver::AddListeners()
  846. {
  847. OSStatus err = noErr;
  848. // Add listeners
  849. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback, this);
  850. if (err != noErr) {
  851. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDeviceProcessorOverload");
  852. printError(err);
  853. return -1;
  854. }
  855. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback, this);
  856. if (err != noErr) {
  857. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioHardwarePropertyDevices");
  858. printError(err);
  859. return -1;
  860. }
  861. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback, this);
  862. if (err != noErr) {
  863. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  864. printError(err);
  865. return -1;
  866. }
  867. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback, this);
  868. if (err != noErr) {
  869. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsRunning");
  870. printError(err);
  871. return -1;
  872. }
  873. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  874. if (err != noErr) {
  875. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  876. printError(err);
  877. return -1;
  878. }
  879. err = AudioDeviceAddPropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  880. if (err != noErr) {
  881. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  882. printError(err);
  883. return -1;
  884. }
  885. if (!fEngineControl->fSyncMode && fIOUsage != 1.f) {
  886. UInt32 outSize = sizeof(float);
  887. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyIOCycleUsage, outSize, &fIOUsage);
  888. if (err != noErr) {
  889. jack_error("Error calling AudioDeviceSetProperty kAudioDevicePropertyIOCycleUsage");
  890. printError(err);
  891. }
  892. }
  893. return 0;
  894. }
  895. void JackCoreAudioDriver::RemoveListeners()
  896. {
  897. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback);
  898. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback);
  899. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback);
  900. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback);
  901. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  902. AudioDeviceRemovePropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  903. }
  904. int JackCoreAudioDriver::Open(jack_nframes_t buffer_size,
  905. jack_nframes_t samplerate,
  906. bool capturing,
  907. bool playing,
  908. int inchannels,
  909. int outchannels,
  910. bool monitor,
  911. const char* capture_driver_uid,
  912. const char* playback_driver_uid,
  913. jack_nframes_t capture_latency,
  914. jack_nframes_t playback_latency,
  915. int async_output_latency,
  916. int computation_grain)
  917. {
  918. int in_nChannels = 0;
  919. int out_nChannels = 0;
  920. char capture_driver_name[256];
  921. char playback_driver_name[256];
  922. // Keep initial state
  923. fCapturing = capturing;
  924. fPlaying = playing;
  925. fInChannels = inchannels;
  926. fOutChannels = outchannels;
  927. fMonitor = monitor;
  928. strcpy(fCaptureUID, capture_driver_uid);
  929. strcpy(fPlaybackUID, playback_driver_uid);
  930. fCaptureLatency = capture_latency;
  931. fPlaybackLatency = playback_latency;
  932. fIOUsage = float(async_output_latency) / 100.f;
  933. fComputationGrain = float(computation_grain) / 100.f;
  934. SInt32 major;
  935. SInt32 minor;
  936. Gestalt(gestaltSystemVersionMajor, &major);
  937. Gestalt(gestaltSystemVersionMinor, &minor);
  938. // Starting with 10.6 systems, the HAL notification thread is created internally
  939. if (major == 10 && minor >=6) {
  940. CFRunLoopRef theRunLoop = NULL;
  941. AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  942. OSStatus theError = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
  943. if (theError != noErr) {
  944. jack_error("JackCoreAudioDriver::Open kAudioHardwarePropertyRunLoop error");
  945. }
  946. }
  947. if (SetupDevices(capture_driver_uid, playback_driver_uid, capture_driver_name, playback_driver_name) < 0)
  948. return -1;
  949. // Generic JackAudioDriver Open
  950. if (JackAudioDriver::Open(buffer_size, samplerate, capturing, playing, inchannels, outchannels, monitor, capture_driver_name, playback_driver_name, capture_latency, playback_latency) != 0)
  951. return -1;
  952. if (SetupChannels(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, true) < 0)
  953. return -1;
  954. if (SetupBufferSizeAndSampleRate(buffer_size, samplerate) < 0)
  955. return -1;
  956. if (OpenAUHAL(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, buffer_size, samplerate, true) < 0)
  957. goto error;
  958. if (capturing && inchannels > 0)
  959. if (SetupBuffers(inchannels) < 0)
  960. goto error;
  961. if (AddListeners() < 0)
  962. goto error;
  963. // Core driver may have changed the in/out values
  964. fCaptureChannels = inchannels;
  965. fPlaybackChannels = outchannels;
  966. return noErr;
  967. error:
  968. Close();
  969. return -1;
  970. }
  971. int JackCoreAudioDriver::Close()
  972. {
  973. jack_log("JackCoreAudioDriver::Close");
  974. Stop();
  975. JackAudioDriver::Close();
  976. RemoveListeners();
  977. DisposeBuffers();
  978. CloseAUHAL();
  979. if (fPluginID > 0)
  980. DestroyAggregateDevice();
  981. return 0;
  982. }
  983. int JackCoreAudioDriver::Attach()
  984. {
  985. OSStatus err;
  986. JackPort* port;
  987. jack_port_id_t port_index;
  988. UInt32 size;
  989. Boolean isWritable;
  990. char channel_name[64];
  991. char name[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  992. char alias[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  993. unsigned long port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
  994. jack_log("JackCoreAudioDriver::Attach fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
  995. for (int i = 0; i < fCaptureChannels; i++) {
  996. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, &isWritable);
  997. if (err != noErr)
  998. jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error ");
  999. if (err == noErr && size > 0) {
  1000. err = AudioDeviceGetProperty(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, channel_name);
  1001. if (err != noErr)
  1002. jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error ");
  1003. snprintf(alias, sizeof(alias) - 1, "%s:%s:out_%s%u", fAliasName, fCaptureDriverName, channel_name, i + 1);
  1004. } else {
  1005. snprintf(alias, sizeof(alias) - 1, "%s:%s:out%u", fAliasName, fCaptureDriverName, i + 1);
  1006. }
  1007. snprintf(name, sizeof(name) - 1, "%s:capture_%d", fClientControl.fName, i + 1);
  1008. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
  1009. jack_error("Cannot register port for %s", name);
  1010. return -1;
  1011. }
  1012. size = sizeof(UInt32);
  1013. UInt32 value1 = 0;
  1014. UInt32 value2 = 0;
  1015. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertyLatency, &size, &value1);
  1016. if (err != noErr)
  1017. jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error ");
  1018. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertySafetyOffset, &size, &value2);
  1019. if (err != noErr)
  1020. jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error ");
  1021. port = fGraphManager->GetPort(port_index);
  1022. port->SetAlias(alias);
  1023. port->SetLatency(fEngineControl->fBufferSize + value1 + value2 + fCaptureLatency);
  1024. fCapturePortList[i] = port_index;
  1025. }
  1026. port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
  1027. for (int i = 0; i < fPlaybackChannels; i++) {
  1028. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, &isWritable);
  1029. if (err != noErr)
  1030. jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error ");
  1031. if (err == noErr && size > 0) {
  1032. err = AudioDeviceGetProperty(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, channel_name);
  1033. if (err != noErr)
  1034. jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error ");
  1035. snprintf(alias, sizeof(alias) - 1, "%s:%s:in_%s%u", fAliasName, fPlaybackDriverName, channel_name, i + 1);
  1036. } else {
  1037. snprintf(alias, sizeof(alias) - 1, "%s:%s:in%u", fAliasName, fPlaybackDriverName, i + 1);
  1038. }
  1039. snprintf(name, sizeof(name) - 1, "%s:playback_%d", fClientControl.fName, i + 1);
  1040. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
  1041. jack_error("Cannot register port for %s", name);
  1042. return -1;
  1043. }
  1044. size = sizeof(UInt32);
  1045. UInt32 value1 = 0;
  1046. UInt32 value2 = 0;
  1047. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertyLatency, &size, &value1);
  1048. if (err != noErr)
  1049. jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error ");
  1050. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertySafetyOffset, &size, &value2);
  1051. if (err != noErr)
  1052. jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error ");
  1053. port = fGraphManager->GetPort(port_index);
  1054. port->SetAlias(alias);
  1055. // Add more latency if "async" mode is used...
  1056. port->SetLatency(fEngineControl->fBufferSize + ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize * fIOUsage) + value1 + value2 + fPlaybackLatency);
  1057. fPlaybackPortList[i] = port_index;
  1058. // Monitor ports
  1059. if (fWithMonitorPorts) {
  1060. jack_log("Create monitor port ");
  1061. snprintf(name, sizeof(name) - 1, "%s:monitor_%u", fClientControl.fName, i + 1);
  1062. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, fEngineControl->fBufferSize)) == NO_PORT) {
  1063. jack_error("Cannot register monitor port for %s", name);
  1064. return -1;
  1065. } else {
  1066. port = fGraphManager->GetPort(port_index);
  1067. port->SetAlias(alias);
  1068. port->SetLatency(fEngineControl->fBufferSize);
  1069. fMonitorPortList[i] = port_index;
  1070. }
  1071. }
  1072. }
  1073. // Input buffers do no change : prepare them only once
  1074. for (int i = 0; i < fCaptureChannels; i++) {
  1075. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1076. }
  1077. return 0;
  1078. }
  1079. int JackCoreAudioDriver::Start()
  1080. {
  1081. jack_log("JackCoreAudioDriver::Start");
  1082. JackAudioDriver::Start();
  1083. /*
  1084. #ifdef MAC_OS_X_VERSION_10_5
  1085. OSStatus err = AudioDeviceCreateIOProcID(fDeviceID, MeasureCallback, this, &fMesureCallbackID);
  1086. #else
  1087. OSStatus err = AudioDeviceAddIOProc(fDeviceID, MeasureCallback, this);
  1088. #endif
  1089. */
  1090. OSStatus err = AudioDeviceAddIOProc(fDeviceID, MeasureCallback, this);
  1091. if (err != noErr)
  1092. return -1;
  1093. err = AudioOutputUnitStart(fAUHAL);
  1094. if (err != noErr)
  1095. return -1;
  1096. if ((err = AudioDeviceStart(fDeviceID, MeasureCallback)) != noErr) {
  1097. jack_error("Cannot start MeasureCallback");
  1098. printError(err);
  1099. return -1;
  1100. }
  1101. return 0;
  1102. }
  1103. int JackCoreAudioDriver::Stop()
  1104. {
  1105. jack_log("JackCoreAudioDriver::Stop");
  1106. AudioDeviceStop(fDeviceID, MeasureCallback);
  1107. /*
  1108. #ifdef MAC_OS_X_VERSION_10_5
  1109. AudioDeviceDestroyIOProcID(fDeviceID, fMesureCallbackID);
  1110. #else
  1111. AudioDeviceRemoveIOProc(fDeviceID, MeasureCallback);
  1112. #endif
  1113. */
  1114. AudioDeviceRemoveIOProc(fDeviceID, MeasureCallback);
  1115. return (AudioOutputUnitStop(fAUHAL) == noErr) ? 0 : -1;
  1116. }
  1117. int JackCoreAudioDriver::SetBufferSize(jack_nframes_t buffer_size)
  1118. {
  1119. OSStatus err;
  1120. UInt32 outSize = sizeof(UInt32);
  1121. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
  1122. if (err != noErr) {
  1123. jack_error("Cannot set buffer size %ld", buffer_size);
  1124. printError(err);
  1125. return -1;
  1126. }
  1127. JackAudioDriver::SetBufferSize(buffer_size); // never fails
  1128. // Input buffers do no change : prepare them only once
  1129. for (int i = 0; i < fCaptureChannels; i++) {
  1130. fJackInputData->mBuffers[i].mNumberChannels = 1;
  1131. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(float);
  1132. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1133. }
  1134. return 0;
  1135. }
  1136. bool JackCoreAudioDriver::TakeHog(AudioDeviceID deviceID, bool isInput)
  1137. {
  1138. pid_t hog_pid;
  1139. OSStatus err;
  1140. UInt32 propSize = sizeof(hog_pid);
  1141. err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyHogMode, &propSize, &hog_pid);
  1142. if (err) {
  1143. jack_error("Cannot read hog state...");
  1144. printError(err);
  1145. }
  1146. if (hog_pid != getpid()) {
  1147. hog_pid = getpid();
  1148. err = AudioDeviceSetProperty(deviceID, 0, 0, isInput, kAudioDevicePropertyHogMode, propSize, &hog_pid);
  1149. if (err != noErr) {
  1150. jack_error("Can't hog device = %d because it's being hogged by another program", deviceID);
  1151. return false;
  1152. }
  1153. }
  1154. return true;
  1155. }
  1156. } // end of namespace
  1157. #ifdef __cplusplus
  1158. extern "C"
  1159. {
  1160. #endif
  1161. SERVER_EXPORT jack_driver_desc_t* driver_get_descriptor()
  1162. {
  1163. jack_driver_desc_t *desc;
  1164. unsigned int i;
  1165. desc = (jack_driver_desc_t*)calloc(1, sizeof(jack_driver_desc_t));
  1166. strcpy(desc->name, "coreaudio"); // size MUST be less then JACK_DRIVER_NAME_MAX + 1
  1167. strcpy(desc->desc, "Apple CoreAudio API based audio backend"); // size MUST be less then JACK_DRIVER_PARAM_DESC + 1
  1168. desc->nparams = 15;
  1169. desc->params = (jack_driver_param_desc_t*)calloc(desc->nparams, sizeof(jack_driver_param_desc_t));
  1170. i = 0;
  1171. strcpy(desc->params[i].name, "channels");
  1172. desc->params[i].character = 'c';
  1173. desc->params[i].type = JackDriverParamInt;
  1174. desc->params[i].value.ui = 0;
  1175. strcpy(desc->params[i].short_desc, "Maximum number of channels");
  1176. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1177. i++;
  1178. strcpy(desc->params[i].name, "inchannels");
  1179. desc->params[i].character = 'i';
  1180. desc->params[i].type = JackDriverParamInt;
  1181. desc->params[i].value.ui = 0;
  1182. strcpy(desc->params[i].short_desc, "Maximum number of input channels");
  1183. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1184. i++;
  1185. strcpy(desc->params[i].name, "outchannels");
  1186. desc->params[i].character = 'o';
  1187. desc->params[i].type = JackDriverParamInt;
  1188. desc->params[i].value.ui = 0;
  1189. strcpy(desc->params[i].short_desc, "Maximum number of output channels");
  1190. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1191. i++;
  1192. strcpy(desc->params[i].name, "capture");
  1193. desc->params[i].character = 'C';
  1194. desc->params[i].type = JackDriverParamString;
  1195. strcpy(desc->params[i].value.str, "will take default CoreAudio input device");
  1196. strcpy(desc->params[i].short_desc, "Provide capture ports. Optionally set CoreAudio device name");
  1197. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1198. i++;
  1199. strcpy(desc->params[i].name, "playback");
  1200. desc->params[i].character = 'P';
  1201. desc->params[i].type = JackDriverParamString;
  1202. strcpy(desc->params[i].value.str, "will take default CoreAudio output device");
  1203. strcpy(desc->params[i].short_desc, "Provide playback ports. Optionally set CoreAudio device name");
  1204. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1205. i++;
  1206. strcpy (desc->params[i].name, "monitor");
  1207. desc->params[i].character = 'm';
  1208. desc->params[i].type = JackDriverParamBool;
  1209. desc->params[i].value.i = 0;
  1210. strcpy(desc->params[i].short_desc, "Provide monitor ports for the output");
  1211. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1212. i++;
  1213. strcpy(desc->params[i].name, "duplex");
  1214. desc->params[i].character = 'D';
  1215. desc->params[i].type = JackDriverParamBool;
  1216. desc->params[i].value.i = TRUE;
  1217. strcpy(desc->params[i].short_desc, "Provide both capture and playback ports");
  1218. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1219. i++;
  1220. strcpy(desc->params[i].name, "rate");
  1221. desc->params[i].character = 'r';
  1222. desc->params[i].type = JackDriverParamUInt;
  1223. desc->params[i].value.ui = 44100U;
  1224. strcpy(desc->params[i].short_desc, "Sample rate");
  1225. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1226. i++;
  1227. strcpy(desc->params[i].name, "period");
  1228. desc->params[i].character = 'p';
  1229. desc->params[i].type = JackDriverParamUInt;
  1230. desc->params[i].value.ui = 128U;
  1231. strcpy(desc->params[i].short_desc, "Frames per period");
  1232. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1233. i++;
  1234. strcpy(desc->params[i].name, "device");
  1235. desc->params[i].character = 'd';
  1236. desc->params[i].type = JackDriverParamString;
  1237. strcpy(desc->params[i].value.str, "will take default CoreAudio device name");
  1238. strcpy(desc->params[i].short_desc, "CoreAudio device name");
  1239. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1240. i++;
  1241. strcpy(desc->params[i].name, "input-latency");
  1242. desc->params[i].character = 'I';
  1243. desc->params[i].type = JackDriverParamUInt;
  1244. desc->params[i].value.i = 0;
  1245. strcpy(desc->params[i].short_desc, "Extra input latency (frames)");
  1246. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1247. i++;
  1248. strcpy(desc->params[i].name, "output-latency");
  1249. desc->params[i].character = 'O';
  1250. desc->params[i].type = JackDriverParamUInt;
  1251. desc->params[i].value.i = 0;
  1252. strcpy(desc->params[i].short_desc, "Extra output latency (frames)");
  1253. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1254. i++;
  1255. strcpy(desc->params[i].name, "list-devices");
  1256. desc->params[i].character = 'l';
  1257. desc->params[i].type = JackDriverParamBool;
  1258. desc->params[i].value.i = FALSE;
  1259. strcpy(desc->params[i].short_desc, "Display available CoreAudio devices");
  1260. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1261. i++;
  1262. strcpy(desc->params[i].name, "async-latency");
  1263. desc->params[i].character = 'L';
  1264. desc->params[i].type = JackDriverParamUInt;
  1265. desc->params[i].value.i = 100;
  1266. strcpy(desc->params[i].short_desc, "Extra output latency in asynchronous mode (percent)");
  1267. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1268. i++;
  1269. strcpy(desc->params[i].name, "grain");
  1270. desc->params[i].character = 'G';
  1271. desc->params[i].type = JackDriverParamUInt;
  1272. desc->params[i].value.i = 100;
  1273. strcpy(desc->params[i].short_desc, "Computation grain in RT thread (percent)");
  1274. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1275. return desc;
  1276. }
  1277. SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
  1278. {
  1279. jack_nframes_t srate = 44100;
  1280. jack_nframes_t frames_per_interrupt = 128;
  1281. int capture = FALSE;
  1282. int playback = FALSE;
  1283. int chan_in = 0;
  1284. int chan_out = 0;
  1285. bool monitor = false;
  1286. const char* capture_driver_uid = "";
  1287. const char* playback_driver_uid = "";
  1288. const JSList *node;
  1289. const jack_driver_param_t *param;
  1290. jack_nframes_t systemic_input_latency = 0;
  1291. jack_nframes_t systemic_output_latency = 0;
  1292. int async_output_latency = 100;
  1293. int computation_grain = -1;
  1294. for (node = params; node; node = jack_slist_next(node)) {
  1295. param = (const jack_driver_param_t *) node->data;
  1296. switch (param->character) {
  1297. case 'd':
  1298. capture_driver_uid = strdup(param->value.str);
  1299. playback_driver_uid = strdup(param->value.str);
  1300. break;
  1301. case 'D':
  1302. capture = TRUE;
  1303. playback = TRUE;
  1304. break;
  1305. case 'c':
  1306. chan_in = chan_out = (int) param->value.ui;
  1307. break;
  1308. case 'i':
  1309. chan_in = (int) param->value.ui;
  1310. break;
  1311. case 'o':
  1312. chan_out = (int) param->value.ui;
  1313. break;
  1314. case 'C':
  1315. capture = TRUE;
  1316. if (strcmp(param->value.str, "none") != 0) {
  1317. capture_driver_uid = strdup(param->value.str);
  1318. }
  1319. break;
  1320. case 'P':
  1321. playback = TRUE;
  1322. if (strcmp(param->value.str, "none") != 0) {
  1323. playback_driver_uid = strdup(param->value.str);
  1324. }
  1325. break;
  1326. case 'm':
  1327. monitor = param->value.i;
  1328. break;
  1329. case 'r':
  1330. srate = param->value.ui;
  1331. break;
  1332. case 'p':
  1333. frames_per_interrupt = (unsigned int) param->value.ui;
  1334. break;
  1335. case 'I':
  1336. systemic_input_latency = param->value.ui;
  1337. break;
  1338. case 'O':
  1339. systemic_output_latency = param->value.ui;
  1340. break;
  1341. case 'l':
  1342. Jack::DisplayDeviceNames();
  1343. break;
  1344. case 'L':
  1345. async_output_latency = param->value.ui;
  1346. break;
  1347. case 'G':
  1348. computation_grain = param->value.ui;
  1349. break;
  1350. }
  1351. }
  1352. /* duplex is the default */
  1353. if (!capture && !playback) {
  1354. capture = TRUE;
  1355. playback = TRUE;
  1356. }
  1357. Jack::JackCoreAudioDriver* driver = new Jack::JackCoreAudioDriver("system", "coreaudio", engine, table);
  1358. if (driver->Open(frames_per_interrupt, srate, capture, playback, chan_in, chan_out, monitor, capture_driver_uid,
  1359. playback_driver_uid, systemic_input_latency, systemic_output_latency, async_output_latency, computation_grain) == 0) {
  1360. return driver;
  1361. } else {
  1362. delete driver;
  1363. return NULL;
  1364. }
  1365. }
  1366. #ifdef __cplusplus
  1367. }
  1368. #endif