more consistent naming of MIDI ports (vs. audio); drop use of ALSA seq client ID...
[jack.git] / tools / alsa_out.c
blob72f002ff4ad3ceef6a12ad06caf797caaf751f30
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 playback: %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, int nperiods) {
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, 1 );
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, nperiods)) < 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 );
214 int num_null_samples = nperiods * period * channels;
215 ALSASAMPLE *tmp = alloca( num_null_samples * sizeof( ALSASAMPLE ) );
216 memset( tmp, 0, num_null_samples * sizeof( ALSASAMPLE ) );
217 snd_pcm_writei( handle, tmp, num_null_samples );
220 return handle;
225 * The process callback for this JACK application.
226 * It is called by JACK at the appropriate times.
228 int process (jack_nframes_t nframes, void *arg) {
230 ALSASAMPLE *outbuf;
231 float *floatbuf, *resampbuf;
232 int rlen;
233 int err;
234 snd_pcm_sframes_t delay;
237 snd_pcm_delay( alsa_handle, &delay );
239 // Do it the hard way.
240 // this is for compensating xruns etc...
243 if( delay > (target_delay+max_diff) ) {
244 snd_pcm_rewind( alsa_handle, delay - target_delay );
245 //snd_pcm_writei( alsa_handle, tmp, target_delay-t_delay );
246 printf( "delay = %d", (int) delay );
247 snd_pcm_delay( alsa_handle, &delay );
248 printf( "... and delay = %d\n", (int) delay );
249 delay = target_delay;
250 // XXX: at least set it to that value.
251 current_resample_factor = (double) sample_rate / (double) jack_sample_rate;
253 if( delay < (target_delay-max_diff) ) {
254 ALSASAMPLE *tmp = alloca( (target_delay-delay) * sizeof( ALSASAMPLE ) * num_channels );
255 memset( tmp, 0, sizeof( ALSASAMPLE ) * num_channels * (target_delay-delay) );
256 snd_pcm_writei( alsa_handle, tmp, target_delay-delay );
257 printf( "delay = %d", (int) delay );
258 snd_pcm_delay( alsa_handle, &delay );
259 printf( "... and delay = %d\n", (int) delay );
260 delay = target_delay;
261 // XXX: at least set it to that value.
262 current_resample_factor = (double) sample_rate / (double) jack_sample_rate;
264 /* ok... now we should have target_delay +- max_diff on the alsa side.
266 * calculate the number of frames, we want to get.
269 double resamp_rate = (double)jack_sample_rate / (double)sample_rate; // == nframes / alsa_samples.
270 double request_samples = nframes / resamp_rate; //== alsa_samples;
272 double offset = delay - target_delay;
274 //double frlen = request_samples - offset / catch_factor;
275 double frlen = request_samples - offset;
277 double compute_factor = frlen / (double) nframes;
279 double diff_value = pow(current_resample_factor - compute_factor, 3) / (double) catch_factor;
280 current_resample_factor -= diff_value;
281 rlen = ceil( ((double)nframes) * current_resample_factor ) + 2;
283 if( (print_counter--) == 0 ) {
284 print_counter = 10;
285 printf( "res: %f, \tdiff = %f, \toffset = %f \n", (float)current_resample_factor, (float)diff_value, (float) offset );
289 * now this should do it...
292 outbuf = alloca( rlen * sizeof( ALSASAMPLE ) * num_channels );
294 floatbuf = alloca( rlen * sizeof( float ) );
295 resampbuf = alloca( nframes * sizeof( float ) );
297 * render jack ports to the outbuf...
300 int chn = 0;
301 JSList *node = playback_ports;
302 JSList *src_node = playback_srcs;
303 SRC_DATA src;
304 while ( node != NULL)
306 int i;
307 jack_port_t *port = (jack_port_t *) node->data;
308 float *buf = jack_port_get_buffer (port, nframes);
310 SRC_STATE *src_state = src_node->data;
312 src.data_in = buf;
313 src.input_frames = nframes;
315 src.data_out = resampbuf;
316 src.output_frames = rlen;
317 src.end_of_input = 0;
319 //src.src_ratio = (float) frlen / (float) nframes;
320 src.src_ratio = current_resample_factor;
322 //src_set_ratio( src_state, src.src_ratio );
323 src_process( src_state, &src );
325 for (i=0; i < rlen; i++) {
326 outbuf[chn+ i*num_channels]= resampbuf[i] * 32767;
329 src_node = jack_slist_next (src_node);
330 node = jack_slist_next (node);
331 chn++;
334 // now write the output...
336 again:
337 err = snd_pcm_writei(alsa_handle, outbuf, src.output_frames_gen);
338 if( err < 0 ) {
339 //printf( "err = %d\n", err );
340 if (xrun_recovery(alsa_handle, err) < 0) {
341 //printf("Write error: %s\n", snd_strerror(err));
342 //exit(EXIT_FAILURE);
344 goto again;
346 // if( err != rlen ) {
347 // printf( "write = %d\n", rlen );
348 // }
353 return 0;
358 * Allocate the necessary jack ports...
361 void alloc_ports( int n_capture, int n_playback ) {
363 int port_flags = JackPortIsOutput;
364 int chn;
365 jack_port_t *port;
366 char buf[32];
368 capture_ports = NULL;
369 for (chn = 0; chn < n_capture; chn++)
371 snprintf (buf, sizeof(buf) - 1, "capture_%u", chn+1);
373 port = jack_port_register (client, buf,
374 JACK_DEFAULT_AUDIO_TYPE,
375 port_flags, 0);
377 if (!port)
379 printf( "jacknet_client: cannot register port for %s", buf);
380 break;
383 capture_srcs = jack_slist_append( capture_srcs, src_new( SRC_SINC_FASTEST, 1, NULL ) );
384 capture_ports = jack_slist_append (capture_ports, port);
387 port_flags = JackPortIsInput;
389 playback_ports = NULL;
390 for (chn = 0; chn < n_playback; chn++)
392 snprintf (buf, sizeof(buf) - 1, "playback_%u", chn+1);
394 port = jack_port_register (client, buf,
395 JACK_DEFAULT_AUDIO_TYPE,
396 port_flags, 0);
398 if (!port)
400 printf( "jacknet_client: cannot register port for %s", buf);
401 break;
404 playback_srcs = jack_slist_append( playback_srcs, src_new( SRC_SINC_FASTEST, 1, NULL ) );
405 playback_ports = jack_slist_append (playback_ports, port);
410 * This is the shutdown callback for this JACK application.
411 * It is called by JACK if the server ever shuts down or
412 * decides to disconnect the client.
415 void jack_shutdown (void *arg) {
417 exit (1);
421 * be user friendly.
422 * be user friendly.
423 * be user friendly.
426 void printUsage() {
427 fprintf(stderr, "usage: alsa_out [options]\n"
428 "\n"
429 " -j <jack name> - reports a different name to jack\n"
430 " -d <alsa_device> \n"
431 " -c <channels> \n"
432 " -p <period_size> \n"
433 " -n <num_period> \n"
434 " -r <sample_rate> \n"
435 " -m <max_diff> \n"
436 " -t <target_delay> \n"
437 " -f <catch_factor> \n"
438 "\n");
443 * the main function....
447 int main (int argc, char *argv[]) {
448 char jack_name[30] = "alsa_out";
449 char alsa_device[30] = "hw:0";
451 extern char *optarg;
452 extern int optind, optopt;
453 int errflg=0;
454 int c;
456 while ((c = getopt(argc, argv, ":j:r:c:p:n:d:m:t:f:")) != -1) {
457 switch(c) {
458 case 'j':
459 strcpy(jack_name,optarg);
460 break;
461 case 'r':
462 sample_rate = atoi(optarg);
463 break;
464 case 'c':
465 num_channels = atoi(optarg);
466 break;
467 case 'p':
468 period_size = atoi(optarg);
469 break;
470 case 'n':
471 num_periods = atoi(optarg);
472 break;
473 case 'd':
474 strcpy(alsa_device,optarg);
475 break;
476 case 't':
477 target_delay = atoi(optarg);
478 break;
479 case 'm':
480 max_diff = atoi(optarg);
481 break;
482 case 'f':
483 catch_factor = atoi(optarg);
484 break;
485 case ':':
486 fprintf(stderr,
487 "Option -%c requires an operand\n", optopt);
488 errflg++;
489 break;
490 case '?':
491 fprintf(stderr,
492 "Unrecognized option: -%c\n", optopt);
493 errflg++;
496 if (errflg) {
497 printUsage();
498 exit(2);
501 // Setup target delay and max_diff for the normal user, who does not play with them...
503 if( !target_delay )
504 target_delay = num_periods*period_size / 2;
506 if( !max_diff )
507 max_diff = period_size / 2;
511 if ((client = jack_client_new (jack_name)) == 0) {
512 fprintf (stderr, "jack server not running?\n");
513 return 1;
516 /* tell the JACK server to call `process()' whenever
517 there is work to be done.
520 jack_set_process_callback (client, process, 0);
522 /* tell the JACK server to call `jack_shutdown()' if
523 it ever shuts down, either entirely, or if it
524 just decides to stop calling us.
527 jack_on_shutdown (client, jack_shutdown, 0);
530 // alloc input ports, which are blasted out to alsa...
531 alloc_ports( 0, num_channels );
533 // get jack sample_rate
535 jack_sample_rate = jack_get_sample_rate( client );
537 if( !sample_rate )
538 sample_rate = jack_sample_rate;
540 current_resample_factor = (double) sample_rate / (double) jack_sample_rate;
541 // now open the alsa fd...
543 alsa_handle = open_audiofd( alsa_device, 0, sample_rate, num_channels, period_size, num_periods);
544 if( alsa_handle < 0 )
545 exit(20);
548 /* tell the JACK server that we are ready to roll */
550 if (jack_activate (client)) {
551 fprintf (stderr, "cannot activate client");
552 return 1;
555 while(1) sleep(1);
556 jack_client_close (client);
557 exit (0);