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.
17 #include <jack/jack.h>
18 #include <jack/jslist.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
;
38 double resample_mean
= 1.0;
39 double static_resample_factor
= 1.0;
43 int offset_differential_index
= 0;
45 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;
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;
60 double controlquant
= 10000.0;
61 int smooth_size
= 256;
65 int samplerate_quality
= 2;
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
;
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
);
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]))
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
);
104 printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err
));
106 } else if (err
== -EAGAIN
) {
107 while ((err
= snd_pcm_resume(handle
)) == -EAGAIN
)
108 usleep(100); /* wait until the suspend flag is released */
110 err
= snd_pcm_prepare(handle
);
112 printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err
));
119 static int set_hwformat( snd_pcm_t
*handle
, snd_pcm_hw_params_t
*params
)
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
);
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
) {
138 unsigned int buffer_time
;
139 unsigned int period_time
;
141 unsigned int rchannels
;
143 /* choose all parameters */
144 err
= snd_pcm_hw_params_any(handle
, params
);
146 printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err
));
149 /* set the interleaved read/write format */
150 err
= snd_pcm_hw_params_set_access(handle
, params
, access
);
152 printf("Access type not available for playback: %s\n", snd_strerror(err
));
156 /* set the sample format */
157 err
= set_hwformat(handle
, params
);
159 printf("Sample format not available for playback: %s\n", snd_strerror(err
));
162 /* set the count of channels */
163 rchannels
= channels
;
164 err
= snd_pcm_hw_params_set_channels_near(handle
, params
, &rchannels
);
166 printf("Channels count (%i) not available for record: %s\n", channels
, snd_strerror(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 */
175 err
= snd_pcm_hw_params_set_rate_near(handle
, params
, &rrate
, 0);
177 printf("Rate %iHz not available for playback: %s\n", rate
, snd_strerror(err
));
181 printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate
, rrate
);
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
);
189 printf("Unable to set buffer time %i for playback: %s\n", 1000000*period
*nperiods
/rate
, snd_strerror(err
));
192 err
= snd_pcm_hw_params_get_buffer_size( params
, &real_buffer_size
);
194 printf("Unable to get buffer size back: %s\n", snd_strerror(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
);
204 printf("Unable to set period time %i for playback: %s\n", 1000000*period
/rate
, snd_strerror(err
));
207 err
= snd_pcm_hw_params_get_period_size(params
, &real_period_size
, NULL
);
209 printf("Unable to get period size back: %s\n", snd_strerror(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
);
218 printf("Unable to set hw params for playback: %s\n", snd_strerror(err
));
224 static int set_swparams(snd_pcm_t
*handle
, snd_pcm_sw_params_t
*swparams
, int period
, int nperiods
) {
227 /* get the current swparams */
228 err
= snd_pcm_sw_params_current(handle
, swparams
);
230 printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err
));
233 /* start the transfer when the buffer is full */
234 err
= snd_pcm_sw_params_set_start_threshold(handle
, swparams
, period
);
236 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err
));
239 err
= snd_pcm_sw_params_set_stop_threshold(handle
, swparams
, -1 );
241 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(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 );
247 printf("Unable to set avail min for capture: %s\n", snd_strerror(err
));
250 /* align all transfers to 1 sample */
251 err
= snd_pcm_sw_params_set_xfer_align(handle
, swparams
, 1);
253 printf("Unable to set transfer align for capture: %s\n", snd_strerror(err
));
256 /* write the parameters to the playback device */
257 err
= snd_pcm_sw_params(handle
, swparams
);
259 printf("Unable to set sw params for capture: %s\n", snd_strerror(err
));
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
) {
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
));
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
));
285 if ((err
= set_swparams(handle
, swparams
, period
, nperiods
)) < 0) {
286 printf("Setting of swparams failed: %s\n", snd_strerror(err
));
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
);
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
) {
316 snd_pcm_sframes_t delay
= target_delay
;
319 snd_pcm_delay( alsa_handle
, &delay
);
321 delay
-= jack_frames_since_cycle_start( client
);
322 delay
+= jack_get_buffer_size( client
) / 2;
323 // Do it the hard way.
324 // this is for compensating xruns etc...
326 if( delay
> (target_delay
+max_diff
) ) {
327 snd_pcm_rewind( alsa_handle
, delay
- target_delay
);
328 output_new_delay
= (int) delay
;
330 delay
= target_delay
;
332 // Set the resample_rate... we need to adjust the offset integral, to do this.
333 // first look at the PI controller, this code is just a special case, which should never execute once
334 // everything is swung in.
335 offset_integral
= - (resample_mean
- static_resample_factor
) * catch_factor
* catch_factor2
;
336 // Also clear the array. we are beginning a new control cycle.
337 for( i
=0; i
<smooth_size
; i
++ )
338 offset_array
[i
] = 0.0;
340 if( delay
< (target_delay
-max_diff
) ) {
341 char *tmp
= alloca( (target_delay
-delay
) * formats
[format
].sample_size
* num_channels
);
342 memset( tmp
, 0, formats
[format
].sample_size
* num_channels
* (target_delay
-delay
) );
343 snd_pcm_writei( alsa_handle
, tmp
, target_delay
-delay
);
345 output_new_delay
= (int) delay
;
347 delay
= target_delay
;
349 // Set the resample_rate... we need to adjust the offset integral, to do this.
350 offset_integral
= - (resample_mean
- static_resample_factor
) * catch_factor
* catch_factor2
;
351 // Also clear the array. we are beginning a new control cycle.
352 for( i
=0; i
<smooth_size
; i
++ )
353 offset_array
[i
] = 0.0;
355 /* ok... now we should have target_delay +- max_diff on the alsa side.
357 * calculate the number of frames, we want to get.
360 double offset
= delay
- target_delay
;
363 offset_array
[(offset_differential_index
++)% smooth_size
] = offset
;
365 // Build the mean of the windowed offset array
366 // basically fir lowpassing.
367 double smooth_offset
= 0.0;
368 for( i
=0; i
<smooth_size
; i
++ )
370 offset_array
[ (i
+ offset_differential_index
-1) % smooth_size
] * window_array
[i
];
371 smooth_offset
/= (double) smooth_size
;
373 // this is the integral of the smoothed_offset
374 offset_integral
+= smooth_offset
;
377 // the smooth offset still contains unwanted noise
378 // which would go straigth onto the resample coeff.
379 // it only used in the P component and the I component is used for the fine tuning anyways.
380 if( fabs( smooth_offset
) < pclamp
)
383 // ok. now this is the PI controller.
384 // u(t) = K * ( e(t) + 1/T \int e(t') dt' )
385 // K = 1/catch_factor and T = catch_factor2
386 double current_resample_factor
= static_resample_factor
- smooth_offset
/ (double) catch_factor
- offset_integral
/ (double) catch_factor
/ (double)catch_factor2
;
388 // now quantize this value around resample_mean, so that the noise which is in the integral component doesnt hurt.
389 current_resample_factor
= floor( (current_resample_factor
- resample_mean
) * controlquant
+ 0.5 ) / controlquant
+ resample_mean
;
391 // Output "instrumentatio" gonna change that to real instrumentation in a few.
392 output_resampling_factor
= (float) current_resample_factor
;
393 output_diff
= (float) smooth_offset
;
394 output_integral
= (float) offset_integral
;
395 output_offset
= (float) offset
;
398 if( current_resample_factor
< 0.25 ) current_resample_factor
= 0.25;
399 if( current_resample_factor
> 4 ) current_resample_factor
= 4;
401 // Now Calculate how many samples we need.
402 rlen
= ceil( ((double)nframes
) * current_resample_factor
)+2;
405 // Calculate resample_mean so we can init ourselves to saner values.
406 resample_mean
= 0.9999 * resample_mean
+ 0.0001 * current_resample_factor
;
408 * now this should do it...
411 outbuf
= alloca( rlen
* formats
[format
].sample_size
* num_channels
);
413 resampbuf
= alloca( rlen
* sizeof( float ) );
415 * render jack ports to the outbuf...
419 JSList
*node
= playback_ports
;
420 JSList
*src_node
= playback_srcs
;
423 while ( node
!= NULL
)
425 jack_port_t
*port
= (jack_port_t
*) node
->data
;
426 float *buf
= jack_port_get_buffer (port
, nframes
);
428 SRC_STATE
*src_state
= src_node
->data
;
431 src
.input_frames
= nframes
;
433 src
.data_out
= resampbuf
;
434 src
.output_frames
= rlen
;
435 src
.end_of_input
= 0;
437 src
.src_ratio
= current_resample_factor
;
439 src_process( src_state
, &src
);
441 formats
[format
].jack_to_soundcard( outbuf
+ format
[formats
].sample_size
* chn
, resampbuf
, src
.output_frames_gen
, num_channels
*format
[formats
].sample_size
, NULL
);
443 src_node
= jack_slist_next (src_node
);
444 node
= jack_slist_next (node
);
448 // now write the output...
450 err
= snd_pcm_writei(alsa_handle
, outbuf
, src
.output_frames_gen
);
451 //err = snd_pcm_writei(alsa_handle, outbuf, src.output_frames_gen);
453 printf( "err = %d\n", err
);
454 if (xrun_recovery(alsa_handle
, err
) < 0) {
455 printf("Write error: %s\n", snd_strerror(err
));
466 * Allocate the necessary jack ports...
469 void alloc_ports( int n_capture
, int n_playback
) {
471 int port_flags
= JackPortIsOutput
| JackPortIsPhysical
| JackPortIsTerminal
;
476 capture_ports
= NULL
;
477 for (chn
= 0; chn
< n_capture
; chn
++)
479 snprintf (buf
, sizeof(buf
) - 1, "capture_%u", chn
+1);
481 port
= jack_port_register (client
, buf
,
482 JACK_DEFAULT_AUDIO_TYPE
,
487 printf( "jacknet_client: cannot register port for %s", buf
);
491 capture_srcs
= jack_slist_append( capture_srcs
, src_new( 4-samplerate_quality
, 1, NULL
) );
492 capture_ports
= jack_slist_append (capture_ports
, port
);
495 port_flags
= JackPortIsInput
;
497 playback_ports
= NULL
;
498 for (chn
= 0; chn
< n_playback
; chn
++)
500 snprintf (buf
, sizeof(buf
) - 1, "playback_%u", chn
+1);
502 port
= jack_port_register (client
, buf
,
503 JACK_DEFAULT_AUDIO_TYPE
,
508 printf( "jacknet_client: cannot register port for %s", buf
);
512 playback_srcs
= jack_slist_append( playback_srcs
, src_new( 4-samplerate_quality
, 1, NULL
) );
513 playback_ports
= jack_slist_append (playback_ports
, port
);
518 * This is the shutdown callback for this JACK application.
519 * It is called by JACK if the server ever shuts down or
520 * decides to disconnect the client.
523 void jack_shutdown (void *arg
) {
535 fprintf(stderr
, "usage: alsa_out [options]\n"
537 " -j <jack name> - client name\n"
538 " -d <alsa_device> \n"
540 " -p <period_size> \n"
541 " -n <num_period> \n"
542 " -r <sample_rate> \n"
543 " -q <sample_rate quality [0..4]\n"
545 " -t <target_delay> \n"
546 " -i turns on instrumentation\n"
547 " -v turns on printouts\n"
553 * the main function....
557 sigterm_handler( int signal
)
563 int main (int argc
, char *argv
[]) {
564 char jack_name
[30] = "alsa_out";
565 char alsa_device
[30] = "hw:0";
568 extern int optind
, optopt
;
572 while ((c
= getopt(argc
, argv
, "ivj:r:c:p:n:d:q:m:t:f:F:C:Q:s:")) != -1) {
575 strcpy(jack_name
,optarg
);
578 sample_rate
= atoi(optarg
);
581 num_channels
= atoi(optarg
);
584 period_size
= atoi(optarg
);
587 num_periods
= atoi(optarg
);
590 strcpy(alsa_device
,optarg
);
593 target_delay
= atoi(optarg
);
596 samplerate_quality
= atoi(optarg
);
599 max_diff
= atoi(optarg
);
602 catch_factor
= atoi(optarg
);
605 catch_factor2
= atoi(optarg
);
608 pclamp
= (double) atoi(optarg
);
611 controlquant
= (double) atoi(optarg
);
620 smooth_size
= atoi(optarg
);
624 "Option -%c requires an operand\n", optopt
);
629 "Unrecognized option: -%c\n", optopt
);
638 if( (samplerate_quality
< 0) || (samplerate_quality
> 4) ) {
639 fprintf (stderr
, "invalid samplerate quality\n");
642 if ((client
= jack_client_open (jack_name
, 0, NULL
)) == 0) {
643 fprintf (stderr
, "jack server not running?\n");
647 /* tell the JACK server to call `process()' whenever
648 there is work to be done.
651 jack_set_process_callback (client
, process
, 0);
653 /* tell the JACK server to call `jack_shutdown()' if
654 it ever shuts down, either entirely, or if it
655 just decides to stop calling us.
658 jack_on_shutdown (client
, jack_shutdown
, 0);
661 // get jack sample_rate
663 jack_sample_rate
= jack_get_sample_rate( client
);
666 sample_rate
= jack_sample_rate
;
668 static_resample_factor
= (double) sample_rate
/ (double) jack_sample_rate
;
669 resample_mean
= static_resample_factor
;
671 offset_array
= malloc( sizeof(double) * smooth_size
);
672 if( offset_array
== NULL
) {
673 fprintf( stderr
, "no memory for offset_array !!!\n" );
676 window_array
= malloc( sizeof(double) * smooth_size
);
677 if( window_array
== NULL
) {
678 fprintf( stderr
, "no memory for window_array !!!\n" );
682 for( i
=0; i
<smooth_size
; i
++ ) {
683 offset_array
[i
] = 0.0;
684 window_array
[i
] = hann( (double) i
/ ((double) smooth_size
- 1.0) );
687 jack_buffer_size
= jack_get_buffer_size( client
);
688 // Setup target delay and max_diff for the normal user, who does not play with them...
690 target_delay
= (num_periods
*period_size
/ 2) - jack_buffer_size
/2;
693 max_diff
= target_delay
;
695 if( max_diff
> target_delay
) {
696 fprintf( stderr
, "target_delay (%d) cant be smaller than max_diff(%d)\n", target_delay
, max_diff
);
699 if( (target_delay
+max_diff
) > (num_periods
*period_size
) ) {
700 fprintf( stderr
, "target_delay+max_diff (%d) cant be bigger than buffersize(%d)\n", target_delay
+max_diff
, num_periods
*period_size
);
703 // now open the alsa fd...
704 alsa_handle
= open_audiofd( alsa_device
, 0, sample_rate
, num_channels
, period_size
, num_periods
);
705 if( alsa_handle
== 0 )
708 printf( "selected sample format: %s\n", formats
[format
].name
);
710 // alloc input ports, which are blasted out to alsa...
711 alloc_ports( 0, num_channels
);
714 /* tell the JACK server that we are ready to roll */
716 if (jack_activate (client
)) {
717 fprintf (stderr
, "cannot activate client");
721 signal( SIGTERM
, sigterm_handler
);
722 signal( SIGINT
, sigterm_handler
);
727 if( output_new_delay
) {
728 printf( "delay = %d\n", output_new_delay
);
729 output_new_delay
= 0;
731 printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor
, output_diff
, output_offset
);
733 } else if( instrument
) {
734 printf( "# n\tresamp\tdiff\toffseti\tintegral\n");
738 printf( "%d\t%f\t%f\t%f\t%f\n", n
++, output_resampling_factor
, output_diff
, output_offset
, output_integral
);
744 if( output_new_delay
) {
745 printf( "delay = %d\n", output_new_delay
);
746 output_new_delay
= 0;
751 jack_deactivate( client
);
752 jack_client_close (client
);