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.

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