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.

1580 lines
61KB

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