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.

1221 lines
41KB

  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(alsa_driver_info_t info)
  244. {
  245. // Generic JackAudioDriver Open
  246. if (JackAudioDriver::Open(
  247. info.frames_per_period,
  248. info.frame_rate,
  249. info.devices_capture_size > 0,
  250. info.devices_playback_size > 0,
  251. -1,
  252. -1,
  253. info.monitor,
  254. info.devices_capture_size > 0 ? info.devices[0].capture_name : "-",
  255. info.devices_playback_size > 0 ? info.devices[0].playback_name : "-",
  256. info.capture_latency,
  257. info.playback_latency) != 0) {
  258. return -1;
  259. }
  260. jack_log("JackAlsaDriver::Open capture_driver_name = %s", info.devices_capture_size > 0 ? info.devices[0].capture_name : "-");
  261. jack_log("JackAlsaDriver::Open playback_driver_name = %s", info.devices_playback_size > 0 ? info.devices[0].playback_name : "-");
  262. #ifndef __QNXNTO__
  263. #ifndef __ANDROID__
  264. if (strcmp(info.midi_name, "seq") == 0)
  265. info.midi_driver = alsa_seqmidi_new((jack_client_t*)this, 0);
  266. else if (strcmp(info.midi_name, "raw") == 0)
  267. info.midi_driver = alsa_rawmidi_new((jack_client_t*)this);
  268. #endif
  269. // FIXME: needs adaptation for multiple drivers
  270. if (JackServerGlobals::on_device_acquire != NULL) {
  271. int capture_card = card_to_num(info.devices_capture_size > 0 ? info.devices[0].capture_name : "-");
  272. int playback_card = card_to_num(info.devices_playback_size > 0 ? info.devices[0].playback_name : "-");
  273. char audio_name[32];
  274. if (capture_card >= 0) {
  275. snprintf(audio_name, sizeof(audio_name), "Audio%d", capture_card);
  276. if (!JackServerGlobals::on_device_acquire(audio_name)) {
  277. jack_error("Audio device %s cannot be acquired...", info.devices_capture_size > 0 ? info.devices[0].capture_name : "-");
  278. return -1;
  279. }
  280. }
  281. if (playback_card >= 0 && playback_card != capture_card) {
  282. snprintf(audio_name, sizeof(audio_name), "Audio%d", playback_card);
  283. if (!JackServerGlobals::on_device_acquire(audio_name)) {
  284. jack_error("Audio device %s cannot be acquired...",info.devices_playback_size > 0 ? info.devices[0].playback_name : "-" );
  285. if (capture_card >= 0) {
  286. snprintf(audio_name, sizeof(audio_name), "Audio%d", capture_card);
  287. JackServerGlobals::on_device_release(audio_name);
  288. }
  289. return -1;
  290. }
  291. }
  292. }
  293. #endif
  294. fDriver = alsa_driver_new ((char*)"alsa_pcm", info, NULL);
  295. if (!fDriver) {
  296. Close();
  297. return -1;
  298. }
  299. /* we need to initialize variables for all devices, mainly channels count since this is required by Jack to setup ports */
  300. UpdateDriverTargetState(DriverMode::Init);
  301. if (alsa_driver_open((alsa_driver_t *)fDriver) < 0) {
  302. Close();
  303. return -1;
  304. }
  305. /* we are starting with all alsa devices closed, therfore populate jack channels based on user hint */
  306. if (info.features & ALSA_DRIVER_FEAT_BACKEND_EVAL_ON_INIT && info.features & ALSA_DRIVER_FEAT_BACKEND_CLOSE_IDLE) {
  307. for (size_t i = 0; i < std::max(info.devices_capture_size, info.devices_playback_size); ++i) {
  308. if (i < info.devices_capture_size && info.devices[i].capture_channels < 1) {
  309. jack_error ("invalid or missing channels parameter with '-x' option 'start-closed' for device C: '%s'", info.devices[i].capture_name);
  310. Close();
  311. return -1;
  312. }
  313. if (i < info.devices_playback_size && info.devices[i].playback_channels < 1) {
  314. jack_error ("invalid or missing channels parameter with '-x' option 'start-closed' for device P: '%s'", info.devices[i].playback_name);
  315. Close();
  316. return -1;
  317. }
  318. fCaptureChannels += info.devices[i].capture_channels;
  319. fPlaybackChannels += info.devices[i].playback_channels;
  320. }
  321. /* in case we really opened alsa devices, channel information is generated by driver */
  322. } else {
  323. fCaptureChannels = ((alsa_driver_t *)fDriver)->capture_nchannels;
  324. fPlaybackChannels = ((alsa_driver_t *)fDriver)->playback_nchannels;
  325. }
  326. #ifndef __QNXNTO__
  327. if (JackServerGlobals::on_device_reservation_loop != NULL) {
  328. device_reservation_loop_running = true;
  329. if (JackPosixThread::StartImp(&fReservationLoopThread, 0, 0, on_device_reservation_loop, NULL) != 0) {
  330. device_reservation_loop_running = false;
  331. }
  332. }
  333. #endif
  334. return 0;
  335. }
  336. int JackAlsaDriver::Close()
  337. {
  338. // Generic audio driver close
  339. int res = JackAudioDriver::Close();
  340. UpdateDriverTargetState(DriverMode::Shutdown);
  341. alsa_driver_close((alsa_driver_t *)fDriver);
  342. if (fDriver) {
  343. alsa_driver_delete((alsa_driver_t*)fDriver);
  344. }
  345. #ifndef __QNXNTO__
  346. if (device_reservation_loop_running) {
  347. device_reservation_loop_running = false;
  348. JackPosixThread::StopImp(fReservationLoopThread);
  349. }
  350. // FIXME: needs adaptation for multiple drivers
  351. if (JackServerGlobals::on_device_release != NULL)
  352. {
  353. char audio_name[32];
  354. int capture_card = card_to_num(fCaptureDriverName);
  355. if (capture_card >= 0) {
  356. snprintf(audio_name, sizeof(audio_name), "Audio%d", capture_card);
  357. JackServerGlobals::on_device_release(audio_name);
  358. }
  359. int playback_card = card_to_num(fPlaybackDriverName);
  360. if (playback_card >= 0 && playback_card != capture_card) {
  361. snprintf(audio_name, sizeof(audio_name), "Audio%d", playback_card);
  362. JackServerGlobals::on_device_release(audio_name);
  363. }
  364. }
  365. #endif
  366. return res;
  367. }
  368. int JackAlsaDriver::Start()
  369. {
  370. int res = JackAudioDriver::Start();
  371. if (res >= 0) {
  372. res = alsa_driver_start((alsa_driver_t *)fDriver);
  373. if (res < 0) {
  374. JackAudioDriver::Stop();
  375. }
  376. }
  377. return res;
  378. }
  379. int JackAlsaDriver::Stop()
  380. {
  381. int res = alsa_driver_stop((alsa_driver_t *)fDriver);
  382. if (JackAudioDriver::Stop() < 0) {
  383. res = -1;
  384. }
  385. return res;
  386. }
  387. int JackAlsaDriver::Reload()
  388. {
  389. UpdateDriverTargetState(DriverMode::Runtime);
  390. alsa_driver_t* driver = (alsa_driver_t*) fDriver;
  391. if (alsa_driver_close (driver) < 0) {
  392. jack_error("JackAlsaDriver::Reload close failed");
  393. return -1;
  394. }
  395. if (alsa_driver_open (driver) < 0) {
  396. jack_error("JackAlsaDriver::Reload open failed");
  397. return -1;
  398. }
  399. return 0;
  400. }
  401. int JackAlsaDriver::Read()
  402. {
  403. /* Taken from alsa_driver_run_cycle */
  404. alsa_driver_wait_status_t wait_status;
  405. jack_nframes_t nframes = 0;
  406. fDelayedUsecs = 0.f;
  407. /* wait until all devices have some data available */
  408. do {
  409. nframes = alsa_driver_wait((alsa_driver_t *)fDriver, -1, &wait_status, &fDelayedUsecs);
  410. if (wait_status != ALSA_DRIVER_WAIT_OK) {
  411. jack_error("JackAlsaDriver::Read wait failed, xrun recovery");
  412. goto retry;
  413. }
  414. } while (nframes == 0);
  415. if (nframes != fEngineControl->fBufferSize)
  416. jack_log("JackAlsaDriver::Read warning fBufferSize = %ld nframes = %ld", fEngineControl->fBufferSize, nframes);
  417. // Has to be done before read
  418. JackDriver::CycleIncTime();
  419. if (alsa_driver_read((alsa_driver_t *)fDriver, fEngineControl->fBufferSize) != 0) {
  420. jack_error("JackAlsaDriver::Read read failed, xrun recovery");
  421. goto retry;
  422. }
  423. return 0;
  424. retry:
  425. /* we detected an xrun and restarted: notify
  426. * clients about the delay.
  427. */
  428. jack_error("JackAlsaDriver::Read failed, xrun recovery");
  429. alsa_driver_xrun_recovery((alsa_driver_t *)fDriver, &fDelayedUsecs);
  430. NotifyXRun(fBeginDateUst, fDelayedUsecs);
  431. return -1;
  432. }
  433. int JackAlsaDriver::Write()
  434. {
  435. if (alsa_driver_write((alsa_driver_t *)fDriver, fEngineControl->fBufferSize) != 0) {
  436. jack_error("JackAlsaDriver::Write failed, xrun recovery");
  437. alsa_driver_xrun_recovery((alsa_driver_t *)fDriver, &fDelayedUsecs);
  438. NotifyXRun(fBeginDateUst, fDelayedUsecs);
  439. return -1;
  440. }
  441. return 0;
  442. }
  443. void JackAlsaDriver::ReadInputAux(alsa_device_t *device, jack_nframes_t orig_nframes, snd_pcm_sframes_t contiguous, snd_pcm_sframes_t nread)
  444. {
  445. /* global channel offset to fCapturePortList of this capture alsa device */
  446. channel_t port_n = device->capture_channel_offset;
  447. for (channel_t chn = 0; chn < device->capture_nchannels; ++chn, ++port_n) {
  448. if (fGraphManager->GetConnectionsNum(fCapturePortList[port_n]) > 0) {
  449. jack_default_audio_sample_t* buf = (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fCapturePortList[port_n], orig_nframes);
  450. alsa_driver_read_from_channel((alsa_driver_t *)fDriver, device, chn, buf + nread, contiguous);
  451. }
  452. }
  453. }
  454. void JackAlsaDriver::MonitorInputAux()
  455. {
  456. for (int chn = 0; chn < fCaptureChannels; chn++) {
  457. JackPort* port = fGraphManager->GetPort(fCapturePortList[chn]);
  458. if (port->MonitoringInput()) {
  459. ((alsa_driver_t *)fDriver)->input_monitor_mask |= (1 << chn);
  460. }
  461. }
  462. }
  463. void JackAlsaDriver::ClearOutputAux()
  464. {
  465. for (int chn = 0; chn < fPlaybackChannels; chn++) {
  466. jack_default_audio_sample_t* buf =
  467. (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fPlaybackPortList[chn], fEngineControl->fBufferSize);
  468. memset(buf, 0, sizeof (jack_default_audio_sample_t) * fEngineControl->fBufferSize);
  469. }
  470. }
  471. void JackAlsaDriver::SetTimetAux(jack_time_t time)
  472. {
  473. fBeginDateUst = time;
  474. }
  475. int JackAlsaDriver::PortSetDefaultMetadata(jack_port_id_t port_id, const char* pretty_name)
  476. {
  477. return fEngine->PortSetDefaultMetadata(fClientControl.fRefNum, port_id, pretty_name);
  478. }
  479. int JackAlsaDriver::UpdateDriverTargetState(DriverMode mode)
  480. {
  481. int c_list_index = 0, p_list_index = 0;
  482. alsa_driver_t* driver = (alsa_driver_t*) fDriver;
  483. for (int i = 0; i < driver->devices_count; ++i) {
  484. alsa_device_t *device = &driver->devices[i];
  485. int capture_connections_count = 0;
  486. for (int j = 0; j < device->capture_nchannels; ++j) {
  487. capture_connections_count += fGraphManager->GetConnectionsNum(fCapturePortList[c_list_index]);
  488. c_list_index++;
  489. }
  490. device->capture_target_state = TargetState(mode, capture_connections_count);
  491. int playback_connections_count = 0;
  492. for (int j = 0; j < device->playback_nchannels; ++j) {
  493. playback_connections_count += fGraphManager->GetConnectionsNum(fPlaybackPortList[p_list_index]);
  494. p_list_index++;
  495. }
  496. device->playback_target_state = TargetState(mode, playback_connections_count);
  497. }
  498. return 0;
  499. }
  500. int JackAlsaDriver::TargetState(DriverMode mode, int connections_count)
  501. {
  502. alsa_driver_t* driver = (alsa_driver_t*) fDriver;
  503. if (mode == DriverMode::Shutdown) {
  504. return SND_PCM_STATE_NOTREADY;
  505. }
  506. if (connections_count > 0) {
  507. return SND_PCM_STATE_RUNNING;
  508. }
  509. // evaluation during init is disabled by user option
  510. if (mode == DriverMode::Init && !(driver->features & ALSA_DRIVER_FEAT_BACKEND_EVAL_ON_INIT)) {
  511. return SND_PCM_STATE_RUNNING;
  512. }
  513. if (driver->features & ALSA_DRIVER_FEAT_BACKEND_CLOSE_IDLE) {
  514. return SND_PCM_STATE_NOTREADY;
  515. }
  516. return SND_PCM_STATE_PREPARED;
  517. }
  518. void JackAlsaDriver::WriteOutputAux(alsa_device_t *device, jack_nframes_t orig_nframes, snd_pcm_sframes_t contiguous, snd_pcm_sframes_t nwritten)
  519. {
  520. /* global channel offset to fPlaybackPortList of this playback alsa device */
  521. channel_t port_n = device->playback_channel_offset;
  522. for (channel_t chn = 0; chn < device->playback_nchannels; ++chn, ++port_n) {
  523. // Output ports
  524. if (fGraphManager->GetConnectionsNum(fPlaybackPortList[port_n]) > 0) {
  525. jack_default_audio_sample_t* buf = (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fPlaybackPortList[port_n], orig_nframes);
  526. alsa_driver_write_to_channel(((alsa_driver_t *)fDriver), device, chn, buf + nwritten, contiguous);
  527. // Monitor ports
  528. if (fWithMonitorPorts && fGraphManager->GetConnectionsNum(fMonitorPortList[port_n]) > 0) {
  529. jack_default_audio_sample_t* monbuf = (jack_default_audio_sample_t*)fGraphManager->GetBuffer(fMonitorPortList[port_n], orig_nframes);
  530. memcpy(monbuf + nwritten, buf + nwritten, contiguous * sizeof(jack_default_audio_sample_t));
  531. }
  532. }
  533. }
  534. }
  535. int JackAlsaDriver::is_realtime() const
  536. {
  537. return fEngineControl->fRealTime;
  538. }
  539. int JackAlsaDriver::create_thread(pthread_t *thread, int priority, int realtime, void *(*start_routine)(void*), void *arg)
  540. {
  541. #ifdef __ANDROID__
  542. return JackAndroidThread::StartImp(thread, priority, realtime, start_routine, arg);
  543. #else
  544. return JackPosixThread::StartImp(thread, priority, realtime, start_routine, arg);
  545. #endif
  546. }
  547. jack_port_id_t JackAlsaDriver::port_register(const char *port_name, const char *port_type, unsigned long flags, unsigned long buffer_size)
  548. {
  549. jack_port_id_t port_index;
  550. int res = fEngine->PortRegister(fClientControl.fRefNum, port_name, port_type, flags, buffer_size, &port_index);
  551. return (res == 0) ? port_index : 0;
  552. }
  553. int JackAlsaDriver::port_unregister(jack_port_id_t port_index)
  554. {
  555. return fEngine->PortUnRegister(fClientControl.fRefNum, port_index);
  556. }
  557. void* JackAlsaDriver::port_get_buffer(int port, jack_nframes_t nframes)
  558. {
  559. return fGraphManager->GetBuffer(port, nframes);
  560. }
  561. int JackAlsaDriver::port_set_alias(int port, const char* name)
  562. {
  563. return fGraphManager->GetPort(port)->SetAlias(name);
  564. }
  565. jack_nframes_t JackAlsaDriver::get_sample_rate() const
  566. {
  567. return fEngineControl->fSampleRate;
  568. }
  569. jack_nframes_t JackAlsaDriver::frame_time() const
  570. {
  571. JackTimer timer;
  572. fEngineControl->ReadFrameTime(&timer);
  573. return timer.Time2Frames(GetMicroSeconds(), fEngineControl->fBufferSize);
  574. }
  575. jack_nframes_t JackAlsaDriver::last_frame_time() const
  576. {
  577. JackTimer timer;
  578. fEngineControl->ReadFrameTime(&timer);
  579. return timer.CurFrame();
  580. }
  581. } // end of namespace
  582. #ifdef __cplusplus
  583. extern "C"
  584. {
  585. #endif
  586. #ifndef __QNXNTO__
  587. static
  588. jack_driver_param_constraint_desc_t *
  589. enum_alsa_devices()
  590. {
  591. snd_ctl_t * handle;
  592. snd_ctl_card_info_t * info;
  593. snd_pcm_info_t * pcminfo_capture;
  594. snd_pcm_info_t * pcminfo_playback;
  595. int card_no = -1;
  596. jack_driver_param_value_t card_id;
  597. jack_driver_param_value_t device_id;
  598. char description[64];
  599. int device_no;
  600. bool has_capture;
  601. bool has_playback;
  602. jack_driver_param_constraint_desc_t * constraint_ptr;
  603. uint32_t array_size = 0;
  604. snd_ctl_card_info_alloca(&info);
  605. snd_pcm_info_alloca(&pcminfo_capture);
  606. snd_pcm_info_alloca(&pcminfo_playback);
  607. constraint_ptr = NULL;
  608. while(snd_card_next(&card_no) >= 0 && card_no >= 0)
  609. {
  610. snprintf(card_id.str, sizeof(card_id.str), "hw:%d", card_no);
  611. if (snd_ctl_open(&handle, card_id.str, 0) >= 0 &&
  612. snd_ctl_card_info(handle, info) >= 0)
  613. {
  614. snprintf(card_id.str, sizeof(card_id.str), "hw:%s", snd_ctl_card_info_get_id(info));
  615. if (!jack_constraint_add_enum(
  616. &constraint_ptr,
  617. &array_size,
  618. &card_id,
  619. snd_ctl_card_info_get_name(info)))
  620. goto fail;
  621. device_no = -1;
  622. while (snd_ctl_pcm_next_device(handle, &device_no) >= 0 && device_no != -1)
  623. {
  624. snprintf(device_id.str, sizeof(device_id.str), "%s,%d", card_id.str, device_no);
  625. snd_pcm_info_set_device(pcminfo_capture, device_no);
  626. snd_pcm_info_set_subdevice(pcminfo_capture, 0);
  627. snd_pcm_info_set_stream(pcminfo_capture, SND_PCM_STREAM_CAPTURE);
  628. has_capture = snd_ctl_pcm_info(handle, pcminfo_capture) >= 0;
  629. snd_pcm_info_set_device(pcminfo_playback, device_no);
  630. snd_pcm_info_set_subdevice(pcminfo_playback, 0);
  631. snd_pcm_info_set_stream(pcminfo_playback, SND_PCM_STREAM_PLAYBACK);
  632. has_playback = snd_ctl_pcm_info(handle, pcminfo_playback) >= 0;
  633. if (has_capture && has_playback)
  634. {
  635. snprintf(description, sizeof(description),"%s (duplex)", snd_pcm_info_get_name(pcminfo_capture));
  636. }
  637. else if (has_capture)
  638. {
  639. snprintf(description, sizeof(description),"%s (capture)", snd_pcm_info_get_name(pcminfo_capture));
  640. }
  641. else if (has_playback)
  642. {
  643. snprintf(description, sizeof(description),"%s (playback)", snd_pcm_info_get_name(pcminfo_playback));
  644. }
  645. else
  646. {
  647. continue;
  648. }
  649. if (!jack_constraint_add_enum(
  650. &constraint_ptr,
  651. &array_size,
  652. &device_id,
  653. description))
  654. goto fail;
  655. }
  656. snd_ctl_close(handle);
  657. }
  658. }
  659. return constraint_ptr;
  660. fail:
  661. jack_constraint_free(constraint_ptr);
  662. return NULL;
  663. }
  664. #endif
  665. static int
  666. dither_opt (char c, DitherAlgorithm* dither)
  667. {
  668. switch (c) {
  669. case '-':
  670. case 'n':
  671. *dither = None;
  672. break;
  673. case 'r':
  674. *dither = Rectangular;
  675. break;
  676. case 's':
  677. *dither = Shaped;
  678. break;
  679. case 't':
  680. *dither = Triangular;
  681. break;
  682. default:
  683. fprintf (stderr, "ALSA driver: illegal dithering mode %c\n", c);
  684. return -1;
  685. }
  686. return 0;
  687. }
  688. SERVER_EXPORT const jack_driver_desc_t* driver_get_descriptor ()
  689. {
  690. jack_driver_desc_t * desc;
  691. jack_driver_desc_filler_t filler;
  692. jack_driver_param_value_t value;
  693. desc = jack_driver_descriptor_construct("alsa", JackDriverMaster, "Linux ALSA API based audio backend", &filler);
  694. strcpy(value.str, "hw:0");
  695. #ifndef __QNXNTO__
  696. #ifdef __ANDROID__
  697. jack_driver_descriptor_add_parameter(desc, &filler, "device", 'd', JackDriverParamString, &value, NULL, "ALSA device name", NULL);
  698. #else
  699. jack_driver_descriptor_add_parameter(desc, &filler, "device", 'd', JackDriverParamString, &value, enum_alsa_devices(), "ALSA device name", NULL);
  700. #endif
  701. #endif
  702. strcpy(value.str, "none");
  703. jack_driver_descriptor_add_parameter(desc, &filler, "capture", 'C', JackDriverParamString, &value, NULL, "Provide capture ports. Optionally set device", NULL);
  704. jack_driver_descriptor_add_parameter(desc, &filler, "playback", 'P', JackDriverParamString, &value, NULL, "Provide playback ports. Optionally set device", NULL);
  705. value.ui = 48000U;
  706. jack_driver_descriptor_add_parameter(desc, &filler, "rate", 'r', JackDriverParamUInt, &value, NULL, "Sample rate", NULL);
  707. value.ui = 1024U;
  708. jack_driver_descriptor_add_parameter(desc, &filler, "period", 'p', JackDriverParamUInt, &value, NULL, "Frames per period", NULL);
  709. value.ui = 2U;
  710. jack_driver_descriptor_add_parameter(desc, &filler, "nperiods", 'n', JackDriverParamUInt, &value, NULL, "Number of periods of playback latency", NULL);
  711. value.i = 0;
  712. jack_driver_descriptor_add_parameter(desc, &filler, "hwmon", 'H', JackDriverParamBool, &value, NULL, "Hardware monitoring, if available", NULL);
  713. value.i = 0;
  714. jack_driver_descriptor_add_parameter(desc, &filler, "hwmeter", 'M', JackDriverParamBool, &value, NULL, "Hardware metering, if available", NULL);
  715. value.i = 1;
  716. jack_driver_descriptor_add_parameter(desc, &filler, "duplex", 'D', JackDriverParamBool, &value, NULL, "Provide both capture and playback ports", NULL);
  717. value.i = 0;
  718. jack_driver_descriptor_add_parameter(desc, &filler, "softmode", 's', JackDriverParamBool, &value, NULL, "Soft-mode, no xrun handling", NULL);
  719. value.i = 0;
  720. jack_driver_descriptor_add_parameter(desc, &filler, "monitor", 'm', JackDriverParamBool, &value, NULL, "Provide monitor ports for the output", NULL);
  721. value.c = 'n';
  722. jack_driver_descriptor_add_parameter(
  723. desc,
  724. &filler,
  725. "dither",
  726. 'z',
  727. JackDriverParamChar,
  728. &value,
  729. jack_constraint_compose_enum_char(
  730. JACK_CONSTRAINT_FLAG_STRICT | JACK_CONSTRAINT_FLAG_FAKE_VALUE,
  731. dither_constraint_descr_array),
  732. "Dithering mode",
  733. NULL);
  734. strcpy(value.str, "none");
  735. jack_driver_descriptor_add_parameter(desc, &filler, "inchannels", 'i', JackDriverParamString, &value, NULL, "List of device capture channels (defaults to hw max)", NULL);
  736. jack_driver_descriptor_add_parameter(desc, &filler, "outchannels", 'o', JackDriverParamString, &value, NULL, "List of device playback channels (defaults to hw max)", NULL);
  737. value.i = FALSE;
  738. jack_driver_descriptor_add_parameter(desc, &filler, "shorts", 'S', JackDriverParamBool, &value, NULL, "Try 16-bit samples before 32-bit", NULL);
  739. value.ui = 0;
  740. jack_driver_descriptor_add_parameter(desc, &filler, "input-latency", 'I', JackDriverParamUInt, &value, NULL, "Extra input latency (frames)", NULL);
  741. jack_driver_descriptor_add_parameter(desc, &filler, "output-latency", 'O', JackDriverParamUInt, &value, NULL, "Extra output latency (frames)", NULL);
  742. strcpy(value.str, "none");
  743. jack_driver_descriptor_add_parameter(
  744. desc,
  745. &filler,
  746. "midi-driver",
  747. 'X',
  748. JackDriverParamString,
  749. &value,
  750. jack_constraint_compose_enum_str(
  751. JACK_CONSTRAINT_FLAG_STRICT | JACK_CONSTRAINT_FLAG_FAKE_VALUE,
  752. midi_constraint_descr_array),
  753. "ALSA MIDI driver",
  754. NULL);
  755. value.i = 0;
  756. jack_driver_descriptor_add_parameter(desc, &filler, "eval-on-init", 'x', JackDriverParamBool, &value, NULL, "Do not start ALSA devices on jack startup", NULL);
  757. value.i = 0;
  758. jack_driver_descriptor_add_parameter(desc, &filler, "close-idle", 'c', JackDriverParamBool, &value, NULL, "Close idle devices on alsa driver restart request", NULL);
  759. value.i = 0;
  760. jack_driver_descriptor_add_parameter(desc, &filler, "unlinked-devs", 'u', JackDriverParamBool, &value, NULL, "Do not link devices", NULL);
  761. return desc;
  762. }
  763. struct array_string_t
  764. {
  765. enum flags {
  766. none,
  767. discard_duplicate,
  768. };
  769. std::vector<char*> data;
  770. };
  771. void array_string_free(struct array_string_t *obj)
  772. {
  773. if (obj == NULL) {
  774. return;
  775. }
  776. for (size_t i = 0; i < obj->data.size(); ++i) {
  777. free(obj->data[i]);
  778. }
  779. }
  780. struct array_string_t array_string_split(const char *str, const char sep, array_string_t::flags flags = array_string_t::none)
  781. {
  782. struct array_string_t result;
  783. std::stringstream stream;
  784. stream << std::string(str);
  785. if (stream.str().find(sep) == std::string::npos) {
  786. result.data.push_back((char*) calloc(JACK_CLIENT_NAME_SIZE + 1, sizeof(char)));
  787. strncpy(result.data[0], str, JACK_CLIENT_NAME_SIZE);
  788. result.data[0][JACK_CLIENT_NAME_SIZE] = '\0';
  789. return result;
  790. }
  791. std::string driver;
  792. while (std::getline(stream, driver, sep)) {
  793. driver.erase(std::remove_if(driver.begin(), driver.end(), isspace), driver.end());
  794. if (std::find(result.data.begin(), result.data.end(), driver) != result.data.end() && (flags & array_string_t::discard_duplicate))
  795. continue;
  796. char *str = (char*) calloc(JACK_CLIENT_NAME_SIZE + 1, sizeof(char));
  797. strncpy(str, driver.c_str(), JACK_CLIENT_NAME_SIZE);
  798. str[JACK_CLIENT_NAME_SIZE] = '\0';
  799. result.data.push_back(str);
  800. }
  801. return result;
  802. }
  803. static Jack::JackAlsaDriver* g_alsa_driver;
  804. SERVER_EXPORT Jack::JackDriverClientInterface* driver_initialize(Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params)
  805. {
  806. const JSList * node;
  807. const jack_driver_param_t * param;
  808. alsa_driver_info_t info = {};
  809. info.devices = NULL;
  810. info.midi_name = strdup("none");
  811. info.hw_monitoring = FALSE;
  812. info.hw_metering = FALSE;
  813. info.monitor = FALSE;
  814. info.soft_mode = FALSE;
  815. info.frame_rate = 48000;
  816. info.frames_per_period = 1024;
  817. info.periods_n = 2;
  818. info.dither = None;
  819. info.shorts_first = FALSE;
  820. info.capture_latency = 0;
  821. info.playback_latency = 0;
  822. char *capture_names_param = NULL;
  823. char *playback_names_param = NULL;
  824. char *capture_channels_param = NULL;
  825. char *playback_channels_param = NULL;
  826. int duplex = FALSE;
  827. for (node = params; node; node = jack_slist_next (node)) {
  828. param = (const jack_driver_param_t *) node->data;
  829. switch (param->character) {
  830. case 'C':
  831. if (strcmp (param->value.str, "none") != 0) {
  832. capture_names_param = strdup (param->value.str);
  833. jack_log("capture device %s", capture_names_param);
  834. }
  835. break;
  836. case 'P':
  837. if (strcmp (param->value.str, "none") != 0) {
  838. playback_names_param = strdup (param->value.str);
  839. jack_log("playback device %s", playback_names_param);
  840. }
  841. break;
  842. case 'D':
  843. duplex = TRUE;
  844. break;
  845. case 'd':
  846. if (strcmp (param->value.str, "none") != 0) {
  847. playback_names_param = strdup (param->value.str);
  848. capture_names_param = strdup (param->value.str);
  849. jack_log("playback device %s", playback_names_param);
  850. jack_log("capture device %s", capture_names_param);
  851. }
  852. break;
  853. case 'H':
  854. info.hw_monitoring = param->value.i;
  855. break;
  856. case 'm':
  857. info.monitor = param->value.i;
  858. break;
  859. case 'M':
  860. info.hw_metering = param->value.i;
  861. break;
  862. case 'r':
  863. info.frame_rate = param->value.ui;
  864. jack_log("apparent rate = %d", info.frame_rate);
  865. break;
  866. case 'p':
  867. info.frames_per_period = param->value.ui;
  868. jack_log("frames per period = %d", info.frames_per_period);
  869. break;
  870. case 'n':
  871. info.periods_n = param->value.ui;
  872. if (info.periods_n < 2) { /* enforce minimum value */
  873. info.periods_n = 2;
  874. }
  875. break;
  876. case 's':
  877. info.soft_mode = param->value.i;
  878. break;
  879. case 'z':
  880. if (dither_opt (param->value.c, &info.dither)) {
  881. return NULL;
  882. }
  883. break;
  884. case 'i':
  885. capture_channels_param = strdup(param->value.str);
  886. break;
  887. case 'o':
  888. playback_channels_param = strdup(param->value.str);
  889. break;
  890. case 'S':
  891. info.shorts_first = param->value.i;
  892. break;
  893. case 'I':
  894. info.capture_latency = param->value.ui;
  895. break;
  896. case 'O':
  897. info.playback_latency = param->value.ui;
  898. break;
  899. case 'X':
  900. free(info.midi_name);
  901. info.midi_name = strdup(param->value.str);
  902. break;
  903. case 'x':
  904. info.features |= param->value.i ? ALSA_DRIVER_FEAT_BACKEND_EVAL_ON_INIT : 0;
  905. break;
  906. case 'c':
  907. info.features |= param->value.i ? ALSA_DRIVER_FEAT_BACKEND_CLOSE_IDLE : 0;
  908. break;
  909. case 'u':
  910. info.features |= param->value.i ? ALSA_DRIVER_FEAT_UNLINKED_DEVS : 0;
  911. break;
  912. }
  913. }
  914. /* duplex is the default */
  915. if (!capture_names_param && !playback_names_param) {
  916. duplex = TRUE;
  917. }
  918. if (duplex) {
  919. if (!capture_names_param) {
  920. capture_names_param = strdup("hw:0");
  921. }
  922. if (!playback_names_param) {
  923. playback_names_param = strdup("hw:0");
  924. }
  925. }
  926. struct array_string_t capture_names = {};
  927. if (capture_names_param) {
  928. capture_names = array_string_split(capture_names_param, ' ', array_string_t::discard_duplicate);
  929. free(capture_names_param);
  930. }
  931. struct array_string_t playback_names = {};
  932. if (playback_names_param) {
  933. playback_names = array_string_split(playback_names_param, ' ', array_string_t::discard_duplicate);
  934. free(playback_names_param);
  935. }
  936. struct array_string_t capture_channels = {};
  937. if (capture_channels_param) {
  938. capture_channels = array_string_split(capture_channels_param, ' ');
  939. free(capture_channels_param);
  940. }
  941. struct array_string_t playback_channels = {};
  942. if (playback_channels_param) {
  943. playback_channels = array_string_split(playback_channels_param, ' ');
  944. free(playback_channels_param);
  945. }
  946. info.devices_capture_size = capture_names.data.size();
  947. info.devices_playback_size = playback_names.data.size();
  948. info.devices = (alsa_device_info_t*) calloc(std::max(info.devices_capture_size, info.devices_playback_size), sizeof(alsa_device_info_t));
  949. for (size_t i = 0; i < std::max(info.devices_capture_size, info.devices_playback_size); ++i) {
  950. if (i < capture_names.data.size()) {
  951. info.devices[i].capture_name = strdup(capture_names.data[i]);
  952. }
  953. if (i < capture_channels.data.size()) {
  954. info.devices[i].capture_channels = atoi(capture_channels.data[i]);
  955. }
  956. if (i < playback_names.data.size()) {
  957. info.devices[i].playback_name = strdup(playback_names.data[i]);
  958. }
  959. if (i < playback_channels.data.size()) {
  960. info.devices[i].playback_channels = atoi(playback_channels.data[i]);
  961. }
  962. }
  963. array_string_free(&capture_names);
  964. array_string_free(&playback_names);
  965. array_string_free(&capture_channels);
  966. array_string_free(&playback_channels);
  967. g_alsa_driver = new Jack::JackAlsaDriver("system", "alsa_pcm", engine, table);
  968. Jack::JackDriverClientInterface* threaded_driver = new Jack::JackThreadedDriver(g_alsa_driver);
  969. // Special open for ALSA driver...
  970. if (g_alsa_driver->Open(info) == 0) {
  971. return threaded_driver;
  972. } else {
  973. delete threaded_driver; // Delete the decorated driver
  974. return NULL;
  975. }
  976. }
  977. // Code to be used in alsa_driver.c
  978. void ReadInput(alsa_device_t *device, jack_nframes_t orig_nframes, snd_pcm_sframes_t contiguous, snd_pcm_sframes_t nread)
  979. {
  980. g_alsa_driver->ReadInputAux(device, orig_nframes, contiguous, nread);
  981. }
  982. void MonitorInput()
  983. {
  984. g_alsa_driver->MonitorInputAux();
  985. }
  986. void ClearOutput()
  987. {
  988. g_alsa_driver->ClearOutputAux();
  989. }
  990. void WriteOutput(alsa_device_t *device, jack_nframes_t orig_nframes, snd_pcm_sframes_t contiguous, snd_pcm_sframes_t nwritten)
  991. {
  992. g_alsa_driver->WriteOutputAux(device, orig_nframes, contiguous, nwritten);
  993. }
  994. void SetTime(jack_time_t time)
  995. {
  996. g_alsa_driver->SetTimetAux(time);
  997. }
  998. int Restart()
  999. {
  1000. int res;
  1001. if ((res = g_alsa_driver->Stop()) != 0) {
  1002. jack_error("restart: stop driver failed");
  1003. return res;
  1004. }
  1005. if ((res = g_alsa_driver->Start()) != 0) {
  1006. jack_error("restart: start driver failed");
  1007. return res;
  1008. }
  1009. return res;
  1010. }
  1011. #ifdef __cplusplus
  1012. }
  1013. #endif