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.

1087 lines
39KB

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