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.

1205 lines
40KB

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