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.

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