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.

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