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.

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