jack1 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.

1124 lines
38KB

  1. /*
  2. Copyright � Grame, 2003.
  3. Copyright � Johnny Petrantoni, 2003.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. Grame Research Laboratory, 9, rue du Garet 69001 Lyon - France
  16. grame@rd.grame.fr
  17. Johnny Petrantoni, johnny@lato-b.com - Italy, Rome.
  18. Jan 30, 2004: Johnny Petrantoni: first code of the coreaudio driver, based on portaudio driver by Stephane Letz.
  19. Feb 02, 2004: Johnny Petrantoni: fixed null cycle, removed double copy of buffers in AudioRender, the driver works fine (tested with Built-in Audio and Hammerfall RME), but no cpu load is displayed.
  20. Feb 03, 2004: Johnny Petrantoni: some little fix.
  21. Feb 03, 2004: Stephane Letz: some fix in AudioRender.cpp code.
  22. Feb 03, 2004: Johnny Petrantoni: removed the default device stuff (useless, in jackosx, because JackPilot manages this behavior), the device must be specified. and all parameter must be correct.
  23. Feb 04, 2004: Johnny Petrantoni: now the driver supports interfaces with multiple interleaved streams (such as the MOTU 828).
  24. Nov 05, 2004: S.Letz: correct management of -I option for use with JackPilot.
  25. Nov 15, 2004: S.Letz: Set a default value for deviceID.
  26. Nov 30, 2004: S.Letz: In coreaudio_driver_write : clear to avoid playing dirty buffers when the client does not produce output anymore.
  27. Dec 05, 2004: S.Letz: XRun detection
  28. Dec 09, 2004: S.Letz: Dynamic buffer size change
  29. Dec 23, 2004: S.Letz: Correct bug in dynamic buffer size change : update period_usecs
  30. Jan 20, 2005: S.Letz: Almost complete rewrite using AUHAL.
  31. May 20, 2005: S.Letz: Add "systemic" latencies management.
  32. Jun 06, 2005: S.Letz: Remove the "-I" parameter, change the semantic of "-n" parameter : -n (driver name) now correctly uses the PropertyDeviceUID
  33. (persistent accross reboot...) as the identifier for the used coreaudio driver.
  34. Jun 14, 2005: S.Letz: Since the "-I" parameter is not used anymore, rename the "systemic" latencies management parametes "-I" and "-O" like for the ALSA driver.
  35. Aug 16, 2005: S.Letz: Remove get_device_id_from_num, use get_default_device instead. If the -n option is not used or the device name cannot
  36. be found, the default device is used. Note: the default device can be used only if both default input and default output are the same.
  37. Dec 19, 2005: S.Letz: Add -d option (display_device_names).
  38. Apri 7, 2006: S.Letz: Synchronization with the jackdmp coreaudio driver version: improve half-duplex management.
  39. May 17, 2006: S.Letz: Minor fix in driver_initialize.
  40. May 18, 2006: S.Letz: Document sample rate default value.
  41. May 31, 2006: S.Letz: Apply Rui patch for more consistent driver parameter naming.
  42. Dec 04, 2007: S.Letz: Fix a bug in sample rate management (occuring in particular with "aggregate" devices).
  43. */
  44. #include <stdio.h>
  45. #include <string.h>
  46. #include <jack/engine.h>
  47. #include "coreaudio_driver.h"
  48. const int CAVersion = 3;
  49. //#define PRINTDEBUG 1
  50. static void JCALog(char *fmt, ...)
  51. {
  52. #ifdef PRINTDEBUG
  53. va_list ap;
  54. va_start(ap, fmt);
  55. fprintf(stderr, "JCA: ");
  56. vfprintf(stderr, fmt, ap);
  57. va_end(ap);
  58. #endif
  59. }
  60. static void printError(OSStatus err)
  61. {
  62. #ifdef DEBUG
  63. switch (err) {
  64. case kAudioHardwareNoError:
  65. JCALog("error code : kAudioHardwareNoError\n");
  66. break;
  67. case kAudioHardwareNotRunningError:
  68. JCALog("error code : kAudioHardwareNotRunningError\n");
  69. break;
  70. case kAudioHardwareUnspecifiedError:
  71. JCALog("error code : kAudioHardwareUnspecifiedError\n");
  72. break;
  73. case kAudioHardwareUnknownPropertyError:
  74. JCALog("error code : kAudioHardwareUnknownPropertyError\n");
  75. break;
  76. case kAudioHardwareBadPropertySizeError:
  77. JCALog("error code : kAudioHardwareBadPropertySizeError\n");
  78. break;
  79. case kAudioHardwareIllegalOperationError:
  80. JCALog("error code : kAudioHardwareIllegalOperationError\n");
  81. break;
  82. case kAudioHardwareBadDeviceError:
  83. JCALog("error code : kAudioHardwareBadDeviceError\n");
  84. break;
  85. case kAudioHardwareBadStreamError:
  86. JCALog("error code : kAudioHardwareBadStreamError\n");
  87. break;
  88. case kAudioDeviceUnsupportedFormatError:
  89. JCALog("error code : kAudioDeviceUnsupportedFormatError\n");
  90. break;
  91. case kAudioDevicePermissionsError:
  92. JCALog("error code : kAudioDevicePermissionsError\n");
  93. break;
  94. default:
  95. JCALog("error code : unknown %ld\n", err);
  96. break;
  97. }
  98. #endif
  99. }
  100. static OSStatus get_device_name_from_id(AudioDeviceID id, char name[256])
  101. {
  102. UInt32 size = sizeof(char) * 256;
  103. OSStatus res = AudioDeviceGetProperty(id, 0, false,
  104. kAudioDevicePropertyDeviceName,
  105. &size,
  106. &name[0]);
  107. return res;
  108. }
  109. static OSStatus get_device_id_from_uid(char* UID, AudioDeviceID* id)
  110. {
  111. UInt32 size = sizeof(AudioValueTranslation);
  112. CFStringRef inIUD = CFStringCreateWithCString(NULL, UID, CFStringGetSystemEncoding());
  113. AudioValueTranslation value = { &inIUD, sizeof(CFStringRef), id, sizeof(AudioDeviceID) };
  114. if (inIUD == NULL) {
  115. return kAudioHardwareUnspecifiedError;
  116. } else {
  117. OSStatus res = AudioHardwareGetProperty(kAudioHardwarePropertyDeviceForUID, &size, &value);
  118. CFRelease(inIUD);
  119. JCALog("get_device_id_from_uid %s %ld \n", UID, *id);
  120. return (*id == kAudioDeviceUnknown) ? kAudioHardwareBadDeviceError : res;
  121. }
  122. }
  123. static OSStatus get_default_device(AudioDeviceID * id)
  124. {
  125. OSStatus res;
  126. UInt32 theSize = sizeof(UInt32);
  127. AudioDeviceID inDefault;
  128. AudioDeviceID outDefault;
  129. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice,
  130. &theSize, &inDefault)) != noErr)
  131. return res;
  132. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
  133. &theSize, &outDefault)) != noErr)
  134. return res;
  135. JCALog("get_default_device: input %ld output %ld\n", inDefault, outDefault);
  136. // Get the device only if default input and ouput are the same
  137. if (inDefault == outDefault) {
  138. *id = inDefault;
  139. return noErr;
  140. } else {
  141. jack_error("Default input and output devices are not the same !!");
  142. return kAudioHardwareBadDeviceError;
  143. }
  144. }
  145. static OSStatus get_default_input_device(AudioDeviceID* id)
  146. {
  147. OSStatus res;
  148. UInt32 theSize = sizeof(UInt32);
  149. AudioDeviceID inDefault;
  150. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultInputDevice,
  151. &theSize, &inDefault)) != noErr)
  152. return res;
  153. JCALog("get_default_input_device: input = %ld \n", inDefault);
  154. *id = inDefault;
  155. return noErr;
  156. }
  157. static OSStatus get_default_output_device(AudioDeviceID* id)
  158. {
  159. OSStatus res;
  160. UInt32 theSize = sizeof(UInt32);
  161. AudioDeviceID outDefault;
  162. if ((res = AudioHardwareGetProperty(kAudioHardwarePropertyDefaultOutputDevice,
  163. &theSize, &outDefault)) != noErr)
  164. return res;
  165. JCALog("get_default_output_device: output = %ld\n", outDefault);
  166. *id = outDefault;
  167. return noErr;
  168. }
  169. OSStatus get_total_channels(AudioDeviceID device, int* channelCount, bool isInput)
  170. {
  171. OSStatus err = noErr;
  172. UInt32 outSize;
  173. Boolean outWritable;
  174. AudioBufferList* bufferList = 0;
  175. AudioStreamID* streamList = 0;
  176. int i, numStream;
  177. err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreams, &outSize, &outWritable);
  178. if (err == noErr) {
  179. streamList = (AudioStreamID*)malloc(outSize);
  180. numStream = outSize/sizeof(AudioStreamID);
  181. JCALog("get_total_channels device stream number = %ld numStream = %ld\n", device, numStream);
  182. err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreams, &outSize, streamList);
  183. if (err == noErr) {
  184. AudioStreamBasicDescription streamDesc;
  185. outSize = sizeof(AudioStreamBasicDescription);
  186. for (i = 0; i < numStream; i++) {
  187. err = AudioStreamGetProperty(streamList[i], 0, kAudioDevicePropertyStreamFormat, &outSize, &streamDesc);
  188. JCALog("get_total_channels streamDesc mFormatFlags = %ld mChannelsPerFrame = %ld\n", streamDesc.mFormatFlags, streamDesc.mChannelsPerFrame);
  189. }
  190. }
  191. }
  192. *channelCount = 0;
  193. err = AudioDeviceGetPropertyInfo(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, &outWritable);
  194. if (err == noErr) {
  195. bufferList = (AudioBufferList*)malloc(outSize);
  196. err = AudioDeviceGetProperty(device, 0, isInput, kAudioDevicePropertyStreamConfiguration, &outSize, bufferList);
  197. if (err == noErr) {
  198. for (i = 0; i < bufferList->mNumberBuffers; i++)
  199. *channelCount += bufferList->mBuffers[i].mNumberChannels;
  200. }
  201. }
  202. if (streamList)
  203. free(streamList);
  204. if (bufferList)
  205. free(bufferList);
  206. return err;
  207. }
  208. static OSStatus display_device_names()
  209. {
  210. UInt32 size;
  211. Boolean isWritable;
  212. int i, deviceNum;
  213. OSStatus err;
  214. CFStringRef UIname;
  215. err = AudioHardwareGetPropertyInfo(kAudioHardwarePropertyDevices, &size, &isWritable);
  216. if (err != noErr)
  217. return err;
  218. deviceNum = size/sizeof(AudioDeviceID);
  219. AudioDeviceID devices[deviceNum];
  220. err = AudioHardwareGetProperty(kAudioHardwarePropertyDevices, &size, devices);
  221. if (err != noErr)
  222. return err;
  223. for (i = 0; i < deviceNum; i++) {
  224. char device_name[256];
  225. char internal_name[256];
  226. size = sizeof(CFStringRef);
  227. UIname = NULL;
  228. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceUID, &size, &UIname);
  229. if (err == noErr) {
  230. CFStringGetCString(UIname, internal_name, 256, CFStringGetSystemEncoding());
  231. } else {
  232. goto error;
  233. }
  234. size = 256;
  235. err = AudioDeviceGetProperty(devices[i], 0, false, kAudioDevicePropertyDeviceName, &size, device_name);
  236. if (err != noErr)
  237. return err;
  238. printf("ICI\n");
  239. printf("Device name = \'%s\', internal_name = \'%s\' (to be used as -d parameter)\n", device_name, internal_name);
  240. }
  241. return noErr;
  242. error:
  243. if (UIname != NULL)
  244. CFRelease(UIname);
  245. return err;
  246. }
  247. static OSStatus render(void *inRefCon,
  248. AudioUnitRenderActionFlags *ioActionFlags,
  249. const AudioTimeStamp *inTimeStamp,
  250. UInt32 inBusNumber,
  251. UInt32 inNumberFrames,
  252. AudioBufferList *ioData)
  253. {
  254. int res, i;
  255. JSList *node;
  256. coreaudio_driver_t* ca_driver = (coreaudio_driver_t*)inRefCon;
  257. AudioUnitRender(ca_driver->au_hal, ioActionFlags, inTimeStamp, 1, inNumberFrames, ca_driver->input_list);
  258. if (ca_driver->xrun_detected > 0) { /* XRun was detected */
  259. jack_time_t current_time = jack_get_microseconds();
  260. ca_driver->engine->delay(ca_driver->engine, current_time -
  261. (ca_driver->last_wait_ust + ca_driver->period_usecs));
  262. ca_driver->last_wait_ust = current_time;
  263. ca_driver->xrun_detected = 0;
  264. return 0;
  265. } else {
  266. ca_driver->last_wait_ust = jack_get_microseconds();
  267. ca_driver->engine->transport_cycle_start(ca_driver->engine,
  268. jack_get_microseconds());
  269. res = ca_driver->engine->run_cycle(ca_driver->engine, inNumberFrames, 0);
  270. }
  271. if (ca_driver->null_cycle_occured) {
  272. ca_driver->null_cycle_occured = 0;
  273. for (i = 0; i < ca_driver->playback_nchannels; i++) {
  274. memset((float*)ioData->mBuffers[i].mData, 0, sizeof(float) * inNumberFrames);
  275. }
  276. } else {
  277. for (i = 0, node = ca_driver->playback_ports; i < ca_driver->playback_nchannels; i++, node = jack_slist_next(node)) {
  278. memcpy((float*)ioData->mBuffers[i].mData,
  279. (jack_default_audio_sample_t*)jack_port_get_buffer(((jack_port_t *) node->data), inNumberFrames),
  280. sizeof(float) * inNumberFrames);
  281. }
  282. }
  283. return res;
  284. }
  285. static OSStatus render_input(void *inRefCon,
  286. AudioUnitRenderActionFlags *ioActionFlags,
  287. const AudioTimeStamp *inTimeStamp,
  288. UInt32 inBusNumber,
  289. UInt32 inNumberFrames,
  290. AudioBufferList *ioData)
  291. {
  292. coreaudio_driver_t* ca_driver = (coreaudio_driver_t*)inRefCon;
  293. AudioUnitRender(ca_driver->au_hal, ioActionFlags, inTimeStamp, 1, inNumberFrames, ca_driver->input_list);
  294. if (ca_driver->xrun_detected > 0) { /* XRun was detected */
  295. jack_time_t current_time = jack_get_microseconds();
  296. ca_driver->engine->delay(ca_driver->engine, current_time -
  297. (ca_driver->last_wait_ust + ca_driver->period_usecs));
  298. ca_driver->last_wait_ust = current_time;
  299. ca_driver->xrun_detected = 0;
  300. return 0;
  301. } else {
  302. ca_driver->last_wait_ust = jack_get_microseconds();
  303. ca_driver->engine->transport_cycle_start(ca_driver->engine,
  304. jack_get_microseconds());
  305. return ca_driver->engine->run_cycle(ca_driver->engine, inNumberFrames, 0);
  306. }
  307. }
  308. static OSStatus notification(AudioDeviceID inDevice,
  309. UInt32 inChannel,
  310. Boolean isInput,
  311. AudioDevicePropertyID inPropertyID,
  312. void* inClientData)
  313. {
  314. coreaudio_driver_t* ca_driver = (coreaudio_driver_t*)inClientData;
  315. if (inPropertyID == kAudioDeviceProcessorOverload) {
  316. ca_driver->xrun_detected = 1;
  317. }
  318. return noErr;
  319. }
  320. static int
  321. coreaudio_driver_attach(coreaudio_driver_t * driver, jack_engine_t * engine)
  322. {
  323. jack_port_t *port;
  324. JSList *node;
  325. int port_flags;
  326. channel_t chn;
  327. char buf[JACK_PORT_NAME_SIZE];
  328. char channel_name[64];
  329. OSStatus err;
  330. UInt32 size;
  331. UInt32 value1,value2;
  332. Boolean isWritable;
  333. driver->engine = engine;
  334. driver->engine->set_buffer_size(engine, driver->frames_per_cycle);
  335. driver->engine->set_sample_rate(engine, driver->frame_rate);
  336. port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
  337. /*
  338. if (driver->has_hw_monitoring) {
  339. port_flags |= JackPortCanMonitor;
  340. }
  341. */
  342. for (chn = 0; chn < driver->capture_nchannels; chn++) {
  343. err = AudioDeviceGetPropertyInfo(driver->device_id, chn + 1, true, kAudioDevicePropertyChannelName, &size, &isWritable);
  344. if (err == noErr && size > 0) {
  345. err = AudioDeviceGetProperty(driver->device_id, chn + 1, true, kAudioDevicePropertyChannelName, &size, channel_name);
  346. if (err != noErr)
  347. JCALog("AudioDeviceGetProperty kAudioDevicePropertyChannelName error \n");
  348. snprintf(buf, sizeof(buf) - 1, "%s:out_%s%lu", driver->capture_driver_name, channel_name, chn + 1);
  349. } else {
  350. snprintf(buf, sizeof(buf) - 1, "%s:out%lu", driver->capture_driver_name, chn + 1);
  351. }
  352. if ((port = jack_port_register(driver->client, buf,
  353. JACK_DEFAULT_AUDIO_TYPE, port_flags,
  354. 0)) == NULL) {
  355. jack_error("coreaudio: cannot register port for %s", buf);
  356. break;
  357. }
  358. size = sizeof(UInt32);
  359. value1 = value2 = 0;
  360. err = AudioDeviceGetProperty(driver->device_id, 0, true, kAudioDevicePropertyLatency, &size, &value1);
  361. if (err != noErr)
  362. JCALog("AudioDeviceGetProperty kAudioDevicePropertyLatency error \n");
  363. err = AudioDeviceGetProperty(driver->device_id, 0, true, kAudioDevicePropertySafetyOffset, &size, &value2);
  364. if (err != noErr)
  365. JCALog("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error \n");
  366. jack_port_set_latency(port, driver->frames_per_cycle + value1 + value2 + driver->capture_frame_latency);
  367. driver->capture_ports =
  368. jack_slist_append(driver->capture_ports, port);
  369. }
  370. port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
  371. for (chn = 0; chn < driver->playback_nchannels; chn++) {
  372. err = AudioDeviceGetPropertyInfo(driver->device_id, chn + 1, false, kAudioDevicePropertyChannelName, &size, &isWritable);
  373. if (err == noErr && size > 0) {
  374. err = AudioDeviceGetProperty(driver->device_id, chn + 1, false, kAudioDevicePropertyChannelName, &size, channel_name);
  375. if (err != noErr)
  376. JCALog("AudioDeviceGetProperty kAudioDevicePropertyChannelName error \n");
  377. snprintf(buf, sizeof(buf) - 1, "%s:in_%s%lu", driver->playback_driver_name, channel_name, chn + 1);
  378. } else {
  379. snprintf(buf, sizeof(buf) - 1, "%s:in%lu", driver->playback_driver_name, chn + 1);
  380. }
  381. if ((port = jack_port_register(driver->client, buf,
  382. JACK_DEFAULT_AUDIO_TYPE, port_flags,
  383. 0)) == NULL) {
  384. jack_error("coreaudio: cannot register port for %s", buf);
  385. break;
  386. }
  387. size = sizeof(UInt32);
  388. value1 = value2 = 0;
  389. err = AudioDeviceGetProperty(driver->device_id, 0, false, kAudioDevicePropertyLatency, &size, &value1);
  390. if (err != noErr)
  391. JCALog("AudioDeviceGetProperty kAudioDevicePropertyLatency error \n");
  392. err = AudioDeviceGetProperty(driver->device_id, 0, false, kAudioDevicePropertySafetyOffset, &size, &value2);
  393. if (err != noErr)
  394. JCALog("AudioDeviceGetProperty kAudioDevicePropertySafetyOffset error \n");
  395. jack_port_set_latency(port, driver->frames_per_cycle + value1 + value2 + driver->playback_frame_latency);
  396. driver->playback_ports =
  397. jack_slist_append(driver->playback_ports, port);
  398. }
  399. // Input buffers do no change : prepare them only once
  400. for (chn = 0, node = driver->capture_ports; chn < driver->capture_nchannels; chn++, node = jack_slist_next(node)) {
  401. driver->input_list->mBuffers[chn].mData
  402. = (jack_default_audio_sample_t*)jack_port_get_buffer(((jack_port_t *) node->data), driver->frames_per_cycle);
  403. }
  404. jack_activate(driver->client);
  405. return 0;
  406. }
  407. static int
  408. coreaudio_driver_detach(coreaudio_driver_t * driver, jack_engine_t * engine)
  409. {
  410. JSList *node;
  411. if (driver->engine == 0) {
  412. return -1;
  413. }
  414. for (node = driver->capture_ports; node; node = jack_slist_next(node)) {
  415. jack_port_unregister(driver->client, ((jack_port_t *) node->data));
  416. }
  417. jack_slist_free(driver->capture_ports);
  418. driver->capture_ports = 0;
  419. for (node = driver->playback_ports; node; node = jack_slist_next(node)) {
  420. jack_port_unregister(driver->client, ((jack_port_t *) node->data));
  421. }
  422. jack_slist_free(driver->playback_ports);
  423. driver->playback_ports = 0;
  424. driver->engine = 0;
  425. return 0;
  426. }
  427. static int
  428. coreaudio_driver_null_cycle(coreaudio_driver_t * driver, jack_nframes_t nframes)
  429. {
  430. driver->null_cycle_occured = 1;
  431. return 0;
  432. }
  433. static int
  434. coreaudio_driver_read(coreaudio_driver_t * driver, jack_nframes_t nframes)
  435. {
  436. return 0;
  437. }
  438. static int
  439. coreaudio_driver_write(coreaudio_driver_t * driver, jack_nframes_t nframes)
  440. {
  441. return 0;
  442. }
  443. static int coreaudio_driver_audio_start(coreaudio_driver_t * driver)
  444. {
  445. return (AudioOutputUnitStart(driver->au_hal) == noErr) ? 0 : -1;
  446. }
  447. static int coreaudio_driver_audio_stop(coreaudio_driver_t * driver)
  448. {
  449. return (AudioOutputUnitStop(driver->au_hal) == noErr) ? 0 : -1;
  450. }
  451. static int
  452. coreaudio_driver_bufsize(coreaudio_driver_t * driver,
  453. jack_nframes_t nframes)
  454. {
  455. /* This gets called from the engine server thread, so it must
  456. * be serialized with the driver thread. Stopping the audio
  457. * also stops that thread. */
  458. /*
  459. TO DO
  460. */
  461. return 0;
  462. }
  463. /** create a new driver instance
  464. */
  465. static jack_driver_t *coreaudio_driver_new(char* name,
  466. jack_client_t* client,
  467. jack_nframes_t nframes,
  468. jack_nframes_t samplerate,
  469. int capturing,
  470. int playing,
  471. int inchannels,
  472. int outchannels,
  473. char* capture_driver_uid,
  474. char* playback_driver_uid,
  475. jack_nframes_t capture_latency,
  476. jack_nframes_t playback_latency)
  477. {
  478. coreaudio_driver_t *driver;
  479. OSStatus err = noErr;
  480. ComponentResult err1;
  481. UInt32 outSize;
  482. UInt32 enableIO;
  483. AudioStreamBasicDescription srcFormat, dstFormat;
  484. Float64 sampleRate;
  485. int in_nChannels = 0;
  486. int out_nChannels = 0;
  487. int i;
  488. driver = (coreaudio_driver_t *) calloc(1, sizeof(coreaudio_driver_t));
  489. jack_driver_init((jack_driver_t *) driver);
  490. if (!jack_power_of_two(nframes)) {
  491. fprintf(stderr, "CA: -p must be a power of two.\n");
  492. goto error;
  493. }
  494. driver->frames_per_cycle = nframes;
  495. driver->frame_rate = samplerate;
  496. driver->capturing = capturing;
  497. driver->playing = playing;
  498. driver->xrun_detected = 0;
  499. driver->null_cycle = 0;
  500. driver->attach = (JackDriverAttachFunction) coreaudio_driver_attach;
  501. driver->detach = (JackDriverDetachFunction) coreaudio_driver_detach;
  502. driver->read = (JackDriverReadFunction) coreaudio_driver_read;
  503. driver->write = (JackDriverReadFunction) coreaudio_driver_write;
  504. driver->null_cycle =
  505. (JackDriverNullCycleFunction) coreaudio_driver_null_cycle;
  506. driver->bufsize = (JackDriverBufSizeFunction) coreaudio_driver_bufsize;
  507. driver->start = (JackDriverStartFunction) coreaudio_driver_audio_start;
  508. driver->stop = (JackDriverStopFunction) coreaudio_driver_audio_stop;
  509. driver->capture_frame_latency = capture_latency;
  510. driver->playback_frame_latency = playback_latency;
  511. // Duplex
  512. if (capture_driver_uid != NULL && playback_driver_uid != NULL) {
  513. JCALog("Open duplex \n");
  514. if (get_device_id_from_uid(playback_driver_uid, &driver->device_id) != noErr) {
  515. if (get_default_device(&driver->device_id) != noErr) {
  516. jack_error("Cannot open default device");
  517. goto error;
  518. }
  519. }
  520. if (get_device_name_from_id(driver->device_id, driver->capture_driver_name) != noErr || get_device_name_from_id(driver->device_id, driver->playback_driver_name) != noErr) {
  521. jack_error("Cannot get device name from device ID");
  522. goto error;
  523. }
  524. // Capture only
  525. } else if (capture_driver_uid != NULL) {
  526. JCALog("Open capture only \n");
  527. if (get_device_id_from_uid(capture_driver_uid, &driver->device_id) != noErr) {
  528. if (get_default_input_device(&driver->device_id) != noErr) {
  529. jack_error("Cannot open default device");
  530. goto error;
  531. }
  532. }
  533. if (get_device_name_from_id(driver->device_id, driver->capture_driver_name) != noErr) {
  534. jack_error("Cannot get device name from device ID");
  535. goto error;
  536. }
  537. // Playback only
  538. } else if (playback_driver_uid != NULL) {
  539. JCALog("Open playback only \n");
  540. if (get_device_id_from_uid(playback_driver_uid, &driver->device_id) != noErr) {
  541. if (get_default_output_device(&driver->device_id) != noErr) {
  542. jack_error("Cannot open default device");
  543. goto error;
  544. }
  545. }
  546. if (get_device_name_from_id(driver->device_id, driver->playback_driver_name) != noErr) {
  547. jack_error("Cannot get device name from device ID");
  548. goto error;
  549. }
  550. // Use default driver in duplex mode
  551. } else {
  552. JCALog("Open default driver \n");
  553. if (get_default_device(&driver->device_id) != noErr) {
  554. jack_error("Cannot open default device");
  555. goto error;
  556. }
  557. if (get_device_name_from_id(driver->device_id, driver->capture_driver_name) != noErr || get_device_name_from_id(driver->device_id, driver->playback_driver_name) != noErr) {
  558. jack_error("Cannot get device name from device ID");
  559. goto error;
  560. }
  561. }
  562. driver->client = client;
  563. driver->period_usecs =
  564. (((float) driver->frames_per_cycle) / driver->frame_rate) *
  565. 1000000.0f;
  566. if (capturing) {
  567. err = get_total_channels(driver->device_id, &in_nChannels, true);
  568. if (err != noErr) {
  569. jack_error("Cannot get input channel number");
  570. printError(err);
  571. goto error;
  572. }
  573. }
  574. if (playing) {
  575. err = get_total_channels(driver->device_id, &out_nChannels, false);
  576. if (err != noErr) {
  577. jack_error("Cannot get output channel number");
  578. printError(err);
  579. goto error;
  580. }
  581. }
  582. if (inchannels > in_nChannels) {
  583. jack_error("This device hasn't required input channels inchannels = %ld in_nChannels = %ld", inchannels, in_nChannels);
  584. goto error;
  585. }
  586. if (outchannels > out_nChannels) {
  587. jack_error("This device hasn't required output channels outchannels = %ld out_nChannels = %ld", outchannels, out_nChannels);
  588. goto error;
  589. }
  590. if (inchannels == 0) {
  591. JCALog("Setup max in channels = %ld\n", in_nChannels);
  592. inchannels = in_nChannels;
  593. }
  594. if (outchannels == 0) {
  595. JCALog("Setup max out channels = %ld\n", out_nChannels);
  596. outchannels = out_nChannels;
  597. }
  598. // Setting buffer size
  599. outSize = sizeof(UInt32);
  600. err = AudioDeviceSetProperty(driver->device_id, NULL, 0, false, kAudioDevicePropertyBufferFrameSize, outSize, &nframes);
  601. if (err != noErr) {
  602. jack_error("Cannot set buffer size %ld", nframes);
  603. printError(err);
  604. goto error;
  605. }
  606. // Set sample rate
  607. outSize = sizeof(Float64);
  608. err = AudioDeviceGetProperty(driver->device_id, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, &outSize, &sampleRate);
  609. if (err != noErr) {
  610. jack_error("Cannot get current sample rate");
  611. printError(err);
  612. goto error;
  613. }
  614. if (samplerate != (jack_nframes_t)sampleRate) {
  615. sampleRate = (Float64)samplerate;
  616. err = AudioDeviceSetProperty(driver->device_id, NULL, 0, kAudioDeviceSectionGlobal, kAudioDevicePropertyNominalSampleRate, outSize, &sampleRate);
  617. if (err != noErr) {
  618. jack_error("Cannot set sample rate = %ld", samplerate);
  619. printError(err);
  620. goto error;
  621. }
  622. }
  623. // AUHAL
  624. ComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_HALOutput, kAudioUnitManufacturer_Apple, 0, 0};
  625. Component HALOutput = FindNextComponent(NULL, &cd);
  626. err1 = OpenAComponent(HALOutput, &driver->au_hal);
  627. if (err1 != noErr) {
  628. jack_error("Error calling OpenAComponent");
  629. printError(err1);
  630. goto error;
  631. }
  632. err1 = AudioUnitInitialize(driver->au_hal);
  633. if (err1 != noErr) {
  634. jack_error("Cannot initialize AUHAL unit");
  635. printError(err1);
  636. goto error;
  637. }
  638. // Start I/O
  639. enableIO = 1;
  640. if (capturing && inchannels > 0) {
  641. JCALog("Setup AUHAL input\n");
  642. err1 = AudioUnitSetProperty(driver->au_hal, 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. goto error;
  647. }
  648. }
  649. if (playing && outchannels > 0) {
  650. JCALog("Setup AUHAL output\n");
  651. err1 = AudioUnitSetProperty(driver->au_hal, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
  652. if (err1 != noErr) {
  653. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_EnableIO,kAudioUnitScope_Output");
  654. printError(err1);
  655. goto error;
  656. }
  657. }
  658. // Setup up choosen device, in both input and output cases
  659. err1 = AudioUnitSetProperty(driver->au_hal, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &driver->device_id, sizeof(AudioDeviceID));
  660. if (err1 != noErr) {
  661. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_CurrentDevice");
  662. printError(err1);
  663. goto error;
  664. }
  665. // Set buffer size
  666. if (capturing && inchannels > 0) {
  667. err1 = AudioUnitSetProperty(driver->au_hal, 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. goto error;
  672. }
  673. }
  674. if (playing && outchannels > 0) {
  675. err1 = AudioUnitSetProperty(driver->au_hal, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, (UInt32*)&nframes, sizeof(UInt32));
  676. if (err1 != noErr) {
  677. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_MaximumFramesPerSlice");
  678. printError(err1);
  679. goto error;
  680. }
  681. }
  682. // Setup channel map
  683. if (capturing && inchannels > 0 && inchannels < in_nChannels) {
  684. SInt32 chanArr[in_nChannels];
  685. for (i = 0; i < in_nChannels; i++) {
  686. chanArr[i] = -1;
  687. }
  688. for (i = 0; i < inchannels; i++) {
  689. chanArr[i] = i;
  690. }
  691. AudioUnitSetProperty(driver->au_hal, kAudioOutputUnitProperty_ChannelMap , kAudioUnitScope_Input, 1, chanArr, sizeof(SInt32) * in_nChannels);
  692. if (err1 != noErr) {
  693. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 1");
  694. printError(err1);
  695. }
  696. }
  697. if (playing && outchannels > 0 && outchannels < out_nChannels) {
  698. SInt32 chanArr[out_nChannels];
  699. for (i = 0; i < out_nChannels; i++) {
  700. chanArr[i] = -1;
  701. }
  702. for (i = 0; i < outchannels; i++) {
  703. chanArr[i] = i;
  704. }
  705. err1 = AudioUnitSetProperty(driver->au_hal, kAudioOutputUnitProperty_ChannelMap, kAudioUnitScope_Output, 0, chanArr, sizeof(SInt32) * out_nChannels);
  706. if (err1 != noErr) {
  707. jack_error("Error calling AudioUnitSetProperty - kAudioOutputUnitProperty_ChannelMap 0");
  708. printError(err1);
  709. }
  710. }
  711. // Setup stream converters
  712. if (capturing && inchannels > 0) {
  713. srcFormat.mSampleRate = samplerate;
  714. srcFormat.mFormatID = kAudioFormatLinearPCM;
  715. srcFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  716. srcFormat.mBytesPerPacket = sizeof(float);
  717. srcFormat.mFramesPerPacket = 1;
  718. srcFormat.mBytesPerFrame = sizeof(float);
  719. srcFormat.mChannelsPerFrame = outchannels;
  720. srcFormat.mBitsPerChannel = 32;
  721. err1 = AudioUnitSetProperty(driver->au_hal, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &srcFormat, sizeof(AudioStreamBasicDescription));
  722. if (err1 != noErr) {
  723. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Input");
  724. printError(err1);
  725. }
  726. }
  727. if (playing && outchannels > 0) {
  728. dstFormat.mSampleRate = samplerate;
  729. dstFormat.mFormatID = kAudioFormatLinearPCM;
  730. dstFormat.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kLinearPCMFormatFlagIsNonInterleaved;
  731. dstFormat.mBytesPerPacket = sizeof(float);
  732. dstFormat.mFramesPerPacket = 1;
  733. dstFormat.mBytesPerFrame = sizeof(float);
  734. dstFormat.mChannelsPerFrame = inchannels;
  735. dstFormat.mBitsPerChannel = 32;
  736. err1 = AudioUnitSetProperty(driver->au_hal, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &dstFormat, sizeof(AudioStreamBasicDescription));
  737. if (err1 != noErr) {
  738. jack_error("Error calling AudioUnitSetProperty - kAudioUnitProperty_StreamFormat kAudioUnitScope_Output");
  739. printError(err1);
  740. }
  741. }
  742. // Setup callbacks
  743. if (inchannels > 0 && outchannels == 0) {
  744. AURenderCallbackStruct output;
  745. output.inputProc = render_input;
  746. output.inputProcRefCon = driver;
  747. err1 = AudioUnitSetProperty(driver->au_hal, 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. goto error;
  752. }
  753. } else {
  754. AURenderCallbackStruct output;
  755. output.inputProc = render;
  756. output.inputProcRefCon = driver;
  757. err1 = AudioUnitSetProperty(driver->au_hal, 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. goto error;
  762. }
  763. }
  764. if (capturing && inchannels > 0) {
  765. driver->input_list = (AudioBufferList*)malloc(sizeof(UInt32) + inchannels * sizeof(AudioBuffer));
  766. if (driver->input_list == 0)
  767. goto error;
  768. driver->input_list->mNumberBuffers = inchannels;
  769. // Prepare buffers
  770. for (i = 0; i < driver->capture_nchannels; i++) {
  771. driver->input_list->mBuffers[i].mNumberChannels = 1;
  772. driver->input_list->mBuffers[i].mDataByteSize = nframes * sizeof(float);
  773. }
  774. }
  775. err = AudioDeviceAddPropertyListener(driver->device_id, 0, true, kAudioDeviceProcessorOverload, notification, driver);
  776. if (err != noErr)
  777. goto error;
  778. driver->playback_nchannels = outchannels;
  779. driver->capture_nchannels = inchannels;
  780. return ((jack_driver_t *) driver);
  781. error:
  782. AudioUnitUninitialize(driver->au_hal);
  783. CloseComponent(driver->au_hal);
  784. jack_error("Cannot open the coreaudio driver");
  785. free(driver);
  786. return NULL;
  787. }
  788. /** free all memory allocated by a driver instance
  789. */
  790. static void coreaudio_driver_delete(coreaudio_driver_t * driver)
  791. {
  792. AudioDeviceRemovePropertyListener(driver->device_id, 0, true, kAudioDeviceProcessorOverload, notification);
  793. free(driver->input_list);
  794. AudioUnitUninitialize(driver->au_hal);
  795. CloseComponent(driver->au_hal);
  796. free(driver);
  797. }
  798. //== driver "plugin" interface =================================================
  799. /* DRIVER "PLUGIN" INTERFACE */
  800. const char driver_client_name[] = "coreaudio";
  801. jack_driver_desc_t *driver_get_descriptor()
  802. {
  803. jack_driver_desc_t *desc;
  804. unsigned int i;
  805. desc = calloc(1, sizeof(jack_driver_desc_t));
  806. strcpy(desc->name, "coreaudio");
  807. desc->nparams = 12;
  808. desc->params = calloc(desc->nparams, sizeof(jack_driver_param_desc_t));
  809. i = 0;
  810. strcpy(desc->params[i].name, "channels");
  811. desc->params[i].character = 'c';
  812. desc->params[i].type = JackDriverParamInt;
  813. desc->params[i].value.ui = 2;
  814. strcpy(desc->params[i].short_desc, "Maximum number of channels");
  815. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  816. i++;
  817. strcpy(desc->params[i].name, "inchannels");
  818. desc->params[i].character = 'i';
  819. desc->params[i].type = JackDriverParamInt;
  820. desc->params[i].value.ui = 2;
  821. strcpy(desc->params[i].short_desc, "Maximum number of input channels");
  822. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  823. i++;
  824. strcpy(desc->params[i].name, "outchannels");
  825. desc->params[i].character = 'o';
  826. desc->params[i].type = JackDriverParamInt;
  827. desc->params[i].value.ui = 2;
  828. strcpy(desc->params[i].short_desc, "Maximum number of output channels");
  829. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  830. i++;
  831. strcpy(desc->params[i].name, "capture");
  832. desc->params[i].character = 'C';
  833. desc->params[i].type = JackDriverParamString;
  834. strcpy(desc->params[i].value.str, "will take default CoreAudio input device");
  835. strcpy(desc->params[i].short_desc, "Provide capture ports. Optionally set CoreAudio device name");
  836. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  837. i++;
  838. strcpy(desc->params[i].name, "playback");
  839. desc->params[i].character = 'P';
  840. desc->params[i].type = JackDriverParamString;
  841. strcpy(desc->params[i].value.str, "will take default CoreAudio output device");
  842. strcpy(desc->params[i].short_desc, "Provide playback ports. Optionally set CoreAudio device name");
  843. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  844. i++;
  845. strcpy(desc->params[i].name, "duplex");
  846. desc->params[i].character = 'D';
  847. desc->params[i].type = JackDriverParamBool;
  848. desc->params[i].value.i = TRUE;
  849. strcpy(desc->params[i].short_desc, "Capture and playback");
  850. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  851. i++;
  852. strcpy(desc->params[i].name, "rate");
  853. desc->params[i].character = 'r';
  854. desc->params[i].type = JackDriverParamUInt;
  855. desc->params[i].value.ui = 44100U;
  856. strcpy(desc->params[i].short_desc, "Sample rate");
  857. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  858. i++;
  859. strcpy(desc->params[i].name, "period");
  860. desc->params[i].character = 'p';
  861. desc->params[i].type = JackDriverParamUInt;
  862. desc->params[i].value.ui = 128U;
  863. strcpy(desc->params[i].short_desc, "Frames per period");
  864. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  865. i++;
  866. strcpy(desc->params[i].name, "device");
  867. desc->params[i].character = 'd';
  868. desc->params[i].type = JackDriverParamString;
  869. desc->params[i].value.ui = 128U;
  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, "input-latency");
  875. desc->params[i].character = 'I';
  876. desc->params[i].type = JackDriverParamUInt;
  877. desc->params[i].value.i = 0;
  878. strcpy(desc->params[i].short_desc, "Extra input latency");
  879. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  880. i++;
  881. strcpy(desc->params[i].name, "output-latency");
  882. desc->params[i].character = 'O';
  883. desc->params[i].type = JackDriverParamUInt;
  884. desc->params[i].value.i = 0;
  885. strcpy(desc->params[i].short_desc, "Extra output latency");
  886. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  887. i++;
  888. strcpy(desc->params[i].name, "list-devices");
  889. desc->params[i].character = 'l';
  890. desc->params[i].type = JackDriverParamBool;
  891. desc->params[i].value.i = FALSE;
  892. strcpy(desc->params[i].short_desc, "Display available CoreAudio devices");
  893. strcpy(desc->params[i].long_desc, desc->params[i].short_desc);
  894. return desc;
  895. }
  896. jack_driver_t *driver_initialize(jack_client_t * client,
  897. const JSList * params)
  898. {
  899. jack_nframes_t srate = 44100; /* Some older Mac models only support this value */
  900. jack_nframes_t frames_per_interrupt = 128;
  901. int capture = FALSE;
  902. int playback = FALSE;
  903. int chan_in = 0;
  904. int chan_out = 0;
  905. char* capture_pcm_name = NULL;
  906. char* playback_pcm_name = NULL;
  907. const JSList *node;
  908. const jack_driver_param_t *param;
  909. jack_nframes_t systemic_input_latency = 0;
  910. jack_nframes_t systemic_output_latency = 0;
  911. for (node = params; node; node = jack_slist_next(node)) {
  912. param = (const jack_driver_param_t *) node->data;
  913. switch (param->character) {
  914. case 'd':
  915. capture_pcm_name = strdup(param->value.str);
  916. playback_pcm_name = strdup(param->value.str);
  917. break;
  918. case 'D':
  919. capture = TRUE;
  920. playback = TRUE;
  921. break;
  922. case 'c':
  923. chan_in = chan_out = (int) param->value.ui;
  924. break;
  925. case 'i':
  926. chan_in = (int) param->value.ui;
  927. break;
  928. case 'o':
  929. chan_out = (int) param->value.ui;
  930. break;
  931. case 'C':
  932. capture = TRUE;
  933. if (strcmp(param->value.str, "none") != 0) {
  934. capture_pcm_name = strdup(param->value.str);
  935. }
  936. break;
  937. case 'P':
  938. playback = TRUE;
  939. if (strcmp(param->value.str, "none") != 0) {
  940. playback_pcm_name = strdup(param->value.str);
  941. }
  942. break;
  943. case 'r':
  944. srate = param->value.ui;
  945. break;
  946. case 'p':
  947. frames_per_interrupt = (unsigned int) param->value.ui;
  948. break;
  949. case 'I':
  950. systemic_input_latency = param->value.ui;
  951. break;
  952. case 'O':
  953. systemic_output_latency = param->value.ui;
  954. break;
  955. case 'l':
  956. display_device_names();
  957. break;
  958. }
  959. }
  960. /* duplex is the default */
  961. if (!capture && !playback) {
  962. capture = TRUE;
  963. playback = TRUE;
  964. }
  965. return coreaudio_driver_new("coreaudio", client, frames_per_interrupt,
  966. srate, capture, playback, chan_in,
  967. chan_out, capture_pcm_name, playback_pcm_name, systemic_input_latency, systemic_output_latency);
  968. }
  969. void driver_finish(jack_driver_t * driver)
  970. {
  971. coreaudio_driver_delete((coreaudio_driver_t *) driver);
  972. }