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;
44 int offset_differential_index
= 0;
46 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_S24_3LE
, 3, sample_move_d24_sS
, sample_move_dS_s24
, "24bit - real" },
90 { SND_PCM_FORMAT_FLOAT_LE
, 4, sample_move_dS_floatLE
, sample_move_floatLE_sSs
, "float" },
91 { SND_PCM_FORMAT_S32
, 4, sample_move_d32u24_sS
, sample_move_dS_s32u24
, "32bit" },
92 { SND_PCM_FORMAT_S24
, 4, sample_move_d24_sS
, sample_move_dS_s24
, "24bit" },
93 { SND_PCM_FORMAT_S16
, 2, sample_move_d16_sS
, sample_move_dS_s16
, "16bit" }
95 #define NUMFORMATS (sizeof(formats)/sizeof(formats[0]))
98 // Alsa stuff... i dont want to touch this bullshit in the next years.... please...
100 static int xrun_recovery(snd_pcm_t
*handle
, int err
) {
101 // printf( "xrun !!!.... %d\n", err );
102 if (err
== -EPIPE
) { /* under-run */
103 err
= snd_pcm_prepare(handle
);
105 printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err
));
107 } else if (err
== -EAGAIN
) {
108 while ((err
= snd_pcm_resume(handle
)) == -EAGAIN
)
109 usleep(100); /* wait until the suspend flag is released */
111 err
= snd_pcm_prepare(handle
);
113 printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err
));
120 static int set_hwformat( snd_pcm_t
*handle
, snd_pcm_hw_params_t
*params
)
125 for( i
=0; i
<NUMFORMATS
; i
++ ) {
126 /* set the sample format */
127 err
= snd_pcm_hw_params_set_format(handle
, params
, formats
[i
].format_id
);
137 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
) {
139 unsigned int buffer_time
;
140 unsigned int period_time
;
142 unsigned int rchannels
;
144 /* choose all parameters */
145 err
= snd_pcm_hw_params_any(handle
, params
);
147 printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err
));
150 /* set the interleaved read/write format */
151 err
= snd_pcm_hw_params_set_access(handle
, params
, access
);
153 printf("Access type not available for playback: %s\n", snd_strerror(err
));
157 /* set the sample format */
158 err
= set_hwformat(handle
, params
);
160 printf("Sample format not available for playback: %s\n", snd_strerror(err
));
163 /* set the count of channels */
164 rchannels
= channels
;
165 err
= snd_pcm_hw_params_set_channels_near(handle
, params
, &rchannels
);
167 printf("Channels count (%i) not available for record: %s\n", channels
, snd_strerror(err
));
170 if (rchannels
!= channels
) {
171 printf("WARNING: chennel count does not match (requested %d got %d)\n", channels
, rchannels
);
172 num_channels
= rchannels
;
174 /* set the stream rate */
176 err
= snd_pcm_hw_params_set_rate_near(handle
, params
, &rrate
, 0);
178 printf("Rate %iHz not available for playback: %s\n", rate
, snd_strerror(err
));
182 printf("WARNING: Rate doesn't match (requested %iHz, get %iHz)\n", rate
, rrate
);
185 /* set the buffer time */
187 buffer_time
= 1000000*period
*nperiods
/rate
;
188 err
= snd_pcm_hw_params_set_buffer_time_near(handle
, params
, &buffer_time
, &dir
);
190 printf("Unable to set buffer time %i for playback: %s\n", 1000000*period
*nperiods
/rate
, snd_strerror(err
));
193 err
= snd_pcm_hw_params_get_buffer_size( params
, &real_buffer_size
);
195 printf("Unable to get buffer size back: %s\n", snd_strerror(err
));
198 if( real_buffer_size
!= nperiods
* period
) {
199 printf( "WARNING: buffer size does not match: (requested %d, got %d)\n", nperiods
* period
, (int) real_buffer_size
);
201 /* set the period time */
202 period_time
= 1000000*period
/rate
;
203 err
= snd_pcm_hw_params_set_period_time_near(handle
, params
, &period_time
, &dir
);
205 printf("Unable to set period time %i for playback: %s\n", 1000000*period
/rate
, snd_strerror(err
));
208 err
= snd_pcm_hw_params_get_period_size(params
, &real_period_size
, NULL
);
210 printf("Unable to get period size back: %s\n", snd_strerror(err
));
213 if( real_period_size
!= period
) {
214 printf( "WARNING: period size does not match: (requested %i, got %i)\n", period
, (int)real_period_size
);
216 /* write the parameters to device */
217 err
= snd_pcm_hw_params(handle
, params
);
219 printf("Unable to set hw params for playback: %s\n", snd_strerror(err
));
225 static int set_swparams(snd_pcm_t
*handle
, snd_pcm_sw_params_t
*swparams
, int period
) {
228 /* get the current swparams */
229 err
= snd_pcm_sw_params_current(handle
, swparams
);
231 printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err
));
234 /* start the transfer when the buffer is full */
235 err
= snd_pcm_sw_params_set_start_threshold(handle
, swparams
, period
);
237 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err
));
240 err
= snd_pcm_sw_params_set_stop_threshold(handle
, swparams
, -1 );
242 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err
));
245 /* allow the transfer when at least period_size samples can be processed */
246 err
= snd_pcm_sw_params_set_avail_min(handle
, swparams
, 2*period
);
248 printf("Unable to set avail min for capture: %s\n", snd_strerror(err
));
251 /* align all transfers to 1 sample */
252 err
= snd_pcm_sw_params_set_xfer_align(handle
, swparams
, 1);
254 printf("Unable to set transfer align for capture: %s\n", snd_strerror(err
));
257 /* write the parameters to the playback device */
258 err
= snd_pcm_sw_params(handle
, swparams
);
260 printf("Unable to set sw params for capture: %s\n", snd_strerror(err
));
266 // ok... i only need this function to communicate with the alsa bloat api...
268 static snd_pcm_t
*open_audiofd( char *device_name
, int capture
, int rate
, int channels
, int period
, int nperiods
) {
271 snd_pcm_hw_params_t
*hwparams
;
272 snd_pcm_sw_params_t
*swparams
;
274 snd_pcm_hw_params_alloca(&hwparams
);
275 snd_pcm_sw_params_alloca(&swparams
);
277 if ((err
= snd_pcm_open(&(handle
), device_name
, capture
? SND_PCM_STREAM_CAPTURE
: SND_PCM_STREAM_PLAYBACK
, SND_PCM_NONBLOCK
)) < 0) {
278 printf("Capture open error: %s\n", snd_strerror(err
));
282 if ((err
= set_hwparams(handle
, hwparams
,SND_PCM_ACCESS_RW_INTERLEAVED
, rate
, channels
, period
, nperiods
)) < 0) {
283 printf("Setting of hwparams failed: %s\n", snd_strerror(err
));
286 if ((err
= set_swparams(handle
, swparams
, period
)) < 0) {
287 printf("Setting of swparams failed: %s\n", snd_strerror(err
));
291 snd_pcm_start( handle
);
292 snd_pcm_wait( handle
, 200 );
297 double hann( double x
)
299 return 0.5 * (1.0 - cos( 2*M_PI
* x
) );
303 * The process callback for this JACK application.
304 * It is called by JACK at the appropriate times.
306 int process (jack_nframes_t nframes
, void *arg
) {
312 snd_pcm_sframes_t delay
= target_delay
;
313 int put_back_samples
=0;
316 snd_pcm_delay( alsa_handle
, &delay
);
318 //delay -= jack_frames_since_cycle_start( client );
319 // Do it the hard way.
320 // this is for compensating xruns etc...
322 if( delay
> (target_delay
+max_diff
) ) {
323 char *tmp
= alloca( (delay
-target_delay
) * formats
[format
].sample_size
* num_channels
);
324 snd_pcm_readi( alsa_handle
, tmp
, delay
-target_delay
);
325 output_new_delay
= (int) delay
;
327 delay
= target_delay
;
329 // Set the resample_rate... we need to adjust the offset integral, to do this.
330 // first look at the PI controller, this code is just a special case, which should never execute once
331 // everything is swung in.
332 offset_integral
= - (resample_mean
- static_resample_factor
) * catch_factor
* catch_factor2
;
333 // Also clear the array. we are beginning a new control cycle.
334 for( i
=0; i
<smooth_size
; i
++ )
335 offset_array
[i
] = 0.0;
337 if( delay
< (target_delay
-max_diff
) ) {
338 snd_pcm_rewind( alsa_handle
, target_delay
- delay
);
339 output_new_delay
= (int) delay
;
340 delay
= target_delay
;
342 // Set the resample_rate... we need to adjust the offset integral, to do this.
343 offset_integral
= - (resample_mean
- static_resample_factor
) * catch_factor
* catch_factor2
;
344 // Also clear the array. we are beginning a new control cycle.
345 for( i
=0; i
<smooth_size
; i
++ )
346 offset_array
[i
] = 0.0;
348 /* ok... now we should have target_delay +- max_diff on the alsa side.
350 * calculate the number of frames, we want to get.
353 double offset
= delay
- target_delay
;
356 offset_array
[(offset_differential_index
++)% smooth_size
] = offset
;
358 // Build the mean of the windowed offset array
359 // basically fir lowpassing.
360 double smooth_offset
= 0.0;
361 for( i
=0; i
<smooth_size
; i
++ )
363 offset_array
[ (i
+ offset_differential_index
-1) % smooth_size
] * window_array
[i
];
364 smooth_offset
/= (double) smooth_size
;
366 // this is the integral of the smoothed_offset
367 offset_integral
+= smooth_offset
;
370 // the smooth offset still contains unwanted noise
371 // which would go straigth onto the resample coeff.
372 // it only used in the P component and the I component is used for the fine tuning anyways.
373 if( fabs( smooth_offset
) < pclamp
)
376 // ok. now this is the PI controller.
377 // u(t) = K * ( e(t) + 1/T \int e(t') dt' )
378 // K = 1/catch_factor and T = catch_factor2
379 double current_resample_factor
= static_resample_factor
- smooth_offset
/ (double) catch_factor
- offset_integral
/ (double) catch_factor
/ (double)catch_factor2
;
381 // now quantize this value around resample_mean, so that the noise which is in the integral component doesnt hurt.
382 current_resample_factor
= floor( (current_resample_factor
- resample_mean
) * controlquant
+ 0.5 ) / controlquant
+ resample_mean
;
384 // Output "instrumentatio" gonna change that to real instrumentation in a few.
385 output_resampling_factor
= (float) current_resample_factor
;
386 output_diff
= (float) smooth_offset
;
387 output_integral
= (float) offset_integral
;
388 output_offset
= (float) offset
;
391 if( current_resample_factor
< 0.25 ) current_resample_factor
= 0.25;
392 if( current_resample_factor
> 4 ) current_resample_factor
= 4;
394 // Now Calculate how many samples we need.
395 rlen
= ceil( ((double)nframes
) / current_resample_factor
)+2;
398 // Calculate resample_mean so we can init ourselves to saner values.
399 resample_mean
= 0.9999 * resample_mean
+ 0.0001 * current_resample_factor
;
401 * now this should do it...
404 outbuf
= alloca( rlen
* formats
[format
].sample_size
* num_channels
);
406 resampbuf
= alloca( rlen
* sizeof( float ) );
410 err
= snd_pcm_readi(alsa_handle
, outbuf
, rlen
);
412 printf( "err = %d\n", err
);
413 if (xrun_recovery(alsa_handle
, err
) < 0) {
414 //printf("Write error: %s\n", snd_strerror(err));
415 //exit(EXIT_FAILURE);
420 //printf( "read = %d\n", rlen );
424 * render jack ports to the outbuf...
428 JSList
*node
= capture_ports
;
429 JSList
*src_node
= capture_srcs
;
432 while ( node
!= NULL
)
434 jack_port_t
*port
= (jack_port_t
*) node
->data
;
435 float *buf
= jack_port_get_buffer (port
, nframes
);
437 SRC_STATE
*src_state
= src_node
->data
;
439 formats
[format
].soundcard_to_jack( resampbuf
, outbuf
+ format
[formats
].sample_size
* chn
, rlen
, num_channels
*format
[formats
].sample_size
);
441 src
.data_in
= resampbuf
;
442 src
.input_frames
= rlen
;
445 src
.output_frames
= nframes
;
446 src
.end_of_input
= 0;
448 src
.src_ratio
= current_resample_factor
;
450 src_process( src_state
, &src
);
452 put_back_samples
= rlen
-src
.input_frames_used
;
454 src_node
= jack_slist_next (src_node
);
455 node
= jack_slist_next (node
);
459 // Put back the samples libsamplerate did not consume.
460 //printf( "putback = %d\n", put_back_samples );
461 snd_pcm_rewind( alsa_handle
, put_back_samples
);
468 * Allocate the necessary jack ports...
471 void alloc_ports( int n_capture
, int n_playback
) {
473 int port_flags
= JackPortIsOutput
;
478 capture_ports
= NULL
;
479 for (chn
= 0; chn
< n_capture
; chn
++)
481 snprintf (buf
, sizeof(buf
) - 1, "capture_%u", chn
+1);
483 port
= jack_port_register (client
, buf
,
484 JACK_DEFAULT_AUDIO_TYPE
,
489 printf( "jacknet_client: cannot register port for %s", buf
);
493 capture_srcs
= jack_slist_append( capture_srcs
, src_new( 4-samplerate_quality
, 1, NULL
) );
494 capture_ports
= jack_slist_append (capture_ports
, port
);
497 port_flags
= JackPortIsInput
;
499 playback_ports
= NULL
;
500 for (chn
= 0; chn
< n_playback
; chn
++)
502 snprintf (buf
, sizeof(buf
) - 1, "playback_%u", chn
+1);
504 port
= jack_port_register (client
, buf
,
505 JACK_DEFAULT_AUDIO_TYPE
,
510 printf( "jacknet_client: cannot register port for %s", buf
);
514 playback_srcs
= jack_slist_append( playback_srcs
, src_new( 4-samplerate_quality
, 1, NULL
) );
515 playback_ports
= jack_slist_append (playback_ports
, port
);
520 * This is the shutdown callback for this JACK application.
521 * It is called by JACK if the server ever shuts down or
522 * decides to disconnect the client.
525 void jack_shutdown (void *arg
) {
537 fprintf(stderr
, "usage: alsa_out [options]\n"
539 " -j <jack name> - client name\n"
540 " -d <alsa_device> \n"
542 " -p <period_size> \n"
543 " -n <num_period> \n"
544 " -r <sample_rate> \n"
545 " -q <sample_rate quality [0..4]\n"
547 " -t <target_delay> \n"
548 " -i turns on instrumentation\n"
549 " -v turns on printouts\n"
555 * the main function....
559 sigterm_handler( int signal
)
565 int main (int argc
, char *argv
[]) {
566 char jack_name
[30] = "alsa_in";
567 char alsa_device
[30] = "hw:0";
570 extern int optind
, optopt
;
574 while ((c
= getopt(argc
, argv
, "ivj:r:c:p:n:d:q:m:t:f:F:C:Q:s:")) != -1) {
577 strcpy(jack_name
,optarg
);
580 sample_rate
= atoi(optarg
);
583 num_channels
= atoi(optarg
);
586 period_size
= atoi(optarg
);
589 num_periods
= atoi(optarg
);
592 strcpy(alsa_device
,optarg
);
595 target_delay
= atoi(optarg
);
598 samplerate_quality
= atoi(optarg
);
601 max_diff
= atoi(optarg
);
604 catch_factor
= atoi(optarg
);
607 catch_factor2
= atoi(optarg
);
610 pclamp
= (double) atoi(optarg
);
613 controlquant
= (double) atoi(optarg
);
622 smooth_size
= atoi(optarg
);
626 "Option -%c requires an operand\n", optopt
);
631 "Unrecognized option: -%c\n", optopt
);
640 if( (samplerate_quality
< 0) || (samplerate_quality
> 4) ) {
641 fprintf (stderr
, "invalid samplerate quality\n");
644 if ((client
= jack_client_open (jack_name
, 0, NULL
)) == 0) {
645 fprintf (stderr
, "jack server not running?\n");
649 /* tell the JACK server to call `process()' whenever
650 there is work to be done.
653 jack_set_process_callback (client
, process
, 0);
655 /* tell the JACK server to call `jack_shutdown()' if
656 it ever shuts down, either entirely, or if it
657 just decides to stop calling us.
660 jack_on_shutdown (client
, jack_shutdown
, 0);
663 // get jack sample_rate
665 jack_sample_rate
= jack_get_sample_rate( client
);
668 sample_rate
= jack_sample_rate
;
670 // now open the alsa fd...
671 alsa_handle
= open_audiofd( alsa_device
, 1, sample_rate
, num_channels
, period_size
, num_periods
);
672 if( alsa_handle
== 0 )
675 printf( "selected sample format: %s\n", formats
[format
].name
);
677 static_resample_factor
= (double) jack_sample_rate
/ (double) sample_rate
;
678 resample_mean
= static_resample_factor
;
680 offset_array
= malloc( sizeof(double) * smooth_size
);
681 if( offset_array
== NULL
) {
682 fprintf( stderr
, "no memory for offset_array !!!\n" );
685 window_array
= malloc( sizeof(double) * smooth_size
);
686 if( window_array
== NULL
) {
687 fprintf( stderr
, "no memory for window_array !!!\n" );
691 for( i
=0; i
<smooth_size
; i
++ ) {
692 offset_array
[i
] = 0.0;
693 window_array
[i
] = hann( (double) i
/ ((double) smooth_size
- 1.0) );
696 jack_buffer_size
= jack_get_buffer_size( client
);
697 // Setup target delay and max_diff for the normal user, who does not play with them...
699 target_delay
= (num_periods
*period_size
/ 2) - jack_buffer_size
/2;
702 max_diff
= target_delay
;
704 if( max_diff
> target_delay
) {
705 fprintf( stderr
, "target_delay (%d) cant be smaller than max_diff(%d)\n", target_delay
, max_diff
);
708 if( (target_delay
+max_diff
) > (num_periods
*period_size
) ) {
709 fprintf( stderr
, "target_delay+max_diff (%d) cant be bigger than buffersize(%d)\n", target_delay
+max_diff
, num_periods
*period_size
);
712 // alloc input ports, which are blasted out to alsa...
713 alloc_ports( num_channels
, 0 );
716 /* tell the JACK server that we are ready to roll */
718 if (jack_activate (client
)) {
719 fprintf (stderr
, "cannot activate client");
723 signal( SIGTERM
, sigterm_handler
);
724 signal( SIGINT
, sigterm_handler
);
729 if( output_new_delay
) {
730 printf( "delay = %d\n", output_new_delay
);
731 output_new_delay
= 0;
733 printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor
, output_diff
, output_offset
);
735 } else if( instrument
) {
736 printf( "# n\tresamp\tdiff\toffseti\tintegral\n");
740 printf( "%d\t%f\t%f\t%f\t%f\n", n
++, output_resampling_factor
, output_diff
, output_offset
, output_integral
);
746 if( output_new_delay
) {
747 printf( "delay = %d\n", output_new_delay
);
748 output_new_delay
= 0;
753 jack_deactivate( client
);
754 jack_client_close (client
);