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.

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