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.

1555 lines
60KB

  1. /*
  2. Copyright (C) 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 "JackCoreAudioAdapter.h"
  16. #include "JackError.h"
  17. #include <unistd.h>
  18. #include <CoreServices/CoreServices.h>
  19. namespace Jack
  20. {
  21. static void PrintStreamDesc(AudioStreamBasicDescription *inDesc)
  22. {
  23. jack_log("- - - - - - - - - - - - - - - - - - - -");
  24. jack_log(" Sample Rate:%f", inDesc->mSampleRate);
  25. jack_log(" Format ID:%.*s", (int) sizeof(inDesc->mFormatID), (char*)&inDesc->mFormatID);
  26. jack_log(" Format Flags:%lX", inDesc->mFormatFlags);
  27. jack_log(" Bytes per Packet:%ld", inDesc->mBytesPerPacket);
  28. jack_log(" Frames per Packet:%ld", inDesc->mFramesPerPacket);
  29. jack_log(" Bytes per Frame:%ld", inDesc->mBytesPerFrame);
  30. jack_log(" Channels per Frame:%ld", inDesc->mChannelsPerFrame);
  31. jack_log(" Bits per Channel:%ld", inDesc->mBitsPerChannel);
  32. jack_log("- - - - - - - - - - - - - - - - - - - -");
  33. }
  34. static OSStatus DisplayDeviceNames()
  35. {
  36. UInt32 size;
  37. Boolean isWritable;
  38. int i, deviceNum;
  39. OSStatus err;
  40. CFStringRef UIname;
  41. err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
  42. if (err != noErr)
  43. return err;
  44. deviceNum = size / sizeof(AudioDeviceID);
  45. AudioDeviceID devices[deviceNum];
  46. err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
  47. if (err != noErr)
  48. return err;
  49. for (i = 0; i < deviceNum; i++) {
  50. char device_name[256];
  51. char internal_name[256];
  52. size = sizeof(CFStringRef);
  53. UIname = NULL;
  54. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  55. if (err == noErr) {
  56. CFStringGetCString(UIname, internal_name, 256, CFStringGetSystemEncoding());
  57. } else {
  58. goto error;
  59. }
  60. size = 256;
  61. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &size, device_name);
  62. if (err != noErr)
  63. return err;
  64. jack_info("Device name = \'%s\', internal_name = \'%s\' (to be used as -C, -P, or -d parameter)", device_name, internal_name);
  65. }
  66. return noErr;
  67. error:
  68. if (UIname != NULL)
  69. CFRelease(UIname);
  70. return err;
  71. }
  72. static void printError(OSStatus err)
  73. {
  74. switch (err) {
  75. case kAudioHardwareNoError:
  76. jack_log("error code : kAudioHardwareNoError");
  77. break;
  78. case kAudioConverterErr_FormatNotSupported:
  79. jack_log("error code : kAudioConverterErr_FormatNotSupported");
  80. break;
  81. case kAudioConverterErr_OperationNotSupported:
  82. jack_log("error code : kAudioConverterErr_OperationNotSupported");
  83. break;
  84. case kAudioConverterErr_PropertyNotSupported:
  85. jack_log("error code : kAudioConverterErr_PropertyNotSupported");
  86. break;
  87. case kAudioConverterErr_InvalidInputSize:
  88. jack_log("error code : kAudioConverterErr_InvalidInputSize");
  89. break;
  90. case kAudioConverterErr_InvalidOutputSize:
  91. jack_log("error code : kAudioConverterErr_InvalidOutputSize");
  92. break;
  93. case kAudioConverterErr_UnspecifiedError:
  94. jack_log("error code : kAudioConverterErr_UnspecifiedError");
  95. break;
  96. case kAudioConverterErr_BadPropertySizeError:
  97. jack_log("error code : kAudioConverterErr_BadPropertySizeError");
  98. break;
  99. case kAudioConverterErr_RequiresPacketDescriptionsError:
  100. jack_log("error code : kAudioConverterErr_RequiresPacketDescriptionsError");
  101. break;
  102. case kAudioConverterErr_InputSampleRateOutOfRange:
  103. jack_log("error code : kAudioConverterErr_InputSampleRateOutOfRange");
  104. break;
  105. case kAudioConverterErr_OutputSampleRateOutOfRange:
  106. jack_log("error code : kAudioConverterErr_OutputSampleRateOutOfRange");
  107. break;
  108. case kAudioHardwareNotRunningError:
  109. jack_log("error code : kAudioHardwareNotRunningError");
  110. break;
  111. case kAudioHardwareUnknownPropertyError:
  112. jack_log("error code : kAudioHardwareUnknownPropertyError");
  113. break;
  114. case kAudioHardwareIllegalOperationError:
  115. jack_log("error code : kAudioHardwareIllegalOperationError");
  116. break;
  117. case kAudioHardwareBadDeviceError:
  118. jack_log("error code : kAudioHardwareBadDeviceError");
  119. break;
  120. case kAudioHardwareBadStreamError:
  121. jack_log("error code : kAudioHardwareBadStreamError");
  122. break;
  123. case kAudioDeviceUnsupportedFormatError:
  124. jack_log("error code : kAudioDeviceUnsupportedFormatError");
  125. break;
  126. case kAudioDevicePermissionsError:
  127. jack_log("error code : kAudioDevicePermissionsError");
  128. break;
  129. case kAudioHardwareBadObjectError:
  130. jack_log("error code : kAudioHardwareBadObjectError");
  131. break;
  132. case kAudioHardwareUnsupportedOperationError:
  133. jack_log("error code : kAudioHardwareUnsupportedOperationError");
  134. break;
  135. default:
  136. jack_log("error code : unknown");
  137. break;
  138. }
  139. }
  140. OSStatus JackCoreAudioAdapter::SRNotificationCallback(AudioDeviceID inDevice,
  141. UInt32 inChannel,
  142. Boolean isInput,
  143. AudioDevicePropertyID inPropertyID,
  144. void* inClientData)
  145. {
  146. JackCoreAudioAdapter* driver = static_cast<JackCoreAudioAdapter*>(inClientData);
  147. switch (inPropertyID) {
  148. case kAudioDevicePropertyNominalSampleRate: {
  149. jack_log("JackCoreAudioAdapter::SRNotificationCallback kAudioDevicePropertyNominalSampleRate");
  150. driver->fState = true;
  151. break;
  152. }
  153. }
  154. return noErr;
  155. }
  156. // A better implementation would try to recover in case of hardware device change (see HALLAB HLFilePlayerWindowControllerAudioDevicePropertyListenerProc code)
  157. OSStatus JackCoreAudioAdapter::DeviceNotificationCallback(AudioDeviceID inDevice,
  158. UInt32 inChannel,
  159. Boolean isInput,
  160. AudioDevicePropertyID inPropertyID,
  161. void* inClientData)
  162. {
  163. switch (inPropertyID) {
  164. case kAudioDeviceProcessorOverload: {
  165. jack_error("JackCoreAudioAdapter::DeviceNotificationCallback kAudioDeviceProcessorOverload");
  166. break;
  167. }
  168. case kAudioDevicePropertyStreamConfiguration: {
  169. jack_error("Cannot handle kAudioDevicePropertyStreamConfiguration");
  170. return kAudioHardwareUnsupportedOperationError;
  171. }
  172. case kAudioDevicePropertyNominalSampleRate: {
  173. jack_error("Cannot handle kAudioDevicePropertyNominalSampleRate");
  174. return kAudioHardwareUnsupportedOperationError;
  175. }
  176. }
  177. return noErr;
  178. }
  179. int JackCoreAudioAdapter::AddListeners()
  180. {
  181. OSStatus err = noErr;
  182. // Add listeners
  183. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback, this);
  184. if (err != noErr) {
  185. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDeviceProcessorOverload");
  186. printError(err);
  187. return -1;
  188. }
  189. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback, this);
  190. if (err != noErr) {
  191. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioHardwarePropertyDevices");
  192. printError(err);
  193. return -1;
  194. }
  195. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback, this);
  196. if (err != noErr) {
  197. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  198. printError(err);
  199. return -1;
  200. }
  201. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback, this);
  202. if (err != noErr) {
  203. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsRunning");
  204. printError(err);
  205. return -1;
  206. }
  207. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  208. if (err != noErr) {
  209. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  210. printError(err);
  211. return -1;
  212. }
  213. err = AudioDeviceAddPropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  214. if (err != noErr) {
  215. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  216. printError(err);
  217. return -1;
  218. }
  219. return 0;
  220. }
  221. void JackCoreAudioAdapter::RemoveListeners()
  222. {
  223. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDeviceProcessorOverload, DeviceNotificationCallback);
  224. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback);
  225. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback);
  226. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback);
  227. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  228. AudioDeviceRemovePropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  229. }
  230. OSStatus JackCoreAudioAdapter::Render(void *inRefCon,
  231. AudioUnitRenderActionFlags *ioActionFlags,
  232. const AudioTimeStamp *inTimeStamp,
  233. UInt32 inBusNumber,
  234. UInt32 inNumberFrames,
  235. AudioBufferList *ioData)
  236. {
  237. JackCoreAudioAdapter* adapter = static_cast<JackCoreAudioAdapter*>(inRefCon);
  238. AudioUnitRender(adapter->fAUHAL, ioActionFlags, inTimeStamp, 1, inNumberFrames, adapter->fInputData);
  239. jack_default_audio_sample_t* inputBuffer[adapter->fCaptureChannels];
  240. jack_default_audio_sample_t* outputBuffer[adapter->fPlaybackChannels];
  241. for (int i = 0; i < adapter->fCaptureChannels; i++) {
  242. inputBuffer[i] = (jack_default_audio_sample_t*)adapter->fInputData->mBuffers[i].mData;
  243. }
  244. for (int i = 0; i < adapter->fPlaybackChannels; i++) {
  245. outputBuffer[i] = (jack_default_audio_sample_t*)ioData->mBuffers[i].mData;
  246. }
  247. adapter->PushAndPull((jack_default_audio_sample_t**)inputBuffer, (jack_default_audio_sample_t**)outputBuffer, inNumberFrames);
  248. return noErr;
  249. }
  250. JackCoreAudioAdapter::JackCoreAudioAdapter(jack_nframes_t buffer_size, jack_nframes_t sample_rate, const JSList* params)
  251. :JackAudioAdapterInterface(buffer_size, sample_rate), fInputData(0), fCapturing(false), fPlaying(false), fState(false)
  252. {
  253. const JSList* node;
  254. const jack_driver_param_t* param;
  255. int in_nChannels = 0;
  256. int out_nChannels = 0;
  257. char captureName[256];
  258. char playbackName[256];
  259. fCaptureUID[0] = 0;
  260. fPlaybackUID[0] = 0;
  261. fClockDriftCompensate = false;
  262. // Default values
  263. fCaptureChannels = -1;
  264. fPlaybackChannels = -1;
  265. SInt32 major;
  266. SInt32 minor;
  267. Gestalt(gestaltSystemVersionMajor, &major);
  268. Gestalt(gestaltSystemVersionMinor, &minor);
  269. // Starting with 10.6 systems, the HAL notification thread is created internally
  270. if (major == 10 && minor >= 6) {
  271. CFRunLoopRef theRunLoop = NULL;
  272. AudioObjectPropertyAddress theAddress = { kAudioHardwarePropertyRunLoop, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  273. OSStatus theError = AudioObjectSetPropertyData (kAudioObjectSystemObject, &theAddress, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
  274. if (theError != noErr) {
  275. jack_error("JackCoreAudioAdapter::Open kAudioHardwarePropertyRunLoop error");
  276. }
  277. }
  278. for (node = params; node; node = jack_slist_next(node)) {
  279. param = (const jack_driver_param_t*) node->data;
  280. switch (param->character) {
  281. case 'c' :
  282. fCaptureChannels = fPlaybackChannels = param->value.ui;
  283. break;
  284. case 'i':
  285. fCaptureChannels = param->value.ui;
  286. break;
  287. case 'o':
  288. fPlaybackChannels = param->value.ui;
  289. break;
  290. case 'C':
  291. fCapturing = true;
  292. strncpy(fCaptureUID, param->value.str, 256);
  293. break;
  294. case 'P':
  295. fPlaying = true;
  296. strncpy(fPlaybackUID, param->value.str, 256);
  297. break;
  298. case 'd':
  299. strncpy(fCaptureUID, param->value.str, 256);
  300. strncpy(fPlaybackUID, param->value.str, 256);
  301. break;
  302. case 'D':
  303. fCapturing = fPlaying = true;
  304. break;
  305. case 'r':
  306. SetAdaptedSampleRate(param->value.ui);
  307. break;
  308. case 'p':
  309. SetAdaptedBufferSize(param->value.ui);
  310. break;
  311. case 'l':
  312. DisplayDeviceNames();
  313. break;
  314. case 'q':
  315. fQuality = param->value.ui;
  316. break;
  317. case 'g':
  318. fRingbufferCurSize = param->value.ui;
  319. fAdaptative = false;
  320. break;
  321. case 's':
  322. fClockDriftCompensate = true;
  323. break;
  324. }
  325. }
  326. /* duplex is the default */
  327. if (!fCapturing && !fPlaying) {
  328. fCapturing = true;
  329. fPlaying = true;
  330. }
  331. if (SetupDevices(fCaptureUID, fPlaybackUID, captureName, playbackName, fAdaptedSampleRate) < 0) {
  332. throw std::bad_alloc();
  333. }
  334. if (SetupChannels(fCapturing, fPlaying, fCaptureChannels, fPlaybackChannels, in_nChannels, out_nChannels, true) < 0) {
  335. throw std::bad_alloc();
  336. }
  337. if (SetupBufferSize(fAdaptedBufferSize) < 0) {
  338. throw std::bad_alloc();
  339. }
  340. if (SetupSampleRate(fAdaptedSampleRate) < 0) {
  341. throw std::bad_alloc();
  342. }
  343. if (OpenAUHAL(fCapturing, fPlaying, fCaptureChannels, fPlaybackChannels, in_nChannels, out_nChannels, fAdaptedBufferSize, fAdaptedSampleRate) < 0) {
  344. throw std::bad_alloc();
  345. }
  346. if (fCapturing && fCaptureChannels > 0) {
  347. if (SetupBuffers(fCaptureChannels) < 0) {
  348. throw std::bad_alloc();
  349. }
  350. }
  351. if (AddListeners() < 0) {
  352. throw std::bad_alloc();
  353. }
  354. }
  355. OSStatus JackCoreAudioAdapter::GetDefaultDevice(AudioDeviceID* id)
  356. {
  357. OSStatus res;
  358. UInt32 theSize = sizeof(UInt32);
  359. AudioDeviceID inDefault;
  360. AudioDeviceID outDefault;
  361. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  362. return res;
  363. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  364. return res;
  365. jack_log("GetDefaultDevice: input = %ld output = %ld", inDefault, outDefault);
  366. // Get the device only if default input and output are the same
  367. if (inDefault != outDefault) {
  368. jack_error("Default input and output devices are not the same !!");
  369. return kAudioHardwareBadDeviceError;
  370. } else if (inDefault == 0) {
  371. jack_error("Default input and output devices are null !!");
  372. return kAudioHardwareBadDeviceError;
  373. } else {
  374. *id = inDefault;
  375. return noErr;
  376. }
  377. }
  378. OSStatus JackCoreAudioAdapter::GetTotalChannels(AudioDeviceID device, int& channelCount, bool isInput)
  379. {
  380. OSStatus err = noErr;
  381. UInt32 outSize;
  382. Boolean outWritable;
  383. channelCount = 0;
  384. err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, &outWritable);
  385. if (err == noErr) {
  386. AudioBufferList bufferList[outSize];
  387. err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, bufferList);
  388. if (err == noErr) {
  389. for (unsigned int i = 0; i < bufferList->mNumberBuffers; i++)
  390. channelCount += bufferList->mBuffers[i].mNumberChannels;
  391. }
  392. }
  393. return err;
  394. }
  395. OSStatus JackCoreAudioAdapter::GetDeviceIDFromUID(const char* UID, AudioDeviceID* id)
  396. {
  397. UInt32 size = sizeof(AudioValueTranslation);
  398. CFStringRef inIUD = CFStringCreateWithCString(NULL, UID, CFStringGetSystemEncoding());
  399. AudioValueTranslation value = { &inIUD, sizeof(CFStringRef), id, sizeof(AudioDeviceID) };
  400. if (inIUD == NULL) {
  401. return kAudioHardwareUnspecifiedError;
  402. } else {
  403. OSStatus res = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, &size, &value);
  404. CFRelease(inIUD);
  405. jack_log("GetDeviceIDFromUID %s %ld", UID, *id);
  406. return (*id == kAudioDeviceUnknown) ? kAudioHardwareBadDeviceError : res;
  407. }
  408. }
  409. OSStatus JackCoreAudioAdapter::GetDefaultInputDevice(AudioDeviceID* id)
  410. {
  411. OSStatus res;
  412. UInt32 theSize = sizeof(UInt32);
  413. AudioDeviceID inDefault;
  414. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  415. return res;
  416. if (inDefault == 0) {
  417. jack_error("Error : input device is 0, please select a correct one !!");
  418. return -1;
  419. }
  420. jack_log("GetDefaultInputDevice: input = %ld ", inDefault);
  421. *id = inDefault;
  422. return noErr;
  423. }
  424. OSStatus JackCoreAudioAdapter::GetDefaultOutputDevice(AudioDeviceID* id)
  425. {
  426. OSStatus res;
  427. UInt32 theSize = sizeof(UInt32);
  428. AudioDeviceID outDefault;
  429. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  430. return res;
  431. if (outDefault == 0) {
  432. jack_error("Error : output device is 0, please select a correct one !!");
  433. return -1;
  434. }
  435. jack_log("GetDefaultOutputDevice: output = %ld", outDefault);
  436. *id = outDefault;
  437. return noErr;
  438. }
  439. OSStatus JackCoreAudioAdapter::GetDeviceNameFromID(AudioDeviceID id, char* name)
  440. {
  441. UInt32 size = 256;
  442. return AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceName, &size, name);
  443. }
  444. // Setup
  445. int JackCoreAudioAdapter::SetupDevices(const char* capture_driver_uid,
  446. const char* playback_driver_uid,
  447. char* capture_driver_name,
  448. char* playback_driver_name,
  449. jack_nframes_t samplerate)
  450. {
  451. capture_driver_name[0] = 0;
  452. playback_driver_name[0] = 0;
  453. // Duplex
  454. if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
  455. // Same device for capture and playback...
  456. if (strcmp(capture_driver_uid, playback_driver_uid) == 0) {
  457. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  458. jack_log("Will take default in/out");
  459. if (GetDefaultDevice(&fDeviceID) != noErr) {
  460. jack_error("Cannot open default device");
  461. return -1;
  462. }
  463. }
  464. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  465. jack_error("Cannot get device name from device ID");
  466. return -1;
  467. }
  468. } else {
  469. // Creates aggregate device
  470. AudioDeviceID captureID, playbackID;
  471. if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
  472. jack_log("Will take default input");
  473. if (GetDefaultInputDevice(&captureID) != noErr) {
  474. jack_error("Cannot open default input device");
  475. return -1;
  476. }
  477. }
  478. if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
  479. jack_log("Will take default output");
  480. if (GetDefaultOutputDevice(&playbackID) != noErr) {
  481. jack_error("Cannot open default output device");
  482. return -1;
  483. }
  484. }
  485. if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr)
  486. return -1;
  487. }
  488. // Capture only
  489. } else if (strcmp(capture_driver_uid, "") != 0) {
  490. jack_log("JackCoreAudioAdapter::Open capture only");
  491. if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
  492. if (GetDefaultInputDevice(&fDeviceID) != noErr) {
  493. jack_error("Cannot open default input device");
  494. return -1;
  495. }
  496. }
  497. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
  498. jack_error("Cannot get device name from device ID");
  499. return -1;
  500. }
  501. // Playback only
  502. } else if (strcmp(playback_driver_uid, "") != 0) {
  503. jack_log("JackCoreAudioAdapter::Open playback only");
  504. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  505. if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
  506. jack_error("Cannot open default output device");
  507. return -1;
  508. }
  509. }
  510. if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  511. jack_error("Cannot get device name from device ID");
  512. return -1;
  513. }
  514. // Use default driver in duplex mode
  515. } else {
  516. jack_log("JackCoreAudioAdapter::Open default driver");
  517. if (GetDefaultDevice(&fDeviceID) != noErr) {
  518. jack_error("Cannot open default device in duplex mode, so aggregate default input and default output");
  519. // Creates aggregate device
  520. AudioDeviceID captureID, playbackID;
  521. if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
  522. jack_log("Will take default input");
  523. if (GetDefaultInputDevice(&captureID) != noErr) {
  524. jack_error("Cannot open default input device");
  525. return -1;
  526. }
  527. }
  528. if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
  529. jack_log("Will take default output");
  530. if (GetDefaultOutputDevice(&playbackID) != noErr) {
  531. jack_error("Cannot open default output device");
  532. return -1;
  533. }
  534. }
  535. if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr)
  536. return -1;
  537. }
  538. }
  539. return 0;
  540. }
  541. int JackCoreAudioAdapter::SetupChannels(bool capturing,
  542. bool playing,
  543. int& inchannels,
  544. int& outchannels,
  545. int& in_nChannels,
  546. int& out_nChannels,
  547. bool strict)
  548. {
  549. OSStatus err = noErr;
  550. if (capturing) {
  551. err = GetTotalChannels(fDeviceID, in_nChannels, true);
  552. if (err != noErr) {
  553. jack_error("Cannot get input channel number");
  554. printError(err);
  555. return -1;
  556. } else {
  557. jack_log("Max input channels : %d", in_nChannels);
  558. }
  559. }
  560. if (playing) {
  561. err = GetTotalChannels(fDeviceID, out_nChannels, false);
  562. if (err != noErr) {
  563. jack_error("Cannot get output channel number");
  564. printError(err);
  565. return -1;
  566. } else {
  567. jack_log("Max output channels : %d", out_nChannels);
  568. }
  569. }
  570. if (inchannels > in_nChannels) {
  571. jack_error("This device hasn't required input channels inchannels = %ld in_nChannels = %ld", inchannels, in_nChannels);
  572. if (strict)
  573. return -1;
  574. }
  575. if (outchannels > out_nChannels) {
  576. jack_error("This device hasn't required output channels outchannels = %ld out_nChannels = %ld", outchannels, out_nChannels);
  577. if (strict)
  578. return -1;
  579. }
  580. if (inchannels == -1) {
  581. jack_log("Setup max in channels = %ld", in_nChannels);
  582. inchannels = in_nChannels;
  583. }
  584. if (outchannels == -1) {
  585. jack_log("Setup max out channels = %ld", out_nChannels);
  586. outchannels = out_nChannels;
  587. }
  588. return 0;
  589. }
  590. int JackCoreAudioAdapter::SetupBufferSize(jack_nframes_t buffer_size)
  591. {
  592. // Setting buffer size
  593. UInt32 outSize = sizeof(UInt32);
  594. OSStatus err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
  595. if (err != noErr) {
  596. jack_error("Cannot set buffer size %ld", buffer_size);
  597. printError(err);
  598. return -1;
  599. }
  600. return 0;
  601. }
  602. int JackCoreAudioAdapter::SetupSampleRate(jack_nframes_t samplerate)
  603. {
  604. return SetupSampleRateAux(fDeviceID, samplerate);
  605. }
  606. int JackCoreAudioAdapter::SetupSampleRateAux(AudioDeviceID inDevice, jack_nframes_t samplerate)
  607. {
  608. OSStatus err = noErr;
  609. UInt32 outSize;
  610. Float64 sampleRate;
  611. // Get sample rate
  612. outSize = sizeof(Float64);
  613. err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
  614. if (err != noErr) {
  615. jack_error("Cannot get current sample rate");
  616. printError(err);
  617. return -1;
  618. } else {
  619. jack_log("Current sample rate = %f", sampleRate);
  620. }
  621. // If needed, set new sample rate
  622. if (samplerate != (jack_nframes_t)sampleRate) {
  623. sampleRate = (Float64)samplerate;
  624. // To get SR change notification
  625. err = AudioDeviceAddPropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback, this);
  626. if (err != noErr) {
  627. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  628. printError(err);
  629. return -1;
  630. }
  631. err = AudioDeviceSetProperty(inDevice, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &sampleRate);
  632. if (err != noErr) {
  633. jack_error("Cannot set sample rate = %ld", samplerate);
  634. printError(err);
  635. return -1;
  636. }
  637. // Waiting for SR change notification
  638. int count = 0;
  639. while (!fState && count++ < WAIT_COUNTER) {
  640. usleep(100000);
  641. jack_log("Wait count = %d", count);
  642. }
  643. // Remove SR change notification
  644. AudioDeviceRemovePropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
  645. }
  646. return 0;
  647. }
  648. int JackCoreAudioAdapter::SetupBuffers(int inchannels)
  649. {
  650. jack_log("JackCoreAudioAdapter::SetupBuffers: input = %ld", inchannels);
  651. // Prepare buffers
  652. fInputData = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
  653. fInputData->mNumberBuffers = inchannels;
  654. for (int i = 0; i < fCaptureChannels; i++) {
  655. fInputData->mBuffers[i].mNumberChannels = 1;
  656. fInputData->mBuffers[i].mDataByteSize = fAdaptedBufferSize * sizeof(jack_default_audio_sample_t);
  657. fInputData->mBuffers[i].mData = malloc(fAdaptedBufferSize * sizeof(jack_default_audio_sample_t));
  658. }
  659. return 0;
  660. }
  661. void JackCoreAudioAdapter::DisposeBuffers()
  662. {
  663. if (fInputData) {
  664. for (int i = 0; i < fCaptureChannels; i++)
  665. free(fInputData->mBuffers[i].mData);
  666. free(fInputData);
  667. fInputData = 0;
  668. }
  669. }
  670. int JackCoreAudioAdapter::OpenAUHAL(bool capturing,
  671. bool playing,
  672. int inchannels,
  673. int outchannels,
  674. int in_nChannels,
  675. int out_nChannels,
  676. jack_nframes_t buffer_size,
  677. jack_nframes_t samplerate)
  678. {
  679. ComponentResult err1;
  680. UInt32 enableIO;
  681. AudioStreamBasicDescription srcFormat, dstFormat;
  682. AudioDeviceID currAudioDeviceID;
  683. UInt32 size;
  684. jack_log("OpenAUHAL capturing = %d playing = %d inchannels = %d outchannels = %d in_nChannels = %d out_nChannels = %d", capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels);
  685. if (inchannels == 0 && outchannels == 0) {
  686. jack_error("No input and output channels...");
  687. return -1;
  688. }
  689. // AUHAL
  690. ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
  691. Component HALOutput = FindNextComponent(NULL, &cd);
  692. err1 = OpenAComponent(HALOutput, &fAUHAL);
  693. if (err1 != noErr) {
  694. jack_error("Error calling OpenAComponent");
  695. printError(err1);
  696. goto error;
  697. }
  698. err1 = AudioUnitInitialize(fAUHAL);
  699. if (err1 != noErr) {
  700. jack_error("Cannot initialize AUHAL unit");
  701. printError(err1);
  702. goto error;
  703. }
  704. // Start I/O
  705. if (capturing && inchannels > 0) {
  706. enableIO = 1;
  707. jack_log("Setup AUHAL input on");
  708. } else {
  709. enableIO = 0;
  710. jack_log("Setup AUHAL input off");
  711. }
  712. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
  713. if (err1 != noErr) {
  714. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
  715. printError(err1);
  716. goto error;
  717. }
  718. if (playing && outchannels > 0) {
  719. enableIO = 1;
  720. jack_log("Setup AUHAL output on");
  721. } else {
  722. enableIO = 0;
  723. jack_log("Setup AUHAL output off");
  724. }
  725. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
  726. if (err1 != noErr) {
  727. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
  728. printError(err1);
  729. goto error;
  730. }
  731. size = sizeof(AudioDeviceID);
  732. err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
  733. if (err1 != noErr) {
  734. jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
  735. printError(err1);
  736. goto error;
  737. } else {
  738. jack_log("AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
  739. }
  740. // Setup up choosen device, in both input and output cases
  741. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
  742. if (err1 != noErr) {
  743. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
  744. printError(err1);
  745. goto error;
  746. }
  747. // Set buffer size
  748. if (capturing && inchannels > 0) {
  749. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*)&buffer_size, sizeof(UInt32));
  750. if (err1 != noErr) {
  751. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  752. printError(err1);
  753. goto error;
  754. }
  755. }
  756. if (playing && outchannels > 0) {
  757. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*)&buffer_size, sizeof(UInt32));
  758. if (err1 != noErr) {
  759. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  760. printError(err1);
  761. goto error;
  762. }
  763. }
  764. // Setup channel map
  765. if (capturing && inchannels > 0 && inchannels < in_nChannels) {
  766. SInt32 chanArr[in_nChannels];
  767. for (int i = 0; i < in_nChannels; i++) {
  768. chanArr[i] = -1;
  769. }
  770. for (int i = 0; i < inchannels; i++) {
  771. chanArr[i] = i;
  772. }
  773. AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
  774. if (err1 != noErr) {
  775. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 1");
  776. printError(err1);
  777. goto error;
  778. }
  779. }
  780. if (playing && outchannels > 0 && outchannels < out_nChannels) {
  781. SInt32 chanArr[out_nChannels];
  782. for (int i = 0; i < out_nChannels; i++) {
  783. chanArr[i] = -1;
  784. }
  785. for (int i = 0; i < outchannels; i++) {
  786. chanArr[i] = i;
  787. }
  788. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
  789. if (err1 != noErr) {
  790. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 0");
  791. printError(err1);
  792. goto error;
  793. }
  794. }
  795. // Setup stream converters
  796. if (capturing && inchannels > 0) {
  797. size = sizeof(AudioStreamBasicDescription);
  798. err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &srcFormat, &size);
  799. if (err1 != noErr) {
  800. jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  801. printError(err1);
  802. goto error;
  803. }
  804. PrintStreamDesc(&srcFormat);
  805. jack_log("Setup AUHAL input stream converter SR = %ld", samplerate);
  806. srcFormat.mSampleRate = samplerate;
  807. srcFormat.mFormatID = kAudioFormatLinearPCM;
  808. srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  809. srcFormat.mBytesPerPacket = sizeof(jack_default_audio_sample_t);
  810. srcFormat.mFramesPerPacket = 1;
  811. srcFormat.mBytesPerFrame = sizeof(jack_default_audio_sample_t);
  812. srcFormat.mChannelsPerFrame = inchannels;
  813. srcFormat.mBitsPerChannel = 32;
  814. PrintStreamDesc(&srcFormat);
  815. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &srcFormat, sizeof(AudioStreamBasicDescription));
  816. if (err1 != noErr) {
  817. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  818. printError(err1);
  819. goto error;
  820. }
  821. }
  822. if (playing && outchannels > 0) {
  823. size = sizeof(AudioStreamBasicDescription);
  824. err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 1, &dstFormat, &size);
  825. if (err1 != noErr) {
  826. jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  827. printError(err1);
  828. goto error;
  829. }
  830. PrintStreamDesc(&dstFormat);
  831. jack_log("Setup AUHAL output stream converter SR = %ld", samplerate);
  832. dstFormat.mSampleRate = samplerate;
  833. dstFormat.mFormatID = kAudioFormatLinearPCM;
  834. dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  835. dstFormat.mBytesPerPacket = sizeof(jack_default_audio_sample_t);
  836. dstFormat.mFramesPerPacket = 1;
  837. dstFormat.mBytesPerFrame = sizeof(jack_default_audio_sample_t);
  838. dstFormat.mChannelsPerFrame = outchannels;
  839. dstFormat.mBitsPerChannel = 32;
  840. PrintStreamDesc(&dstFormat);
  841. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &dstFormat, sizeof(AudioStreamBasicDescription));
  842. if (err1 != noErr) {
  843. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  844. printError(err1);
  845. goto error;
  846. }
  847. }
  848. // Setup callbacks
  849. if (inchannels > 0 && outchannels == 0) {
  850. AURenderCallbackStruct output;
  851. output.inputProc = Render;
  852. output.inputProcRefCon = this;
  853. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
  854. if (err1 != noErr) {
  855. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
  856. printError(err1);
  857. goto error;
  858. }
  859. } else {
  860. AURenderCallbackStruct output;
  861. output.inputProc = Render;
  862. output.inputProcRefCon = this;
  863. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
  864. if (err1 != noErr) {
  865. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
  866. printError(err1);
  867. goto error;
  868. }
  869. }
  870. return 0;
  871. error:
  872. CloseAUHAL();
  873. return -1;
  874. }
  875. OSStatus JackCoreAudioAdapter::DestroyAggregateDevice()
  876. {
  877. OSStatus osErr = noErr;
  878. AudioObjectPropertyAddress pluginAOPA;
  879. pluginAOPA.mSelector = kAudioPlugInDestroyAggregateDevice;
  880. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  881. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  882. UInt32 outDataSize;
  883. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  884. if (osErr != noErr) {
  885. jack_error("JackCoreAudioAdapter::DestroyAggregateDevice : AudioObjectGetPropertyDataSize error");
  886. printError(osErr);
  887. return osErr;
  888. }
  889. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, 0, NULL, &outDataSize, &fDeviceID);
  890. if (osErr != noErr) {
  891. jack_error("JackCoreAudioAdapter::DestroyAggregateDevice : AudioObjectGetPropertyData error");
  892. printError(osErr);
  893. return osErr;
  894. }
  895. return noErr;
  896. }
  897. static CFStringRef GetDeviceName(AudioDeviceID id)
  898. {
  899. UInt32 size = sizeof(CFStringRef);
  900. CFStringRef UIname;
  901. OSStatus err = AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  902. return (err == noErr) ? UIname : NULL;
  903. }
  904. OSStatus JackCoreAudioAdapter::CreateAggregateDevice(AudioDeviceID captureDeviceID, AudioDeviceID playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
  905. {
  906. OSStatus err = noErr;
  907. AudioObjectID sub_device[32];
  908. UInt32 outSize = sizeof(sub_device);
  909. err = AudioDeviceGetProperty(captureDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  910. vector<AudioDeviceID> captureDeviceIDArray;
  911. if (err != noErr) {
  912. jack_log("Input device does not have subdevices");
  913. captureDeviceIDArray.push_back(captureDeviceID);
  914. } else {
  915. int num_devices = outSize / sizeof(AudioObjectID);
  916. jack_log("Input device has %d subdevices", num_devices);
  917. for (int i = 0; i < num_devices; i++) {
  918. captureDeviceIDArray.push_back(sub_device[i]);
  919. }
  920. }
  921. err = AudioDeviceGetProperty(playbackDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  922. vector<AudioDeviceID> playbackDeviceIDArray;
  923. if (err != noErr) {
  924. jack_log("Output device does not have subdevices");
  925. playbackDeviceIDArray.push_back(playbackDeviceID);
  926. } else {
  927. int num_devices = outSize / sizeof(AudioObjectID);
  928. jack_log("Output device has %d subdevices", num_devices);
  929. for (int i = 0; i < num_devices; i++) {
  930. playbackDeviceIDArray.push_back(sub_device[i]);
  931. }
  932. }
  933. return CreateAggregateDeviceAux(captureDeviceIDArray, playbackDeviceIDArray, samplerate, outAggregateDevice);
  934. }
  935. OSStatus JackCoreAudioAdapter::CreateAggregateDeviceAux(vector<AudioDeviceID> captureDeviceID, vector<AudioDeviceID> playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
  936. {
  937. OSStatus osErr = noErr;
  938. UInt32 outSize;
  939. Boolean outWritable;
  940. // Prepare sub-devices for clock drift compensation
  941. // Workaround for bug in the HAL : until 10.6.2
  942. AudioObjectPropertyAddress theAddressOwned = { kAudioObjectPropertyOwnedObjects, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  943. AudioObjectPropertyAddress theAddressDrift = { kAudioSubDevicePropertyDriftCompensation, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  944. UInt32 theQualifierDataSize = sizeof(AudioObjectID);
  945. AudioClassID inClass = kAudioSubDeviceClassID;
  946. void* theQualifierData = &inClass;
  947. UInt32 subDevicesNum = 0;
  948. //---------------------------------------------------------------------------
  949. // Setup SR of both devices otherwise creating AD may fail...
  950. //---------------------------------------------------------------------------
  951. UInt32 keptclockdomain = 0;
  952. UInt32 clockdomain = 0;
  953. outSize = sizeof(UInt32);
  954. bool need_clock_drift_compensation = false;
  955. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  956. if (SetupSampleRateAux(captureDeviceID[i], samplerate) < 0) {
  957. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : cannot set SR of input device");
  958. } else {
  959. // Check clock domain
  960. osErr = AudioDeviceGetProperty(captureDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
  961. if (osErr != 0) {
  962. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
  963. printError(osErr);
  964. } else {
  965. keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
  966. jack_log("JackCoreAudioAdapter::CreateAggregateDevice : input clockdomain = %d", clockdomain);
  967. if (clockdomain != 0 && clockdomain != keptclockdomain) {
  968. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
  969. need_clock_drift_compensation = true;
  970. }
  971. }
  972. }
  973. }
  974. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  975. if (SetupSampleRateAux(playbackDeviceID[i], samplerate) < 0) {
  976. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : cannot set SR of output device");
  977. } else {
  978. // Check clock domain
  979. osErr = AudioDeviceGetProperty(playbackDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
  980. if (osErr != 0) {
  981. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
  982. printError(osErr);
  983. } else {
  984. keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
  985. jack_log("JackCoreAudioAdapter::CreateAggregateDevice : output clockdomain = %d", clockdomain);
  986. if (clockdomain != 0 && clockdomain != keptclockdomain) {
  987. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
  988. need_clock_drift_compensation = true;
  989. }
  990. }
  991. }
  992. }
  993. // If no valid clock domain was found, then assume we have to compensate...
  994. if (keptclockdomain == 0) {
  995. need_clock_drift_compensation = true;
  996. }
  997. //---------------------------------------------------------------------------
  998. // Start to create a new aggregate by getting the base audio hardware plugin
  999. //---------------------------------------------------------------------------
  1000. char device_name[256];
  1001. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  1002. GetDeviceNameFromID(captureDeviceID[i], device_name);
  1003. jack_info("Separated input = '%s' ", device_name);
  1004. }
  1005. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  1006. GetDeviceNameFromID(playbackDeviceID[i], device_name);
  1007. jack_info("Separated output = '%s' ", device_name);
  1008. }
  1009. osErr = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyPlugInForBundleID, &outSize, &outWritable);
  1010. if (osErr != noErr) {
  1011. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioHardwareGetPropertyInfo kAudioHardwarePropertyPlugInForBundleID error");
  1012. printError(osErr);
  1013. return osErr;
  1014. }
  1015. AudioValueTranslation pluginAVT;
  1016. CFStringRef inBundleRef = CFSTR("com.apple.audio.CoreAudio");
  1017. pluginAVT.mInputData = &inBundleRef;
  1018. pluginAVT.mInputDataSize = sizeof(inBundleRef);
  1019. pluginAVT.mOutputData = &fPluginID;
  1020. pluginAVT.mOutputDataSize = sizeof(fPluginID);
  1021. osErr = AudioHardwareGetProperty(kAudioHardwarePropertyPlugInForBundleID, &outSize, &pluginAVT);
  1022. if (osErr != noErr) {
  1023. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioHardwareGetProperty kAudioHardwarePropertyPlugInForBundleID error");
  1024. printError(osErr);
  1025. return osErr;
  1026. }
  1027. //-------------------------------------------------
  1028. // Create a CFDictionary for our aggregate device
  1029. //-------------------------------------------------
  1030. CFMutableDictionaryRef aggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  1031. CFStringRef AggregateDeviceNameRef = CFSTR("JackDuplex");
  1032. CFStringRef AggregateDeviceUIDRef = CFSTR("com.grame.JackDuplex");
  1033. // add the name of the device to the dictionary
  1034. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceNameKey), AggregateDeviceNameRef);
  1035. // add our choice of UID for the aggregate device to the dictionary
  1036. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceUIDKey), AggregateDeviceUIDRef);
  1037. // add a "private aggregate key" to the dictionary
  1038. int value = 1;
  1039. CFNumberRef AggregateDeviceNumberRef = CFNumberCreate(NULL, kCFNumberIntType, &value);
  1040. SInt32 system;
  1041. Gestalt(gestaltSystemVersion, &system);
  1042. jack_log("JackCoreAudioAdapter::CreateAggregateDevice : system version = %x limit = %x", system, 0x00001054);
  1043. // Starting with 10.5.4 systems, the AD can be internal... (better)
  1044. if (system < 0x00001054) {
  1045. jack_log("JackCoreAudioAdapter::CreateAggregateDevice : public aggregate device....");
  1046. } else {
  1047. jack_log("JackCoreAudioAdapter::CreateAggregateDevice : private aggregate device....");
  1048. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceIsPrivateKey), AggregateDeviceNumberRef);
  1049. }
  1050. // Prepare sub-devices for clock drift compensation
  1051. CFMutableArrayRef subDevicesArrayClock = NULL;
  1052. /*
  1053. if (fClockDriftCompensate) {
  1054. if (need_clock_drift_compensation) {
  1055. jack_info("Clock drift compensation activated...");
  1056. subDevicesArrayClock = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  1057. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  1058. CFStringRef UID = GetDeviceName(captureDeviceID[i]);
  1059. if (UID) {
  1060. CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  1061. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
  1062. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
  1063. //CFRelease(UID);
  1064. CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
  1065. }
  1066. }
  1067. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  1068. CFStringRef UID = GetDeviceName(playbackDeviceID[i]);
  1069. if (UID) {
  1070. CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  1071. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
  1072. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
  1073. //CFRelease(UID);
  1074. CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
  1075. }
  1076. }
  1077. // add sub-device clock array for the aggregate device to the dictionary
  1078. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceSubDeviceListKey), subDevicesArrayClock);
  1079. } else {
  1080. jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
  1081. }
  1082. }
  1083. */
  1084. //-------------------------------------------------
  1085. // Create a CFMutableArray for our sub-device list
  1086. //-------------------------------------------------
  1087. // we need to append the UID for each device to a CFMutableArray, so create one here
  1088. CFMutableArrayRef subDevicesArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  1089. vector<CFStringRef> captureDeviceUID;
  1090. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  1091. CFStringRef ref = GetDeviceName(captureDeviceID[i]);
  1092. if (ref == NULL)
  1093. return -1;
  1094. captureDeviceUID.push_back(ref);
  1095. // input sub-devices in this example, so append the sub-device's UID to the CFArray
  1096. CFArrayAppendValue(subDevicesArray, ref);
  1097. }
  1098. vector<CFStringRef> playbackDeviceUID;
  1099. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  1100. CFStringRef ref = GetDeviceName(playbackDeviceID[i]);
  1101. if (ref == NULL)
  1102. return -1;
  1103. playbackDeviceUID.push_back(ref);
  1104. // output sub-devices in this example, so append the sub-device's UID to the CFArray
  1105. CFArrayAppendValue(subDevicesArray, ref);
  1106. }
  1107. //-----------------------------------------------------------------------
  1108. // Feed the dictionary to the plugin, to create a blank aggregate device
  1109. //-----------------------------------------------------------------------
  1110. AudioObjectPropertyAddress pluginAOPA;
  1111. pluginAOPA.mSelector = kAudioPlugInCreateAggregateDevice;
  1112. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  1113. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  1114. UInt32 outDataSize;
  1115. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  1116. if (osErr != noErr) {
  1117. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioObjectGetPropertyDataSize error");
  1118. printError(osErr);
  1119. goto error;
  1120. }
  1121. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, sizeof(aggDeviceDict), &aggDeviceDict, &outDataSize, outAggregateDevice);
  1122. if (osErr != noErr) {
  1123. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioObjectGetPropertyData error");
  1124. printError(osErr);
  1125. goto error;
  1126. }
  1127. // pause for a bit to make sure that everything completed correctly
  1128. // this is to work around a bug in the HAL where a new aggregate device seems to disappear briefly after it is created
  1129. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  1130. //-------------------------
  1131. // Set the sub-device list
  1132. //-------------------------
  1133. pluginAOPA.mSelector = kAudioAggregateDevicePropertyFullSubDeviceList;
  1134. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  1135. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  1136. outDataSize = sizeof(CFMutableArrayRef);
  1137. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &subDevicesArray);
  1138. if (osErr != noErr) {
  1139. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioObjectSetPropertyData for sub-device list error");
  1140. printError(osErr);
  1141. goto error;
  1142. }
  1143. // pause again to give the changes time to take effect
  1144. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  1145. //-----------------------
  1146. // Set the master device
  1147. //-----------------------
  1148. // set the master device manually (this is the device which will act as the master clock for the aggregate device)
  1149. // pass in the UID of the device you want to use
  1150. pluginAOPA.mSelector = kAudioAggregateDevicePropertyMasterSubDevice;
  1151. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  1152. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  1153. outDataSize = sizeof(CFStringRef);
  1154. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &captureDeviceUID[0]); // First apture is master...
  1155. if (osErr != noErr) {
  1156. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioObjectSetPropertyData for master device error");
  1157. printError(osErr);
  1158. goto error;
  1159. }
  1160. // pause again to give the changes time to take effect
  1161. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  1162. // Prepare sub-devices for clock drift compensation
  1163. // Workaround for bug in the HAL : until 10.6.2
  1164. if (fClockDriftCompensate) {
  1165. if (need_clock_drift_compensation) {
  1166. jack_info("Clock drift compensation activated...");
  1167. // Get the property data size
  1168. osErr = AudioObjectGetPropertyDataSize(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize);
  1169. if (osErr != noErr) {
  1170. jack_error("JackCoreAudioAdapter::CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
  1171. printError(osErr);
  1172. }
  1173. // Calculate the number of object IDs
  1174. subDevicesNum = outSize / sizeof(AudioObjectID);
  1175. jack_info("JackCoreAudioAdapter::CreateAggregateDevice clock drift compensation, number of sub-devices = %d", subDevicesNum);
  1176. AudioObjectID subDevices[subDevicesNum];
  1177. outSize = sizeof(subDevices);
  1178. osErr = AudioObjectGetPropertyData(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize, subDevices);
  1179. if (osErr != noErr) {
  1180. jack_error("JackCoreAudioAdapter::CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
  1181. printError(osErr);
  1182. }
  1183. // Set kAudioSubDevicePropertyDriftCompensation property...
  1184. for (UInt32 index = 0; index < subDevicesNum; ++index) {
  1185. UInt32 theDriftCompensationValue = 1;
  1186. osErr = AudioObjectSetPropertyData(subDevices[index], &theAddressDrift, 0, NULL, sizeof(UInt32), &theDriftCompensationValue);
  1187. if (osErr != noErr) {
  1188. jack_error("JackCoreAudioAdapter::CreateAggregateDevice kAudioSubDevicePropertyDriftCompensation error");
  1189. printError(osErr);
  1190. }
  1191. }
  1192. } else {
  1193. jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
  1194. }
  1195. }
  1196. // pause again to give the changes time to take effect
  1197. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  1198. //----------
  1199. // Clean up
  1200. //----------
  1201. // release the private AD key
  1202. CFRelease(AggregateDeviceNumberRef);
  1203. // release the CF objects we have created - we don't need them any more
  1204. CFRelease(aggDeviceDict);
  1205. CFRelease(subDevicesArray);
  1206. if (subDevicesArrayClock)
  1207. CFRelease(subDevicesArrayClock);
  1208. // release the device UID
  1209. for (UInt32 i = 0; i < captureDeviceUID.size(); i++) {
  1210. CFRelease(captureDeviceUID[i]);
  1211. }
  1212. for (UInt32 i = 0; i < playbackDeviceUID.size(); i++) {
  1213. CFRelease(playbackDeviceUID[i]);
  1214. }
  1215. jack_log("New aggregate device %ld", *outAggregateDevice);
  1216. return noErr;
  1217. error:
  1218. DestroyAggregateDevice();
  1219. return -1;
  1220. }
  1221. bool JackCoreAudioAdapter::IsAggregateDevice(AudioDeviceID device)
  1222. {
  1223. OSStatus err = noErr;
  1224. AudioObjectID sub_device[32];
  1225. UInt32 outSize = sizeof(sub_device);
  1226. err = AudioDeviceGetProperty(device, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  1227. if (err != noErr) {
  1228. jack_log("Device does not have subdevices");
  1229. return false;
  1230. } else {
  1231. int num_devices = outSize / sizeof(AudioObjectID);
  1232. jack_log("Device does has %d subdevices", num_devices);
  1233. return true;
  1234. }
  1235. }
  1236. void JackCoreAudioAdapter::CloseAUHAL()
  1237. {
  1238. AudioUnitUninitialize(fAUHAL);
  1239. CloseComponent(fAUHAL);
  1240. }
  1241. int JackCoreAudioAdapter::Open()
  1242. {
  1243. return (AudioOutputUnitStart(fAUHAL) != noErr) ? -1 : 0;
  1244. }
  1245. int JackCoreAudioAdapter::Close()
  1246. {
  1247. #ifdef JACK_MONITOR
  1248. fTable.Save(fHostBufferSize, fHostSampleRate, fAdaptedSampleRate, fAdaptedBufferSize);
  1249. #endif
  1250. AudioOutputUnitStop(fAUHAL);
  1251. DisposeBuffers();
  1252. CloseAUHAL();
  1253. RemoveListeners();
  1254. if (fPluginID > 0)
  1255. DestroyAggregateDevice();
  1256. return 0;
  1257. }
  1258. int JackCoreAudioAdapter::SetSampleRate ( jack_nframes_t sample_rate ) {
  1259. JackAudioAdapterInterface::SetHostSampleRate ( sample_rate );
  1260. Close();
  1261. return Open();
  1262. }
  1263. int JackCoreAudioAdapter::SetBufferSize ( jack_nframes_t buffer_size ) {
  1264. JackAudioAdapterInterface::SetHostBufferSize ( buffer_size );
  1265. Close();
  1266. return Open();
  1267. }
  1268. } // namespace
  1269. #ifdef __cplusplus
  1270. extern "C"
  1271. {
  1272. #endif
  1273. SERVER_EXPORT jack_driver_desc_t* jack_get_descriptor()
  1274. {
  1275. jack_driver_desc_t * desc;
  1276. jack_driver_desc_filler_t filler;
  1277. jack_driver_param_value_t value;
  1278. desc = jack_driver_descriptor_construct("audioadapter", JackDriverNone, "netjack audio <==> net backend adapter", &filler);
  1279. value.i = -1;
  1280. 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");
  1281. jack_driver_descriptor_add_parameter(desc, &filler, "inchannels", 'i', JackDriverParamInt, &value, NULL, "Maximum number of input channels", "Maximum number of input channels. If -1, max possible number of input channels will be used");
  1282. jack_driver_descriptor_add_parameter(desc, &filler, "outchannels", 'o', JackDriverParamInt, &value, NULL, "Maximum number of output channels", "Maximum number of output channels. If -1, max possible number of output channels will be used");
  1283. value.str[0] = 0;
  1284. jack_driver_descriptor_add_parameter(desc, &filler, "capture", 'C', JackDriverParamString, &value, NULL, "Input CoreAudio device name", NULL);
  1285. jack_driver_descriptor_add_parameter(desc, &filler, "playback", 'P', JackDriverParamString, &value, NULL, "Output CoreAudio device name", NULL);
  1286. value.ui = 44100U;
  1287. jack_driver_descriptor_add_parameter(desc, &filler, "rate", 'r', JackDriverParamUInt, &value, NULL, "Sample rate", NULL);
  1288. value.ui = 512U;
  1289. jack_driver_descriptor_add_parameter(desc, &filler, "period", 'p', JackDriverParamUInt, &value, NULL, "Frames per period", NULL);
  1290. value.i = TRUE;
  1291. jack_driver_descriptor_add_parameter(desc, &filler, "duplex", 'D', JackDriverParamBool, &value, NULL, "Provide both capture and playback ports", NULL);
  1292. value.str[0] = 0;
  1293. jack_driver_descriptor_add_parameter(desc, &filler, "device", 'd', JackDriverParamString, &value, NULL, "CoreAudio device name", NULL);
  1294. value.i = TRUE;
  1295. jack_driver_descriptor_add_parameter(desc, &filler, "list-devices", 'l', JackDriverParamBool, &value, NULL, "Display available CoreAudio devices", NULL);
  1296. value.ui = 0;
  1297. jack_driver_descriptor_add_parameter(desc, &filler, "quality", 'q', JackDriverParamInt, &value, NULL, "Resample algorithm quality (0 - 4)", NULL);
  1298. value.ui = 32768;
  1299. jack_driver_descriptor_add_parameter(desc, &filler, "ring-buffer", 'g', JackDriverParamInt, &value, NULL, "Fixed ringbuffer size", "Fixed ringbuffer size (if not set => automatic adaptative)");
  1300. value.i = FALSE;
  1301. 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");
  1302. return desc;
  1303. }
  1304. #ifdef __cplusplus
  1305. }
  1306. #endif