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.

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