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.

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