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.

1610 lines
62KB

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