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;
76 snd_pcm_uframes_t real_buffer_size
;
77 snd_pcm_uframes_t real_period_size
;
85 // format selection, and corresponding functions from memops in a nice set of structs.
87 typedef struct alsa_format
{
88 snd_pcm_format_t format_id
;
90 void (*jack_to_soundcard
) (char *dst
, jack_default_audio_sample_t
*src
, unsigned long nsamples
, unsigned long dst_skip
, dither_state_t
*state
);
91 void (*soundcard_to_jack
) (jack_default_audio_sample_t
*dst
, char *src
, unsigned long nsamples
, unsigned long src_skip
);
95 alsa_format_t formats
[] = {
96 { SND_PCM_FORMAT_FLOAT_LE
, 4, sample_move_dS_floatLE
, sample_move_floatLE_sSs
, "float" },
97 { SND_PCM_FORMAT_S32
, 4, sample_move_d32u24_sS
, sample_move_dS_s32u24
, "32bit" },
98 { SND_PCM_FORMAT_S24_3LE
, 3, sample_move_d24_sS
, sample_move_dS_s24
, "24bit - real" },
99 { SND_PCM_FORMAT_S24
, 4, sample_move_d24_sS
, sample_move_dS_s24
, "24bit" },
100 { SND_PCM_FORMAT_S16
, 2, sample_move_d16_sS
, sample_move_dS_s16
, "16bit" }
102 #define NUMFORMATS (sizeof(formats)/sizeof(formats[0]))
105 // Alsa stuff... i dont want to touch this bullshit in the next years.... please...
107 static int xrun_recovery(snd_pcm_t
*handle
, int err
) {
108 // printf( "xrun !!!.... %d\n", err );
109 if (err
== -EPIPE
) { /* under-run */
110 err
= snd_pcm_prepare(handle
);
112 printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err
));
114 } else if (err
== -EAGAIN
) {
115 while ((err
= snd_pcm_resume(handle
)) == -EAGAIN
)
116 usleep(100); /* wait until the suspend flag is released */
118 err
= snd_pcm_prepare(handle
);
120 printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err
));
127 static int set_hwformat( snd_pcm_t
*handle
, snd_pcm_hw_params_t
*params
)
132 for( i
=0; i
<NUMFORMATS
; i
++ ) {
133 /* set the sample format */
134 err
= snd_pcm_hw_params_set_format(handle
, params
, formats
[i
].format_id
);
144 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
) {
146 unsigned int buffer_time
;
147 unsigned int period_time
;
149 unsigned int rchannels
;
151 /* choose all parameters */
152 err
= snd_pcm_hw_params_any(handle
, params
);
154 printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err
));
157 /* set the interleaved read/write format */
158 err
= snd_pcm_hw_params_set_access(handle
, params
, access
);
160 printf("Access type not available for playback: %s\n", snd_strerror(err
));
164 /* set the sample format */
165 err
= set_hwformat(handle
, params
);
167 printf("Sample format not available for playback: %s\n", snd_strerror(err
));
170 /* set the count of channels */
171 rchannels
= channels
;
172 err
= snd_pcm_hw_params_set_channels_near(handle
, params
, &rchannels
);
174 printf("Channels count (%i) not available for record: %s\n", channels
, snd_strerror(err
));
177 if (rchannels
!= channels
) {
178 printf("WARNING: chennel count does not match (requested %d got %d)\n", channels
, rchannels
);
179 num_channels
= rchannels
;
181 /* set the stream rate */
183 err
= snd_pcm_hw_params_set_rate_near(handle
, params
, &rrate
, 0);
185 printf("Rate %iHz not available for playback: %s\n", rate
, snd_strerror(err
));
189 printf("WARNING: Rate doesn't match (requested %iHz, get %iHz)\n", rate
, rrate
);
192 /* set the buffer time */
194 buffer_time
= 1000000*(uint64_t)period
*nperiods
/rate
;
195 err
= snd_pcm_hw_params_set_buffer_time_near(handle
, params
, &buffer_time
, &dir
);
197 printf("Unable to set buffer time %i for playback: %s\n", 1000000*period
*nperiods
/rate
, snd_strerror(err
));
200 err
= snd_pcm_hw_params_get_buffer_size( params
, &real_buffer_size
);
202 printf("Unable to get buffer size back: %s\n", snd_strerror(err
));
205 if( real_buffer_size
!= nperiods
* period
) {
206 printf( "WARNING: buffer size does not match: (requested %d, got %d)\n", nperiods
* period
, (int) real_buffer_size
);
208 /* set the period time */
209 period_time
= 1000000*(uint64_t)period
/rate
;
210 err
= snd_pcm_hw_params_set_period_time_near(handle
, params
, &period_time
, &dir
);
212 printf("Unable to set period time %i for playback: %s\n", 1000000*period
/rate
, snd_strerror(err
));
215 err
= snd_pcm_hw_params_get_period_size(params
, &real_period_size
, NULL
);
217 printf("Unable to get period size back: %s\n", snd_strerror(err
));
220 if( real_period_size
!= period
) {
221 printf( "WARNING: period size does not match: (requested %i, got %i)\n", period
, (int)real_period_size
);
223 /* write the parameters to device */
224 err
= snd_pcm_hw_params(handle
, params
);
226 printf("Unable to set hw params for playback: %s\n", snd_strerror(err
));
232 static int set_swparams(snd_pcm_t
*handle
, snd_pcm_sw_params_t
*swparams
, int period
) {
235 /* get the current swparams */
236 err
= snd_pcm_sw_params_current(handle
, swparams
);
238 printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err
));
241 /* start the transfer when the buffer is full */
242 err
= snd_pcm_sw_params_set_start_threshold(handle
, swparams
, period
);
244 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err
));
247 err
= snd_pcm_sw_params_set_stop_threshold(handle
, swparams
, -1 );
249 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err
));
252 /* allow the transfer when at least period_size samples can be processed */
253 err
= snd_pcm_sw_params_set_avail_min(handle
, swparams
, 2*period
);
255 printf("Unable to set avail min for capture: %s\n", snd_strerror(err
));
258 /* align all transfers to 1 sample */
259 err
= snd_pcm_sw_params_set_xfer_align(handle
, swparams
, 1);
261 printf("Unable to set transfer align for capture: %s\n", snd_strerror(err
));
264 /* write the parameters to the playback device */
265 err
= snd_pcm_sw_params(handle
, swparams
);
267 printf("Unable to set sw params for capture: %s\n", snd_strerror(err
));
273 // ok... i only need this function to communicate with the alsa bloat api...
275 static snd_pcm_t
*open_audiofd( char *device_name
, int capture
, int rate
, int channels
, int period
, int nperiods
) {
278 snd_pcm_hw_params_t
*hwparams
;
279 snd_pcm_sw_params_t
*swparams
;
281 snd_pcm_hw_params_alloca(&hwparams
);
282 snd_pcm_sw_params_alloca(&swparams
);
284 if ((err
= snd_pcm_open(&(handle
), device_name
, capture
? SND_PCM_STREAM_CAPTURE
: SND_PCM_STREAM_PLAYBACK
, SND_PCM_NONBLOCK
)) < 0) {
285 printf("Capture open error: %s\n", snd_strerror(err
));
289 if ((err
= set_hwparams(handle
, hwparams
,SND_PCM_ACCESS_RW_INTERLEAVED
, rate
, channels
, period
, nperiods
)) < 0) {
290 printf("Setting of hwparams failed: %s\n", snd_strerror(err
));
293 if ((err
= set_swparams(handle
, swparams
, period
)) < 0) {
294 printf("Setting of swparams failed: %s\n", snd_strerror(err
));
298 snd_pcm_start( handle
);
299 snd_pcm_wait( handle
, 200 );
304 double hann( double x
)
306 return 0.5 * (1.0 - cos( 2*M_PI
* x
) );
310 * The process callback for this JACK application.
311 * It is called by JACK at the appropriate times.
313 int process (jack_nframes_t nframes
, void *arg
) {
317 snd_pcm_sframes_t delay
= target_delay
;
318 int put_back_samples
=0;
321 delay
= snd_pcm_avail( alsa_handle
);
323 delay
-= jack_frames_since_cycle_start( client
);
324 // Do it the hard way.
325 // this is for compensating xruns etc...
327 if( delay
> (target_delay
+max_diff
) ) {
329 output_new_delay
= (int) delay
;
331 while ((delay
-target_delay
) > 0) {
332 snd_pcm_uframes_t to_read
= ((delay
-target_delay
) > 512) ? 512 : (delay
-target_delay
);
333 snd_pcm_readi( alsa_handle
, tmpbuf
, to_read
);
337 delay
= target_delay
;
339 // Set the resample_rate... we need to adjust the offset integral, to do this.
340 // first look at the PI controller, this code is just a special case, which should never execute once
341 // everything is swung in.
342 offset_integral
= - (resample_mean
- static_resample_factor
) * catch_factor
* catch_factor2
;
343 // Also clear the array. we are beginning a new control cycle.
344 for( i
=0; i
<smooth_size
; i
++ )
345 offset_array
[i
] = 0.0;
347 if( delay
< (target_delay
-max_diff
) ) {
348 snd_pcm_rewind( alsa_handle
, target_delay
- delay
);
349 output_new_delay
= (int) delay
;
350 delay
= target_delay
;
352 // Set the resample_rate... we need to adjust the offset integral, to do this.
353 offset_integral
= - (resample_mean
- static_resample_factor
) * catch_factor
* catch_factor2
;
354 // Also clear the array. we are beginning a new control cycle.
355 for( i
=0; i
<smooth_size
; i
++ )
356 offset_array
[i
] = 0.0;
358 /* ok... now we should have target_delay +- max_diff on the alsa side.
360 * calculate the number of frames, we want to get.
363 double offset
= delay
- target_delay
;
366 offset_array
[(offset_differential_index
++)% smooth_size
] = offset
;
368 // Build the mean of the windowed offset array
369 // basically fir lowpassing.
370 double smooth_offset
= 0.0;
371 for( i
=0; i
<smooth_size
; i
++ )
373 offset_array
[ (i
+ offset_differential_index
-1) % smooth_size
] * window_array
[i
];
374 smooth_offset
/= (double) smooth_size
;
376 // this is the integral of the smoothed_offset
377 offset_integral
+= smooth_offset
;
380 // the smooth offset still contains unwanted noise
381 // which would go straigth onto the resample coeff.
382 // it only used in the P component and the I component is used for the fine tuning anyways.
383 if( fabs( smooth_offset
) < pclamp
)
386 // ok. now this is the PI controller.
387 // u(t) = K * ( e(t) + 1/T \int e(t') dt' )
388 // K = 1/catch_factor and T = catch_factor2
389 double current_resample_factor
= static_resample_factor
- smooth_offset
/ (double) catch_factor
- offset_integral
/ (double) catch_factor
/ (double)catch_factor2
;
391 // now quantize this value around resample_mean, so that the noise which is in the integral component doesnt hurt.
392 current_resample_factor
= floor( (current_resample_factor
- resample_mean
) * controlquant
+ 0.5 ) / controlquant
+ resample_mean
;
394 // Output "instrumentatio" gonna change that to real instrumentation in a few.
395 output_resampling_factor
= (float) current_resample_factor
;
396 output_diff
= (float) smooth_offset
;
397 output_integral
= (float) offset_integral
;
398 output_offset
= (float) offset
;
401 if( current_resample_factor
< resample_lower_limit
) current_resample_factor
= resample_lower_limit
;
402 if( current_resample_factor
> resample_upper_limit
) current_resample_factor
= resample_upper_limit
;
404 // Now Calculate how many samples we need.
405 rlen
= ceil( ((double)nframes
) / current_resample_factor
)+2;
408 // Calculate resample_mean so we can init ourselves to saner values.
409 resample_mean
= 0.9999 * resample_mean
+ 0.0001 * current_resample_factor
;
413 err
= snd_pcm_readi(alsa_handle
, outbuf
, rlen
);
415 printf( "err = %d\n", err
);
416 if (xrun_recovery(alsa_handle
, err
) < 0) {
417 //printf("Write error: %s\n", snd_strerror(err));
418 //exit(EXIT_FAILURE);
423 //printf( "read = %d\n", rlen );
427 * render jack ports to the outbuf...
431 JSList
*node
= capture_ports
;
432 JSList
*src_node
= capture_srcs
;
435 while ( node
!= NULL
)
437 jack_port_t
*port
= (jack_port_t
*) node
->data
;
438 float *buf
= jack_port_get_buffer (port
, nframes
);
440 SRC_STATE
*src_state
= src_node
->data
;
442 formats
[format
].soundcard_to_jack( resampbuf
, outbuf
+ format
[formats
].sample_size
* chn
, rlen
, num_channels
*format
[formats
].sample_size
);
444 src
.data_in
= resampbuf
;
445 src
.input_frames
= rlen
;
448 src
.output_frames
= nframes
;
449 src
.end_of_input
= 0;
451 src
.src_ratio
= current_resample_factor
;
453 src_process( src_state
, &src
);
455 put_back_samples
= rlen
-src
.input_frames_used
;
457 src_node
= jack_slist_next (src_node
);
458 node
= jack_slist_next (node
);
462 // Put back the samples libsamplerate did not consume.
463 //printf( "putback = %d\n", put_back_samples );
464 snd_pcm_rewind( alsa_handle
, put_back_samples
);
470 * the latency callback.
471 * sets up the latencies on the ports.
475 latency_cb (jack_latency_callback_mode_t mode
, void *arg
)
477 jack_latency_range_t range
;
480 range
.min
= range
.max
= target_delay
;
482 if (mode
== JackCaptureLatency
) {
483 for (node
= capture_ports
; node
; node
= jack_slist_next (node
)) {
484 jack_port_t
*port
= node
->data
;
485 jack_port_set_latency_range (port
, mode
, &range
);
488 for (node
= playback_ports
; node
; node
= jack_slist_next (node
)) {
489 jack_port_t
*port
= node
->data
;
490 jack_port_set_latency_range (port
, mode
, &range
);
497 * Allocate the necessary jack ports...
500 void alloc_ports( int n_capture
, int n_playback
) {
502 int port_flags
= JackPortIsOutput
;
507 capture_ports
= NULL
;
508 for (chn
= 0; chn
< n_capture
; chn
++)
510 snprintf (buf
, sizeof(buf
) - 1, "capture_%u", chn
+1);
512 port
= jack_port_register (client
, buf
,
513 JACK_DEFAULT_AUDIO_TYPE
,
518 printf( "jacknet_client: cannot register port for %s", buf
);
522 capture_srcs
= jack_slist_append( capture_srcs
, src_new( 4-samplerate_quality
, 1, NULL
) );
523 capture_ports
= jack_slist_append (capture_ports
, port
);
526 port_flags
= JackPortIsInput
;
528 playback_ports
= NULL
;
529 for (chn
= 0; chn
< n_playback
; chn
++)
531 snprintf (buf
, sizeof(buf
) - 1, "playback_%u", chn
+1);
533 port
= jack_port_register (client
, buf
,
534 JACK_DEFAULT_AUDIO_TYPE
,
539 printf( "jacknet_client: cannot register port for %s", buf
);
543 playback_srcs
= jack_slist_append( playback_srcs
, src_new( 4-samplerate_quality
, 1, NULL
) );
544 playback_ports
= jack_slist_append (playback_ports
, port
);
549 * This is the shutdown callback for this JACK application.
550 * It is called by JACK if the server ever shuts down or
551 * decides to disconnect the client.
554 void jack_shutdown (void *arg
) {
566 fprintf(stderr
, "usage: alsa_out [options]\n"
568 " -j <jack name> - client name\n"
569 " -d <alsa_device> \n"
571 " -p <period_size> \n"
572 " -n <num_period> \n"
573 " -r <sample_rate> \n"
574 " -q <sample_rate quality [0..4]\n"
576 " -t <target_delay> \n"
577 " -i turns on instrumentation\n"
578 " -v turns on printouts\n"
584 * the main function....
588 sigterm_handler( int signal
)
594 int main (int argc
, char *argv
[]) {
595 char jack_name
[30] = "alsa_in";
596 char alsa_device
[30] = "hw:0";
599 extern int optind
, optopt
;
603 while ((c
= getopt(argc
, argv
, "ivj:r:c:p:n:d:q:m:t:f:F:C:Q:s:")) != -1) {
606 strcpy(jack_name
,optarg
);
609 sample_rate
= atoi(optarg
);
612 num_channels
= atoi(optarg
);
615 period_size
= atoi(optarg
);
618 num_periods
= atoi(optarg
);
621 strcpy(alsa_device
,optarg
);
624 target_delay
= atoi(optarg
);
627 samplerate_quality
= atoi(optarg
);
630 max_diff
= atoi(optarg
);
633 catch_factor
= atoi(optarg
);
636 catch_factor2
= atoi(optarg
);
639 pclamp
= (double) atoi(optarg
);
642 controlquant
= (double) atoi(optarg
);
651 smooth_size
= atoi(optarg
);
655 "Option -%c requires an operand\n", optopt
);
660 "Unrecognized option: -%c\n", optopt
);
669 if( (samplerate_quality
< 0) || (samplerate_quality
> 4) ) {
670 fprintf (stderr
, "invalid samplerate quality\n");
673 if ((client
= jack_client_open (jack_name
, 0, NULL
)) == 0) {
674 fprintf (stderr
, "jack server not running?\n");
678 /* tell the JACK server to call `process()' whenever
679 there is work to be done.
682 jack_set_process_callback (client
, process
, 0);
684 /* tell the JACK server to call `jack_shutdown()' if
685 it ever shuts down, either entirely, or if it
686 just decides to stop calling us.
689 jack_on_shutdown (client
, jack_shutdown
, 0);
691 if (jack_set_latency_callback
)
692 jack_set_latency_callback (client
, latency_cb
, 0);
694 // get jack sample_rate
696 jack_sample_rate
= jack_get_sample_rate( client
);
699 sample_rate
= jack_sample_rate
;
701 // now open the alsa fd...
702 alsa_handle
= open_audiofd( alsa_device
, 1, sample_rate
, num_channels
, period_size
, num_periods
);
703 if( alsa_handle
== 0 )
706 printf( "selected sample format: %s\n", formats
[format
].name
);
708 static_resample_factor
= (double) jack_sample_rate
/ (double) sample_rate
;
709 resample_lower_limit
= static_resample_factor
* 0.25;
710 resample_upper_limit
= static_resample_factor
* 4.0;
711 resample_mean
= static_resample_factor
;
713 offset_array
= malloc( sizeof(double) * smooth_size
);
714 if( offset_array
== NULL
) {
715 fprintf( stderr
, "no memory for offset_array !!!\n" );
718 window_array
= malloc( sizeof(double) * smooth_size
);
719 if( window_array
== NULL
) {
720 fprintf( stderr
, "no memory for window_array !!!\n" );
724 for( i
=0; i
<smooth_size
; i
++ ) {
725 offset_array
[i
] = 0.0;
726 window_array
[i
] = hann( (double) i
/ ((double) smooth_size
- 1.0) );
729 jack_buffer_size
= jack_get_buffer_size( client
);
730 // Setup target delay and max_diff for the normal user, who does not play with them...
732 target_delay
= (num_periods
*period_size
/ 2) + jack_buffer_size
/2;
735 max_diff
= num_periods
*period_size
- target_delay
;
737 if( max_diff
> target_delay
) {
738 fprintf( stderr
, "target_delay (%d) cant be smaller than max_diff(%d)\n", target_delay
, max_diff
);
741 if( (target_delay
+max_diff
) > (num_periods
*period_size
) ) {
742 fprintf( stderr
, "target_delay+max_diff (%d) cant be bigger than buffersize(%d)\n", target_delay
+max_diff
, num_periods
*period_size
);
745 // alloc input ports, which are blasted out to alsa...
746 alloc_ports( num_channels
, 0 );
748 outbuf
= malloc( num_periods
* period_size
* formats
[format
].sample_size
* num_channels
);
749 resampbuf
= malloc( num_periods
* period_size
* sizeof( float ) );
750 tmpbuf
= malloc( 512 * formats
[format
].sample_size
* num_channels
);
752 if ((outbuf
== NULL
) || (resampbuf
== NULL
) || (tmpbuf
== NULL
))
754 fprintf( stderr
, "no memory for buffers.\n" );
758 memset( tmpbuf
, 0, 512 * formats
[format
].sample_size
* num_channels
);
760 /* tell the JACK server that we are ready to roll */
762 if (jack_activate (client
)) {
763 fprintf (stderr
, "cannot activate client");
767 signal( SIGTERM
, sigterm_handler
);
768 signal( SIGINT
, sigterm_handler
);
773 if( output_new_delay
) {
774 printf( "delay = %d\n", output_new_delay
);
775 output_new_delay
= 0;
777 printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor
, output_diff
, output_offset
);
779 } else if( instrument
) {
780 printf( "# n\tresamp\tdiff\toffseti\tintegral\n");
784 printf( "%d\t%f\t%f\t%f\t%f\n", n
++, output_resampling_factor
, output_diff
, output_offset
, output_integral
);
790 if( output_new_delay
) {
791 printf( "delay = %d\n", output_new_delay
);
792 output_new_delay
= 0;
797 jack_deactivate( client
);
798 jack_client_close (client
);