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.

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