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.

633 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. // Do it the hard way.
  220. // this is for compensating xruns etc...
  221. if( delay > (target_delay+max_diff) ) {
  222. ALSASAMPLE *tmp = alloca( (delay-target_delay) * sizeof( ALSASAMPLE ) * num_channels );
  223. snd_pcm_readi( alsa_handle, tmp, delay-target_delay );
  224. soundcard_frames += (delay-target_delay);
  225. output_new_delay = (int) delay;
  226. dont_adjust_resampling_factor = 1;
  227. //delay = target_delay;
  228. // XXX: at least set it to that value.
  229. //current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
  230. }
  231. if( delay < (target_delay-max_diff) ) {
  232. snd_pcm_rewind( alsa_handle, target_delay - delay );
  233. soundcard_frames -= (target_delay-delay);
  234. output_new_delay = (int) delay;
  235. dont_adjust_resampling_factor = 1;
  236. //delay = target_delay;
  237. // XXX: at least set it to that value.
  238. //current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
  239. }
  240. if( 0 ) {
  241. /* ok... now we should have target_delay +- max_diff on the alsa side.
  242. *
  243. * calculate the number of frames, we want to get.
  244. */
  245. // float resamp_rate = (float)jack_sample_rate / (float)sample_rate; // == nframes / alsa_samples.
  246. // float request_samples = nframes / resamp_rate; //== alsa_samples;
  247. //float offset = delay - target_delay;
  248. //float frlen = request_samples + offset / catch_factor;
  249. //rlen = ceil( frlen );
  250. // This is the code from the alsa_out...
  251. double resamp_rate = (double)jack_sample_rate / (double)sample_rate; // == nframes / alsa_samples.
  252. double request_samples = nframes / resamp_rate; //== alsa_samples;
  253. //double request_samples = nframes / current_resample_factor; //== alsa_samples;
  254. double offset = delay - target_delay;
  255. //double frlen = request_samples - offset / catch_factor;
  256. double frlen = request_samples + offset;
  257. //alsa_out.c: double compute_factor = frlen / (double) nframes;
  258. double compute_factor = (double) nframes / frlen;
  259. double diff_value = pow(current_resample_factor - compute_factor, 3) / (double) catch_factor;
  260. current_resample_factor -= diff_value;
  261. current_resample_factor = current_resample_factor < 0.25 ? 0.25 : current_resample_factor;
  262. }
  263. time_smoother_get_linear_params( smoother, this_frame_time, this_soundcard_time, jack_get_sample_rate(client)/4,
  264. &a, &b );
  265. if( !dont_adjust_resampling_factor )
  266. current_resample_factor = b - a/(double)nframes/(double)catch_factor;
  267. else
  268. current_resample_factor = b;
  269. double offset = a;
  270. double diff_value = b;
  271. output_resampling_factor = (float) current_resample_factor;
  272. //if( fabs( offset ) > fabs( output_offset ) ) {
  273. output_diff = (float) diff_value;
  274. output_offset = (float) offset;
  275. //}
  276. if( current_resample_factor < 0.25 ) current_resample_factor = 0.25;
  277. if( current_resample_factor > 4 ) current_resample_factor = 4;
  278. rlen = ceil( ((double)nframes) * current_resample_factor )+2;
  279. assert( rlen > 10 );
  280. /*
  281. * now this should do it...
  282. */
  283. outbuf = alloca( rlen * sizeof( ALSASAMPLE ) * num_channels );
  284. floatbuf = alloca( rlen * sizeof( float ) );
  285. resampbuf = alloca( nframes * sizeof( float ) );
  286. // get the data...
  287. again:
  288. err = snd_pcm_readi(alsa_handle, outbuf, rlen);
  289. if( err < 0 ) {
  290. printf( "err = %d\n", err );
  291. if (xrun_recovery(alsa_handle, err) < 0) {
  292. //printf("Write error: %s\n", snd_strerror(err));
  293. //exit(EXIT_FAILURE);
  294. }
  295. goto again;
  296. }
  297. soundcard_frames += err;
  298. if( err != rlen ) {
  299. //printf( "read = %d\n", rlen );
  300. }
  301. /*
  302. * render jack ports to the outbuf...
  303. */
  304. int chn = 0;
  305. JSList *node = capture_ports;
  306. JSList *src_node = capture_srcs;
  307. while ( node != NULL)
  308. {
  309. int i;
  310. jack_port_t *port = (jack_port_t *) node->data;
  311. float *buf = jack_port_get_buffer (port, nframes);
  312. SRC_STATE *src_state = src_node->data;
  313. SRC_DATA src;
  314. for (i=0; i < rlen; i++) {
  315. resampbuf[i] = (float) outbuf[chn+ i*num_channels] / 32767;
  316. }
  317. src.data_in = resampbuf;
  318. src.input_frames = rlen;
  319. src.data_out = buf;
  320. src.output_frames = nframes;
  321. src.end_of_input = 0;
  322. //src.src_ratio = (float) nframes / frlen;
  323. src.src_ratio = current_resample_factor;
  324. //src_set_ratio( src_state, src.src_ratio );
  325. src_process( src_state, &src );
  326. put_back_samples = rlen-src.input_frames_used;
  327. if( src.output_frames_gen != nframes )
  328. //printf( "did not fill jack_buffer...\n" );
  329. src_node = jack_slist_next (src_node);
  330. node = jack_slist_next (node);
  331. chn++;
  332. }
  333. //printf( "putback = %d\n", put_back_samples );
  334. snd_pcm_rewind( alsa_handle, put_back_samples );
  335. soundcard_frames -= put_back_samples;
  336. return 0;
  337. }
  338. /**
  339. * Allocate the necessary jack ports...
  340. */
  341. void alloc_ports( int n_capture, int n_playback ) {
  342. int port_flags = JackPortIsOutput;
  343. int chn;
  344. jack_port_t *port;
  345. char buf[32];
  346. capture_ports = NULL;
  347. for (chn = 0; chn < n_capture; chn++)
  348. {
  349. snprintf (buf, sizeof(buf) - 1, "capture_%u", chn+1);
  350. port = jack_port_register (client, buf,
  351. JACK_DEFAULT_AUDIO_TYPE,
  352. port_flags, 0);
  353. if (!port)
  354. {
  355. printf( "jacknet_client: cannot register port for %s", buf);
  356. break;
  357. }
  358. capture_srcs = jack_slist_append( capture_srcs, src_new( SRC_SINC_FASTEST, 1, NULL ) );
  359. capture_ports = jack_slist_append (capture_ports, port);
  360. }
  361. port_flags = JackPortIsInput;
  362. playback_ports = NULL;
  363. for (chn = 0; chn < n_playback; chn++)
  364. {
  365. snprintf (buf, sizeof(buf) - 1, "playback_%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. playback_srcs = jack_slist_append( playback_srcs, src_new( SRC_SINC_FASTEST, 1, NULL ) );
  375. playback_ports = jack_slist_append (playback_ports, port);
  376. }
  377. }
  378. /**
  379. * This is the shutdown callback for this JACK application.
  380. * It is called by JACK if the server ever shuts down or
  381. * decides to disconnect the client.
  382. */
  383. void jack_shutdown (void *arg) {
  384. exit (1);
  385. }
  386. /**
  387. * be user friendly.
  388. * be user friendly.
  389. * be user friendly.
  390. */
  391. void printUsage() {
  392. fprintf(stderr, "usage: alsa_out [options]\n"
  393. "\n"
  394. " -j <jack name> - reports a different name to jack\n"
  395. " -d <alsa_device> \n"
  396. " -c <channels> \n"
  397. " -p <period_size> \n"
  398. " -n <num_period> \n"
  399. " -r <sample_rate> \n"
  400. " -m <max_diff> \n"
  401. " -t <target_delay> \n"
  402. " -f <catch_factor> \n"
  403. "\n");
  404. }
  405. /**
  406. * the main function....
  407. */
  408. int main (int argc, char *argv[]) {
  409. char jack_name[30] = "alsa_in";
  410. char alsa_device[30] = "hw:0";
  411. extern char *optarg;
  412. extern int optind, optopt;
  413. int errflg=0;
  414. int c;
  415. while ((c = getopt(argc, argv, ":j:r:c:p:n:d:m:t:f:")) != -1) {
  416. switch(c) {
  417. case 'j':
  418. strcpy(jack_name,optarg);
  419. break;
  420. case 'r':
  421. sample_rate = atoi(optarg);
  422. break;
  423. case 'c':
  424. num_channels = atoi(optarg);
  425. break;
  426. case 'p':
  427. period_size = atoi(optarg);
  428. break;
  429. case 'n':
  430. num_periods = atoi(optarg);
  431. break;
  432. case 'd':
  433. strcpy(alsa_device,optarg);
  434. break;
  435. case 't':
  436. target_delay = atoi(optarg);
  437. break;
  438. case 'm':
  439. max_diff = atoi(optarg);
  440. break;
  441. case 'f':
  442. catch_factor = atoi(optarg);
  443. break;
  444. case ':':
  445. fprintf(stderr,
  446. "Option -%c requires an operand\n", optopt);
  447. errflg++;
  448. break;
  449. case '?':
  450. fprintf(stderr,
  451. "Unrecognized option: -%c\n", optopt);
  452. errflg++;
  453. }
  454. }
  455. if (errflg) {
  456. printUsage();
  457. exit(2);
  458. }
  459. // Setup target delay and max_diff for the normal user, who does not play with them...
  460. if( !target_delay )
  461. target_delay = num_periods*period_size / 2;
  462. if( !max_diff )
  463. max_diff = period_size / 2;
  464. smoother = time_smoother_new( 100 );
  465. if( !smoother ) {
  466. fprintf (stderr, "no memory\n");
  467. return 10;
  468. }
  469. if ((client = jack_client_new (jack_name)) == 0) {
  470. fprintf (stderr, "jack server not running?\n");
  471. return 1;
  472. }
  473. /* tell the JACK server to call `process()' whenever
  474. there is work to be done.
  475. */
  476. jack_set_process_callback (client, process, 0);
  477. /* tell the JACK server to call `jack_shutdown()' if
  478. it ever shuts down, either entirely, or if it
  479. just decides to stop calling us.
  480. */
  481. jack_on_shutdown (client, jack_shutdown, 0);
  482. // alloc input ports, which are blasted out to alsa...
  483. alloc_ports( num_channels, 0 );
  484. // get jack sample_rate
  485. jack_sample_rate = jack_get_sample_rate( client );
  486. if( !sample_rate )
  487. sample_rate = jack_sample_rate;
  488. current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
  489. //// now open the alsa fd...
  490. alsa_handle = open_audiofd( alsa_device, 1, sample_rate, num_channels, period_size, num_periods);
  491. if( alsa_handle < 0 )
  492. exit(20);
  493. /* tell the JACK server that we are ready to roll */
  494. if (jack_activate (client)) {
  495. fprintf (stderr, "cannot activate client");
  496. return 1;
  497. }
  498. while(1) {
  499. usleep(500000);
  500. if( output_new_delay ) {
  501. printf( "delay = %d\n", output_new_delay );
  502. output_new_delay = 0;
  503. }
  504. printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor, output_diff, output_offset );
  505. output_offset = 0.0;
  506. }
  507. jack_client_close (client);
  508. exit (0);
  509. }