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.

2465 lines
94KB

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