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.

1047 lines
38KB

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