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.

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