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.

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