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.

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