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.

2081 lines
81KB

  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. int JackCoreAudioDriver::Attach()
  1337. {
  1338. OSStatus err;
  1339. JackPort* port;
  1340. jack_port_id_t port_index;
  1341. UInt32 size;
  1342. Boolean isWritable;
  1343. char channel_name[64];
  1344. char name[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  1345. char alias[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
  1346. jack_latency_range_t range;
  1347. jack_log("JackCoreAudioDriver::Attach fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
  1348. for (int i = 0; i < fCaptureChannels; i++) {
  1349. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, &isWritable);
  1350. if (err != noErr)
  1351. jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error");
  1352. if (err == noErr && size > 0) {
  1353. err = AudioDeviceGetProperty(fDeviceID, i + 1, true, kAudioDevicePropertyChannelName, &size, channel_name);
  1354. if (err != noErr)
  1355. jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error");
  1356. snprintf(alias, sizeof(alias) - 1, "%s:%s:out_%s%u", fAliasName, fCaptureDriverName, channel_name, i + 1);
  1357. } else {
  1358. snprintf(alias, sizeof(alias) - 1, "%s:%s:out%u", fAliasName, fCaptureDriverName, i + 1);
  1359. }
  1360. snprintf(name, sizeof(name) - 1, "%s:capture_%d", fClientControl.fName, i + 1);
  1361. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, CaptureDriverFlags, fEngineControl->fBufferSize)) == NO_PORT) {
  1362. jack_error("Cannot register port for %s", name);
  1363. return -1;
  1364. }
  1365. size = sizeof(UInt32);
  1366. UInt32 value1 = 0;
  1367. UInt32 value2 = 0;
  1368. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertyLatency, &size, &value1);
  1369. if (err != noErr)
  1370. jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error");
  1371. err = AudioDeviceGetProperty(fDeviceID, 0, true, kAudioDevicePropertySafetyOffset, &size, &value2);
  1372. if (err != noErr)
  1373. jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error");
  1374. port = fGraphManager->GetPort(port_index);
  1375. port->SetAlias(alias);
  1376. range.min = range.max = fEngineControl->fBufferSize + value1 + value2 + fCaptureLatency;
  1377. port->SetLatencyRange(JackCaptureLatency, &range);
  1378. fCapturePortList[i] = port_index;
  1379. }
  1380. for (int i = 0; i < fPlaybackChannels; i++) {
  1381. err = AudioDeviceGetPropertyInfo(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, &isWritable);
  1382. if (err != noErr)
  1383. jack_log("AudioDeviceGetPropertyInfo kAudioDevicePropertyChannelName error");
  1384. if (err == noErr && size > 0) {
  1385. err = AudioDeviceGetProperty(fDeviceID, i + 1, false, kAudioDevicePropertyChannelName, &size, channel_name);
  1386. if (err != noErr)
  1387. jack_log("AudioDeviceGetProperty kAudioDevicePropertyChannelName error");
  1388. snprintf(alias, sizeof(alias) - 1, "%s:%s:in_%s%u", fAliasName, fPlaybackDriverName, channel_name, i + 1);
  1389. } else {
  1390. snprintf(alias, sizeof(alias) - 1, "%s:%s:in%u", fAliasName, fPlaybackDriverName, i + 1);
  1391. }
  1392. snprintf(name, sizeof(name) - 1, "%s:playback_%d", fClientControl.fName, i + 1);
  1393. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, PlaybackDriverFlags, fEngineControl->fBufferSize)) == NO_PORT) {
  1394. jack_error("Cannot register port for %s", name);
  1395. return -1;
  1396. }
  1397. size = sizeof(UInt32);
  1398. UInt32 value1 = 0;
  1399. UInt32 value2 = 0;
  1400. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertyLatency, &size, &value1);
  1401. if (err != noErr)
  1402. jack_log("AudioDeviceGetProperty kAudioDevicePropertyLatency error");
  1403. err = AudioDeviceGetProperty(fDeviceID, 0, false, kAudioDevicePropertySafetyOffset, &size, &value2);
  1404. if (err != noErr)
  1405. jack_log("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error");
  1406. port = fGraphManager->GetPort(port_index);
  1407. port->SetAlias(alias);
  1408. // Add more latency if "async" mode is used...
  1409. range.min = range.max = fEngineControl->fBufferSize + ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize * fIOUsage) + value1 + value2 + fPlaybackLatency;
  1410. port->SetLatencyRange(JackPlaybackLatency, &range);
  1411. fPlaybackPortList[i] = port_index;
  1412. // Monitor ports
  1413. if (fWithMonitorPorts) {
  1414. jack_log("Create monitor port");
  1415. snprintf(name, sizeof(name) - 1, "%s:monitor_%u", fClientControl.fName, i + 1);
  1416. if ((port_index = fGraphManager->AllocatePort(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, MonitorDriverFlags, fEngineControl->fBufferSize)) == NO_PORT) {
  1417. jack_error("Cannot register monitor port for %s", name);
  1418. return -1;
  1419. } else {
  1420. port = fGraphManager->GetPort(port_index);
  1421. range.min = range.max = fEngineControl->fBufferSize;
  1422. port->SetLatencyRange(JackCaptureLatency, &range);
  1423. fMonitorPortList[i] = port_index;
  1424. }
  1425. }
  1426. }
  1427. // Input buffers do no change : prepare them only once
  1428. for (int i = 0; i < fCaptureChannels; i++) {
  1429. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1430. }
  1431. return 0;
  1432. }
  1433. int JackCoreAudioDriver::Start()
  1434. {
  1435. jack_log("JackCoreAudioDriver::Start");
  1436. if (JackAudioDriver::Start() >= 0) {
  1437. OSStatus err = AudioOutputUnitStart(fAUHAL);
  1438. if (err == noErr) {
  1439. // Waiting for Measure callback to be called (= driver has started)
  1440. fState = false;
  1441. int count = 0;
  1442. while (!fState && count++ < WAIT_COUNTER) {
  1443. usleep(100000);
  1444. jack_log("JackCoreAudioDriver::Start wait count = %d", count);
  1445. }
  1446. if (count < WAIT_COUNTER) {
  1447. jack_info("CoreAudio driver is running...");
  1448. return 0;
  1449. }
  1450. jack_error("CoreAudio driver cannot start...");
  1451. }
  1452. JackAudioDriver::Stop();
  1453. }
  1454. return -1;
  1455. }
  1456. int JackCoreAudioDriver::Stop()
  1457. {
  1458. jack_log("JackCoreAudioDriver::Stop");
  1459. int res = (AudioOutputUnitStop(fAUHAL) == noErr) ? 0 : -1;
  1460. if (JackAudioDriver::Stop() < 0) {
  1461. res = -1;
  1462. }
  1463. return res;
  1464. }
  1465. int JackCoreAudioDriver::SetBufferSize(jack_nframes_t buffer_size)
  1466. {
  1467. OSStatus err;
  1468. UInt32 outSize = sizeof(UInt32);
  1469. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
  1470. if (err != noErr) {
  1471. jack_error("Cannot set buffer size %ld", buffer_size);
  1472. printError(err);
  1473. return -1;
  1474. }
  1475. JackAudioDriver::SetBufferSize(buffer_size); // never fails
  1476. // Input buffers do no change : prepare them only once
  1477. for (int i = 0; i < fCaptureChannels; i++) {
  1478. fJackInputData->mBuffers[i].mNumberChannels = 1;
  1479. fJackInputData->mBuffers[i].mDataByteSize = fEngineControl->fBufferSize * sizeof(jack_default_audio_sample_t);
  1480. fJackInputData->mBuffers[i].mData = GetInputBuffer(i);
  1481. }
  1482. return 0;
  1483. }
  1484. bool JackCoreAudioDriver::TakeHogAux(AudioDeviceID deviceID, bool isInput)
  1485. {
  1486. pid_t hog_pid;
  1487. OSStatus err;
  1488. UInt32 propSize = sizeof(hog_pid);
  1489. err = AudioDeviceGetProperty(deviceID, 0, isInput, kAudioDevicePropertyHogMode, &propSize, &hog_pid);
  1490. if (err) {
  1491. jack_error("Cannot read hog state...");
  1492. printError(err);
  1493. }
  1494. if (hog_pid != getpid()) {
  1495. hog_pid = getpid();
  1496. err = AudioDeviceSetProperty(deviceID, 0, 0, isInput, kAudioDevicePropertyHogMode, propSize, &hog_pid);
  1497. if (err != noErr) {
  1498. jack_error("Can't hog device = %d because it's being hogged by another program or cannot be hogged", deviceID);
  1499. return false;
  1500. }
  1501. }
  1502. return true;
  1503. }
  1504. bool JackCoreAudioDriver::TakeHog()
  1505. {
  1506. OSStatus err = noErr;
  1507. AudioObjectID sub_device[32];
  1508. UInt32 outSize = sizeof(sub_device);
  1509. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  1510. if (err != noErr) {
  1511. jack_log("Device does not have subdevices");
  1512. return TakeHogAux(fDeviceID, true);
  1513. } else {
  1514. int num_devices = outSize / sizeof(AudioObjectID);
  1515. jack_log("Device does has %d subdevices", num_devices);
  1516. for (int i = 0; i < num_devices; i++) {
  1517. if (!TakeHogAux(sub_device[i], true)) {
  1518. return false;
  1519. }
  1520. }
  1521. return true;
  1522. }
  1523. }
  1524. bool JackCoreAudioDriver::IsAggregateDevice(AudioDeviceID device)
  1525. {
  1526. UInt32 deviceType, outSize = sizeof(UInt32);
  1527. OSStatus err = AudioDeviceGetProperty(device, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyTransportType, &outSize, &deviceType);
  1528. if (err != noErr) {
  1529. jack_log("JackCoreAudioDriver::IsAggregateDevice kAudioDevicePropertyTransportType error");
  1530. return false;
  1531. } else {
  1532. return (deviceType == kAudioDeviceTransportTypeAggregate);
  1533. }
  1534. }
  1535. } // end of namespace
  1536. #ifdef __cplusplus
  1537. extern "C"
  1538. {
  1539. #endif
  1540. SERVER_EXPORT jack_driver_desc_t* driver_get_descriptor()
  1541. {
  1542. jack_driver_desc_t *desc;
  1543. unsigned int i;
  1544. desc = (jack_driver_desc_t*)calloc(1, sizeof(jack_driver_desc_t));
  1545. strcpy(desc->name, "coreaudio"); // size MUST be less then JACK_DRIVER_NAME_MAX + 1
  1546. strcpy(desc->desc, "Apple CoreAudio API based audio backend"); // size MUST be less then JACK_DRIVER_PARAM_DESC + 1
  1547. desc->nparams = 17;
  1548. desc->params = (jack_driver_param_desc_t*)calloc(desc->nparams, sizeof(jack_driver_param_desc_t));
  1549. i = 0;
  1550. strcpy(desc->params[i].name, "channels");
  1551. desc->params[i].character = 'c';
  1552. desc->params[i].type = JackDriverParamInt;
  1553. desc->params[i].value.ui = -1;
  1554. strcpy(desc->params[i].short_desc, "Maximum number of channels");
  1555. strcpy(desc->params[i].long_desc, "Maximum number of channels. If -1, max possible number of channels will be used");
  1556. i++;
  1557. strcpy(desc->params[i].name, "inchannels");
  1558. desc->params[i].character = 'i';
  1559. desc->params[i].type = JackDriverParamInt;
  1560. desc->params[i].value.ui = -1;
  1561. strcpy(desc->params[i].short_desc, "Maximum number of input channels");
  1562. strcpy(desc->params[i].long_desc, "Maximum number of input channels. If -1, max possible number of input channels will be used");
  1563. i++;
  1564. strcpy(desc->params[i].name, "outchannels");
  1565. desc->params[i].character = 'o';
  1566. desc->params[i].type = JackDriverParamInt;
  1567. desc->params[i].value.ui = -1;
  1568. strcpy(desc->params[i].short_desc, "Maximum number of output channels");
  1569. strcpy(desc->params[i].long_desc, "Maximum number of output channels. If -1, max possible number of output channels will be used");
  1570. i++;
  1571. strcpy(desc->params[i].name, "capture");
  1572. desc->params[i].character = 'C';
  1573. desc->params[i].type = JackDriverParamString;
  1574. strcpy(desc->params[i].short_desc, "Input CoreAudio device name");
  1575. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1576. i++;
  1577. strcpy(desc->params[i].name, "playback");
  1578. desc->params[i].character = 'P';
  1579. desc->params[i].type = JackDriverParamString;
  1580. strcpy(desc->params[i].short_desc, "Output CoreAudio device name");
  1581. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1582. i++;
  1583. strcpy (desc->params[i].name, "monitor");
  1584. desc->params[i].character = 'm';
  1585. desc->params[i].type = JackDriverParamBool;
  1586. desc->params[i].value.i = 0;
  1587. strcpy(desc->params[i].short_desc, "Provide monitor ports for the output");
  1588. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1589. i++;
  1590. strcpy(desc->params[i].name, "duplex");
  1591. desc->params[i].character = 'D';
  1592. desc->params[i].type = JackDriverParamBool;
  1593. desc->params[i].value.i = TRUE;
  1594. strcpy(desc->params[i].short_desc, "Provide both capture and playback ports");
  1595. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1596. i++;
  1597. strcpy(desc->params[i].name, "rate");
  1598. desc->params[i].character = 'r';
  1599. desc->params[i].type = JackDriverParamUInt;
  1600. desc->params[i].value.ui = 44100U;
  1601. strcpy(desc->params[i].short_desc, "Sample rate");
  1602. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1603. i++;
  1604. strcpy(desc->params[i].name, "period");
  1605. desc->params[i].character = 'p';
  1606. desc->params[i].type = JackDriverParamUInt;
  1607. desc->params[i].value.ui = 128U;
  1608. strcpy(desc->params[i].short_desc, "Frames per period");
  1609. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1610. i++;
  1611. strcpy(desc->params[i].name, "device");
  1612. desc->params[i].character = 'd';
  1613. desc->params[i].type = JackDriverParamString;
  1614. strcpy(desc->params[i].short_desc, "CoreAudio device name");
  1615. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1616. i++;
  1617. strcpy(desc->params[i].name, "input-latency");
  1618. desc->params[i].character = 'I';
  1619. desc->params[i].type = JackDriverParamUInt;
  1620. desc->params[i].value.i = 0;
  1621. strcpy(desc->params[i].short_desc, "Extra input latency (frames)");
  1622. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1623. i++;
  1624. strcpy(desc->params[i].name, "output-latency");
  1625. desc->params[i].character = 'O';
  1626. desc->params[i].type = JackDriverParamUInt;
  1627. desc->params[i].value.i = 0;
  1628. strcpy(desc->params[i].short_desc, "Extra output latency (frames)");
  1629. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1630. i++;
  1631. strcpy(desc->params[i].name, "list-devices");
  1632. desc->params[i].character = 'l';
  1633. desc->params[i].type = JackDriverParamBool;
  1634. desc->params[i].value.i = FALSE;
  1635. strcpy(desc->params[i].short_desc, "Display available CoreAudio devices");
  1636. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1637. i++;
  1638. strcpy(desc->params[i].name, "hog");
  1639. desc->params[i].character = 'H';
  1640. desc->params[i].type = JackDriverParamBool;
  1641. desc->params[i].value.i = FALSE;
  1642. strcpy(desc->params[i].short_desc, "Take exclusive access of the audio device");
  1643. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1644. i++;
  1645. strcpy(desc->params[i].name, "async-latency");
  1646. desc->params[i].character = 'L';
  1647. desc->params[i].type = JackDriverParamUInt;
  1648. desc->params[i].value.i = 100;
  1649. strcpy(desc->params[i].short_desc, "Extra output latency in asynchronous mode (percent)");
  1650. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1651. i++;
  1652. strcpy(desc->params[i].name, "grain");
  1653. desc->params[i].character = 'G';
  1654. desc->params[i].type = JackDriverParamUInt;
  1655. desc->params[i].value.i = 100;
  1656. strcpy(desc->params[i].short_desc, "Computation grain in RT thread (percent)");
  1657. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  1658. i++;
  1659. strcpy(desc->params[i].name, "clock-drift");
  1660. desc->params[i].character = 's';
  1661. desc->params[i].type = JackDriverParamBool;
  1662. desc->params[i].value.i = FALSE;
  1663. strcpy(desc->params[i].short_desc, "Clock drift compensation");
  1664. strcpy(desc->params[i].long_desc, "Whether to compensate clock drift in dynamically created aggregate device");
  1665. return desc;
  1666. }
  1667. SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
  1668. {
  1669. jack_nframes_t srate = 44100;
  1670. jack_nframes_t frames_per_interrupt = 128;
  1671. bool capture = false;
  1672. bool playback = false;
  1673. int chan_in = -1; // Default: if not explicitely set, then max possible will be used...
  1674. int chan_out = -1; // Default: if not explicitely set, then max possible will be used...
  1675. bool monitor = false;
  1676. const char* capture_driver_uid = "";
  1677. const char* playback_driver_uid = "";
  1678. const JSList *node;
  1679. const jack_driver_param_t *param;
  1680. jack_nframes_t systemic_input_latency = 0;
  1681. jack_nframes_t systemic_output_latency = 0;
  1682. int async_output_latency = 100;
  1683. int computation_grain = -1;
  1684. bool hogged = false;
  1685. bool clock_drift = false;
  1686. for (node = params; node; node = jack_slist_next(node)) {
  1687. param = (const jack_driver_param_t *) node->data;
  1688. switch (param->character) {
  1689. case 'd':
  1690. capture_driver_uid = param->value.str;
  1691. playback_driver_uid = param->value.str;
  1692. break;
  1693. case 'D':
  1694. capture = true;
  1695. playback = true;
  1696. break;
  1697. case 'c':
  1698. chan_in = chan_out = (int)param->value.ui;
  1699. break;
  1700. case 'i':
  1701. chan_in = (int)param->value.ui;
  1702. break;
  1703. case 'o':
  1704. chan_out = (int)param->value.ui;
  1705. break;
  1706. case 'C':
  1707. capture = true;
  1708. if (strcmp(param->value.str, "none") != 0) {
  1709. capture_driver_uid = param->value.str;
  1710. }
  1711. break;
  1712. case 'P':
  1713. playback = true;
  1714. if (strcmp(param->value.str, "none") != 0) {
  1715. playback_driver_uid = param->value.str;
  1716. }
  1717. break;
  1718. case 'm':
  1719. monitor = param->value.i;
  1720. break;
  1721. case 'r':
  1722. srate = param->value.ui;
  1723. break;
  1724. case 'p':
  1725. frames_per_interrupt = (unsigned int)param->value.ui;
  1726. break;
  1727. case 'I':
  1728. systemic_input_latency = param->value.ui;
  1729. break;
  1730. case 'O':
  1731. systemic_output_latency = param->value.ui;
  1732. break;
  1733. case 'l':
  1734. Jack::DisplayDeviceNames();
  1735. break;
  1736. case 'H':
  1737. hogged = true;
  1738. break;
  1739. case 'L':
  1740. async_output_latency = param->value.ui;
  1741. break;
  1742. case 'G':
  1743. computation_grain = param->value.ui;
  1744. break;
  1745. case 's':
  1746. clock_drift = true;
  1747. break;
  1748. }
  1749. }
  1750. /* duplex is the default */
  1751. if (!capture && !playback) {
  1752. capture = true;
  1753. playback = true;
  1754. }
  1755. Jack::JackCoreAudioDriver* driver = new Jack::JackCoreAudioDriver("system", "coreaudio", engine, table);
  1756. if (driver->Open(frames_per_interrupt, srate, capture, playback, chan_in, chan_out, monitor, capture_driver_uid,
  1757. playback_driver_uid, systemic_input_latency, systemic_output_latency, async_output_latency, computation_grain, hogged, clock_drift) == 0) {
  1758. return driver;
  1759. } else {
  1760. delete driver;
  1761. return NULL;
  1762. }
  1763. }
  1764. #ifdef __cplusplus
  1765. }
  1766. #endif