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.

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