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
;
39 double resample_mean
= 1.0;
40 double static_resample_factor
= 1.0;
41 double resample_lower_limit
= 0.25;
42 double resample_upper_limit
= 4.0;
46 int offset_differential_index
= 0;
48 double offset_integral
= 0;
50 // ------------------------------------------------------ commandline parameters
52 int sample_rate
= 0; /* stream rate */
53 int num_channels
= 2; /* count of channels */
54 int period_size
= 1024;
57 int target_delay
= 0; /* the delay which the program should try to approach. */
58 int max_diff
= 0; /* the diff value, when a hard readpointer skip should occur */
59 int catch_factor
= 100000;
60 int catch_factor2
= 10000;
62 double controlquant
= 10000.0;
63 int smooth_size
= 256;
67 int samplerate_quality
= 2;
71 volatile float output_resampling_factor
= 1.0;
72 volatile int output_new_delay
= 0;
73 volatile float output_offset
= 0.0;
74 volatile float output_integral
= 0.0;
75 volatile float output_diff
= 0.0;
76 volatile int running_freewheel
= 0;
78 snd_pcm_uframes_t real_buffer_size
;
79 snd_pcm_uframes_t real_period_size
;
87 // format selection, and corresponding functions from memops in a nice set of structs.
89 typedef struct alsa_format
{
90 snd_pcm_format_t format_id
;
92 void (*jack_to_soundcard
) (char *dst
, jack_default_audio_sample_t
*src
, unsigned long nsamples
, unsigned long dst_skip
, dither_state_t
*state
);
93 void (*soundcard_to_jack
) (jack_default_audio_sample_t
*dst
, char *src
, unsigned long nsamples
, unsigned long src_skip
);
97 alsa_format_t formats
[] = {
98 { SND_PCM_FORMAT_FLOAT_LE
, 4, sample_move_dS_floatLE
, sample_move_floatLE_sSs
, "float" },
99 { SND_PCM_FORMAT_S32
, 4, sample_move_d32u24_sS
, sample_move_dS_s32u24
, "32bit" },
100 { SND_PCM_FORMAT_S24_3LE
, 3, sample_move_d24_sS
, sample_move_dS_s24
, "24bit - real" },
101 { SND_PCM_FORMAT_S24
, 4, sample_move_d24_sS
, sample_move_dS_s24
, "24bit" },
102 { SND_PCM_FORMAT_S16
, 2, sample_move_d16_sS
, sample_move_dS_s16
, "16bit" }
104 ,{ SND_PCM_FORMAT_S16_LE
, 2, sample_move_d16_sS
, sample_move_dS_s16
, "16bit little-endian" }
107 #define NUMFORMATS (sizeof(formats)/sizeof(formats[0]))
110 // Alsa stuff... i don't want to touch this bullshit in the next years.... please...
112 static int xrun_recovery(snd_pcm_t
*handle
, int err
) {
113 // printf( "xrun !!!.... %d\n", err );
114 if (err
== -EPIPE
) { /* under-run */
115 err
= snd_pcm_prepare(handle
);
117 printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err
));
119 } else if (err
== -ESTRPIPE
) {
120 while ((err
= snd_pcm_resume(handle
)) == -EAGAIN
)
121 usleep(100); /* wait until the suspend flag is released */
123 err
= snd_pcm_prepare(handle
);
125 printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err
));
132 static int set_hwformat( snd_pcm_t
*handle
, snd_pcm_hw_params_t
*params
)
136 snd_pcm_hw_params_set_format(handle
, params
, formats
[format
].format_id
);
142 for( i
=0; i
<NUMFORMATS
; i
++ ) {
143 /* set the sample format */
144 err
= snd_pcm_hw_params_set_format(handle
, params
, formats
[i
].format_id
);
155 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
) {
157 unsigned int buffer_time
;
158 unsigned int period_time
;
160 unsigned int rchannels
;
162 /* choose all parameters */
163 err
= snd_pcm_hw_params_any(handle
, params
);
165 printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err
));
168 /* set the interleaved read/write format */
169 err
= snd_pcm_hw_params_set_access(handle
, params
, access
);
171 printf("Access type not available for playback: %s\n", snd_strerror(err
));
175 /* set the sample format */
176 err
= set_hwformat(handle
, params
);
178 printf("Sample format not available for playback: %s\n", snd_strerror(err
));
181 /* set the count of channels */
182 rchannels
= channels
;
183 err
= snd_pcm_hw_params_set_channels_near(handle
, params
, &rchannels
);
185 printf("Channels count (%i) not available for record: %s\n", channels
, snd_strerror(err
));
188 if (rchannels
!= channels
) {
189 printf("WARNING: channel count does not match (requested %d got %d)\n", channels
, rchannels
);
190 num_channels
= rchannels
;
192 /* set the stream rate */
194 err
= snd_pcm_hw_params_set_rate_near(handle
, params
, &rrate
, 0);
196 printf("Rate %iHz not available for playback: %s\n", rate
, snd_strerror(err
));
200 printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate
, rrate
);
203 /* set the buffer time */
205 buffer_time
= 1000000*(uint64_t)period
*nperiods
/rate
;
206 err
= snd_pcm_hw_params_set_buffer_time_near(handle
, params
, &buffer_time
, &dir
);
208 printf("Unable to set buffer time %i for playback: %s\n", 1000000*period
*nperiods
/rate
, snd_strerror(err
));
211 err
= snd_pcm_hw_params_get_buffer_size( params
, &real_buffer_size
);
213 printf("Unable to get buffer size back: %s\n", snd_strerror(err
));
216 if( real_buffer_size
!= nperiods
* period
) {
217 printf( "WARNING: buffer size does not match: (requested %d, got %d)\n", nperiods
* period
, (int) real_buffer_size
);
219 /* set the period time */
220 period_time
= 1000000*(uint64_t)period
/rate
;
221 err
= snd_pcm_hw_params_set_period_time_near(handle
, params
, &period_time
, &dir
);
223 printf("Unable to set period time %i for playback: %s\n", 1000000*period
/rate
, snd_strerror(err
));
226 err
= snd_pcm_hw_params_get_period_size(params
, &real_period_size
, NULL
);
228 printf("Unable to get period size back: %s\n", snd_strerror(err
));
231 if( real_period_size
!= period
) {
232 printf( "WARNING: period size does not match: (requested %i, got %i)\n", period
, (int)real_period_size
);
234 /* write the parameters to device */
235 err
= snd_pcm_hw_params(handle
, params
);
237 printf("Unable to set hw params for playback: %s\n", snd_strerror(err
));
243 static int set_swparams(snd_pcm_t
*handle
, snd_pcm_sw_params_t
*swparams
, int period
, int nperiods
) {
246 /* get the current swparams */
247 err
= snd_pcm_sw_params_current(handle
, swparams
);
249 printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err
));
252 /* start the transfer when the buffer is full */
253 err
= snd_pcm_sw_params_set_start_threshold(handle
, swparams
, period
);
255 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err
));
258 err
= snd_pcm_sw_params_set_stop_threshold(handle
, swparams
, -1 );
260 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err
));
263 /* allow the transfer when at least period_size samples can be processed */
264 err
= snd_pcm_sw_params_set_avail_min(handle
, swparams
, 1 );
266 printf("Unable to set avail min for capture: %s\n", snd_strerror(err
));
269 /* align all transfers to 1 sample */
270 err
= snd_pcm_sw_params_set_xfer_align(handle
, swparams
, 1);
272 printf("Unable to set transfer align for capture: %s\n", snd_strerror(err
));
275 /* write the parameters to the playback device */
276 err
= snd_pcm_sw_params(handle
, swparams
);
278 printf("Unable to set sw params for capture: %s\n", snd_strerror(err
));
284 // ok... i only need this function to communicate with the alsa bloat api...
286 static snd_pcm_t
*open_audiofd( char *device_name
, int capture
, int rate
, int channels
, int period
, int nperiods
) {
289 snd_pcm_hw_params_t
*hwparams
;
290 snd_pcm_sw_params_t
*swparams
;
292 snd_pcm_hw_params_alloca(&hwparams
);
293 snd_pcm_sw_params_alloca(&swparams
);
295 if ((err
= snd_pcm_open(&(handle
), device_name
, capture
? SND_PCM_STREAM_CAPTURE
: SND_PCM_STREAM_PLAYBACK
, SND_PCM_NONBLOCK
)) < 0) {
296 printf("Capture open error: %s\n", snd_strerror(err
));
300 if ((err
= set_hwparams(handle
, hwparams
,SND_PCM_ACCESS_RW_INTERLEAVED
, rate
, channels
, period
, nperiods
)) < 0) {
301 printf("Setting of hwparams failed: %s\n", snd_strerror(err
));
304 if ((err
= set_swparams(handle
, swparams
, period
, nperiods
)) < 0) {
305 printf("Setting of swparams failed: %s\n", snd_strerror(err
));
309 //snd_pcm_start( handle );
310 //snd_pcm_wait( handle, 200 );
311 int num_null_samples
= nperiods
* period
* channels
;
312 char *tmp
= alloca( num_null_samples
* formats
[format
].sample_size
);
313 memset( tmp
, 0, num_null_samples
* formats
[format
].sample_size
);
314 snd_pcm_writei( handle
, tmp
, num_null_samples
);
320 double hann( double x
)
322 return 0.5 * (1.0 - cos( 2*M_PI
* x
) );
326 * The freewheel callback.
328 void freewheel (int starting
, void* arg
) {
329 running_freewheel
= starting
;
333 * The process callback for this JACK application.
334 * It is called by JACK at the appropriate times.
336 int process (jack_nframes_t nframes
, void *arg
) {
338 if (running_freewheel
) {
339 JSList
*node
= playback_ports
;
341 while ( node
!= NULL
)
343 jack_port_t
*port
= (jack_port_t
*) node
->data
;
344 float *buf
= jack_port_get_buffer (port
, nframes
);
346 memset(buf
, 0, sizeof(float)*nframes
);
348 node
= jack_slist_next (node
);
356 snd_pcm_sframes_t delay
= target_delay
;
359 delay
= (num_periods
*period_size
)-snd_pcm_avail( alsa_handle
) ;
361 delay
-= round( jack_frames_since_cycle_start( client
) * static_resample_factor
);
362 // Do it the hard way.
363 // this is for compensating xruns etc...
365 if( delay
> (target_delay
+max_diff
) ) {
366 snd_pcm_rewind( alsa_handle
, delay
- target_delay
);
367 output_new_delay
= (int) delay
;
369 delay
= target_delay
;
371 // Set the resample_rate... we need to adjust the offset integral, to do this.
372 // first look at the PI controller, this code is just a special case, which should never execute once
373 // everything is swung in.
374 offset_integral
= - (resample_mean
- static_resample_factor
) * catch_factor
* catch_factor2
;
375 // Also clear the array. we are beginning a new control cycle.
376 for( i
=0; i
<smooth_size
; i
++ )
377 offset_array
[i
] = 0.0;
379 if( delay
< (target_delay
-max_diff
) ) {
381 output_new_delay
= (int) delay
;
383 while ((target_delay
-delay
) > 0) {
384 snd_pcm_uframes_t to_write
= ((target_delay
-delay
) > 512) ? 512 : (target_delay
-delay
);
385 snd_pcm_writei( alsa_handle
, tmpbuf
, to_write
);
389 delay
= target_delay
;
391 // Set the resample_rate... we need to adjust the offset integral, to do this.
392 offset_integral
= - (resample_mean
- static_resample_factor
) * catch_factor
* catch_factor2
;
393 // Also clear the array. we are beginning a new control cycle.
394 for( i
=0; i
<smooth_size
; i
++ )
395 offset_array
[i
] = 0.0;
397 /* ok... now we should have target_delay +- max_diff on the alsa side.
399 * calculate the number of frames, we want to get.
402 double offset
= delay
- target_delay
;
405 offset_array
[(offset_differential_index
++)% smooth_size
] = offset
;
407 // Build the mean of the windowed offset array
408 // basically fir lowpassing.
409 double smooth_offset
= 0.0;
410 for( i
=0; i
<smooth_size
; i
++ )
412 offset_array
[ (i
+ offset_differential_index
-1) % smooth_size
] * window_array
[i
];
413 smooth_offset
/= (double) smooth_size
;
415 // this is the integral of the smoothed_offset
416 offset_integral
+= smooth_offset
;
419 // the smooth offset still contains unwanted noise
420 // which would go straight onto the resample coeff.
421 // it only used in the P component and the I component is used for the fine tuning anyways.
422 if( fabs( smooth_offset
) < pclamp
)
425 // ok. now this is the PI controller.
426 // u(t) = K * ( e(t) + 1/T \int e(t') dt' )
427 // K = 1/catch_factor and T = catch_factor2
428 double current_resample_factor
= static_resample_factor
- smooth_offset
/ (double) catch_factor
- offset_integral
/ (double) catch_factor
/ (double)catch_factor2
;
430 // now quantize this value around resample_mean, so that the noise which is in the integral component doesn't hurt.
431 current_resample_factor
= floor( (current_resample_factor
- resample_mean
) * controlquant
+ 0.5 ) / controlquant
+ resample_mean
;
433 // Output "instrumentatio" gonna change that to real instrumentation in a few.
434 output_resampling_factor
= (float) current_resample_factor
;
435 output_diff
= (float) smooth_offset
;
436 output_integral
= (float) offset_integral
;
437 output_offset
= (float) offset
;
440 if( current_resample_factor
< resample_lower_limit
) current_resample_factor
= resample_lower_limit
;
441 if( current_resample_factor
> resample_upper_limit
) current_resample_factor
= resample_upper_limit
;
443 // Now Calculate how many samples we need.
444 rlen
= ceil( ((double)nframes
) * current_resample_factor
)+2;
447 // Calculate resample_mean so we can init ourselves to saner values.
448 resample_mean
= 0.9999 * resample_mean
+ 0.0001 * current_resample_factor
;
450 * now this should do it...
453 outbuf
= alloca( rlen
* formats
[format
].sample_size
* num_channels
);
455 resampbuf
= alloca( rlen
* sizeof( float ) );
457 * render jack ports to the outbuf...
461 JSList
*node
= playback_ports
;
462 JSList
*src_node
= playback_srcs
;
465 while ( node
!= NULL
)
467 jack_port_t
*port
= (jack_port_t
*) node
->data
;
468 float *buf
= jack_port_get_buffer (port
, nframes
);
470 SRC_STATE
*src_state
= src_node
->data
;
473 src
.input_frames
= nframes
;
475 src
.data_out
= resampbuf
;
476 src
.output_frames
= rlen
;
477 src
.end_of_input
= 0;
479 src
.src_ratio
= current_resample_factor
;
481 src_process( src_state
, &src
);
483 formats
[format
].jack_to_soundcard( outbuf
+ format
[formats
].sample_size
* chn
, resampbuf
, src
.output_frames_gen
, num_channels
*format
[formats
].sample_size
, NULL
);
485 src_node
= jack_slist_next (src_node
);
486 node
= jack_slist_next (node
);
490 // now write the output...
492 err
= snd_pcm_writei(alsa_handle
, outbuf
, src
.output_frames_gen
);
493 //err = snd_pcm_writei(alsa_handle, outbuf, src.output_frames_gen);
495 printf( "err = %d\n", err
);
496 if (xrun_recovery(alsa_handle
, err
) < 0) {
497 printf("Write error: %s\n", snd_strerror(err
));
507 * the latency callback.
508 * sets up the latencies on the ports.
512 latency_cb (jack_latency_callback_mode_t mode
, void *arg
)
514 jack_latency_range_t range
;
517 range
.min
= range
.max
= round(target_delay
/ static_resample_factor
);
519 if (mode
== JackCaptureLatency
) {
520 for (node
= capture_ports
; node
; node
= jack_slist_next (node
)) {
521 jack_port_t
*port
= node
->data
;
522 jack_port_set_latency_range (port
, mode
, &range
);
525 for (node
= playback_ports
; node
; node
= jack_slist_next (node
)) {
526 jack_port_t
*port
= node
->data
;
527 jack_port_set_latency_range (port
, mode
, &range
);
534 * Allocate the necessary jack ports...
537 void alloc_ports( int n_capture
, int n_playback
) {
539 int port_flags
= JackPortIsOutput
| JackPortIsPhysical
| JackPortIsTerminal
;
544 capture_ports
= NULL
;
545 for (chn
= 0; chn
< n_capture
; chn
++)
547 snprintf (buf
, sizeof(buf
) - 1, "capture_%u", chn
+1);
549 port
= jack_port_register (client
, buf
,
550 JACK_DEFAULT_AUDIO_TYPE
,
555 printf( "jacknet_client: cannot register port for %s", buf
);
559 capture_srcs
= jack_slist_append( capture_srcs
, src_new( 4-samplerate_quality
, 1, NULL
) );
560 capture_ports
= jack_slist_append (capture_ports
, port
);
563 port_flags
= JackPortIsInput
;
565 playback_ports
= NULL
;
566 for (chn
= 0; chn
< n_playback
; chn
++)
568 snprintf (buf
, sizeof(buf
) - 1, "playback_%u", chn
+1);
570 port
= jack_port_register (client
, buf
,
571 JACK_DEFAULT_AUDIO_TYPE
,
576 printf( "jacknet_client: cannot register port for %s", buf
);
580 playback_srcs
= jack_slist_append( playback_srcs
, src_new( 4-samplerate_quality
, 1, NULL
) );
581 playback_ports
= jack_slist_append (playback_ports
, port
);
586 * This is the shutdown callback for this JACK application.
587 * It is called by JACK if the server ever shuts down or
588 * decides to disconnect the client.
591 void jack_shutdown (void *arg
) {
603 fprintf(stderr
, "usage: alsa_out [options]\n"
605 " -j <jack name> - client name\n"
606 " -d <alsa_device> \n"
608 " -p <period_size> \n"
609 " -n <num_period> \n"
610 " -r <sample_rate> \n"
611 " -q <sample_rate quality [0..4]\n"
613 " -t <target_delay> \n"
614 " -i turns on instrumentation\n"
615 " -v turns on printouts\n"
621 * the main function....
625 sigterm_handler( int signal
)
631 int main (int argc
, char *argv
[]) {
632 char jack_name
[30] = "alsa_out";
633 char alsa_device
[30] = "hw:0";
635 char *server_name
= NULL
;
638 extern int optind
, optopt
;
642 while ((c
= getopt(argc
, argv
, "ivj:r:c:p:n:d:q:m:t:f:F:C:Q:s:S:")) != -1) {
645 strcpy(jack_name
,optarg
);
648 sample_rate
= atoi(optarg
);
651 num_channels
= atoi(optarg
);
654 period_size
= atoi(optarg
);
657 num_periods
= atoi(optarg
);
660 strcpy(alsa_device
,optarg
);
663 target_delay
= atoi(optarg
);
666 samplerate_quality
= atoi(optarg
);
669 max_diff
= atoi(optarg
);
672 catch_factor
= atoi(optarg
);
675 catch_factor2
= atoi(optarg
);
678 pclamp
= (double) atoi(optarg
);
681 controlquant
= (double) atoi(optarg
);
690 smooth_size
= atoi(optarg
);
693 server_name
= optarg
;
694 jack_opts
|= JackServerName
;
698 "Option -%c requires an operand\n", optopt
);
703 "Unrecognized option: -%c\n", optopt
);
712 if( (samplerate_quality
< 0) || (samplerate_quality
> 4) ) {
713 fprintf (stderr
, "invalid samplerate quality\n");
716 if ((client
= jack_client_open (jack_name
, jack_opts
, NULL
, server_name
)) == 0) {
717 fprintf (stderr
, "jack server not running?\n");
721 /* tell the JACK server to call `process()' whenever
722 there is work to be done.
725 jack_set_process_callback (client
, process
, 0);
727 /* tell the JACK server to call `freewheel()' whenever
728 freewheel mode changes.
731 jack_set_freewheel_callback (client
, freewheel
, 0);
733 /* tell the JACK server to call `jack_shutdown()' if
734 it ever shuts down, either entirely, or if it
735 just decides to stop calling us.
738 jack_on_shutdown (client
, jack_shutdown
, 0);
740 if (jack_set_latency_callback
)
741 jack_set_latency_callback (client
, latency_cb
, 0);
743 // get jack sample_rate
745 jack_sample_rate
= jack_get_sample_rate( client
);
748 sample_rate
= jack_sample_rate
;
750 static_resample_factor
= (double) sample_rate
/ (double) jack_sample_rate
;
751 resample_lower_limit
= static_resample_factor
* 0.25;
752 resample_upper_limit
= static_resample_factor
* 4.0;
753 resample_mean
= static_resample_factor
;
755 offset_array
= malloc( sizeof(double) * smooth_size
);
756 if( offset_array
== NULL
) {
757 fprintf( stderr
, "no memory for offset_array !!!\n" );
760 window_array
= malloc( sizeof(double) * smooth_size
);
761 if( window_array
== NULL
) {
762 fprintf( stderr
, "no memory for window_array !!!\n" );
766 for( i
=0; i
<smooth_size
; i
++ ) {
767 offset_array
[i
] = 0.0;
768 window_array
[i
] = hann( (double) i
/ ((double) smooth_size
- 1.0) );
771 jack_buffer_size
= jack_get_buffer_size( client
);
772 // Setup target delay and max_diff for the normal user, who does not play with them...
774 target_delay
= (num_periods
*period_size
/ 2) - jack_buffer_size
/2;
777 max_diff
= target_delay
;
779 if( max_diff
> target_delay
) {
780 fprintf( stderr
, "target_delay (%d) can not be smaller than max_diff(%d)\n", target_delay
, max_diff
);
783 if( (target_delay
+max_diff
) > (num_periods
*period_size
) ) {
784 fprintf( stderr
, "target_delay+max_diff (%d) can not be bigger than buffersize(%d)\n", target_delay
+max_diff
, num_periods
*period_size
);
787 // now open the alsa fd...
788 alsa_handle
= open_audiofd( alsa_device
, 0, sample_rate
, num_channels
, period_size
, num_periods
);
789 if( alsa_handle
== 0 )
792 printf( "selected sample format: %s\n", formats
[format
].name
);
794 // alloc input ports, which are blasted out to alsa...
795 alloc_ports( 0, num_channels
);
797 outbuf
= malloc( num_periods
* period_size
* formats
[format
].sample_size
* num_channels
);
798 resampbuf
= malloc( num_periods
* period_size
* sizeof( float ) );
799 tmpbuf
= malloc( 512 * formats
[format
].sample_size
* num_channels
);
801 if ((outbuf
== NULL
) || (resampbuf
== NULL
) || (tmpbuf
== NULL
))
803 fprintf( stderr
, "no memory for buffers.\n" );
808 /* tell the JACK server that we are ready to roll */
810 if (jack_activate (client
)) {
811 fprintf (stderr
, "cannot activate client");
815 signal( SIGTERM
, sigterm_handler
);
816 signal( SIGINT
, sigterm_handler
);
821 if( output_new_delay
) {
822 printf( "delay = %d\n", output_new_delay
);
823 output_new_delay
= 0;
825 printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor
, output_diff
, output_offset
);
827 } else if( instrument
) {
828 printf( "# n\tresamp\tdiff\toffseti\tintegral\n");
832 printf( "%d\t%f\t%f\t%f\t%f\n", n
++, output_resampling_factor
, output_diff
, output_offset
, output_integral
);
838 if( output_new_delay
) {
839 printf( "delay = %d\n", output_new_delay
);
840 output_new_delay
= 0;
845 jack_deactivate( client
);
846 jack_client_close (client
);