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.

2103 lines
82KB

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