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.

2334 lines
90KB

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