more consistent naming of MIDI ports (vs. audio); drop use of ALSA seq client ID...
[jack.git] / tools / alsa_in.c
blob8874efcf621006784cea6e90b5e89da070b1921c
1 /** @file simple_client.c
3 * @brief This simple client demonstrates the basic features of JACK
4 * as they would be used by many applications.
5 */
7 #include <stdio.h>
8 #include <errno.h>
9 #include <unistd.h>
10 #include <stdlib.h>
11 #include <string.h>
13 #include <alloca.h>
14 #include <math.h>
16 #include <jack/jack.h>
17 #include <jack/jslist.h>
19 #define ALSA_PCM_OLD_HW_PARAMS_API
20 #define ALSA_PCM_OLD_SW_PARAMS_API
21 #include "alsa/asoundlib.h"
23 #include <samplerate.h>
25 typedef signed short ALSASAMPLE;
27 // Here are the lists of the jack ports...
29 JSList *capture_ports = NULL;
30 JSList *capture_srcs = NULL;
31 JSList *playback_ports = NULL;
32 JSList *playback_srcs = NULL;
33 jack_client_t *client;
35 // TODO: make the sample format configurable soon...
36 snd_pcm_format_t format = SND_PCM_FORMAT_S16; /* sample format */
38 snd_pcm_t *alsa_handle;
40 int jack_sample_rate;
42 double current_resample_factor = 1.0;
44 // ------------------------------------------------------ commandline parameters
46 int sample_rate = 0; /* stream rate */
47 int num_channels = 2; /* count of channels */
48 int period_size = 1024;
49 int num_periods = 2;
51 int target_delay = 0; /* the delay which the program should try to approach. */
52 int max_diff = 0; /* the diff value, when a hard readpointer skip should occur */
53 int catch_factor = 1000;
55 // Debug stuff:
57 int print_counter = 10;
59 // Alsa stuff... i dont want to touch this bullshit in the next years.... please...
61 static int xrun_recovery(snd_pcm_t *handle, int err) {
62 //printf( "xrun !!!....\n" );
63 if (err == -EPIPE) { /* under-run */
64 err = snd_pcm_prepare(handle);
65 if (err < 0)
66 printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err));
67 return 0;
68 } else if (err == -ESTRPIPE) {
69 while ((err = snd_pcm_resume(handle)) == -EAGAIN)
70 sleep(1); /* wait until the suspend flag is released */
71 if (err < 0) {
72 err = snd_pcm_prepare(handle);
73 if (err < 0)
74 printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err));
76 return 0;
78 return err;
81 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 ) {
82 int err, dir=0;
84 /* choose all parameters */
85 err = snd_pcm_hw_params_any(handle, params);
86 if (err < 0) {
87 printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
88 return err;
90 /* set the interleaved read/write format */
91 err = snd_pcm_hw_params_set_access(handle, params, access);
92 if (err < 0) {
93 printf("Access type not available for playback: %s\n", snd_strerror(err));
94 return err;
96 /* set the sample format */
97 err = snd_pcm_hw_params_set_format(handle, params, format);
98 if (err < 0) {
99 printf("Sample format not available for playback: %s\n", snd_strerror(err));
100 return err;
102 /* set the count of channels */
103 err = snd_pcm_hw_params_set_channels(handle, params, channels);
104 if (err < 0) {
105 printf("Channels count (%i) not available for record: %s\n", channels, snd_strerror(err));
106 return err;
108 /* set the stream rate */
109 err = snd_pcm_hw_params_set_rate_near(handle, params, rate, 0);
110 if (err < 0) {
111 printf("Rate %iHz not available for capture: %s\n", rate, snd_strerror(err));
112 return err;
114 if (err != rate) {
115 printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate, err);
116 return -EINVAL;
118 /* set the buffer time */
119 err = snd_pcm_hw_params_set_buffer_time_near(handle, params, 1000000*period*nperiods/rate, &dir);
120 if (err < 0) {
121 printf("Unable to set buffer time %i for playback: %s\n", 1000000*period*nperiods/rate, snd_strerror(err));
122 return err;
124 if( snd_pcm_hw_params_get_buffer_size(params) != nperiods * period ) {
125 printf( "WARNING: buffer size does not match: (requested %d, got %d)\n", nperiods * period, (int) snd_pcm_hw_params_get_buffer_size(params) );
127 /* set the period time */
128 err = snd_pcm_hw_params_set_period_time_near(handle, params, 1000000*period/rate, &dir);
129 if (err < 0) {
130 printf("Unable to set period time %i for playback: %s\n", 1000000*period/rate, snd_strerror(err));
131 return err;
133 int ps = snd_pcm_hw_params_get_period_size(params, NULL );
134 if( ps != period ) {
135 printf( "WARNING: period size does not match: (requested %i, got %i)\n", period, ps );
137 /* write the parameters to device */
138 err = snd_pcm_hw_params(handle, params);
139 if (err < 0) {
140 printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
141 return err;
143 return 0;
146 static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams, int period) {
147 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;
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;
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;
166 /* allow the transfer when at least period_size samples can be processed */
167 err = snd_pcm_sw_params_set_avail_min(handle, swparams, period );
168 if (err < 0) {
169 printf("Unable to set avail min for capture: %s\n", snd_strerror(err));
170 return err;
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;
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;
184 return 0;
187 // ok... i only need this function to communicate with the alsa bloat api...
189 static snd_pcm_t *open_audiofd( char *device_name, int capture, int rate, int channels, int period, int nperiods ) {
190 int err;
191 snd_pcm_t *handle;
192 snd_pcm_hw_params_t *hwparams;
193 snd_pcm_sw_params_t *swparams;
195 snd_pcm_hw_params_alloca(&hwparams);
196 snd_pcm_sw_params_alloca(&swparams);
198 if ((err = snd_pcm_open(&(handle), device_name, capture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK )) < 0) {
199 printf("Capture open error: %s\n", snd_strerror(err));
200 return NULL;
203 if ((err = set_hwparams(handle, hwparams,SND_PCM_ACCESS_RW_INTERLEAVED, rate, channels, period, nperiods )) < 0) {
204 printf("Setting of hwparams failed: %s\n", snd_strerror(err));
205 return NULL;
207 if ((err = set_swparams(handle, swparams, period)) < 0) {
208 printf("Setting of swparams failed: %s\n", snd_strerror(err));
209 return NULL;
212 snd_pcm_start( handle );
213 snd_pcm_wait( handle, 200 );
215 return handle;
220 * The process callback for this JACK application.
221 * It is called by JACK at the appropriate times.
223 int process (jack_nframes_t nframes, void *arg) {
225 ALSASAMPLE *outbuf;
226 float *floatbuf, *resampbuf;
227 int rlen;
228 int err;
229 snd_pcm_sframes_t delay;
230 int put_back_samples=0;
233 snd_pcm_delay( alsa_handle, &delay );
235 delay = delay;
236 // Do it the hard way.
237 // this is for compensating xruns etc...
239 if( delay > (target_delay+max_diff) ) {
240 ALSASAMPLE *tmp = alloca( (delay-target_delay) * sizeof( ALSASAMPLE ) * num_channels );
241 snd_pcm_readi( alsa_handle, tmp, delay-target_delay );
242 printf( "delay = %d\n", (int) delay );
243 delay = target_delay;
244 // XXX: at least set it to that value.
245 current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
247 if( delay < (target_delay-max_diff) ) {
248 snd_pcm_rewind( alsa_handle, target_delay - delay );
249 printf( "delay = %d\n", (int) delay );
250 delay = target_delay;
251 // XXX: at least set it to that value.
252 current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
255 /* ok... now we should have target_delay +- max_diff on the alsa side.
257 * calculate the number of frames, we want to get.
260 // float resamp_rate = (float)jack_sample_rate / (float)sample_rate; // == nframes / alsa_samples.
261 // float request_samples = nframes / resamp_rate; //== alsa_samples;
263 //float offset = delay - target_delay;
265 //float frlen = request_samples + offset / catch_factor;
266 //rlen = ceil( frlen );
268 // This is the code from the alsa_out...
270 double resamp_rate = (double)jack_sample_rate / (double)sample_rate; // == nframes / alsa_samples.
271 double request_samples = nframes / resamp_rate; //== alsa_samples;
273 double offset = delay - target_delay;
275 //double frlen = request_samples - offset / catch_factor;
276 double frlen = request_samples + offset;
277 //alsa_out.c: double compute_factor = frlen / (double) nframes;
278 double compute_factor = (double) nframes / frlen;
280 double diff_value = pow(current_resample_factor - compute_factor, 3) / (double) catch_factor;
281 current_resample_factor -= diff_value;
282 rlen = ceil( ((double)nframes) / current_resample_factor )+2;
284 if( (print_counter--) == 0 ) {
285 print_counter = 10;
286 printf( "res: %f, \tdiff = %f, \toffset = %f \n", (float)current_resample_factor, (float)diff_value, (float) offset );
290 * now this should do it...
293 outbuf = alloca( rlen * sizeof( ALSASAMPLE ) * num_channels );
295 floatbuf = alloca( rlen * sizeof( float ) );
296 resampbuf = alloca( nframes * sizeof( float ) );
298 // get the data...
299 again:
300 err = snd_pcm_readi(alsa_handle, outbuf, rlen);
301 if( err < 0 ) {
302 printf( "err = %d\n", err );
303 if (xrun_recovery(alsa_handle, err) < 0) {
304 //printf("Write error: %s\n", snd_strerror(err));
305 //exit(EXIT_FAILURE);
307 goto again;
309 if( err != rlen ) {
310 printf( "read = %d\n", rlen );
314 * render jack ports to the outbuf...
317 int chn = 0;
318 JSList *node = capture_ports;
319 JSList *src_node = capture_srcs;
320 while ( node != NULL)
322 int i;
323 jack_port_t *port = (jack_port_t *) node->data;
324 float *buf = jack_port_get_buffer (port, nframes);
326 SRC_STATE *src_state = src_node->data;
327 SRC_DATA src;
329 for (i=0; i < rlen; i++) {
330 resampbuf[i] = (float) outbuf[chn+ i*num_channels] / 32767;
333 src.data_in = resampbuf;
334 src.input_frames = rlen;
336 src.data_out = buf;
337 src.output_frames = nframes;
338 src.end_of_input = 0;
340 //src.src_ratio = (float) nframes / frlen;
341 src.src_ratio = current_resample_factor;
343 //src_set_ratio( src_state, src.src_ratio );
344 src_process( src_state, &src );
346 put_back_samples = rlen-src.input_frames_used;
348 if( src.output_frames_gen != nframes )
349 printf( "did not fill jack_buffer...\n" );
351 src_node = jack_slist_next (src_node);
352 node = jack_slist_next (node);
353 chn++;
356 //printf( "putback = %d\n", put_back_samples );
357 snd_pcm_rewind( alsa_handle, put_back_samples );
359 return 0;
364 * Allocate the necessary jack ports...
367 void alloc_ports( int n_capture, int n_playback ) {
369 int port_flags = JackPortIsOutput;
370 int chn;
371 jack_port_t *port;
372 char buf[32];
374 capture_ports = NULL;
375 for (chn = 0; chn < n_capture; chn++)
377 snprintf (buf, sizeof(buf) - 1, "capture_%u", chn+1);
379 port = jack_port_register (client, buf,
380 JACK_DEFAULT_AUDIO_TYPE,
381 port_flags, 0);
383 if (!port)
385 printf( "jacknet_client: cannot register port for %s", buf);
386 break;
389 capture_srcs = jack_slist_append( capture_srcs, src_new( SRC_SINC_FASTEST, 1, NULL ) );
390 capture_ports = jack_slist_append (capture_ports, port);
393 port_flags = JackPortIsInput;
395 playback_ports = NULL;
396 for (chn = 0; chn < n_playback; chn++)
398 snprintf (buf, sizeof(buf) - 1, "playback_%u", chn+1);
400 port = jack_port_register (client, buf,
401 JACK_DEFAULT_AUDIO_TYPE,
402 port_flags, 0);
404 if (!port)
406 printf( "jacknet_client: cannot register port for %s", buf);
407 break;
410 playback_srcs = jack_slist_append( playback_srcs, src_new( SRC_SINC_FASTEST, 1, NULL ) );
411 playback_ports = jack_slist_append (playback_ports, port);
416 * This is the shutdown callback for this JACK application.
417 * It is called by JACK if the server ever shuts down or
418 * decides to disconnect the client.
421 void jack_shutdown (void *arg) {
423 exit (1);
427 * be user friendly.
428 * be user friendly.
429 * be user friendly.
432 void printUsage() {
433 fprintf(stderr, "usage: alsa_out [options]\n"
434 "\n"
435 " -j <jack name> - reports a different name to jack\n"
436 " -d <alsa_device> \n"
437 " -c <channels> \n"
438 " -p <period_size> \n"
439 " -n <num_period> \n"
440 " -r <sample_rate> \n"
441 " -m <max_diff> \n"
442 " -t <target_delay> \n"
443 " -f <catch_factor> \n"
444 "\n");
449 * the main function....
453 int main (int argc, char *argv[]) {
454 char jack_name[30] = "alsa_in";
455 char alsa_device[30] = "hw:0";
457 extern char *optarg;
458 extern int optind, optopt;
459 int errflg=0;
460 int c;
462 while ((c = getopt(argc, argv, ":j:r:c:p:n:d:m:t:f:")) != -1) {
463 switch(c) {
464 case 'j':
465 strcpy(jack_name,optarg);
466 break;
467 case 'r':
468 sample_rate = atoi(optarg);
469 break;
470 case 'c':
471 num_channels = atoi(optarg);
472 break;
473 case 'p':
474 period_size = atoi(optarg);
475 break;
476 case 'n':
477 num_periods = atoi(optarg);
478 break;
479 case 'd':
480 strcpy(alsa_device,optarg);
481 break;
482 case 't':
483 target_delay = atoi(optarg);
484 break;
485 case 'm':
486 max_diff = atoi(optarg);
487 break;
488 case 'f':
489 catch_factor = atoi(optarg);
490 break;
491 case ':':
492 fprintf(stderr,
493 "Option -%c requires an operand\n", optopt);
494 errflg++;
495 break;
496 case '?':
497 fprintf(stderr,
498 "Unrecognized option: -%c\n", optopt);
499 errflg++;
502 if (errflg) {
503 printUsage();
504 exit(2);
507 // Setup target delay and max_diff for the normal user, who does not play with them...
509 if( !target_delay )
510 target_delay = num_periods*period_size / 2;
512 if( !max_diff )
513 max_diff = period_size / 2;
517 if ((client = jack_client_new (jack_name)) == 0) {
518 fprintf (stderr, "jack server not running?\n");
519 return 1;
522 /* tell the JACK server to call `process()' whenever
523 there is work to be done.
526 jack_set_process_callback (client, process, 0);
528 /* tell the JACK server to call `jack_shutdown()' if
529 it ever shuts down, either entirely, or if it
530 just decides to stop calling us.
533 jack_on_shutdown (client, jack_shutdown, 0);
536 // alloc input ports, which are blasted out to alsa...
537 alloc_ports( num_channels, 0 );
539 // get jack sample_rate
541 jack_sample_rate = jack_get_sample_rate( client );
543 if( !sample_rate )
544 sample_rate = jack_sample_rate;
546 current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
547 //// now open the alsa fd...
549 alsa_handle = open_audiofd( alsa_device, 1, sample_rate, num_channels, period_size, num_periods);
550 if( alsa_handle < 0 )
551 exit(20);
554 /* tell the JACK server that we are ready to roll */
556 if (jack_activate (client)) {
557 fprintf (stderr, "cannot activate client");
558 return 1;
561 while(1) sleep(1);
562 jack_client_close (client);
563 exit (0);