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.

622 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. int periods_until_stability = 10;
  33. time_smoother *smoother;
  34. // ------------------------------------------------------ commandline parameters
  35. int sample_rate = 0; /* stream rate */
  36. int num_channels = 2; /* count of channels */
  37. int period_size = 1024;
  38. int num_periods = 2;
  39. int target_delay = 0; /* the delay which the program should try to approach. */
  40. int max_diff = 0; /* the diff value, when a hard readpointer skip should occur */
  41. int catch_factor = 1000;
  42. // Debug stuff:
  43. int print_counter = 10;
  44. volatile float output_resampling_factor = 0.0;
  45. volatile int output_new_delay = 0;
  46. volatile float output_offset = 0.0;
  47. volatile float output_diff = 0.0;
  48. // Alsa stuff... i dont want to touch this bullshit in the next years.... please...
  49. static int xrun_recovery(snd_pcm_t *handle, int err) {
  50. //printf( "xrun !!!....\n" );
  51. if (err == -EPIPE) { /* under-run */
  52. err = snd_pcm_prepare(handle);
  53. if (err < 0)
  54. printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err));
  55. return 0;
  56. } else if (err == -ESTRPIPE) {
  57. while ((err = snd_pcm_resume(handle)) == -EAGAIN)
  58. sleep(1); /* wait until the suspend flag is released */
  59. if (err < 0) {
  60. err = snd_pcm_prepare(handle);
  61. if (err < 0)
  62. printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err));
  63. }
  64. return 0;
  65. }
  66. return err;
  67. }
  68. 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 ) {
  69. int err, dir=0;
  70. /* choose all parameters */
  71. err = snd_pcm_hw_params_any(handle, params);
  72. if (err < 0) {
  73. printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
  74. return err;
  75. }
  76. /* set the interleaved read/write format */
  77. err = snd_pcm_hw_params_set_access(handle, params, access);
  78. if (err < 0) {
  79. printf("Access type not available for playback: %s\n", snd_strerror(err));
  80. return err;
  81. }
  82. /* set the sample format */
  83. err = snd_pcm_hw_params_set_format(handle, params, format);
  84. if (err < 0) {
  85. printf("Sample format not available for playback: %s\n", snd_strerror(err));
  86. return err;
  87. }
  88. /* set the count of channels */
  89. err = snd_pcm_hw_params_set_channels(handle, params, channels);
  90. if (err < 0) {
  91. printf("Channels count (%i) not available for record: %s\n", channels, snd_strerror(err));
  92. return err;
  93. }
  94. /* set the stream rate */
  95. err = snd_pcm_hw_params_set_rate_near(handle, params, rate, 0);
  96. if (err < 0) {
  97. printf("Rate %iHz not available for playback: %s\n", rate, snd_strerror(err));
  98. return err;
  99. }
  100. if (err != rate) {
  101. printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate, err);
  102. return -EINVAL;
  103. }
  104. /* set the buffer time */
  105. err = snd_pcm_hw_params_set_buffer_time_near(handle, params, 1000000*period*nperiods/rate, &dir);
  106. if (err < 0) {
  107. printf("Unable to set buffer time %i for playback: %s\n", 1000000*period*nperiods/rate, snd_strerror(err));
  108. return err;
  109. }
  110. if( snd_pcm_hw_params_get_buffer_size(params) != nperiods * period ) {
  111. printf( "WARNING: buffer size does not match: (requested %d, got %d)\n", nperiods * period, (int) snd_pcm_hw_params_get_buffer_size(params) );
  112. }
  113. /* set the period time */
  114. err = snd_pcm_hw_params_set_period_time_near(handle, params, 1000000*period/rate, &dir);
  115. if (err < 0) {
  116. printf("Unable to set period time %i for playback: %s\n", 1000000*period/rate, snd_strerror(err));
  117. return err;
  118. }
  119. int ps = snd_pcm_hw_params_get_period_size(params, NULL );
  120. if( ps != period ) {
  121. printf( "WARNING: period size does not match: (requested %i, got %i)\n", period, ps );
  122. }
  123. /* write the parameters to device */
  124. err = snd_pcm_hw_params(handle, params);
  125. if (err < 0) {
  126. printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
  127. return err;
  128. }
  129. return 0;
  130. }
  131. static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams, int period, int nperiods) {
  132. int err;
  133. /* get the current swparams */
  134. err = snd_pcm_sw_params_current(handle, swparams);
  135. if (err < 0) {
  136. printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err));
  137. return err;
  138. }
  139. /* start the transfer when the buffer is full */
  140. err = snd_pcm_sw_params_set_start_threshold(handle, swparams, period );
  141. if (err < 0) {
  142. printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
  143. return err;
  144. }
  145. err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, -1 );
  146. if (err < 0) {
  147. printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
  148. return err;
  149. }
  150. /* allow the transfer when at least period_size samples can be processed */
  151. err = snd_pcm_sw_params_set_avail_min(handle, swparams, 1 );
  152. if (err < 0) {
  153. printf("Unable to set avail min for capture: %s\n", snd_strerror(err));
  154. return err;
  155. }
  156. /* align all transfers to 1 sample */
  157. err = snd_pcm_sw_params_set_xfer_align(handle, swparams, 1);
  158. if (err < 0) {
  159. printf("Unable to set transfer align for capture: %s\n", snd_strerror(err));
  160. return err;
  161. }
  162. /* write the parameters to the playback device */
  163. err = snd_pcm_sw_params(handle, swparams);
  164. if (err < 0) {
  165. printf("Unable to set sw params for capture: %s\n", snd_strerror(err));
  166. return err;
  167. }
  168. return 0;
  169. }
  170. // ok... i only need this function to communicate with the alsa bloat api...
  171. static snd_pcm_t *open_audiofd( char *device_name, int capture, int rate, int channels, int period, int nperiods ) {
  172. int err;
  173. snd_pcm_t *handle;
  174. snd_pcm_hw_params_t *hwparams;
  175. snd_pcm_sw_params_t *swparams;
  176. snd_pcm_hw_params_alloca(&hwparams);
  177. snd_pcm_sw_params_alloca(&swparams);
  178. if ((err = snd_pcm_open(&(handle), device_name, capture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK )) < 0) {
  179. printf("Capture open error: %s\n", snd_strerror(err));
  180. return NULL;
  181. }
  182. if ((err = set_hwparams(handle, hwparams,SND_PCM_ACCESS_RW_INTERLEAVED, rate, channels, period, nperiods )) < 0) {
  183. printf("Setting of hwparams failed: %s\n", snd_strerror(err));
  184. return NULL;
  185. }
  186. if ((err = set_swparams(handle, swparams, period, nperiods)) < 0) {
  187. printf("Setting of swparams failed: %s\n", snd_strerror(err));
  188. return NULL;
  189. }
  190. //snd_pcm_start( handle );
  191. //snd_pcm_wait( handle, 200 );
  192. int num_null_samples = nperiods * period * channels;
  193. ALSASAMPLE *tmp = alloca( num_null_samples * sizeof( ALSASAMPLE ) );
  194. memset( tmp, 0, num_null_samples * sizeof( ALSASAMPLE ) );
  195. snd_pcm_writei( handle, tmp, num_null_samples );
  196. return handle;
  197. }
  198. jack_nframes_t soundcard_frames = 0;
  199. /**
  200. * The process callback for this JACK application.
  201. * It is called by JACK at the appropriate times.
  202. */
  203. int process (jack_nframes_t nframes, void *arg) {
  204. ALSASAMPLE *outbuf;
  205. float *floatbuf, *resampbuf;
  206. int rlen;
  207. int err;
  208. snd_pcm_sframes_t delay;
  209. jack_nframes_t this_frame_time;
  210. jack_nframes_t this_soundcard_time;
  211. int dont_adjust_resampling_factor = 0;
  212. double a, b;
  213. double offset;
  214. double diff_value;
  215. snd_pcm_delay( alsa_handle, &delay );
  216. this_frame_time = jack_frame_time(client);
  217. this_soundcard_time = soundcard_frames + delay;
  218. time_smoother_put( smoother, this_frame_time, this_soundcard_time );
  219. // Do it the hard way.
  220. // this is for compensating xruns etc...
  221. if( delay > (target_delay+max_diff) ) {
  222. snd_pcm_rewind( alsa_handle, delay - target_delay );
  223. soundcard_frames -= (delay-target_delay);
  224. output_new_delay = (int) delay;
  225. dont_adjust_resampling_factor = 1;
  226. //snd_pcm_delay( alsa_handle, &delay );
  227. delay = target_delay;
  228. // XXX: at least set it to that value.
  229. //current_resample_factor = (double) sample_rate / (double) jack_sample_rate;
  230. current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
  231. periods_until_stability = 10;
  232. }
  233. if( delay < (target_delay-max_diff) ) {
  234. ALSASAMPLE *tmp = alloca( (target_delay-delay) * sizeof( ALSASAMPLE ) * num_channels );
  235. memset( tmp, 0, sizeof( ALSASAMPLE ) * num_channels * (target_delay-delay) );
  236. snd_pcm_writei( alsa_handle, tmp, target_delay-delay );
  237. soundcard_frames += (target_delay-delay);
  238. output_new_delay = (int) delay;
  239. dont_adjust_resampling_factor = 1;
  240. //snd_pcm_delay( alsa_handle, &delay );
  241. delay = target_delay;
  242. // XXX: at least set it to that value.
  243. //current_resample_factor = (double) sample_rate / (double) jack_sample_rate;
  244. current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
  245. periods_until_stability = 10;
  246. }
  247. /* ok... now we should have target_delay +- max_diff on the alsa side.
  248. *
  249. * calculate the number of frames, we want to get.
  250. */
  251. //if( periods_until_stability ) {
  252. if( 1 ) {
  253. double resamp_rate = (double)jack_sample_rate / (double)sample_rate; // == nframes / alsa_samples.
  254. double request_samples = nframes / resamp_rate; //== alsa_samples;
  255. //double request_samples = nframes * current_resample_factor; //== alsa_samples;
  256. offset = delay - target_delay;
  257. //double frlen = request_samples - offset / catch_factor;
  258. double frlen = request_samples - offset;
  259. double compute_factor = frlen / (double) nframes;
  260. //double compute_factor = (double) nframes / frlen;
  261. diff_value = pow(current_resample_factor - compute_factor, 3) / (double) catch_factor;
  262. current_resample_factor -= diff_value;
  263. periods_until_stability -= 1;
  264. }
  265. else
  266. {
  267. time_smoother_get_linear_params( smoother, this_frame_time, this_soundcard_time, jack_get_sample_rate(client)/4,
  268. &a, &b );
  269. if( dont_adjust_resampling_factor ) {
  270. current_resample_factor = 1.0/( b - a/(double)nframes/(double)catch_factor );
  271. //double delay_diff = (double)delay - (double)target_delay;
  272. //current_resample_factor = 1.0/( b + a/(double)nframes - delay_diff/(double)nframes/(double)catch_factor );
  273. } else
  274. current_resample_factor = 1.0/b;
  275. offset = delay - target_delay;
  276. diff_value = b;
  277. }
  278. output_resampling_factor = (float) current_resample_factor;
  279. output_diff = (float) diff_value;
  280. output_offset = (float) offset;
  281. if( current_resample_factor < 0.25 ) current_resample_factor = 0.25;
  282. if( current_resample_factor > 4 ) current_resample_factor = 4;
  283. rlen = ceil( ((double)nframes) * current_resample_factor )+2;
  284. assert( rlen > 10 );
  285. /*
  286. * now this should do it...
  287. */
  288. outbuf = alloca( rlen * sizeof( ALSASAMPLE ) * num_channels );
  289. floatbuf = alloca( rlen * sizeof( float ) );
  290. resampbuf = alloca( nframes * sizeof( float ) );
  291. /*
  292. * render jack ports to the outbuf...
  293. */
  294. int chn = 0;
  295. JSList *node = playback_ports;
  296. JSList *src_node = playback_srcs;
  297. SRC_DATA src;
  298. while ( node != NULL)
  299. {
  300. int i;
  301. jack_port_t *port = (jack_port_t *) node->data;
  302. float *buf = jack_port_get_buffer (port, nframes);
  303. SRC_STATE *src_state = src_node->data;
  304. src.data_in = buf;
  305. src.input_frames = nframes;
  306. src.data_out = resampbuf;
  307. src.output_frames = rlen;
  308. src.end_of_input = 0;
  309. src.src_ratio = current_resample_factor;
  310. src_process( src_state, &src );
  311. for (i=0; i < rlen; i++) {
  312. outbuf[chn+ i*num_channels]= resampbuf[i] * 32767;
  313. }
  314. src_node = jack_slist_next (src_node);
  315. node = jack_slist_next (node);
  316. chn++;
  317. }
  318. // now write the output...
  319. again:
  320. err = snd_pcm_writei(alsa_handle, outbuf, src.output_frames_gen);
  321. if( err < 0 ) {
  322. printf( "err = %d\n", err );
  323. if (xrun_recovery(alsa_handle, err) < 0) {
  324. //printf("Write error: %s\n", snd_strerror(err));
  325. //exit(EXIT_FAILURE);
  326. }
  327. goto again;
  328. }
  329. soundcard_frames += err;
  330. // if( err != rlen ) {
  331. // printf( "write = %d\n", rlen );
  332. // }
  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_out";
  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( 0, num_channels );
  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) sample_rate / (double) jack_sample_rate;
  486. // now open the alsa fd...
  487. alsa_handle = open_audiofd( alsa_device, 0, 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. }
  503. jack_client_close (client);
  504. exit (0);
  505. }