1 /** @file simple_client.c
2 *
3 * @brief This simple client demonstrates the basic features of JACK
4 * as they would be used by many applications.
5 */
6
7 #include <stdio.h>
8 #include <errno.h>
9 #include <unistd.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <signal.h>
13
14 #include <math.h>
15
16 #include <jack/jack.h>
17 #include <jack/jslist.h>
18 #include "memops.h"
19
20 #include "alsa/asoundlib.h"
21
22 #include <samplerate.h>
23
24 // Here are the lists of the jack ports...
25
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;
31
32 snd_pcm_t *alsa_handle;
33
34 int jack_sample_rate;
35 int jack_buffer_size;
36
37 int quit = 0;
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;
42
43 double *offset_array;
44 double *window_array;
45 int offset_differential_index = 0;
46
47 double offset_integral = 0;
48
49 // ------------------------------------------------------ commandline parameters
50
51 int sample_rate = 0; /* stream rate */
52 int num_channels = 2; /* count of channels */
53 int period_size = 1024;
54 int num_periods = 2;
55
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;
60 double pclamp = 15.0;
61 double controlquant = 10000.0;
62 int smooth_size = 256;
63 int good_window=0;
64 int verbose = 0;
65 int instrument = 0;
66 int samplerate_quality = 2;
67
68 // Debug stuff:
69
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;
76
77 snd_pcm_uframes_t real_buffer_size;
78 snd_pcm_uframes_t real_period_size;
79
80 // buffers
81
82 char *tmpbuf;
83 char *outbuf;
84 float *resampbuf;
85
86 // format selection, and corresponding functions from memops in a nice set of structs.
87
88 typedef struct alsa_format {
89 snd_pcm_format_t format_id;
90 size_t sample_size;
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);
93 const char *name;
94 } alsa_format_t;
95
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" }
102 #ifdef __ANDROID__
103 ,{ SND_PCM_FORMAT_S16_LE, 2, sample_move_d16_sS, sample_move_dS_s16, "16bit little-endian" }
104 #endif
105 };
106 #define NUMFORMATS (sizeof(formats)/sizeof(formats[0]))
107 int format=0;
108
109 // Alsa stuff... i don't want to touch this bullshit in the next years.... please...
110
xrun_recovery(snd_pcm_t * handle,int err)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);
115 if (err < 0)
116 printf("Can't recover from underrun, prepare failed: %s\n", snd_strerror(err));
117 return 0;
118 } else if (err == -ESTRPIPE) {
119 while ((err = snd_pcm_resume(handle)) == -EAGAIN)
120 usleep(100); /* wait until the suspend flag is released */
121 if (err < 0) {
122 err = snd_pcm_prepare(handle);
123 if (err < 0)
124 printf("Can't recover from suspend, prepare failed: %s\n", snd_strerror(err));
125 }
126 return 0;
127 }
128 return err;
129 }
130
set_hwformat(snd_pcm_t * handle,snd_pcm_hw_params_t * params)131 static int set_hwformat( snd_pcm_t *handle, snd_pcm_hw_params_t *params )
132 {
133 #ifdef __ANDROID__
134 format = 5;
135 snd_pcm_hw_params_set_format(handle, params, formats[format].format_id);
136 return 0;
137 #else
138 int i;
139 int err;
140
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);
144 if (err == 0) {
145 format = i;
146 return 0;
147 }
148 }
149
150 return err;
151 #endif
152 }
153
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)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 ) {
155 int err, dir=0;
156 unsigned int buffer_time;
157 unsigned int period_time;
158 unsigned int rrate;
159 unsigned int rchannels;
160
161 /* choose all parameters */
162 err = snd_pcm_hw_params_any(handle, params);
163 if (err < 0) {
164 printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
165 return err;
166 }
167 /* set the interleaved read/write format */
168 err = snd_pcm_hw_params_set_access(handle, params, access);
169 if (err < 0) {
170 printf("Access type not available for playback: %s\n", snd_strerror(err));
171 return err;
172 }
173
174 /* set the sample format */
175 err = set_hwformat(handle, params);
176 if (err < 0) {
177 printf("Sample format not available for playback: %s\n", snd_strerror(err));
178 return err;
179 }
180 /* set the count of channels */
181 rchannels = channels;
182 err = snd_pcm_hw_params_set_channels_near(handle, params, &rchannels);
183 if (err < 0) {
184 printf("Channels count (%i) not available for record: %s\n", channels, snd_strerror(err));
185 return err;
186 }
187 if (rchannels != channels) {
188 printf("WARNING: channel count does not match (requested %d got %d)\n", channels, rchannels);
189 num_channels = rchannels;
190 }
191 /* set the stream rate */
192 rrate = rate;
193 err = snd_pcm_hw_params_set_rate_near(handle, params, &rrate, 0);
194 if (err < 0) {
195 printf("Rate %iHz not available for playback: %s\n", rate, snd_strerror(err));
196 return err;
197 }
198 if (rrate != rate) {
199 printf("WARNING: Rate doesn't match (requested %iHz, get %iHz)\n", rate, rrate);
200 sample_rate = rrate;
201 }
202 /* set the buffer time */
203
204 buffer_time = 1000000*(uint64_t)period*nperiods/rate;
205 err = snd_pcm_hw_params_set_buffer_time_near(handle, params, &buffer_time, &dir);
206 if (err < 0) {
207 printf("Unable to set buffer time %i for playback: %s\n", 1000000*period*nperiods/rate, snd_strerror(err));
208 return err;
209 }
210 err = snd_pcm_hw_params_get_buffer_size( params, &real_buffer_size );
211 if (err < 0) {
212 printf("Unable to get buffer size back: %s\n", snd_strerror(err));
213 return err;
214 }
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 );
217 }
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);
221 if (err < 0) {
222 printf("Unable to set period time %i for playback: %s\n", 1000000*period/rate, snd_strerror(err));
223 return err;
224 }
225 err = snd_pcm_hw_params_get_period_size(params, &real_period_size, NULL );
226 if (err < 0) {
227 printf("Unable to get period size back: %s\n", snd_strerror(err));
228 return err;
229 }
230 if( real_period_size != period ) {
231 printf( "WARNING: period size does not match: (requested %i, got %i)\n", period, (int)real_period_size );
232 }
233 /* write the parameters to device */
234 err = snd_pcm_hw_params(handle, params);
235 if (err < 0) {
236 printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
237 return err;
238 }
239 return 0;
240 }
241
set_swparams(snd_pcm_t * handle,snd_pcm_sw_params_t * swparams,int period)242 static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams, int period) {
243 int err;
244
245 /* get the current swparams */
246 err = snd_pcm_sw_params_current(handle, swparams);
247 if (err < 0) {
248 printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err));
249 return err;
250 }
251 /* start the transfer when the buffer is full */
252 err = snd_pcm_sw_params_set_start_threshold(handle, swparams, period );
253 if (err < 0) {
254 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
255 return err;
256 }
257 err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, -1 );
258 if (err < 0) {
259 printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
260 return err;
261 }
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 );
264 if (err < 0) {
265 printf("Unable to set avail min for capture: %s\n", snd_strerror(err));
266 return err;
267 }
268 /* align all transfers to 1 sample */
269 err = snd_pcm_sw_params_set_xfer_align(handle, swparams, 1);
270 if (err < 0) {
271 printf("Unable to set transfer align for capture: %s\n", snd_strerror(err));
272 return err;
273 }
274 /* write the parameters to the playback device */
275 err = snd_pcm_sw_params(handle, swparams);
276 if (err < 0) {
277 printf("Unable to set sw params for capture: %s\n", snd_strerror(err));
278 return err;
279 }
280 return 0;
281 }
282
283 // ok... i only need this function to communicate with the alsa bloat api...
284
open_audiofd(char * device_name,int capture,int rate,int channels,int period,int nperiods)285 static snd_pcm_t *open_audiofd( char *device_name, int capture, int rate, int channels, int period, int nperiods ) {
286 int err;
287 snd_pcm_t *handle;
288 snd_pcm_hw_params_t *hwparams;
289 snd_pcm_sw_params_t *swparams;
290
291 snd_pcm_hw_params_alloca(&hwparams);
292 snd_pcm_sw_params_alloca(&swparams);
293
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));
296 return NULL;
297 }
298
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));
301 return NULL;
302 }
303 if ((err = set_swparams(handle, swparams, period)) < 0) {
304 printf("Setting of swparams failed: %s\n", snd_strerror(err));
305 return NULL;
306 }
307
308 snd_pcm_start( handle );
309 snd_pcm_wait( handle, 200 );
310
311 return handle;
312 }
313
hann(double x)314 double hann( double x )
315 {
316 return 0.5 * (1.0 - cos( 2*M_PI * x ) );
317 }
318
319 /**
320 * The freewheel callback.
321 */
freewheel(int starting,void * arg)322 void freewheel (int starting, void* arg) {
323 running_freewheel = starting;
324 }
325
326 /**
327 * The process callback for this JACK application.
328 * It is called by JACK at the appropriate times.
329 */
process(jack_nframes_t nframes,void * arg)330 int process (jack_nframes_t nframes, void *arg) {
331
332 if (running_freewheel) {
333 JSList *node = capture_ports;
334
335 while ( node != NULL)
336 {
337 jack_port_t *port = (jack_port_t *) node->data;
338 float *buf = jack_port_get_buffer (port, nframes);
339
340 memset(buf, 0, sizeof(float)*nframes);
341
342 node = jack_slist_next (node);
343 }
344
345 return 0;
346 }
347
348 int rlen;
349 int err;
350 snd_pcm_sframes_t delay = target_delay;
351 int put_back_samples=0;
352 int i;
353
354 delay = snd_pcm_avail( alsa_handle );
355
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...
359
360 if( delay > (target_delay+max_diff) ) {
361
362 output_new_delay = (int) delay;
363
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 );
367 delay -= to_read;
368 }
369
370 delay = target_delay;
371
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;
379 }
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;
384
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;
390 }
391 /* ok... now we should have target_delay +- max_diff on the alsa side.
392 *
393 * calculate the number of frames, we want to get.
394 */
395
396 double offset = delay - target_delay;
397
398 // Save offset.
399 offset_array[(offset_differential_index++)% smooth_size ] = offset;
400
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++ )
405 smooth_offset +=
406 offset_array[ (i + offset_differential_index-1) % smooth_size] * window_array[i];
407 smooth_offset /= (double) smooth_size;
408
409 // this is the integral of the smoothed_offset
410 offset_integral += smooth_offset;
411
412 // Clamp 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 )
417 smooth_offset = 0.0;
418
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;
423
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;
426
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;
432
433 // Clamp a bit.
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;
436
437 // Now Calculate how many samples we need.
438 rlen = ceil( ((double)nframes) / current_resample_factor )+2;
439 assert( rlen > 2 );
440
441 // Calculate resample_mean so we can init ourselves to saner values.
442 resample_mean = 0.9999 * resample_mean + 0.0001 * current_resample_factor;
443
444 // get the data...
445 again:
446 err = snd_pcm_readi(alsa_handle, outbuf, rlen);
447 if( err < 0 ) {
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);
452 }
453 goto again;
454 }
455 if( err != rlen ) {
456 //printf( "read = %d\n", rlen );
457 }
458
459 /*
460 * render jack ports to the outbuf...
461 */
462
463 int chn = 0;
464 JSList *node = capture_ports;
465 JSList *src_node = capture_srcs;
466 SRC_DATA src;
467
468 while ( node != NULL)
469 {
470 jack_port_t *port = (jack_port_t *) node->data;
471 float *buf = jack_port_get_buffer (port, nframes);
472
473 SRC_STATE *src_state = src_node->data;
474
475 formats[format].soundcard_to_jack( resampbuf, outbuf + format[formats].sample_size * chn, rlen, num_channels*format[formats].sample_size );
476
477 src.data_in = resampbuf;
478 src.input_frames = rlen;
479
480 src.data_out = buf;
481 src.output_frames = nframes;
482 src.end_of_input = 0;
483
484 src.src_ratio = current_resample_factor;
485
486 src_process( src_state, &src );
487
488 put_back_samples = rlen-src.input_frames_used;
489
490 src_node = jack_slist_next (src_node);
491 node = jack_slist_next (node);
492 chn++;
493 }
494
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 );
498
499 return 0;
500 }
501
502 /**
503 * the latency callback.
504 * sets up the latencies on the ports.
505 */
506
507 void
latency_cb(jack_latency_callback_mode_t mode,void * arg)508 latency_cb (jack_latency_callback_mode_t mode, void *arg)
509 {
510 jack_latency_range_t range;
511 JSList *node;
512
513 range.min = range.max = round(target_delay * static_resample_factor);
514
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);
519 }
520 } else {
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);
524 }
525 }
526 }
527
528
529 /**
530 * Allocate the necessary jack ports...
531 */
532
alloc_ports(int n_capture,int n_playback)533 void alloc_ports( int n_capture, int n_playback ) {
534
535 int port_flags = JackPortIsOutput;
536 int chn;
537 jack_port_t *port;
538 char buf[32];
539
540 capture_ports = NULL;
541 for (chn = 0; chn < n_capture; chn++)
542 {
543 snprintf (buf, sizeof(buf) - 1, "capture_%u", chn+1);
544
545 port = jack_port_register (client, buf,
546 JACK_DEFAULT_AUDIO_TYPE,
547 port_flags, 0);
548
549 if (!port)
550 {
551 printf( "jacknet_client: cannot register port for %s", buf);
552 break;
553 }
554
555 capture_srcs = jack_slist_append( capture_srcs, src_new( 4-samplerate_quality, 1, NULL ) );
556 capture_ports = jack_slist_append (capture_ports, port);
557 }
558
559 port_flags = JackPortIsInput;
560
561 playback_ports = NULL;
562 for (chn = 0; chn < n_playback; chn++)
563 {
564 snprintf (buf, sizeof(buf) - 1, "playback_%u", chn+1);
565
566 port = jack_port_register (client, buf,
567 JACK_DEFAULT_AUDIO_TYPE,
568 port_flags, 0);
569
570 if (!port)
571 {
572 printf( "jacknet_client: cannot register port for %s", buf);
573 break;
574 }
575
576 playback_srcs = jack_slist_append( playback_srcs, src_new( 4-samplerate_quality, 1, NULL ) );
577 playback_ports = jack_slist_append (playback_ports, port);
578 }
579 }
580
581 /**
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.
585 */
586
jack_shutdown(void * arg)587 void jack_shutdown (void *arg) {
588
589 exit (1);
590 }
591
592 /**
593 * be user friendly.
594 * be user friendly.
595 * be user friendly.
596 */
597
printUsage()598 void printUsage() {
599 fprintf(stderr, "usage: alsa_out [options]\n"
600 "\n"
601 " -j <jack name> - client name\n"
602 " -S <server name> - server to connect\n"
603 " -d <alsa_device> \n"
604 " -c <channels> \n"
605 " -p <period_size> \n"
606 " -n <num_period> \n"
607 " -r <sample_rate> \n"
608 " -q <sample_rate quality [0..4]\n"
609 " -m <max_diff> \n"
610 " -t <target_delay> \n"
611 " -i turns on instrumentation\n"
612 " -v turns on printouts\n"
613 "\n");
614 }
615
616
617 /**
618 * the main function....
619 */
620
621 void
sigterm_handler(int signal)622 sigterm_handler( int signal )
623 {
624 quit = 1;
625 }
626
627
main(int argc,char * argv[])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;
632 int jack_opts = 0;
633
634 extern char *optarg;
635 extern int optind, optopt;
636 int errflg=0;
637 int c;
638
639 while ((c = getopt(argc, argv, "ivj:r:c:p:n:d:q:m:t:f:F:C:Q:s:S:")) != -1) {
640 switch(c) {
641 case 'j':
642 strcpy(jack_name,optarg);
643 break;
644 case 'r':
645 sample_rate = atoi(optarg);
646 break;
647 case 'c':
648 num_channels = atoi(optarg);
649 break;
650 case 'p':
651 period_size = atoi(optarg);
652 break;
653 case 'n':
654 num_periods = atoi(optarg);
655 break;
656 case 'd':
657 strcpy(alsa_device,optarg);
658 break;
659 case 't':
660 target_delay = atoi(optarg);
661 break;
662 case 'q':
663 samplerate_quality = atoi(optarg);
664 break;
665 case 'm':
666 max_diff = atoi(optarg);
667 break;
668 case 'f':
669 catch_factor = atoi(optarg);
670 break;
671 case 'F':
672 catch_factor2 = atoi(optarg);
673 break;
674 case 'C':
675 pclamp = (double) atoi(optarg);
676 break;
677 case 'Q':
678 controlquant = (double) atoi(optarg);
679 break;
680 case 'v':
681 verbose = 1;
682 break;
683 case 'i':
684 instrument = 1;
685 break;
686 case 's':
687 smooth_size = atoi(optarg);
688 break;
689 case 'S':
690 server_name = optarg;
691 jack_opts |= JackServerName;
692 break;
693 case ':':
694 fprintf(stderr,
695 "Option -%c requires an operand\n", optopt);
696 errflg++;
697 break;
698 case '?':
699 fprintf(stderr,
700 "Unrecognized option: -%c\n", optopt);
701 errflg++;
702 }
703 }
704 if (errflg) {
705 printUsage();
706 exit(2);
707 }
708
709 if( (samplerate_quality < 0) || (samplerate_quality > 4) ) {
710 fprintf (stderr, "invalid samplerate quality\n");
711 return 1;
712 }
713 if ((client = jack_client_open (jack_name, jack_opts, NULL, server_name)) == 0) {
714 fprintf (stderr, "jack server not running?\n");
715 return 1;
716 }
717
718 /* tell the JACK server to call `process()' whenever
719 there is work to be done.
720 */
721
722 jack_set_process_callback (client, process, 0);
723
724 /* tell the JACK server to call `freewheel()' whenever
725 freewheel mode changes.
726 */
727
728 jack_set_freewheel_callback (client, freewheel, 0);
729
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.
733 */
734
735 jack_on_shutdown (client, jack_shutdown, 0);
736
737 if (jack_set_latency_callback)
738 jack_set_latency_callback (client, latency_cb, 0);
739
740 // get jack sample_rate
741
742 jack_sample_rate = jack_get_sample_rate( client );
743
744 if( !sample_rate )
745 sample_rate = jack_sample_rate;
746
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 )
750 exit(20);
751
752 printf( "selected sample format: %s\n", formats[format].name );
753
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;
758
759 offset_array = malloc( sizeof(double) * smooth_size );
760 if( offset_array == NULL ) {
761 fprintf( stderr, "no memory for offset_array !!!\n" );
762 exit(20);
763 }
764 window_array = malloc( sizeof(double) * smooth_size );
765 if( window_array == NULL ) {
766 fprintf( stderr, "no memory for window_array !!!\n" );
767 exit(20);
768 }
769 int i;
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) );
773 }
774
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...
777 if( !target_delay )
778 target_delay = (num_periods*period_size / 2) + jack_buffer_size/2;
779
780 if( !max_diff )
781 max_diff = num_periods*period_size - target_delay ;
782
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 );
785 exit(20);
786 }
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 );
789 exit(20);
790 }
791 // alloc input ports, which are blasted out to alsa...
792 alloc_ports( num_channels, 0 );
793
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 );
797
798 if ((outbuf == NULL) || (resampbuf == NULL) || (tmpbuf == NULL))
799 {
800 fprintf( stderr, "no memory for buffers.\n" );
801 exit(20);
802 }
803
804 memset( tmpbuf, 0, 512 * formats[format].sample_size * num_channels);
805
806 /* tell the JACK server that we are ready to roll */
807
808 if (jack_activate (client)) {
809 fprintf (stderr, "cannot activate client");
810 return 1;
811 }
812
813 signal( SIGTERM, sigterm_handler );
814 signal( SIGINT, sigterm_handler );
815
816 if( verbose ) {
817 while(!quit) {
818 usleep(500000);
819 if( output_new_delay ) {
820 printf( "delay = %d\n", output_new_delay );
821 output_new_delay = 0;
822 }
823 printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor, output_diff, output_offset );
824 }
825 } else if( instrument ) {
826 printf( "# n\tresamp\tdiff\toffseti\tintegral\n");
827 int n=0;
828 while(!quit) {
829 usleep(1000);
830 printf( "%d\t%f\t%f\t%f\t%f\n", n++, output_resampling_factor, output_diff, output_offset, output_integral );
831 }
832 } else {
833 while(!quit)
834 {
835 usleep(500000);
836 if( output_new_delay ) {
837 printf( "delay = %d\n", output_new_delay );
838 output_new_delay = 0;
839 }
840 }
841 }
842
843 jack_deactivate( client );
844 jack_client_close (client);
845 exit (0);
846 }
847