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.

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