jack1 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.

677 lines
19KB

  1. /** @file simple_client.c
  2. *
  3. * @brief This simple client demonstrates the basic features of JACK
  4. * as they would be used by many applications.
  5. */
  6. #include <stdio.h>
  7. #include <errno.h>
  8. #include <unistd.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <alloca.h>
  12. #include <math.h>
  13. #include <jack/jack.h>
  14. #include <jack/jslist.h>
  15. #include "alsa/asoundlib.h"
  16. #include <samplerate.h>
  17. #define OFF_D_SIZE 256
  18. typedef signed short ALSASAMPLE;
  19. // Here are the lists of the jack ports...
  20. JSList *capture_ports = NULL;
  21. JSList *capture_srcs = NULL;
  22. JSList *playback_ports = NULL;
  23. JSList *playback_srcs = NULL;
  24. jack_client_t *client;
  25. // TODO: make the sample format configurable soon...
  26. snd_pcm_format_t format = SND_PCM_FORMAT_S16; /* sample format */
  27. snd_pcm_t *alsa_handle;
  28. int jack_sample_rate;
  29. int jack_buffer_size;
  30. double resample_mean = 1.0;
  31. double static_resample_factor = 1.0;
  32. double offset_array[OFF_D_SIZE];
  33. int offset_differential_index = 0;
  34. double offset_integral = 0;
  35. // ------------------------------------------------------ commandline parameters
  36. int sample_rate = 0; /* stream rate */
  37. int num_channels = 2; /* count of channels */
  38. int period_size = 1024;
  39. int num_periods = 2;
  40. int target_delay = 0; /* the delay which the program should try to approach. */
  41. int max_diff = 0; /* the diff value, when a hard readpointer skip should occur */
  42. int catch_factor = 100000;
  43. int catch_factor2 = 10000;
  44. double pclamp = 15.0;
  45. double controlquant = 10000.0;
  46. int good_window=0;
  47. int verbose = 0;
  48. int instrument = 0;
  49. // Debug stuff:
  50. volatile float output_resampling_factor = 1.0;
  51. volatile int output_new_delay = 0;
  52. volatile float output_offset = 0.0;
  53. volatile float output_integral = 0.0;
  54. volatile float output_diff = 0.0;
  55. snd_pcm_uframes_t real_buffer_size;
  56. snd_pcm_uframes_t real_period_size;
  57. // Alsa stuff... i dont want to touch this bullshit in the next years.... please...
  58. static int xrun_recovery(snd_pcm_t *handle, int err) {
  59. // printf( "xrun !!!.... %d\n", err );
  60. if (err == -EPIPE) { /* under-run */
  61. err = snd_pcm_prepare(handle);
  62. if (err < 0)
  63. printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err));
  64. return 0;
  65. } else if (err == -EAGAIN) {
  66. while ((err = snd_pcm_resume(handle)) == -EAGAIN)
  67. usleep(100); /* wait until the suspend flag is released */
  68. if (err < 0) {
  69. err = snd_pcm_prepare(handle);
  70. if (err < 0)
  71. printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err));
  72. }
  73. return 0;
  74. }
  75. return err;
  76. }
  77. static int set_hwparams(snd_pcm_t *handle, snd_pcm_hw_params_t *params, snd_pcm_access_t access, int rate, int channels, int period, int nperiods ) {
  78. int err, dir=0;
  79. unsigned int buffer_time;
  80. unsigned int period_time;
  81. unsigned int rrate;
  82. /* choose all parameters */
  83. err = snd_pcm_hw_params_any(handle, params);
  84. if (err < 0) {
  85. printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
  86. return err;
  87. }
  88. /* set the interleaved read/write format */
  89. err = snd_pcm_hw_params_set_access(handle, params, access);
  90. if (err < 0) {
  91. printf("Access type not available for playback: %s\n", snd_strerror(err));
  92. return err;
  93. }
  94. /* set the sample format */
  95. err = snd_pcm_hw_params_set_format(handle, params, format);
  96. if (err < 0) {
  97. printf("Sample format not available for playback: %s\n", snd_strerror(err));
  98. return err;
  99. }
  100. /* set the count of channels */
  101. err = snd_pcm_hw_params_set_channels(handle, params, channels);
  102. if (err < 0) {
  103. printf("Channels count (%i) not available for record: %s\n", channels, snd_strerror(err));
  104. return err;
  105. }
  106. /* set the stream rate */
  107. rrate = rate;
  108. err = snd_pcm_hw_params_set_rate_near(handle, params, &rrate, 0);
  109. if (err < 0) {
  110. printf("Rate %iHz not available for playback: %s\n", rate, snd_strerror(err));
  111. return err;
  112. }
  113. if (rrate != rate) {
  114. printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate, rrate);
  115. return -EINVAL;
  116. }
  117. /* set the buffer time */
  118. buffer_time = 1000000*period*nperiods/rate;
  119. err = snd_pcm_hw_params_set_buffer_time_near(handle, params, &buffer_time, &dir);
  120. if (err < 0) {
  121. printf("Unable to set buffer time %i for playback: %s\n", 1000000*period*nperiods/rate, snd_strerror(err));
  122. return err;
  123. }
  124. err = snd_pcm_hw_params_get_buffer_size( params, &real_buffer_size );
  125. if (err < 0) {
  126. printf("Unable to get buffer size back: %s\n", snd_strerror(err));
  127. return err;
  128. }
  129. if( real_buffer_size != nperiods * period ) {
  130. printf( "WARNING: buffer size does not match: (requested %d, got %d)\n", nperiods * period, (int) real_buffer_size );
  131. }
  132. /* set the period time */
  133. period_time = 1000000*period/rate;
  134. err = snd_pcm_hw_params_set_period_time_near(handle, params, &period_time, &dir);
  135. if (err < 0) {
  136. printf("Unable to set period time %i for playback: %s\n", 1000000*period/rate, snd_strerror(err));
  137. return err;
  138. }
  139. err = snd_pcm_hw_params_get_period_size(params, &real_period_size, NULL );
  140. if (err < 0) {
  141. printf("Unable to get period size back: %s\n", snd_strerror(err));
  142. return err;
  143. }
  144. if( real_period_size != period ) {
  145. printf( "WARNING: period size does not match: (requested %i, got %i)\n", period, (int)real_period_size );
  146. }
  147. /* write the parameters to device */
  148. err = snd_pcm_hw_params(handle, params);
  149. if (err < 0) {
  150. printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
  151. return err;
  152. }
  153. return 0;
  154. }
  155. static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams, int period) {
  156. int err;
  157. /* get the current swparams */
  158. err = snd_pcm_sw_params_current(handle, swparams);
  159. if (err < 0) {
  160. printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err));
  161. return err;
  162. }
  163. /* start the transfer when the buffer is full */
  164. err = snd_pcm_sw_params_set_start_threshold(handle, swparams, period );
  165. if (err < 0) {
  166. printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
  167. return err;
  168. }
  169. err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, -1 );
  170. if (err < 0) {
  171. printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
  172. return err;
  173. }
  174. /* allow the transfer when at least period_size samples can be processed */
  175. err = snd_pcm_sw_params_set_avail_min(handle, swparams, 2*period );
  176. if (err < 0) {
  177. printf("Unable to set avail min for capture: %s\n", snd_strerror(err));
  178. return err;
  179. }
  180. /* align all transfers to 1 sample */
  181. err = snd_pcm_sw_params_set_xfer_align(handle, swparams, 1);
  182. if (err < 0) {
  183. printf("Unable to set transfer align for capture: %s\n", snd_strerror(err));
  184. return err;
  185. }
  186. /* write the parameters to the playback device */
  187. err = snd_pcm_sw_params(handle, swparams);
  188. if (err < 0) {
  189. printf("Unable to set sw params for capture: %s\n", snd_strerror(err));
  190. return err;
  191. }
  192. return 0;
  193. }
  194. // ok... i only need this function to communicate with the alsa bloat api...
  195. static snd_pcm_t *open_audiofd( char *device_name, int capture, int rate, int channels, int period, int nperiods ) {
  196. int err;
  197. snd_pcm_t *handle;
  198. snd_pcm_hw_params_t *hwparams;
  199. snd_pcm_sw_params_t *swparams;
  200. snd_pcm_hw_params_alloca(&hwparams);
  201. snd_pcm_sw_params_alloca(&swparams);
  202. if ((err = snd_pcm_open(&(handle), device_name, capture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK )) < 0) {
  203. printf("Capture open error: %s\n", snd_strerror(err));
  204. return NULL;
  205. }
  206. if ((err = set_hwparams(handle, hwparams,SND_PCM_ACCESS_RW_INTERLEAVED, rate, channels, period, nperiods )) < 0) {
  207. printf("Setting of hwparams failed: %s\n", snd_strerror(err));
  208. return NULL;
  209. }
  210. if ((err = set_swparams(handle, swparams, period)) < 0) {
  211. printf("Setting of swparams failed: %s\n", snd_strerror(err));
  212. return NULL;
  213. }
  214. snd_pcm_start( handle );
  215. snd_pcm_wait( handle, 200 );
  216. return handle;
  217. }
  218. double hann( double x )
  219. {
  220. return 0.5 * (1.0 - cos( 2*M_PI * x ) );
  221. }
  222. /**
  223. * The process callback for this JACK application.
  224. * It is called by JACK at the appropriate times.
  225. */
  226. int process (jack_nframes_t nframes, void *arg) {
  227. ALSASAMPLE *outbuf;
  228. float *resampbuf;
  229. int rlen;
  230. int err;
  231. snd_pcm_sframes_t delay = target_delay;
  232. int put_back_samples=0;
  233. int i;
  234. snd_pcm_delay( alsa_handle, &delay );
  235. //delay -= jack_frames_since_cycle_start( client );
  236. // Do it the hard way.
  237. // this is for compensating xruns etc...
  238. if( delay > (target_delay+max_diff) ) {
  239. ALSASAMPLE *tmp = alloca( (delay-target_delay) * sizeof( ALSASAMPLE ) * num_channels );
  240. snd_pcm_readi( alsa_handle, tmp, delay-target_delay );
  241. output_new_delay = (int) delay;
  242. delay = target_delay;
  243. // Set the resample_rate... we need to adjust the offset integral, to do this.
  244. // first look at the PI controller, this code is just a special case, which should never execute once
  245. // everything is swung in.
  246. offset_integral = - (resample_mean - static_resample_factor) * catch_factor * catch_factor2;
  247. // Also clear the array. we are beginning a new control cycle.
  248. for( i=0; i<OFF_D_SIZE; i++ )
  249. offset_array[i] = 0.0;
  250. }
  251. if( delay < (target_delay-max_diff) ) {
  252. snd_pcm_rewind( alsa_handle, target_delay - delay );
  253. output_new_delay = (int) delay;
  254. delay = target_delay;
  255. // Set the resample_rate... we need to adjust the offset integral, to do this.
  256. offset_integral = - (resample_mean - static_resample_factor) * catch_factor * catch_factor2;
  257. // Also clear the array. we are beginning a new control cycle.
  258. for( i=0; i<OFF_D_SIZE; i++ )
  259. offset_array[i] = 0.0;
  260. }
  261. /* ok... now we should have target_delay +- max_diff on the alsa side.
  262. *
  263. * calculate the number of frames, we want to get.
  264. */
  265. double offset = delay - target_delay;
  266. // Save offset.
  267. offset_array[(offset_differential_index++)% OFF_D_SIZE ] = offset;
  268. // Build the mean of the windowed offset array
  269. // basically fir lowpassing.
  270. double smooth_offset = 0.0;
  271. for( i=0; i<OFF_D_SIZE; i++ )
  272. smooth_offset +=
  273. offset_array[ (i + offset_differential_index-1) % OFF_D_SIZE] * hann( (double) i / ((double) OFF_D_SIZE - 1.0) );
  274. smooth_offset /= (double) OFF_D_SIZE;
  275. // this is the integral of the smoothed_offset
  276. offset_integral += smooth_offset;
  277. // Clamp offset.
  278. // the smooth offset still contains unwanted noise
  279. // which would go straigth onto the resample coeff.
  280. // it only used in the P component and the I component is used for the fine tuning anyways.
  281. if( fabs( smooth_offset ) < pclamp )
  282. smooth_offset = 0.0;
  283. // ok. now this is the PI controller.
  284. // u(t) = K * ( e(t) + 1/T \int e(t') dt' )
  285. // K = 1/catch_factor and T = catch_factor2
  286. double current_resample_factor = static_resample_factor - smooth_offset / (double) catch_factor - offset_integral / (double) catch_factor / (double)catch_factor2;
  287. // now quantize this value around resample_mean, so that the noise which is in the integral component doesnt hurt.
  288. current_resample_factor = floor( (current_resample_factor - resample_mean) * controlquant + 0.5 ) / controlquant + resample_mean;
  289. // Output "instrumentatio" gonna change that to real instrumentation in a few.
  290. output_resampling_factor = (float) current_resample_factor;
  291. output_diff = (float) smooth_offset;
  292. output_integral = (float) offset_integral;
  293. output_offset = (float) offset;
  294. // Clamp a bit.
  295. if( current_resample_factor < 0.25 ) current_resample_factor = 0.25;
  296. if( current_resample_factor > 4 ) current_resample_factor = 4;
  297. // Now Calculate how many samples we need.
  298. rlen = ceil( ((double)nframes) / current_resample_factor )+2;
  299. assert( rlen > 2 );
  300. // Calculate resample_mean so we can init ourselves to saner values.
  301. resample_mean = 0.9999 * resample_mean + 0.0001 * current_resample_factor;
  302. /*
  303. * now this should do it...
  304. */
  305. outbuf = alloca( rlen * sizeof( ALSASAMPLE ) * num_channels );
  306. resampbuf = alloca( rlen * sizeof( float ) );
  307. // get the data...
  308. again:
  309. err = snd_pcm_readi(alsa_handle, outbuf, rlen);
  310. if( err < 0 ) {
  311. printf( "err = %d\n", err );
  312. if (xrun_recovery(alsa_handle, err) < 0) {
  313. //printf("Write error: %s\n", snd_strerror(err));
  314. //exit(EXIT_FAILURE);
  315. }
  316. goto again;
  317. }
  318. if( err != rlen ) {
  319. //printf( "read = %d\n", rlen );
  320. }
  321. /*
  322. * render jack ports to the outbuf...
  323. */
  324. int chn = 0;
  325. JSList *node = capture_ports;
  326. JSList *src_node = capture_srcs;
  327. SRC_DATA src;
  328. while ( node != NULL)
  329. {
  330. int i;
  331. jack_port_t *port = (jack_port_t *) node->data;
  332. float *buf = jack_port_get_buffer (port, nframes);
  333. SRC_STATE *src_state = src_node->data;
  334. for (i=0; i < rlen; i++) {
  335. resampbuf[i] = (float) outbuf[chn+ i*num_channels] / 32767;
  336. }
  337. src.data_in = resampbuf;
  338. src.input_frames = rlen;
  339. src.data_out = buf;
  340. src.output_frames = nframes;
  341. src.end_of_input = 0;
  342. src.src_ratio = current_resample_factor;
  343. src_process( src_state, &src );
  344. put_back_samples = rlen-src.input_frames_used;
  345. src_node = jack_slist_next (src_node);
  346. node = jack_slist_next (node);
  347. chn++;
  348. }
  349. // Put back the samples libsamplerate did not consume.
  350. //printf( "putback = %d\n", put_back_samples );
  351. snd_pcm_rewind( alsa_handle, put_back_samples );
  352. return 0;
  353. }
  354. /**
  355. * Allocate the necessary jack ports...
  356. */
  357. void alloc_ports( int n_capture, int n_playback ) {
  358. int port_flags = JackPortIsOutput;
  359. int chn;
  360. jack_port_t *port;
  361. char buf[32];
  362. capture_ports = NULL;
  363. for (chn = 0; chn < n_capture; chn++)
  364. {
  365. snprintf (buf, sizeof(buf) - 1, "capture_%u", chn+1);
  366. port = jack_port_register (client, buf,
  367. JACK_DEFAULT_AUDIO_TYPE,
  368. port_flags, 0);
  369. if (!port)
  370. {
  371. printf( "jacknet_client: cannot register port for %s", buf);
  372. break;
  373. }
  374. capture_srcs = jack_slist_append( capture_srcs, src_new( SRC_SINC_FASTEST, 1, NULL ) );
  375. capture_ports = jack_slist_append (capture_ports, port);
  376. }
  377. port_flags = JackPortIsInput;
  378. playback_ports = NULL;
  379. for (chn = 0; chn < n_playback; chn++)
  380. {
  381. snprintf (buf, sizeof(buf) - 1, "playback_%u", chn+1);
  382. port = jack_port_register (client, buf,
  383. JACK_DEFAULT_AUDIO_TYPE,
  384. port_flags, 0);
  385. if (!port)
  386. {
  387. printf( "jacknet_client: cannot register port for %s", buf);
  388. break;
  389. }
  390. playback_srcs = jack_slist_append( playback_srcs, src_new( SRC_SINC_FASTEST, 1, NULL ) );
  391. playback_ports = jack_slist_append (playback_ports, port);
  392. }
  393. }
  394. /**
  395. * This is the shutdown callback for this JACK application.
  396. * It is called by JACK if the server ever shuts down or
  397. * decides to disconnect the client.
  398. */
  399. void jack_shutdown (void *arg) {
  400. exit (1);
  401. }
  402. /**
  403. * be user friendly.
  404. * be user friendly.
  405. * be user friendly.
  406. */
  407. void printUsage() {
  408. fprintf(stderr, "usage: alsa_out [options]\n"
  409. "\n"
  410. " -j <jack name> - reports a different name to jack\n"
  411. " -d <alsa_device> \n"
  412. " -c <channels> \n"
  413. " -p <period_size> \n"
  414. " -n <num_period> \n"
  415. " -r <sample_rate> \n"
  416. " -m <max_diff> \n"
  417. " -t <target_delay> \n"
  418. " -f <catch_factor> \n"
  419. " -i turns on instrumentation\n"
  420. " -v turns on printouts\n"
  421. "\n");
  422. }
  423. /**
  424. * the main function....
  425. */
  426. int main (int argc, char *argv[]) {
  427. char jack_name[30] = "alsa_in";
  428. char alsa_device[30] = "hw:0";
  429. extern char *optarg;
  430. extern int optind, optopt;
  431. int errflg=0;
  432. int c;
  433. while ((c = getopt(argc, argv, "ivj:r:c:p:n:d:m:t:f:F:C:Q:")) != -1) {
  434. switch(c) {
  435. case 'j':
  436. strcpy(jack_name,optarg);
  437. break;
  438. case 'r':
  439. sample_rate = atoi(optarg);
  440. break;
  441. case 'c':
  442. num_channels = atoi(optarg);
  443. break;
  444. case 'p':
  445. period_size = atoi(optarg);
  446. break;
  447. case 'n':
  448. num_periods = atoi(optarg);
  449. break;
  450. case 'd':
  451. strcpy(alsa_device,optarg);
  452. break;
  453. case 't':
  454. target_delay = atoi(optarg);
  455. break;
  456. case 'm':
  457. max_diff = atoi(optarg);
  458. break;
  459. case 'f':
  460. catch_factor = atoi(optarg);
  461. break;
  462. case 'F':
  463. catch_factor2 = atoi(optarg);
  464. break;
  465. case 'C':
  466. pclamp = (double) atoi(optarg);
  467. break;
  468. case 'Q':
  469. controlquant = (double) atoi(optarg);
  470. break;
  471. case 'v':
  472. verbose = 1;
  473. break;
  474. case 'i':
  475. instrument = 1;
  476. break;
  477. case ':':
  478. fprintf(stderr,
  479. "Option -%c requires an operand\n", optopt);
  480. errflg++;
  481. break;
  482. case '?':
  483. fprintf(stderr,
  484. "Unrecognized option: -%c\n", optopt);
  485. errflg++;
  486. }
  487. }
  488. if (errflg) {
  489. printUsage();
  490. exit(2);
  491. }
  492. if ((client = jack_client_new (jack_name)) == 0) {
  493. fprintf (stderr, "jack server not running?\n");
  494. return 1;
  495. }
  496. /* tell the JACK server to call `process()' whenever
  497. there is work to be done.
  498. */
  499. jack_set_process_callback (client, process, 0);
  500. /* tell the JACK server to call `jack_shutdown()' if
  501. it ever shuts down, either entirely, or if it
  502. just decides to stop calling us.
  503. */
  504. jack_on_shutdown (client, jack_shutdown, 0);
  505. // alloc input ports, which are blasted out to alsa...
  506. alloc_ports( num_channels, 0 );
  507. // get jack sample_rate
  508. jack_sample_rate = jack_get_sample_rate( client );
  509. if( !sample_rate )
  510. sample_rate = jack_sample_rate;
  511. static_resample_factor = (double) jack_sample_rate / (double) sample_rate;
  512. resample_mean = static_resample_factor;
  513. int i;
  514. for( i=0; i<OFF_D_SIZE; i++ )
  515. offset_array[i] = 0.0;
  516. jack_buffer_size = jack_get_buffer_size( client );
  517. // Setup target delay and max_diff for the normal user, who does not play with them...
  518. if( !target_delay )
  519. target_delay = (num_periods*period_size / 2) - jack_buffer_size/2;
  520. if( !max_diff )
  521. max_diff = target_delay;
  522. if( max_diff > target_delay ) {
  523. fprintf( stderr, "target_delay (%d) cant be smaller than max_diff(%d)\n", target_delay, max_diff );
  524. exit(20);
  525. }
  526. if( (target_delay+max_diff) > (num_periods*period_size) ) {
  527. fprintf( stderr, "target_delay+max_diff (%d) cant be bigger than buffersize(%d)\n", target_delay+max_diff, num_periods*period_size );
  528. exit(20);
  529. }
  530. // now open the alsa fd...
  531. alsa_handle = open_audiofd( alsa_device, 1, sample_rate, num_channels, period_size, num_periods);
  532. if( alsa_handle < 0 )
  533. exit(20);
  534. /* tell the JACK server that we are ready to roll */
  535. if (jack_activate (client)) {
  536. fprintf (stderr, "cannot activate client");
  537. return 1;
  538. }
  539. if( verbose ) {
  540. while(1) {
  541. usleep(500000);
  542. if( output_new_delay ) {
  543. printf( "delay = %d\n", output_new_delay );
  544. output_new_delay = 0;
  545. }
  546. printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor, output_diff, output_offset );
  547. }
  548. } else if( instrument ) {
  549. printf( "# n\tresamp\tdiff\toffseti\tintegral\n");
  550. int n=0;
  551. while(1) {
  552. usleep(1000);
  553. printf( "%d\t%f\t%f\t%f\t%f\n", n++, output_resampling_factor, output_diff, output_offset, output_integral );
  554. }
  555. } else {
  556. while(1) sleep(10);
  557. }
  558. jack_client_close (client);
  559. exit (0);
  560. }