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;
77 snd_pcm_uframes_t real_buffer_size
;
78 snd_pcm_uframes_t real_period_size
;
80 // format selection, and corresponding functions from memops in a nice set of structs.
82 typedef struct alsa_format
{
83 snd_pcm_format_t format_id
;
85 void (*jack_to_soundcard
) (char *dst
, jack_default_audio_sample_t
*src
, unsigned long nsamples
, unsigned long dst_skip
, dither_state_t
*state
);
86 void (*soundcard_to_jack
) (jack_default_audio_sample_t
*dst
, char *src
, unsigned long nsamples
, unsigned long src_skip
);
90 alsa_format_t formats
[] = {
91 { SND_PCM_FORMAT_FLOAT_LE
, 4, sample_move_dS_floatLE
, sample_move_floatLE_sSs
, "float" },
92 { SND_PCM_FORMAT_S32
, 4, sample_move_d32u24_sS
, sample_move_dS_s32u24
, "32bit" },
93 { SND_PCM_FORMAT_S24_3LE
, 3, sample_move_d24_sS
, sample_move_dS_s24
, "24bit - real" },
94 { SND_PCM_FORMAT_S24
, 4, sample_move_d24_sS
, sample_move_dS_s24
, "24bit" },
95 { SND_PCM_FORMAT_S16
, 2, sample_move_d16_sS
, sample_move_dS_s16
, "16bit" }
97 #define NUMFORMATS (sizeof(formats)/sizeof(formats[0]))
100 // Alsa stuff... i dont want to touch this bullshit in the next years.... please...
102 static int xrun_recovery(snd_pcm_t
*handle
, int err
) {
103 // printf( "xrun !!!.... %d\n", err );
104 if (err
== -EPIPE
) { /* under-run */
105 err
= snd_pcm_prepare(handle
);
107 printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err
));
109 } else if (err
== -EAGAIN
) {
110 while ((err
= snd_pcm_resume(handle
)) == -EAGAIN
)
111 usleep(100); /* wait until the suspend flag is released */
113 err
= snd_pcm_prepare(handle
);
115 printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err
));
122 static int set_hwformat( snd_pcm_t
*handle
, snd_pcm_hw_params_t
*params
)
127 for( i
=0; i
<NUMFORMATS
; i
++ ) {
128 /* set the sample format */
129 err
= snd_pcm_hw_params_set_format(handle
, params
, formats
[i
].format_id
);
139 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
) {
141 unsigned int buffer_time
;
142 unsigned int period_time
;
144 unsigned int rchannels
;
146 /* choose all parameters */
147 err
= snd_pcm_hw_params_any(handle
, params
);
149 printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err
));
152 /* set the interleaved read/write format */
153 err
= snd_pcm_hw_params_set_access(handle
, params
, access
);
155 printf("Access type not available for playback: %s\n", snd_strerror(err
));
159 /* set the sample format */
160 err
= set_hwformat(handle
, params
);
162 printf("Sample format not available for playback: %s\n", snd_strerror(err
));
165 /* set the count of channels */
166 rchannels
= channels
;
167 err
= snd_pcm_hw_params_set_channels_near(handle
, params
, &rchannels
);
169 printf("Channels count (%i) not available for record: %s\n", channels
, snd_strerror(err
));
172 if (rchannels
!= channels
) {
173 printf("WARNING: chennel count does not match (requested %d got %d)\n", channels
, rchannels
);
174 num_channels
= rchannels
;
176 /* set the stream rate */
178 err
= snd_pcm_hw_params_set_rate_near(handle
, params
, &rrate
, 0);
180 printf("Rate %iHz not available for playback: %s\n", rate
, snd_strerror(err
));
184 printf("WARNING: Rate doesn't match (requested %iHz, get %iHz)\n", rate
, rrate
);
187 /* set the buffer time */
189 buffer_time
= 1000000*(uint64_t)period
*nperiods
/rate
;
190 err
= snd_pcm_hw_params_set_buffer_time_near(handle
, params
, &buffer_time
, &dir
);
192 printf("Unable to set buffer time %i for playback: %s\n", 1000000*period
*nperiods
/rate
, snd_strerror(err
));
195 err
= snd_pcm_hw_params_get_buffer_size( params
, &real_buffer_size
);
197 printf("Unable to get buffer size back: %s\n", snd_strerror(err
));
200 if( real_buffer_size
!= nperiods
* period
) {
201 printf( "WARNING: buffer size does not match: (requested %d, got %d)\n", nperiods
* period
, (int) real_buffer_size
);
203 /* set the period time */
204 period_time
= 1000000*(uint64_t)period
/rate
;
205 err
= snd_pcm_hw_params_set_period_time_near(handle
, params
, &period_time
, &dir
);
207 printf("Unable to set period time %i for playback: %s\n", 1000000*period
/rate
, snd_strerror(err
));
210 err
= snd_pcm_hw_params_get_period_size(params
, &real_period_size
, NULL
);
212 printf("Unable to get period size back: %s\n", snd_strerror(err
));
215 if( real_period_size
!= period
) {
216 printf( "WARNING: period size does not match: (requested %i, got %i)\n", period
, (int)real_period_size
);
218 /* write the parameters to device */
219 err
= snd_pcm_hw_params(handle
, params
);
221 printf("Unable to set hw params for playback: %s\n", snd_strerror(err
));
227 static int set_swparams(snd_pcm_t
*handle
, snd_pcm_sw_params_t
*swparams
, int period
) {
230 /* get the current swparams */
231 err
= snd_pcm_sw_params_current(handle
, swparams
);
233 printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err
));
236 /* start the transfer when the buffer is full */
237 err
= snd_pcm_sw_params_set_start_threshold(handle
, swparams
, period
);
239 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err
));
242 err
= snd_pcm_sw_params_set_stop_threshold(handle
, swparams
, -1 );
244 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err
));
247 /* allow the transfer when at least period_size samples can be processed */
248 err
= snd_pcm_sw_params_set_avail_min(handle
, swparams
, 2*period
);
250 printf("Unable to set avail min for capture: %s\n", snd_strerror(err
));
253 /* align all transfers to 1 sample */
254 err
= snd_pcm_sw_params_set_xfer_align(handle
, swparams
, 1);
256 printf("Unable to set transfer align for capture: %s\n", snd_strerror(err
));
259 /* write the parameters to the playback device */
260 err
= snd_pcm_sw_params(handle
, swparams
);
262 printf("Unable to set sw params for capture: %s\n", snd_strerror(err
));
268 // ok... i only need this function to communicate with the alsa bloat api...
270 static snd_pcm_t
*open_audiofd( char *device_name
, int capture
, int rate
, int channels
, int period
, int nperiods
) {
273 snd_pcm_hw_params_t
*hwparams
;
274 snd_pcm_sw_params_t
*swparams
;
276 snd_pcm_hw_params_alloca(&hwparams
);
277 snd_pcm_sw_params_alloca(&swparams
);
279 if ((err
= snd_pcm_open(&(handle
), device_name
, capture
? SND_PCM_STREAM_CAPTURE
: SND_PCM_STREAM_PLAYBACK
, SND_PCM_NONBLOCK
)) < 0) {
280 printf("Capture open error: %s\n", snd_strerror(err
));
284 if ((err
= set_hwparams(handle
, hwparams
,SND_PCM_ACCESS_RW_INTERLEAVED
, rate
, channels
, period
, nperiods
)) < 0) {
285 printf("Setting of hwparams failed: %s\n", snd_strerror(err
));
288 if ((err
= set_swparams(handle
, swparams
, period
)) < 0) {
289 printf("Setting of swparams failed: %s\n", snd_strerror(err
));
293 snd_pcm_start( handle
);
294 snd_pcm_wait( handle
, 200 );
299 double hann( double x
)
301 return 0.5 * (1.0 - cos( 2*M_PI
* x
) );
305 * The process callback for this JACK application.
306 * It is called by JACK at the appropriate times.
308 int process (jack_nframes_t nframes
, void *arg
) {
314 snd_pcm_sframes_t delay
= target_delay
;
315 int put_back_samples
=0;
318 delay
= snd_pcm_avail( alsa_handle
);
320 delay
-= jack_frames_since_cycle_start( client
);
321 // Do it the hard way.
322 // this is for compensating xruns etc...
324 if( delay
> (target_delay
+max_diff
) ) {
325 char *tmp
= alloca( (delay
-target_delay
) * formats
[format
].sample_size
* num_channels
);
326 snd_pcm_readi( alsa_handle
, tmp
, 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 snd_pcm_rewind( alsa_handle
, target_delay
- delay
);
341 output_new_delay
= (int) delay
;
342 delay
= target_delay
;
344 // Set the resample_rate... we need to adjust the offset integral, to do this.
345 offset_integral
= - (resample_mean
- static_resample_factor
) * catch_factor
* catch_factor2
;
346 // Also clear the array. we are beginning a new control cycle.
347 for( i
=0; i
<smooth_size
; i
++ )
348 offset_array
[i
] = 0.0;
350 /* ok... now we should have target_delay +- max_diff on the alsa side.
352 * calculate the number of frames, we want to get.
355 double offset
= delay
- target_delay
;
358 offset_array
[(offset_differential_index
++)% smooth_size
] = offset
;
360 // Build the mean of the windowed offset array
361 // basically fir lowpassing.
362 double smooth_offset
= 0.0;
363 for( i
=0; i
<smooth_size
; i
++ )
365 offset_array
[ (i
+ offset_differential_index
-1) % smooth_size
] * window_array
[i
];
366 smooth_offset
/= (double) smooth_size
;
368 // this is the integral of the smoothed_offset
369 offset_integral
+= smooth_offset
;
372 // the smooth offset still contains unwanted noise
373 // which would go straigth onto the resample coeff.
374 // it only used in the P component and the I component is used for the fine tuning anyways.
375 if( fabs( smooth_offset
) < pclamp
)
378 // ok. now this is the PI controller.
379 // u(t) = K * ( e(t) + 1/T \int e(t') dt' )
380 // K = 1/catch_factor and T = catch_factor2
381 double current_resample_factor
= static_resample_factor
- smooth_offset
/ (double) catch_factor
- offset_integral
/ (double) catch_factor
/ (double)catch_factor2
;
383 // now quantize this value around resample_mean, so that the noise which is in the integral component doesnt hurt.
384 current_resample_factor
= floor( (current_resample_factor
- resample_mean
) * controlquant
+ 0.5 ) / controlquant
+ resample_mean
;
386 // Output "instrumentatio" gonna change that to real instrumentation in a few.
387 output_resampling_factor
= (float) current_resample_factor
;
388 output_diff
= (float) smooth_offset
;
389 output_integral
= (float) offset_integral
;
390 output_offset
= (float) offset
;
393 if( current_resample_factor
< resample_lower_limit
) current_resample_factor
= resample_lower_limit
;
394 if( current_resample_factor
> resample_upper_limit
) current_resample_factor
= resample_upper_limit
;
396 // Now Calculate how many samples we need.
397 rlen
= ceil( ((double)nframes
) / current_resample_factor
)+2;
400 // Calculate resample_mean so we can init ourselves to saner values.
401 resample_mean
= 0.9999 * resample_mean
+ 0.0001 * current_resample_factor
;
403 * now this should do it...
406 outbuf
= alloca( rlen
* formats
[format
].sample_size
* num_channels
);
408 resampbuf
= alloca( rlen
* sizeof( float ) );
412 err
= snd_pcm_readi(alsa_handle
, outbuf
, rlen
);
414 printf( "err = %d\n", err
);
415 if (xrun_recovery(alsa_handle
, err
) < 0) {
416 //printf("Write error: %s\n", snd_strerror(err));
417 //exit(EXIT_FAILURE);
422 //printf( "read = %d\n", rlen );
426 * render jack ports to the outbuf...
430 JSList
*node
= capture_ports
;
431 JSList
*src_node
= capture_srcs
;
434 while ( node
!= NULL
)
436 jack_port_t
*port
= (jack_port_t
*) node
->data
;
437 float *buf
= jack_port_get_buffer (port
, nframes
);
439 SRC_STATE
*src_state
= src_node
->data
;
441 formats
[format
].soundcard_to_jack( resampbuf
, outbuf
+ format
[formats
].sample_size
* chn
, rlen
, num_channels
*format
[formats
].sample_size
);
443 src
.data_in
= resampbuf
;
444 src
.input_frames
= rlen
;
447 src
.output_frames
= nframes
;
448 src
.end_of_input
= 0;
450 src
.src_ratio
= current_resample_factor
;
452 src_process( src_state
, &src
);
454 put_back_samples
= rlen
-src
.input_frames_used
;
456 src_node
= jack_slist_next (src_node
);
457 node
= jack_slist_next (node
);
461 // Put back the samples libsamplerate did not consume.
462 //printf( "putback = %d\n", put_back_samples );
463 snd_pcm_rewind( alsa_handle
, put_back_samples
);
470 * Allocate the necessary jack ports...
473 void alloc_ports( int n_capture
, int n_playback
) {
475 int port_flags
= JackPortIsOutput
;
480 capture_ports
= NULL
;
481 for (chn
= 0; chn
< n_capture
; chn
++)
483 snprintf (buf
, sizeof(buf
) - 1, "capture_%u", chn
+1);
485 port
= jack_port_register (client
, buf
,
486 JACK_DEFAULT_AUDIO_TYPE
,
491 printf( "jacknet_client: cannot register port for %s", buf
);
495 capture_srcs
= jack_slist_append( capture_srcs
, src_new( 4-samplerate_quality
, 1, NULL
) );
496 capture_ports
= jack_slist_append (capture_ports
, port
);
499 port_flags
= JackPortIsInput
;
501 playback_ports
= NULL
;
502 for (chn
= 0; chn
< n_playback
; chn
++)
504 snprintf (buf
, sizeof(buf
) - 1, "playback_%u", chn
+1);
506 port
= jack_port_register (client
, buf
,
507 JACK_DEFAULT_AUDIO_TYPE
,
512 printf( "jacknet_client: cannot register port for %s", buf
);
516 playback_srcs
= jack_slist_append( playback_srcs
, src_new( 4-samplerate_quality
, 1, NULL
) );
517 playback_ports
= jack_slist_append (playback_ports
, port
);
522 * This is the shutdown callback for this JACK application.
523 * It is called by JACK if the server ever shuts down or
524 * decides to disconnect the client.
527 void jack_shutdown (void *arg
) {
539 fprintf(stderr
, "usage: alsa_out [options]\n"
541 " -j <jack name> - client name\n"
542 " -d <alsa_device> \n"
544 " -p <period_size> \n"
545 " -n <num_period> \n"
546 " -r <sample_rate> \n"
547 " -q <sample_rate quality [0..4]\n"
549 " -t <target_delay> \n"
550 " -i turns on instrumentation\n"
551 " -v turns on printouts\n"
557 * the main function....
561 sigterm_handler( int signal
)
567 int main (int argc
, char *argv
[]) {
568 char jack_name
[30] = "alsa_in";
569 char alsa_device
[30] = "hw:0";
572 extern int optind
, optopt
;
576 while ((c
= getopt(argc
, argv
, "ivj:r:c:p:n:d:q:m:t:f:F:C:Q:s:")) != -1) {
579 strcpy(jack_name
,optarg
);
582 sample_rate
= atoi(optarg
);
585 num_channels
= atoi(optarg
);
588 period_size
= atoi(optarg
);
591 num_periods
= atoi(optarg
);
594 strcpy(alsa_device
,optarg
);
597 target_delay
= atoi(optarg
);
600 samplerate_quality
= atoi(optarg
);
603 max_diff
= atoi(optarg
);
606 catch_factor
= atoi(optarg
);
609 catch_factor2
= atoi(optarg
);
612 pclamp
= (double) atoi(optarg
);
615 controlquant
= (double) atoi(optarg
);
624 smooth_size
= atoi(optarg
);
628 "Option -%c requires an operand\n", optopt
);
633 "Unrecognized option: -%c\n", optopt
);
642 if( (samplerate_quality
< 0) || (samplerate_quality
> 4) ) {
643 fprintf (stderr
, "invalid samplerate quality\n");
646 if ((client
= jack_client_open (jack_name
, 0, NULL
)) == 0) {
647 fprintf (stderr
, "jack server not running?\n");
651 /* tell the JACK server to call `process()' whenever
652 there is work to be done.
655 jack_set_process_callback (client
, process
, 0);
657 /* tell the JACK server to call `jack_shutdown()' if
658 it ever shuts down, either entirely, or if it
659 just decides to stop calling us.
662 jack_on_shutdown (client
, jack_shutdown
, 0);
665 // get jack sample_rate
667 jack_sample_rate
= jack_get_sample_rate( client
);
670 sample_rate
= jack_sample_rate
;
672 // now open the alsa fd...
673 alsa_handle
= open_audiofd( alsa_device
, 1, sample_rate
, num_channels
, period_size
, num_periods
);
674 if( alsa_handle
== 0 )
677 printf( "selected sample format: %s\n", formats
[format
].name
);
679 static_resample_factor
= (double) jack_sample_rate
/ (double) sample_rate
;
680 resample_lower_limit
= static_resample_factor
* 0.25;
681 resample_upper_limit
= static_resample_factor
* 4.0;
682 resample_mean
= static_resample_factor
;
684 offset_array
= malloc( sizeof(double) * smooth_size
);
685 if( offset_array
== NULL
) {
686 fprintf( stderr
, "no memory for offset_array !!!\n" );
689 window_array
= malloc( sizeof(double) * smooth_size
);
690 if( window_array
== NULL
) {
691 fprintf( stderr
, "no memory for window_array !!!\n" );
695 for( i
=0; i
<smooth_size
; i
++ ) {
696 offset_array
[i
] = 0.0;
697 window_array
[i
] = hann( (double) i
/ ((double) smooth_size
- 1.0) );
700 jack_buffer_size
= jack_get_buffer_size( client
);
701 // Setup target delay and max_diff for the normal user, who does not play with them...
703 target_delay
= (num_periods
*period_size
/ 2) + jack_buffer_size
/2;
706 max_diff
= num_periods
*period_size
- target_delay
;
708 if( max_diff
> target_delay
) {
709 fprintf( stderr
, "target_delay (%d) cant be smaller than max_diff(%d)\n", target_delay
, max_diff
);
712 if( (target_delay
+max_diff
) > (num_periods
*period_size
) ) {
713 fprintf( stderr
, "target_delay+max_diff (%d) cant be bigger than buffersize(%d)\n", target_delay
+max_diff
, num_periods
*period_size
);
716 // alloc input ports, which are blasted out to alsa...
717 alloc_ports( num_channels
, 0 );
720 /* tell the JACK server that we are ready to roll */
722 if (jack_activate (client
)) {
723 fprintf (stderr
, "cannot activate client");
727 signal( SIGTERM
, sigterm_handler
);
728 signal( SIGINT
, sigterm_handler
);
733 if( output_new_delay
) {
734 printf( "delay = %d\n", output_new_delay
);
735 output_new_delay
= 0;
737 printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor
, output_diff
, output_offset
);
739 } else if( instrument
) {
740 printf( "# n\tresamp\tdiff\toffseti\tintegral\n");
744 printf( "%d\t%f\t%f\t%f\t%f\n", n
++, output_resampling_factor
, output_diff
, output_offset
, output_integral
);
750 if( output_new_delay
) {
751 printf( "delay = %d\n", output_new_delay
);
752 output_new_delay
= 0;
757 jack_deactivate( client
);
758 jack_client_close (client
);