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.

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