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.
16 #include <jack/jack.h>
17 #include <jack/jslist.h>
20 #include "alsa/asoundlib.h"
22 #include <samplerate.h>
24 // Here are the lists of the jack ports...
26 JSList
*capture_ports
= NULL
;
27 JSList
*capture_srcs
= NULL
;
28 JSList
*playback_ports
= NULL
;
29 JSList
*playback_srcs
= NULL
;
30 jack_client_t
*client
;
32 snd_pcm_t
*alsa_handle
;
38 double resample_mean
= 1.0;
39 double static_resample_factor
= 1.0;
40 double resample_lower_limit
= 0.25;
41 double resample_upper_limit
= 4.0;
45 int offset_differential_index
= 0;
47 double offset_integral
= 0;
49 // ------------------------------------------------------ commandline parameters
51 int sample_rate
= 0; /* stream rate */
52 int num_channels
= 2; /* count of channels */
53 int period_size
= 1024;
56 int target_delay
= 0; /* the delay which the program should try to approach. */
57 int max_diff
= 0; /* the diff value, when a hard readpointer skip should occur */
58 int catch_factor
= 100000;
59 int catch_factor2
= 10000;
61 double controlquant
= 10000.0;
62 int smooth_size
= 256;
66 int samplerate_quality
= 2;
70 volatile float output_resampling_factor
= 1.0;
71 volatile int output_new_delay
= 0;
72 volatile float output_offset
= 0.0;
73 volatile float output_integral
= 0.0;
74 volatile float output_diff
= 0.0;
75 volatile int running_freewheel
= 0;
77 snd_pcm_uframes_t real_buffer_size
;
78 snd_pcm_uframes_t real_period_size
;
86 // format selection, and corresponding functions from memops in a nice set of structs.
88 typedef struct alsa_format
{
89 snd_pcm_format_t format_id
;
91 void (*jack_to_soundcard
) (char *dst
, jack_default_audio_sample_t
*src
, unsigned long nsamples
, unsigned long dst_skip
, dither_state_t
*state
);
92 void (*soundcard_to_jack
) (jack_default_audio_sample_t
*dst
, char *src
, unsigned long nsamples
, unsigned long src_skip
);
96 alsa_format_t formats
[] = {
97 { SND_PCM_FORMAT_FLOAT_LE
, 4, sample_move_dS_floatLE
, sample_move_floatLE_sSs
, "float" },
98 { SND_PCM_FORMAT_S32
, 4, sample_move_d32u24_sS
, sample_move_dS_s32u24
, "32bit" },
99 { SND_PCM_FORMAT_S24_3LE
, 3, sample_move_d24_sS
, sample_move_dS_s24
, "24bit - real" },
100 { SND_PCM_FORMAT_S24
, 4, sample_move_d24_sS
, sample_move_dS_s24
, "24bit" },
101 { SND_PCM_FORMAT_S16
, 2, sample_move_d16_sS
, sample_move_dS_s16
, "16bit" }
103 ,{ SND_PCM_FORMAT_S16_LE
, 2, sample_move_d16_sS
, sample_move_dS_s16
, "16bit little-endian" }
106 #define NUMFORMATS (sizeof(formats)/sizeof(formats[0]))
109 // Alsa stuff... i don't want to touch this bullshit in the next years.... please...
111 static int xrun_recovery(snd_pcm_t
*handle
, int err
) {
112 // printf( "xrun !!!.... %d\n", err );
113 if (err
== -EPIPE
) { /* under-run */
114 err
= snd_pcm_prepare(handle
);
116 printf("Can't recover from underrun, prepare failed: %s\n", snd_strerror(err
));
118 } else if (err
== -ESTRPIPE
) {
119 while ((err
= snd_pcm_resume(handle
)) == -EAGAIN
)
120 usleep(100); /* wait until the suspend flag is released */
122 err
= snd_pcm_prepare(handle
);
124 printf("Can't recover from suspend, prepare failed: %s\n", snd_strerror(err
));
131 static int set_hwformat( snd_pcm_t
*handle
, snd_pcm_hw_params_t
*params
)
135 snd_pcm_hw_params_set_format(handle
, params
, formats
[format
].format_id
);
141 for( i
=0; i
<NUMFORMATS
; i
++ ) {
142 /* set the sample format */
143 err
= snd_pcm_hw_params_set_format(handle
, params
, formats
[i
].format_id
);
154 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
) {
156 unsigned int buffer_time
;
157 unsigned int period_time
;
159 unsigned int rchannels
;
161 /* choose all parameters */
162 err
= snd_pcm_hw_params_any(handle
, params
);
164 printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err
));
167 /* set the interleaved read/write format */
168 err
= snd_pcm_hw_params_set_access(handle
, params
, access
);
170 printf("Access type not available for playback: %s\n", snd_strerror(err
));
174 /* set the sample format */
175 err
= set_hwformat(handle
, params
);
177 printf("Sample format not available for playback: %s\n", snd_strerror(err
));
180 /* set the count of channels */
181 rchannels
= channels
;
182 err
= snd_pcm_hw_params_set_channels_near(handle
, params
, &rchannels
);
184 printf("Channels count (%i) not available for record: %s\n", channels
, snd_strerror(err
));
187 if (rchannels
!= channels
) {
188 printf("WARNING: channel count does not match (requested %d got %d)\n", channels
, rchannels
);
189 num_channels
= rchannels
;
191 /* set the stream rate */
193 err
= snd_pcm_hw_params_set_rate_near(handle
, params
, &rrate
, 0);
195 printf("Rate %iHz not available for playback: %s\n", rate
, snd_strerror(err
));
199 printf("WARNING: Rate doesn't match (requested %iHz, get %iHz)\n", rate
, rrate
);
202 /* set the buffer time */
204 buffer_time
= 1000000*(uint64_t)period
*nperiods
/rate
;
205 err
= snd_pcm_hw_params_set_buffer_time_near(handle
, params
, &buffer_time
, &dir
);
207 printf("Unable to set buffer time %i for playback: %s\n", 1000000*period
*nperiods
/rate
, snd_strerror(err
));
210 err
= snd_pcm_hw_params_get_buffer_size( params
, &real_buffer_size
);
212 printf("Unable to get buffer size back: %s\n", snd_strerror(err
));
215 if( real_buffer_size
!= nperiods
* period
) {
216 printf( "WARNING: buffer size does not match: (requested %d, got %d)\n", nperiods
* period
, (int) real_buffer_size
);
218 /* set the period time */
219 period_time
= 1000000*(uint64_t)period
/rate
;
220 err
= snd_pcm_hw_params_set_period_time_near(handle
, params
, &period_time
, &dir
);
222 printf("Unable to set period time %i for playback: %s\n", 1000000*period
/rate
, snd_strerror(err
));
225 err
= snd_pcm_hw_params_get_period_size(params
, &real_period_size
, NULL
);
227 printf("Unable to get period size back: %s\n", snd_strerror(err
));
230 if( real_period_size
!= period
) {
231 printf( "WARNING: period size does not match: (requested %i, got %i)\n", period
, (int)real_period_size
);
233 /* write the parameters to device */
234 err
= snd_pcm_hw_params(handle
, params
);
236 printf("Unable to set hw params for playback: %s\n", snd_strerror(err
));
242 static int set_swparams(snd_pcm_t
*handle
, snd_pcm_sw_params_t
*swparams
, int period
) {
245 /* get the current swparams */
246 err
= snd_pcm_sw_params_current(handle
, swparams
);
248 printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err
));
251 /* start the transfer when the buffer is full */
252 err
= snd_pcm_sw_params_set_start_threshold(handle
, swparams
, period
);
254 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err
));
257 err
= snd_pcm_sw_params_set_stop_threshold(handle
, swparams
, -1 );
259 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err
));
262 /* allow the transfer when at least period_size samples can be processed */
263 err
= snd_pcm_sw_params_set_avail_min(handle
, swparams
, 2*period
);
265 printf("Unable to set avail min for capture: %s\n", snd_strerror(err
));
268 /* align all transfers to 1 sample */
269 err
= snd_pcm_sw_params_set_xfer_align(handle
, swparams
, 1);
271 printf("Unable to set transfer align for capture: %s\n", snd_strerror(err
));
274 /* write the parameters to the playback device */
275 err
= snd_pcm_sw_params(handle
, swparams
);
277 printf("Unable to set sw params for capture: %s\n", snd_strerror(err
));
283 // ok... i only need this function to communicate with the alsa bloat api...
285 static snd_pcm_t
*open_audiofd( char *device_name
, int capture
, int rate
, int channels
, int period
, int nperiods
) {
288 snd_pcm_hw_params_t
*hwparams
;
289 snd_pcm_sw_params_t
*swparams
;
291 snd_pcm_hw_params_alloca(&hwparams
);
292 snd_pcm_sw_params_alloca(&swparams
);
294 if ((err
= snd_pcm_open(&(handle
), device_name
, capture
? SND_PCM_STREAM_CAPTURE
: SND_PCM_STREAM_PLAYBACK
, SND_PCM_NONBLOCK
)) < 0) {
295 printf("Capture open error: %s\n", snd_strerror(err
));
299 if ((err
= set_hwparams(handle
, hwparams
,SND_PCM_ACCESS_RW_INTERLEAVED
, rate
, channels
, period
, nperiods
)) < 0) {
300 printf("Setting of hwparams failed: %s\n", snd_strerror(err
));
303 if ((err
= set_swparams(handle
, swparams
, period
)) < 0) {
304 printf("Setting of swparams failed: %s\n", snd_strerror(err
));
308 snd_pcm_start( handle
);
309 snd_pcm_wait( handle
, 200 );
314 double hann( double x
)
316 return 0.5 * (1.0 - cos( 2*M_PI
* x
) );
320 * The freewheel callback.
322 void freewheel (int starting
, void* arg
) {
323 running_freewheel
= starting
;
327 * The process callback for this JACK application.
328 * It is called by JACK at the appropriate times.
330 int process (jack_nframes_t nframes
, void *arg
) {
332 if (running_freewheel
) {
333 JSList
*node
= capture_ports
;
335 while ( node
!= NULL
)
337 jack_port_t
*port
= (jack_port_t
*) node
->data
;
338 float *buf
= jack_port_get_buffer (port
, nframes
);
340 memset(buf
, 0, sizeof(float)*nframes
);
342 node
= jack_slist_next (node
);
350 snd_pcm_sframes_t delay
= target_delay
;
351 int put_back_samples
=0;
354 delay
= snd_pcm_avail( alsa_handle
);
356 delay
-= round( jack_frames_since_cycle_start( client
) / static_resample_factor
);
357 // Do it the hard way.
358 // this is for compensating xruns etc...
360 if( delay
> (target_delay
+max_diff
) ) {
362 output_new_delay
= (int) delay
;
364 while ((delay
-target_delay
) > 0) {
365 snd_pcm_uframes_t to_read
= ((delay
-target_delay
) > 512) ? 512 : (delay
-target_delay
);
366 snd_pcm_readi( alsa_handle
, tmpbuf
, to_read
);
370 delay
= target_delay
;
372 // Set the resample_rate... we need to adjust the offset integral, to do this.
373 // first look at the PI controller, this code is just a special case, which should never execute once
374 // everything is swung in.
375 offset_integral
= - (resample_mean
- static_resample_factor
) * catch_factor
* catch_factor2
;
376 // Also clear the array. we are beginning a new control cycle.
377 for( i
=0; i
<smooth_size
; i
++ )
378 offset_array
[i
] = 0.0;
380 if( delay
< (target_delay
-max_diff
) ) {
381 snd_pcm_rewind( alsa_handle
, target_delay
- delay
);
382 output_new_delay
= (int) delay
;
383 delay
= target_delay
;
385 // Set the resample_rate... we need to adjust the offset integral, to do this.
386 offset_integral
= - (resample_mean
- static_resample_factor
) * catch_factor
* catch_factor2
;
387 // Also clear the array. we are beginning a new control cycle.
388 for( i
=0; i
<smooth_size
; i
++ )
389 offset_array
[i
] = 0.0;
391 /* ok... now we should have target_delay +- max_diff on the alsa side.
393 * calculate the number of frames, we want to get.
396 double offset
= delay
- target_delay
;
399 offset_array
[(offset_differential_index
++)% smooth_size
] = offset
;
401 // Build the mean of the windowed offset array
402 // basically fir lowpassing.
403 double smooth_offset
= 0.0;
404 for( i
=0; i
<smooth_size
; i
++ )
406 offset_array
[ (i
+ offset_differential_index
-1) % smooth_size
] * window_array
[i
];
407 smooth_offset
/= (double) smooth_size
;
409 // this is the integral of the smoothed_offset
410 offset_integral
+= smooth_offset
;
413 // the smooth offset still contains unwanted noise
414 // which would go straight onto the resample coeff.
415 // it only used in the P component and the I component is used for the fine tuning anyways.
416 if( fabs( smooth_offset
) < pclamp
)
419 // ok. now this is the PI controller.
420 // u(t) = K * ( e(t) + 1/T \int e(t') dt' )
421 // K = 1/catch_factor and T = catch_factor2
422 double current_resample_factor
= static_resample_factor
- smooth_offset
/ (double) catch_factor
- offset_integral
/ (double) catch_factor
/ (double)catch_factor2
;
424 // now quantize this value around resample_mean, so that the noise which is in the integral component doesn't hurt.
425 current_resample_factor
= floor( (current_resample_factor
- resample_mean
) * controlquant
+ 0.5 ) / controlquant
+ resample_mean
;
427 // Output "instrumentatio" gonna change that to real instrumentation in a few.
428 output_resampling_factor
= (float) current_resample_factor
;
429 output_diff
= (float) smooth_offset
;
430 output_integral
= (float) offset_integral
;
431 output_offset
= (float) offset
;
434 if( current_resample_factor
< resample_lower_limit
) current_resample_factor
= resample_lower_limit
;
435 if( current_resample_factor
> resample_upper_limit
) current_resample_factor
= resample_upper_limit
;
437 // Now Calculate how many samples we need.
438 rlen
= ceil( ((double)nframes
) / current_resample_factor
)+2;
441 // Calculate resample_mean so we can init ourselves to saner values.
442 resample_mean
= 0.9999 * resample_mean
+ 0.0001 * current_resample_factor
;
446 err
= snd_pcm_readi(alsa_handle
, outbuf
, rlen
);
448 printf( "err = %d\n", err
);
449 if (xrun_recovery(alsa_handle
, err
) < 0) {
450 //printf("Write error: %s\n", snd_strerror(err));
451 //exit(EXIT_FAILURE);
456 //printf( "read = %d\n", rlen );
460 * render jack ports to the outbuf...
464 JSList
*node
= capture_ports
;
465 JSList
*src_node
= capture_srcs
;
468 while ( node
!= NULL
)
470 jack_port_t
*port
= (jack_port_t
*) node
->data
;
471 float *buf
= jack_port_get_buffer (port
, nframes
);
473 SRC_STATE
*src_state
= src_node
->data
;
475 formats
[format
].soundcard_to_jack( resampbuf
, outbuf
+ format
[formats
].sample_size
* chn
, rlen
, num_channels
*format
[formats
].sample_size
);
477 src
.data_in
= resampbuf
;
478 src
.input_frames
= rlen
;
481 src
.output_frames
= nframes
;
482 src
.end_of_input
= 0;
484 src
.src_ratio
= current_resample_factor
;
486 src_process( src_state
, &src
);
488 put_back_samples
= rlen
-src
.input_frames_used
;
490 src_node
= jack_slist_next (src_node
);
491 node
= jack_slist_next (node
);
495 // Put back the samples libsamplerate did not consume.
496 //printf( "putback = %d\n", put_back_samples );
497 snd_pcm_rewind( alsa_handle
, put_back_samples
);
503 * the latency callback.
504 * sets up the latencies on the ports.
508 latency_cb (jack_latency_callback_mode_t mode
, void *arg
)
510 jack_latency_range_t range
;
513 range
.min
= range
.max
= round(target_delay
* static_resample_factor
);
515 if (mode
== JackCaptureLatency
) {
516 for (node
= capture_ports
; node
; node
= jack_slist_next (node
)) {
517 jack_port_t
*port
= node
->data
;
518 jack_port_set_latency_range (port
, mode
, &range
);
521 for (node
= playback_ports
; node
; node
= jack_slist_next (node
)) {
522 jack_port_t
*port
= node
->data
;
523 jack_port_set_latency_range (port
, mode
, &range
);
530 * Allocate the necessary jack ports...
533 void alloc_ports( int n_capture
, int n_playback
) {
535 int port_flags
= JackPortIsOutput
;
540 capture_ports
= NULL
;
541 for (chn
= 0; chn
< n_capture
; chn
++)
543 snprintf (buf
, sizeof(buf
) - 1, "capture_%u", chn
+1);
545 port
= jack_port_register (client
, buf
,
546 JACK_DEFAULT_AUDIO_TYPE
,
551 printf( "jacknet_client: cannot register port for %s", buf
);
555 capture_srcs
= jack_slist_append( capture_srcs
, src_new( 4-samplerate_quality
, 1, NULL
) );
556 capture_ports
= jack_slist_append (capture_ports
, port
);
559 port_flags
= JackPortIsInput
;
561 playback_ports
= NULL
;
562 for (chn
= 0; chn
< n_playback
; chn
++)
564 snprintf (buf
, sizeof(buf
) - 1, "playback_%u", chn
+1);
566 port
= jack_port_register (client
, buf
,
567 JACK_DEFAULT_AUDIO_TYPE
,
572 printf( "jacknet_client: cannot register port for %s", buf
);
576 playback_srcs
= jack_slist_append( playback_srcs
, src_new( 4-samplerate_quality
, 1, NULL
) );
577 playback_ports
= jack_slist_append (playback_ports
, port
);
582 * This is the shutdown callback for this JACK application.
583 * It is called by JACK if the server ever shuts down or
584 * decides to disconnect the client.
587 void jack_shutdown (void *arg
) {
599 fprintf(stderr
, "usage: alsa_out [options]\n"
601 " -j <jack name> - client name\n"
602 " -S <server name> - server to connect\n"
603 " -d <alsa_device> \n"
605 " -p <period_size> \n"
606 " -n <num_period> \n"
607 " -r <sample_rate> \n"
608 " -q <sample_rate quality [0..4]\n"
610 " -t <target_delay> \n"
611 " -i turns on instrumentation\n"
612 " -v turns on printouts\n"
618 * the main function....
622 sigterm_handler( int signal
)
628 int main (int argc
, char *argv
[]) {
629 char jack_name
[30] = "alsa_in";
630 char alsa_device
[30] = "hw:0";
631 char *server_name
= NULL
;
635 extern int optind
, optopt
;
639 while ((c
= getopt(argc
, argv
, "ivj:r:c:p:n:d:q:m:t:f:F:C:Q:s:S:")) != -1) {
642 strcpy(jack_name
,optarg
);
645 sample_rate
= atoi(optarg
);
648 num_channels
= atoi(optarg
);
651 period_size
= atoi(optarg
);
654 num_periods
= atoi(optarg
);
657 strcpy(alsa_device
,optarg
);
660 target_delay
= atoi(optarg
);
663 samplerate_quality
= atoi(optarg
);
666 max_diff
= atoi(optarg
);
669 catch_factor
= atoi(optarg
);
672 catch_factor2
= atoi(optarg
);
675 pclamp
= (double) atoi(optarg
);
678 controlquant
= (double) atoi(optarg
);
687 smooth_size
= atoi(optarg
);
690 server_name
= optarg
;
691 jack_opts
|= JackServerName
;
695 "Option -%c requires an operand\n", optopt
);
700 "Unrecognized option: -%c\n", optopt
);
709 if( (samplerate_quality
< 0) || (samplerate_quality
> 4) ) {
710 fprintf (stderr
, "invalid samplerate quality\n");
713 if ((client
= jack_client_open (jack_name
, jack_opts
, NULL
, server_name
)) == 0) {
714 fprintf (stderr
, "jack server not running?\n");
718 /* tell the JACK server to call `process()' whenever
719 there is work to be done.
722 jack_set_process_callback (client
, process
, 0);
724 /* tell the JACK server to call `freewheel()' whenever
725 freewheel mode changes.
728 jack_set_freewheel_callback (client
, freewheel
, 0);
730 /* tell the JACK server to call `jack_shutdown()' if
731 it ever shuts down, either entirely, or if it
732 just decides to stop calling us.
735 jack_on_shutdown (client
, jack_shutdown
, 0);
737 if (jack_set_latency_callback
)
738 jack_set_latency_callback (client
, latency_cb
, 0);
740 // get jack sample_rate
742 jack_sample_rate
= jack_get_sample_rate( client
);
745 sample_rate
= jack_sample_rate
;
747 // now open the alsa fd...
748 alsa_handle
= open_audiofd( alsa_device
, 1, sample_rate
, num_channels
, period_size
, num_periods
);
749 if( alsa_handle
== 0 )
752 printf( "selected sample format: %s\n", formats
[format
].name
);
754 static_resample_factor
= (double) jack_sample_rate
/ (double) sample_rate
;
755 resample_lower_limit
= static_resample_factor
* 0.25;
756 resample_upper_limit
= static_resample_factor
* 4.0;
757 resample_mean
= static_resample_factor
;
759 offset_array
= malloc( sizeof(double) * smooth_size
);
760 if( offset_array
== NULL
) {
761 fprintf( stderr
, "no memory for offset_array !!!\n" );
764 window_array
= malloc( sizeof(double) * smooth_size
);
765 if( window_array
== NULL
) {
766 fprintf( stderr
, "no memory for window_array !!!\n" );
770 for( i
=0; i
<smooth_size
; i
++ ) {
771 offset_array
[i
] = 0.0;
772 window_array
[i
] = hann( (double) i
/ ((double) smooth_size
- 1.0) );
775 jack_buffer_size
= jack_get_buffer_size( client
);
776 // Setup target delay and max_diff for the normal user, who does not play with them...
778 target_delay
= (num_periods
*period_size
/ 2) + jack_buffer_size
/2;
781 max_diff
= num_periods
*period_size
- target_delay
;
783 if( max_diff
> target_delay
) {
784 fprintf( stderr
, "target_delay (%d) can not be smaller than max_diff(%d)\n", target_delay
, max_diff
);
787 if( (target_delay
+max_diff
) > (num_periods
*period_size
) ) {
788 fprintf( stderr
, "target_delay+max_diff (%d) can not be bigger than buffersize(%d)\n", target_delay
+max_diff
, num_periods
*period_size
);
791 // alloc input ports, which are blasted out to alsa...
792 alloc_ports( num_channels
, 0 );
794 outbuf
= malloc( num_periods
* period_size
* formats
[format
].sample_size
* num_channels
);
795 resampbuf
= malloc( num_periods
* period_size
* sizeof( float ) );
796 tmpbuf
= malloc( 512 * formats
[format
].sample_size
* num_channels
);
798 if ((outbuf
== NULL
) || (resampbuf
== NULL
) || (tmpbuf
== NULL
))
800 fprintf( stderr
, "no memory for buffers.\n" );
804 memset( tmpbuf
, 0, 512 * formats
[format
].sample_size
* num_channels
);
806 /* tell the JACK server that we are ready to roll */
808 if (jack_activate (client
)) {
809 fprintf (stderr
, "cannot activate client");
813 signal( SIGTERM
, sigterm_handler
);
814 signal( SIGINT
, sigterm_handler
);
819 if( output_new_delay
) {
820 printf( "delay = %d\n", output_new_delay
);
821 output_new_delay
= 0;
823 printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor
, output_diff
, output_offset
);
825 } else if( instrument
) {
826 printf( "# n\tresamp\tdiff\toffseti\tintegral\n");
830 printf( "%d\t%f\t%f\t%f\t%f\n", n
++, output_resampling_factor
, output_diff
, output_offset
, output_integral
);
836 if( output_new_delay
) {
837 printf( "delay = %d\n", output_new_delay
);
838 output_new_delay
= 0;
843 jack_deactivate( client
);
844 jack_client_close (client
);