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.

1084 lines
36KB

  1. /*
  2. Copyright (C) 2001 Paul Davis
  3. Copyright (C) 2004 Grame
  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. */
  16. #define __STDC_FORMAT_MACROS // For inttypes.h to work in C++
  17. #include <iostream>
  18. #include <math.h>
  19. #include <stdio.h>
  20. #include <memory.h>
  21. #include <unistd.h>
  22. #include <stdlib.h>
  23. #include <errno.h>
  24. #include <stdarg.h>
  25. #include <signal.h>
  26. #include <sys/types.h>
  27. #include <sys/time.h>
  28. #include <string.h>
  29. #include <sstream>
  30. #include <fstream>
  31. #include <algorithm>
  32. #include <cctype>
  33. #include <vector>
  34. #include "JackAlsaDriver.h"
  35. #include "JackEngineControl.h"
  36. #include "JackClientControl.h"
  37. #include "JackPort.h"
  38. #include "JackGraphManager.h"
  39. #include "JackLockedEngine.h"
  40. #ifdef __ANDROID__
  41. #include "JackAndroidThread.h"
  42. #else
  43. #include "JackPosixThread.h"
  44. #endif
  45. #include "JackCompilerDeps.h"
  46. #include "JackServerGlobals.h"
  47. static struct jack_constraint_enum_str_descriptor midi_constraint_descr_array[] =
  48. {
  49. { "none", "no MIDI driver" },
  50. { "seq", "ALSA Sequencer driver" },
  51. { "raw", "ALSA RawMIDI driver" },
  52. { 0 }
  53. };
  54. static struct jack_constraint_enum_char_descriptor dither_constraint_descr_array[] =
  55. {
  56. { 'n', "none" },
  57. { 'r', "rectangular" },
  58. { 's', "shaped" },
  59. { 't', "triangular" },
  60. { 0 }
  61. };
  62. namespace Jack
  63. {
  64. static volatile bool device_reservation_loop_running = false;
  65. static void* on_device_reservation_loop(void*)
  66. {
  67. while (device_reservation_loop_running && JackServerGlobals::on_device_reservation_loop != NULL) {
  68. JackServerGlobals::on_device_reservation_loop();
  69. usleep(50*1000);
  70. }
  71. return NULL;
  72. }
  73. int JackAlsaDriver::SetBufferSize(jack_nframes_t buffer_size)
  74. {
  75. jack_log("JackAlsaDriver::SetBufferSize %ld", buffer_size);
  76. int res = alsa_driver_reset_parameters((alsa_driver_t *)fDriver, buffer_size,
  77. ((alsa_driver_t *)fDriver)->user_nperiods,
  78. ((alsa_driver_t *)fDriver)->frame_rate);
  79. if (res == 0) { // update fEngineControl and fGraphManager
  80. JackAudioDriver::SetBufferSize(buffer_size); // Generic change, never fails
  81. // ALSA specific
  82. UpdateLatencies();
  83. } else {
  84. // Restore old values
  85. alsa_driver_reset_parameters((alsa_driver_t *)fDriver, fEngineControl->fBufferSize,
  86. ((alsa_driver_t *)fDriver)->user_nperiods,
  87. ((alsa_driver_t *)fDriver)->frame_rate);
  88. }
  89. return res;
  90. }
  91. void JackAlsaDriver::UpdateLatencies()
  92. {
  93. jack_latency_range_t range;
  94. alsa_driver_t* alsa_driver = (alsa_driver_t*)fDriver;
  95. for (int i = 0; i < fCaptureChannels; i++) {
  96. range.min = range.max = alsa_driver->frames_per_cycle + alsa_driver->capture_frame_latency;
  97. fGraphManager->GetPort(fCapturePortList[i])->SetLatencyRange(JackCaptureLatency, &range);
  98. }
  99. for (int i = 0; i < fPlaybackChannels; i++) {
  100. // Add one buffer more latency if "async" mode is used...
  101. range.min = range.max = (alsa_driver->frames_per_cycle * (alsa_driver->user_nperiods - 1)) +
  102. ((fEngineControl->fSyncMode) ? 0 : fEngineControl->fBufferSize) + alsa_driver->playback_frame_latency;
  103. fGraphManager->GetPort(fPlaybackPortList[i])->SetLatencyRange(JackPlaybackLatency, &range);
  104. // Monitor port
  105. if (fWithMonitorPorts) {
  106. range.min = range.max = alsa_driver->frames_per_cycle;
  107. fGraphManager->GetPort(fMonitorPortList[i])->SetLatencyRange(JackCaptureLatency, &range);
  108. }
  109. }
  110. }
  111. int JackAlsaDriver::Attach()
  112. {
  113. JackPort* port;
  114. jack_port_id_t port_id;
  115. unsigned long port_flags = (unsigned long)CaptureDriverFlags;
  116. char name[REAL_JACK_PORT_NAME_SIZE+1];
  117. char alias[REAL_JACK_PORT_NAME_SIZE+1];
  118. assert(fCaptureChannels < DRIVER_PORT_NUM);
  119. assert(fPlaybackChannels < DRIVER_PORT_NUM);
  120. alsa_driver_t* alsa_driver = (alsa_driver_t*)fDriver;
  121. if (alsa_driver->has_hw_monitoring)
  122. port_flags |= JackPortCanMonitor;
  123. // ALSA driver may have changed the values
  124. JackAudioDriver::SetBufferSize(alsa_driver->frames_per_cycle);
  125. JackAudioDriver::SetSampleRate(alsa_driver->frame_rate);
  126. jack_log("JackAlsaDriver::Attach fBufferSize %ld fSampleRate %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate);
  127. for (int i = 0, port_list_index = 0; i < alsa_driver->devices_c_count; ++i) {
  128. alsa_device_t *device = &alsa_driver->devices[i];
  129. for (int j = 0; j < device->capture_nchannels; ++j, ++port_list_index) {
  130. snprintf(name, sizeof(name), "%s:capture_%d", fClientControl.fName, port_list_index + 1);
  131. snprintf(alias, sizeof(alias), "%s:%s:capture_%d", fAliasName, device->capture_name, j + 1);
  132. if (fEngine->PortRegister(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize, &port_id) < 0) {
  133. jack_error("driver: cannot register port for %s", name);
  134. return -1;
  135. }
  136. port = fGraphManager->GetPort(port_id);
  137. port->SetAlias(alias);
  138. fCapturePortList[port_list_index] = port_id;
  139. jack_log("JackAlsaDriver::Attach fCapturePortList[i] %ld ", port_id);
  140. }
  141. }
  142. port_flags = (unsigned long)PlaybackDriverFlags;
  143. for (int i = 0, port_list_index = 0; i < alsa_driver->devices_p_count; ++i) {
  144. alsa_device_t *device = &alsa_driver->devices[i];
  145. for (int j = 0; j < device->playback_nchannels; ++j, ++port_list_index) {
  146. snprintf(name, sizeof(name), "%s:playback_%d", fClientControl.fName, port_list_index + 1);
  147. snprintf(alias, sizeof(alias), "%s:%s:playback_%d", fAliasName, device->playback_name, j + 1);
  148. if (fEngine->PortRegister(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, (JackPortFlags)port_flags, fEngineControl->fBufferSize, &port_id) < 0) {
  149. jack_error("driver: cannot register port for %s", name);
  150. return -1;
  151. }
  152. port = fGraphManager->GetPort(port_id);
  153. port->SetAlias(alias);
  154. fPlaybackPortList[port_list_index] = port_id;
  155. jack_log("JackAlsaDriver::Attach fPlaybackPortList[i] %ld ", port_id);
  156. // Monitor ports
  157. if (fWithMonitorPorts) {
  158. jack_log("Create monitor port");
  159. snprintf(name, sizeof(name), "%s:monitor_%d", fClientControl.fName, port_list_index + 1);
  160. if (fEngine->PortRegister(fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE, MonitorDriverFlags, fEngineControl->fBufferSize, &port_id) < 0) {
  161. jack_error("ALSA: cannot register monitor port for %s", name);
  162. } else {
  163. fMonitorPortList[port_list_index] = port_id;
  164. }
  165. }
  166. }
  167. }
  168. UpdateLatencies();
  169. if (alsa_driver->midi) {
  170. int err = (alsa_driver->midi->attach)(alsa_driver->midi);
  171. if (err)
  172. jack_error ("ALSA: cannot attach MIDI: %d", err);
  173. }
  174. return 0;
  175. }
  176. int JackAlsaDriver::Detach()
  177. {
  178. alsa_driver_t* alsa_driver = (alsa_driver_t*)fDriver;
  179. if (alsa_driver->midi)
  180. (alsa_driver->midi->detach)(alsa_driver->midi);
  181. return JackAudioDriver::Detach();
  182. }
  183. #ifndef __QNXNTO__
  184. extern "C" char* get_control_device_name(const char * device_name)
  185. {
  186. char * ctl_name;
  187. const char * comma;
  188. /* the user wants a hw or plughw device, the ctl name
  189. * should be hw:x where x is the card identification.
  190. * We skip the subdevice suffix that starts with comma */
  191. if (strncasecmp(device_name, "plughw:", 7) == 0) {
  192. /* skip the "plug" prefix" */
  193. device_name += 4;
  194. }
  195. comma = strchr(device_name, ',');
  196. if (comma == NULL) {
  197. ctl_name = strdup(device_name);
  198. if (ctl_name == NULL) {
  199. jack_error("strdup(\"%s\") failed.", device_name);
  200. }
  201. } else {
  202. ctl_name = strndup(device_name, comma - device_name);
  203. if (ctl_name == NULL) {
  204. jack_error("strndup(\"%s\", %u) failed.", device_name, (unsigned int)(comma - device_name));
  205. }
  206. }
  207. return ctl_name;
  208. }
  209. #endif
  210. #ifndef __QNXNTO__
  211. static int card_to_num(const char* device)
  212. {
  213. int err;
  214. char* ctl_name;
  215. snd_ctl_card_info_t *card_info;
  216. snd_ctl_t* ctl_handle;
  217. int i = -1;
  218. snd_ctl_card_info_alloca (&card_info);
  219. ctl_name = get_control_device_name(device);
  220. if (ctl_name == NULL) {
  221. jack_error("get_control_device_name() failed.");
  222. goto fail;
  223. }
  224. if ((err = snd_ctl_open (&ctl_handle, ctl_name, 0)) < 0) {
  225. jack_error ("control open \"%s\" (%s)", ctl_name,
  226. snd_strerror(err));
  227. goto free;
  228. }
  229. if ((err = snd_ctl_card_info(ctl_handle, card_info)) < 0) {
  230. jack_error ("control hardware info \"%s\" (%s)",
  231. device, snd_strerror (err));
  232. goto close;
  233. }
  234. i = snd_ctl_card_info_get_card(card_info);
  235. close:
  236. snd_ctl_close(ctl_handle);
  237. free:
  238. free(ctl_name);
  239. fail:
  240. return i;
  241. }
  242. #endif
  243. int JackAlsaDriver::Open(jack_nframes_t nframes,
  244. jack_nframes_t user_nperiods,
  245. jack_nframes_t samplerate,
  246. bool hw_monitoring,
  247. bool hw_metering,
  248. bool capturing,
  249. bool playing,
  250. DitherAlgorithm dither,
  251. bool soft_mode,
  252. bool monitor,
  253. int inchannels,
  254. int outchannels,
  255. bool shorts_first,
  256. const char* capture_driver_name,
  257. const char* playback_driver_name,
  258. jack_nframes_t capture_latency,
  259. jack_nframes_t playback_latency,
  260. const char* midi_driver_name)
  261. {
  262. struct array_string_t capture_drivers = array_string_split(capture_driver_name, ' ');
  263. struct array_string_t playback_drivers = array_string_split(playback_driver_name, ' ');
  264. // Generic JackAudioDriver Open
  265. if (JackAudioDriver::Open(nframes, samplerate, capturing, playing,
  266. inchannels, outchannels, monitor,
  267. capture_drivers.size > 1 ? capture_drivers.data[0] : capture_driver_name,
  268. playback_drivers.size > 1 ? playback_drivers.data[0] : playback_driver_name,
  269. capture_latency, playback_latency) != 0) {
  270. array_string_free(&capture_drivers);
  271. array_string_free(&playback_drivers);
  272. return -1;
  273. }
  274. jack_log("JackAlsaDriver::Open capture_driver_name = %s", capture_driver_name);
  275. jack_log("JackAlsaDriver::Open playback_driver_name = %s", playback_driver_name);
  276. alsa_midi_t *midi = 0;
  277. #ifndef __QNXNTO__
  278. #ifndef __ANDROID__
  279. if (strcmp(midi_driver_name, "seq") == 0)
  280. midi = alsa_seqmidi_new((jack_client_t*)this, 0);
  281. else if (strcmp(midi_driver_name, "raw") == 0)
  282. midi = alsa_rawmidi_new((jack_client_t*)this);
  283. #endif
  284. // FIXME: needs adaptation for multiple drivers
  285. if (JackServerGlobals::on_device_acquire != NULL) {
  286. int capture_card = card_to_num(capture_drivers.data[0]);
  287. int playback_card = card_to_num(playback_drivers.data[0]);
  288. char audio_name[32];
  289. if (capture_card >= 0) {
  290. snprintf(audio_name, sizeof(audio_name), "Audio%d", capture_card);
  291. if (!JackServerGlobals::on_device_acquire(audio_name)) {
  292. jack_error("Audio device %s cannot be acquired...", capture_drivers.data[0]);
  293. array_string_free(&capture_drivers);
  294. array_string_free(&playback_drivers);
  295. return -1;
  296. }
  297. }
  298. if (playback_card >= 0 && playback_card != capture_card) {
  299. snprintf(audio_name, sizeof(audio_name), "Audio%d", playback_card);
  300. if (!JackServerGlobals::on_device_acquire(audio_name)) {
  301. jack_error("Audio device %s cannot be acquired...", playback_drivers.data[0]);
  302. if (capture_card >= 0) {
  303. snprintf(audio_name, sizeof(audio_name), "Audio%d", capture_card);
  304. JackServerGlobals::on_device_release(audio_name);
  305. }
  306. array_string_free(&capture_drivers);
  307. array_string_free(&playback_drivers);
  308. return -1;
  309. }
  310. }
  311. }
  312. #endif
  313. fDriver = alsa_driver_new ((char*)"alsa_pcm",
  314. capture_drivers.data,
  315. playback_drivers.data,
  316. capture_driver_name,
  317. playback_driver_name,
  318. NULL,
  319. nframes,
  320. user_nperiods,
  321. samplerate,
  322. hw_monitoring,
  323. hw_metering,
  324. capturing ? capture_drivers.size : 0,
  325. playing ? playback_drivers.size : 0,
  326. dither,
  327. soft_mode,
  328. monitor,
  329. inchannels,
  330. outchannels,
  331. shorts_first,
  332. capture_latency,
  333. playback_latency,
  334. midi);
  335. array_string_free(&capture_drivers);
  336. array_string_free(&playback_drivers);
  337. if (fDriver) {
  338. // ALSA driver may have changed the in/out values
  339. fCaptureChannels = ((alsa_driver_t *)fDriver)->capture_nchannels;
  340. fPlaybackChannels = ((alsa_driver_t *)fDriver)->playback_nchannels;
  341. #ifndef __QNXNTO__
  342. if (JackServerGlobals::on_device_reservation_loop != NULL) {
  343. device_reservation_loop_running = true;
  344. if (JackPosixThread::StartImp(&fReservationLoopThread, 0, 0, on_device_reservation_loop, NULL) != 0) {
  345. device_reservation_loop_running = false;
  346. }
  347. }
  348. #endif
  349. return 0;
  350. } else {
  351. Close();
  352. return -1;
  353. }
  354. }
  355. int JackAlsaDriver::Close()
  356. {
  357. // Generic audio driver close
  358. int res = JackAudioDriver::Close();
  359. if (fDriver) {
  360. alsa_driver_delete((alsa_driver_t*)fDriver);
  361. }
  362. #ifndef __QNXNTO__
  363. if (device_reservation_loop_running) {
  364. device_reservation_loop_running = false;
  365. JackPosixThread::StopImp(fReservationLoopThread);
  366. }
  367. // FIXME: needs adaptation for multiple drivers
  368. if (JackServerGlobals::on_device_release != NULL)
  369. {
  370. char audio_name[32];
  371. int capture_card = card_to_num(fCaptureDriverName);
  372. if (capture_card >= 0) {
  373. snprintf(audio_name, sizeof(audio_name), "Audio%d", capture_card);
  374. JackServerGlobals::on_device_release(audio_name);
  375. }
  376. int playback_card = card_to_num(fPlaybackDriverName);
  377. if (playback_card >= 0 && playback_card != capture_card) {
  378. snprintf(audio_name, sizeof(audio_name), "Audio%d", playback_card);
  379. JackServerGlobals::on_device_release(audio_name);
  380. }
  381. }
  382. #endif
  383. return res;
  384. }
  385. int JackAlsaDriver::Start()
  386. {
  387. int res = JackAudioDriver::Start();
  388. if (res >= 0) {
  389. res = alsa_driver_start((alsa_driver_t *)fDriver);
  390. if (res < 0) {
  391. JackAudioDriver::Stop();
  392. }
  393. }
  394. return res;
  395. }
  396. int JackAlsaDriver::Stop()
  397. {
  398. int res = alsa_driver_stop((alsa_driver_t *)fDriver);
  399. if (JackAudioDriver::Stop() < 0) {
  400. res = -1;
  401. }
  402. return res;
  403. }
  404. int JackAlsaDriver::Read()
  405. {
  406. /* Taken from alsa_driver_run_cycle */
  407. int wait_status;
  408. jack_nframes_t nframes;
  409. fDelayedUsecs = 0.f;
  410. retry:
  411. nframes = alsa_driver_wait((alsa_driver_t *)fDriver, -1, &wait_status, &fDelayedUsecs);
  412. if (wait_status < 0)
  413. return -1; /* driver failed */
  414. if (nframes == 0) {
  415. /* we detected an xrun and restarted: notify
  416. * clients about the delay.
  417. */
  418. jack_log("ALSA XRun wait_status = %d", wait_status);
  419. NotifyXRun(fBeginDateUst, fDelayedUsecs);
  420. goto retry; /* recoverable error*/
  421. }
  422. if (nframes != fEngineControl->fBufferSize)
  423. jack_log("JackAlsaDriver::Read warning fBufferSize = %ld nframes = %ld", fEngineControl->fBufferSize, nframes);
  424. // Has to be done before read
  425. JackDriver::CycleIncTime();
  426. return alsa_driver_read((alsa_driver_t *)fDriver, fEngineControl->fBufferSize);
  427. }
  428. int JackAlsaDriver::Write()
  429. {
  430. return alsa_driver_write((alsa_driver_t *)fDriver, fEngineControl->fBufferSize);
  431. }
  432. void JackAlsaDriver::ReadInputAux(alsa_device_t *device, jack_nframes_t orig_nframes, snd_pcm_sframes_t contiguous, snd_pcm_sframes_t nread)
  433. {
  434. /* global channel offset to fCapturePortList of this capture alsa device */
  435. channel_t port_n = device->capture_channel_offset;
  436. for (channel_t chn = 0; chn < device->capture_nchannels; ++chn, ++port_n) {
  437. if (fGraphManager->GetConnectionsNum(fCapturePortList[port_n]) > 0) {
  438. jack_default_audio_sample_t* buf = (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fCapturePortList[port_n], orig_nframes);
  439. alsa_driver_read_from_channel((alsa_driver_t *)fDriver, device, chn, buf + nread, contiguous);
  440. }
  441. }
  442. }
  443. void JackAlsaDriver::MonitorInputAux()
  444. {
  445. for (int chn = 0; chn < fCaptureChannels; chn++) {
  446. JackPort* port = fGraphManager->GetPort(fCapturePortList[chn]);
  447. if (port->MonitoringInput()) {
  448. ((alsa_driver_t *)fDriver)->input_monitor_mask |= (1 << chn);
  449. }
  450. }
  451. }
  452. void JackAlsaDriver::ClearOutputAux()
  453. {
  454. for (int chn = 0; chn < fPlaybackChannels; chn++) {
  455. jack_default_audio_sample_t* buf =
  456. (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fPlaybackPortList[chn], fEngineControl->fBufferSize);
  457. memset(buf, 0, sizeof (jack_default_audio_sample_t) * fEngineControl->fBufferSize);
  458. }
  459. }
  460. void JackAlsaDriver::SetTimetAux(jack_time_t time)
  461. {
  462. fBeginDateUst = time;
  463. }
  464. int JackAlsaDriver::PortSetDefaultMetadata(jack_port_id_t port_id, const char* pretty_name)
  465. {
  466. return fEngine->PortSetDefaultMetadata(fClientControl.fRefNum, port_id, pretty_name);
  467. }
  468. void JackAlsaDriver::WriteOutputAux(alsa_device_t *device, jack_nframes_t orig_nframes, snd_pcm_sframes_t contiguous, snd_pcm_sframes_t nwritten)
  469. {
  470. /* global channel offset to fPlaybackPortList of this playback alsa device */
  471. channel_t port_n = device->playback_channel_offset;
  472. for (channel_t chn = 0; chn < device->playback_nchannels; ++chn, ++port_n) {
  473. // Output ports
  474. if (fGraphManager->GetConnectionsNum(fPlaybackPortList[port_n]) > 0) {
  475. jack_default_audio_sample_t* buf = (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fPlaybackPortList[port_n], orig_nframes);
  476. alsa_driver_write_to_channel(((alsa_driver_t *)fDriver), device, chn, buf + nwritten, contiguous);
  477. // Monitor ports
  478. if (fWithMonitorPorts && fGraphManager->GetConnectionsNum(fMonitorPortList[port_n]) > 0) {
  479. jack_default_audio_sample_t* monbuf = (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fMonitorPortList[port_n], orig_nframes);
  480. memcpy(monbuf + nwritten, buf + nwritten, contiguous * sizeof(jack_default_audio_sample_t));
  481. }
  482. }
  483. }
  484. }
  485. int JackAlsaDriver::is_realtime() const
  486. {
  487. return fEngineControl->fRealTime;
  488. }
  489. int JackAlsaDriver::create_thread(pthread_t *thread, int priority, int realtime, void *(*start_routine)(void*), void *arg)
  490. {
  491. #ifdef __ANDROID__
  492. return JackAndroidThread::StartImp(thread, priority, realtime, start_routine, arg);
  493. #else
  494. return JackPosixThread::StartImp(thread, priority, realtime, start_routine, arg);
  495. #endif
  496. }
  497. jack_port_id_t JackAlsaDriver::port_register(const char *port_name, const char *port_type, unsigned long flags, unsigned long buffer_size)
  498. {
  499. jack_port_id_t port_index;
  500. int res = fEngine->PortRegister(fClientControl.fRefNum, port_name, port_type, flags, buffer_size, &port_index);
  501. return (res == 0) ? port_index : 0;
  502. }
  503. int JackAlsaDriver::port_unregister(jack_port_id_t port_index)
  504. {
  505. return fEngine->PortUnRegister(fClientControl.fRefNum, port_index);
  506. }
  507. void* JackAlsaDriver::port_get_buffer(int port, jack_nframes_t nframes)
  508. {
  509. return fGraphManager->GetBuffer(port, nframes);
  510. }
  511. int JackAlsaDriver::port_set_alias(int port, const char* name)
  512. {
  513. return fGraphManager->GetPort(port)->SetAlias(name);
  514. }
  515. jack_nframes_t JackAlsaDriver::get_sample_rate() const
  516. {
  517. return fEngineControl->fSampleRate;
  518. }
  519. jack_nframes_t JackAlsaDriver::frame_time() const
  520. {
  521. JackTimer timer;
  522. fEngineControl->ReadFrameTime(&timer);
  523. return timer.Time2Frames(GetMicroSeconds(), fEngineControl->fBufferSize);
  524. }
  525. jack_nframes_t JackAlsaDriver::last_frame_time() const
  526. {
  527. JackTimer timer;
  528. fEngineControl->ReadFrameTime(&timer);
  529. return timer.CurFrame();
  530. }
  531. } // end of namespace
  532. #ifdef __cplusplus
  533. extern "C"
  534. {
  535. #endif
  536. #ifndef __QNXNTO__
  537. static
  538. jack_driver_param_constraint_desc_t *
  539. enum_alsa_devices()
  540. {
  541. snd_ctl_t * handle;
  542. snd_ctl_card_info_t * info;
  543. snd_pcm_info_t * pcminfo_capture;
  544. snd_pcm_info_t * pcminfo_playback;
  545. int card_no = -1;
  546. jack_driver_param_value_t card_id;
  547. jack_driver_param_value_t device_id;
  548. char description[64];
  549. int device_no;
  550. bool has_capture;
  551. bool has_playback;
  552. jack_driver_param_constraint_desc_t * constraint_ptr;
  553. uint32_t array_size = 0;
  554. snd_ctl_card_info_alloca(&info);
  555. snd_pcm_info_alloca(&pcminfo_capture);
  556. snd_pcm_info_alloca(&pcminfo_playback);
  557. constraint_ptr = NULL;
  558. while(snd_card_next(&card_no) >= 0 && card_no >= 0)
  559. {
  560. snprintf(card_id.str, sizeof(card_id.str), "hw:%d", card_no);
  561. if (snd_ctl_open(&handle, card_id.str, 0) >= 0 &&
  562. snd_ctl_card_info(handle, info) >= 0)
  563. {
  564. snprintf(card_id.str, sizeof(card_id.str), "hw:%s", snd_ctl_card_info_get_id(info));
  565. if (!jack_constraint_add_enum(
  566. &constraint_ptr,
  567. &array_size,
  568. &card_id,
  569. snd_ctl_card_info_get_name(info)))
  570. goto fail;
  571. device_no = -1;
  572. while (snd_ctl_pcm_next_device(handle, &device_no) >= 0 && device_no != -1)
  573. {
  574. snprintf(device_id.str, sizeof(device_id.str), "%s,%d", card_id.str, device_no);
  575. snd_pcm_info_set_device(pcminfo_capture, device_no);
  576. snd_pcm_info_set_subdevice(pcminfo_capture, 0);
  577. snd_pcm_info_set_stream(pcminfo_capture, SND_PCM_STREAM_CAPTURE);
  578. has_capture = snd_ctl_pcm_info(handle, pcminfo_capture) >= 0;
  579. snd_pcm_info_set_device(pcminfo_playback, device_no);
  580. snd_pcm_info_set_subdevice(pcminfo_playback, 0);
  581. snd_pcm_info_set_stream(pcminfo_playback, SND_PCM_STREAM_PLAYBACK);
  582. has_playback = snd_ctl_pcm_info(handle, pcminfo_playback) >= 0;
  583. if (has_capture && has_playback)
  584. {
  585. snprintf(description, sizeof(description),"%s (duplex)", snd_pcm_info_get_name(pcminfo_capture));
  586. }
  587. else if (has_capture)
  588. {
  589. snprintf(description, sizeof(description),"%s (capture)", snd_pcm_info_get_name(pcminfo_capture));
  590. }
  591. else if (has_playback)
  592. {
  593. snprintf(description, sizeof(description),"%s (playback)", snd_pcm_info_get_name(pcminfo_playback));
  594. }
  595. else
  596. {
  597. continue;
  598. }
  599. if (!jack_constraint_add_enum(
  600. &constraint_ptr,
  601. &array_size,
  602. &device_id,
  603. description))
  604. goto fail;
  605. }
  606. snd_ctl_close(handle);
  607. }
  608. }
  609. return constraint_ptr;
  610. fail:
  611. jack_constraint_free(constraint_ptr);
  612. return NULL;
  613. }
  614. #endif
  615. static int
  616. dither_opt (char c, DitherAlgorithm* dither)
  617. {
  618. switch (c) {
  619. case '-':
  620. case 'n':
  621. *dither = None;
  622. break;
  623. case 'r':
  624. *dither = Rectangular;
  625. break;
  626. case 's':
  627. *dither = Shaped;
  628. break;
  629. case 't':
  630. *dither = Triangular;
  631. break;
  632. default:
  633. fprintf (stderr, "ALSA driver: illegal dithering mode %c\n", c);
  634. return -1;
  635. }
  636. return 0;
  637. }
  638. SERVER_EXPORT const jack_driver_desc_t* driver_get_descriptor ()
  639. {
  640. jack_driver_desc_t * desc;
  641. jack_driver_desc_filler_t filler;
  642. jack_driver_param_value_t value;
  643. desc = jack_driver_descriptor_construct("alsa", JackDriverMaster, "Linux ALSA API based audio backend", &filler);
  644. strcpy(value.str, "hw:0");
  645. #ifndef __QNXNTO__
  646. #ifdef __ANDROID__
  647. jack_driver_descriptor_add_parameter(desc, &filler, "device", 'd', JackDriverParamString, &value, NULL, "ALSA device name", NULL);
  648. #else
  649. jack_driver_descriptor_add_parameter(desc, &filler, "device", 'd', JackDriverParamString, &value, enum_alsa_devices(), "ALSA device name", NULL);
  650. #endif
  651. #endif
  652. strcpy(value.str, "none");
  653. jack_driver_descriptor_add_parameter(desc, &filler, "capture", 'C', JackDriverParamString, &value, NULL, "Provide capture ports. Optionally set device", NULL);
  654. jack_driver_descriptor_add_parameter(desc, &filler, "playback", 'P', JackDriverParamString, &value, NULL, "Provide playback ports. Optionally set device", NULL);
  655. value.ui = 48000U;
  656. jack_driver_descriptor_add_parameter(desc, &filler, "rate", 'r', JackDriverParamUInt, &value, NULL, "Sample rate", NULL);
  657. value.ui = 1024U;
  658. jack_driver_descriptor_add_parameter(desc, &filler, "period", 'p', JackDriverParamUInt, &value, NULL, "Frames per period", NULL);
  659. value.ui = 2U;
  660. jack_driver_descriptor_add_parameter(desc, &filler, "nperiods", 'n', JackDriverParamUInt, &value, NULL, "Number of periods of playback latency", NULL);
  661. value.i = 0;
  662. jack_driver_descriptor_add_parameter(desc, &filler, "hwmon", 'H', JackDriverParamBool, &value, NULL, "Hardware monitoring, if available", NULL);
  663. value.i = 0;
  664. jack_driver_descriptor_add_parameter(desc, &filler, "hwmeter", 'M', JackDriverParamBool, &value, NULL, "Hardware metering, if available", NULL);
  665. value.i = 1;
  666. jack_driver_descriptor_add_parameter(desc, &filler, "duplex", 'D', JackDriverParamBool, &value, NULL, "Provide both capture and playback ports", NULL);
  667. value.i = 0;
  668. jack_driver_descriptor_add_parameter(desc, &filler, "softmode", 's', JackDriverParamBool, &value, NULL, "Soft-mode, no xrun handling", NULL);
  669. value.i = 0;
  670. jack_driver_descriptor_add_parameter(desc, &filler, "monitor", 'm', JackDriverParamBool, &value, NULL, "Provide monitor ports for the output", NULL);
  671. value.c = 'n';
  672. jack_driver_descriptor_add_parameter(
  673. desc,
  674. &filler,
  675. "dither",
  676. 'z',
  677. JackDriverParamChar,
  678. &value,
  679. jack_constraint_compose_enum_char(
  680. JACK_CONSTRAINT_FLAG_STRICT | JACK_CONSTRAINT_FLAG_FAKE_VALUE,
  681. dither_constraint_descr_array),
  682. "Dithering mode",
  683. NULL);
  684. value.ui = 0;
  685. jack_driver_descriptor_add_parameter(desc, &filler, "inchannels", 'i', JackDriverParamUInt, &value, NULL, "Number of capture channels (defaults to hardware max)", NULL);
  686. jack_driver_descriptor_add_parameter(desc, &filler, "outchannels", 'o', JackDriverParamUInt, &value, NULL, "Number of playback channels (defaults to hardware max)", NULL);
  687. value.i = FALSE;
  688. jack_driver_descriptor_add_parameter(desc, &filler, "shorts", 'S', JackDriverParamBool, &value, NULL, "Try 16-bit samples before 32-bit", NULL);
  689. value.ui = 0;
  690. jack_driver_descriptor_add_parameter(desc, &filler, "input-latency", 'I', JackDriverParamUInt, &value, NULL, "Extra input latency (frames)", NULL);
  691. jack_driver_descriptor_add_parameter(desc, &filler, "output-latency", 'O', JackDriverParamUInt, &value, NULL, "Extra output latency (frames)", NULL);
  692. strcpy(value.str, "none");
  693. jack_driver_descriptor_add_parameter(
  694. desc,
  695. &filler,
  696. "midi-driver",
  697. 'X',
  698. JackDriverParamString,
  699. &value,
  700. jack_constraint_compose_enum_str(
  701. JACK_CONSTRAINT_FLAG_STRICT | JACK_CONSTRAINT_FLAG_FAKE_VALUE,
  702. midi_constraint_descr_array),
  703. "ALSA MIDI driver",
  704. NULL);
  705. return desc;
  706. }
  707. struct array_string_t
  708. {
  709. uint64_t size;
  710. char **data;
  711. };
  712. void array_string_free(struct array_string_t *obj)
  713. {
  714. if (obj == NULL) {
  715. return;
  716. }
  717. if (obj->data == NULL) {
  718. return;
  719. }
  720. for (size_t i = 0; i < obj->size; ++i) {
  721. free(obj->data[i]);
  722. }
  723. free(obj->data);
  724. obj->data = NULL;
  725. obj->size = 0;
  726. }
  727. struct array_string_t array_string_split(const char *str, const char sep)
  728. {
  729. struct array_string_t result;
  730. result.size = 0;
  731. std::stringstream stream;
  732. stream << std::string(str);
  733. if (stream.str().find(sep) == std::string::npos) {
  734. result.data = (char**) calloc(1, sizeof(char*));
  735. result.data[0] = (char*) calloc(JACK_CLIENT_NAME_SIZE + 1, sizeof(char));
  736. result.size = 1;
  737. strncpy(result.data[0], str, JACK_CLIENT_NAME_SIZE);
  738. result.data[0][JACK_CLIENT_NAME_SIZE] = '\0';
  739. return result;
  740. }
  741. std::string driver;
  742. std::vector<char*> drivers;
  743. while (std::getline(stream, driver, sep)) {
  744. driver.erase(std::remove_if(driver.begin(), driver.end(), isspace), driver.end());
  745. if (std::find(drivers.begin(), drivers.end(), driver) != drivers.end())
  746. continue;
  747. char *str = (char*) calloc(JACK_CLIENT_NAME_SIZE + 1, sizeof(char));
  748. strncpy(str, driver.c_str(), JACK_CLIENT_NAME_SIZE);
  749. str[JACK_CLIENT_NAME_SIZE] = '\0';
  750. drivers.push_back(str);
  751. }
  752. result.data = (char**) calloc(driver.size(), sizeof(char*));
  753. result.size = drivers.size();
  754. memcpy(result.data, drivers.data(), result.size * sizeof(char*));
  755. return result;
  756. }
  757. static Jack::JackAlsaDriver* g_alsa_driver;
  758. SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
  759. {
  760. jack_nframes_t srate = 48000;
  761. jack_nframes_t frames_per_interrupt = 1024;
  762. unsigned long user_nperiods = 2;
  763. const char *playback_pcm_name = "hw:0";
  764. const char *capture_pcm_name = "hw:0";
  765. int hw_monitoring = FALSE;
  766. int hw_metering = FALSE;
  767. int capture = FALSE;
  768. int playback = FALSE;
  769. int soft_mode = FALSE;
  770. int monitor = FALSE;
  771. DitherAlgorithm dither = None;
  772. int user_capture_nchnls = 0;
  773. int user_playback_nchnls = 0;
  774. int shorts_first = FALSE;
  775. jack_nframes_t systemic_input_latency = 0;
  776. jack_nframes_t systemic_output_latency = 0;
  777. const JSList * node;
  778. const jack_driver_param_t * param;
  779. const char *midi_driver = "none";
  780. for (node = params; node; node = jack_slist_next (node)) {
  781. param = (const jack_driver_param_t *) node->data;
  782. switch (param->character) {
  783. case 'C':
  784. capture = TRUE;
  785. if (strcmp (param->value.str, "none") != 0) {
  786. capture_pcm_name = strdup (param->value.str);
  787. jack_log("capture device %s", capture_pcm_name);
  788. }
  789. break;
  790. case 'P':
  791. playback = TRUE;
  792. if (strcmp (param->value.str, "none") != 0) {
  793. playback_pcm_name = strdup (param->value.str);
  794. jack_log("playback device %s", playback_pcm_name);
  795. }
  796. break;
  797. case 'D':
  798. playback = TRUE;
  799. capture = TRUE;
  800. break;
  801. case 'd':
  802. if (strcmp (param->value.str, "none") != 0) {
  803. playback_pcm_name = strdup (param->value.str);
  804. capture_pcm_name = strdup (param->value.str);
  805. jack_log("playback device %s", playback_pcm_name);
  806. jack_log("capture device %s", capture_pcm_name);
  807. }
  808. break;
  809. case 'H':
  810. hw_monitoring = param->value.i;
  811. break;
  812. case 'm':
  813. monitor = param->value.i;
  814. break;
  815. case 'M':
  816. hw_metering = param->value.i;
  817. break;
  818. case 'r':
  819. srate = param->value.ui;
  820. jack_log("apparent rate = %d", srate);
  821. break;
  822. case 'p':
  823. frames_per_interrupt = param->value.ui;
  824. jack_log("frames per period = %d", frames_per_interrupt);
  825. break;
  826. case 'n':
  827. user_nperiods = param->value.ui;
  828. if (user_nperiods < 2) { /* enforce minimum value */
  829. user_nperiods = 2;
  830. }
  831. break;
  832. case 's':
  833. soft_mode = param->value.i;
  834. break;
  835. case 'z':
  836. if (dither_opt (param->value.c, &dither)) {
  837. return NULL;
  838. }
  839. break;
  840. case 'i':
  841. user_capture_nchnls = param->value.ui;
  842. break;
  843. case 'o':
  844. user_playback_nchnls = param->value.ui;
  845. break;
  846. case 'S':
  847. shorts_first = param->value.i;
  848. break;
  849. case 'I':
  850. systemic_input_latency = param->value.ui;
  851. break;
  852. case 'O':
  853. systemic_output_latency = param->value.ui;
  854. break;
  855. case 'X':
  856. midi_driver = strdup(param->value.str);
  857. break;
  858. }
  859. }
  860. /* duplex is the default */
  861. if (!capture && !playback) {
  862. capture = TRUE;
  863. playback = TRUE;
  864. }
  865. g_alsa_driver = new Jack::JackAlsaDriver("system", "alsa_pcm", engine, table);
  866. Jack::JackDriverClientInterface* threaded_driver = new Jack::JackThreadedDriver(g_alsa_driver);
  867. // Special open for ALSA driver...
  868. if (g_alsa_driver->Open(frames_per_interrupt, user_nperiods, srate, hw_monitoring, hw_metering, capture, playback, dither, soft_mode, monitor,
  869. user_capture_nchnls, user_playback_nchnls, shorts_first, capture_pcm_name, playback_pcm_name,
  870. systemic_input_latency, systemic_output_latency, midi_driver) == 0) {
  871. return threaded_driver;
  872. } else {
  873. delete threaded_driver; // Delete the decorated driver
  874. return NULL;
  875. }
  876. }
  877. // Code to be used in alsa_driver.c
  878. void ReadInput(alsa_device_t *device, jack_nframes_t orig_nframes, snd_pcm_sframes_t contiguous, snd_pcm_sframes_t nread)
  879. {
  880. g_alsa_driver->ReadInputAux(device, orig_nframes, contiguous, nread);
  881. }
  882. void MonitorInput()
  883. {
  884. g_alsa_driver->MonitorInputAux();
  885. }
  886. void ClearOutput()
  887. {
  888. g_alsa_driver->ClearOutputAux();
  889. }
  890. void WriteOutput(alsa_device_t *device, jack_nframes_t orig_nframes, snd_pcm_sframes_t contiguous, snd_pcm_sframes_t nwritten)
  891. {
  892. g_alsa_driver->WriteOutputAux(device, orig_nframes, contiguous, nwritten);
  893. }
  894. void SetTime(jack_time_t time)
  895. {
  896. g_alsa_driver->SetTimetAux(time);
  897. }
  898. int Restart()
  899. {
  900. int res;
  901. if ((res = g_alsa_driver->Stop()) != 0) {
  902. jack_error("restart: stop driver failed");
  903. return res;
  904. }
  905. if ((res = g_alsa_driver->Start()) != 0) {
  906. jack_error("restart: start driver failed");
  907. return res;
  908. }
  909. return res;
  910. }
  911. #ifdef __cplusplus
  912. }
  913. #endif