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.

560 lines
15KB

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