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.

1437 lines
54KB

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