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.

1615 lines
60KB

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