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.

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