Merge branch 'master' into port_register_notification_defer
[jack2.git] / example-clients / alsa_in.c
blob2a8b78c31652c1ca9978c8a4d7f9e47eb9e4fc41
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>
12 #include <signal.h>
14 #include <alloca.h>
15 #include <math.h>
17 #include <jack/jack.h>
18 #include <jack/jslist.h>
19 #include <memops.h>
21 #include "alsa/asoundlib.h"
23 #include <samplerate.h>
25 // Here are the lists of the jack ports...
27 JSList *capture_ports = NULL;
28 JSList *capture_srcs = NULL;
29 JSList *playback_ports = NULL;
30 JSList *playback_srcs = NULL;
31 jack_client_t *client;
33 snd_pcm_t *alsa_handle;
35 int jack_sample_rate;
36 int jack_buffer_size;
38 int quit = 0;
39 double resample_mean = 1.0;
40 double static_resample_factor = 1.0;
42 double *offset_array;
43 double *window_array;
44 int offset_differential_index = 0;
46 double offset_integral = 0;
48 // ------------------------------------------------------ commandline parameters
50 int sample_rate = 0; /* stream rate */
51 int num_channels = 2; /* count of channels */
52 int period_size = 1024;
53 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 = 100000;
58 int catch_factor2 = 10000;
59 double pclamp = 15.0;
60 double controlquant = 10000.0;
61 int smooth_size = 256;
62 int good_window=0;
63 int verbose = 0;
64 int instrument = 0;
65 int samplerate_quality = 2;
67 // Debug stuff:
69 volatile float output_resampling_factor = 1.0;
70 volatile int output_new_delay = 0;
71 volatile float output_offset = 0.0;
72 volatile float output_integral = 0.0;
73 volatile float output_diff = 0.0;
75 snd_pcm_uframes_t real_buffer_size;
76 snd_pcm_uframes_t real_period_size;
78 // format selection, and corresponding functions from memops in a nice set of structs.
80 typedef struct alsa_format {
81 snd_pcm_format_t format_id;
82 size_t sample_size;
83 void (*jack_to_soundcard) (char *dst, jack_default_audio_sample_t *src, unsigned long nsamples, unsigned long dst_skip, dither_state_t *state);
84 void (*soundcard_to_jack) (jack_default_audio_sample_t *dst, char *src, unsigned long nsamples, unsigned long src_skip);
85 const char *name;
86 } alsa_format_t;
88 alsa_format_t formats[] = {
89 { SND_PCM_FORMAT_FLOAT_LE, 4, sample_move_dS_floatLE, sample_move_floatLE_sSs, "float" },
90 { SND_PCM_FORMAT_S32, 4, sample_move_d32u24_sS, sample_move_dS_s32u24, "32bit" },
91 { SND_PCM_FORMAT_S24_3LE, 3, sample_move_d24_sS, sample_move_dS_s24, "24bit - real" },
92 { SND_PCM_FORMAT_S24, 4, sample_move_d24_sS, sample_move_dS_s24, "24bit" },
93 { SND_PCM_FORMAT_S16, 2, sample_move_d16_sS, sample_move_dS_s16, "16bit" }
95 #define NUMFORMATS (sizeof(formats)/sizeof(formats[0]))
96 int format=0;
98 // Alsa stuff... i dont want to touch this bullshit in the next years.... please...
100 static int xrun_recovery(snd_pcm_t *handle, int err) {
101 // printf( "xrun !!!.... %d\n", err );
102 if (err == -EPIPE) { /* under-run */
103 err = snd_pcm_prepare(handle);
104 if (err < 0)
105 printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err));
106 return 0;
107 } else if (err == -EAGAIN) {
108 while ((err = snd_pcm_resume(handle)) == -EAGAIN)
109 usleep(100); /* wait until the suspend flag is released */
110 if (err < 0) {
111 err = snd_pcm_prepare(handle);
112 if (err < 0)
113 printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err));
115 return 0;
117 return err;
120 static int set_hwformat( snd_pcm_t *handle, snd_pcm_hw_params_t *params )
122 int i;
123 int err;
125 for( i=0; i<NUMFORMATS; i++ ) {
126 /* set the sample format */
127 err = snd_pcm_hw_params_set_format(handle, params, formats[i].format_id);
128 if (err == 0) {
129 format = i;
130 return 0;
134 return err;
137 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 ) {
138 int err, dir=0;
139 unsigned int buffer_time;
140 unsigned int period_time;
141 unsigned int rrate;
142 unsigned int rchannels;
144 /* choose all parameters */
145 err = snd_pcm_hw_params_any(handle, params);
146 if (err < 0) {
147 printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
148 return err;
150 /* set the interleaved read/write format */
151 err = snd_pcm_hw_params_set_access(handle, params, access);
152 if (err < 0) {
153 printf("Access type not available for playback: %s\n", snd_strerror(err));
154 return err;
157 /* set the sample format */
158 err = set_hwformat(handle, params);
159 if (err < 0) {
160 printf("Sample format not available for playback: %s\n", snd_strerror(err));
161 return err;
163 /* set the count of channels */
164 rchannels = channels;
165 err = snd_pcm_hw_params_set_channels_near(handle, params, &rchannels);
166 if (err < 0) {
167 printf("Channels count (%i) not available for record: %s\n", channels, snd_strerror(err));
168 return err;
170 if (rchannels != channels) {
171 printf("WARNING: chennel count does not match (requested %d got %d)\n", channels, rchannels);
172 num_channels = rchannels;
174 /* set the stream rate */
175 rrate = rate;
176 err = snd_pcm_hw_params_set_rate_near(handle, params, &rrate, 0);
177 if (err < 0) {
178 printf("Rate %iHz not available for playback: %s\n", rate, snd_strerror(err));
179 return err;
181 if (rrate != rate) {
182 printf("WARNING: Rate doesn't match (requested %iHz, get %iHz)\n", rate, rrate);
183 sample_rate = rrate;
185 /* set the buffer time */
187 buffer_time = 1000000*period*nperiods/rate;
188 err = snd_pcm_hw_params_set_buffer_time_near(handle, params, &buffer_time, &dir);
189 if (err < 0) {
190 printf("Unable to set buffer time %i for playback: %s\n", 1000000*period*nperiods/rate, snd_strerror(err));
191 return err;
193 err = snd_pcm_hw_params_get_buffer_size( params, &real_buffer_size );
194 if (err < 0) {
195 printf("Unable to get buffer size back: %s\n", snd_strerror(err));
196 return err;
198 if( real_buffer_size != nperiods * period ) {
199 printf( "WARNING: buffer size does not match: (requested %d, got %d)\n", nperiods * period, (int) real_buffer_size );
201 /* set the period time */
202 period_time = 1000000*period/rate;
203 err = snd_pcm_hw_params_set_period_time_near(handle, params, &period_time, &dir);
204 if (err < 0) {
205 printf("Unable to set period time %i for playback: %s\n", 1000000*period/rate, snd_strerror(err));
206 return err;
208 err = snd_pcm_hw_params_get_period_size(params, &real_period_size, NULL );
209 if (err < 0) {
210 printf("Unable to get period size back: %s\n", snd_strerror(err));
211 return err;
213 if( real_period_size != period ) {
214 printf( "WARNING: period size does not match: (requested %i, got %i)\n", period, (int)real_period_size );
216 /* write the parameters to device */
217 err = snd_pcm_hw_params(handle, params);
218 if (err < 0) {
219 printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
220 return err;
222 return 0;
225 static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams, int period) {
226 int err;
228 /* get the current swparams */
229 err = snd_pcm_sw_params_current(handle, swparams);
230 if (err < 0) {
231 printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err));
232 return err;
234 /* start the transfer when the buffer is full */
235 err = snd_pcm_sw_params_set_start_threshold(handle, swparams, period );
236 if (err < 0) {
237 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
238 return err;
240 err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, -1 );
241 if (err < 0) {
242 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
243 return err;
245 /* allow the transfer when at least period_size samples can be processed */
246 err = snd_pcm_sw_params_set_avail_min(handle, swparams, 2*period );
247 if (err < 0) {
248 printf("Unable to set avail min for capture: %s\n", snd_strerror(err));
249 return err;
251 /* align all transfers to 1 sample */
252 err = snd_pcm_sw_params_set_xfer_align(handle, swparams, 1);
253 if (err < 0) {
254 printf("Unable to set transfer align for capture: %s\n", snd_strerror(err));
255 return err;
257 /* write the parameters to the playback device */
258 err = snd_pcm_sw_params(handle, swparams);
259 if (err < 0) {
260 printf("Unable to set sw params for capture: %s\n", snd_strerror(err));
261 return err;
263 return 0;
266 // ok... i only need this function to communicate with the alsa bloat api...
268 static snd_pcm_t *open_audiofd( char *device_name, int capture, int rate, int channels, int period, int nperiods ) {
269 int err;
270 snd_pcm_t *handle;
271 snd_pcm_hw_params_t *hwparams;
272 snd_pcm_sw_params_t *swparams;
274 snd_pcm_hw_params_alloca(&hwparams);
275 snd_pcm_sw_params_alloca(&swparams);
277 if ((err = snd_pcm_open(&(handle), device_name, capture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK )) < 0) {
278 printf("Capture open error: %s\n", snd_strerror(err));
279 return NULL;
282 if ((err = set_hwparams(handle, hwparams,SND_PCM_ACCESS_RW_INTERLEAVED, rate, channels, period, nperiods )) < 0) {
283 printf("Setting of hwparams failed: %s\n", snd_strerror(err));
284 return NULL;
286 if ((err = set_swparams(handle, swparams, period)) < 0) {
287 printf("Setting of swparams failed: %s\n", snd_strerror(err));
288 return NULL;
291 snd_pcm_start( handle );
292 snd_pcm_wait( handle, 200 );
294 return handle;
297 double hann( double x )
299 return 0.5 * (1.0 - cos( 2*M_PI * x ) );
303 * The process callback for this JACK application.
304 * It is called by JACK at the appropriate times.
306 int process (jack_nframes_t nframes, void *arg) {
308 char *outbuf;
309 float *resampbuf;
310 int rlen;
311 int err;
312 snd_pcm_sframes_t delay = target_delay;
313 int put_back_samples=0;
314 int i;
316 delay = snd_pcm_avail( alsa_handle );
318 delay -= jack_frames_since_cycle_start( client );
319 // Do it the hard way.
320 // this is for compensating xruns etc...
322 if( delay > (target_delay+max_diff) ) {
323 char *tmp = alloca( (delay-target_delay) * formats[format].sample_size * num_channels );
324 snd_pcm_readi( alsa_handle, tmp, delay-target_delay );
325 output_new_delay = (int) delay;
327 delay = target_delay;
329 // Set the resample_rate... we need to adjust the offset integral, to do this.
330 // first look at the PI controller, this code is just a special case, which should never execute once
331 // everything is swung in.
332 offset_integral = - (resample_mean - static_resample_factor) * catch_factor * catch_factor2;
333 // Also clear the array. we are beginning a new control cycle.
334 for( i=0; i<smooth_size; i++ )
335 offset_array[i] = 0.0;
337 if( delay < (target_delay-max_diff) ) {
338 snd_pcm_rewind( alsa_handle, target_delay - delay );
339 output_new_delay = (int) delay;
340 delay = target_delay;
342 // Set the resample_rate... we need to adjust the offset integral, to do this.
343 offset_integral = - (resample_mean - static_resample_factor) * catch_factor * catch_factor2;
344 // Also clear the array. we are beginning a new control cycle.
345 for( i=0; i<smooth_size; i++ )
346 offset_array[i] = 0.0;
348 /* ok... now we should have target_delay +- max_diff on the alsa side.
350 * calculate the number of frames, we want to get.
353 double offset = delay - target_delay;
355 // Save offset.
356 offset_array[(offset_differential_index++)% smooth_size ] = offset;
358 // Build the mean of the windowed offset array
359 // basically fir lowpassing.
360 double smooth_offset = 0.0;
361 for( i=0; i<smooth_size; i++ )
362 smooth_offset +=
363 offset_array[ (i + offset_differential_index-1) % smooth_size] * window_array[i];
364 smooth_offset /= (double) smooth_size;
366 // this is the integral of the smoothed_offset
367 offset_integral += smooth_offset;
369 // Clamp offset.
370 // the smooth offset still contains unwanted noise
371 // which would go straigth onto the resample coeff.
372 // it only used in the P component and the I component is used for the fine tuning anyways.
373 if( fabs( smooth_offset ) < pclamp )
374 smooth_offset = 0.0;
376 // ok. now this is the PI controller.
377 // u(t) = K * ( e(t) + 1/T \int e(t') dt' )
378 // K = 1/catch_factor and T = catch_factor2
379 double current_resample_factor = static_resample_factor - smooth_offset / (double) catch_factor - offset_integral / (double) catch_factor / (double)catch_factor2;
381 // now quantize this value around resample_mean, so that the noise which is in the integral component doesnt hurt.
382 current_resample_factor = floor( (current_resample_factor - resample_mean) * controlquant + 0.5 ) / controlquant + resample_mean;
384 // Output "instrumentatio" gonna change that to real instrumentation in a few.
385 output_resampling_factor = (float) current_resample_factor;
386 output_diff = (float) smooth_offset;
387 output_integral = (float) offset_integral;
388 output_offset = (float) offset;
390 // Clamp a bit.
391 if( current_resample_factor < 0.25 ) current_resample_factor = 0.25;
392 if( current_resample_factor > 4 ) current_resample_factor = 4;
394 // Now Calculate how many samples we need.
395 rlen = ceil( ((double)nframes) / current_resample_factor )+2;
396 assert( rlen > 2 );
398 // Calculate resample_mean so we can init ourselves to saner values.
399 resample_mean = 0.9999 * resample_mean + 0.0001 * current_resample_factor;
401 * now this should do it...
404 outbuf = alloca( rlen * formats[format].sample_size * num_channels );
406 resampbuf = alloca( rlen * sizeof( float ) );
408 // get the data...
409 again:
410 err = snd_pcm_readi(alsa_handle, outbuf, rlen);
411 if( err < 0 ) {
412 printf( "err = %d\n", err );
413 if (xrun_recovery(alsa_handle, err) < 0) {
414 //printf("Write error: %s\n", snd_strerror(err));
415 //exit(EXIT_FAILURE);
417 goto again;
419 if( err != rlen ) {
420 //printf( "read = %d\n", rlen );
424 * render jack ports to the outbuf...
427 int chn = 0;
428 JSList *node = capture_ports;
429 JSList *src_node = capture_srcs;
430 SRC_DATA src;
432 while ( node != NULL)
434 jack_port_t *port = (jack_port_t *) node->data;
435 float *buf = jack_port_get_buffer (port, nframes);
437 SRC_STATE *src_state = src_node->data;
439 formats[format].soundcard_to_jack( resampbuf, outbuf + format[formats].sample_size * chn, rlen, num_channels*format[formats].sample_size );
441 src.data_in = resampbuf;
442 src.input_frames = rlen;
444 src.data_out = buf;
445 src.output_frames = nframes;
446 src.end_of_input = 0;
448 src.src_ratio = current_resample_factor;
450 src_process( src_state, &src );
452 put_back_samples = rlen-src.input_frames_used;
454 src_node = jack_slist_next (src_node);
455 node = jack_slist_next (node);
456 chn++;
459 // Put back the samples libsamplerate did not consume.
460 //printf( "putback = %d\n", put_back_samples );
461 snd_pcm_rewind( alsa_handle, put_back_samples );
463 return 0;
468 * Allocate the necessary jack ports...
471 void alloc_ports( int n_capture, int n_playback ) {
473 int port_flags = JackPortIsOutput;
474 int chn;
475 jack_port_t *port;
476 char buf[32];
478 capture_ports = NULL;
479 for (chn = 0; chn < n_capture; chn++)
481 snprintf (buf, sizeof(buf) - 1, "capture_%u", chn+1);
483 port = jack_port_register (client, buf,
484 JACK_DEFAULT_AUDIO_TYPE,
485 port_flags, 0);
487 if (!port)
489 printf( "jacknet_client: cannot register port for %s", buf);
490 break;
493 capture_srcs = jack_slist_append( capture_srcs, src_new( 4-samplerate_quality, 1, NULL ) );
494 capture_ports = jack_slist_append (capture_ports, port);
497 port_flags = JackPortIsInput;
499 playback_ports = NULL;
500 for (chn = 0; chn < n_playback; chn++)
502 snprintf (buf, sizeof(buf) - 1, "playback_%u", chn+1);
504 port = jack_port_register (client, buf,
505 JACK_DEFAULT_AUDIO_TYPE,
506 port_flags, 0);
508 if (!port)
510 printf( "jacknet_client: cannot register port for %s", buf);
511 break;
514 playback_srcs = jack_slist_append( playback_srcs, src_new( 4-samplerate_quality, 1, NULL ) );
515 playback_ports = jack_slist_append (playback_ports, port);
520 * This is the shutdown callback for this JACK application.
521 * It is called by JACK if the server ever shuts down or
522 * decides to disconnect the client.
525 void jack_shutdown (void *arg) {
527 exit (1);
531 * be user friendly.
532 * be user friendly.
533 * be user friendly.
536 void printUsage() {
537 fprintf(stderr, "usage: alsa_out [options]\n"
538 "\n"
539 " -j <jack name> - client name\n"
540 " -d <alsa_device> \n"
541 " -c <channels> \n"
542 " -p <period_size> \n"
543 " -n <num_period> \n"
544 " -r <sample_rate> \n"
545 " -q <sample_rate quality [0..4]\n"
546 " -m <max_diff> \n"
547 " -t <target_delay> \n"
548 " -i turns on instrumentation\n"
549 " -v turns on printouts\n"
550 "\n");
555 * the main function....
558 void
559 sigterm_handler( int signal )
561 quit = 1;
565 int main (int argc, char *argv[]) {
566 char jack_name[30] = "alsa_in";
567 char alsa_device[30] = "hw:0";
569 extern char *optarg;
570 extern int optind, optopt;
571 int errflg=0;
572 int c;
574 while ((c = getopt(argc, argv, "ivj:r:c:p:n:d:q:m:t:f:F:C:Q:s:")) != -1) {
575 switch(c) {
576 case 'j':
577 strcpy(jack_name,optarg);
578 break;
579 case 'r':
580 sample_rate = atoi(optarg);
581 break;
582 case 'c':
583 num_channels = atoi(optarg);
584 break;
585 case 'p':
586 period_size = atoi(optarg);
587 break;
588 case 'n':
589 num_periods = atoi(optarg);
590 break;
591 case 'd':
592 strcpy(alsa_device,optarg);
593 break;
594 case 't':
595 target_delay = atoi(optarg);
596 break;
597 case 'q':
598 samplerate_quality = atoi(optarg);
599 break;
600 case 'm':
601 max_diff = atoi(optarg);
602 break;
603 case 'f':
604 catch_factor = atoi(optarg);
605 break;
606 case 'F':
607 catch_factor2 = atoi(optarg);
608 break;
609 case 'C':
610 pclamp = (double) atoi(optarg);
611 break;
612 case 'Q':
613 controlquant = (double) atoi(optarg);
614 break;
615 case 'v':
616 verbose = 1;
617 break;
618 case 'i':
619 instrument = 1;
620 break;
621 case 's':
622 smooth_size = atoi(optarg);
623 break;
624 case ':':
625 fprintf(stderr,
626 "Option -%c requires an operand\n", optopt);
627 errflg++;
628 break;
629 case '?':
630 fprintf(stderr,
631 "Unrecognized option: -%c\n", optopt);
632 errflg++;
635 if (errflg) {
636 printUsage();
637 exit(2);
640 if( (samplerate_quality < 0) || (samplerate_quality > 4) ) {
641 fprintf (stderr, "invalid samplerate quality\n");
642 return 1;
644 if ((client = jack_client_open (jack_name, 0, NULL)) == 0) {
645 fprintf (stderr, "jack server not running?\n");
646 return 1;
649 /* tell the JACK server to call `process()' whenever
650 there is work to be done.
653 jack_set_process_callback (client, process, 0);
655 /* tell the JACK server to call `jack_shutdown()' if
656 it ever shuts down, either entirely, or if it
657 just decides to stop calling us.
660 jack_on_shutdown (client, jack_shutdown, 0);
663 // get jack sample_rate
665 jack_sample_rate = jack_get_sample_rate( client );
667 if( !sample_rate )
668 sample_rate = jack_sample_rate;
670 // now open the alsa fd...
671 alsa_handle = open_audiofd( alsa_device, 1, sample_rate, num_channels, period_size, num_periods);
672 if( alsa_handle == 0 )
673 exit(20);
675 printf( "selected sample format: %s\n", formats[format].name );
677 static_resample_factor = (double) jack_sample_rate / (double) sample_rate;
678 resample_mean = static_resample_factor;
680 offset_array = malloc( sizeof(double) * smooth_size );
681 if( offset_array == NULL ) {
682 fprintf( stderr, "no memory for offset_array !!!\n" );
683 exit(20);
685 window_array = malloc( sizeof(double) * smooth_size );
686 if( window_array == NULL ) {
687 fprintf( stderr, "no memory for window_array !!!\n" );
688 exit(20);
690 int i;
691 for( i=0; i<smooth_size; i++ ) {
692 offset_array[i] = 0.0;
693 window_array[i] = hann( (double) i / ((double) smooth_size - 1.0) );
696 jack_buffer_size = jack_get_buffer_size( client );
697 // Setup target delay and max_diff for the normal user, who does not play with them...
698 if( !target_delay )
699 target_delay = (num_periods*period_size / 2) + jack_buffer_size/2;
701 if( !max_diff )
702 max_diff = num_periods*period_size - target_delay ;
704 if( max_diff > target_delay ) {
705 fprintf( stderr, "target_delay (%d) cant be smaller than max_diff(%d)\n", target_delay, max_diff );
706 exit(20);
708 if( (target_delay+max_diff) > (num_periods*period_size) ) {
709 fprintf( stderr, "target_delay+max_diff (%d) cant be bigger than buffersize(%d)\n", target_delay+max_diff, num_periods*period_size );
710 exit(20);
712 // alloc input ports, which are blasted out to alsa...
713 alloc_ports( num_channels, 0 );
716 /* tell the JACK server that we are ready to roll */
718 if (jack_activate (client)) {
719 fprintf (stderr, "cannot activate client");
720 return 1;
723 signal( SIGTERM, sigterm_handler );
724 signal( SIGINT, sigterm_handler );
726 if( verbose ) {
727 while(!quit) {
728 usleep(500000);
729 if( output_new_delay ) {
730 printf( "delay = %d\n", output_new_delay );
731 output_new_delay = 0;
733 printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor, output_diff, output_offset );
735 } else if( instrument ) {
736 printf( "# n\tresamp\tdiff\toffseti\tintegral\n");
737 int n=0;
738 while(!quit) {
739 usleep(1000);
740 printf( "%d\t%f\t%f\t%f\t%f\n", n++, output_resampling_factor, output_diff, output_offset, output_integral );
742 } else {
743 while(!quit)
745 usleep(500000);
746 if( output_new_delay ) {
747 printf( "delay = %d\n", output_new_delay );
748 output_new_delay = 0;
753 jack_deactivate( client );
754 jack_client_close (client);
755 exit (0);