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.

2012 lines
79KB

  1. /*
  2. Copyright (C) 2004-2008 Grame
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  14. */
  15. #include "JackCoreAudioDriver.h"
  16. #include "JackEngineControl.h"
  17. #include "JackMachThread.h"
  18. #include "JackGraphManager.h"
  19. #include "JackError.h"
  20. #include "JackClientControl.h"
  21. #include "JackDriverLoader.h"
  22. #include "JackGlobals.h"
  23. #include "JackTools.h"
  24. #include "JackCompilerDeps.h"
  25. #include <iostream>
  26. #include <CoreServices/CoreServices.h>
  27. #include <CoreFoundation/CFNumber.h>
  28. namespace Jack
  29. {
  30. static void Print4CharCode(const char* msg, long c)
  31. {
  32. UInt32 __4CC_number = (c);
  33. char __4CC_string[5];
  34. *((SInt32*)__4CC_string) = EndianU32_NtoB(__4CC_number);
  35. __4CC_string[4] = 0;
  36. jack_log("%s'%s'", (msg), __4CC_string);
  37. }
  38. static void PrintStreamDesc(AudioStreamBasicDescription *inDesc)
  39. {
  40. jack_log("- - - - - - - - - - - - - - - - - - - -");
  41. jack_log(" Sample Rate:%f", inDesc->mSampleRate);
  42. jack_log(" Format ID:%.*s", (int) sizeof(inDesc->mFormatID), (char*)&inDesc->mFormatID);
  43. jack_log(" Format Flags:%lX", inDesc->mFormatFlags);
  44. jack_log(" Bytes per Packet:%ld", inDesc->mBytesPerPacket);
  45. jack_log(" Frames per Packet:%ld", inDesc->mFramesPerPacket);
  46. jack_log(" Bytes per Frame:%ld", inDesc->mBytesPerFrame);
  47. jack_log(" Channels per Frame:%ld", inDesc->mChannelsPerFrame);
  48. jack_log(" Bits per Channel:%ld", inDesc->mBitsPerChannel);
  49. jack_log("- - - - - - - - - - - - - - - - - - - -");
  50. }
  51. static void printError(OSStatus err)
  52. {
  53. switch (err) {
  54. case kAudioHardwareNoError:
  55. jack_log("error code : kAudioHardwareNoError");
  56. break;
  57. case kAudioConverterErr_FormatNotSupported:
  58. jack_log("error code : kAudioConverterErr_FormatNotSupported");
  59. break;
  60. case kAudioConverterErr_OperationNotSupported:
  61. jack_log("error code : kAudioConverterErr_OperationNotSupported");
  62. break;
  63. case kAudioConverterErr_PropertyNotSupported:
  64. jack_log("error code : kAudioConverterErr_PropertyNotSupported");
  65. break;
  66. case kAudioConverterErr_InvalidInputSize:
  67. jack_log("error code : kAudioConverterErr_InvalidInputSize");
  68. break;
  69. case kAudioConverterErr_InvalidOutputSize:
  70. jack_log("error code : kAudioConverterErr_InvalidOutputSize");
  71. break;
  72. case kAudioConverterErr_UnspecifiedError:
  73. jack_log("error code : kAudioConverterErr_UnspecifiedError");
  74. break;
  75. case kAudioConverterErr_BadPropertySizeError:
  76. jack_log("error code : kAudioConverterErr_BadPropertySizeError");
  77. break;
  78. case kAudioConverterErr_RequiresPacketDescriptionsError:
  79. jack_log("error code : kAudioConverterErr_RequiresPacketDescriptionsError");
  80. break;
  81. case kAudioConverterErr_InputSampleRateOutOfRange:
  82. jack_log("error code : kAudioConverterErr_InputSampleRateOutOfRange");
  83. break;
  84. case kAudioConverterErr_OutputSampleRateOutOfRange:
  85. jack_log("error code : kAudioConverterErr_OutputSampleRateOutOfRange");
  86. break;
  87. case kAudioHardwareNotRunningError:
  88. jack_log("error code : kAudioHardwareNotRunningError");
  89. break;
  90. case kAudioHardwareUnknownPropertyError:
  91. jack_log("error code : kAudioHardwareUnknownPropertyError");
  92. break;
  93. case kAudioHardwareIllegalOperationError:
  94. jack_log("error code : kAudioHardwareIllegalOperationError");
  95. break;
  96. case kAudioHardwareBadDeviceError:
  97. jack_log("error code : kAudioHardwareBadDeviceError");
  98. break;
  99. case kAudioHardwareBadStreamError:
  100. jack_log("error code : kAudioHardwareBadStreamError");
  101. break;
  102. case kAudioDeviceUnsupportedFormatError:
  103. jack_log("error code : kAudioDeviceUnsupportedFormatError");
  104. break;
  105. case kAudioDevicePermissionsError:
  106. jack_log("error code : kAudioDevicePermissionsError");
  107. break;
  108. case kAudioHardwareBadObjectError:
  109. jack_log("error code : kAudioHardwareBadObjectError");
  110. break;
  111. case kAudioHardwareUnsupportedOperationError:
  112. jack_log("error code : kAudioHardwareUnsupportedOperationError");
  113. break;
  114. default:
  115. Print4CharCode("error code : unknown", err);
  116. break;
  117. }
  118. }
  119. static OSStatus DisplayDeviceNames()
  120. {
  121. UInt32 size;
  122. Boolean isWritable;
  123. int i, deviceNum;
  124. OSStatus err;
  125. CFStringRef UIname;
  126. err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
  127. if (err != noErr)
  128. return err;
  129. deviceNum = size / sizeof(AudioDeviceID);
  130. AudioDeviceID devices[deviceNum];
  131. err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
  132. if (err != noErr)
  133. return err;
  134. for (i = 0; i < deviceNum; i++) {
  135. char device_name[256];
  136. char internal_name[256];
  137. size = sizeof(CFStringRef);
  138. UIname = NULL;
  139. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  140. if (err == noErr) {
  141. CFStringGetCString(UIname, internal_name, 256, CFStringGetSystemEncoding());
  142. } else {
  143. goto error;
  144. }
  145. size = 256;
  146. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &size, device_name);
  147. if (err != noErr)
  148. return err;
  149. jack_info("Device name = \'%s\', internal_name = \'%s\' (to be used as -C, -P, or -d parameter)", device_name, internal_name);
  150. }
  151. return noErr;
  152. error:
  153. if (UIname != NULL)
  154. CFRelease(UIname);
  155. return err;
  156. }
  157. static CFStringRef GetDeviceName(AudioDeviceID id)
  158. {
  159. UInt32 size = sizeof(CFStringRef);
  160. CFStringRef UIname;
  161. OSStatus err = AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  162. return (err == noErr) ? UIname : NULL;
  163. }
  164. OSStatus JackCoreAudioDriver::Render(void *inRefCon,
  165. AudioUnitRenderActionFlags *ioActionFlags,
  166. const AudioTimeStamp *inTimeStamp,
  167. UInt32 inBusNumber,
  168. UInt32 inNumberFrames,
  169. AudioBufferList *ioData)
  170. {
  171. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inRefCon;
  172. driver->fActionFags = ioActionFlags;
  173. driver->fCurrentTime = (AudioTimeStamp *)inTimeStamp;
  174. driver->fDriverOutputData = ioData;
  175. // Setup threaded based log function et get RT thread parameters once...
  176. if (set_threaded_log_function()) {
  177. jack_log("set_threaded_log_function");
  178. JackMachThread::GetParams(pthread_self(), &driver->fEngineControl->fPeriod, &driver->fEngineControl->fComputation, &driver->fEngineControl->fConstraint);
  179. if (driver->fComputationGrain > 0) {
  180. jack_log("JackCoreAudioDriver::Render : RT thread computation setup to %d percent of period", int(driver->fComputationGrain * 100));
  181. driver->fEngineControl->fComputation = driver->fEngineControl->fPeriod * driver->fComputationGrain;
  182. }
  183. // Signal waiting start function...
  184. driver->fState = true;
  185. }
  186. driver->CycleTakeBeginTime();
  187. return driver->Process();
  188. }
  189. int JackCoreAudioDriver::Read()
  190. {
  191. if (fCaptureChannels > 0) { // Calling AudioUnitRender with no input returns a '????' error (callback setting issue ??), so hack to avoid it here...
  192. return (AudioUnitRender(fAUHAL, fActionFags, fCurrentTime, 1, fEngineControl->fBufferSize, fJackInputData) == noErr) ? 0 : -1;
  193. } else {
  194. return 0;
  195. }
  196. }
  197. int JackCoreAudioDriver::Write()
  198. {
  199. for (int i = 0; i < fPlaybackChannels; i++) {
  200. if (fGraphManager->GetConnectionsNum(fPlaybackPortList[i]) > 0) {
  201. jack_default_audio_sample_t* buffer = GetOutputBuffer(i);
  202. int size = sizeof(jack_default_audio_sample_t) * fEngineControl->fBufferSize;
  203. memcpy((jack_default_audio_sample_t*)fDriverOutputData->mBuffers[i].mData, buffer, size);
  204. // Monitor ports
  205. if (fWithMonitorPorts && fGraphManager->GetConnectionsNum(fMonitorPortList[i]) > 0)
  206. memcpy(GetMonitorBuffer(i), buffer, size);
  207. } else {
  208. memset((jack_default_audio_sample_t*)fDriverOutputData->mBuffers[i].mData, 0, sizeof(jack_default_audio_sample_t) * fEngineControl->fBufferSize);
  209. }
  210. }
  211. return 0;
  212. }
  213. OSStatus JackCoreAudioDriver::SRNotificationCallback(AudioDeviceID inDevice,
  214. UInt32 inChannel,
  215. Boolean isInput,
  216. AudioDevicePropertyID inPropertyID,
  217. void* inClientData)
  218. {
  219. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  220. switch (inPropertyID) {
  221. case kAudioDevicePropertyNominalSampleRate: {
  222. jack_log("JackCoreAudioDriver::SRNotificationCallback kAudioDevicePropertyNominalSampleRate");
  223. driver->fState = true;
  224. // Check new sample rate
  225. Float64 sampleRate;
  226. UInt32 outSize = sizeof(Float64);
  227. OSStatus err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
  228. if (err != noErr) {
  229. jack_error("Cannot get current sample rate");
  230. printError(err);
  231. } else {
  232. jack_log("SRNotificationCallback : checked sample rate = %f", sampleRate);
  233. }
  234. break;
  235. }
  236. }
  237. return noErr;
  238. }
  239. // A better implementation would possibly try to recover in case of hardware device change (see HALLAB HLFilePlayerWindowControllerAudioDevicePropertyListenerProc code)
  240. OSStatus JackCoreAudioDriver::DeviceNotificationCallback(AudioDeviceID inDevice,
  241. UInt32 inChannel,
  242. Boolean isInput,
  243. AudioDevicePropertyID inPropertyID,
  244. void* inClientData)
  245. {
  246. JackCoreAudioDriver* driver = (JackCoreAudioDriver*)inClientData;
  247. switch (inPropertyID) {
  248. case kAudioDevicePropertyDeviceIsRunning: {
  249. UInt32 isrunning = 0;
  250. UInt32 outsize = sizeof(UInt32);
  251. if (AudioDeviceGetProperty(driver->fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyDeviceIsRunning, &outsize, &isrunning) == noErr) {
  252. jack_log("JackCoreAudioDriver::DeviceNotificationCallback kAudioDevicePropertyDeviceIsRunning = %d", isrunning);
  253. }
  254. break;
  255. }
  256. case kAudioDeviceProcessorOverload: {
  257. jack_error("JackCoreAudioDriver::DeviceNotificationCallback kAudioDeviceProcessorOverload");
  258. jack_time_t cur_time = GetMicroSeconds();
  259. driver->NotifyXRun(cur_time, float(cur_time - driver->fBeginDateUst)); // Better this value than nothing...
  260. break;
  261. }
  262. case kAudioDevicePropertyStreamConfiguration: {
  263. jack_error("Cannot handle kAudioDevicePropertyStreamConfiguration : server will quit...");
  264. driver->NotifyFailure(JackBackendError, "Another application has changed the device configuration."); // Message length limited to JACK_MESSAGE_SIZE
  265. driver->CloseAUHAL();
  266. kill(JackTools::GetPID(), SIGINT);
  267. return kAudioHardwareUnsupportedOperationError;
  268. }
  269. case kAudioDevicePropertyNominalSampleRate: {
  270. Float64 sampleRate = 0;
  271. UInt32 outsize = sizeof(Float64);
  272. OSStatus err = AudioDeviceGetProperty(driver->fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outsize, &sampleRate);
  273. if (err != noErr)
  274. return kAudioHardwareUnsupportedOperationError;
  275. char device_name[256];
  276. const char* digidesign_name = "Digidesign";
  277. driver->GetDeviceNameFromID(driver->fDeviceID, device_name);
  278. if (sampleRate != driver->fEngineControl->fSampleRate) {
  279. // Digidesign hardware, so "special" code : change the SR again here
  280. if (strncmp(device_name, digidesign_name, sizeof(digidesign_name)) == 0) {
  281. jack_log("Digidesign HW = %s", device_name);
  282. // Set sample rate again...
  283. sampleRate = driver->fEngineControl->fSampleRate;
  284. err = AudioDeviceSetProperty(driver->fDeviceID, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outsize, &sampleRate);
  285. if (err != noErr) {
  286. jack_error("Cannot set sample rate = %f", sampleRate);
  287. printError(err);
  288. } else {
  289. jack_log("Set sample rate = %f", sampleRate);
  290. }
  291. // Check new sample rate again...
  292. outsize = sizeof(Float64);
  293. err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outsize, &sampleRate);
  294. if (err != noErr) {
  295. jack_error("Cannot get current sample rate");
  296. printError(err);
  297. } else {
  298. jack_log("Checked sample rate = %f", sampleRate);
  299. }
  300. return noErr;
  301. } else {
  302. driver->NotifyFailure(JackBackendError, "Another application has changed the sample rate."); // Message length limited to JACK_MESSAGE_SIZE
  303. driver->CloseAUHAL();
  304. kill(JackTools::GetPID(), SIGINT);
  305. return kAudioHardwareUnsupportedOperationError;
  306. }
  307. }
  308. }
  309. }
  310. return noErr;
  311. }
  312. OSStatus JackCoreAudioDriver::GetDeviceIDFromUID(const char* UID, AudioDeviceID* id)
  313. {
  314. UInt32 size = sizeof(AudioValueTranslation);
  315. CFStringRef inIUD = CFStringCreateWithCString(NULL, UID, CFStringGetSystemEncoding());
  316. AudioValueTranslation value = { &inIUD, sizeof(CFStringRef), id, sizeof(AudioDeviceID) };
  317. if (inIUD == NULL) {
  318. return kAudioHardwareUnspecifiedError;
  319. } else {
  320. OSStatus res = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, &size, &value);
  321. CFRelease(inIUD);
  322. jack_log("GetDeviceIDFromUID %s %ld", UID, *id);
  323. return (*id == kAudioDeviceUnknown) ? kAudioHardwareBadDeviceError : res;
  324. }
  325. }
  326. OSStatus JackCoreAudioDriver::GetDefaultDevice(AudioDeviceID* id)
  327. {
  328. OSStatus res;
  329. UInt32 theSize = sizeof(UInt32);
  330. AudioDeviceID inDefault;
  331. AudioDeviceID outDefault;
  332. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  333. return res;
  334. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  335. return res;
  336. jack_log("GetDefaultDevice: input = %ld output = %ld", inDefault, outDefault);
  337. // Get the device only if default input and output are the same
  338. if (inDefault != outDefault) {
  339. jack_error("Default input and output devices are not the same !!");
  340. return kAudioHardwareBadDeviceError;
  341. } else if (inDefault == 0) {
  342. jack_error("Default input and output devices are null !!");
  343. return kAudioHardwareBadDeviceError;
  344. } else {
  345. *id = inDefault;
  346. return noErr;
  347. }
  348. }
  349. OSStatus JackCoreAudioDriver::GetDefaultInputDevice(AudioDeviceID* id)
  350. {
  351. OSStatus res;
  352. UInt32 theSize = sizeof(UInt32);
  353. AudioDeviceID inDefault;
  354. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  355. return res;
  356. if (inDefault == 0) {
  357. jack_error("Error : input device is 0, please select a correct one !!");
  358. return -1;
  359. }
  360. jack_log("GetDefaultInputDevice: input = %ld ", inDefault);
  361. *id = inDefault;
  362. return noErr;
  363. }
  364. OSStatus JackCoreAudioDriver::GetDefaultOutputDevice(AudioDeviceID* id)
  365. {
  366. OSStatus res;
  367. UInt32 theSize = sizeof(UInt32);
  368. AudioDeviceID outDefault;
  369. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  370. return res;
  371. if (outDefault == 0) {
  372. jack_error("Error : output device is 0, please select a correct one !!");
  373. return -1;
  374. }
  375. jack_log("GetDefaultOutputDevice: output = %ld", outDefault);
  376. *id = outDefault;
  377. return noErr;
  378. }
  379. OSStatus JackCoreAudioDriver::GetDeviceNameFromID(AudioDeviceID id, char* name)
  380. {
  381. UInt32 size = 256;
  382. return AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceName, &size, name);
  383. }
  384. OSStatus JackCoreAudioDriver::GetTotalChannels(AudioDeviceID device, int& channelCount, bool isInput)
  385. {
  386. OSStatus err = noErr;
  387. UInt32 outSize;
  388. Boolean outWritable;
  389. channelCount = 0;
  390. err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, &outWritable);
  391. if (err == noErr) {
  392. AudioBufferList bufferList[outSize];
  393. err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, bufferList);
  394. if (err == noErr) {
  395. for (unsigned int i = 0; i < bufferList->mNumberBuffers; i++)
  396. channelCount += bufferList->mBuffers[i].mNumberChannels;
  397. }
  398. }
  399. return err;
  400. }
  401. JackCoreAudioDriver::JackCoreAudioDriver(const char* name, const char* alias, JackLockedEngine* engine, JackSynchro* table)
  402. : JackAudioDriver(name, alias, engine, table),
  403. fJackInputData(NULL),
  404. fDriverOutputData(NULL),
  405. fPluginID(0),
  406. fState(false),
  407. fHogged(false),
  408. fIOUsage(1.f),
  409. fComputationGrain(-1.f),
  410. fClockDriftCompensate(false)
  411. {}
  412. JackCoreAudioDriver::~JackCoreAudioDriver()
  413. {}
  414. OSStatus JackCoreAudioDriver::DestroyAggregateDevice()
  415. {
  416. OSStatus osErr = noErr;
  417. AudioObjectPropertyAddress pluginAOPA;
  418. pluginAOPA.mSelector = kAudioPlugInDestroyAggregateDevice;
  419. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  420. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  421. UInt32 outDataSize;
  422. if (fPluginID > 0) {
  423. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  424. if (osErr != noErr) {
  425. jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyDataSize error");
  426. printError(osErr);
  427. return osErr;
  428. }
  429. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, 0, NULL, &outDataSize, &fDeviceID);
  430. if (osErr != noErr) {
  431. jack_error("JackCoreAudioDriver::DestroyAggregateDevice : AudioObjectGetPropertyData error");
  432. printError(osErr);
  433. return osErr;
  434. }
  435. }
  436. return noErr;
  437. }
  438. OSStatus JackCoreAudioDriver::CreateAggregateDevice(AudioDeviceID captureDeviceID, AudioDeviceID playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
  439. {
  440. OSStatus err = noErr;
  441. AudioObjectID sub_device[32];
  442. UInt32 outSize = sizeof(sub_device);
  443. err = AudioDeviceGetProperty(captureDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  444. vector<AudioDeviceID> captureDeviceIDArray;
  445. if (err != noErr) {
  446. jack_log("Input device does not have subdevices");
  447. captureDeviceIDArray.push_back(captureDeviceID);
  448. } else {
  449. int num_devices = outSize / sizeof(AudioObjectID);
  450. jack_log("Input device has %d subdevices", num_devices);
  451. for (int i = 0; i < num_devices; i++) {
  452. captureDeviceIDArray.push_back(sub_device[i]);
  453. }
  454. }
  455. err = AudioDeviceGetProperty(playbackDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  456. vector<AudioDeviceID> playbackDeviceIDArray;
  457. if (err != noErr) {
  458. jack_log("Output device does not have subdevices");
  459. playbackDeviceIDArray.push_back(playbackDeviceID);
  460. } else {
  461. int num_devices = outSize / sizeof(AudioObjectID);
  462. jack_log("Output device has %d subdevices", num_devices);
  463. for (int i = 0; i < num_devices; i++) {
  464. playbackDeviceIDArray.push_back(sub_device[i]);
  465. }
  466. }
  467. return CreateAggregateDeviceAux(captureDeviceIDArray, playbackDeviceIDArray, samplerate, outAggregateDevice);
  468. }
  469. OSStatus JackCoreAudioDriver::CreateAggregateDeviceAux(vector<AudioDeviceID> captureDeviceID, vector<AudioDeviceID> playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
  470. {
  471. OSStatus osErr = noErr;
  472. UInt32 outSize;
  473. Boolean outWritable;
  474. // Prepare sub-devices for clock drift compensation
  475. // Workaround for bug in the HAL : until 10.6.2
  476. AudioObjectPropertyAddress theAddressOwned = { kAudioObjectPropertyOwnedObjects, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  477. AudioObjectPropertyAddress theAddressDrift = { kAudioSubDevicePropertyDriftCompensation, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  478. UInt32 theQualifierDataSize = sizeof(AudioObjectID);
  479. AudioClassID inClass = kAudioSubDeviceClassID;
  480. void* theQualifierData = &inClass;
  481. UInt32 subDevicesNum = 0;
  482. //---------------------------------------------------------------------------
  483. // Setup SR of both devices otherwise creating AD may fail...
  484. //---------------------------------------------------------------------------
  485. UInt32 keptclockdomain = 0;
  486. UInt32 clockdomain = 0;
  487. outSize = sizeof(UInt32);
  488. bool need_clock_drift_compensation = false;
  489. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  490. if (SetupSampleRateAux(captureDeviceID[i], samplerate) < 0) {
  491. jack_error("JackCoreAudioDriver::CreateAggregateDevice : cannot set SR of input device");
  492. } else {
  493. // Check clock domain
  494. osErr = AudioDeviceGetProperty(captureDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
  495. if (osErr != 0) {
  496. jack_error("JackCoreAudioDriver::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
  497. printError(osErr);
  498. } else {
  499. keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
  500. jack_log("JackCoreAudioDriver::CreateAggregateDevice : input clockdomain = %d", clockdomain);
  501. if (clockdomain != 0 && clockdomain != keptclockdomain) {
  502. jack_error("JackCoreAudioDriver::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
  503. need_clock_drift_compensation = true;
  504. }
  505. }
  506. }
  507. }
  508. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  509. if (SetupSampleRateAux(playbackDeviceID[i], samplerate) < 0) {
  510. jack_error("JackCoreAudioDriver::CreateAggregateDevice : cannot set SR of output device");
  511. } else {
  512. // Check clock domain
  513. osErr = AudioDeviceGetProperty(playbackDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
  514. if (osErr != 0) {
  515. jack_error("JackCoreAudioDriver::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
  516. printError(osErr);
  517. } else {
  518. keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
  519. jack_log("JackCoreAudioDriver::CreateAggregateDevice : output clockdomain = %d", clockdomain);
  520. if (clockdomain != 0 && clockdomain != keptclockdomain) {
  521. jack_error("JackCoreAudioDriver::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
  522. need_clock_drift_compensation = true;
  523. }
  524. }
  525. }
  526. }
  527. // If no valid clock domain was found, then assume we have to compensate...
  528. if (keptclockdomain == 0) {
  529. need_clock_drift_compensation = true;
  530. }
  531. //---------------------------------------------------------------------------
  532. // Start to create a new aggregate by getting the base audio hardware plugin
  533. //---------------------------------------------------------------------------
  534. char device_name[256];
  535. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  536. GetDeviceNameFromID(captureDeviceID[i], device_name);
  537. jack_info("Separated input = '%s' ", device_name);
  538. }
  539. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  540. GetDeviceNameFromID(playbackDeviceID[i], device_name);
  541. jack_info("Separated output = '%s' ", device_name);
  542. }
  543. osErr = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyPlugInForBundleID, &outSize, &outWritable);
  544. if (osErr != noErr) {
  545. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioHardwareGetPropertyInfo kAudioHardwarePropertyPlugInForBundleID error");
  546. printError(osErr);
  547. return osErr;
  548. }
  549. AudioValueTranslation pluginAVT;
  550. CFStringRef inBundleRef = CFSTR("com.apple.audio.CoreAudio");
  551. pluginAVT.mInputData = &inBundleRef;
  552. pluginAVT.mInputDataSize = sizeof(inBundleRef);
  553. pluginAVT.mOutputData = &fPluginID;
  554. pluginAVT.mOutputDataSize = sizeof(fPluginID);
  555. osErr = AudioHardwareGetProperty(kAudioHardwarePropertyPlugInForBundleID, &outSize, &pluginAVT);
  556. if (osErr != noErr) {
  557. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioHardwareGetProperty kAudioHardwarePropertyPlugInForBundleID error");
  558. printError(osErr);
  559. return osErr;
  560. }
  561. //-------------------------------------------------
  562. // Create a CFDictionary for our aggregate device
  563. //-------------------------------------------------
  564. CFMutableDictionaryRef aggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  565. CFStringRef AggregateDeviceNameRef = CFSTR("JackDuplex");
  566. CFStringRef AggregateDeviceUIDRef = CFSTR("com.grame.JackDuplex");
  567. // add the name of the device to the dictionary
  568. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceNameKey), AggregateDeviceNameRef);
  569. // add our choice of UID for the aggregate device to the dictionary
  570. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceUIDKey), AggregateDeviceUIDRef);
  571. // add a "private aggregate key" to the dictionary
  572. int value = 1;
  573. CFNumberRef AggregateDeviceNumberRef = CFNumberCreate(NULL, kCFNumberIntType, &value);
  574. SInt32 system;
  575. Gestalt(gestaltSystemVersion, &system);
  576. jack_log("JackCoreAudioDriver::CreateAggregateDevice : system version = %x limit = %x", system, 0x00001054);
  577. // Starting with 10.5.4 systems, the AD can be internal... (better)
  578. if (system < 0x00001054) {
  579. jack_log("JackCoreAudioDriver::CreateAggregateDevice : public aggregate device....");
  580. } else {
  581. jack_log("JackCoreAudioDriver::CreateAggregateDevice : private aggregate device....");
  582. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceIsPrivateKey), AggregateDeviceNumberRef);
  583. }
  584. // Prepare sub-devices for clock drift compensation
  585. CFMutableArrayRef subDevicesArrayClock = NULL;
  586. /*
  587. if (fClockDriftCompensate) {
  588. if (need_clock_drift_compensation) {
  589. jack_info("Clock drift compensation activated...");
  590. subDevicesArrayClock = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  591. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  592. CFStringRef UID = GetDeviceName(captureDeviceID[i]);
  593. if (UID) {
  594. CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  595. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
  596. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
  597. //CFRelease(UID);
  598. CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
  599. }
  600. }
  601. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  602. CFStringRef UID = GetDeviceName(playbackDeviceID[i]);
  603. if (UID) {
  604. CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  605. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
  606. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
  607. //CFRelease(UID);
  608. CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
  609. }
  610. }
  611. // add sub-device clock array for the aggregate device to the dictionary
  612. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceSubDeviceListKey), subDevicesArrayClock);
  613. } else {
  614. jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
  615. }
  616. }
  617. */
  618. //-------------------------------------------------
  619. // Create a CFMutableArray for our sub-device list
  620. //-------------------------------------------------
  621. // we need to append the UID for each device to a CFMutableArray, so create one here
  622. CFMutableArrayRef subDevicesArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  623. vector<CFStringRef> captureDeviceUID;
  624. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  625. CFStringRef ref = GetDeviceName(captureDeviceID[i]);
  626. if (ref == NULL)
  627. return -1;
  628. captureDeviceUID.push_back(ref);
  629. // input sub-devices in this example, so append the sub-device's UID to the CFArray
  630. CFArrayAppendValue(subDevicesArray, ref);
  631. }
  632. vector<CFStringRef> playbackDeviceUID;
  633. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  634. CFStringRef ref = GetDeviceName(playbackDeviceID[i]);
  635. if (ref == NULL)
  636. return -1;
  637. playbackDeviceUID.push_back(ref);
  638. // output sub-devices in this example, so append the sub-device's UID to the CFArray
  639. CFArrayAppendValue(subDevicesArray, ref);
  640. }
  641. //-----------------------------------------------------------------------
  642. // Feed the dictionary to the plugin, to create a blank aggregate device
  643. //-----------------------------------------------------------------------
  644. AudioObjectPropertyAddress pluginAOPA;
  645. pluginAOPA.mSelector = kAudioPlugInCreateAggregateDevice;
  646. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  647. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  648. UInt32 outDataSize;
  649. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  650. if (osErr != noErr) {
  651. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectGetPropertyDataSize error");
  652. printError(osErr);
  653. goto error;
  654. }
  655. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, sizeof(aggDeviceDict), &aggDeviceDict, &outDataSize, outAggregateDevice);
  656. if (osErr != noErr) {
  657. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectGetPropertyData error");
  658. printError(osErr);
  659. goto error;
  660. }
  661. // pause for a bit to make sure that everything completed correctly
  662. // this is to work around a bug in the HAL where a new aggregate device seems to disappear briefly after it is created
  663. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  664. //-------------------------
  665. // Set the sub-device list
  666. //-------------------------
  667. pluginAOPA.mSelector = kAudioAggregateDevicePropertyFullSubDeviceList;
  668. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  669. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  670. outDataSize = sizeof(CFMutableArrayRef);
  671. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &subDevicesArray);
  672. if (osErr != noErr) {
  673. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectSetPropertyData for sub-device list error");
  674. printError(osErr);
  675. goto error;
  676. }
  677. // pause again to give the changes time to take effect
  678. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  679. //-----------------------
  680. // Set the master device
  681. //-----------------------
  682. // set the master device manually (this is the device which will act as the master clock for the aggregate device)
  683. // pass in the UID of the device you want to use
  684. pluginAOPA.mSelector = kAudioAggregateDevicePropertyMasterSubDevice;
  685. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  686. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  687. outDataSize = sizeof(CFStringRef);
  688. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &captureDeviceUID[0]); // First apture is master...
  689. if (osErr != noErr) {
  690. jack_error("JackCoreAudioDriver::CreateAggregateDevice : AudioObjectSetPropertyData for master device error");
  691. printError(osErr);
  692. goto error;
  693. }
  694. // pause again to give the changes time to take effect
  695. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  696. // Prepare sub-devices for clock drift compensation
  697. // Workaround for bug in the HAL : until 10.6.2
  698. if (fClockDriftCompensate) {
  699. if (need_clock_drift_compensation) {
  700. jack_info("Clock drift compensation activated...");
  701. // Get the property data size
  702. osErr = AudioObjectGetPropertyDataSize(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize);
  703. if (osErr != noErr) {
  704. jack_error("JackCoreAudioDriver::CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
  705. printError(osErr);
  706. }
  707. // Calculate the number of object IDs
  708. subDevicesNum = outSize / sizeof(AudioObjectID);
  709. jack_info("JackCoreAudioDriver::CreateAggregateDevice clock drift compensation, number of sub-devices = %d", subDevicesNum);
  710. AudioObjectID subDevices[subDevicesNum];
  711. outSize = sizeof(subDevices);
  712. osErr = AudioObjectGetPropertyData(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize, subDevices);
  713. if (osErr != noErr) {
  714. jack_error("JackCoreAudioDriver::CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
  715. printError(osErr);
  716. }
  717. // Set kAudioSubDevicePropertyDriftCompensation property...
  718. for (UInt32 index = 0; index < subDevicesNum; ++index) {
  719. UInt32 theDriftCompensationValue = 1;
  720. osErr = AudioObjectSetPropertyData(subDevices[index], &theAddressDrift, 0, NULL, sizeof(UInt32), &theDriftCompensationValue);
  721. if (osErr != noErr) {
  722. jack_error("JackCoreAudioDriver::CreateAggregateDevice kAudioSubDevicePropertyDriftCompensation error");
  723. printError(osErr);
  724. }
  725. }
  726. } else {
  727. jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
  728. }
  729. }
  730. // pause again to give the changes time to take effect
  731. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  732. //----------
  733. // Clean up
  734. //----------
  735. // release the private AD key
  736. CFRelease(AggregateDeviceNumberRef);
  737. // release the CF objects we have created - we don't need them any more
  738. CFRelease(aggDeviceDict);
  739. CFRelease(subDevicesArray);
  740. if (subDevicesArrayClock)
  741. CFRelease(subDevicesArrayClock);
  742. // release the device UID
  743. for (UInt32 i = 0; i < captureDeviceUID.size(); i++) {
  744. CFRelease(captureDeviceUID[i]);
  745. }
  746. for (UInt32 i = 0; i < playbackDeviceUID.size(); i++) {
  747. CFRelease(playbackDeviceUID[i]);
  748. }
  749. jack_log("New aggregate device %ld", *outAggregateDevice);
  750. return noErr;
  751. error:
  752. DestroyAggregateDevice();
  753. return -1;
  754. }
  755. int JackCoreAudioDriver::SetupDevices(const char* capture_driver_uid,
  756. const char* playback_driver_uid,
  757. char* capture_driver_name,
  758. char* playback_driver_name,
  759. jack_nframes_t samplerate)
  760. {
  761. capture_driver_name[0] = 0;
  762. playback_driver_name[0] = 0;
  763. // Duplex
  764. if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
  765. jack_log("JackCoreAudioDriver::Open duplex");
  766. // Same device for capture and playback...
  767. if (strcmp(capture_driver_uid, playback_driver_uid) == 0) {
  768. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  769. jack_log("Will take default in/out");
  770. if (GetDefaultDevice(&fDeviceID) != noErr) {
  771. jack_error("Cannot open default device");
  772. return -1;
  773. }
  774. }
  775. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  776. jack_error("Cannot get device name from device ID");
  777. return -1;
  778. }
  779. } else {
  780. // Creates aggregate device
  781. AudioDeviceID captureID, playbackID;
  782. if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
  783. jack_log("Will take default input");
  784. if (GetDefaultInputDevice(&captureID) != noErr) {
  785. jack_error("Cannot open default input device");
  786. return -1;
  787. }
  788. }
  789. if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
  790. jack_log("Will take default output");
  791. if (GetDefaultOutputDevice(&playbackID) != noErr) {
  792. jack_error("Cannot open default output device");
  793. return -1;
  794. }
  795. }
  796. if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr)
  797. return -1;
  798. }
  799. // Capture only
  800. } else if (strcmp(capture_driver_uid, "") != 0) {
  801. jack_log("JackCoreAudioDriver::Open capture only");
  802. if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
  803. jack_log("Will take default input");
  804. if (GetDefaultInputDevice(&fDeviceID) != noErr) {
  805. jack_error("Cannot open default input device");
  806. return -1;
  807. }
  808. }
  809. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
  810. jack_error("Cannot get device name from device ID");
  811. return -1;
  812. }
  813. // Playback only
  814. } else if (strcmp(playback_driver_uid, "") != 0) {
  815. jack_log("JackCoreAudioDriver::Open playback only");
  816. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  817. jack_log("Will take default output");
  818. if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
  819. jack_error("Cannot open default output device");
  820. return -1;
  821. }
  822. }
  823. if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  824. jack_error("Cannot get device name from device ID");
  825. return -1;
  826. }
  827. // Use default driver in duplex mode
  828. } else {
  829. jack_log("JackCoreAudioDriver::Open default driver");
  830. if (GetDefaultDevice(&fDeviceID) != noErr) {
  831. jack_error("Cannot open default device in duplex mode, so aggregate default input and default output");
  832. // Creates aggregate device
  833. AudioDeviceID captureID, playbackID;
  834. if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
  835. jack_log("Will take default input");
  836. if (GetDefaultInputDevice(&captureID) != noErr) {
  837. jack_error("Cannot open default input device");
  838. return -1;
  839. }
  840. }
  841. if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
  842. jack_log("Will take default output");
  843. if (GetDefaultOutputDevice(&playbackID) != noErr) {
  844. jack_error("Cannot open default output device");
  845. return -1;
  846. }
  847. }
  848. if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr)
  849. return -1;
  850. }
  851. }
  852. if (fHogged) {
  853. if (TakeHog()) {
  854. jack_info("Device = %ld has been hogged", fDeviceID);
  855. }
  856. }
  857. return 0;
  858. }
  859. /*
  860. Return the max possible input channels in in_nChannels and output channels in out_nChannels.
  861. */
  862. int JackCoreAudioDriver::SetupChannels(bool capturing, bool playing, int& inchannels, int& outchannels, int& in_nChannels, int& out_nChannels, bool strict)
  863. {
  864. OSStatus err = noErr;
  865. if (capturing) {
  866. err = GetTotalChannels(fDeviceID, in_nChannels, true);
  867. if (err != noErr) {
  868. jack_error("Cannot get input channel number");
  869. printError(err);
  870. return -1;
  871. } else {
  872. jack_log("Max input channels : %d", in_nChannels);
  873. }
  874. }
  875. if (playing) {
  876. err = GetTotalChannels(fDeviceID, out_nChannels, false);
  877. if (err != noErr) {
  878. jack_error("Cannot get output channel number");
  879. printError(err);
  880. return -1;
  881. } else {
  882. jack_log("Max output channels : %d", out_nChannels);
  883. }
  884. }
  885. if (inchannels > in_nChannels) {
  886. jack_error("This device hasn't required input channels inchannels = %d in_nChannels = %d", inchannels, in_nChannels);
  887. if (strict)
  888. return -1;
  889. }
  890. if (outchannels > out_nChannels) {
  891. jack_error("This device hasn't required output channels outchannels = %d out_nChannels = %d", outchannels, out_nChannels);
  892. if (strict)
  893. return -1;
  894. }
  895. if (inchannels == -1) {
  896. jack_log("Setup max in channels = %d", in_nChannels);
  897. inchannels = in_nChannels;
  898. }
  899. if (outchannels == -1) {
  900. jack_log("Setup max out channels = %d", out_nChannels);
  901. outchannels = out_nChannels;
  902. }
  903. return 0;
  904. }
  905. int JackCoreAudioDriver::SetupBufferSize(jack_nframes_t buffer_size)
  906. {
  907. // Setting buffer size
  908. UInt32 outSize = sizeof(UInt32);
  909. OSStatus err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
  910. if (err != noErr) {
  911. jack_error("Cannot set buffer size %ld", buffer_size);
  912. printError(err);
  913. return -1;
  914. }
  915. return 0;
  916. }
  917. int JackCoreAudioDriver::SetupSampleRate(jack_nframes_t samplerate)
  918. {
  919. return SetupSampleRateAux(fDeviceID, samplerate);
  920. }
  921. int JackCoreAudioDriver::SetupSampleRateAux(AudioDeviceID inDevice, jack_nframes_t samplerate)
  922. {
  923. OSStatus err = noErr;
  924. UInt32 outSize;
  925. Float64 sampleRate;
  926. // Get sample rate
  927. outSize = sizeof(Float64);
  928. err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
  929. if (err != noErr) {
  930. jack_error("Cannot get current sample rate");
  931. printError(err);
  932. return -1;
  933. } else {
  934. jack_log("Current sample rate = %f", sampleRate);
  935. }
  936. // If needed, set new sample rate
  937. if (samplerate != (jack_nframes_t)sampleRate) {
  938. sampleRate = (Float64)samplerate;
  939. // To get SR change notification
  940. err = AudioDeviceAddPropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback, this);
  941. if (err != noErr) {
  942. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  943. printError(err);
  944. return -1;
  945. }
  946. err = AudioDeviceSetProperty(inDevice, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &sampleRate);
  947. if (err != noErr) {
  948. jack_error("Cannot set sample rate = %ld", samplerate);
  949. printError(err);
  950. return -1;
  951. }
  952. // Waiting for SR change notification
  953. int count = 0;
  954. while (!fState && count++ < WAIT_COUNTER) {
  955. usleep(100000);
  956. jack_log("Wait count = %d", count);
  957. }
  958. // Check new sample rate
  959. outSize = sizeof(Float64);
  960. err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
  961. if (err != noErr) {
  962. jack_error("Cannot get current sample rate");
  963. printError(err);
  964. } else {
  965. jack_log("Checked sample rate = %f", sampleRate);
  966. }
  967. // Remove SR change notification
  968. AudioDeviceRemovePropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
  969. }
  970. return 0;
  971. }
  972. int JackCoreAudioDriver::OpenAUHAL(bool capturing,
  973. bool playing,
  974. int inchannels,
  975. int outchannels,
  976. int in_nChannels,
  977. int out_nChannels,
  978. jack_nframes_t buffer_size,
  979. jack_nframes_t samplerate)
  980. {
  981. ComponentResult err1;
  982. UInt32 enableIO;
  983. AudioStreamBasicDescription srcFormat, dstFormat;
  984. AudioDeviceID currAudioDeviceID;
  985. UInt32 size;
  986. jack_log("OpenAUHAL capturing = %d playing = %d inchannels = %d outchannels = %d in_nChannels = %d out_nChannels = %d", capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels);
  987. if (inchannels == 0 && outchannels == 0) {
  988. jack_error("No input and output channels...");
  989. return -1;
  990. }
  991. // AUHAL
  992. ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
  993. Component HALOutput = FindNextComponent(NULL, &cd);
  994. err1 = OpenAComponent(HALOutput, &fAUHAL);
  995. if (err1 != noErr) {
  996. jack_error("Error calling OpenAComponent");
  997. printError(err1);
  998. goto error;
  999. }
  1000. err1 = AudioUnitInitialize(fAUHAL);
  1001. if (err1 != noErr) {
  1002. jack_error("Cannot initialize AUHAL unit");
  1003. printError(err1);
  1004. goto error;
  1005. }
  1006. // Start I/O
  1007. if (capturing && inchannels > 0) {
  1008. enableIO = 1;
  1009. jack_log("Setup AUHAL input on");
  1010. } else {
  1011. enableIO = 0;
  1012. jack_log("Setup AUHAL input off");
  1013. }
  1014. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
  1015. if (err1 != noErr) {
  1016. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
  1017. printError(err1);
  1018. goto error;
  1019. }
  1020. if (playing && outchannels > 0) {
  1021. enableIO = 1;
  1022. jack_log("Setup AUHAL output on");
  1023. } else {
  1024. enableIO = 0;
  1025. jack_log("Setup AUHAL output off");
  1026. }
  1027. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
  1028. if (err1 != noErr) {
  1029. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
  1030. printError(err1);
  1031. goto error;
  1032. }
  1033. size = sizeof(AudioDeviceID);
  1034. err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
  1035. if (err1 != noErr) {
  1036. jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
  1037. printError(err1);
  1038. goto error;
  1039. } else {
  1040. jack_log("AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
  1041. }
  1042. // Setup up choosen device, in both input and output cases
  1043. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
  1044. if (err1 != noErr) {
  1045. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
  1046. printError(err1);
  1047. goto error;
  1048. }
  1049. // Set buffer size
  1050. if (capturing && inchannels > 0) {
  1051. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*)&buffer_size, sizeof(UInt32));
  1052. if (err1 != noErr) {
  1053. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  1054. printError(err1);
  1055. goto error;
  1056. }
  1057. }
  1058. if (playing && outchannels > 0) {
  1059. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*)&buffer_size, sizeof(UInt32));
  1060. if (err1 != noErr) {
  1061. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  1062. printError(err1);
  1063. goto error;
  1064. }
  1065. }
  1066. // Setup channel map
  1067. if (capturing && inchannels > 0 && inchannels < in_nChannels) {
  1068. SInt32 chanArr[in_nChannels];
  1069. for (int i = 0; i < in_nChannels; i++) {
  1070. chanArr[i] = -1;
  1071. }
  1072. for (int i = 0; i < inchannels; i++) {
  1073. chanArr[i] = i;
  1074. }
  1075. AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
  1076. if (err1 != noErr) {
  1077. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 1");
  1078. printError(err1);
  1079. goto error;
  1080. }
  1081. }
  1082. if (playing && outchannels > 0 && outchannels < out_nChannels) {
  1083. SInt32 chanArr[out_nChannels];
  1084. for (int i = 0; i < out_nChannels; i++) {
  1085. chanArr[i] = -1;
  1086. }
  1087. for (int i = 0; i < outchannels; i++) {
  1088. chanArr[i] = i;
  1089. }
  1090. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
  1091. if (err1 != noErr) {
  1092. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 0");
  1093. printError(err1);
  1094. goto error;
  1095. }
  1096. }
  1097. // Setup stream converters
  1098. if (capturing && inchannels > 0) {
  1099. size = sizeof(AudioStreamBasicDescription);
  1100. err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &srcFormat, &size);
  1101. if (err1 != noErr) {
  1102. jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  1103. printError(err1);
  1104. goto error;
  1105. }
  1106. PrintStreamDesc(&srcFormat);
  1107. jack_log("Setup AUHAL input stream converter SR = %ld", samplerate);
  1108. srcFormat.mSampleRate = samplerate;
  1109. srcFormat.mFormatID = kAudioFormatLinearPCM;
  1110. srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  1111. srcFormat.mBytesPerPacket = sizeof(jack_default_audio_sample_t);
  1112. srcFormat.mFramesPerPacket = 1;
  1113. srcFormat.mBytesPerFrame = sizeof(jack_default_audio_sample_t);
  1114. srcFormat.mChannelsPerFrame = inchannels;
  1115. srcFormat.mBitsPerChannel = 32;
  1116. PrintStreamDesc(&srcFormat);
  1117. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &srcFormat, sizeof(AudioStreamBasicDescription));
  1118. if (err1 != noErr) {
  1119. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  1120. printError(err1);
  1121. goto error;
  1122. }
  1123. }
  1124. if (playing && outchannels > 0) {
  1125. size = sizeof(AudioStreamBasicDescription);
  1126. err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &dstFormat, &size);
  1127. if (err1 != noErr) {
  1128. jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  1129. printError(err1);
  1130. goto error;
  1131. }
  1132. PrintStreamDesc(&dstFormat);
  1133. jack_log("Setup AUHAL output stream converter SR = %ld", samplerate);
  1134. dstFormat.mSampleRate = samplerate;
  1135. dstFormat.mFormatID = kAudioFormatLinearPCM;
  1136. dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  1137. dstFormat.mBytesPerPacket = sizeof(jack_default_audio_sample_t);
  1138. dstFormat.mFramesPerPacket = 1;
  1139. dstFormat.mBytesPerFrame = sizeof(jack_default_audio_sample_t);
  1140. dstFormat.mChannelsPerFrame = outchannels;
  1141. dstFormat.mBitsPerChannel = 32;
  1142. PrintStreamDesc(&dstFormat);
  1143. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &dstFormat, sizeof(AudioStreamBasicDescription));
  1144. if (err1 != noErr) {
  1145. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  1146. printError(err1);
  1147. goto error;
  1148. }
  1149. }
  1150. // Setup callbacks
  1151. if (inchannels > 0 && outchannels == 0) {
  1152. AURenderCallbackStruct output;
  1153. output.inputProc = Render;
  1154. output.inputProcRefCon = this;
  1155. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
  1156. if (err1 != noErr) {
  1157. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
  1158. printError(err1);
  1159. goto error;
  1160. }
  1161. } else {
  1162. AURenderCallbackStruct output;
  1163. output.inputProc = Render;
  1164. output.inputProcRefCon = this;
  1165. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
  1166. if (err1 != noErr) {
  1167. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
  1168. printError(err1);
  1169. goto error;
  1170. }
  1171. }
  1172. return 0;
  1173. error:
  1174. CloseAUHAL();
  1175. return -1;
  1176. }
  1177. int JackCoreAudioDriver::SetupBuffers(int inchannels)
  1178. {
  1179. // Prepare buffers
  1180. fJackInputData = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
  1181. fJackInputData->mNumberBuffers = inchannels;
  1182. for (int i = 0; i < inchannels; i++) {
  1183. fJackInputData->mBuffers[i].mNumberChannels = 1;
  1184. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(jack_default_audio_sample_t);
  1185. }
  1186. return 0;
  1187. }
  1188. void JackCoreAudioDriver::DisposeBuffers()
  1189. {
  1190. if (fJackInputData) {
  1191. free(fJackInputData);
  1192. fJackInputData = 0;
  1193. }
  1194. }
  1195. void JackCoreAudioDriver::CloseAUHAL()
  1196. {
  1197. AudioUnitUninitialize(fAUHAL);
  1198. CloseComponent(fAUHAL);
  1199. }
  1200. int JackCoreAudioDriver::AddListeners()
  1201. {
  1202. OSStatus err = noErr;
  1203. // Add listeners
  1204. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback, this);
  1205. if (err != noErr) {
  1206. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDeviceProcessorOverload");
  1207. printError(err);
  1208. return -1;
  1209. }
  1210. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback, this);
  1211. if (err != noErr) {
  1212. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioHardwarePropertyDevices");
  1213. printError(err);
  1214. return -1;
  1215. }
  1216. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback, this);
  1217. if (err != noErr) {
  1218. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  1219. printError(err);
  1220. return -1;
  1221. }
  1222. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback, this);
  1223. if (err != noErr) {
  1224. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsRunning");
  1225. printError(err);
  1226. return -1;
  1227. }
  1228. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  1229. if (err != noErr) {
  1230. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  1231. printError(err);
  1232. return -1;
  1233. }
  1234. err = AudioDeviceAddPropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  1235. if (err != noErr) {
  1236. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  1237. printError(err);
  1238. return -1;
  1239. }
  1240. if (!fEngineControl->fSyncMode && fIOUsage != 1.f) {
  1241. UInt32 outSize = sizeof(float);
  1242. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyIOCycleUsage, outSize, &fIOUsage);
  1243. if (err != noErr) {
  1244. jack_error("Error calling AudioDeviceSetProperty kAudioDevicePropertyIOCycleUsage");
  1245. printError(err);
  1246. }
  1247. }
  1248. return 0;
  1249. }
  1250. void JackCoreAudioDriver::RemoveListeners()
  1251. {
  1252. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback);
  1253. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback);
  1254. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback);
  1255. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback);
  1256. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  1257. AudioDeviceRemovePropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  1258. }
  1259. int JackCoreAudioDriver::Open(jack_nframes_t buffer_size,
  1260. jack_nframes_t samplerate,
  1261. bool capturing,
  1262. bool playing,
  1263. int inchannels,
  1264. int outchannels,
  1265. bool monitor,
  1266. const char* capture_driver_uid,
  1267. const char* playback_driver_uid,
  1268. jack_nframes_t capture_latency,
  1269. jack_nframes_t playback_latency,
  1270. int async_output_latency,
  1271. int computation_grain,
  1272. bool hogged,
  1273. bool clock_drift)
  1274. {
  1275. int in_nChannels = 0;
  1276. int out_nChannels = 0;
  1277. char capture_driver_name[256];
  1278. char playback_driver_name[256];
  1279. // Keep initial state
  1280. strcpy(fCaptureUID, capture_driver_uid);
  1281. strcpy(fPlaybackUID, playback_driver_uid);
  1282. fCaptureLatency = capture_latency;
  1283. fPlaybackLatency = playback_latency;
  1284. fIOUsage = float(async_output_latency) / 100.f;
  1285. fComputationGrain = float(computation_grain) / 100.f;
  1286. fHogged = hogged;
  1287. fClockDriftCompensate = clock_drift;
  1288. SInt32 major;
  1289. SInt32 minor;
  1290. Gestalt(gestaltSystemVersionMajor, &major);
  1291. Gestalt(gestaltSystemVersionMinor, &minor);
  1292. // Starting with 10.6 systems, the HAL notification thread is created internally
  1293. if (major == 10 && minor >= 6) {
  1294. CFRunLoopRef theRunLoop = NULL;
  1295. AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  1296. OSStatus osErr = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
  1297. if (osErr != noErr) {
  1298. jack_error("JackCoreAudioDriver::Open kAudioHardwarePropertyRunLoop error");
  1299. printError(osErr);
  1300. }
  1301. }
  1302. if (SetupDevices(capture_driver_uid, playback_driver_uid, capture_driver_name, playback_driver_name, samplerate) < 0)
  1303. goto error;
  1304. // Generic JackAudioDriver Open
  1305. if (JackAudioDriver::Open(buffer_size, samplerate, capturing, playing, inchannels, outchannels, monitor, capture_driver_name, playback_driver_name, capture_latency, playback_latency) != 0)
  1306. goto error;
  1307. if (SetupChannels(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, true) < 0)
  1308. goto error;
  1309. if (SetupBufferSize(buffer_size) < 0)
  1310. goto error;
  1311. if (SetupSampleRate(samplerate) < 0)
  1312. goto error;
  1313. if (OpenAUHAL(capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels, buffer_size, samplerate) < 0)
  1314. goto error;
  1315. if (capturing && inchannels > 0)
  1316. if (SetupBuffers(inchannels) < 0)
  1317. goto error;
  1318. if (AddListeners() < 0)
  1319. goto error;
  1320. // Core driver may have changed the in/out values
  1321. fCaptureChannels = inchannels;
  1322. fPlaybackChannels = outchannels;
  1323. return noErr;
  1324. error:
  1325. Close();
  1326. return -1;
  1327. }
  1328. int JackCoreAudioDriver::Close()
  1329. {
  1330. jack_log("JackCoreAudioDriver::Close");
  1331. // Generic audio driver close
  1332. int res = JackAudioDriver::Close();
  1333. RemoveListeners();
  1334. DisposeBuffers();
  1335. CloseAUHAL();
  1336. DestroyAggregateDevice();
  1337. return res;
  1338. }
  1339. void JackCoreAudioDriver::UpdateLatencies()
  1340. {
  1341. UInt32 size;
  1342. OSStatus err;
  1343. jack_latency_range_t range;
  1344. range.max = fEngineControl->fBufferSize;
  1345. range.min = fEngineControl->fBufferSize;
  1346. for (int i = 0; i < fCaptureChannels; i++) {
  1347. size = sizeof(UInt32);
  1348. UInt32 value1 = 0;
  1349. UInt32 value2 = 0;
  1350. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertyLatency, &size, &value1);
  1351. if (err != noErr)
  1352. jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error");
  1353. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertySafetyOffset, &size, &value2);
  1354. if (err != noErr)
  1355. jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error");
  1356. range.min = range.max = fEngineControl->fBufferSize + value1 + value2 + fCaptureLatency;
  1357. fGraphManager->GetPort(fCapturePortList[i])->SetLatencyRange(JackCaptureLatency, &range);
  1358. }
  1359. for (int i = 0; i < fPlaybackChannels; i++) {
  1360. size = sizeof(UInt32);
  1361. UInt32 value1 = 0;
  1362. UInt32 value2 = 0;
  1363. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertyLatency, &size, &value1);
  1364. if (err != noErr)
  1365. jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error");
  1366. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertySafetyOffset, &size, &value2);
  1367. if (err != noErr)
  1368. jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error");
  1369. // Add more latency if "async" mode is used...
  1370. range.min = range.max
  1371. = fEngineControl->fBufferSize + ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize * fIOUsage) + value1 + value2 + fPlaybackLatency;
  1372. fGraphManager->GetPort(fPlaybackPortList[i])->SetLatencyRange(JackPlaybackLatency, &range);
  1373. // Monitor port
  1374. if (fWithMonitorPorts) {
  1375. range.min = range.max = fEngineControl->fBufferSize;
  1376. fGraphManager->GetPort(fMonitorPortList[i])->SetLatencyRange(JackCaptureLatency, &range);
  1377. }
  1378. }
  1379. }
  1380. int JackCoreAudioDriver::Attach()
  1381. {
  1382. OSStatus err;
  1383. JackPort* port;
  1384. jack_port_id_t port_index;
  1385. UInt32 size;
  1386. Boolean isWritable;
  1387. char channel_name[64];
  1388. char name[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  1389. char alias[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  1390. jack_log("JackCoreAudioDriver::Attach fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
  1391. for (int i = 0; i < fCaptureChannels; i++) {
  1392. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, &isWritable);
  1393. if (err != noErr)
  1394. jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error");
  1395. if (err == noErr && size > 0) {
  1396. err = AudioDeviceGetProperty(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, channel_name);
  1397. if (err != noErr)
  1398. jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error");
  1399. snprintf(alias, sizeof(alias) - 1, "%s:%s:out_%s%u", fAliasName, fCaptureDriverName, channel_name, i + 1);
  1400. } else {
  1401. snprintf(alias, sizeof(alias) - 1, "%s:%s:out%u", fAliasName, fCaptureDriverName, i + 1);
  1402. }
  1403. snprintf(name, sizeof(name) - 1, "%s:capture_%d", fClientControl.fName, i + 1);
  1404. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, CaptureDriverFlags, fEngineControl->fBufferSize)) == NO_PORT) {
  1405. jack_error("Cannot register port for %s", name);
  1406. return -1;
  1407. }
  1408. port = fGraphManager->GetPort(port_index);
  1409. port->SetAlias(alias);
  1410. fCapturePortList[i] = port_index;
  1411. }
  1412. for (int i = 0; i < fPlaybackChannels; i++) {
  1413. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, &isWritable);
  1414. if (err != noErr)
  1415. jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error");
  1416. if (err == noErr && size > 0) {
  1417. err = AudioDeviceGetProperty(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, channel_name);
  1418. if (err != noErr)
  1419. jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error");
  1420. snprintf(alias, sizeof(alias) - 1, "%s:%s:in_%s%u", fAliasName, fPlaybackDriverName, channel_name, i + 1);
  1421. } else {
  1422. snprintf(alias, sizeof(alias) - 1, "%s:%s:in%u", fAliasName, fPlaybackDriverName, i + 1);
  1423. }
  1424. snprintf(name, sizeof(name) - 1, "%s:playback_%d", fClientControl.fName, i + 1);
  1425. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, PlaybackDriverFlags, fEngineControl->fBufferSize)) == NO_PORT) {
  1426. jack_error("Cannot register port for %s", name);
  1427. return -1;
  1428. }
  1429. port = fGraphManager->GetPort(port_index);
  1430. port->SetAlias(alias);
  1431. fPlaybackPortList[i] = port_index;
  1432. // Monitor ports
  1433. if (fWithMonitorPorts) {
  1434. jack_log("Create monitor port");
  1435. snprintf(name, sizeof(name) - 1, "%s:monitor_%u", fClientControl.fName, i + 1);
  1436. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, MonitorDriverFlags, fEngineControl->fBufferSize)) == NO_PORT) {
  1437. jack_error("Cannot register monitor port for %s", name);
  1438. return -1;
  1439. } else {
  1440. fMonitorPortList[i] = port_index;
  1441. }
  1442. }
  1443. }
  1444. UpdateLatencies();
  1445. // Input buffers do no change : prepare them only once
  1446. for (int i = 0; i < fCaptureChannels; i++) {
  1447. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1448. }
  1449. return 0;
  1450. }
  1451. int JackCoreAudioDriver::Start()
  1452. {
  1453. jack_log("JackCoreAudioDriver::Start");
  1454. if (JackAudioDriver::Start() >= 0) {
  1455. OSStatus err = AudioOutputUnitStart(fAUHAL);
  1456. if (err == noErr) {
  1457. // Waiting for Measure callback to be called (= driver has started)
  1458. fState = false;
  1459. int count = 0;
  1460. while (!fState && count++ < WAIT_COUNTER) {
  1461. usleep(100000);
  1462. jack_log("JackCoreAudioDriver::Start wait count = %d", count);
  1463. }
  1464. if (count < WAIT_COUNTER) {
  1465. jack_info("CoreAudio driver is running...");
  1466. return 0;
  1467. }
  1468. jack_error("CoreAudio driver cannot start...");
  1469. }
  1470. JackAudioDriver::Stop();
  1471. }
  1472. return -1;
  1473. }
  1474. int JackCoreAudioDriver::Stop()
  1475. {
  1476. jack_log("JackCoreAudioDriver::Stop");
  1477. int res = (AudioOutputUnitStop(fAUHAL) == noErr) ? 0 : -1;
  1478. if (JackAudioDriver::Stop() < 0) {
  1479. res = -1;
  1480. }
  1481. return res;
  1482. }
  1483. int JackCoreAudioDriver::SetBufferSize(jack_nframes_t buffer_size)
  1484. {
  1485. UInt32 outSize = sizeof(UInt32);
  1486. OSStatus err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
  1487. if (err != noErr) {
  1488. jack_error("Cannot set buffer size %ld", buffer_size);
  1489. printError(err);
  1490. return -1;
  1491. }
  1492. JackAudioDriver::SetBufferSize(buffer_size); // Generic change, never fails
  1493. // CoreAudio specific
  1494. UpdateLatencies();
  1495. // Input buffers do no change : prepare them only once
  1496. for (int i = 0; i < fCaptureChannels; i++) {
  1497. fJackInputData->mBuffers[i].mNumberChannels = 1;
  1498. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(jack_default_audio_sample_t);
  1499. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1500. }
  1501. return 0;
  1502. }
  1503. bool JackCoreAudioDriver::TakeHogAux(AudioDeviceID deviceID, bool isInput)
  1504. {
  1505. pid_t hog_pid;
  1506. OSStatus err;
  1507. UInt32 propSize = sizeof(hog_pid);
  1508. err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyHogMode, &propSize, &hog_pid);
  1509. if (err) {
  1510. jack_error("Cannot read hog state...");
  1511. printError(err);
  1512. }
  1513. if (hog_pid != getpid()) {
  1514. hog_pid = getpid();
  1515. err = AudioDeviceSetProperty(deviceID, 0, 0, isInput, kAudioDevicePropertyHogMode, propSize, &hog_pid);
  1516. if (err != noErr) {
  1517. jack_error("Can't hog device = %d because it's being hogged by another program or cannot be hogged", deviceID);
  1518. return false;
  1519. }
  1520. }
  1521. return true;
  1522. }
  1523. bool JackCoreAudioDriver::TakeHog()
  1524. {
  1525. OSStatus err = noErr;
  1526. AudioObjectID sub_device[32];
  1527. UInt32 outSize = sizeof(sub_device);
  1528. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  1529. if (err != noErr) {
  1530. jack_log("Device does not have subdevices");
  1531. return TakeHogAux(fDeviceID, true);
  1532. } else {
  1533. int num_devices = outSize / sizeof(AudioObjectID);
  1534. jack_log("Device does has %d subdevices", num_devices);
  1535. for (int i = 0; i < num_devices; i++) {
  1536. if (!TakeHogAux(sub_device[i], true)) {
  1537. return false;
  1538. }
  1539. }
  1540. return true;
  1541. }
  1542. }
  1543. bool JackCoreAudioDriver::IsAggregateDevice(AudioDeviceID device)
  1544. {
  1545. UInt32 deviceType, outSize = sizeof(UInt32);
  1546. OSStatus err = AudioDeviceGetProperty(device, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyTransportType, &outSize, &deviceType);
  1547. if (err != noErr) {
  1548. jack_log("JackCoreAudioDriver::IsAggregateDevice kAudioDevicePropertyTransportType error");
  1549. return false;
  1550. } else {
  1551. return (deviceType == kAudioDeviceTransportTypeAggregate);
  1552. }
  1553. }
  1554. } // end of namespace
  1555. #ifdef __cplusplus
  1556. extern "C"
  1557. {
  1558. #endif
  1559. SERVER_EXPORT jack_driver_desc_t* driver_get_descriptor()
  1560. {
  1561. jack_driver_desc_t * desc;
  1562. jack_driver_desc_filler_t filler;
  1563. jack_driver_param_value_t value;
  1564. desc = jack_driver_descriptor_construct("coreaudio", "Apple CoreAudio API based audio backend", &filler);
  1565. value.i = -1;
  1566. jack_driver_descriptor_add_parameter(desc, &filler, "channels", 'c', JackDriverParamInt, &value, NULL, "Maximum number of channels", "Maximum number of channels. If -1, max possible number of channels will be used");
  1567. jack_driver_descriptor_add_parameter(desc, &filler, "inchannels", 'i', JackDriverParamInt, &value, NULL, "Maximum number of input channels", "Maximum number of input channels. If -1, max possible number of input channels will be used");
  1568. jack_driver_descriptor_add_parameter(desc, &filler, "outchannels", 'o', JackDriverParamInt, &value, NULL, "Maximum number of output channels", "Maximum number of output channels. If -1, max possible number of output channels will be used");
  1569. value.str[0] = 0;
  1570. jack_driver_descriptor_add_parameter(desc, &filler, "capture", 'C', JackDriverParamString, &value, NULL, "Input CoreAudio device name", NULL);
  1571. jack_driver_descriptor_add_parameter(desc, &filler, "playback", 'P', JackDriverParamString, &value, NULL, "Output CoreAudio device name", NULL);
  1572. value.i = 0;
  1573. jack_driver_descriptor_add_parameter(desc, &filler, "monitor", 'm', JackDriverParamBool, &value, NULL, "Provide monitor ports for the output", NULL);
  1574. value.i = TRUE;
  1575. jack_driver_descriptor_add_parameter(desc, &filler, "duplex", 'D', JackDriverParamBool, &value, NULL, "Provide both capture and playback ports", NULL);
  1576. value.ui = 44100U;
  1577. jack_driver_descriptor_add_parameter(desc, &filler, "rate", 'r', JackDriverParamUInt, &value, NULL, "Sample rate", NULL);
  1578. value.ui = 128U;
  1579. jack_driver_descriptor_add_parameter(desc, &filler, "period", 'p', JackDriverParamUInt, &value, NULL, "Frames per period", NULL);
  1580. value.str[0] = 0;
  1581. jack_driver_descriptor_add_parameter(desc, &filler, "device", 'd', JackDriverParamString, &value, NULL, "CoreAudio device name", NULL);
  1582. value.ui = 0;
  1583. jack_driver_descriptor_add_parameter(desc, &filler, "input-latency", 'I', JackDriverParamUInt, &value, NULL, "Extra input latency (frames)", NULL);
  1584. jack_driver_descriptor_add_parameter(desc, &filler, "output-latency", 'O', JackDriverParamUInt, &value, NULL, "Extra output latency (frames)", NULL);
  1585. value.i = FALSE;
  1586. jack_driver_descriptor_add_parameter(desc, &filler, "list-devices", 'l', JackDriverParamBool, &value, NULL, "Display available CoreAudio devices", NULL);
  1587. value.i = FALSE;
  1588. jack_driver_descriptor_add_parameter(desc, &filler, "hog", 'H', JackDriverParamBool, &value, NULL, "Take exclusive access of the audio device", NULL);
  1589. value.ui = 100;
  1590. jack_driver_descriptor_add_parameter(desc, &filler, "async-latency", 'L', JackDriverParamUInt, &value, NULL, "Extra output latency in asynchronous mode (percent)", NULL);
  1591. value.ui = 100;
  1592. jack_driver_descriptor_add_parameter(desc, &filler, "grain", 'G', JackDriverParamUInt, &value, NULL, "Computation grain in RT thread (percent)", NULL);
  1593. value.i = FALSE;
  1594. jack_driver_descriptor_add_parameter(desc, &filler, "clock-drift", 's', JackDriverParamBool, &value, NULL, "Clock drift compensation", "Whether to compensate clock drift in dynamically created aggregate device");
  1595. return desc;
  1596. }
  1597. SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
  1598. {
  1599. jack_nframes_t srate = 44100;
  1600. jack_nframes_t frames_per_interrupt = 128;
  1601. bool capture = false;
  1602. bool playback = false;
  1603. int chan_in = -1; // Default: if not explicitely set, then max possible will be used...
  1604. int chan_out = -1; // Default: if not explicitely set, then max possible will be used...
  1605. bool monitor = false;
  1606. const char* capture_driver_uid = "";
  1607. const char* playback_driver_uid = "";
  1608. const JSList *node;
  1609. const jack_driver_param_t *param;
  1610. jack_nframes_t systemic_input_latency = 0;
  1611. jack_nframes_t systemic_output_latency = 0;
  1612. int async_output_latency = 100;
  1613. int computation_grain = -1;
  1614. bool hogged = false;
  1615. bool clock_drift = false;
  1616. for (node = params; node; node = jack_slist_next(node)) {
  1617. param = (const jack_driver_param_t *) node->data;
  1618. switch (param->character) {
  1619. case 'd':
  1620. capture_driver_uid = param->value.str;
  1621. playback_driver_uid = param->value.str;
  1622. break;
  1623. case 'D':
  1624. capture = true;
  1625. playback = true;
  1626. break;
  1627. case 'c':
  1628. chan_in = chan_out = (int)param->value.ui;
  1629. break;
  1630. case 'i':
  1631. chan_in = (int)param->value.ui;
  1632. break;
  1633. case 'o':
  1634. chan_out = (int)param->value.ui;
  1635. break;
  1636. case 'C':
  1637. capture = true;
  1638. if (strcmp(param->value.str, "none") != 0) {
  1639. capture_driver_uid = param->value.str;
  1640. }
  1641. break;
  1642. case 'P':
  1643. playback = true;
  1644. if (strcmp(param->value.str, "none") != 0) {
  1645. playback_driver_uid = param->value.str;
  1646. }
  1647. break;
  1648. case 'm':
  1649. monitor = param->value.i;
  1650. break;
  1651. case 'r':
  1652. srate = param->value.ui;
  1653. break;
  1654. case 'p':
  1655. frames_per_interrupt = (unsigned int)param->value.ui;
  1656. break;
  1657. case 'I':
  1658. systemic_input_latency = param->value.ui;
  1659. break;
  1660. case 'O':
  1661. systemic_output_latency = param->value.ui;
  1662. break;
  1663. case 'l':
  1664. Jack::DisplayDeviceNames();
  1665. break;
  1666. case 'H':
  1667. hogged = true;
  1668. break;
  1669. case 'L':
  1670. async_output_latency = param->value.ui;
  1671. break;
  1672. case 'G':
  1673. computation_grain = param->value.ui;
  1674. break;
  1675. case 's':
  1676. clock_drift = true;
  1677. break;
  1678. }
  1679. }
  1680. /* duplex is the default */
  1681. if (!capture && !playback) {
  1682. capture = true;
  1683. playback = true;
  1684. }
  1685. Jack::JackCoreAudioDriver* driver = new Jack::JackCoreAudioDriver("system", "coreaudio", engine, table);
  1686. if (driver->Open(frames_per_interrupt, srate, capture, playback, chan_in, chan_out, monitor, capture_driver_uid,
  1687. playback_driver_uid, systemic_input_latency, systemic_output_latency, async_output_latency, computation_grain, hogged, clock_drift) == 0) {
  1688. return driver;
  1689. } else {
  1690. delete driver;
  1691. return NULL;
  1692. }
  1693. }
  1694. #ifdef __cplusplus
  1695. }
  1696. #endif