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.

626 lines
17KB

  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. #define ALSA_PCM_OLD_HW_PARAMS_API
  16. #define ALSA_PCM_OLD_SW_PARAMS_API
  17. #include "alsa/asoundlib.h"
  18. #include <samplerate.h>
  19. #include "time_smoother.h"
  20. typedef signed short ALSASAMPLE;
  21. // Here are the lists of the jack ports...
  22. JSList *capture_ports = NULL;
  23. JSList *capture_srcs = NULL;
  24. JSList *playback_ports = NULL;
  25. JSList *playback_srcs = NULL;
  26. jack_client_t *client;
  27. // TODO: make the sample format configurable soon...
  28. snd_pcm_format_t format = SND_PCM_FORMAT_S16; /* sample format */
  29. snd_pcm_t *alsa_handle;
  30. int jack_sample_rate;
  31. double current_resample_factor = 1.0;
  32. time_smoother *smoother;
  33. // ------------------------------------------------------ commandline parameters
  34. int sample_rate = 0; /* stream rate */
  35. int num_channels = 2; /* count of channels */
  36. int period_size = 1024;
  37. int num_periods = 2;
  38. int target_delay = 0; /* the delay which the program should try to approach. */
  39. int max_diff = 0; /* the diff value, when a hard readpointer skip should occur */
  40. int catch_factor = 1000;
  41. // Debug stuff:
  42. int print_counter = 10;
  43. volatile float output_resampling_factor = 0.0;
  44. volatile int output_new_delay = 0;
  45. volatile float output_offset = 0.0;
  46. volatile float output_diff = 0.0;
  47. // Alsa stuff... i dont want to touch this bullshit in the next years.... please...
  48. static int xrun_recovery(snd_pcm_t *handle, int err) {
  49. //printf( "xrun !!!....\n" );
  50. if (err == -EPIPE) { /* under-run */
  51. err = snd_pcm_prepare(handle);
  52. if (err < 0)
  53. printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err));
  54. return 0;
  55. } else if (err == -ESTRPIPE) {
  56. while ((err = snd_pcm_resume(handle)) == -EAGAIN)
  57. sleep(1); /* wait until the suspend flag is released */
  58. if (err < 0) {
  59. err = snd_pcm_prepare(handle);
  60. if (err < 0)
  61. printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err));
  62. }
  63. return 0;
  64. }
  65. return err;
  66. }
  67. 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 ) {
  68. int err, dir=0;
  69. /* choose all parameters */
  70. err = snd_pcm_hw_params_any(handle, params);
  71. if (err < 0) {
  72. printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
  73. return err;
  74. }
  75. /* set the interleaved read/write format */
  76. err = snd_pcm_hw_params_set_access(handle, params, access);
  77. if (err < 0) {
  78. printf("Access type not available for playback: %s\n", snd_strerror(err));
  79. return err;
  80. }
  81. /* set the sample format */
  82. err = snd_pcm_hw_params_set_format(handle, params, format);
  83. if (err < 0) {
  84. printf("Sample format not available for playback: %s\n", snd_strerror(err));
  85. return err;
  86. }
  87. /* set the count of channels */
  88. err = snd_pcm_hw_params_set_channels(handle, params, channels);
  89. if (err < 0) {
  90. printf("Channels count (%i) not available for record: %s\n", channels, snd_strerror(err));
  91. return err;
  92. }
  93. /* set the stream rate */
  94. err = snd_pcm_hw_params_set_rate_near(handle, params, rate, 0);
  95. if (err < 0) {
  96. printf("Rate %iHz not available for capture: %s\n", rate, snd_strerror(err));
  97. return err;
  98. }
  99. if (err != rate) {
  100. printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate, err);
  101. return -EINVAL;
  102. }
  103. /* set the buffer time */
  104. err = snd_pcm_hw_params_set_buffer_time_near(handle, params, 1000000*period*nperiods/rate, &dir);
  105. if (err < 0) {
  106. printf("Unable to set buffer time %i for playback: %s\n", 1000000*period*nperiods/rate, snd_strerror(err));
  107. return err;
  108. }
  109. if( snd_pcm_hw_params_get_buffer_size(params) != nperiods * period ) {
  110. printf( "WARNING: buffer size does not match: (requested %d, got %d)\n", nperiods * period, (int) snd_pcm_hw_params_get_buffer_size(params) );
  111. }
  112. /* set the period time */
  113. err = snd_pcm_hw_params_set_period_time_near(handle, params, 1000000*period/rate, &dir);
  114. if (err < 0) {
  115. printf("Unable to set period time %i for playback: %s\n", 1000000*period/rate, snd_strerror(err));
  116. return err;
  117. }
  118. int ps = snd_pcm_hw_params_get_period_size(params, NULL );
  119. if( ps != period ) {
  120. printf( "WARNING: period size does not match: (requested %i, got %i)\n", period, ps );
  121. }
  122. /* write the parameters to device */
  123. err = snd_pcm_hw_params(handle, params);
  124. if (err < 0) {
  125. printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
  126. return err;
  127. }
  128. return 0;
  129. }
  130. static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams, int period) {
  131. int err;
  132. /* get the current swparams */
  133. err = snd_pcm_sw_params_current(handle, swparams);
  134. if (err < 0) {
  135. printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err));
  136. return err;
  137. }
  138. /* start the transfer when the buffer is full */
  139. err = snd_pcm_sw_params_set_start_threshold(handle, swparams, period );
  140. if (err < 0) {
  141. printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
  142. return err;
  143. }
  144. err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, -1 );
  145. if (err < 0) {
  146. printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
  147. return err;
  148. }
  149. /* allow the transfer when at least period_size samples can be processed */
  150. err = snd_pcm_sw_params_set_avail_min(handle, swparams, 2*period );
  151. if (err < 0) {
  152. printf("Unable to set avail min for capture: %s\n", snd_strerror(err));
  153. return err;
  154. }
  155. /* align all transfers to 1 sample */
  156. err = snd_pcm_sw_params_set_xfer_align(handle, swparams, 1);
  157. if (err < 0) {
  158. printf("Unable to set transfer align for capture: %s\n", snd_strerror(err));
  159. return err;
  160. }
  161. /* write the parameters to the playback device */
  162. err = snd_pcm_sw_params(handle, swparams);
  163. if (err < 0) {
  164. printf("Unable to set sw params for capture: %s\n", snd_strerror(err));
  165. return err;
  166. }
  167. return 0;
  168. }
  169. // ok... i only need this function to communicate with the alsa bloat api...
  170. static snd_pcm_t *open_audiofd( char *device_name, int capture, int rate, int channels, int period, int nperiods ) {
  171. int err;
  172. snd_pcm_t *handle;
  173. snd_pcm_hw_params_t *hwparams;
  174. snd_pcm_sw_params_t *swparams;
  175. snd_pcm_hw_params_alloca(&hwparams);
  176. snd_pcm_sw_params_alloca(&swparams);
  177. if ((err = snd_pcm_open(&(handle), device_name, capture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK )) < 0) {
  178. printf("Capture open error: %s\n", snd_strerror(err));
  179. return NULL;
  180. }
  181. if ((err = set_hwparams(handle, hwparams,SND_PCM_ACCESS_RW_INTERLEAVED, rate, channels, period, nperiods )) < 0) {
  182. printf("Setting of hwparams failed: %s\n", snd_strerror(err));
  183. return NULL;
  184. }
  185. if ((err = set_swparams(handle, swparams, period)) < 0) {
  186. printf("Setting of swparams failed: %s\n", snd_strerror(err));
  187. return NULL;
  188. }
  189. snd_pcm_start( handle );
  190. snd_pcm_wait( handle, 200 );
  191. return handle;
  192. }
  193. jack_nframes_t soundcard_frames = 0;
  194. /**
  195. * The process callback for this JACK application.
  196. * It is called by JACK at the appropriate times.
  197. */
  198. int process (jack_nframes_t nframes, void *arg) {
  199. ALSASAMPLE *outbuf;
  200. float *floatbuf, *resampbuf;
  201. int rlen;
  202. int err;
  203. snd_pcm_sframes_t delay, absolute_delay;
  204. jack_nframes_t this_frame_time;
  205. jack_nframes_t this_soundcard_time;
  206. int put_back_samples=0;
  207. int dont_adjust_resampling_factor = 0;
  208. double a, b;
  209. {
  210. snd_pcm_delay( alsa_handle, &delay );
  211. this_frame_time = jack_frame_time(client);
  212. this_soundcard_time = soundcard_frames + delay;
  213. }
  214. time_smoother_put( smoother, this_frame_time, this_soundcard_time );
  215. // subtract jack_frames_since_cycle_start, to compensate for
  216. // cpu jitter.
  217. //absolute_delay = delay;
  218. //delay = delay - jack_frames_since_cycle_start( client );
  219. //output_new_delay = (int) delay;
  220. // Do it the hard way.
  221. // this is for compensating xruns etc...
  222. if( delay > (target_delay+max_diff) ) {
  223. ALSASAMPLE *tmp = alloca( (delay-target_delay) * sizeof( ALSASAMPLE ) * num_channels );
  224. snd_pcm_readi( alsa_handle, tmp, delay-target_delay );
  225. soundcard_frames += (delay-target_delay);
  226. output_new_delay = (int) delay;
  227. dont_adjust_resampling_factor = 1;
  228. delay = target_delay;
  229. // XXX: at least set it to that value.
  230. current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
  231. }
  232. if( delay < (target_delay-max_diff) ) {
  233. snd_pcm_rewind( alsa_handle, target_delay - delay );
  234. soundcard_frames -= (target_delay-delay);
  235. output_new_delay = (int) delay;
  236. dont_adjust_resampling_factor = 1;
  237. delay = target_delay;
  238. // XXX: at least set it to that value.
  239. current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
  240. }
  241. if( 1 ) {
  242. double resamp_rate = (double)jack_sample_rate / (double)sample_rate; // == nframes / alsa_samples.
  243. double request_samples = nframes / resamp_rate; //== alsa_samples;
  244. double offset = delay - target_delay;
  245. double frlen = request_samples + offset;
  246. double compute_factor = (double) nframes / frlen;
  247. double diff_value = pow(current_resample_factor - compute_factor, 3) / (double) catch_factor;
  248. current_resample_factor -= diff_value;
  249. // clamp...
  250. current_resample_factor = current_resample_factor < 0.25 ? 0.25 : current_resample_factor;
  251. output_resampling_factor = (float) current_resample_factor;
  252. output_offset = offset;
  253. output_diff = diff_value;
  254. }
  255. else
  256. {
  257. time_smoother_get_linear_params( smoother, this_frame_time, this_soundcard_time, jack_get_sample_rate(client)/4,
  258. &a, &b );
  259. if( !dont_adjust_resampling_factor )
  260. current_resample_factor = b - a/(double)nframes/(double)catch_factor;
  261. else
  262. current_resample_factor = b;
  263. double offset = a;
  264. double diff_value = b;
  265. output_resampling_factor = (float) current_resample_factor;
  266. output_diff = (float) diff_value;
  267. output_offset = (float) offset;
  268. }
  269. if( current_resample_factor < 0.25 ) current_resample_factor = 0.25;
  270. if( current_resample_factor > 4 ) current_resample_factor = 4;
  271. rlen = ceil( ((double)nframes) / current_resample_factor )+20;
  272. assert( rlen > 10 );
  273. /*
  274. * now this should do it...
  275. */
  276. outbuf = alloca( rlen * sizeof( ALSASAMPLE ) * num_channels );
  277. floatbuf = alloca( rlen * sizeof( float ) );
  278. resampbuf = alloca( nframes * sizeof( float ) );
  279. // get the data...
  280. again:
  281. err = snd_pcm_readi(alsa_handle, outbuf, rlen);
  282. if( err < 0 ) {
  283. printf( "err = %d\n", err );
  284. if (xrun_recovery(alsa_handle, err) < 0) {
  285. //printf("Write error: %s\n", snd_strerror(err));
  286. //exit(EXIT_FAILURE);
  287. }
  288. goto again;
  289. }
  290. soundcard_frames += err;
  291. if( err != rlen ) {
  292. //printf( "read = %d\n", rlen );
  293. }
  294. /*
  295. * render jack ports to the outbuf...
  296. */
  297. int chn = 0;
  298. JSList *node = capture_ports;
  299. JSList *src_node = capture_srcs;
  300. while ( node != NULL)
  301. {
  302. int i;
  303. jack_port_t *port = (jack_port_t *) node->data;
  304. float *buf = jack_port_get_buffer (port, nframes);
  305. SRC_STATE *src_state = src_node->data;
  306. SRC_DATA src;
  307. for (i=0; i < rlen; i++) {
  308. resampbuf[i] = (float) outbuf[chn+ i*num_channels] / 32767;
  309. }
  310. src.data_in = resampbuf;
  311. src.input_frames = rlen;
  312. src.data_out = buf;
  313. src.output_frames = nframes;
  314. src.end_of_input = 0;
  315. //src.src_ratio = (float) nframes / frlen;
  316. src.src_ratio = current_resample_factor;
  317. //src_set_ratio( src_state, src.src_ratio );
  318. src_process( src_state, &src );
  319. put_back_samples = rlen-src.input_frames_used;
  320. /*
  321. if( src.output_frames_gen != nframes ) {
  322. printf( "did not fill jack_buffer... %ld\n", nframes-src.output_frames_gen );
  323. printf( "rlen=%d ratio=%f... nframes=%d\ninputused=%d\n", rlen, current_resample_factor, nframes, src.input_frames_used );
  324. }
  325. */
  326. src_node = jack_slist_next (src_node);
  327. node = jack_slist_next (node);
  328. chn++;
  329. }
  330. //printf( "putback = %d\n", put_back_samples );
  331. snd_pcm_rewind( alsa_handle, put_back_samples );
  332. soundcard_frames -= put_back_samples;
  333. return 0;
  334. }
  335. /**
  336. * Allocate the necessary jack ports...
  337. */
  338. void alloc_ports( int n_capture, int n_playback ) {
  339. int port_flags = JackPortIsOutput;
  340. int chn;
  341. jack_port_t *port;
  342. char buf[32];
  343. capture_ports = NULL;
  344. for (chn = 0; chn < n_capture; chn++)
  345. {
  346. snprintf (buf, sizeof(buf) - 1, "capture_%u", chn+1);
  347. port = jack_port_register (client, buf,
  348. JACK_DEFAULT_AUDIO_TYPE,
  349. port_flags, 0);
  350. if (!port)
  351. {
  352. printf( "jacknet_client: cannot register port for %s", buf);
  353. break;
  354. }
  355. capture_srcs = jack_slist_append( capture_srcs, src_new( SRC_SINC_FASTEST, 1, NULL ) );
  356. capture_ports = jack_slist_append (capture_ports, port);
  357. }
  358. port_flags = JackPortIsInput;
  359. playback_ports = NULL;
  360. for (chn = 0; chn < n_playback; chn++)
  361. {
  362. snprintf (buf, sizeof(buf) - 1, "playback_%u", chn+1);
  363. port = jack_port_register (client, buf,
  364. JACK_DEFAULT_AUDIO_TYPE,
  365. port_flags, 0);
  366. if (!port)
  367. {
  368. printf( "jacknet_client: cannot register port for %s", buf);
  369. break;
  370. }
  371. playback_srcs = jack_slist_append( playback_srcs, src_new( SRC_SINC_FASTEST, 1, NULL ) );
  372. playback_ports = jack_slist_append (playback_ports, port);
  373. }
  374. }
  375. /**
  376. * This is the shutdown callback for this JACK application.
  377. * It is called by JACK if the server ever shuts down or
  378. * decides to disconnect the client.
  379. */
  380. void jack_shutdown (void *arg) {
  381. exit (1);
  382. }
  383. /**
  384. * be user friendly.
  385. * be user friendly.
  386. * be user friendly.
  387. */
  388. void printUsage() {
  389. fprintf(stderr, "usage: alsa_out [options]\n"
  390. "\n"
  391. " -j <jack name> - reports a different name to jack\n"
  392. " -d <alsa_device> \n"
  393. " -c <channels> \n"
  394. " -p <period_size> \n"
  395. " -n <num_period> \n"
  396. " -r <sample_rate> \n"
  397. " -m <max_diff> \n"
  398. " -t <target_delay> \n"
  399. " -f <catch_factor> \n"
  400. "\n");
  401. }
  402. /**
  403. * the main function....
  404. */
  405. int main (int argc, char *argv[]) {
  406. char jack_name[30] = "alsa_in";
  407. char alsa_device[30] = "hw:0";
  408. extern char *optarg;
  409. extern int optind, optopt;
  410. int errflg=0;
  411. int c;
  412. while ((c = getopt(argc, argv, ":j:r:c:p:n:d:m:t:f:")) != -1) {
  413. switch(c) {
  414. case 'j':
  415. strcpy(jack_name,optarg);
  416. break;
  417. case 'r':
  418. sample_rate = atoi(optarg);
  419. break;
  420. case 'c':
  421. num_channels = atoi(optarg);
  422. break;
  423. case 'p':
  424. period_size = atoi(optarg);
  425. break;
  426. case 'n':
  427. num_periods = atoi(optarg);
  428. break;
  429. case 'd':
  430. strcpy(alsa_device,optarg);
  431. break;
  432. case 't':
  433. target_delay = atoi(optarg);
  434. break;
  435. case 'm':
  436. max_diff = atoi(optarg);
  437. break;
  438. case 'f':
  439. catch_factor = atoi(optarg);
  440. break;
  441. case ':':
  442. fprintf(stderr,
  443. "Option -%c requires an operand\n", optopt);
  444. errflg++;
  445. break;
  446. case '?':
  447. fprintf(stderr,
  448. "Unrecognized option: -%c\n", optopt);
  449. errflg++;
  450. }
  451. }
  452. if (errflg) {
  453. printUsage();
  454. exit(2);
  455. }
  456. // Setup target delay and max_diff for the normal user, who does not play with them...
  457. if( !target_delay )
  458. target_delay = num_periods*period_size / 2;
  459. if( !max_diff )
  460. max_diff = period_size / 2;
  461. smoother = time_smoother_new( 100 );
  462. if( !smoother ) {
  463. fprintf (stderr, "no memory\n");
  464. return 10;
  465. }
  466. if ((client = jack_client_new (jack_name)) == 0) {
  467. fprintf (stderr, "jack server not running?\n");
  468. return 1;
  469. }
  470. /* tell the JACK server to call `process()' whenever
  471. there is work to be done.
  472. */
  473. jack_set_process_callback (client, process, 0);
  474. /* tell the JACK server to call `jack_shutdown()' if
  475. it ever shuts down, either entirely, or if it
  476. just decides to stop calling us.
  477. */
  478. jack_on_shutdown (client, jack_shutdown, 0);
  479. // alloc input ports, which are blasted out to alsa...
  480. alloc_ports( num_channels, 0 );
  481. // get jack sample_rate
  482. jack_sample_rate = jack_get_sample_rate( client );
  483. if( !sample_rate )
  484. sample_rate = jack_sample_rate;
  485. current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
  486. //// now open the alsa fd...
  487. alsa_handle = open_audiofd( alsa_device, 1, sample_rate, num_channels, period_size, num_periods);
  488. if( alsa_handle < 0 )
  489. exit(20);
  490. /* tell the JACK server that we are ready to roll */
  491. if (jack_activate (client)) {
  492. fprintf (stderr, "cannot activate client");
  493. return 1;
  494. }
  495. while(1) {
  496. usleep(500000);
  497. if( output_new_delay ) {
  498. printf( "delay = %d\n", output_new_delay );
  499. output_new_delay = 0;
  500. }
  501. printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor, output_diff, output_offset );
  502. output_offset = 0.0;
  503. }
  504. jack_client_close (client);
  505. exit (0);
  506. }