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.

1055 lines
38KB

  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. #if defined(HAVE_CONFIG_H)
  16. #include "config.h"
  17. #endif
  18. #include "JackCoreAudioAdapter.h"
  19. #include "JackError.h"
  20. #include <unistd.h>
  21. namespace Jack
  22. {
  23. static OSStatus DisplayDeviceNames()
  24. {
  25. UInt32 size;
  26. Boolean isWritable;
  27. int i, deviceNum;
  28. OSStatus err;
  29. CFStringRef UIname;
  30. err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
  31. if (err != noErr)
  32. return err;
  33. deviceNum = size / sizeof(AudioDeviceID);
  34. AudioDeviceID devices[deviceNum];
  35. err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
  36. if (err != noErr)
  37. return err;
  38. for (i = 0; i < deviceNum; i++) {
  39. char device_name[256];
  40. char internal_name[256];
  41. size = sizeof(CFStringRef);
  42. UIname = NULL;
  43. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  44. if (err == noErr) {
  45. CFStringGetCString(UIname, internal_name, 256, CFStringGetSystemEncoding());
  46. } else {
  47. goto error;
  48. }
  49. size = 256;
  50. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &size, device_name);
  51. if (err != noErr)
  52. return err;
  53. jack_info("Device name = \'%s\', internal_name = \'%s\' (to be used as -C, -P, or -d parameter)", device_name, internal_name);
  54. }
  55. return noErr;
  56. error:
  57. if (UIname != NULL)
  58. CFRelease(UIname);
  59. return err;
  60. }
  61. static void printError(OSStatus err)
  62. {
  63. switch (err) {
  64. case kAudioHardwareNoError:
  65. jack_log("error code : kAudioHardwareNoError");
  66. break;
  67. case kAudioConverterErr_FormatNotSupported:
  68. jack_log("error code : kAudioConverterErr_FormatNotSupported");
  69. break;
  70. case kAudioConverterErr_OperationNotSupported:
  71. jack_log("error code : kAudioConverterErr_OperationNotSupported");
  72. break;
  73. case kAudioConverterErr_PropertyNotSupported:
  74. jack_log("error code : kAudioConverterErr_PropertyNotSupported");
  75. break;
  76. case kAudioConverterErr_InvalidInputSize:
  77. jack_log("error code : kAudioConverterErr_InvalidInputSize");
  78. break;
  79. case kAudioConverterErr_InvalidOutputSize:
  80. jack_log("error code : kAudioConverterErr_InvalidOutputSize");
  81. break;
  82. case kAudioConverterErr_UnspecifiedError:
  83. jack_log("error code : kAudioConverterErr_UnspecifiedError");
  84. break;
  85. case kAudioConverterErr_BadPropertySizeError:
  86. jack_log("error code : kAudioConverterErr_BadPropertySizeError");
  87. break;
  88. case kAudioConverterErr_RequiresPacketDescriptionsError:
  89. jack_log("error code : kAudioConverterErr_RequiresPacketDescriptionsError");
  90. break;
  91. case kAudioConverterErr_InputSampleRateOutOfRange:
  92. jack_log("error code : kAudioConverterErr_InputSampleRateOutOfRange");
  93. break;
  94. case kAudioConverterErr_OutputSampleRateOutOfRange:
  95. jack_log("error code : kAudioConverterErr_OutputSampleRateOutOfRange");
  96. break;
  97. case kAudioHardwareNotRunningError:
  98. jack_log("error code : kAudioHardwareNotRunningError");
  99. break;
  100. case kAudioHardwareUnknownPropertyError:
  101. jack_log("error code : kAudioHardwareUnknownPropertyError");
  102. break;
  103. case kAudioHardwareIllegalOperationError:
  104. jack_log("error code : kAudioHardwareIllegalOperationError");
  105. break;
  106. case kAudioHardwareBadDeviceError:
  107. jack_log("error code : kAudioHardwareBadDeviceError");
  108. break;
  109. case kAudioHardwareBadStreamError:
  110. jack_log("error code : kAudioHardwareBadStreamError");
  111. break;
  112. case kAudioDeviceUnsupportedFormatError:
  113. jack_log("error code : kAudioDeviceUnsupportedFormatError");
  114. break;
  115. case kAudioDevicePermissionsError:
  116. jack_log("error code : kAudioDevicePermissionsError");
  117. break;
  118. case kAudioHardwareBadObjectError:
  119. jack_log("error code : kAudioHardwareBadObjectError");
  120. break;
  121. case kAudioHardwareUnsupportedOperationError:
  122. jack_log("error code : kAudioHardwareUnsupportedOperationError");
  123. break;
  124. default:
  125. jack_log("error code : unknown");
  126. break;
  127. }
  128. }
  129. OSStatus JackCoreAudioAdapter::SRNotificationCallback(AudioDeviceID inDevice,
  130. UInt32 inChannel,
  131. Boolean isInput,
  132. AudioDevicePropertyID inPropertyID,
  133. void* inClientData)
  134. {
  135. JackCoreAudioAdapter* driver = static_cast<JackCoreAudioAdapter*>(inClientData);
  136. switch (inPropertyID) {
  137. case kAudioDevicePropertyNominalSampleRate: {
  138. jack_log("JackCoreAudioDriver::SRNotificationCallback kAudioDevicePropertyNominalSampleRate");
  139. driver->fState = true;
  140. break;
  141. }
  142. }
  143. return noErr;
  144. }
  145. // A better implementation would try to recover in case of hardware device change (see HALLAB HLFilePlayerWindowControllerAudioDevicePropertyListenerProc code)
  146. OSStatus JackCoreAudioAdapter::DeviceNotificationCallback(AudioDeviceID inDevice,
  147. UInt32 inChannel,
  148. Boolean isInput,
  149. AudioDevicePropertyID inPropertyID,
  150. void* inClientData)
  151. {
  152. JackCoreAudioAdapter* driver = (JackCoreAudioAdapter*)inClientData;
  153. switch (inPropertyID) {
  154. case kAudioDevicePropertyStreamConfiguration:
  155. case kAudioDevicePropertyNominalSampleRate: {
  156. UInt32 outSize = sizeof(Float64);
  157. Float64 sampleRate;
  158. int in_nChannels = 0;
  159. int out_nChannels = 0;
  160. char capture_driver_name[256];
  161. char playback_driver_name[256];
  162. // Stop and restart
  163. AudioOutputUnitStop(driver->fAUHAL);
  164. driver->RemoveListeners();
  165. driver->CloseAUHAL();
  166. OSStatus err = AudioDeviceGetProperty(driver->fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
  167. if (err != noErr) {
  168. jack_error("Cannot get current sample rate");
  169. printError(err);
  170. }
  171. jack_log("JackCoreAudioDriver::DeviceNotificationCallback kAudioDevicePropertyNominalSampleRate %ld", long(sampleRate));
  172. if (driver->SetupDevices(driver->fCaptureUID, driver->fPlaybackUID, capture_driver_name, playback_driver_name) < 0)
  173. return -1;
  174. if (driver->SetupChannels(driver->fCapturing, driver->fPlaying, driver->fCaptureChannels, driver->fPlaybackChannels, in_nChannels, out_nChannels, false) < 0)
  175. return -1;
  176. if (driver->SetupBufferSizeAndSampleRate(driver->fAdaptedBufferSize, sampleRate) < 0)
  177. return -1;
  178. driver->SetAdaptedSampleRate(sampleRate);
  179. if (driver->OpenAUHAL(driver->fCapturing,
  180. driver->fPlaying,
  181. driver->fCaptureChannels,
  182. driver->fPlaybackChannels,
  183. in_nChannels,
  184. out_nChannels,
  185. driver->fAdaptedBufferSize,
  186. sampleRate,
  187. false) < 0)
  188. goto error;
  189. if (driver->AddListeners() < 0)
  190. goto error;
  191. AudioOutputUnitStart(driver->fAUHAL);
  192. return noErr;
  193. error:
  194. driver->CloseAUHAL();
  195. break;
  196. }
  197. }
  198. return noErr;
  199. }
  200. int JackCoreAudioAdapter::AddListeners()
  201. {
  202. OSStatus err = noErr;
  203. // Add listeners
  204. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback, this);
  205. if (err != noErr) {
  206. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioHardwarePropertyDevices");
  207. printError(err);
  208. return -1;
  209. }
  210. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback, this);
  211. if (err != noErr) {
  212. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  213. printError(err);
  214. return -1;
  215. }
  216. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback, this);
  217. if (err != noErr) {
  218. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyDeviceIsRunning");
  219. printError(err);
  220. return -1;
  221. }
  222. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  223. if (err != noErr) {
  224. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  225. printError(err);
  226. return -1;
  227. }
  228. err = AudioDeviceAddPropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback, this);
  229. if (err != noErr) {
  230. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyStreamConfiguration");
  231. printError(err);
  232. return -1;
  233. }
  234. return 0;
  235. }
  236. void JackCoreAudioAdapter::RemoveListeners()
  237. {
  238. /*
  239. #ifdef MAC_OS_X_VERSION_10_5
  240. AudioDeviceDestroyIOProcID(fDeviceID, fMesureCallbackID);
  241. #else
  242. AudioDeviceRemoveIOProc(fDeviceID, MeasureCallback);
  243. #endif
  244. */
  245. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioHardwarePropertyDevices, DeviceNotificationCallback);
  246. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, DeviceNotificationCallback);
  247. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyDeviceIsRunning, DeviceNotificationCallback);
  248. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  249. AudioDeviceRemovePropertyListener(fDeviceID, 0, false, kAudioDevicePropertyStreamConfiguration, DeviceNotificationCallback);
  250. }
  251. OSStatus JackCoreAudioAdapter::Render(void *inRefCon,
  252. AudioUnitRenderActionFlags *ioActionFlags,
  253. const AudioTimeStamp *inTimeStamp,
  254. UInt32 inBusNumber,
  255. UInt32 inNumberFrames,
  256. AudioBufferList *ioData)
  257. {
  258. JackCoreAudioAdapter* adapter = static_cast<JackCoreAudioAdapter*>(inRefCon);
  259. AudioUnitRender(adapter->fAUHAL, ioActionFlags, inTimeStamp, 1, inNumberFrames, adapter->fInputData);
  260. bool failure = false;
  261. jack_nframes_t time1, time2;
  262. adapter->ResampleFactor(time1, time2);
  263. for (int i = 0; i < adapter->fCaptureChannels; i++) {
  264. adapter->fCaptureRingBuffer[i]->SetRatio(time1, time2);
  265. if (adapter->fCaptureRingBuffer[i]->WriteResample((float*)adapter->fInputData->mBuffers[i].mData, inNumberFrames) < inNumberFrames)
  266. failure = true;
  267. }
  268. for (int i = 0; i < adapter->fPlaybackChannels; i++) {
  269. adapter->fPlaybackRingBuffer[i]->SetRatio(time2, time1);
  270. if (adapter->fPlaybackRingBuffer[i]->ReadResample((float*)ioData->mBuffers[i].mData, inNumberFrames) < inNumberFrames)
  271. failure = true;
  272. }
  273. #ifdef JACK_MONITOR
  274. adapter->fTable.Write(time1, time2, double(time1) / double(time2), double(time2) / double(time1),
  275. adapter->fCaptureRingBuffer[0]->ReadSpace(), adapter->fPlaybackRingBuffer[0]->WriteSpace());
  276. #endif
  277. // Reset all ringbuffers in case of failure
  278. if (failure) {
  279. jack_error("JackCoreAudioAdapter::Render ringbuffer failure... reset");
  280. adapter->ResetRingBuffers();
  281. }
  282. return noErr;
  283. }
  284. JackCoreAudioAdapter::JackCoreAudioAdapter(jack_nframes_t buffer_size, jack_nframes_t sample_rate, const JSList* params)
  285. :JackAudioAdapterInterface(buffer_size, sample_rate), fInputData(0), fCapturing(false), fPlaying(false), fState(false)
  286. {
  287. const JSList* node;
  288. const jack_driver_param_t* param;
  289. char captureName[256];
  290. char playbackName[256];
  291. fCaptureUID[0] = 0;
  292. fPlaybackUID[0] = 0;
  293. // Default values
  294. fCaptureChannels = 0;
  295. fPlaybackChannels = 0;
  296. for (node = params; node; node = jack_slist_next(node)) {
  297. param = (const jack_driver_param_t*) node->data;
  298. switch (param->character) {
  299. case 'c' :
  300. fCaptureChannels = fPlaybackChannels = param->value.ui;
  301. break;
  302. case 'i':
  303. fCaptureChannels = param->value.ui;
  304. break;
  305. case 'o':
  306. fPlaybackChannels = param->value.ui;
  307. break;
  308. case 'C':
  309. fCapturing = true;
  310. strncpy(fCaptureUID, param->value.str, 256);
  311. break;
  312. case 'P':
  313. fPlaying = true;
  314. strncpy(fPlaybackUID, param->value.str, 256);
  315. break;
  316. case 'd':
  317. strncpy(fCaptureUID, param->value.str, 256);
  318. strncpy(fPlaybackUID, param->value.str, 256);
  319. break;
  320. case 'D':
  321. fCapturing = fPlaying = true;
  322. break;
  323. case 'r':
  324. SetAdaptedSampleRate(param->value.ui);
  325. break;
  326. case 'p':
  327. SetAdaptedBufferSize(param->value.ui);
  328. break;
  329. case 'l':
  330. DisplayDeviceNames();
  331. break;
  332. }
  333. }
  334. /* duplex is the default */
  335. if (!fCapturing && !fPlaying) {
  336. fCapturing = true;
  337. fPlaying = true;
  338. }
  339. int in_nChannels = 0;
  340. int out_nChannels = 0;
  341. if (SetupDevices(fCaptureUID, fPlaybackUID, captureName, playbackName) < 0)
  342. throw -1;
  343. if (SetupChannels(fCapturing, fPlaying, fCaptureChannels, fPlaybackChannels, in_nChannels, out_nChannels, true) < 0)
  344. throw -1;
  345. if (SetupBufferSizeAndSampleRate(fAdaptedBufferSize, fAdaptedSampleRate) < 0)
  346. throw -1;
  347. if (fCapturing && fCaptureChannels > 0)
  348. if (SetupBuffers(fCaptureChannels) < 0)
  349. throw -1;
  350. if (OpenAUHAL(fCapturing, fPlaying, fCaptureChannels, fPlaybackChannels, in_nChannels, out_nChannels, fAdaptedBufferSize, fAdaptedSampleRate, true) < 0)
  351. throw -1;
  352. if (AddListeners() < 0)
  353. throw -1;
  354. }
  355. OSStatus JackCoreAudioAdapter::GetDefaultDevice(AudioDeviceID* id)
  356. {
  357. OSStatus res;
  358. UInt32 theSize = sizeof(UInt32);
  359. AudioDeviceID inDefault;
  360. AudioDeviceID outDefault;
  361. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  362. return res;
  363. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  364. return res;
  365. jack_log("GetDefaultDevice: input = %ld output = %ld", inDefault, outDefault);
  366. // Get the device only if default input and ouput are the same
  367. if (inDefault == outDefault) {
  368. *id = inDefault;
  369. return noErr;
  370. } else {
  371. jack_error("Default input and output devices are not the same !!");
  372. return kAudioHardwareBadDeviceError;
  373. }
  374. }
  375. OSStatus JackCoreAudioAdapter::GetTotalChannels(AudioDeviceID device, int& channelCount, bool isInput)
  376. {
  377. OSStatus err = noErr;
  378. UInt32 outSize;
  379. Boolean outWritable;
  380. AudioBufferList* bufferList = 0;
  381. channelCount = 0;
  382. err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, &outWritable);
  383. if (err == noErr) {
  384. bufferList = (AudioBufferList*)malloc(outSize);
  385. err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, bufferList);
  386. if (err == noErr) {
  387. for (unsigned int i = 0; i < bufferList->mNumberBuffers; i++)
  388. channelCount += bufferList->mBuffers[i].mNumberChannels;
  389. }
  390. if (bufferList)
  391. free(bufferList);
  392. }
  393. return err;
  394. }
  395. OSStatus JackCoreAudioAdapter::GetDeviceIDFromUID(const char* UID, AudioDeviceID* id)
  396. {
  397. UInt32 size = sizeof(AudioValueTranslation);
  398. CFStringRef inIUD = CFStringCreateWithCString(NULL, UID, CFStringGetSystemEncoding());
  399. AudioValueTranslation value = { &inIUD, sizeof(CFStringRef), id, sizeof(AudioDeviceID) };
  400. if (inIUD == NULL) {
  401. return kAudioHardwareUnspecifiedError;
  402. } else {
  403. OSStatus res = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, &size, &value);
  404. CFRelease(inIUD);
  405. jack_log("GetDeviceIDFromUID %s %ld", UID, *id);
  406. return (*id == kAudioDeviceUnknown) ? kAudioHardwareBadDeviceError : res;
  407. }
  408. }
  409. OSStatus JackCoreAudioAdapter::GetDefaultInputDevice(AudioDeviceID* id)
  410. {
  411. OSStatus res;
  412. UInt32 theSize = sizeof(UInt32);
  413. AudioDeviceID inDefault;
  414. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  415. return res;
  416. jack_log("GetDefaultInputDevice: input = %ld ", inDefault);
  417. *id = inDefault;
  418. return noErr;
  419. }
  420. OSStatus JackCoreAudioAdapter::GetDefaultOutputDevice(AudioDeviceID* id)
  421. {
  422. OSStatus res;
  423. UInt32 theSize = sizeof(UInt32);
  424. AudioDeviceID outDefault;
  425. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  426. return res;
  427. jack_log("GetDefaultOutputDevice: output = %ld", outDefault);
  428. *id = outDefault;
  429. return noErr;
  430. }
  431. OSStatus JackCoreAudioAdapter::GetDeviceNameFromID(AudioDeviceID id, char* name)
  432. {
  433. UInt32 size = 256;
  434. return AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceName, &size, name);
  435. }
  436. // Setup
  437. int JackCoreAudioAdapter::SetupDevices(const char* capture_driver_uid,
  438. const char* playback_driver_uid,
  439. char* capture_driver_name,
  440. char* playback_driver_name)
  441. {
  442. capture_driver_name[0] = 0;
  443. playback_driver_name[0] = 0;
  444. // Duplex
  445. if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
  446. jack_log("JackCoreAudioAdapter::Open duplex");
  447. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  448. if (GetDefaultDevice(&fDeviceID) != noErr) {
  449. jack_error("Cannot open default device");
  450. return -1;
  451. }
  452. }
  453. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  454. jack_error("Cannot get device name from device ID");
  455. return -1;
  456. }
  457. // Capture only
  458. } else if (strcmp(capture_driver_uid, "") != 0) {
  459. jack_log("JackCoreAudioAdapter::Open capture only");
  460. if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
  461. if (GetDefaultInputDevice(&fDeviceID) != noErr) {
  462. jack_error("Cannot open default device");
  463. return -1;
  464. }
  465. }
  466. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
  467. jack_error("Cannot get device name from device ID");
  468. return -1;
  469. }
  470. // Playback only
  471. } else if (strcmp(playback_driver_uid, "") != 0) {
  472. jack_log("JackCoreAudioAdapter::Open playback only");
  473. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  474. if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
  475. jack_error("Cannot open default device");
  476. return -1;
  477. }
  478. }
  479. if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  480. jack_error("Cannot get device name from device ID");
  481. return -1;
  482. }
  483. // Use default driver in duplex mode
  484. } else {
  485. jack_log("JackCoreAudioAdapter::Open default driver");
  486. if (GetDefaultDevice(&fDeviceID) != noErr) {
  487. jack_error("Cannot open default device");
  488. return -1;
  489. }
  490. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  491. jack_error("Cannot get device name from device ID");
  492. return -1;
  493. }
  494. }
  495. return 0;
  496. }
  497. int JackCoreAudioAdapter::SetupChannels(bool capturing,
  498. bool playing,
  499. int& inchannels,
  500. int& outchannels,
  501. int& in_nChannels,
  502. int& out_nChannels,
  503. bool strict)
  504. {
  505. OSStatus err = noErr;
  506. if (capturing) {
  507. err = GetTotalChannels(fDeviceID, in_nChannels, true);
  508. if (err != noErr) {
  509. jack_error("Cannot get input channel number");
  510. printError(err);
  511. return -1;
  512. }
  513. }
  514. if (playing) {
  515. err = GetTotalChannels(fDeviceID, out_nChannels, false);
  516. if (err != noErr) {
  517. jack_error("Cannot get output channel number");
  518. printError(err);
  519. return -1;
  520. }
  521. }
  522. if (inchannels > in_nChannels) {
  523. jack_error("This device hasn't required input channels inchannels = %ld in_nChannels = %ld", inchannels, in_nChannels);
  524. if (strict)
  525. return -1;
  526. }
  527. if (outchannels > out_nChannels) {
  528. jack_error("This device hasn't required output channels outchannels = %ld out_nChannels = %ld", outchannels, out_nChannels);
  529. if (strict)
  530. return -1;
  531. }
  532. if (inchannels == 0) {
  533. jack_log("Setup max in channels = %ld", in_nChannels);
  534. inchannels = in_nChannels;
  535. }
  536. if (outchannels == 0) {
  537. jack_log("Setup max out channels = %ld", out_nChannels);
  538. outchannels = out_nChannels;
  539. }
  540. return 0;
  541. }
  542. int JackCoreAudioAdapter::SetupBufferSizeAndSampleRate(jack_nframes_t nframes, jack_nframes_t samplerate)
  543. {
  544. OSStatus err = noErr;
  545. UInt32 outSize;
  546. Float64 sampleRate;
  547. // Setting buffer size
  548. outSize = sizeof(UInt32);
  549. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &nframes);
  550. if (err != noErr) {
  551. jack_error("Cannot set buffer size %ld", nframes);
  552. printError(err);
  553. return -1;
  554. }
  555. // Get sample rate
  556. outSize = sizeof(Float64);
  557. err = AudioDeviceGetProperty(fDeviceID, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
  558. if (err != noErr) {
  559. jack_error("Cannot get current sample rate");
  560. printError(err);
  561. return -1;
  562. }
  563. // If needed, set new sample rate
  564. if (samplerate != (jack_nframes_t)sampleRate) {
  565. sampleRate = (Float64)samplerate;
  566. // To get SR change notification
  567. err = AudioDeviceAddPropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback, this);
  568. if (err != noErr) {
  569. jack_error("Error calling AudioDeviceAddPropertyListener with kAudioDevicePropertyNominalSampleRate");
  570. printError(err);
  571. return -1;
  572. }
  573. err = AudioDeviceSetProperty(fDeviceID, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &sampleRate);
  574. if (err != noErr) {
  575. jack_error("Cannot set sample rate = %ld", samplerate);
  576. printError(err);
  577. return -1;
  578. }
  579. // Waiting for SR change notification
  580. int count = 0;
  581. while (!fState && count++ < 100) {
  582. usleep(100000);
  583. jack_log("Wait count = %ld", count);
  584. }
  585. // Remove SR change notification
  586. AudioDeviceRemovePropertyListener(fDeviceID, 0, true, kAudioDevicePropertyNominalSampleRate, SRNotificationCallback);
  587. }
  588. return 0;
  589. }
  590. int JackCoreAudioAdapter::SetupBuffers(int inchannels)
  591. {
  592. jack_log("JackCoreAudioAdapter::SetupBuffers: input = %ld", inchannels);
  593. // Prepare buffers
  594. fInputData = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
  595. if (fInputData == 0) {
  596. jack_error("Cannot allocate memory for input buffers");
  597. return -1;
  598. }
  599. fInputData->mNumberBuffers = inchannels;
  600. for (int i = 0; i < fCaptureChannels; i++) {
  601. fInputData->mBuffers[i].mNumberChannels = 1;
  602. fInputData->mBuffers[i].mDataByteSize = fAdaptedBufferSize * sizeof(float);
  603. fInputData->mBuffers[i].mData = malloc(fAdaptedBufferSize * sizeof(float));
  604. }
  605. return 0;
  606. }
  607. void JackCoreAudioAdapter::DisposeBuffers()
  608. {
  609. if (fInputData) {
  610. for (int i = 0; i < fCaptureChannels; i++)
  611. free(fInputData->mBuffers[i].mData);
  612. free(fInputData);
  613. fInputData = 0;
  614. }
  615. }
  616. int JackCoreAudioAdapter::OpenAUHAL(bool capturing,
  617. bool playing,
  618. int inchannels,
  619. int outchannels,
  620. int in_nChannels,
  621. int out_nChannels,
  622. jack_nframes_t nframes,
  623. jack_nframes_t samplerate,
  624. bool strict)
  625. {
  626. ComponentResult err1;
  627. UInt32 enableIO;
  628. AudioStreamBasicDescription srcFormat, dstFormat;
  629. jack_log("OpenAUHAL capturing = %ld playing = %ld inchannels = %ld outchannels = %ld in_nChannels = %ld out_nChannels = %ld ", capturing, playing, inchannels, outchannels, in_nChannels, out_nChannels);
  630. // AUHAL
  631. ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
  632. Component HALOutput = FindNextComponent(NULL, &cd);
  633. err1 = OpenAComponent(HALOutput, &fAUHAL);
  634. if (err1 != noErr) {
  635. jack_error("Error calling OpenAComponent");
  636. printError(err1);
  637. return -1;
  638. }
  639. err1 = AudioUnitInitialize(fAUHAL);
  640. if (err1 != noErr) {
  641. jack_error("Cannot initialize AUHAL unit");
  642. printError(err1);
  643. return -1;
  644. }
  645. // Start I/O
  646. enableIO = 1;
  647. if (capturing && inchannels > 0) {
  648. jack_log("Setup AUHAL input");
  649. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
  650. if (err1 != noErr) {
  651. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
  652. printError(err1);
  653. if (strict)
  654. return -1;
  655. }
  656. }
  657. if (playing && outchannels > 0) {
  658. jack_log("Setup AUHAL output");
  659. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
  660. if (err1 != noErr) {
  661. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
  662. printError(err1);
  663. if (strict)
  664. return -1;
  665. }
  666. }
  667. // Setup up choosen device, in both input and output cases
  668. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
  669. if (err1 != noErr) {
  670. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
  671. printError(err1);
  672. if (strict)
  673. return -1;
  674. }
  675. // Set buffer size
  676. if (capturing && inchannels > 0) {
  677. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*) & nframes, sizeof(UInt32));
  678. if (err1 != noErr) {
  679. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  680. printError(err1);
  681. if (strict)
  682. return -1;
  683. }
  684. }
  685. if (playing && outchannels > 0) {
  686. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*) & nframes, sizeof(UInt32));
  687. if (err1 != noErr) {
  688. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  689. printError(err1);
  690. if (strict)
  691. return -1;
  692. }
  693. }
  694. // Setup channel map
  695. if (capturing && inchannels > 0 && inchannels < in_nChannels) {
  696. SInt32 chanArr[in_nChannels];
  697. for (int i = 0; i < in_nChannels; i++) {
  698. chanArr[i] = -1;
  699. }
  700. for (int i = 0; i < inchannels; i++) {
  701. chanArr[i] = i;
  702. }
  703. AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
  704. if (err1 != noErr) {
  705. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 1");
  706. printError(err1);
  707. }
  708. }
  709. if (playing && outchannels > 0 && outchannels < out_nChannels) {
  710. SInt32 chanArr[out_nChannels];
  711. for (int i = 0; i < out_nChannels; i++) {
  712. chanArr[i] = -1;
  713. }
  714. for (int i = 0; i < outchannels; i++) {
  715. chanArr[i] = i;
  716. }
  717. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
  718. if (err1 != noErr) {
  719. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 0");
  720. printError(err1);
  721. }
  722. }
  723. // Setup stream converters
  724. jack_log("Setup AUHAL input stream converter SR = %ld", samplerate);
  725. srcFormat.mSampleRate = samplerate;
  726. srcFormat.mFormatID = kAudioFormatLinearPCM;
  727. srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  728. srcFormat.mBytesPerPacket = sizeof(float);
  729. srcFormat.mFramesPerPacket = 1;
  730. srcFormat.mBytesPerFrame = sizeof(float);
  731. srcFormat.mChannelsPerFrame = outchannels;
  732. srcFormat.mBitsPerChannel = 32;
  733. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &srcFormat, sizeof(AudioStreamBasicDescription));
  734. if (err1 != noErr) {
  735. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  736. printError(err1);
  737. }
  738. jack_log("Setup AUHAL output stream converter SR = %ld", samplerate);
  739. dstFormat.mSampleRate = samplerate;
  740. dstFormat.mFormatID = kAudioFormatLinearPCM;
  741. dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  742. dstFormat.mBytesPerPacket = sizeof(float);
  743. dstFormat.mFramesPerPacket = 1;
  744. dstFormat.mBytesPerFrame = sizeof(float);
  745. dstFormat.mChannelsPerFrame = inchannels;
  746. dstFormat.mBitsPerChannel = 32;
  747. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &dstFormat, sizeof(AudioStreamBasicDescription));
  748. if (err1 != noErr) {
  749. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  750. printError(err1);
  751. }
  752. // Setup callbacks
  753. if (inchannels > 0 && outchannels == 0) {
  754. AURenderCallbackStruct output;
  755. output.inputProc = Render;
  756. output.inputProcRefCon = this;
  757. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
  758. if (err1 != noErr) {
  759. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
  760. printError(err1);
  761. return -1;
  762. }
  763. } else {
  764. AURenderCallbackStruct output;
  765. output.inputProc = Render;
  766. output.inputProcRefCon = this;
  767. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
  768. if (err1 != noErr) {
  769. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
  770. printError(err1);
  771. return -1;
  772. }
  773. }
  774. return 0;
  775. }
  776. void JackCoreAudioAdapter::CloseAUHAL()
  777. {
  778. AudioUnitUninitialize(fAUHAL);
  779. CloseComponent(fAUHAL);
  780. }
  781. int JackCoreAudioAdapter::Open()
  782. {
  783. return (AudioOutputUnitStart(fAUHAL) != noErr) ? -1 : 0;
  784. }
  785. int JackCoreAudioAdapter::Close()
  786. {
  787. #ifdef JACK_MONITOR
  788. fTable.Save();
  789. #endif
  790. AudioOutputUnitStop(fAUHAL);
  791. DisposeBuffers();
  792. CloseAUHAL();
  793. return 0;
  794. }
  795. int JackCoreAudioAdapter::SetSampleRate ( jack_nframes_t sample_rate ) {
  796. JackAudioAdapterInterface::SetHostSampleRate ( sample_rate );
  797. Close();
  798. return Open();
  799. }
  800. int JackCoreAudioAdapter::SetBufferSize ( jack_nframes_t buffer_size ) {
  801. JackAudioAdapterInterface::SetHostBufferSize ( buffer_size );
  802. Close();
  803. return Open();
  804. }
  805. } // namespace
  806. #ifdef __cplusplus
  807. extern "C"
  808. {
  809. #endif
  810. EXPORT jack_driver_desc_t* jack_get_descriptor()
  811. {
  812. jack_driver_desc_t *desc;
  813. unsigned int i;
  814. desc = (jack_driver_desc_t*)calloc(1, sizeof(jack_driver_desc_t));
  815. strcpy(desc->name, "audioadapter"); // size MUST be less then JACK_DRIVER_NAME_MAX + 1
  816. desc->nparams = 10;
  817. desc->params = (jack_driver_param_desc_t*)calloc(desc->nparams, sizeof(jack_driver_param_desc_t));
  818. i = 0;
  819. strcpy(desc->params[i].name, "channels");
  820. desc->params[i].character = 'c';
  821. desc->params[i].type = JackDriverParamInt;
  822. desc->params[i].value.ui = 0;
  823. strcpy(desc->params[i].short_desc, "Maximum number of channels");
  824. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  825. i++;
  826. strcpy(desc->params[i].name, "inchannels");
  827. desc->params[i].character = 'i';
  828. desc->params[i].type = JackDriverParamInt;
  829. desc->params[i].value.ui = 0;
  830. strcpy(desc->params[i].short_desc, "Maximum number of input channels");
  831. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  832. i++;
  833. strcpy(desc->params[i].name, "outchannels");
  834. desc->params[i].character = 'o';
  835. desc->params[i].type = JackDriverParamInt;
  836. desc->params[i].value.ui = 0;
  837. strcpy(desc->params[i].short_desc, "Maximum number of output channels");
  838. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  839. i++;
  840. strcpy(desc->params[i].name, "capture");
  841. desc->params[i].character = 'C';
  842. desc->params[i].type = JackDriverParamString;
  843. strcpy(desc->params[i].value.str, "will take default CoreAudio input device");
  844. strcpy(desc->params[i].short_desc, "Provide capture ports. Optionally set CoreAudio device name");
  845. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  846. i++;
  847. strcpy(desc->params[i].name, "playback");
  848. desc->params[i].character = 'P';
  849. desc->params[i].type = JackDriverParamString;
  850. strcpy(desc->params[i].value.str, "will take default CoreAudio output device");
  851. strcpy(desc->params[i].short_desc, "Provide playback ports. Optionally set CoreAudio device name");
  852. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  853. i++;
  854. strcpy(desc->params[i].name, "rate");
  855. desc->params[i].character = 'r';
  856. desc->params[i].type = JackDriverParamUInt;
  857. desc->params[i].value.ui = 44100U;
  858. strcpy(desc->params[i].short_desc, "Sample rate");
  859. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  860. i++;
  861. strcpy(desc->params[i].name, "periodsize");
  862. desc->params[i].character = 'p';
  863. desc->params[i].type = JackDriverParamUInt;
  864. desc->params[i].value.ui = 512U;
  865. strcpy(desc->params[i].short_desc, "Period size");
  866. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  867. i++;
  868. strcpy(desc->params[i].name, "duplex");
  869. desc->params[i].character = 'D';
  870. desc->params[i].type = JackDriverParamBool;
  871. desc->params[i].value.i = TRUE;
  872. strcpy(desc->params[i].short_desc, "Provide both capture and playback ports");
  873. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  874. i++;
  875. strcpy(desc->params[i].name, "device");
  876. desc->params[i].character = 'd';
  877. desc->params[i].type = JackDriverParamString;
  878. strcpy(desc->params[i].value.str, "will take default CoreAudio device name");
  879. strcpy(desc->params[i].short_desc, "CoreAudio device name");
  880. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  881. i++;
  882. strcpy(desc->params[i].name, "list-devices");
  883. desc->params[i].character = 'l';
  884. desc->params[i].type = JackDriverParamBool;
  885. desc->params[i].value.i = TRUE;
  886. strcpy(desc->params[i].short_desc, "Display available CoreAudio devices");
  887. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  888. return desc;
  889. }
  890. #ifdef __cplusplus
  891. }
  892. #endif