JACK tools
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.

529 lines
13KB

  1. // ----------------------------------------------------------------------------
  2. //
  3. // Copyright (C) 2012 Fons Adriaensen <fons@linuxaudio.org>
  4. //
  5. // This program is free software; you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License as published by
  7. // the Free Software Foundation; either version 3 of the License, or
  8. // (at your option) any later version.
  9. //
  10. // This program is distributed in the hope that it will be useful,
  11. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. // GNU General Public License for more details.
  14. //
  15. // You should have received a copy of the GNU General Public License
  16. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. //
  18. // ----------------------------------------------------------------------------
  19. #include <iostream>
  20. #include <stdio.h>
  21. #include <math.h>
  22. #include <jack/thread.h>
  23. #include "jackclient.h"
  24. #include "alsathread.h"
  25. Jackclient::Jackclient (jack_client_t* cl, const char*jserv, int mode, int nchan, void *arg) :
  26. _client (cl),
  27. _arg (arg),
  28. _mode (mode),
  29. _nchan (nchan),
  30. _state (INIT),
  31. _freew (false)
  32. {
  33. init (jserv);
  34. }
  35. Jackclient::~Jackclient (void)
  36. {
  37. fini ();
  38. }
  39. void Jackclient::init (const char *jserv)
  40. {
  41. int spol;
  42. jack_status_t stat;
  43. struct sched_param spar;
  44. if (_client == 0)
  45. {
  46. return;
  47. }
  48. jack_set_process_callback (_client, jack_static_process, (void *) this);
  49. jack_set_latency_callback (_client, jack_static_latency, (void *) this);
  50. jack_set_freewheel_callback (_client, jack_static_freewheel, (void *) this);
  51. jack_set_buffer_size_callback (_client, jack_static_buffsize, (void *) this);
  52. jack_on_shutdown (_client, jack_static_shutdown, (void *) this);
  53. _bsize = 0;
  54. _fsamp = 0;
  55. _jname = jack_get_client_name (_client);
  56. _bsize = jack_get_buffer_size (_client);
  57. _fsamp = jack_get_sample_rate (_client);
  58. if (_nchan)
  59. {
  60. register_ports (_nchan);
  61. }
  62. _rprio = jack_client_real_time_priority (_client);
  63. }
  64. void Jackclient::register_ports (int n)
  65. {
  66. int i, flags;
  67. char s [64];
  68. if (n > sizeof (_ports) / sizeof (_ports[0]))
  69. {
  70. return;
  71. }
  72. flags = JackPortIsTerminal | JackPortIsPhysical;
  73. for (i = 0; i < n; i++)
  74. {
  75. if (_mode == PLAY)
  76. {
  77. sprintf (s, "playback_%d", i + 1);
  78. _ports [i] = jack_port_register (_client, s, JACK_DEFAULT_AUDIO_TYPE,
  79. flags | JackPortIsInput, 0);
  80. }
  81. else
  82. {
  83. sprintf (s, "capture_%d", i + 1);
  84. _ports [i] = jack_port_register (_client, s, JACK_DEFAULT_AUDIO_TYPE,
  85. flags | JackPortIsOutput, 0);
  86. }
  87. }
  88. _nchan = n;
  89. _buff = new float [_bsize * _nchan];
  90. }
  91. void Jackclient::fini (void)
  92. {
  93. delete[] _buff;
  94. }
  95. void Jackclient::jack_static_shutdown (void *arg)
  96. {
  97. ((Jackclient *) arg)->sendinfo (TERM, 0, 0);
  98. }
  99. int Jackclient::jack_static_buffsize (jack_nframes_t nframes, void *arg)
  100. {
  101. Jackclient *J = (Jackclient *) arg;
  102. if (J->_bsize == 0) J->_bsize = nframes;
  103. else if (J->_bsize != (int) nframes) J->_state = Jackclient::TERM;
  104. return 0;
  105. }
  106. void Jackclient::jack_static_freewheel (int state, void *arg)
  107. {
  108. ((Jackclient *) arg)->jack_freewheel (state);
  109. }
  110. void Jackclient::jack_static_latency (jack_latency_callback_mode_t jlcm, void *arg)
  111. {
  112. ((Jackclient *) arg)->jack_latency (jlcm);
  113. }
  114. int Jackclient::jack_static_process (jack_nframes_t nframes, void *arg)
  115. {
  116. return ((Jackclient *) arg)->jack_process (nframes);
  117. }
  118. void Jackclient::start (Lfq_audio *audioq,
  119. Lfq_int32 *commq,
  120. Lfq_adata *alsaq,
  121. Lfq_jdata *infoq,
  122. double ratio,
  123. int delay,
  124. int ltcor,
  125. int rqual)
  126. {
  127. double d;
  128. _audioq = audioq;
  129. _commq = commq;
  130. _alsaq = alsaq;
  131. _infoq = infoq;
  132. _quant = ldexp (1e-6f, 28);
  133. _ratio = ratio;
  134. _rcorr = 1.0;
  135. _resamp.setup (_ratio, _nchan, rqual);
  136. _resamp.set_rrfilt (100);
  137. d = _resamp.inpsize () / 2.0;
  138. if (_mode == PLAY) d *= _ratio;
  139. _delay = delay + d;
  140. _ltcor = ltcor;
  141. _ppsec = (_fsamp + _bsize / 2) / _bsize;
  142. if (jack_activate (_client))
  143. {
  144. fprintf(stderr, "Can't activate Jack");
  145. return;
  146. }
  147. initwait (_ppsec / 2);
  148. jack_recompute_total_latencies (_client);
  149. }
  150. void Jackclient::initwait (int nwait)
  151. {
  152. _count = -nwait;
  153. _commq->wr_int32 (Alsathread::WAIT);
  154. _state = WAIT;
  155. if (nwait > _ppsec) sendinfo (WAIT, 0, 0);
  156. }
  157. void Jackclient::initsync (void)
  158. {
  159. // Reset all lock-free queues.
  160. _commq->reset ();
  161. _alsaq->reset ();
  162. _audioq->reset ();
  163. // Reset and prefill the resampler.
  164. _resamp.reset ();
  165. _resamp.inp_count = _resamp.inpsize () / 2 - 1;
  166. _resamp.out_count = 10000;
  167. _resamp.process ();
  168. // Initiliase state variables.
  169. _t_a0 = _t_a1 = 0;
  170. _k_a0 = _k_a1 = 0;
  171. _k_j0 = 0;
  172. // Initialise loop filter state.
  173. _z1 = _z2 = _z3 = 0;
  174. // Activate the ALSA thread,
  175. _commq->wr_int32 (Alsathread::PROC);
  176. _state = SYNC0;
  177. sendinfo (SYNC0, 0, 0);
  178. }
  179. void Jackclient::setloop (double bw)
  180. {
  181. double w;
  182. // Set the loop bandwidth to bw Hz.
  183. w = 6.28f * 20 * bw * _bsize / _fsamp;
  184. _w0 = 1.0 - exp (-w);
  185. w = 6.28f * bw * _ratio / _fsamp;
  186. _w1 = w * 1.6;
  187. _w2 = w * _bsize / 1.6;
  188. }
  189. void Jackclient::playback (int nframes)
  190. {
  191. int i, j, n;
  192. float *p, *q;
  193. // Interleave inputs into _buff.
  194. for (i = 0; i < _nchan; i++)
  195. {
  196. p = (float *)(jack_port_get_buffer (_ports [i], nframes));
  197. q = _buff + i;
  198. for (j = 0; j < _bsize; j++) q [j * _nchan] = p [j];
  199. }
  200. // Resample _buff and write to audio queue.
  201. // The while loop takes care of wraparound.
  202. _resamp.inp_count = _bsize;
  203. _resamp.inp_data = _buff;
  204. while (_resamp.inp_count)
  205. {
  206. _resamp.out_count = _audioq->wr_linav ();
  207. _resamp.out_data = _audioq->wr_datap ();
  208. n = _resamp.out_count;
  209. _resamp.process ();
  210. n -= _resamp.out_count;
  211. _audioq->wr_commit (n);
  212. // Adjust state by the number of frames used.
  213. _k_j0 += n;
  214. }
  215. }
  216. void Jackclient::capture (int nframes)
  217. {
  218. int i, j, n;
  219. float *p, *q;
  220. // Read from audio queue and resample.
  221. // The while loop takes care of wraparound.
  222. _resamp.out_count = _bsize;
  223. _resamp.out_data = _buff;
  224. while (_resamp.out_count)
  225. {
  226. _resamp.inp_count = _audioq->rd_linav ();
  227. _resamp.inp_data = _audioq->rd_datap ();
  228. n = _resamp.inp_count;
  229. _resamp.process ();
  230. n -= _resamp.inp_count;
  231. _audioq->rd_commit (n);
  232. // Adjust state by the number of frames used.
  233. _k_j0 += n;
  234. }
  235. // Deinterleave _buff to outputs.
  236. for (i = 0; i < _nchan; i++)
  237. {
  238. p = _buff + i;
  239. q = (float *)(jack_port_get_buffer (_ports [i], nframes));
  240. for (j = 0; j < _bsize; j++) q [j] = p [j * _nchan];
  241. }
  242. }
  243. void Jackclient::silence (int nframes)
  244. {
  245. int i;
  246. float *q;
  247. // Write silence to all jack ports.
  248. for (i = 0; i < _nchan; i++)
  249. {
  250. q = (float *)(jack_port_get_buffer (_ports [i], nframes));
  251. memset (q, 0, nframes * sizeof (float));
  252. }
  253. }
  254. void Jackclient::sendinfo (int state, double error, double ratio)
  255. {
  256. Jdata *J;
  257. if (_infoq->wr_avail ())
  258. {
  259. J = _infoq->wr_datap ();
  260. J->_state = state;
  261. J->_error = error;
  262. J->_ratio = ratio;
  263. _infoq->wr_commit ();
  264. }
  265. }
  266. void Jackclient::jack_freewheel (int state)
  267. {
  268. _freew = state ? true : false;
  269. if (_freew) initwait (_ppsec / 4);
  270. }
  271. void Jackclient::jack_latency (jack_latency_callback_mode_t jlcm)
  272. {
  273. jack_latency_range_t R;
  274. int i;
  275. if (_state < WAIT) return;
  276. if (_mode == PLAY)
  277. {
  278. if (jlcm != JackPlaybackLatency) return;
  279. R.min = R.max = (int)(_delay / _ratio) + _ltcor;
  280. }
  281. else
  282. {
  283. if (jlcm != JackCaptureLatency) return;
  284. R.min = R.max = (int)(_delay * _ratio) + _ltcor;
  285. }
  286. for (i = 0; i < _nchan; i++)
  287. {
  288. jack_port_set_latency_range (_ports [i], jlcm, &R);
  289. }
  290. }
  291. int Jackclient::jack_process (int nframes)
  292. {
  293. int dk, n;
  294. Adata *D;
  295. jack_nframes_t ft;
  296. double tj, err, d1, d2;
  297. // Buffer size change or other evil.
  298. if (_state == TERM)
  299. {
  300. sendinfo (TERM, 0, 0);
  301. return 0;
  302. }
  303. // Skip cylce if ports may not yet exist.
  304. if (_state < WAIT) return 0;
  305. // Start synchronisation 1/2 second after entering
  306. // the WAIT state. This delay allows the ALSA thread
  307. // to restart cleanly if necessary. Disabled while
  308. // freewheeling.
  309. if (_state == WAIT)
  310. {
  311. if (_freew) return 0;
  312. if (_mode == CAPT) silence (nframes);
  313. if (++_count == 0) initsync ();
  314. else return 0;
  315. }
  316. // Compute the start time of the current cycle.
  317. // Jack should really provide the usecs directly.
  318. ft = jack_last_frame_time (_client);
  319. tj = 1e-6 * (jack_frames_to_time (_client, ft) & 0x0FFFFFFF);
  320. // Check for any skipped cycles. This is invalid
  321. // the first time, but won't be used then anyway.
  322. dk = ft - _ft - _bsize;
  323. _ft = ft;
  324. // Check if we have timing data from the ALSA thread.
  325. n = _alsaq->rd_avail ();
  326. // If the data queue is full restart synchronisation.
  327. // This can happen e.g. on a jack engine timeout, or
  328. // when too many cycles have been skipped.
  329. if (n == _alsaq->size ())
  330. {
  331. initwait (_ppsec / 2);
  332. return 0;
  333. }
  334. if (n)
  335. {
  336. // Else move interval end to start, and update the
  337. // interval end keeping only the most recent data.
  338. if (_state < SYNC2) _state++;
  339. _t_a0 = _t_a1;
  340. _k_a0 = _k_a1;
  341. while (_alsaq->rd_avail ())
  342. {
  343. D = _alsaq->rd_datap ();
  344. // Restart synchronisation in case of
  345. // an error in the ALSA interface.
  346. if (D->_state == Alsathread::WAIT)
  347. {
  348. initwait (_ppsec / 2);
  349. return 0;
  350. }
  351. _t_a1 = D->_timer;
  352. _k_a1 += D->_nsamp;
  353. _alsaq->rd_commit ();
  354. }
  355. }
  356. err = 0;
  357. if (_state >= SYNC2)
  358. {
  359. // Compute the delay error.
  360. d1 = modtime (tj - _t_a0);
  361. d2 = modtime (_t_a1 - _t_a0);
  362. if (_mode == PLAY)
  363. {
  364. n = _k_j0 - _k_a0; // Must be done as integer as both terms will overflow.
  365. err = n - (_k_a1 - _k_a0) * d1 / d2 + _resamp.inpdist () * _ratio - _delay;
  366. }
  367. else
  368. {
  369. n = _k_a0 - _k_j0;
  370. err = n + (_k_a1 - _k_a0) * d1 / d2 + _resamp.inpdist () - _delay ;
  371. }
  372. n = (int)(floor (err + 0.5));
  373. if (_state == SYNC2)
  374. {
  375. // We have the first delay error value. Adjust both the state
  376. // variables and the audio queue by the same number of frames
  377. // to obtain the actually wanted delay, and start tracking.
  378. if (_mode == PLAY)
  379. {
  380. _audioq->wr_commit (-n);
  381. _k_j0 -= n;
  382. }
  383. else
  384. {
  385. _audioq->rd_commit (n);
  386. _k_j0 += n;
  387. }
  388. err -= n;
  389. setloop (1.0);
  390. _state = PROC1;
  391. }
  392. else if (_state >= PROC1)
  393. {
  394. // Check error conditions.
  395. if (dk)
  396. {
  397. // Jack skipped some cycles. Adjust both the state
  398. // and the audio queue so we can just continue.
  399. // The loop will correct the remaining fraction
  400. // of a frame.
  401. if (_mode == PLAY)
  402. {
  403. dk = (int)(dk * _ratio + 0.5);
  404. if (abs (dk + n) < _bsize / 4)
  405. {
  406. _audioq->wr_commit (dk);
  407. _k_j0 += dk;
  408. err += dk;
  409. n = 0;
  410. }
  411. }
  412. else
  413. {
  414. dk = (int)(dk / _ratio + 0.5);
  415. if (abs (dk - n) < _bsize / 4)
  416. {
  417. _audioq->rd_commit (dk);
  418. _k_j0 += dk;
  419. err -= dk;
  420. n = 0;
  421. }
  422. }
  423. }
  424. if (fabs (err) >= 50)
  425. {
  426. // Something is really wrong, wait 15 seconds then restart.
  427. initwait (15 * _ppsec);
  428. return 0;
  429. }
  430. }
  431. }
  432. // Switch to lower bandwidth after 4 seconds.
  433. if ((_state == PROC1) && (++_count == 4 * _ppsec))
  434. {
  435. _state = PROC2;
  436. setloop (0.05);
  437. }
  438. if (_state >= PROC1)
  439. {
  440. // Run loop filter and set resample ratio.
  441. _z1 += _w0 * (_w1 * err - _z1);
  442. _z2 += _w0 * (_z1 - _z2);
  443. _z3 += _w2 * _z2;
  444. _rcorr = 1 - _z2 - _z3;
  445. if (_rcorr > 1.05) _rcorr = 1.05;
  446. if (_rcorr < 0.95) _rcorr = 0.95;
  447. _resamp.set_rratio (_rcorr);
  448. sendinfo (_state, err, _rcorr);
  449. // Resample and transfer between audio
  450. // queue and jack ports.
  451. if (_mode == PLAY) playback (nframes);
  452. else capture (nframes);
  453. }
  454. else if (_mode == CAPT) silence (nframes);
  455. return 0;
  456. }