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.

1111 lines
40KB

  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_time_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. case 'q':
  323. fQuality = param->value.ui;
  324. break;
  325. case 'g':
  326. fRingbufferSize = param->value.ui;
  327. break;
  328. }
  329. }
  330. /* duplex is the default */
  331. if (!fCapturing && !fPlaying) {
  332. fCapturing = true;
  333. fPlaying = true;
  334. }
  335. int in_nChannels = 0;
  336. int out_nChannels = 0;
  337. if (SetupDevices(fCaptureUID, fPlaybackUID, captureName, playbackName) < 0)
  338. throw -1;
  339. if (SetupChannels(fCapturing, fPlaying, fCaptureChannels, fPlaybackChannels, in_nChannels, out_nChannels, true) < 0)
  340. throw -1;
  341. if (SetupBufferSizeAndSampleRate(fAdaptedBufferSize, fAdaptedSampleRate) < 0)
  342. throw -1;
  343. if (fCapturing && fCaptureChannels > 0)
  344. if (SetupBuffers(fCaptureChannels) < 0)
  345. throw -1;
  346. if (OpenAUHAL(fCapturing, fPlaying, fCaptureChannels, fPlaybackChannels, in_nChannels, out_nChannels, fAdaptedBufferSize, fAdaptedSampleRate, true) < 0)
  347. throw -1;
  348. if (AddListeners() < 0)
  349. throw -1;
  350. }
  351. OSStatus JackCoreAudioAdapter::GetDefaultDevice(AudioDeviceID* id)
  352. {
  353. OSStatus res;
  354. UInt32 theSize = sizeof(UInt32);
  355. AudioDeviceID inDefault;
  356. AudioDeviceID outDefault;
  357. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  358. return res;
  359. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  360. return res;
  361. jack_log("GetDefaultDevice: input = %ld output = %ld", inDefault, outDefault);
  362. // Get the device only if default input and ouput are the same
  363. if (inDefault == outDefault) {
  364. *id = inDefault;
  365. return noErr;
  366. } else {
  367. jack_error("Default input and output devices are not the same !!");
  368. return kAudioHardwareBadDeviceError;
  369. }
  370. }
  371. OSStatus JackCoreAudioAdapter::GetTotalChannels(AudioDeviceID device, int& channelCount, bool isInput)
  372. {
  373. OSStatus err = noErr;
  374. UInt32 outSize;
  375. Boolean outWritable;
  376. AudioBufferList* bufferList = 0;
  377. channelCount = 0;
  378. err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, &outWritable);
  379. if (err == noErr) {
  380. bufferList = (AudioBufferList*)malloc(outSize);
  381. err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, bufferList);
  382. if (err == noErr) {
  383. for (unsigned int i = 0; i < bufferList->mNumberBuffers; i++)
  384. channelCount += bufferList->mBuffers[i].mNumberChannels;
  385. }
  386. if (bufferList)
  387. free(bufferList);
  388. }
  389. return err;
  390. }
  391. OSStatus JackCoreAudioAdapter::GetDeviceIDFromUID(const char* UID, AudioDeviceID* id)
  392. {
  393. UInt32 size = sizeof(AudioValueTranslation);
  394. CFStringRef inIUD = CFStringCreateWithCString(NULL, UID, CFStringGetSystemEncoding());
  395. AudioValueTranslation value = { &inIUD, sizeof(CFStringRef), id, sizeof(AudioDeviceID) };
  396. if (inIUD == NULL) {
  397. return kAudioHardwareUnspecifiedError;
  398. } else {
  399. OSStatus res = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, &size, &value);
  400. CFRelease(inIUD);
  401. jack_log("GetDeviceIDFromUID %s %ld", UID, *id);
  402. return (*id == kAudioDeviceUnknown) ? kAudioHardwareBadDeviceError : res;
  403. }
  404. }
  405. OSStatus JackCoreAudioAdapter::GetDefaultInputDevice(AudioDeviceID* id)
  406. {
  407. OSStatus res;
  408. UInt32 theSize = sizeof(UInt32);
  409. AudioDeviceID inDefault;
  410. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice, &theSize, &inDefault)) != noErr)
  411. return res;
  412. jack_log("GetDefaultInputDevice: input = %ld ", inDefault);
  413. *id = inDefault;
  414. return noErr;
  415. }
  416. OSStatus JackCoreAudioAdapter::GetDefaultOutputDevice(AudioDeviceID* id)
  417. {
  418. OSStatus res;
  419. UInt32 theSize = sizeof(UInt32);
  420. AudioDeviceID outDefault;
  421. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice, &theSize, &outDefault)) != noErr)
  422. return res;
  423. jack_log("GetDefaultOutputDevice: output = %ld", outDefault);
  424. *id = outDefault;
  425. return noErr;
  426. }
  427. OSStatus JackCoreAudioAdapter::GetDeviceNameFromID(AudioDeviceID id, char* name)
  428. {
  429. UInt32 size = 256;
  430. return AudioDeviceGetProperty(id, 0, false, kAudioDevicePropertyDeviceName, &size, name);
  431. }
  432. // Setup
  433. int JackCoreAudioAdapter::SetupDevices(const char* capture_driver_uid,
  434. const char* playback_driver_uid,
  435. char* capture_driver_name,
  436. char* playback_driver_name)
  437. {
  438. capture_driver_name[0] = 0;
  439. playback_driver_name[0] = 0;
  440. // Duplex
  441. if (strcmp(capture_driver_uid, "") != 0 && strcmp(playback_driver_uid, "") != 0) {
  442. jack_log("JackCoreAudioAdapter::Open duplex");
  443. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  444. if (GetDefaultDevice(&fDeviceID) != noErr) {
  445. jack_error("Cannot open default device");
  446. return -1;
  447. }
  448. }
  449. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  450. jack_error("Cannot get device name from device ID");
  451. return -1;
  452. }
  453. // Capture only
  454. } else if (strcmp(capture_driver_uid, "") != 0) {
  455. jack_log("JackCoreAudioAdapter::Open capture only");
  456. if (GetDeviceIDFromUID(capture_driver_uid, &fDeviceID) != noErr) {
  457. if (GetDefaultInputDevice(&fDeviceID) != noErr) {
  458. jack_error("Cannot open default device");
  459. return -1;
  460. }
  461. }
  462. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr) {
  463. jack_error("Cannot get device name from device ID");
  464. return -1;
  465. }
  466. // Playback only
  467. } else if (strcmp(playback_driver_uid, "") != 0) {
  468. jack_log("JackCoreAudioAdapter::Open playback only");
  469. if (GetDeviceIDFromUID(playback_driver_uid, &fDeviceID) != noErr) {
  470. if (GetDefaultOutputDevice(&fDeviceID) != noErr) {
  471. jack_error("Cannot open default device");
  472. return -1;
  473. }
  474. }
  475. if (GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  476. jack_error("Cannot get device name from device ID");
  477. return -1;
  478. }
  479. // Use default driver in duplex mode
  480. } else {
  481. jack_log("JackCoreAudioAdapter::Open default driver");
  482. if (GetDefaultDevice(&fDeviceID) != noErr) {
  483. jack_error("Cannot open default device");
  484. return -1;
  485. }
  486. if (GetDeviceNameFromID(fDeviceID, capture_driver_name) != noErr || GetDeviceNameFromID(fDeviceID, playback_driver_name) != noErr) {
  487. jack_error("Cannot get device name from device ID");
  488. return -1;
  489. }
  490. }
  491. return 0;
  492. }
  493. int JackCoreAudioAdapter::SetupChannels(bool capturing,
  494. bool playing,
  495. int& inchannels,
  496. int& outchannels,
  497. int& in_nChannels,
  498. int& out_nChannels,
  499. bool strict)
  500. {
  501. OSStatus err = noErr;
  502. if (capturing) {
  503. err = GetTotalChannels(fDeviceID, in_nChannels, true);
  504. if (err != noErr) {
  505. jack_error("Cannot get input channel number");
  506. printError(err);
  507. return -1;
  508. } else {
  509. jack_log("Max input channels : %d", in_nChannels);
  510. }
  511. }
  512. if (playing) {
  513. err = GetTotalChannels(fDeviceID, out_nChannels, false);
  514. if (err != noErr) {
  515. jack_error("Cannot get output channel number");
  516. printError(err);
  517. return -1;
  518. } else {
  519. jack_log("Max output channels : %d", out_nChannels);
  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 buffer_size,
  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. if (inchannels == 0 && outchannels == 0) {
  631. jack_error("No input and output channels...");
  632. return -1;
  633. }
  634. // AUHAL
  635. ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
  636. Component HALOutput = FindNextComponent(NULL, &cd);
  637. err1 = OpenAComponent(HALOutput, &fAUHAL);
  638. if (err1 != noErr) {
  639. jack_error("Error calling OpenAComponent");
  640. printError(err1);
  641. return -1;
  642. }
  643. err1 = AudioUnitInitialize(fAUHAL);
  644. if (err1 != noErr) {
  645. jack_error("Cannot initialize AUHAL unit");
  646. printError(err1);
  647. return -1;
  648. }
  649. // Start I/O
  650. if (capturing && inchannels > 0) {
  651. enableIO = 1;
  652. jack_log("Setup AUHAL input on");
  653. } else {
  654. enableIO = 0;
  655. jack_log("Setup AUHAL input off");
  656. }
  657. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
  658. if (err1 != noErr) {
  659. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input");
  660. printError(err1);
  661. if (strict)
  662. return -1;
  663. }
  664. if (playing && outchannels > 0) {
  665. enableIO = 1;
  666. jack_log("Setup AUHAL output on");
  667. } else {
  668. enableIO = 0;
  669. jack_log("Setup AUHAL output off");
  670. }
  671. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
  672. if (err1 != noErr) {
  673. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
  674. printError(err1);
  675. if (strict)
  676. return -1;
  677. }
  678. AudioDeviceID currAudioDeviceID;
  679. UInt32 size = sizeof(AudioDeviceID);
  680. err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
  681. if (err1 != noErr) {
  682. jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
  683. printError(err1);
  684. if (strict)
  685. return -1;
  686. } else {
  687. jack_log("AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
  688. }
  689. // Setup up choosen device, in both input and output cases
  690. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &fDeviceID, sizeof(AudioDeviceID));
  691. if (err1 != noErr) {
  692. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
  693. printError(err1);
  694. if (strict)
  695. return -1;
  696. }
  697. err1 = AudioUnitGetProperty(fAUHAL, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &currAudioDeviceID, &size);
  698. if (err1 != noErr) {
  699. jack_error("Error calling AudioUnitGetProperty - kAudioOutputUnitProperty_CurrentDevice");
  700. printError(err1);
  701. if (strict)
  702. return -1;
  703. } else {
  704. jack_log("AudioUnitGetPropertyCurrentDevice = %d", currAudioDeviceID);
  705. }
  706. // Set buffer size
  707. if (capturing && inchannels > 0) {
  708. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 1, (UInt32*)&buffer_size, sizeof(UInt32));
  709. if (err1 != noErr) {
  710. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  711. printError(err1);
  712. if (strict)
  713. return -1;
  714. }
  715. }
  716. if (playing && outchannels > 0) {
  717. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*)&buffer_size, sizeof(UInt32));
  718. if (err1 != noErr) {
  719. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  720. printError(err1);
  721. if (strict)
  722. return -1;
  723. }
  724. }
  725. // Setup channel map
  726. if (capturing && inchannels > 0 && inchannels < in_nChannels) {
  727. SInt32 chanArr[in_nChannels];
  728. for (int i = 0; i < in_nChannels; i++) {
  729. chanArr[i] = -1;
  730. }
  731. for (int i = 0; i < inchannels; i++) {
  732. chanArr[i] = i;
  733. }
  734. AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
  735. if (err1 != noErr) {
  736. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 1");
  737. printError(err1);
  738. }
  739. }
  740. if (playing && outchannels > 0 && outchannels < out_nChannels) {
  741. SInt32 chanArr[out_nChannels];
  742. for (int i = 0; i < out_nChannels; i++) {
  743. chanArr[i] = -1;
  744. }
  745. for (int i = 0; i < outchannels; i++) {
  746. chanArr[i] = i;
  747. }
  748. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
  749. if (err1 != noErr) {
  750. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 0");
  751. printError(err1);
  752. }
  753. }
  754. // Setup stream converters
  755. jack_log("Setup AUHAL input stream converter SR = %ld", samplerate);
  756. srcFormat.mSampleRate = samplerate;
  757. srcFormat.mFormatID = kAudioFormatLinearPCM;
  758. srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  759. srcFormat.mBytesPerPacket = sizeof(float);
  760. srcFormat.mFramesPerPacket = 1;
  761. srcFormat.mBytesPerFrame = sizeof(float);
  762. srcFormat.mChannelsPerFrame = outchannels;
  763. srcFormat.mBitsPerChannel = 32;
  764. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &srcFormat, sizeof(AudioStreamBasicDescription));
  765. if (err1 != noErr) {
  766. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  767. printError(err1);
  768. }
  769. jack_log("Setup AUHAL output stream converter SR = %ld", samplerate);
  770. dstFormat.mSampleRate = samplerate;
  771. dstFormat.mFormatID = kAudioFormatLinearPCM;
  772. dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  773. dstFormat.mBytesPerPacket = sizeof(float);
  774. dstFormat.mFramesPerPacket = 1;
  775. dstFormat.mBytesPerFrame = sizeof(float);
  776. dstFormat.mChannelsPerFrame = inchannels;
  777. dstFormat.mBitsPerChannel = 32;
  778. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &dstFormat, sizeof(AudioStreamBasicDescription));
  779. if (err1 != noErr) {
  780. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  781. printError(err1);
  782. }
  783. // Setup callbacks
  784. if (inchannels > 0 && outchannels == 0) {
  785. AURenderCallbackStruct output;
  786. output.inputProc = Render;
  787. output.inputProcRefCon = this;
  788. err1 = AudioUnitSetProperty(fAUHAL, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &output, sizeof(output));
  789. if (err1 != noErr) {
  790. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 1");
  791. printError(err1);
  792. return -1;
  793. }
  794. } else {
  795. AURenderCallbackStruct output;
  796. output.inputProc = Render;
  797. output.inputProcRefCon = this;
  798. err1 = AudioUnitSetProperty(fAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
  799. if (err1 != noErr) {
  800. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_SetRenderCallback 0");
  801. printError(err1);
  802. return -1;
  803. }
  804. }
  805. return 0;
  806. }
  807. void JackCoreAudioAdapter::CloseAUHAL()
  808. {
  809. AudioUnitUninitialize(fAUHAL);
  810. CloseComponent(fAUHAL);
  811. }
  812. int JackCoreAudioAdapter::Open()
  813. {
  814. return (AudioOutputUnitStart(fAUHAL) != noErr) ? -1 : 0;
  815. }
  816. int JackCoreAudioAdapter::Close()
  817. {
  818. #ifdef JACK_MONITOR
  819. fTable.Save();
  820. #endif
  821. AudioOutputUnitStop(fAUHAL);
  822. DisposeBuffers();
  823. CloseAUHAL();
  824. RemoveListeners();
  825. return 0;
  826. }
  827. int JackCoreAudioAdapter::SetSampleRate ( jack_nframes_t sample_rate ) {
  828. JackAudioAdapterInterface::SetHostSampleRate ( sample_rate );
  829. Close();
  830. return Open();
  831. }
  832. int JackCoreAudioAdapter::SetBufferSize ( jack_nframes_t buffer_size ) {
  833. JackAudioAdapterInterface::SetHostBufferSize ( buffer_size );
  834. Close();
  835. return Open();
  836. }
  837. } // namespace
  838. #ifdef __cplusplus
  839. extern "C"
  840. {
  841. #endif
  842. SERVER_EXPORT jack_driver_desc_t* jack_get_descriptor()
  843. {
  844. jack_driver_desc_t *desc;
  845. unsigned int i;
  846. desc = (jack_driver_desc_t*)calloc(1, sizeof(jack_driver_desc_t));
  847. strcpy(desc->name, "audioadapter"); // size MUST be less then JACK_DRIVER_NAME_MAX + 1
  848. strcpy(desc->desc, "netjack audio <==> net backend adapter"); // size MUST be less then JACK_DRIVER_PARAM_DESC + 1
  849. desc->nparams = 12;
  850. desc->params = (jack_driver_param_desc_t*)calloc(desc->nparams, sizeof(jack_driver_param_desc_t));
  851. i = 0;
  852. strcpy(desc->params[i].name, "channels");
  853. desc->params[i].character = 'c';
  854. desc->params[i].type = JackDriverParamInt;
  855. desc->params[i].value.ui = 0;
  856. strcpy(desc->params[i].short_desc, "Maximum number of channels");
  857. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  858. i++;
  859. strcpy(desc->params[i].name, "inchannels");
  860. desc->params[i].character = 'i';
  861. desc->params[i].type = JackDriverParamInt;
  862. desc->params[i].value.ui = 0;
  863. strcpy(desc->params[i].short_desc, "Maximum number of input channels");
  864. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  865. i++;
  866. strcpy(desc->params[i].name, "outchannels");
  867. desc->params[i].character = 'o';
  868. desc->params[i].type = JackDriverParamInt;
  869. desc->params[i].value.ui = 0;
  870. strcpy(desc->params[i].short_desc, "Maximum number of output channels");
  871. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  872. i++;
  873. strcpy(desc->params[i].name, "capture");
  874. desc->params[i].character = 'C';
  875. desc->params[i].type = JackDriverParamString;
  876. strcpy(desc->params[i].value.str, "will take default CoreAudio input device");
  877. strcpy(desc->params[i].short_desc, "Provide capture ports. Optionally set CoreAudio device name");
  878. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  879. i++;
  880. strcpy(desc->params[i].name, "playback");
  881. desc->params[i].character = 'P';
  882. desc->params[i].type = JackDriverParamString;
  883. strcpy(desc->params[i].value.str, "will take default CoreAudio output device");
  884. strcpy(desc->params[i].short_desc, "Provide playback ports. Optionally set CoreAudio device name");
  885. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  886. i++;
  887. strcpy(desc->params[i].name, "rate");
  888. desc->params[i].character = 'r';
  889. desc->params[i].type = JackDriverParamUInt;
  890. desc->params[i].value.ui = 44100U;
  891. strcpy(desc->params[i].short_desc, "Sample rate");
  892. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  893. i++;
  894. strcpy(desc->params[i].name, "periodsize");
  895. desc->params[i].character = 'p';
  896. desc->params[i].type = JackDriverParamUInt;
  897. desc->params[i].value.ui = 512U;
  898. strcpy(desc->params[i].short_desc, "Period size");
  899. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  900. i++;
  901. strcpy(desc->params[i].name, "duplex");
  902. desc->params[i].character = 'D';
  903. desc->params[i].type = JackDriverParamBool;
  904. desc->params[i].value.i = TRUE;
  905. strcpy(desc->params[i].short_desc, "Provide both capture and playback ports");
  906. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  907. i++;
  908. strcpy(desc->params[i].name, "device");
  909. desc->params[i].character = 'd';
  910. desc->params[i].type = JackDriverParamString;
  911. strcpy(desc->params[i].value.str, "will take default CoreAudio device name");
  912. strcpy(desc->params[i].short_desc, "CoreAudio device name");
  913. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  914. i++;
  915. strcpy(desc->params[i].name, "list-devices");
  916. desc->params[i].character = 'l';
  917. desc->params[i].type = JackDriverParamBool;
  918. desc->params[i].value.i = TRUE;
  919. strcpy(desc->params[i].short_desc, "Display available CoreAudio devices");
  920. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  921. i++;
  922. strcpy(desc->params[i].name, "quality");
  923. desc->params[i].character = 'q';
  924. desc->params[i].type = JackDriverParamInt;
  925. desc->params[i].value.ui = 0;
  926. strcpy(desc->params[i].short_desc, "Resample algorithm quality (0 - 4)");
  927. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  928. i++;
  929. strcpy(desc->params[i].name, "ring-buffer");
  930. desc->params[i].character = 'g';
  931. desc->params[i].type = JackDriverParamInt;
  932. desc->params[i].value.ui = 0;
  933. strcpy(desc->params[i].short_desc, "Resampling ringbuffer size in frames (default = 32768)");
  934. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  935. return desc;
  936. }
  937. #ifdef __cplusplus
  938. }
  939. #endif