fix building when PATH_MAX is not defined. (should fix debian bug 320736)
[jack.git] / tools / alsa_in.c
blob6609b52c8ec8825aa592f1f096e0c651c4d3aced
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 <jack/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, 4, sample_move_d24_sS, sample_move_dS_s24, "24bit" },
92 { SND_PCM_FORMAT_S16, 2, sample_move_d16_sS, sample_move_dS_s16, "16bit" }
94 #define NUMFORMATS (sizeof(formats)/sizeof(formats[0]))
95 int format=0;
97 // Alsa stuff... i dont want to touch this bullshit in the next years.... please...
99 static int xrun_recovery(snd_pcm_t *handle, int err) {
100 // printf( "xrun !!!.... %d\n", err );
101 if (err == -EPIPE) { /* under-run */
102 err = snd_pcm_prepare(handle);
103 if (err < 0)
104 printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err));
105 return 0;
106 } else if (err == -EAGAIN) {
107 while ((err = snd_pcm_resume(handle)) == -EAGAIN)
108 usleep(100); /* wait until the suspend flag is released */
109 if (err < 0) {
110 err = snd_pcm_prepare(handle);
111 if (err < 0)
112 printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err));
114 return 0;
116 return err;
119 static int set_hwformat( snd_pcm_t *handle, snd_pcm_hw_params_t *params )
121 int i;
122 int err;
124 for( i=0; i<NUMFORMATS; i++ ) {
125 /* set the sample format */
126 err = snd_pcm_hw_params_set_format(handle, params, formats[i].format_id);
127 if (err == 0) {
128 format = i;
129 return 0;
133 return err;
136 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 ) {
137 int err, dir=0;
138 unsigned int buffer_time;
139 unsigned int period_time;
140 unsigned int rrate;
141 unsigned int rchannels;
143 /* choose all parameters */
144 err = snd_pcm_hw_params_any(handle, params);
145 if (err < 0) {
146 printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
147 return err;
149 /* set the interleaved read/write format */
150 err = snd_pcm_hw_params_set_access(handle, params, access);
151 if (err < 0) {
152 printf("Access type not available for playback: %s\n", snd_strerror(err));
153 return err;
156 /* set the sample format */
157 err = set_hwformat(handle, params);
158 if (err < 0) {
159 printf("Sample format not available for playback: %s\n", snd_strerror(err));
160 return err;
162 /* set the count of channels */
163 rchannels = channels;
164 err = snd_pcm_hw_params_set_channels_near(handle, params, &rchannels);
165 if (err < 0) {
166 printf("Channels count (%i) not available for record: %s\n", channels, snd_strerror(err));
167 return err;
169 if (rchannels != channels) {
170 printf("WARNING: chennel count does not match (requested %d got %d)\n", channels, rchannels);
171 num_channels = rchannels;
173 /* set the stream rate */
174 rrate = rate;
175 err = snd_pcm_hw_params_set_rate_near(handle, params, &rrate, 0);
176 if (err < 0) {
177 printf("Rate %iHz not available for playback: %s\n", rate, snd_strerror(err));
178 return err;
180 if (rrate != rate) {
181 printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate, rrate);
182 return -EINVAL;
184 /* set the buffer time */
186 buffer_time = 1000000*period*nperiods/rate;
187 err = snd_pcm_hw_params_set_buffer_time_near(handle, params, &buffer_time, &dir);
188 if (err < 0) {
189 printf("Unable to set buffer time %i for playback: %s\n", 1000000*period*nperiods/rate, snd_strerror(err));
190 return err;
192 err = snd_pcm_hw_params_get_buffer_size( params, &real_buffer_size );
193 if (err < 0) {
194 printf("Unable to get buffer size back: %s\n", snd_strerror(err));
195 return err;
197 if( real_buffer_size != nperiods * period ) {
198 printf( "WARNING: buffer size does not match: (requested %d, got %d)\n", nperiods * period, (int) real_buffer_size );
200 /* set the period time */
201 period_time = 1000000*period/rate;
202 err = snd_pcm_hw_params_set_period_time_near(handle, params, &period_time, &dir);
203 if (err < 0) {
204 printf("Unable to set period time %i for playback: %s\n", 1000000*period/rate, snd_strerror(err));
205 return err;
207 err = snd_pcm_hw_params_get_period_size(params, &real_period_size, NULL );
208 if (err < 0) {
209 printf("Unable to get period size back: %s\n", snd_strerror(err));
210 return err;
212 if( real_period_size != period ) {
213 printf( "WARNING: period size does not match: (requested %i, got %i)\n", period, (int)real_period_size );
215 /* write the parameters to device */
216 err = snd_pcm_hw_params(handle, params);
217 if (err < 0) {
218 printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
219 return err;
221 return 0;
224 static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams, int period) {
225 int err;
227 /* get the current swparams */
228 err = snd_pcm_sw_params_current(handle, swparams);
229 if (err < 0) {
230 printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err));
231 return err;
233 /* start the transfer when the buffer is full */
234 err = snd_pcm_sw_params_set_start_threshold(handle, swparams, period );
235 if (err < 0) {
236 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
237 return err;
239 err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, -1 );
240 if (err < 0) {
241 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
242 return err;
244 /* allow the transfer when at least period_size samples can be processed */
245 err = snd_pcm_sw_params_set_avail_min(handle, swparams, 2*period );
246 if (err < 0) {
247 printf("Unable to set avail min for capture: %s\n", snd_strerror(err));
248 return err;
250 /* align all transfers to 1 sample */
251 err = snd_pcm_sw_params_set_xfer_align(handle, swparams, 1);
252 if (err < 0) {
253 printf("Unable to set transfer align for capture: %s\n", snd_strerror(err));
254 return err;
256 /* write the parameters to the playback device */
257 err = snd_pcm_sw_params(handle, swparams);
258 if (err < 0) {
259 printf("Unable to set sw params for capture: %s\n", snd_strerror(err));
260 return err;
262 return 0;
265 // ok... i only need this function to communicate with the alsa bloat api...
267 static snd_pcm_t *open_audiofd( char *device_name, int capture, int rate, int channels, int period, int nperiods ) {
268 int err;
269 snd_pcm_t *handle;
270 snd_pcm_hw_params_t *hwparams;
271 snd_pcm_sw_params_t *swparams;
273 snd_pcm_hw_params_alloca(&hwparams);
274 snd_pcm_sw_params_alloca(&swparams);
276 if ((err = snd_pcm_open(&(handle), device_name, capture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK )) < 0) {
277 printf("Capture open error: %s\n", snd_strerror(err));
278 return NULL;
281 if ((err = set_hwparams(handle, hwparams,SND_PCM_ACCESS_RW_INTERLEAVED, rate, channels, period, nperiods )) < 0) {
282 printf("Setting of hwparams failed: %s\n", snd_strerror(err));
283 return NULL;
285 if ((err = set_swparams(handle, swparams, period)) < 0) {
286 printf("Setting of swparams failed: %s\n", snd_strerror(err));
287 return NULL;
290 snd_pcm_start( handle );
291 snd_pcm_wait( handle, 200 );
293 return handle;
296 double hann( double x )
298 return 0.5 * (1.0 - cos( 2*M_PI * x ) );
302 * The process callback for this JACK application.
303 * It is called by JACK at the appropriate times.
305 int process (jack_nframes_t nframes, void *arg) {
307 char *outbuf;
308 float *resampbuf;
309 int rlen;
310 int err;
311 snd_pcm_sframes_t delay = target_delay;
312 int put_back_samples=0;
313 int i;
315 snd_pcm_delay( alsa_handle, &delay );
317 //delay -= jack_frames_since_cycle_start( client );
318 // Do it the hard way.
319 // this is for compensating xruns etc...
321 if( delay > (target_delay+max_diff) ) {
322 char *tmp = alloca( (delay-target_delay) * formats[format].sample_size * num_channels );
323 snd_pcm_readi( alsa_handle, tmp, delay-target_delay );
324 output_new_delay = (int) delay;
326 delay = target_delay;
328 // Set the resample_rate... we need to adjust the offset integral, to do this.
329 // first look at the PI controller, this code is just a special case, which should never execute once
330 // everything is swung in.
331 offset_integral = - (resample_mean - static_resample_factor) * catch_factor * catch_factor2;
332 // Also clear the array. we are beginning a new control cycle.
333 for( i=0; i<smooth_size; i++ )
334 offset_array[i] = 0.0;
336 if( delay < (target_delay-max_diff) ) {
337 snd_pcm_rewind( alsa_handle, target_delay - delay );
338 output_new_delay = (int) delay;
339 delay = target_delay;
341 // Set the resample_rate... we need to adjust the offset integral, to do this.
342 offset_integral = - (resample_mean - static_resample_factor) * catch_factor * catch_factor2;
343 // Also clear the array. we are beginning a new control cycle.
344 for( i=0; i<smooth_size; i++ )
345 offset_array[i] = 0.0;
347 /* ok... now we should have target_delay +- max_diff on the alsa side.
349 * calculate the number of frames, we want to get.
352 double offset = delay - target_delay;
354 // Save offset.
355 offset_array[(offset_differential_index++)% smooth_size ] = offset;
357 // Build the mean of the windowed offset array
358 // basically fir lowpassing.
359 double smooth_offset = 0.0;
360 for( i=0; i<smooth_size; i++ )
361 smooth_offset +=
362 offset_array[ (i + offset_differential_index-1) % smooth_size] * window_array[i];
363 smooth_offset /= (double) smooth_size;
365 // this is the integral of the smoothed_offset
366 offset_integral += smooth_offset;
368 // Clamp offset.
369 // the smooth offset still contains unwanted noise
370 // which would go straigth onto the resample coeff.
371 // it only used in the P component and the I component is used for the fine tuning anyways.
372 if( fabs( smooth_offset ) < pclamp )
373 smooth_offset = 0.0;
375 // ok. now this is the PI controller.
376 // u(t) = K * ( e(t) + 1/T \int e(t') dt' )
377 // K = 1/catch_factor and T = catch_factor2
378 double current_resample_factor = static_resample_factor - smooth_offset / (double) catch_factor - offset_integral / (double) catch_factor / (double)catch_factor2;
380 // now quantize this value around resample_mean, so that the noise which is in the integral component doesnt hurt.
381 current_resample_factor = floor( (current_resample_factor - resample_mean) * controlquant + 0.5 ) / controlquant + resample_mean;
383 // Output "instrumentatio" gonna change that to real instrumentation in a few.
384 output_resampling_factor = (float) current_resample_factor;
385 output_diff = (float) smooth_offset;
386 output_integral = (float) offset_integral;
387 output_offset = (float) offset;
389 // Clamp a bit.
390 if( current_resample_factor < 0.25 ) current_resample_factor = 0.25;
391 if( current_resample_factor > 4 ) current_resample_factor = 4;
393 // Now Calculate how many samples we need.
394 rlen = ceil( ((double)nframes) / current_resample_factor )+2;
395 assert( rlen > 2 );
397 // Calculate resample_mean so we can init ourselves to saner values.
398 resample_mean = 0.9999 * resample_mean + 0.0001 * current_resample_factor;
400 * now this should do it...
403 outbuf = alloca( rlen * formats[format].sample_size * num_channels );
405 resampbuf = alloca( rlen * sizeof( float ) );
407 // get the data...
408 again:
409 err = snd_pcm_readi(alsa_handle, outbuf, rlen);
410 if( err < 0 ) {
411 printf( "err = %d\n", err );
412 if (xrun_recovery(alsa_handle, err) < 0) {
413 //printf("Write error: %s\n", snd_strerror(err));
414 //exit(EXIT_FAILURE);
416 goto again;
418 if( err != rlen ) {
419 //printf( "read = %d\n", rlen );
423 * render jack ports to the outbuf...
426 int chn = 0;
427 JSList *node = capture_ports;
428 JSList *src_node = capture_srcs;
429 SRC_DATA src;
431 while ( node != NULL)
433 jack_port_t *port = (jack_port_t *) node->data;
434 float *buf = jack_port_get_buffer (port, nframes);
436 SRC_STATE *src_state = src_node->data;
438 formats[format].soundcard_to_jack( resampbuf, outbuf + format[formats].sample_size * chn, rlen, num_channels*format[formats].sample_size );
440 src.data_in = resampbuf;
441 src.input_frames = rlen;
443 src.data_out = buf;
444 src.output_frames = nframes;
445 src.end_of_input = 0;
447 src.src_ratio = current_resample_factor;
449 src_process( src_state, &src );
451 put_back_samples = rlen-src.input_frames_used;
453 src_node = jack_slist_next (src_node);
454 node = jack_slist_next (node);
455 chn++;
458 // Put back the samples libsamplerate did not consume.
459 //printf( "putback = %d\n", put_back_samples );
460 snd_pcm_rewind( alsa_handle, put_back_samples );
462 return 0;
467 * Allocate the necessary jack ports...
470 void alloc_ports( int n_capture, int n_playback ) {
472 int port_flags = JackPortIsOutput;
473 int chn;
474 jack_port_t *port;
475 char buf[32];
477 capture_ports = NULL;
478 for (chn = 0; chn < n_capture; chn++)
480 snprintf (buf, sizeof(buf) - 1, "capture_%u", chn+1);
482 port = jack_port_register (client, buf,
483 JACK_DEFAULT_AUDIO_TYPE,
484 port_flags, 0);
486 if (!port)
488 printf( "jacknet_client: cannot register port for %s", buf);
489 break;
492 capture_srcs = jack_slist_append( capture_srcs, src_new( 4-samplerate_quality, 1, NULL ) );
493 capture_ports = jack_slist_append (capture_ports, port);
496 port_flags = JackPortIsInput;
498 playback_ports = NULL;
499 for (chn = 0; chn < n_playback; chn++)
501 snprintf (buf, sizeof(buf) - 1, "playback_%u", chn+1);
503 port = jack_port_register (client, buf,
504 JACK_DEFAULT_AUDIO_TYPE,
505 port_flags, 0);
507 if (!port)
509 printf( "jacknet_client: cannot register port for %s", buf);
510 break;
513 playback_srcs = jack_slist_append( playback_srcs, src_new( 4-samplerate_quality, 1, NULL ) );
514 playback_ports = jack_slist_append (playback_ports, port);
519 * This is the shutdown callback for this JACK application.
520 * It is called by JACK if the server ever shuts down or
521 * decides to disconnect the client.
524 void jack_shutdown (void *arg) {
526 exit (1);
530 * be user friendly.
531 * be user friendly.
532 * be user friendly.
535 void printUsage() {
536 fprintf(stderr, "usage: alsa_out [options]\n"
537 "\n"
538 " -j <jack name> - client name\n"
539 " -d <alsa_device> \n"
540 " -c <channels> \n"
541 " -p <period_size> \n"
542 " -n <num_period> \n"
543 " -r <sample_rate> \n"
544 " -q <sample_rate quality [0..4]\n"
545 " -m <max_diff> \n"
546 " -t <target_delay> \n"
547 " -i turns on instrumentation\n"
548 " -v turns on printouts\n"
549 "\n");
554 * the main function....
557 void
558 sigterm_handler( int signal )
560 quit = 1;
564 int main (int argc, char *argv[]) {
565 char jack_name[30] = "alsa_in";
566 char alsa_device[30] = "hw:0";
568 extern char *optarg;
569 extern int optind, optopt;
570 int errflg=0;
571 int c;
573 while ((c = getopt(argc, argv, "ivj:r:c:p:n:d:q:m:t:f:F:C:Q:s:")) != -1) {
574 switch(c) {
575 case 'j':
576 strcpy(jack_name,optarg);
577 break;
578 case 'r':
579 sample_rate = atoi(optarg);
580 break;
581 case 'c':
582 num_channels = atoi(optarg);
583 break;
584 case 'p':
585 period_size = atoi(optarg);
586 break;
587 case 'n':
588 num_periods = atoi(optarg);
589 break;
590 case 'd':
591 strcpy(alsa_device,optarg);
592 break;
593 case 't':
594 target_delay = atoi(optarg);
595 break;
596 case 'q':
597 samplerate_quality = atoi(optarg);
598 break;
599 case 'm':
600 max_diff = atoi(optarg);
601 break;
602 case 'f':
603 catch_factor = atoi(optarg);
604 break;
605 case 'F':
606 catch_factor2 = atoi(optarg);
607 break;
608 case 'C':
609 pclamp = (double) atoi(optarg);
610 break;
611 case 'Q':
612 controlquant = (double) atoi(optarg);
613 break;
614 case 'v':
615 verbose = 1;
616 break;
617 case 'i':
618 instrument = 1;
619 break;
620 case 's':
621 smooth_size = atoi(optarg);
622 break;
623 case ':':
624 fprintf(stderr,
625 "Option -%c requires an operand\n", optopt);
626 errflg++;
627 break;
628 case '?':
629 fprintf(stderr,
630 "Unrecognized option: -%c\n", optopt);
631 errflg++;
634 if (errflg) {
635 printUsage();
636 exit(2);
639 if( (samplerate_quality < 0) || (samplerate_quality > 4) ) {
640 fprintf (stderr, "invalid samplerate quality\n");
641 return 1;
643 if ((client = jack_client_open (jack_name, 0, NULL)) == 0) {
644 fprintf (stderr, "jack server not running?\n");
645 return 1;
648 /* tell the JACK server to call `process()' whenever
649 there is work to be done.
652 jack_set_process_callback (client, process, 0);
654 /* tell the JACK server to call `jack_shutdown()' if
655 it ever shuts down, either entirely, or if it
656 just decides to stop calling us.
659 jack_on_shutdown (client, jack_shutdown, 0);
662 // get jack sample_rate
664 jack_sample_rate = jack_get_sample_rate( client );
666 if( !sample_rate )
667 sample_rate = jack_sample_rate;
669 static_resample_factor = (double) jack_sample_rate / (double) sample_rate;
670 resample_mean = static_resample_factor;
672 offset_array = malloc( sizeof(double) * smooth_size );
673 if( offset_array == NULL ) {
674 fprintf( stderr, "no memory for offset_array !!!\n" );
675 exit(20);
677 window_array = malloc( sizeof(double) * smooth_size );
678 if( window_array == NULL ) {
679 fprintf( stderr, "no memory for window_array !!!\n" );
680 exit(20);
682 int i;
683 for( i=0; i<smooth_size; i++ ) {
684 offset_array[i] = 0.0;
685 window_array[i] = hann( (double) i / ((double) smooth_size - 1.0) );
688 jack_buffer_size = jack_get_buffer_size( client );
689 // Setup target delay and max_diff for the normal user, who does not play with them...
690 if( !target_delay )
691 target_delay = (num_periods*period_size / 2) - jack_buffer_size/2;
693 if( !max_diff )
694 max_diff = target_delay;
696 if( max_diff > target_delay ) {
697 fprintf( stderr, "target_delay (%d) cant be smaller than max_diff(%d)\n", target_delay, max_diff );
698 exit(20);
700 if( (target_delay+max_diff) > (num_periods*period_size) ) {
701 fprintf( stderr, "target_delay+max_diff (%d) cant be bigger than buffersize(%d)\n", target_delay+max_diff, num_periods*period_size );
702 exit(20);
704 // now open the alsa fd...
705 alsa_handle = open_audiofd( alsa_device, 1, sample_rate, num_channels, period_size, num_periods);
706 if( alsa_handle == 0 )
707 exit(20);
709 printf( "selected sample format: %s\n", formats[format].name );
711 // alloc input ports, which are blasted out to alsa...
712 alloc_ports( num_channels, 0 );
715 /* tell the JACK server that we are ready to roll */
717 if (jack_activate (client)) {
718 fprintf (stderr, "cannot activate client");
719 return 1;
722 signal( SIGTERM, sigterm_handler );
723 signal( SIGINT, sigterm_handler );
725 if( verbose ) {
726 while(!quit) {
727 usleep(500000);
728 if( output_new_delay ) {
729 printf( "delay = %d\n", output_new_delay );
730 output_new_delay = 0;
732 printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor, output_diff, output_offset );
734 } else if( instrument ) {
735 printf( "# n\tresamp\tdiff\toffseti\tintegral\n");
736 int n=0;
737 while(!quit) {
738 usleep(1000);
739 printf( "%d\t%f\t%f\t%f\t%f\n", n++, output_resampling_factor, output_diff, output_offset, output_integral );
741 } else {
742 while(!quit)
744 usleep(500000);
745 if( output_new_delay ) {
746 printf( "delay = %d\n", output_new_delay );
747 output_new_delay = 0;
752 jack_deactivate( client );
753 jack_client_close (client);
754 exit (0);