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.

1594 lines
59KB

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