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.

1590 lines
60KB

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