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.

1589 lines
59KB

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