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.

2121 lines
83KB

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