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.

1547 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 -1;
  333. if (SetupChannels(fCapturing, fPlaying, fCaptureChannels, fPlaybackChannels, in_nChannels, out_nChannels, true) < 0)
  334. throw -1;
  335. if (SetupBufferSize(fAdaptedBufferSize) < 0)
  336. throw -1;
  337. if (SetupSampleRate(fAdaptedSampleRate) < 0)
  338. throw -1;
  339. if (OpenAUHAL(fCapturing, fPlaying, fCaptureChannels, fPlaybackChannels, in_nChannels, out_nChannels, fAdaptedBufferSize, fAdaptedSampleRate) < 0)
  340. throw -1;
  341. if (fCapturing && fCaptureChannels > 0)
  342. if (SetupBuffers(fCaptureChannels) < 0)
  343. throw -1;
  344. if (AddListeners() < 0)
  345. throw -1;
  346. }
  347. OSStatus JackCoreAudioAdapter::GetDefaultDevice(AudioDeviceID* id)
  348. {
  349. OSStatus res;
  350. UInt32 theSize = sizeof(UInt32);
  351. AudioDeviceID inDefault;
  352. AudioDeviceID outDefault;
  353. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  354. return res;
  355. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  356. return res;
  357. jack_log("GetDefaultDevice: input = %ld output = %ld", inDefault, outDefault);
  358. // Get the device only if default input and output are the same
  359. if (inDefault != outDefault) {
  360. jack_error("Default input and output devices are not the same !!");
  361. return kAudioHardwareBadDeviceError;
  362. } else if (inDefault == 0) {
  363. jack_error("Default input and output devices are null !!");
  364. return kAudioHardwareBadDeviceError;
  365. } else {
  366. *id = inDefault;
  367. return noErr;
  368. }
  369. }
  370. OSStatus JackCoreAudioAdapter::GetTotalChannels(AudioDeviceID device, int& channelCount, bool isInput)
  371. {
  372. OSStatus err = noErr;
  373. UInt32 outSize;
  374. Boolean outWritable;
  375. channelCount = 0;
  376. err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, &outWritable);
  377. if (err == noErr) {
  378. AudioBufferList bufferList[outSize];
  379. err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, bufferList);
  380. if (err == noErr) {
  381. for (unsigned int i = 0; i < bufferList->mNumberBuffers; i++)
  382. channelCount += bufferList->mBuffers[i].mNumberChannels;
  383. }
  384. }
  385. return err;
  386. }
  387. OSStatus JackCoreAudioAdapter::GetDeviceIDFromUID(const char* UID, AudioDeviceID* id)
  388. {
  389. UInt32 size = sizeof(AudioValueTranslation);
  390. CFStringRef inIUD = CFStringCreateWithCString(NULL, UID, CFStringGetSystemEncoding());
  391. AudioValueTranslation value = { &inIUD, sizeof(CFStringRef), id, sizeof(AudioDeviceID) };
  392. if (inIUD == NULL) {
  393. return kAudioHardwareUnspecifiedError;
  394. } else {
  395. OSStatus res = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, &size, &value);
  396. CFRelease(inIUD);
  397. jack_log("GetDeviceIDFromUID %s %ld", UID, *id);
  398. return (*id == kAudioDeviceUnknown) ? kAudioHardwareBadDeviceError : res;
  399. }
  400. }
  401. OSStatus JackCoreAudioAdapter::GetDefaultInputDevice(AudioDeviceID* id)
  402. {
  403. OSStatus res;
  404. UInt32 theSize = sizeof(UInt32);
  405. AudioDeviceID inDefault;
  406. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  407. return res;
  408. if (inDefault == 0) {
  409. jack_error("Error : input device is 0, please select a correct one !!");
  410. return -1;
  411. }
  412. jack_log("GetDefaultInputDevice: input = %ld ", inDefault);
  413. *id = inDefault;
  414. return noErr;
  415. }
  416. OSStatus JackCoreAudioAdapter::GetDefaultOutputDevice(AudioDeviceID* id)
  417. {
  418. OSStatus res;
  419. UInt32 theSize = sizeof(UInt32);
  420. AudioDeviceID outDefault;
  421. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  422. return res;
  423. if (outDefault == 0) {
  424. jack_error("Error : output device is 0, please select a correct one !!");
  425. return -1;
  426. }
  427. jack_log("GetDefaultOutputDevice: output = %ld", outDefault);
  428. *id = outDefault;
  429. return noErr;
  430. }
  431. OSStatus JackCoreAudioAdapter::GetDeviceNameFromID(AudioDeviceID id, char* name)
  432. {
  433. UInt32 size = 256;
  434. return AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceName, &size, name);
  435. }
  436. // Setup
  437. int JackCoreAudioAdapter::SetupDevices(const char* capture_driver_uid,
  438. const char* playback_driver_uid,
  439. char* capture_driver_name,
  440. char* playback_driver_name,
  441. jack_nframes_t samplerate)
  442. {
  443. capture_driver_name[0] = 0;
  444. playback_driver_name[0] = 0;
  445. // Duplex
  446. if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
  447. // Same device for capture and playback...
  448. if (strcmp(capture_driver_uid, playback_driver_uid) == 0) {
  449. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  450. jack_log("Will take default in/out");
  451. if (GetDefaultDevice(&fDeviceID) != noErr) {
  452. jack_error("Cannot open default device");
  453. return -1;
  454. }
  455. }
  456. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  457. jack_error("Cannot get device name from device ID");
  458. return -1;
  459. }
  460. } else {
  461. // Creates aggregate device
  462. AudioDeviceID captureID, playbackID;
  463. if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
  464. jack_log("Will take default input");
  465. if (GetDefaultInputDevice(&captureID) != noErr) {
  466. jack_error("Cannot open default input device");
  467. return -1;
  468. }
  469. }
  470. if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
  471. jack_log("Will take default output");
  472. if (GetDefaultOutputDevice(&playbackID) != noErr) {
  473. jack_error("Cannot open default output device");
  474. return -1;
  475. }
  476. }
  477. if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr)
  478. return -1;
  479. }
  480. // Capture only
  481. } else if (strcmp(capture_driver_uid, "") != 0) {
  482. jack_log("JackCoreAudioAdapter::Open capture only");
  483. if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
  484. if (GetDefaultInputDevice(&fDeviceID) != noErr) {
  485. jack_error("Cannot open default input device");
  486. return -1;
  487. }
  488. }
  489. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
  490. jack_error("Cannot get device name from device ID");
  491. return -1;
  492. }
  493. // Playback only
  494. } else if (strcmp(playback_driver_uid, "") != 0) {
  495. jack_log("JackCoreAudioAdapter::Open playback only");
  496. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  497. if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
  498. jack_error("Cannot open default output device");
  499. return -1;
  500. }
  501. }
  502. if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  503. jack_error("Cannot get device name from device ID");
  504. return -1;
  505. }
  506. // Use default driver in duplex mode
  507. } else {
  508. jack_log("JackCoreAudioAdapter::Open default driver");
  509. if (GetDefaultDevice(&fDeviceID) != noErr) {
  510. jack_error("Cannot open default device in duplex mode, so aggregate default input and default output");
  511. // Creates aggregate device
  512. AudioDeviceID captureID, playbackID;
  513. if (GetDeviceIDFromUID(capture_driver_uid, &captureID) != noErr) {
  514. jack_log("Will take default input");
  515. if (GetDefaultInputDevice(&captureID) != noErr) {
  516. jack_error("Cannot open default input device");
  517. return -1;
  518. }
  519. }
  520. if (GetDeviceIDFromUID(playback_driver_uid, &playbackID) != noErr) {
  521. jack_log("Will take default output");
  522. if (GetDefaultOutputDevice(&playbackID) != noErr) {
  523. jack_error("Cannot open default output device");
  524. return -1;
  525. }
  526. }
  527. if (CreateAggregateDevice(captureID, playbackID, samplerate, &fDeviceID) != noErr)
  528. return -1;
  529. }
  530. }
  531. return 0;
  532. }
  533. int JackCoreAudioAdapter::SetupChannels(bool capturing,
  534. bool playing,
  535. int& inchannels,
  536. int& outchannels,
  537. int& in_nChannels,
  538. int& out_nChannels,
  539. bool strict)
  540. {
  541. OSStatus err = noErr;
  542. if (capturing) {
  543. err = GetTotalChannels(fDeviceID, in_nChannels, true);
  544. if (err != noErr) {
  545. jack_error("Cannot get input channel number");
  546. printError(err);
  547. return -1;
  548. } else {
  549. jack_log("Max input channels : %d", in_nChannels);
  550. }
  551. }
  552. if (playing) {
  553. err = GetTotalChannels(fDeviceID, out_nChannels, false);
  554. if (err != noErr) {
  555. jack_error("Cannot get output channel number");
  556. printError(err);
  557. return -1;
  558. } else {
  559. jack_log("Max output channels : %d", out_nChannels);
  560. }
  561. }
  562. if (inchannels > in_nChannels) {
  563. jack_error("This device hasn't required input channels inchannels = %ld in_nChannels = %ld", inchannels, in_nChannels);
  564. if (strict)
  565. return -1;
  566. }
  567. if (outchannels > out_nChannels) {
  568. jack_error("This device hasn't required output channels outchannels = %ld out_nChannels = %ld", outchannels, out_nChannels);
  569. if (strict)
  570. return -1;
  571. }
  572. if (inchannels == -1) {
  573. jack_log("Setup max in channels = %ld", in_nChannels);
  574. inchannels = in_nChannels;
  575. }
  576. if (outchannels == -1) {
  577. jack_log("Setup max out channels = %ld", out_nChannels);
  578. outchannels = out_nChannels;
  579. }
  580. return 0;
  581. }
  582. int JackCoreAudioAdapter::SetupBufferSize(jack_nframes_t buffer_size)
  583. {
  584. // Setting buffer size
  585. UInt32 outSize = sizeof(UInt32);
  586. OSStatus err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &buffer_size);
  587. if (err != noErr) {
  588. jack_error("Cannot set buffer size %ld", buffer_size);
  589. printError(err);
  590. return -1;
  591. }
  592. return 0;
  593. }
  594. int JackCoreAudioAdapter::SetupSampleRate(jack_nframes_t samplerate)
  595. {
  596. return SetupSampleRateAux(fDeviceID, samplerate);
  597. }
  598. int JackCoreAudioAdapter::SetupSampleRateAux(AudioDeviceID inDevice, jack_nframes_t samplerate)
  599. {
  600. OSStatus err = noErr;
  601. UInt32 outSize;
  602. Float64 sampleRate;
  603. // Get sample rate
  604. outSize = sizeof(Float64);
  605. err = AudioDeviceGetProperty(inDevice, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
  606. if (err != noErr) {
  607. jack_error("Cannot get current sample rate");
  608. printError(err);
  609. return -1;
  610. } else {
  611. jack_log("Current sample rate = %f", sampleRate);
  612. }
  613. // If needed, set new sample rate
  614. if (samplerate != (jack_nframes_t)sampleRate) {
  615. sampleRate = (Float64)samplerate;
  616. // To get SR change notification
  617. err = AudioDeviceAddPropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback, this);
  618. if (err != noErr) {
  619. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  620. printError(err);
  621. return -1;
  622. }
  623. err = AudioDeviceSetProperty(inDevice, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &sampleRate);
  624. if (err != noErr) {
  625. jack_error("Cannot set sample rate = %ld", samplerate);
  626. printError(err);
  627. return -1;
  628. }
  629. // Waiting for SR change notification
  630. int count = 0;
  631. while (!fState && count++ < WAIT_COUNTER) {
  632. usleep(100000);
  633. jack_log("Wait count = %d", count);
  634. }
  635. // Remove SR change notification
  636. AudioDeviceRemovePropertyListener(inDevice, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
  637. }
  638. return 0;
  639. }
  640. int JackCoreAudioAdapter::SetupBuffers(int inchannels)
  641. {
  642. jack_log("JackCoreAudioAdapter::SetupBuffers: input = %ld", inchannels);
  643. // Prepare buffers
  644. fInputData = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
  645. fInputData->mNumberBuffers = inchannels;
  646. for (int i = 0; i < fCaptureChannels; i++) {
  647. fInputData->mBuffers[i].mNumberChannels = 1;
  648. fInputData->mBuffers[i].mDataByteSize = fAdaptedBufferSize * sizeof(jack_default_audio_sample_t);
  649. fInputData->mBuffers[i].mData = malloc(fAdaptedBufferSize * sizeof(jack_default_audio_sample_t));
  650. }
  651. return 0;
  652. }
  653. void JackCoreAudioAdapter::DisposeBuffers()
  654. {
  655. if (fInputData) {
  656. for (int i = 0; i < fCaptureChannels; i++)
  657. free(fInputData->mBuffers[i].mData);
  658. free(fInputData);
  659. fInputData = 0;
  660. }
  661. }
  662. int JackCoreAudioAdapter::OpenAUHAL(bool capturing,
  663. bool playing,
  664. int inchannels,
  665. int outchannels,
  666. int in_nChannels,
  667. int out_nChannels,
  668. jack_nframes_t buffer_size,
  669. jack_nframes_t samplerate)
  670. {
  671. ComponentResult err1;
  672. UInt32 enableIO;
  673. AudioStreamBasicDescription srcFormat, dstFormat;
  674. AudioDeviceID currAudioDeviceID;
  675. UInt32 size;
  676. 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);
  677. if (inchannels == 0 && outchannels == 0) {
  678. jack_error("No input and output channels...");
  679. return -1;
  680. }
  681. // AUHAL
  682. ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
  683. Component HALOutput = FindNextComponent(NULL, &cd);
  684. err1 = OpenAComponent(HALOutput, &fAUHAL);
  685. if (err1 != noErr) {
  686. jack_error("Error calling OpenAComponent");
  687. printError(err1);
  688. goto error;
  689. }
  690. err1 = AudioUnitInitialize(fAUHAL);
  691. if (err1 != noErr) {
  692. jack_error("Cannot initialize AUHAL unit");
  693. printError(err1);
  694. goto error;
  695. }
  696. // Start I/O
  697. if (capturing && inchannels > 0) {
  698. enableIO = 1;
  699. jack_log("Setup AUHAL input on");
  700. } else {
  701. enableIO = 0;
  702. jack_log("Setup AUHAL input off");
  703. }
  704. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
  705. if (err1 != noErr) {
  706. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
  707. printError(err1);
  708. goto error;
  709. }
  710. if (playing && outchannels > 0) {
  711. enableIO = 1;
  712. jack_log("Setup AUHAL output on");
  713. } else {
  714. enableIO = 0;
  715. jack_log("Setup AUHAL output off");
  716. }
  717. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
  718. if (err1 != noErr) {
  719. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
  720. printError(err1);
  721. goto error;
  722. }
  723. size = sizeof(AudioDeviceID);
  724. err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
  725. if (err1 != noErr) {
  726. jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
  727. printError(err1);
  728. goto error;
  729. } else {
  730. jack_log("AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
  731. }
  732. // Setup up choosen device, in both input and output cases
  733. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
  734. if (err1 != noErr) {
  735. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
  736. printError(err1);
  737. goto error;
  738. }
  739. // Set buffer size
  740. if (capturing && inchannels > 0) {
  741. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*)&buffer_size, sizeof(UInt32));
  742. if (err1 != noErr) {
  743. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  744. printError(err1);
  745. goto error;
  746. }
  747. }
  748. if (playing && outchannels > 0) {
  749. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (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. // Setup channel map
  757. if (capturing && inchannels > 0 && inchannels < in_nChannels) {
  758. SInt32 chanArr[in_nChannels];
  759. for (int i = 0; i < in_nChannels; i++) {
  760. chanArr[i] = -1;
  761. }
  762. for (int i = 0; i < inchannels; i++) {
  763. chanArr[i] = i;
  764. }
  765. AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
  766. if (err1 != noErr) {
  767. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 1");
  768. printError(err1);
  769. goto error;
  770. }
  771. }
  772. if (playing && outchannels > 0 && outchannels < out_nChannels) {
  773. SInt32 chanArr[out_nChannels];
  774. for (int i = 0; i < out_nChannels; i++) {
  775. chanArr[i] = -1;
  776. }
  777. for (int i = 0; i < outchannels; i++) {
  778. chanArr[i] = i;
  779. }
  780. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
  781. if (err1 != noErr) {
  782. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 0");
  783. printError(err1);
  784. goto error;
  785. }
  786. }
  787. // Setup stream converters
  788. if (capturing && inchannels > 0) {
  789. size = sizeof(AudioStreamBasicDescription);
  790. err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &srcFormat, &size);
  791. if (err1 != noErr) {
  792. jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  793. printError(err1);
  794. goto error;
  795. }
  796. PrintStreamDesc(&srcFormat);
  797. jack_log("Setup AUHAL input stream converter SR = %ld", samplerate);
  798. srcFormat.mSampleRate = samplerate;
  799. srcFormat.mFormatID = kAudioFormatLinearPCM;
  800. srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  801. srcFormat.mBytesPerPacket = sizeof(jack_default_audio_sample_t);
  802. srcFormat.mFramesPerPacket = 1;
  803. srcFormat.mBytesPerFrame = sizeof(jack_default_audio_sample_t);
  804. srcFormat.mChannelsPerFrame = inchannels;
  805. srcFormat.mBitsPerChannel = 32;
  806. PrintStreamDesc(&srcFormat);
  807. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &srcFormat, sizeof(AudioStreamBasicDescription));
  808. if (err1 != noErr) {
  809. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  810. printError(err1);
  811. goto error;
  812. }
  813. }
  814. if (playing && outchannels > 0) {
  815. size = sizeof(AudioStreamBasicDescription);
  816. err1 = AudioUnitGetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 1, &dstFormat, &size);
  817. if (err1 != noErr) {
  818. jack_error("Error calling AudioUnitGetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  819. printError(err1);
  820. goto error;
  821. }
  822. PrintStreamDesc(&dstFormat);
  823. jack_log("Setup AUHAL output stream converter SR = %ld", samplerate);
  824. dstFormat.mSampleRate = samplerate;
  825. dstFormat.mFormatID = kAudioFormatLinearPCM;
  826. dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  827. dstFormat.mBytesPerPacket = sizeof(jack_default_audio_sample_t);
  828. dstFormat.mFramesPerPacket = 1;
  829. dstFormat.mBytesPerFrame = sizeof(jack_default_audio_sample_t);
  830. dstFormat.mChannelsPerFrame = outchannels;
  831. dstFormat.mBitsPerChannel = 32;
  832. PrintStreamDesc(&dstFormat);
  833. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &dstFormat, sizeof(AudioStreamBasicDescription));
  834. if (err1 != noErr) {
  835. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  836. printError(err1);
  837. goto error;
  838. }
  839. }
  840. // Setup callbacks
  841. if (inchannels > 0 && outchannels == 0) {
  842. AURenderCallbackStruct output;
  843. output.inputProc = Render;
  844. output.inputProcRefCon = this;
  845. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
  846. if (err1 != noErr) {
  847. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
  848. printError(err1);
  849. goto error;
  850. }
  851. } else {
  852. AURenderCallbackStruct output;
  853. output.inputProc = Render;
  854. output.inputProcRefCon = this;
  855. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
  856. if (err1 != noErr) {
  857. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
  858. printError(err1);
  859. goto error;
  860. }
  861. }
  862. return 0;
  863. error:
  864. CloseAUHAL();
  865. return -1;
  866. }
  867. OSStatus JackCoreAudioAdapter::DestroyAggregateDevice()
  868. {
  869. OSStatus osErr = noErr;
  870. AudioObjectPropertyAddress pluginAOPA;
  871. pluginAOPA.mSelector = kAudioPlugInDestroyAggregateDevice;
  872. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  873. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  874. UInt32 outDataSize;
  875. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  876. if (osErr != noErr) {
  877. jack_error("JackCoreAudioAdapter::DestroyAggregateDevice : AudioObjectGetPropertyDataSize error");
  878. printError(osErr);
  879. return osErr;
  880. }
  881. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, 0, NULL, &outDataSize, &fDeviceID);
  882. if (osErr != noErr) {
  883. jack_error("JackCoreAudioAdapter::DestroyAggregateDevice : AudioObjectGetPropertyData error");
  884. printError(osErr);
  885. return osErr;
  886. }
  887. return noErr;
  888. }
  889. static CFStringRef GetDeviceName(AudioDeviceID id)
  890. {
  891. UInt32 size = sizeof(CFStringRef);
  892. CFStringRef UIname;
  893. OSStatus err = AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  894. return (err == noErr) ? UIname : NULL;
  895. }
  896. OSStatus JackCoreAudioAdapter::CreateAggregateDevice(AudioDeviceID captureDeviceID, AudioDeviceID playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
  897. {
  898. OSStatus err = noErr;
  899. AudioObjectID sub_device[32];
  900. UInt32 outSize = sizeof(sub_device);
  901. err = AudioDeviceGetProperty(captureDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  902. vector<AudioDeviceID> captureDeviceIDArray;
  903. if (err != noErr) {
  904. jack_log("Input device does not have subdevices");
  905. captureDeviceIDArray.push_back(captureDeviceID);
  906. } else {
  907. int num_devices = outSize / sizeof(AudioObjectID);
  908. jack_log("Input device has %d subdevices", num_devices);
  909. for (int i = 0; i < num_devices; i++) {
  910. captureDeviceIDArray.push_back(sub_device[i]);
  911. }
  912. }
  913. err = AudioDeviceGetProperty(playbackDeviceID, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  914. vector<AudioDeviceID> playbackDeviceIDArray;
  915. if (err != noErr) {
  916. jack_log("Output device does not have subdevices");
  917. playbackDeviceIDArray.push_back(playbackDeviceID);
  918. } else {
  919. int num_devices = outSize / sizeof(AudioObjectID);
  920. jack_log("Output device has %d subdevices", num_devices);
  921. for (int i = 0; i < num_devices; i++) {
  922. playbackDeviceIDArray.push_back(sub_device[i]);
  923. }
  924. }
  925. return CreateAggregateDeviceAux(captureDeviceIDArray, playbackDeviceIDArray, samplerate, outAggregateDevice);
  926. }
  927. OSStatus JackCoreAudioAdapter::CreateAggregateDeviceAux(vector<AudioDeviceID> captureDeviceID, vector<AudioDeviceID> playbackDeviceID, jack_nframes_t samplerate, AudioDeviceID* outAggregateDevice)
  928. {
  929. OSStatus osErr = noErr;
  930. UInt32 outSize;
  931. Boolean outWritable;
  932. // Prepare sub-devices for clock drift compensation
  933. // Workaround for bug in the HAL : until 10.6.2
  934. AudioObjectPropertyAddress theAddressOwned = { kAudioObjectPropertyOwnedObjects, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  935. AudioObjectPropertyAddress theAddressDrift = { kAudioSubDevicePropertyDriftCompensation, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  936. UInt32 theQualifierDataSize = sizeof(AudioObjectID);
  937. AudioClassID inClass = kAudioSubDeviceClassID;
  938. void* theQualifierData = &inClass;
  939. UInt32 subDevicesNum = 0;
  940. //---------------------------------------------------------------------------
  941. // Setup SR of both devices otherwise creating AD may fail...
  942. //---------------------------------------------------------------------------
  943. UInt32 keptclockdomain = 0;
  944. UInt32 clockdomain = 0;
  945. outSize = sizeof(UInt32);
  946. bool need_clock_drift_compensation = false;
  947. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  948. if (SetupSampleRateAux(captureDeviceID[i], samplerate) < 0) {
  949. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : cannot set SR of input device");
  950. } else {
  951. // Check clock domain
  952. osErr = AudioDeviceGetProperty(captureDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
  953. if (osErr != 0) {
  954. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
  955. printError(osErr);
  956. } else {
  957. keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
  958. jack_log("JackCoreAudioAdapter::CreateAggregateDevice : input clockdomain = %d", clockdomain);
  959. if (clockdomain != 0 && clockdomain != keptclockdomain) {
  960. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
  961. need_clock_drift_compensation = true;
  962. }
  963. }
  964. }
  965. }
  966. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  967. if (SetupSampleRateAux(playbackDeviceID[i], samplerate) < 0) {
  968. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : cannot set SR of output device");
  969. } else {
  970. // Check clock domain
  971. osErr = AudioDeviceGetProperty(playbackDeviceID[i], 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyClockDomain, &outSize, &clockdomain);
  972. if (osErr != 0) {
  973. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : kAudioDevicePropertyClockDomain error");
  974. printError(osErr);
  975. } else {
  976. keptclockdomain = (keptclockdomain == 0) ? clockdomain : keptclockdomain;
  977. jack_log("JackCoreAudioAdapter::CreateAggregateDevice : output clockdomain = %d", clockdomain);
  978. if (clockdomain != 0 && clockdomain != keptclockdomain) {
  979. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : devices do not share the same clock!! clock drift compensation would be needed...");
  980. need_clock_drift_compensation = true;
  981. }
  982. }
  983. }
  984. }
  985. // If no valid clock domain was found, then assume we have to compensate...
  986. if (keptclockdomain == 0) {
  987. need_clock_drift_compensation = true;
  988. }
  989. //---------------------------------------------------------------------------
  990. // Start to create a new aggregate by getting the base audio hardware plugin
  991. //---------------------------------------------------------------------------
  992. char device_name[256];
  993. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  994. GetDeviceNameFromID(captureDeviceID[i], device_name);
  995. jack_info("Separated input = '%s' ", device_name);
  996. }
  997. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  998. GetDeviceNameFromID(playbackDeviceID[i], device_name);
  999. jack_info("Separated output = '%s' ", device_name);
  1000. }
  1001. osErr = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyPlugInForBundleID, &outSize, &outWritable);
  1002. if (osErr != noErr) {
  1003. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioHardwareGetPropertyInfo kAudioHardwarePropertyPlugInForBundleID error");
  1004. printError(osErr);
  1005. return osErr;
  1006. }
  1007. AudioValueTranslation pluginAVT;
  1008. CFStringRef inBundleRef = CFSTR("com.apple.audio.CoreAudio");
  1009. pluginAVT.mInputData = &inBundleRef;
  1010. pluginAVT.mInputDataSize = sizeof(inBundleRef);
  1011. pluginAVT.mOutputData = &fPluginID;
  1012. pluginAVT.mOutputDataSize = sizeof(fPluginID);
  1013. osErr = AudioHardwareGetProperty(kAudioHardwarePropertyPlugInForBundleID, &outSize, &pluginAVT);
  1014. if (osErr != noErr) {
  1015. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioHardwareGetProperty kAudioHardwarePropertyPlugInForBundleID error");
  1016. printError(osErr);
  1017. return osErr;
  1018. }
  1019. //-------------------------------------------------
  1020. // Create a CFDictionary for our aggregate device
  1021. //-------------------------------------------------
  1022. CFMutableDictionaryRef aggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  1023. CFStringRef AggregateDeviceNameRef = CFSTR("JackDuplex");
  1024. CFStringRef AggregateDeviceUIDRef = CFSTR("com.grame.JackDuplex");
  1025. // add the name of the device to the dictionary
  1026. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceNameKey), AggregateDeviceNameRef);
  1027. // add our choice of UID for the aggregate device to the dictionary
  1028. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceUIDKey), AggregateDeviceUIDRef);
  1029. // add a "private aggregate key" to the dictionary
  1030. int value = 1;
  1031. CFNumberRef AggregateDeviceNumberRef = CFNumberCreate(NULL, kCFNumberIntType, &value);
  1032. SInt32 system;
  1033. Gestalt(gestaltSystemVersion, &system);
  1034. jack_log("JackCoreAudioAdapter::CreateAggregateDevice : system version = %x limit = %x", system, 0x00001054);
  1035. // Starting with 10.5.4 systems, the AD can be internal... (better)
  1036. if (system < 0x00001054) {
  1037. jack_log("JackCoreAudioAdapter::CreateAggregateDevice : public aggregate device....");
  1038. } else {
  1039. jack_log("JackCoreAudioAdapter::CreateAggregateDevice : private aggregate device....");
  1040. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceIsPrivateKey), AggregateDeviceNumberRef);
  1041. }
  1042. // Prepare sub-devices for clock drift compensation
  1043. CFMutableArrayRef subDevicesArrayClock = NULL;
  1044. /*
  1045. if (fClockDriftCompensate) {
  1046. if (need_clock_drift_compensation) {
  1047. jack_info("Clock drift compensation activated...");
  1048. subDevicesArrayClock = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  1049. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  1050. CFStringRef UID = GetDeviceName(captureDeviceID[i]);
  1051. if (UID) {
  1052. CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  1053. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
  1054. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
  1055. //CFRelease(UID);
  1056. CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
  1057. }
  1058. }
  1059. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  1060. CFStringRef UID = GetDeviceName(playbackDeviceID[i]);
  1061. if (UID) {
  1062. CFMutableDictionaryRef subdeviceAggDeviceDict = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
  1063. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceUIDKey), UID);
  1064. CFDictionaryAddValue(subdeviceAggDeviceDict, CFSTR(kAudioSubDeviceDriftCompensationKey), AggregateDeviceNumberRef);
  1065. //CFRelease(UID);
  1066. CFArrayAppendValue(subDevicesArrayClock, subdeviceAggDeviceDict);
  1067. }
  1068. }
  1069. // add sub-device clock array for the aggregate device to the dictionary
  1070. CFDictionaryAddValue(aggDeviceDict, CFSTR(kAudioAggregateDeviceSubDeviceListKey), subDevicesArrayClock);
  1071. } else {
  1072. jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
  1073. }
  1074. }
  1075. */
  1076. //-------------------------------------------------
  1077. // Create a CFMutableArray for our sub-device list
  1078. //-------------------------------------------------
  1079. // we need to append the UID for each device to a CFMutableArray, so create one here
  1080. CFMutableArrayRef subDevicesArray = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
  1081. vector<CFStringRef> captureDeviceUID;
  1082. for (UInt32 i = 0; i < captureDeviceID.size(); i++) {
  1083. CFStringRef ref = GetDeviceName(captureDeviceID[i]);
  1084. if (ref == NULL)
  1085. return -1;
  1086. captureDeviceUID.push_back(ref);
  1087. // input sub-devices in this example, so append the sub-device's UID to the CFArray
  1088. CFArrayAppendValue(subDevicesArray, ref);
  1089. }
  1090. vector<CFStringRef> playbackDeviceUID;
  1091. for (UInt32 i = 0; i < playbackDeviceID.size(); i++) {
  1092. CFStringRef ref = GetDeviceName(playbackDeviceID[i]);
  1093. if (ref == NULL)
  1094. return -1;
  1095. playbackDeviceUID.push_back(ref);
  1096. // output sub-devices in this example, so append the sub-device's UID to the CFArray
  1097. CFArrayAppendValue(subDevicesArray, ref);
  1098. }
  1099. //-----------------------------------------------------------------------
  1100. // Feed the dictionary to the plugin, to create a blank aggregate device
  1101. //-----------------------------------------------------------------------
  1102. AudioObjectPropertyAddress pluginAOPA;
  1103. pluginAOPA.mSelector = kAudioPlugInCreateAggregateDevice;
  1104. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  1105. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  1106. UInt32 outDataSize;
  1107. osErr = AudioObjectGetPropertyDataSize(fPluginID, &pluginAOPA, 0, NULL, &outDataSize);
  1108. if (osErr != noErr) {
  1109. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioObjectGetPropertyDataSize error");
  1110. printError(osErr);
  1111. goto error;
  1112. }
  1113. osErr = AudioObjectGetPropertyData(fPluginID, &pluginAOPA, sizeof(aggDeviceDict), &aggDeviceDict, &outDataSize, outAggregateDevice);
  1114. if (osErr != noErr) {
  1115. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioObjectGetPropertyData error");
  1116. printError(osErr);
  1117. goto error;
  1118. }
  1119. // pause for a bit to make sure that everything completed correctly
  1120. // this is to work around a bug in the HAL where a new aggregate device seems to disappear briefly after it is created
  1121. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  1122. //-------------------------
  1123. // Set the sub-device list
  1124. //-------------------------
  1125. pluginAOPA.mSelector = kAudioAggregateDevicePropertyFullSubDeviceList;
  1126. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  1127. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  1128. outDataSize = sizeof(CFMutableArrayRef);
  1129. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &subDevicesArray);
  1130. if (osErr != noErr) {
  1131. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioObjectSetPropertyData for sub-device list error");
  1132. printError(osErr);
  1133. goto error;
  1134. }
  1135. // pause again to give the changes time to take effect
  1136. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  1137. //-----------------------
  1138. // Set the master device
  1139. //-----------------------
  1140. // set the master device manually (this is the device which will act as the master clock for the aggregate device)
  1141. // pass in the UID of the device you want to use
  1142. pluginAOPA.mSelector = kAudioAggregateDevicePropertyMasterSubDevice;
  1143. pluginAOPA.mScope = kAudioObjectPropertyScopeGlobal;
  1144. pluginAOPA.mElement = kAudioObjectPropertyElementMaster;
  1145. outDataSize = sizeof(CFStringRef);
  1146. osErr = AudioObjectSetPropertyData(*outAggregateDevice, &pluginAOPA, 0, NULL, outDataSize, &captureDeviceUID[0]); // First apture is master...
  1147. if (osErr != noErr) {
  1148. jack_error("JackCoreAudioAdapter::CreateAggregateDevice : AudioObjectSetPropertyData for master device error");
  1149. printError(osErr);
  1150. goto error;
  1151. }
  1152. // pause again to give the changes time to take effect
  1153. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  1154. // Prepare sub-devices for clock drift compensation
  1155. // Workaround for bug in the HAL : until 10.6.2
  1156. if (fClockDriftCompensate) {
  1157. if (need_clock_drift_compensation) {
  1158. jack_info("Clock drift compensation activated...");
  1159. // Get the property data size
  1160. osErr = AudioObjectGetPropertyDataSize(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize);
  1161. if (osErr != noErr) {
  1162. jack_error("JackCoreAudioAdapter::CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
  1163. printError(osErr);
  1164. }
  1165. // Calculate the number of object IDs
  1166. subDevicesNum = outSize / sizeof(AudioObjectID);
  1167. jack_info("JackCoreAudioAdapter::CreateAggregateDevice clock drift compensation, number of sub-devices = %d", subDevicesNum);
  1168. AudioObjectID subDevices[subDevicesNum];
  1169. outSize = sizeof(subDevices);
  1170. osErr = AudioObjectGetPropertyData(*outAggregateDevice, &theAddressOwned, theQualifierDataSize, theQualifierData, &outSize, subDevices);
  1171. if (osErr != noErr) {
  1172. jack_error("JackCoreAudioAdapter::CreateAggregateDevice kAudioObjectPropertyOwnedObjects error");
  1173. printError(osErr);
  1174. }
  1175. // Set kAudioSubDevicePropertyDriftCompensation property...
  1176. for (UInt32 index = 0; index < subDevicesNum; ++index) {
  1177. UInt32 theDriftCompensationValue = 1;
  1178. osErr = AudioObjectSetPropertyData(subDevices[index], &theAddressDrift, 0, NULL, sizeof(UInt32), &theDriftCompensationValue);
  1179. if (osErr != noErr) {
  1180. jack_error("JackCoreAudioAdapter::CreateAggregateDevice kAudioSubDevicePropertyDriftCompensation error");
  1181. printError(osErr);
  1182. }
  1183. }
  1184. } else {
  1185. jack_info("Clock drift compensation was asked but is not needed (devices use the same clock domain)");
  1186. }
  1187. }
  1188. // pause again to give the changes time to take effect
  1189. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, false);
  1190. //----------
  1191. // Clean up
  1192. //----------
  1193. // release the private AD key
  1194. CFRelease(AggregateDeviceNumberRef);
  1195. // release the CF objects we have created - we don't need them any more
  1196. CFRelease(aggDeviceDict);
  1197. CFRelease(subDevicesArray);
  1198. if (subDevicesArrayClock)
  1199. CFRelease(subDevicesArrayClock);
  1200. // release the device UID
  1201. for (UInt32 i = 0; i < captureDeviceUID.size(); i++) {
  1202. CFRelease(captureDeviceUID[i]);
  1203. }
  1204. for (UInt32 i = 0; i < playbackDeviceUID.size(); i++) {
  1205. CFRelease(playbackDeviceUID[i]);
  1206. }
  1207. jack_log("New aggregate device %ld", *outAggregateDevice);
  1208. return noErr;
  1209. error:
  1210. DestroyAggregateDevice();
  1211. return -1;
  1212. }
  1213. bool JackCoreAudioAdapter::IsAggregateDevice(AudioDeviceID device)
  1214. {
  1215. OSStatus err = noErr;
  1216. AudioObjectID sub_device[32];
  1217. UInt32 outSize = sizeof(sub_device);
  1218. err = AudioDeviceGetProperty(device, 0, kAudioDeviceSectionGlobal, kAudioAggregateDevicePropertyActiveSubDeviceList, &outSize, sub_device);
  1219. if (err != noErr) {
  1220. jack_log("Device does not have subdevices");
  1221. return false;
  1222. } else {
  1223. int num_devices = outSize / sizeof(AudioObjectID);
  1224. jack_log("Device does has %d subdevices", num_devices);
  1225. return true;
  1226. }
  1227. }
  1228. void JackCoreAudioAdapter::CloseAUHAL()
  1229. {
  1230. AudioUnitUninitialize(fAUHAL);
  1231. CloseComponent(fAUHAL);
  1232. }
  1233. int JackCoreAudioAdapter::Open()
  1234. {
  1235. return (AudioOutputUnitStart(fAUHAL) != noErr) ? -1 : 0;
  1236. }
  1237. int JackCoreAudioAdapter::Close()
  1238. {
  1239. #ifdef JACK_MONITOR
  1240. fTable.Save(fHostBufferSize, fHostSampleRate, fAdaptedSampleRate, fAdaptedBufferSize);
  1241. #endif
  1242. AudioOutputUnitStop(fAUHAL);
  1243. DisposeBuffers();
  1244. CloseAUHAL();
  1245. RemoveListeners();
  1246. if (fPluginID > 0)
  1247. DestroyAggregateDevice();
  1248. return 0;
  1249. }
  1250. int JackCoreAudioAdapter::SetSampleRate ( jack_nframes_t sample_rate ) {
  1251. JackAudioAdapterInterface::SetHostSampleRate ( sample_rate );
  1252. Close();
  1253. return Open();
  1254. }
  1255. int JackCoreAudioAdapter::SetBufferSize ( jack_nframes_t buffer_size ) {
  1256. JackAudioAdapterInterface::SetHostBufferSize ( buffer_size );
  1257. Close();
  1258. return Open();
  1259. }
  1260. } // namespace
  1261. #ifdef __cplusplus
  1262. extern "C"
  1263. {
  1264. #endif
  1265. SERVER_EXPORT jack_driver_desc_t* jack_get_descriptor()
  1266. {
  1267. jack_driver_desc_t * desc;
  1268. jack_driver_desc_filler_t filler;
  1269. jack_driver_param_value_t value;
  1270. desc = jack_driver_descriptor_construct("audioadapter", "netjack audio <==> net backend adapter", &filler);
  1271. value.i = -1;
  1272. 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");
  1273. 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");
  1274. 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");
  1275. value.str[0] = 0;
  1276. jack_driver_descriptor_add_parameter(desc, &filler, "capture", 'C', JackDriverParamString, &value, NULL, "Input CoreAudio device name", NULL);
  1277. jack_driver_descriptor_add_parameter(desc, &filler, "playback", 'P', JackDriverParamString, &value, NULL, "Output CoreAudio device name", NULL);
  1278. value.ui = 44100U;
  1279. jack_driver_descriptor_add_parameter(desc, &filler, "rate", 'r', JackDriverParamUInt, &value, NULL, "Sample rate", NULL);
  1280. value.ui = 512U;
  1281. jack_driver_descriptor_add_parameter(desc, &filler, "period", 'p', JackDriverParamUInt, &value, NULL, "Frames per period", NULL);
  1282. value.i = TRUE;
  1283. jack_driver_descriptor_add_parameter(desc, &filler, "duplex", 'D', JackDriverParamBool, &value, NULL, "Provide both capture and playback ports", NULL);
  1284. value.str[0] = 0;
  1285. jack_driver_descriptor_add_parameter(desc, &filler, "device", 'd', JackDriverParamString, &value, NULL, "CoreAudio device name", NULL);
  1286. value.i = TRUE;
  1287. jack_driver_descriptor_add_parameter(desc, &filler, "list-devices", 'l', JackDriverParamBool, &value, NULL, "Display available CoreAudio devices", NULL);
  1288. value.ui = 0;
  1289. jack_driver_descriptor_add_parameter(desc, &filler, "quality", 'q', JackDriverParamInt, &value, NULL, "Resample algorithm quality (0 - 4)", NULL);
  1290. value.ui = 32768;
  1291. jack_driver_descriptor_add_parameter(desc, &filler, "ring-buffer", 'g', JackDriverParamInt, &value, NULL, "Fixed ringbuffer size", "Fixed ringbuffer size (if not set => automatic adaptative)");
  1292. value.i = FALSE;
  1293. 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");
  1294. return desc;
  1295. }
  1296. #ifdef __cplusplus
  1297. }
  1298. #endif