fix building when PATH_MAX is not defined. (should fix debian bug 320736)
[jack.git] / tools / alsa_out.c
blob1fff2d38f99c76d414cb734543393808f66f5f12
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 double resample_mean = 1.0;
39 double static_resample_factor = 1.0;
41 double *offset_array;
42 double *window_array;
43 int offset_differential_index = 0;
45 double offset_integral = 0;
46 int quit = 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, int nperiods) {
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, 1 );
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, nperiods)) < 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 );
292 int num_null_samples = nperiods * period * channels;
293 char *tmp = alloca( num_null_samples * formats[format].sample_size );
294 memset( tmp, 0, num_null_samples * formats[format].sample_size );
295 snd_pcm_writei( handle, tmp, num_null_samples );
298 return handle;
301 double hann( double x )
303 return 0.5 * (1.0 - cos( 2*M_PI * x ) );
307 * The process callback for this JACK application.
308 * It is called by JACK at the appropriate times.
310 int process (jack_nframes_t nframes, void *arg) {
312 char *outbuf;
313 float *resampbuf;
314 int rlen;
315 int err;
316 snd_pcm_sframes_t delay = target_delay;
317 int i;
319 snd_pcm_delay( alsa_handle, &delay );
321 //delay -= jack_frames_since_cycle_start( client );
322 // Do it the hard way.
323 // this is for compensating xruns etc...
325 if( delay > (target_delay+max_diff) ) {
326 snd_pcm_rewind( alsa_handle, delay - target_delay );
327 output_new_delay = (int) delay;
329 delay = target_delay;
331 // Set the resample_rate... we need to adjust the offset integral, to do this.
332 // first look at the PI controller, this code is just a special case, which should never execute once
333 // everything is swung in.
334 offset_integral = - (resample_mean - static_resample_factor) * catch_factor * catch_factor2;
335 // Also clear the array. we are beginning a new control cycle.
336 for( i=0; i<smooth_size; i++ )
337 offset_array[i] = 0.0;
339 if( delay < (target_delay-max_diff) ) {
340 char *tmp = alloca( (target_delay-delay) * formats[format].sample_size * num_channels );
341 memset( tmp, 0, formats[format].sample_size * num_channels * (target_delay-delay) );
342 snd_pcm_writei( alsa_handle, tmp, target_delay-delay );
344 output_new_delay = (int) delay;
346 delay = target_delay;
348 // Set the resample_rate... we need to adjust the offset integral, to do this.
349 offset_integral = - (resample_mean - static_resample_factor) * catch_factor * catch_factor2;
350 // Also clear the array. we are beginning a new control cycle.
351 for( i=0; i<smooth_size; i++ )
352 offset_array[i] = 0.0;
354 /* ok... now we should have target_delay +- max_diff on the alsa side.
356 * calculate the number of frames, we want to get.
359 double offset = delay - target_delay;
361 // Save offset.
362 offset_array[(offset_differential_index++)% smooth_size ] = offset;
364 // Build the mean of the windowed offset array
365 // basically fir lowpassing.
366 double smooth_offset = 0.0;
367 for( i=0; i<smooth_size; i++ )
368 smooth_offset +=
369 offset_array[ (i + offset_differential_index-1) % smooth_size] * window_array[i];
370 smooth_offset /= (double) smooth_size;
372 // this is the integral of the smoothed_offset
373 offset_integral += smooth_offset;
375 // Clamp offset.
376 // the smooth offset still contains unwanted noise
377 // which would go straigth onto the resample coeff.
378 // it only used in the P component and the I component is used for the fine tuning anyways.
379 if( fabs( smooth_offset ) < pclamp )
380 smooth_offset = 0.0;
382 // ok. now this is the PI controller.
383 // u(t) = K * ( e(t) + 1/T \int e(t') dt' )
384 // K = 1/catch_factor and T = catch_factor2
385 double current_resample_factor = static_resample_factor - smooth_offset / (double) catch_factor - offset_integral / (double) catch_factor / (double)catch_factor2;
387 // now quantize this value around resample_mean, so that the noise which is in the integral component doesnt hurt.
388 current_resample_factor = floor( (current_resample_factor - resample_mean) * controlquant + 0.5 ) / controlquant + resample_mean;
390 // Output "instrumentatio" gonna change that to real instrumentation in a few.
391 output_resampling_factor = (float) current_resample_factor;
392 output_diff = (float) smooth_offset;
393 output_integral = (float) offset_integral;
394 output_offset = (float) offset;
396 // Clamp a bit.
397 if( current_resample_factor < 0.25 ) current_resample_factor = 0.25;
398 if( current_resample_factor > 4 ) current_resample_factor = 4;
400 // Now Calculate how many samples we need.
401 rlen = ceil( ((double)nframes) * current_resample_factor )+2;
402 assert( rlen > 2 );
404 // Calculate resample_mean so we can init ourselves to saner values.
405 resample_mean = 0.9999 * resample_mean + 0.0001 * current_resample_factor;
407 * now this should do it...
410 outbuf = alloca( rlen * formats[format].sample_size * num_channels );
412 resampbuf = alloca( rlen * sizeof( float ) );
414 * render jack ports to the outbuf...
417 int chn = 0;
418 JSList *node = playback_ports;
419 JSList *src_node = playback_srcs;
420 SRC_DATA src;
422 while ( node != NULL)
424 jack_port_t *port = (jack_port_t *) node->data;
425 float *buf = jack_port_get_buffer (port, nframes);
427 SRC_STATE *src_state = src_node->data;
429 src.data_in = buf;
430 src.input_frames = nframes;
432 src.data_out = resampbuf;
433 src.output_frames = rlen;
434 src.end_of_input = 0;
436 src.src_ratio = current_resample_factor;
438 src_process( src_state, &src );
440 formats[format].jack_to_soundcard( outbuf + format[formats].sample_size * chn, resampbuf, src.output_frames_gen, num_channels*format[formats].sample_size, NULL);
442 src_node = jack_slist_next (src_node);
443 node = jack_slist_next (node);
444 chn++;
447 // now write the output...
448 again:
449 err = snd_pcm_writei(alsa_handle, outbuf, src.output_frames_gen);
450 //err = snd_pcm_writei(alsa_handle, outbuf, src.output_frames_gen);
451 if( err < 0 ) {
452 printf( "err = %d\n", err );
453 if (xrun_recovery(alsa_handle, err) < 0) {
454 printf("Write error: %s\n", snd_strerror(err));
455 exit(EXIT_FAILURE);
457 goto again;
460 return 0;
465 * Allocate the necessary jack ports...
468 void alloc_ports( int n_capture, int n_playback ) {
470 int port_flags = JackPortIsOutput;
471 int chn;
472 jack_port_t *port;
473 char buf[32];
475 capture_ports = NULL;
476 for (chn = 0; chn < n_capture; chn++)
478 snprintf (buf, sizeof(buf) - 1, "capture_%u", chn+1);
480 port = jack_port_register (client, buf,
481 JACK_DEFAULT_AUDIO_TYPE,
482 port_flags, 0);
484 if (!port)
486 printf( "jacknet_client: cannot register port for %s", buf);
487 break;
490 capture_srcs = jack_slist_append( capture_srcs, src_new( 4-samplerate_quality, 1, NULL ) );
491 capture_ports = jack_slist_append (capture_ports, port);
494 port_flags = JackPortIsInput;
496 playback_ports = NULL;
497 for (chn = 0; chn < n_playback; chn++)
499 snprintf (buf, sizeof(buf) - 1, "playback_%u", chn+1);
501 port = jack_port_register (client, buf,
502 JACK_DEFAULT_AUDIO_TYPE,
503 port_flags, 0);
505 if (!port)
507 printf( "jacknet_client: cannot register port for %s", buf);
508 break;
511 playback_srcs = jack_slist_append( playback_srcs, src_new( 4-samplerate_quality, 1, NULL ) );
512 playback_ports = jack_slist_append (playback_ports, port);
517 * This is the shutdown callback for this JACK application.
518 * It is called by JACK if the server ever shuts down or
519 * decides to disconnect the client.
522 void jack_shutdown (void *arg) {
524 exit (1);
528 * be user friendly.
529 * be user friendly.
530 * be user friendly.
533 void printUsage() {
534 fprintf(stderr, "usage: alsa_out [options]\n"
535 "\n"
536 " -j <jack name> - client name\n"
537 " -d <alsa_device> \n"
538 " -c <channels> \n"
539 " -p <period_size> \n"
540 " -n <num_period> \n"
541 " -r <sample_rate> \n"
542 " -q <sample_rate quality [0..4]\n"
543 " -m <max_diff> \n"
544 " -t <target_delay> \n"
545 " -i turns on instrumentation\n"
546 " -v turns on printouts\n"
547 "\n");
552 * the main function....
555 void
556 sigterm_handler( int signal )
558 quit = 1;
562 int main (int argc, char *argv[]) {
563 char jack_name[30] = "alsa_out";
564 char alsa_device[30] = "hw:0";
566 extern char *optarg;
567 extern int optind, optopt;
568 int errflg=0;
569 int c;
571 while ((c = getopt(argc, argv, "ivj:r:c:p:n:d:q:m:t:f:F:C:Q:s:")) != -1) {
572 switch(c) {
573 case 'j':
574 strcpy(jack_name,optarg);
575 break;
576 case 'r':
577 sample_rate = atoi(optarg);
578 break;
579 case 'c':
580 num_channels = atoi(optarg);
581 break;
582 case 'p':
583 period_size = atoi(optarg);
584 break;
585 case 'n':
586 num_periods = atoi(optarg);
587 break;
588 case 'd':
589 strcpy(alsa_device,optarg);
590 break;
591 case 't':
592 target_delay = atoi(optarg);
593 break;
594 case 'q':
595 samplerate_quality = atoi(optarg);
596 break;
597 case 'm':
598 max_diff = atoi(optarg);
599 break;
600 case 'f':
601 catch_factor = atoi(optarg);
602 break;
603 case 'F':
604 catch_factor2 = atoi(optarg);
605 break;
606 case 'C':
607 pclamp = (double) atoi(optarg);
608 break;
609 case 'Q':
610 controlquant = (double) atoi(optarg);
611 break;
612 case 'v':
613 verbose = 1;
614 break;
615 case 'i':
616 instrument = 1;
617 break;
618 case 's':
619 smooth_size = atoi(optarg);
620 break;
621 case ':':
622 fprintf(stderr,
623 "Option -%c requires an operand\n", optopt);
624 errflg++;
625 break;
626 case '?':
627 fprintf(stderr,
628 "Unrecognized option: -%c\n", optopt);
629 errflg++;
632 if (errflg) {
633 printUsage();
634 exit(2);
637 if( (samplerate_quality < 0) || (samplerate_quality > 4) ) {
638 fprintf (stderr, "invalid samplerate quality\n");
639 return 1;
641 if ((client = jack_client_open (jack_name, 0, NULL)) == 0) {
642 fprintf (stderr, "jack server not running?\n");
643 return 1;
646 /* tell the JACK server to call `process()' whenever
647 there is work to be done.
650 jack_set_process_callback (client, process, 0);
652 /* tell the JACK server to call `jack_shutdown()' if
653 it ever shuts down, either entirely, or if it
654 just decides to stop calling us.
657 jack_on_shutdown (client, jack_shutdown, 0);
660 // get jack sample_rate
662 jack_sample_rate = jack_get_sample_rate( client );
664 if( !sample_rate )
665 sample_rate = jack_sample_rate;
667 static_resample_factor = (double) sample_rate / (double) jack_sample_rate;
668 resample_mean = static_resample_factor;
670 offset_array = malloc( sizeof(double) * smooth_size );
671 if( offset_array == NULL ) {
672 fprintf( stderr, "no memory for offset_array !!!\n" );
673 exit(20);
675 window_array = malloc( sizeof(double) * smooth_size );
676 if( window_array == NULL ) {
677 fprintf( stderr, "no memory for window_array !!!\n" );
678 exit(20);
680 int i;
681 for( i=0; i<smooth_size; i++ ) {
682 offset_array[i] = 0.0;
683 window_array[i] = hann( (double) i / ((double) smooth_size - 1.0) );
686 jack_buffer_size = jack_get_buffer_size( client );
687 // Setup target delay and max_diff for the normal user, who does not play with them...
688 if( !target_delay )
689 target_delay = (num_periods*period_size / 2) - jack_buffer_size/2;
691 if( !max_diff )
692 max_diff = target_delay;
694 if( max_diff > target_delay ) {
695 fprintf( stderr, "target_delay (%d) cant be smaller than max_diff(%d)\n", target_delay, max_diff );
696 exit(20);
698 if( (target_delay+max_diff) > (num_periods*period_size) ) {
699 fprintf( stderr, "target_delay+max_diff (%d) cant be bigger than buffersize(%d)\n", target_delay+max_diff, num_periods*period_size );
700 exit(20);
702 // now open the alsa fd...
703 alsa_handle = open_audiofd( alsa_device, 0, sample_rate, num_channels, period_size, num_periods);
704 if( alsa_handle == 0 )
705 exit(20);
707 printf( "selected sample format: %s\n", formats[format].name );
709 // alloc input ports, which are blasted out to alsa...
710 alloc_ports( 0, num_channels );
713 /* tell the JACK server that we are ready to roll */
715 if (jack_activate (client)) {
716 fprintf (stderr, "cannot activate client");
717 return 1;
720 signal( SIGTERM, sigterm_handler );
721 signal( SIGINT, sigterm_handler );
723 if( verbose ) {
724 while(!quit) {
725 usleep(500000);
726 if( output_new_delay ) {
727 printf( "delay = %d\n", output_new_delay );
728 output_new_delay = 0;
730 printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor, output_diff, output_offset );
732 } else if( instrument ) {
733 printf( "# n\tresamp\tdiff\toffseti\tintegral\n");
734 int n=0;
735 while(!quit) {
736 usleep(1000);
737 printf( "%d\t%f\t%f\t%f\t%f\n", n++, output_resampling_factor, output_diff, output_offset, output_integral );
739 } else {
740 while(!quit)
742 usleep(500000);
743 if( output_new_delay ) {
744 printf( "delay = %d\n", output_new_delay );
745 output_new_delay = 0;
750 jack_deactivate( client );
751 jack_client_close (client);
752 exit (0);