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.

1671 lines
62KB

  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),
  338. fJackInputData(NULL),
  339. fDriverOutputData(NULL),
  340. fPluginID(0),
  341. fState(false),
  342. fHogged(false),
  343. fIOUsage(1.f),
  344. fComputationGrain(-1.f)
  345. {}
  346. JackCoreAudioDriver::~JackCoreAudioDriver()
  347. {}
  348. OSStatus JackCoreAudioDriver::DestroyAggregateDevice()
  349. {
  350. OSStatus osErr = noErr;
  351. AudioObjectPropertyAddress pluginAOPA;
  352. pluginAOPA.mSelector = kAudioPlugInDestroyAggregateDevice;
  353. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  354. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  355. UInt32 outDataSize;
  356. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  357. if (osErr != noErr) {
  358. jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyDataSize error");
  359. printError(osErr);
  360. return osErr;
  361. }
  362. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, 0, NULL, &outDataSize, &fDeviceID);
  363. if (osErr != noErr) {
  364. jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyData error");
  365. printError(osErr);
  366. return osErr;
  367. }
  368. return noErr;
  369. }
  370. OSStatus JackCoreAudioDriver::CreateAggregateDevice(AudioDeviceID captureDeviceID, AudioDeviceID playbackDeviceID, AudioDeviceID* outAggregateDevice)
  371. {
  372. OSStatus osErr = noErr;
  373. UInt32 outSize;
  374. Boolean outWritable;
  375. //---------------------------------------------------------------------------
  376. // Start to create a new aggregate by getting the base audio hardware plugin
  377. //---------------------------------------------------------------------------
  378. char capture_name[256];
  379. char playback_name[256];
  380. GetDeviceNameFromID(captureDeviceID, capture_name);
  381. GetDeviceNameFromID(playbackDeviceID, playback_name);
  382. jack_info("Separated input = '%s' and output = '%s' devices, create a private aggregate device to handle them...", capture_name, playback_name);
  383. osErr = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyPlugInForBundleID, &outSize, &outWritable);
  384. if (osErr != noErr)
  385. return osErr;
  386. AudioValueTranslation pluginAVT;
  387. CFStringRef inBundleRef = CFSTR("com.apple.audio.CoreAudio");
  388. pluginAVT.mInputData = &inBundleRef;
  389. pluginAVT.mInputDataSize = sizeof(inBundleRef);
  390. pluginAVT.mOutputData = &fPluginID;
  391. pluginAVT.mOutputDataSize = sizeof(fPluginID);
  392. osErr = AudioHardwareGetProperty(kAudioHardwarePropertyPlugInForBundleID, &outSize, &pluginAVT);
  393. if (osErr != noErr)
  394. return osErr;
  395. //-------------------------------------------------
  396. // Create a CFDictionary for our aggregate device
  397. //-------------------------------------------------
  398. CFMutableDictionaryRef aggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  399. CFStringRef AggregateDeviceNameRef = CFSTR("JackDuplex");
  400. CFStringRef AggregateDeviceUIDRef = CFSTR("com.grame.JackDuplex");
  401. // add the name of the device to the dictionary
  402. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceNameKey), AggregateDeviceNameRef);
  403. // add our choice of UID for the aggregate device to the dictionary
  404. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceUIDKey), AggregateDeviceUIDRef);
  405. // add a "private aggregate key" to the dictionary
  406. int value = 1;
  407. CFNumberRef AggregateDeviceNumberRef = CFNumberCreate(NULL, kCFNumberIntType, &value);
  408. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceIsPrivateKey), AggregateDeviceNumberRef);
  409. //-------------------------------------------------
  410. // Create a CFMutableArray for our sub-device list
  411. //-------------------------------------------------
  412. CFStringRef captureDeviceUID = GetDeviceName(captureDeviceID);
  413. CFStringRef playbackDeviceUID = GetDeviceName(playbackDeviceID);
  414. if (captureDeviceUID == NULL || playbackDeviceUID == NULL)
  415. return -1;
  416. // we need to append the UID for each device to a CFMutableArray, so create one here
  417. CFMutableArrayRef subDevicesArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  418. // two sub-devices in this example, so append the sub-device's UID to the CFArray
  419. CFArrayAppendValue(subDevicesArray, captureDeviceUID);
  420. CFArrayAppendValue(subDevicesArray, playbackDeviceUID);
  421. //-----------------------------------------------------------------------
  422. // Feed the dictionary to the plugin, to create a blank aggregate device
  423. //-----------------------------------------------------------------------
  424. AudioObjectPropertyAddress pluginAOPA;
  425. pluginAOPA.mSelector = kAudioPlugInCreateAggregateDevice;
  426. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  427. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  428. UInt32 outDataSize;
  429. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  430. if (osErr != noErr)
  431. return osErr;
  432. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, sizeof(aggDeviceDict), &aggDeviceDict, &outDataSize, outAggregateDevice);
  433. if (osErr != noErr)
  434. return osErr;
  435. // pause for a bit to make sure that everything completed correctly
  436. // this is to work around a bug in the HAL where a new aggregate device seems to disappear briefly after it is created
  437. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  438. //-------------------------
  439. // Set the sub-device list
  440. //-------------------------
  441. pluginAOPA.mSelector = kAudioAggregateDevicePropertyFullSubDeviceList;
  442. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  443. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  444. outDataSize = sizeof(CFMutableArrayRef);
  445. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &subDevicesArray);
  446. if (osErr != noErr)
  447. return osErr;
  448. // pause again to give the changes time to take effect
  449. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  450. //-----------------------
  451. // Set the master device
  452. //-----------------------
  453. // set the master device manually (this is the device which will act as the master clock for the aggregate device)
  454. // pass in the UID of the device you want to use
  455. pluginAOPA.mSelector = kAudioAggregateDevicePropertyMasterSubDevice;
  456. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  457. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  458. outDataSize = sizeof(CFStringRef);
  459. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &captureDeviceUID); // capture is master...
  460. if (osErr != noErr)
  461. return osErr;
  462. // pause again to give the changes time to take effect
  463. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  464. //----------
  465. // Clean up
  466. //----------
  467. CFRelease(AggregateDeviceNumberRef);
  468. // release the CF objects we have created - we don't need them any more
  469. CFRelease(aggDeviceDict);
  470. CFRelease(subDevicesArray);
  471. // release the device UID
  472. CFRelease(captureDeviceUID);
  473. CFRelease(playbackDeviceUID);
  474. jack_log("New aggregate device %ld", *outAggregateDevice);
  475. return noErr;
  476. }
  477. int JackCoreAudioDriver::SetupDevices(const char* capture_driver_uid, const char* playback_driver_uid, char* capture_driver_name, char* playback_driver_name)
  478. {
  479. capture_driver_name[0] = 0;
  480. playback_driver_name[0] = 0;
  481. // Duplex
  482. if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
  483. jack_log("JackCoreAudioDriver::Open duplex");
  484. // Same device for capture and playback...
  485. if (strcmp(capture_driver_uid, playback_driver_uid) == 0) {
  486. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  487. jack_log("Will take default in/out");
  488. if (GetDefaultDevice(&fDeviceID) != noErr) {
  489. jack_error("Cannot open default device");
  490. return -1;
  491. }
  492. }
  493. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  494. jack_error("Cannot get device name from device ID");
  495. return -1;
  496. }
  497. } else {
  498. // Creates aggregate device
  499. AudioDeviceID captureID, playbackID;
  500. if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr)
  501. return -1;
  502. if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr)
  503. return -1;
  504. if (CreateAggregateDevice(captureID, playbackID, &fDeviceID) != noErr)
  505. return -1;
  506. }
  507. // Capture only
  508. } else if (strcmp(capture_driver_uid, "") != 0) {
  509. jack_log("JackCoreAudioDriver::Open capture only");
  510. if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
  511. jack_log("Will take default input");
  512. if (GetDefaultInputDevice(&fDeviceID) != noErr) {
  513. jack_error("Cannot open default device");
  514. return -1;
  515. }
  516. }
  517. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
  518. jack_error("Cannot get device name from device ID");
  519. return -1;
  520. }
  521. // Playback only
  522. } else if (strcmp(playback_driver_uid, "") != 0) {
  523. jack_log("JackCoreAudioDriver::Open playback only");
  524. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  525. jack_log("Will take default output");
  526. if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
  527. jack_error("Cannot open default device");
  528. return -1;
  529. }
  530. }
  531. if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  532. jack_error("Cannot get device name from device ID");
  533. return -1;
  534. }
  535. // Use default driver in duplex mode
  536. } else {
  537. jack_log("JackCoreAudioDriver::Open default driver");
  538. if (GetDefaultDevice(&fDeviceID) != noErr) {
  539. jack_error("Cannot open default device");
  540. return -1;
  541. }
  542. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  543. jack_error("Cannot get device name from device ID");
  544. return -1;
  545. }
  546. }
  547. if (fHogged) {
  548. if (TakeHog()) {
  549. jack_info("Device = %ld has been hogged", fDeviceID);
  550. } else {
  551. jack_error("Cannot hog device = %ld", fDeviceID);
  552. }
  553. }
  554. return 0;
  555. }
  556. /*
  557. Return the max possible input channels in in_nChannels and output channels in out_nChannels.
  558. */
  559. int JackCoreAudioDriver::SetupChannels(bool capturing, bool playing, int& inchannels, int& outchannels, int& in_nChannels, int& out_nChannels, bool strict)
  560. {
  561. OSStatus err = noErr;
  562. if (capturing) {
  563. err = GetTotalChannels(fDeviceID, in_nChannels, true);
  564. if (err != noErr) {
  565. jack_error("Cannot get input channel number");
  566. printError(err);
  567. return -1;
  568. } else {
  569. jack_log("Max input channels : %d", in_nChannels);
  570. }
  571. }
  572. if (playing) {
  573. err = GetTotalChannels(fDeviceID, out_nChannels, false);
  574. if (err != noErr) {
  575. jack_error("Cannot get output channel number");
  576. printError(err);
  577. return -1;
  578. } else {
  579. jack_log("Max output channels : %d", out_nChannels);
  580. }
  581. }
  582. if (inchannels > in_nChannels) {
  583. jack_error("This device hasn't required input channels inchannels = %d in_nChannels = %d", inchannels, in_nChannels);
  584. if (strict)
  585. return -1;
  586. }
  587. if (outchannels > out_nChannels) {
  588. jack_error("This device hasn't required output channels outchannels = %d out_nChannels = %d", outchannels, out_nChannels);
  589. if (strict)
  590. return -1;
  591. }
  592. if (inchannels == 0) {
  593. jack_log("Setup max in channels = %d", in_nChannels);
  594. inchannels = in_nChannels;
  595. }
  596. if (outchannels == 0) {
  597. jack_log("Setup max out channels = %d", out_nChannels);
  598. outchannels = out_nChannels;
  599. }
  600. return 0;
  601. }
  602. int JackCoreAudioDriver::SetupBufferSizeAndSampleRate(jack_nframes_t buffer_size, jack_nframes_t samplerate)
  603. {
  604. OSStatus err = noErr;
  605. UInt32 outSize;
  606. Float64 sampleRate;
  607. // Setting buffer size
  608. outSize = sizeof(UInt32);
  609. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
  610. if (err != noErr) {
  611. jack_error("Cannot set buffer size %ld", buffer_size);
  612. printError(err);
  613. return -1;
  614. }
  615. // Get sample rate
  616. outSize = sizeof(Float64);
  617. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
  618. if (err != noErr) {
  619. jack_error("Cannot get current sample rate");
  620. printError(err);
  621. return -1;
  622. }
  623. // If needed, set new sample rate
  624. if (samplerate != (jack_nframes_t)sampleRate) {
  625. sampleRate = (Float64)samplerate;
  626. // To get SR change notification
  627. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback, this);
  628. if (err != noErr) {
  629. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  630. printError(err);
  631. return -1;
  632. }
  633. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &sampleRate);
  634. if (err != noErr) {
  635. jack_error("Cannot set sample rate = %ld", samplerate);
  636. printError(err);
  637. return -1;
  638. }
  639. // Waiting for SR change notification
  640. int count = 0;
  641. while (!fState && count++ < 100) {
  642. usleep(100000);
  643. jack_log("Wait count = %d", count);
  644. }
  645. // Remove SR change notification
  646. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
  647. }
  648. return 0;
  649. }
  650. int JackCoreAudioDriver::OpenAUHAL(bool capturing,
  651. bool playing,
  652. int inchannels,
  653. int outchannels,
  654. int in_nChannels,
  655. int out_nChannels,
  656. jack_nframes_t buffer_size,
  657. jack_nframes_t samplerate,
  658. bool strict)
  659. {
  660. ComponentResult err1;
  661. UInt32 enableIO;
  662. AudioStreamBasicDescription srcFormat, dstFormat;
  663. 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);
  664. if (inchannels == 0 && outchannels == 0) {
  665. jack_error("No input and output channels...");
  666. return -1;
  667. }
  668. // AUHAL
  669. ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
  670. Component HALOutput = FindNextComponent(NULL, &cd);
  671. err1 = OpenAComponent(HALOutput, &fAUHAL);
  672. if (err1 != noErr) {
  673. jack_error("Error calling OpenAComponent");
  674. printError(err1);
  675. return -1;
  676. }
  677. err1 = AudioUnitInitialize(fAUHAL);
  678. if (err1 != noErr) {
  679. jack_error("Cannot initialize AUHAL unit");
  680. printError(err1);
  681. return -1;
  682. }
  683. // Start I/O
  684. if (capturing && inchannels > 0) {
  685. enableIO = 1;
  686. jack_log("Setup AUHAL input on");
  687. } else {
  688. enableIO = 0;
  689. jack_log("Setup AUHAL input off");
  690. }
  691. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
  692. if (err1 != noErr) {
  693. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
  694. printError(err1);
  695. if (strict)
  696. return -1;
  697. }
  698. if (playing && outchannels > 0) {
  699. enableIO = 1;
  700. jack_log("Setup AUHAL output on");
  701. } else {
  702. enableIO = 0;
  703. jack_log("Setup AUHAL output off");
  704. }
  705. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
  706. if (err1 != noErr) {
  707. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
  708. printError(err1);
  709. if (strict)
  710. return -1;
  711. }
  712. AudioDeviceID currAudioDeviceID;
  713. UInt32 size = sizeof(AudioDeviceID);
  714. err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
  715. if (err1 != noErr) {
  716. jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
  717. printError(err1);
  718. if (strict)
  719. return -1;
  720. } else {
  721. jack_log("AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
  722. }
  723. // Setup up choosen device, in both input and output cases
  724. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
  725. if (err1 != noErr) {
  726. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
  727. printError(err1);
  728. if (strict)
  729. return -1;
  730. }
  731. // Set buffer size
  732. if (capturing && inchannels > 0) {
  733. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*)&buffer_size, sizeof(UInt32));
  734. if (err1 != noErr) {
  735. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  736. printError(err1);
  737. if (strict)
  738. return -1;
  739. }
  740. }
  741. if (playing && outchannels > 0) {
  742. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*)&buffer_size, sizeof(UInt32));
  743. if (err1 != noErr) {
  744. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  745. printError(err1);
  746. if (strict)
  747. return -1;
  748. }
  749. }
  750. // Setup channel map
  751. if (capturing && inchannels > 0 && inchannels < in_nChannels) {
  752. SInt32 chanArr[in_nChannels];
  753. for (int i = 0; i < in_nChannels; i++) {
  754. chanArr[i] = -1;
  755. }
  756. for (int i = 0; i < inchannels; i++) {
  757. chanArr[i] = i;
  758. }
  759. AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
  760. if (err1 != noErr) {
  761. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 1");
  762. printError(err1);
  763. }
  764. }
  765. if (playing && outchannels > 0 && outchannels < out_nChannels) {
  766. SInt32 chanArr[out_nChannels];
  767. for (int i = 0; i < out_nChannels; i++) {
  768. chanArr[i] = -1;
  769. }
  770. for (int i = 0; i < outchannels; i++) {
  771. chanArr[i] = i;
  772. }
  773. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
  774. if (err1 != noErr) {
  775. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 0");
  776. printError(err1);
  777. }
  778. }
  779. // Setup stream converters
  780. jack_log("Setup AUHAL input stream converter SR = %ld", samplerate);
  781. srcFormat.mSampleRate = samplerate;
  782. srcFormat.mFormatID = kAudioFormatLinearPCM;
  783. srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  784. srcFormat.mBytesPerPacket = sizeof(float);
  785. srcFormat.mFramesPerPacket = 1;
  786. srcFormat.mBytesPerFrame = sizeof(float);
  787. srcFormat.mChannelsPerFrame = outchannels;
  788. srcFormat.mBitsPerChannel = 32;
  789. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &srcFormat, sizeof(AudioStreamBasicDescription));
  790. if (err1 != noErr) {
  791. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  792. printError(err1);
  793. }
  794. jack_log("Setup AUHAL output stream converter SR = %ld", samplerate);
  795. dstFormat.mSampleRate = samplerate;
  796. dstFormat.mFormatID = kAudioFormatLinearPCM;
  797. dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  798. dstFormat.mBytesPerPacket = sizeof(float);
  799. dstFormat.mFramesPerPacket = 1;
  800. dstFormat.mBytesPerFrame = sizeof(float);
  801. dstFormat.mChannelsPerFrame = inchannels;
  802. dstFormat.mBitsPerChannel = 32;
  803. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &dstFormat, sizeof(AudioStreamBasicDescription));
  804. if (err1 != noErr) {
  805. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  806. printError(err1);
  807. }
  808. // Setup callbacks
  809. if (inchannels > 0 && outchannels == 0) {
  810. AURenderCallbackStruct output;
  811. output.inputProc = Render;
  812. output.inputProcRefCon = this;
  813. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
  814. if (err1 != noErr) {
  815. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
  816. printError(err1);
  817. return -1;
  818. }
  819. } else {
  820. AURenderCallbackStruct output;
  821. output.inputProc = Render;
  822. output.inputProcRefCon = this;
  823. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
  824. if (err1 != noErr) {
  825. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
  826. printError(err1);
  827. return -1;
  828. }
  829. }
  830. return 0;
  831. }
  832. int JackCoreAudioDriver::SetupBuffers(int inchannels)
  833. {
  834. // Prepare buffers
  835. fJackInputData = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
  836. if (fJackInputData == 0) {
  837. jack_error("Cannot allocate memory for input buffers");
  838. return -1;
  839. }
  840. fJackInputData->mNumberBuffers = inchannels;
  841. for (int i = 0; i < fCaptureChannels; i++) {
  842. fJackInputData->mBuffers[i].mNumberChannels = 1;
  843. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(float);
  844. }
  845. return 0;
  846. }
  847. void JackCoreAudioDriver::DisposeBuffers()
  848. {
  849. if (fJackInputData) {
  850. free(fJackInputData);
  851. fJackInputData = 0;
  852. }
  853. }
  854. void JackCoreAudioDriver::CloseAUHAL()
  855. {
  856. AudioUnitUninitialize(fAUHAL);
  857. CloseComponent(fAUHAL);
  858. }
  859. int JackCoreAudioDriver::AddListeners()
  860. {
  861. OSStatus err = noErr;
  862. // Add listeners
  863. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback, this);
  864. if (err != noErr) {
  865. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDeviceProcessorOverload");
  866. printError(err);
  867. return -1;
  868. }
  869. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback, this);
  870. if (err != noErr) {
  871. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioHardwarePropertyDevices");
  872. printError(err);
  873. return -1;
  874. }
  875. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback, this);
  876. if (err != noErr) {
  877. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  878. printError(err);
  879. return -1;
  880. }
  881. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback, this);
  882. if (err != noErr) {
  883. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsRunning");
  884. printError(err);
  885. return -1;
  886. }
  887. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  888. if (err != noErr) {
  889. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  890. printError(err);
  891. return -1;
  892. }
  893. err = AudioDeviceAddPropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  894. if (err != noErr) {
  895. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  896. printError(err);
  897. return -1;
  898. }
  899. if (!fEngineControl->fSyncMode && fIOUsage != 1.f) {
  900. UInt32 outSize = sizeof(float);
  901. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyIOCycleUsage, outSize, &fIOUsage);
  902. if (err != noErr) {
  903. jack_error("Error calling AudioDeviceSetProperty kAudioDevicePropertyIOCycleUsage");
  904. printError(err);
  905. }
  906. }
  907. return 0;
  908. }
  909. void JackCoreAudioDriver::RemoveListeners()
  910. {
  911. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback);
  912. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback);
  913. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback);
  914. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback);
  915. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  916. AudioDeviceRemovePropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  917. }
  918. int JackCoreAudioDriver::Open(jack_nframes_t buffer_size,
  919. jack_nframes_t samplerate,
  920. bool capturing,
  921. bool playing,
  922. int inchannels,
  923. int outchannels,
  924. bool monitor,
  925. const char* capture_driver_uid,
  926. const char* playback_driver_uid,
  927. jack_nframes_t capture_latency,
  928. jack_nframes_t playback_latency,
  929. int async_output_latency,
  930. int computation_grain,
  931. bool hogged)
  932. {
  933. int in_nChannels = 0;
  934. int out_nChannels = 0;
  935. char capture_driver_name[256];
  936. char playback_driver_name[256];
  937. // Keep initial state
  938. fCapturing = capturing;
  939. fPlaying = playing;
  940. fInChannels = inchannels;
  941. fOutChannels = outchannels;
  942. fMonitor = monitor;
  943. strcpy(fCaptureUID, capture_driver_uid);
  944. strcpy(fPlaybackUID, playback_driver_uid);
  945. fCaptureLatency = capture_latency;
  946. fPlaybackLatency = playback_latency;
  947. fIOUsage = float(async_output_latency) / 100.f;
  948. fComputationGrain = float(computation_grain) / 100.f;
  949. fHogged = hogged;
  950. SInt32 major;
  951. SInt32 minor;
  952. Gestalt(gestaltSystemVersionMajor, &major);
  953. Gestalt(gestaltSystemVersionMinor, &minor);
  954. // Starting with 10.6 systems, the HAL notification thread is created internally
  955. if (major == 10 && minor >=6) {
  956. CFRunLoopRef theRunLoop = NULL;
  957. AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  958. OSStatus theError = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
  959. if (theError != noErr) {
  960. jack_error("JackCoreAudioDriver::Open kAudioHardwarePropertyRunLoop error");
  961. }
  962. }
  963. if (SetupDevices(capture_driver_uid, playback_driver_uid, capture_driver_name, playback_driver_name) < 0)
  964. return -1;
  965. // Generic JackAudioDriver Open
  966. if (JackAudioDriver::Open(buffer_size, samplerate, capturing, playing, inchannels, outchannels, monitor, capture_driver_name, playback_driver_name, capture_latency, playback_latency) != 0)
  967. return -1;
  968. if (SetupChannels(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, true) < 0)
  969. return -1;
  970. if (SetupBufferSizeAndSampleRate(buffer_size, samplerate) < 0)
  971. return -1;
  972. if (OpenAUHAL(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, buffer_size, samplerate, true) < 0)
  973. goto error;
  974. if (capturing && inchannels > 0)
  975. if (SetupBuffers(inchannels) < 0)
  976. goto error;
  977. if (AddListeners() < 0)
  978. goto error;
  979. // Core driver may have changed the in/out values
  980. fCaptureChannels = inchannels;
  981. fPlaybackChannels = outchannels;
  982. return noErr;
  983. error:
  984. Close();
  985. return -1;
  986. }
  987. int JackCoreAudioDriver::Close()
  988. {
  989. jack_log("JackCoreAudioDriver::Close");
  990. Stop();
  991. JackAudioDriver::Close();
  992. RemoveListeners();
  993. DisposeBuffers();
  994. CloseAUHAL();
  995. if (fPluginID > 0)
  996. DestroyAggregateDevice();
  997. return 0;
  998. }
  999. int JackCoreAudioDriver::Attach()
  1000. {
  1001. OSStatus err;
  1002. JackPort* port;
  1003. jack_port_id_t port_index;
  1004. UInt32 size;
  1005. Boolean isWritable;
  1006. char channel_name[64];
  1007. char name[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  1008. char alias[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  1009. unsigned long port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
  1010. jack_log("JackCoreAudioDriver::Attach fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
  1011. for (int i = 0; i < fCaptureChannels; i++) {
  1012. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, &isWritable);
  1013. if (err != noErr)
  1014. jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error ");
  1015. if (err == noErr && size > 0) {
  1016. err = AudioDeviceGetProperty(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, channel_name);
  1017. if (err != noErr)
  1018. jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error ");
  1019. snprintf(alias, sizeof(alias) - 1, "%s:%s:out_%s%u", fAliasName, fCaptureDriverName, channel_name, i + 1);
  1020. } else {
  1021. snprintf(alias, sizeof(alias) - 1, "%s:%s:out%u", fAliasName, fCaptureDriverName, i + 1);
  1022. }
  1023. snprintf(name, sizeof(name) - 1, "%s:capture_%d", fClientControl.fName, i + 1);
  1024. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
  1025. jack_error("Cannot register port for %s", name);
  1026. return -1;
  1027. }
  1028. size = sizeof(UInt32);
  1029. UInt32 value1 = 0;
  1030. UInt32 value2 = 0;
  1031. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertyLatency, &size, &value1);
  1032. if (err != noErr)
  1033. jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error ");
  1034. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertySafetyOffset, &size, &value2);
  1035. if (err != noErr)
  1036. jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error ");
  1037. port = fGraphManager->GetPort(port_index);
  1038. port->SetAlias(alias);
  1039. port->SetLatency(fEngineControl->fBufferSize + value1 + value2 + fCaptureLatency);
  1040. fCapturePortList[i] = port_index;
  1041. }
  1042. port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
  1043. for (int i = 0; i < fPlaybackChannels; i++) {
  1044. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, &isWritable);
  1045. if (err != noErr)
  1046. jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error ");
  1047. if (err == noErr && size > 0) {
  1048. err = AudioDeviceGetProperty(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, channel_name);
  1049. if (err != noErr)
  1050. jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error ");
  1051. snprintf(alias, sizeof(alias) - 1, "%s:%s:in_%s%u", fAliasName, fPlaybackDriverName, channel_name, i + 1);
  1052. } else {
  1053. snprintf(alias, sizeof(alias) - 1, "%s:%s:in%u", fAliasName, fPlaybackDriverName, i + 1);
  1054. }
  1055. snprintf(name, sizeof(name) - 1, "%s:playback_%d", fClientControl.fName, i + 1);
  1056. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize)) == NO_PORT) {
  1057. jack_error("Cannot register port for %s", name);
  1058. return -1;
  1059. }
  1060. size = sizeof(UInt32);
  1061. UInt32 value1 = 0;
  1062. UInt32 value2 = 0;
  1063. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertyLatency, &size, &value1);
  1064. if (err != noErr)
  1065. jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error ");
  1066. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertySafetyOffset, &size, &value2);
  1067. if (err != noErr)
  1068. jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error ");
  1069. port = fGraphManager->GetPort(port_index);
  1070. port->SetAlias(alias);
  1071. // Add more latency if "async" mode is used...
  1072. port->SetLatency(fEngineControl->fBufferSize + ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize * fIOUsage) + value1 + value2 + fPlaybackLatency);
  1073. fPlaybackPortList[i] = port_index;
  1074. // Monitor ports
  1075. if (fWithMonitorPorts) {
  1076. jack_log("Create monitor port ");
  1077. snprintf(name, sizeof(name) - 1, "%s:monitor_%u", fClientControl.fName, i + 1);
  1078. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, fEngineControl->fBufferSize)) == NO_PORT) {
  1079. jack_error("Cannot register monitor port for %s", name);
  1080. return -1;
  1081. } else {
  1082. port = fGraphManager->GetPort(port_index);
  1083. port->SetAlias(alias);
  1084. port->SetLatency(fEngineControl->fBufferSize);
  1085. fMonitorPortList[i] = port_index;
  1086. }
  1087. }
  1088. }
  1089. // Input buffers do no change : prepare them only once
  1090. for (int i = 0; i < fCaptureChannels; i++) {
  1091. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1092. }
  1093. return 0;
  1094. }
  1095. int JackCoreAudioDriver::Start()
  1096. {
  1097. jack_log("JackCoreAudioDriver::Start");
  1098. JackAudioDriver::Start();
  1099. /*
  1100. #ifdef MAC_OS_X_VERSION_10_5
  1101. OSStatus err = AudioDeviceCreateIOProcID(fDeviceID, MeasureCallback, this, &fMesureCallbackID);
  1102. #else
  1103. OSStatus err = AudioDeviceAddIOProc(fDeviceID, MeasureCallback, this);
  1104. #endif
  1105. */
  1106. OSStatus err = AudioDeviceAddIOProc(fDeviceID, MeasureCallback, this);
  1107. if (err != noErr)
  1108. return -1;
  1109. err = AudioOutputUnitStart(fAUHAL);
  1110. if (err != noErr)
  1111. return -1;
  1112. if ((err = AudioDeviceStart(fDeviceID, MeasureCallback)) != noErr) {
  1113. jack_error("Cannot start MeasureCallback");
  1114. printError(err);
  1115. return -1;
  1116. }
  1117. return 0;
  1118. }
  1119. int JackCoreAudioDriver::Stop()
  1120. {
  1121. jack_log("JackCoreAudioDriver::Stop");
  1122. AudioDeviceStop(fDeviceID, MeasureCallback);
  1123. /*
  1124. #ifdef MAC_OS_X_VERSION_10_5
  1125. AudioDeviceDestroyIOProcID(fDeviceID, fMesureCallbackID);
  1126. #else
  1127. AudioDeviceRemoveIOProc(fDeviceID, MeasureCallback);
  1128. #endif
  1129. */
  1130. AudioDeviceRemoveIOProc(fDeviceID, MeasureCallback);
  1131. return (AudioOutputUnitStop(fAUHAL) == noErr) ? 0 : -1;
  1132. }
  1133. int JackCoreAudioDriver::SetBufferSize(jack_nframes_t buffer_size)
  1134. {
  1135. OSStatus err;
  1136. UInt32 outSize = sizeof(UInt32);
  1137. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
  1138. if (err != noErr) {
  1139. jack_error("Cannot set buffer size %ld", buffer_size);
  1140. printError(err);
  1141. return -1;
  1142. }
  1143. JackAudioDriver::SetBufferSize(buffer_size); // never fails
  1144. // Input buffers do no change : prepare them only once
  1145. for (int i = 0; i < fCaptureChannels; i++) {
  1146. fJackInputData->mBuffers[i].mNumberChannels = 1;
  1147. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(float);
  1148. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1149. }
  1150. return 0;
  1151. }
  1152. bool JackCoreAudioDriver::TakeHogAux(AudioDeviceID deviceID, bool isInput)
  1153. {
  1154. pid_t hog_pid;
  1155. OSStatus err;
  1156. UInt32 propSize = sizeof(hog_pid);
  1157. err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyHogMode, &propSize, &hog_pid);
  1158. if (err) {
  1159. jack_error("Cannot read hog state...");
  1160. printError(err);
  1161. }
  1162. if (hog_pid != getpid()) {
  1163. hog_pid = getpid();
  1164. err = AudioDeviceSetProperty(deviceID, 0, 0, isInput, kAudioDevicePropertyHogMode, propSize, &hog_pid);
  1165. if (err != noErr) {
  1166. jack_error("Can't hog device = %d because it's being hogged by another program", deviceID);
  1167. return false;
  1168. }
  1169. }
  1170. return true;
  1171. }
  1172. bool JackCoreAudioDriver::TakeHog()
  1173. {
  1174. OSStatus err = noErr;
  1175. AudioObjectID sub_device[32];
  1176. UInt32 outSize = sizeof(sub_device);
  1177. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  1178. if (err != noErr) {
  1179. jack_log("Device does not have subdevices");
  1180. return TakeHogAux(fDeviceID, true);
  1181. } else {
  1182. int num_devices = outSize / sizeof(AudioObjectID);
  1183. jack_log("Device does has %d subdevices", num_devices);
  1184. for (int i = 0; i < num_devices; i++) {
  1185. if (!TakeHogAux(sub_device[i], true)) {
  1186. return false;
  1187. }
  1188. }
  1189. return true;
  1190. }
  1191. }
  1192. } // end of namespace
  1193. #ifdef __cplusplus
  1194. extern "C"
  1195. {
  1196. #endif
  1197. SERVER_EXPORT jack_driver_desc_t* driver_get_descriptor()
  1198. {
  1199. jack_driver_desc_t *desc;
  1200. unsigned int i;
  1201. desc = (jack_driver_desc_t*)calloc(1, sizeof(jack_driver_desc_t));
  1202. strcpy(desc->name, "coreaudio"); // size MUST be less then JACK_DRIVER_NAME_MAX + 1
  1203. strcpy(desc->desc, "Apple CoreAudio API based audio backend"); // size MUST be less then JACK_DRIVER_PARAM_DESC + 1
  1204. desc->nparams = 16;
  1205. desc->params = (jack_driver_param_desc_t*)calloc(desc->nparams, sizeof(jack_driver_param_desc_t));
  1206. i = 0;
  1207. strcpy(desc->params[i].name, "channels");
  1208. desc->params[i].character = 'c';
  1209. desc->params[i].type = JackDriverParamInt;
  1210. desc->params[i].value.ui = 0;
  1211. strcpy(desc->params[i].short_desc, "Maximum number of channels");
  1212. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1213. i++;
  1214. strcpy(desc->params[i].name, "inchannels");
  1215. desc->params[i].character = 'i';
  1216. desc->params[i].type = JackDriverParamInt;
  1217. desc->params[i].value.ui = 0;
  1218. strcpy(desc->params[i].short_desc, "Maximum number of input channels");
  1219. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1220. i++;
  1221. strcpy(desc->params[i].name, "outchannels");
  1222. desc->params[i].character = 'o';
  1223. desc->params[i].type = JackDriverParamInt;
  1224. desc->params[i].value.ui = 0;
  1225. strcpy(desc->params[i].short_desc, "Maximum number of output channels");
  1226. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1227. i++;
  1228. strcpy(desc->params[i].name, "capture");
  1229. desc->params[i].character = 'C';
  1230. desc->params[i].type = JackDriverParamString;
  1231. strcpy(desc->params[i].value.str, "will take default CoreAudio input device");
  1232. strcpy(desc->params[i].short_desc, "Provide capture ports. Optionally set CoreAudio device name");
  1233. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1234. i++;
  1235. strcpy(desc->params[i].name, "playback");
  1236. desc->params[i].character = 'P';
  1237. desc->params[i].type = JackDriverParamString;
  1238. strcpy(desc->params[i].value.str, "will take default CoreAudio output device");
  1239. strcpy(desc->params[i].short_desc, "Provide playback ports. Optionally set CoreAudio device name");
  1240. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1241. i++;
  1242. strcpy (desc->params[i].name, "monitor");
  1243. desc->params[i].character = 'm';
  1244. desc->params[i].type = JackDriverParamBool;
  1245. desc->params[i].value.i = 0;
  1246. strcpy(desc->params[i].short_desc, "Provide monitor ports for the output");
  1247. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1248. i++;
  1249. strcpy(desc->params[i].name, "duplex");
  1250. desc->params[i].character = 'D';
  1251. desc->params[i].type = JackDriverParamBool;
  1252. desc->params[i].value.i = TRUE;
  1253. strcpy(desc->params[i].short_desc, "Provide both capture and playback ports");
  1254. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1255. i++;
  1256. strcpy(desc->params[i].name, "rate");
  1257. desc->params[i].character = 'r';
  1258. desc->params[i].type = JackDriverParamUInt;
  1259. desc->params[i].value.ui = 44100U;
  1260. strcpy(desc->params[i].short_desc, "Sample rate");
  1261. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1262. i++;
  1263. strcpy(desc->params[i].name, "period");
  1264. desc->params[i].character = 'p';
  1265. desc->params[i].type = JackDriverParamUInt;
  1266. desc->params[i].value.ui = 128U;
  1267. strcpy(desc->params[i].short_desc, "Frames per period");
  1268. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1269. i++;
  1270. strcpy(desc->params[i].name, "device");
  1271. desc->params[i].character = 'd';
  1272. desc->params[i].type = JackDriverParamString;
  1273. strcpy(desc->params[i].value.str, "will take default CoreAudio device name");
  1274. strcpy(desc->params[i].short_desc, "CoreAudio device name");
  1275. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1276. i++;
  1277. strcpy(desc->params[i].name, "input-latency");
  1278. desc->params[i].character = 'I';
  1279. desc->params[i].type = JackDriverParamUInt;
  1280. desc->params[i].value.i = 0;
  1281. strcpy(desc->params[i].short_desc, "Extra input latency (frames)");
  1282. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1283. i++;
  1284. strcpy(desc->params[i].name, "output-latency");
  1285. desc->params[i].character = 'O';
  1286. desc->params[i].type = JackDriverParamUInt;
  1287. desc->params[i].value.i = 0;
  1288. strcpy(desc->params[i].short_desc, "Extra output latency (frames)");
  1289. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1290. i++;
  1291. strcpy(desc->params[i].name, "list-devices");
  1292. desc->params[i].character = 'l';
  1293. desc->params[i].type = JackDriverParamBool;
  1294. desc->params[i].value.i = FALSE;
  1295. strcpy(desc->params[i].short_desc, "Display available CoreAudio devices");
  1296. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1297. i++;
  1298. strcpy(desc->params[i].name, "hog");
  1299. desc->params[i].character = 'H';
  1300. desc->params[i].type = JackDriverParamBool;
  1301. desc->params[i].value.i = FALSE;
  1302. strcpy(desc->params[i].short_desc, "Take exclusive access of the audio device");
  1303. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1304. i++;
  1305. strcpy(desc->params[i].name, "async-latency");
  1306. desc->params[i].character = 'L';
  1307. desc->params[i].type = JackDriverParamUInt;
  1308. desc->params[i].value.i = 100;
  1309. strcpy(desc->params[i].short_desc, "Extra output latency in asynchronous mode (percent)");
  1310. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1311. i++;
  1312. strcpy(desc->params[i].name, "grain");
  1313. desc->params[i].character = 'G';
  1314. desc->params[i].type = JackDriverParamUInt;
  1315. desc->params[i].value.i = 100;
  1316. strcpy(desc->params[i].short_desc, "Computation grain in RT thread (percent)");
  1317. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1318. return desc;
  1319. }
  1320. SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
  1321. {
  1322. jack_nframes_t srate = 44100;
  1323. jack_nframes_t frames_per_interrupt = 128;
  1324. int capture = FALSE;
  1325. int playback = FALSE;
  1326. int chan_in = 0;
  1327. int chan_out = 0;
  1328. bool monitor = false;
  1329. const char* capture_driver_uid = "";
  1330. const char* playback_driver_uid = "";
  1331. const JSList *node;
  1332. const jack_driver_param_t *param;
  1333. jack_nframes_t systemic_input_latency = 0;
  1334. jack_nframes_t systemic_output_latency = 0;
  1335. int async_output_latency = 100;
  1336. int computation_grain = -1;
  1337. bool hogged = false;
  1338. for (node = params; node; node = jack_slist_next(node)) {
  1339. param = (const jack_driver_param_t *) node->data;
  1340. switch (param->character) {
  1341. case 'd':
  1342. capture_driver_uid = strdup(param->value.str);
  1343. playback_driver_uid = strdup(param->value.str);
  1344. break;
  1345. case 'D':
  1346. capture = TRUE;
  1347. playback = TRUE;
  1348. break;
  1349. case 'c':
  1350. chan_in = chan_out = (int) param->value.ui;
  1351. break;
  1352. case 'i':
  1353. chan_in = (int) param->value.ui;
  1354. break;
  1355. case 'o':
  1356. chan_out = (int) param->value.ui;
  1357. break;
  1358. case 'C':
  1359. capture = TRUE;
  1360. if (strcmp(param->value.str, "none") != 0) {
  1361. capture_driver_uid = strdup(param->value.str);
  1362. }
  1363. break;
  1364. case 'P':
  1365. playback = TRUE;
  1366. if (strcmp(param->value.str, "none") != 0) {
  1367. playback_driver_uid = strdup(param->value.str);
  1368. }
  1369. break;
  1370. case 'm':
  1371. monitor = param->value.i;
  1372. break;
  1373. case 'r':
  1374. srate = param->value.ui;
  1375. break;
  1376. case 'p':
  1377. frames_per_interrupt = (unsigned int) param->value.ui;
  1378. break;
  1379. case 'I':
  1380. systemic_input_latency = param->value.ui;
  1381. break;
  1382. case 'O':
  1383. systemic_output_latency = param->value.ui;
  1384. break;
  1385. case 'l':
  1386. Jack::DisplayDeviceNames();
  1387. break;
  1388. case 'H':
  1389. hogged = true;
  1390. break;
  1391. case 'L':
  1392. async_output_latency = param->value.ui;
  1393. break;
  1394. case 'G':
  1395. computation_grain = param->value.ui;
  1396. break;
  1397. }
  1398. }
  1399. /* duplex is the default */
  1400. if (!capture && !playback) {
  1401. capture = TRUE;
  1402. playback = TRUE;
  1403. }
  1404. Jack::JackCoreAudioDriver* driver = new Jack::JackCoreAudioDriver("system", "coreaudio", engine, table);
  1405. if (driver->Open(frames_per_interrupt, srate, capture, playback, chan_in, chan_out, monitor, capture_driver_uid,
  1406. playback_driver_uid, systemic_input_latency, systemic_output_latency, async_output_latency, computation_grain, hogged) == 0) {
  1407. return driver;
  1408. } else {
  1409. delete driver;
  1410. return NULL;
  1411. }
  1412. }
  1413. #ifdef __cplusplus
  1414. }
  1415. #endif