jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

804 lines
23KB

  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. #include <stdio.h>
  7. #include <errno.h>
  8. #include <unistd.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <signal.h>
  12. #include <math.h>
  13. #include <jack/jack.h>
  14. #include <jack/jslist.h>
  15. #include <jack/memops.h>
  16. #include "alsa/asoundlib.h"
  17. #include <samplerate.h>
  18. // Here are the lists of the jack ports...
  19. JSList *capture_ports = NULL;
  20. JSList *capture_srcs = NULL;
  21. JSList *playback_ports = NULL;
  22. JSList *playback_srcs = NULL;
  23. jack_client_t *client;
  24. snd_pcm_t *alsa_handle;
  25. int jack_sample_rate;
  26. int jack_buffer_size;
  27. int quit = 0;
  28. double resample_mean = 1.0;
  29. double static_resample_factor = 1.0;
  30. double resample_lower_limit = 0.25;
  31. double resample_upper_limit = 4.0;
  32. double *offset_array;
  33. double *window_array;
  34. int offset_differential_index = 0;
  35. double offset_integral = 0;
  36. // ------------------------------------------------------ commandline parameters
  37. int sample_rate = 0; /* stream rate */
  38. int num_channels = 2; /* count of channels */
  39. int period_size = 1024;
  40. int num_periods = 2;
  41. int target_delay = 0; /* the delay which the program should try to approach. */
  42. int max_diff = 0; /* the diff value, when a hard readpointer skip should occur */
  43. int catch_factor = 100000;
  44. int catch_factor2 = 10000;
  45. double pclamp = 15.0;
  46. double controlquant = 10000.0;
  47. int smooth_size = 256;
  48. int good_window=0;
  49. int verbose = 0;
  50. int instrument = 0;
  51. int samplerate_quality = 2;
  52. // Debug stuff:
  53. volatile float output_resampling_factor = 1.0;
  54. volatile int output_new_delay = 0;
  55. volatile float output_offset = 0.0;
  56. volatile float output_integral = 0.0;
  57. volatile float output_diff = 0.0;
  58. snd_pcm_uframes_t real_buffer_size;
  59. snd_pcm_uframes_t real_period_size;
  60. // buffers
  61. char *tmpbuf;
  62. char *outbuf;
  63. float *resampbuf;
  64. // format selection, and corresponding functions from memops in a nice set of structs.
  65. typedef struct alsa_format {
  66. snd_pcm_format_t format_id;
  67. size_t sample_size;
  68. void (*jack_to_soundcard) (char *dst, jack_default_audio_sample_t *src, unsigned long nsamples, unsigned long dst_skip, dither_state_t *state);
  69. void (*soundcard_to_jack) (jack_default_audio_sample_t *dst, char *src, unsigned long nsamples, unsigned long src_skip);
  70. const char *name;
  71. } alsa_format_t;
  72. alsa_format_t formats[] = {
  73. { SND_PCM_FORMAT_FLOAT_LE, 4, sample_move_dS_floatLE, sample_move_floatLE_sSs, "float" },
  74. { SND_PCM_FORMAT_S32, 4, sample_move_d32u24_sS, sample_move_dS_s32u24, "32bit" },
  75. { SND_PCM_FORMAT_S24_3LE, 3, sample_move_d24_sS, sample_move_dS_s24, "24bit - real" },
  76. { SND_PCM_FORMAT_S24, 4, sample_move_d24_sS, sample_move_dS_s24, "24bit" },
  77. { SND_PCM_FORMAT_S16, 2, sample_move_d16_sS, sample_move_dS_s16, "16bit" }
  78. };
  79. #define NUMFORMATS (sizeof(formats)/sizeof(formats[0]))
  80. int format=0;
  81. // Alsa stuff... i dont want to touch this bullshit in the next years.... please...
  82. static int xrun_recovery(snd_pcm_t *handle, int err) {
  83. // printf( "xrun !!!.... %d\n", err );
  84. if (err == -EPIPE) { /* under-run */
  85. err = snd_pcm_prepare(handle);
  86. if (err < 0)
  87. printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err));
  88. return 0;
  89. } else if (err == -EAGAIN) {
  90. while ((err = snd_pcm_resume(handle)) == -EAGAIN)
  91. usleep(100); /* wait until the suspend flag is released */
  92. if (err < 0) {
  93. err = snd_pcm_prepare(handle);
  94. if (err < 0)
  95. printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err));
  96. }
  97. return 0;
  98. }
  99. return err;
  100. }
  101. static int set_hwformat( snd_pcm_t *handle, snd_pcm_hw_params_t *params )
  102. {
  103. int i;
  104. int err;
  105. for( i=0; i<NUMFORMATS; i++ ) {
  106. /* set the sample format */
  107. err = snd_pcm_hw_params_set_format(handle, params, formats[i].format_id);
  108. if (err == 0) {
  109. format = i;
  110. return 0;
  111. }
  112. }
  113. return err;
  114. }
  115. 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 ) {
  116. int err, dir=0;
  117. unsigned int buffer_time;
  118. unsigned int period_time;
  119. unsigned int rrate;
  120. unsigned int rchannels;
  121. /* choose all parameters */
  122. err = snd_pcm_hw_params_any(handle, params);
  123. if (err < 0) {
  124. printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
  125. return err;
  126. }
  127. /* set the interleaved read/write format */
  128. err = snd_pcm_hw_params_set_access(handle, params, access);
  129. if (err < 0) {
  130. printf("Access type not available for playback: %s\n", snd_strerror(err));
  131. return err;
  132. }
  133. /* set the sample format */
  134. err = set_hwformat(handle, params);
  135. if (err < 0) {
  136. printf("Sample format not available for playback: %s\n", snd_strerror(err));
  137. return err;
  138. }
  139. /* set the count of channels */
  140. rchannels = channels;
  141. err = snd_pcm_hw_params_set_channels_near(handle, params, &rchannels);
  142. if (err < 0) {
  143. printf("Channels count (%i) not available for record: %s\n", channels, snd_strerror(err));
  144. return err;
  145. }
  146. if (rchannels != channels) {
  147. printf("WARNING: chennel count does not match (requested %d got %d)\n", channels, rchannels);
  148. num_channels = rchannels;
  149. }
  150. /* set the stream rate */
  151. rrate = rate;
  152. err = snd_pcm_hw_params_set_rate_near(handle, params, &rrate, 0);
  153. if (err < 0) {
  154. printf("Rate %iHz not available for playback: %s\n", rate, snd_strerror(err));
  155. return err;
  156. }
  157. if (rrate != rate) {
  158. printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate, rrate);
  159. return -EINVAL;
  160. }
  161. /* set the buffer time */
  162. buffer_time = 1000000*(uint64_t)period*nperiods/rate;
  163. err = snd_pcm_hw_params_set_buffer_time_near(handle, params, &buffer_time, &dir);
  164. if (err < 0) {
  165. printf("Unable to set buffer time %i for playback: %s\n", 1000000*period*nperiods/rate, snd_strerror(err));
  166. return err;
  167. }
  168. err = snd_pcm_hw_params_get_buffer_size( params, &real_buffer_size );
  169. if (err < 0) {
  170. printf("Unable to get buffer size back: %s\n", snd_strerror(err));
  171. return err;
  172. }
  173. if( real_buffer_size != nperiods * period ) {
  174. printf( "WARNING: buffer size does not match: (requested %d, got %d)\n", nperiods * period, (int) real_buffer_size );
  175. }
  176. /* set the period time */
  177. period_time = 1000000*(uint64_t)period/rate;
  178. err = snd_pcm_hw_params_set_period_time_near(handle, params, &period_time, &dir);
  179. if (err < 0) {
  180. printf("Unable to set period time %i for playback: %s\n", 1000000*period/rate, snd_strerror(err));
  181. return err;
  182. }
  183. err = snd_pcm_hw_params_get_period_size(params, &real_period_size, NULL );
  184. if (err < 0) {
  185. printf("Unable to get period size back: %s\n", snd_strerror(err));
  186. return err;
  187. }
  188. if( real_period_size != period ) {
  189. printf( "WARNING: period size does not match: (requested %i, got %i)\n", period, (int)real_period_size );
  190. }
  191. /* write the parameters to device */
  192. err = snd_pcm_hw_params(handle, params);
  193. if (err < 0) {
  194. printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
  195. return err;
  196. }
  197. return 0;
  198. }
  199. static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams, int period, int nperiods) {
  200. int err;
  201. /* get the current swparams */
  202. err = snd_pcm_sw_params_current(handle, swparams);
  203. if (err < 0) {
  204. printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err));
  205. return err;
  206. }
  207. /* start the transfer when the buffer is full */
  208. err = snd_pcm_sw_params_set_start_threshold(handle, swparams, period );
  209. if (err < 0) {
  210. printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
  211. return err;
  212. }
  213. err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, -1 );
  214. if (err < 0) {
  215. printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
  216. return err;
  217. }
  218. /* allow the transfer when at least period_size samples can be processed */
  219. err = snd_pcm_sw_params_set_avail_min(handle, swparams, 1 );
  220. if (err < 0) {
  221. printf("Unable to set avail min for capture: %s\n", snd_strerror(err));
  222. return err;
  223. }
  224. /* align all transfers to 1 sample */
  225. err = snd_pcm_sw_params_set_xfer_align(handle, swparams, 1);
  226. if (err < 0) {
  227. printf("Unable to set transfer align for capture: %s\n", snd_strerror(err));
  228. return err;
  229. }
  230. /* write the parameters to the playback device */
  231. err = snd_pcm_sw_params(handle, swparams);
  232. if (err < 0) {
  233. printf("Unable to set sw params for capture: %s\n", snd_strerror(err));
  234. return err;
  235. }
  236. return 0;
  237. }
  238. // ok... i only need this function to communicate with the alsa bloat api...
  239. static snd_pcm_t *open_audiofd( char *device_name, int capture, int rate, int channels, int period, int nperiods ) {
  240. int err;
  241. snd_pcm_t *handle;
  242. snd_pcm_hw_params_t *hwparams;
  243. snd_pcm_sw_params_t *swparams;
  244. snd_pcm_hw_params_alloca(&hwparams);
  245. snd_pcm_sw_params_alloca(&swparams);
  246. if ((err = snd_pcm_open(&(handle), device_name, capture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK )) < 0) {
  247. printf("Capture open error: %s\n", snd_strerror(err));
  248. return NULL;
  249. }
  250. if ((err = set_hwparams(handle, hwparams,SND_PCM_ACCESS_RW_INTERLEAVED, rate, channels, period, nperiods )) < 0) {
  251. printf("Setting of hwparams failed: %s\n", snd_strerror(err));
  252. return NULL;
  253. }
  254. if ((err = set_swparams(handle, swparams, period, nperiods)) < 0) {
  255. printf("Setting of swparams failed: %s\n", snd_strerror(err));
  256. return NULL;
  257. }
  258. //snd_pcm_start( handle );
  259. //snd_pcm_wait( handle, 200 );
  260. int num_null_samples = nperiods * period * channels;
  261. char *tmp = alloca( num_null_samples * formats[format].sample_size );
  262. memset( tmp, 0, num_null_samples * formats[format].sample_size );
  263. snd_pcm_writei( handle, tmp, num_null_samples );
  264. return handle;
  265. }
  266. double hann( double x )
  267. {
  268. return 0.5 * (1.0 - cos( 2*M_PI * x ) );
  269. }
  270. /**
  271. * The process callback for this JACK application.
  272. * It is called by JACK at the appropriate times.
  273. */
  274. int process (jack_nframes_t nframes, void *arg) {
  275. int rlen;
  276. int err;
  277. snd_pcm_sframes_t delay = target_delay;
  278. int i;
  279. delay = (num_periods*period_size)-snd_pcm_avail( alsa_handle ) ;
  280. delay -= jack_frames_since_cycle_start( client );
  281. // Do it the hard way.
  282. // this is for compensating xruns etc...
  283. if( delay > (target_delay+max_diff) ) {
  284. snd_pcm_rewind( alsa_handle, delay - target_delay );
  285. output_new_delay = (int) delay;
  286. delay = target_delay;
  287. // Set the resample_rate... we need to adjust the offset integral, to do this.
  288. // first look at the PI controller, this code is just a special case, which should never execute once
  289. // everything is swung in.
  290. offset_integral = - (resample_mean - static_resample_factor) * catch_factor * catch_factor2;
  291. // Also clear the array. we are beginning a new control cycle.
  292. for( i=0; i<smooth_size; i++ )
  293. offset_array[i] = 0.0;
  294. }
  295. if( delay < (target_delay-max_diff) ) {
  296. output_new_delay = (int) delay;
  297. while ((target_delay-delay) > 0) {
  298. snd_pcm_uframes_t to_write = ((target_delay-delay) > 512) ? 512 : (target_delay-delay);
  299. snd_pcm_writei( alsa_handle, tmpbuf, to_write );
  300. delay += to_write;
  301. }
  302. delay = target_delay;
  303. // Set the resample_rate... we need to adjust the offset integral, to do this.
  304. offset_integral = - (resample_mean - static_resample_factor) * catch_factor * catch_factor2;
  305. // Also clear the array. we are beginning a new control cycle.
  306. for( i=0; i<smooth_size; i++ )
  307. offset_array[i] = 0.0;
  308. }
  309. /* ok... now we should have target_delay +- max_diff on the alsa side.
  310. *
  311. * calculate the number of frames, we want to get.
  312. */
  313. double offset = delay - target_delay;
  314. // Save offset.
  315. offset_array[(offset_differential_index++)% smooth_size ] = offset;
  316. // Build the mean of the windowed offset array
  317. // basically fir lowpassing.
  318. double smooth_offset = 0.0;
  319. for( i=0; i<smooth_size; i++ )
  320. smooth_offset +=
  321. offset_array[ (i + offset_differential_index-1) % smooth_size] * window_array[i];
  322. smooth_offset /= (double) smooth_size;
  323. // this is the integral of the smoothed_offset
  324. offset_integral += smooth_offset;
  325. // Clamp offset.
  326. // the smooth offset still contains unwanted noise
  327. // which would go straigth onto the resample coeff.
  328. // it only used in the P component and the I component is used for the fine tuning anyways.
  329. if( fabs( smooth_offset ) < pclamp )
  330. smooth_offset = 0.0;
  331. // ok. now this is the PI controller.
  332. // u(t) = K * ( e(t) + 1/T \int e(t') dt' )
  333. // K = 1/catch_factor and T = catch_factor2
  334. double current_resample_factor = static_resample_factor - smooth_offset / (double) catch_factor - offset_integral / (double) catch_factor / (double)catch_factor2;
  335. // now quantize this value around resample_mean, so that the noise which is in the integral component doesnt hurt.
  336. current_resample_factor = floor( (current_resample_factor - resample_mean) * controlquant + 0.5 ) / controlquant + resample_mean;
  337. // Output "instrumentatio" gonna change that to real instrumentation in a few.
  338. output_resampling_factor = (float) current_resample_factor;
  339. output_diff = (float) smooth_offset;
  340. output_integral = (float) offset_integral;
  341. output_offset = (float) offset;
  342. // Clamp a bit.
  343. if( current_resample_factor < resample_lower_limit ) current_resample_factor = resample_lower_limit;
  344. if( current_resample_factor > resample_upper_limit ) current_resample_factor = resample_upper_limit;
  345. // Now Calculate how many samples we need.
  346. rlen = ceil( ((double)nframes) * current_resample_factor )+2;
  347. assert( rlen > 2 );
  348. // Calculate resample_mean so we can init ourselves to saner values.
  349. resample_mean = 0.9999 * resample_mean + 0.0001 * current_resample_factor;
  350. /*
  351. * now this should do it...
  352. */
  353. outbuf = alloca( rlen * formats[format].sample_size * num_channels );
  354. resampbuf = alloca( rlen * sizeof( float ) );
  355. /*
  356. * render jack ports to the outbuf...
  357. */
  358. int chn = 0;
  359. JSList *node = playback_ports;
  360. JSList *src_node = playback_srcs;
  361. SRC_DATA src;
  362. while ( node != NULL)
  363. {
  364. jack_port_t *port = (jack_port_t *) node->data;
  365. float *buf = jack_port_get_buffer (port, nframes);
  366. SRC_STATE *src_state = src_node->data;
  367. src.data_in = buf;
  368. src.input_frames = nframes;
  369. src.data_out = resampbuf;
  370. src.output_frames = rlen;
  371. src.end_of_input = 0;
  372. src.src_ratio = current_resample_factor;
  373. src_process( src_state, &src );
  374. formats[format].jack_to_soundcard( outbuf + format[formats].sample_size * chn, resampbuf, src.output_frames_gen, num_channels*format[formats].sample_size, NULL);
  375. src_node = jack_slist_next (src_node);
  376. node = jack_slist_next (node);
  377. chn++;
  378. }
  379. // now write the output...
  380. again:
  381. err = snd_pcm_writei(alsa_handle, outbuf, src.output_frames_gen);
  382. //err = snd_pcm_writei(alsa_handle, outbuf, src.output_frames_gen);
  383. if( err < 0 ) {
  384. printf( "err = %d\n", err );
  385. if (xrun_recovery(alsa_handle, err) < 0) {
  386. printf("Write error: %s\n", snd_strerror(err));
  387. exit(EXIT_FAILURE);
  388. }
  389. goto again;
  390. }
  391. return 0;
  392. }
  393. /**
  394. * the latency callback.
  395. * sets up the latencies on the ports.
  396. */
  397. void
  398. latency_cb (jack_latency_callback_mode_t mode, void *arg)
  399. {
  400. jack_latency_range_t range;
  401. JSList *node;
  402. range.min = range.max = target_delay;
  403. if (mode == JackCaptureLatency) {
  404. for (node = capture_ports; node; node = jack_slist_next (node)) {
  405. jack_port_t *port = node->data;
  406. jack_port_set_latency_range (port, mode, &range);
  407. }
  408. } else {
  409. for (node = playback_ports; node; node = jack_slist_next (node)) {
  410. jack_port_t *port = node->data;
  411. jack_port_set_latency_range (port, mode, &range);
  412. }
  413. }
  414. }
  415. /**
  416. * Allocate the necessary jack ports...
  417. */
  418. void alloc_ports( int n_capture, int n_playback ) {
  419. int port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
  420. int chn;
  421. jack_port_t *port;
  422. char buf[32];
  423. capture_ports = NULL;
  424. for (chn = 0; chn < n_capture; chn++)
  425. {
  426. snprintf (buf, sizeof(buf) - 1, "capture_%u", chn+1);
  427. port = jack_port_register (client, buf,
  428. JACK_DEFAULT_AUDIO_TYPE,
  429. port_flags, 0);
  430. if (!port)
  431. {
  432. printf( "jacknet_client: cannot register port for %s", buf);
  433. break;
  434. }
  435. capture_srcs = jack_slist_append( capture_srcs, src_new( 4-samplerate_quality, 1, NULL ) );
  436. capture_ports = jack_slist_append (capture_ports, port);
  437. }
  438. port_flags = JackPortIsInput;
  439. playback_ports = NULL;
  440. for (chn = 0; chn < n_playback; chn++)
  441. {
  442. snprintf (buf, sizeof(buf) - 1, "playback_%u", chn+1);
  443. port = jack_port_register (client, buf,
  444. JACK_DEFAULT_AUDIO_TYPE,
  445. port_flags, 0);
  446. if (!port)
  447. {
  448. printf( "jacknet_client: cannot register port for %s", buf);
  449. break;
  450. }
  451. playback_srcs = jack_slist_append( playback_srcs, src_new( 4-samplerate_quality, 1, NULL ) );
  452. playback_ports = jack_slist_append (playback_ports, port);
  453. }
  454. }
  455. /**
  456. * This is the shutdown callback for this JACK application.
  457. * It is called by JACK if the server ever shuts down or
  458. * decides to disconnect the client.
  459. */
  460. void jack_shutdown (void *arg) {
  461. exit (1);
  462. }
  463. /**
  464. * be user friendly.
  465. * be user friendly.
  466. * be user friendly.
  467. */
  468. void printUsage() {
  469. fprintf(stderr, "usage: alsa_out [options]\n"
  470. "\n"
  471. " -j <jack name> - client name\n"
  472. " -d <alsa_device> \n"
  473. " -c <channels> \n"
  474. " -p <period_size> \n"
  475. " -n <num_period> \n"
  476. " -r <sample_rate> \n"
  477. " -q <sample_rate quality [0..4]\n"
  478. " -m <max_diff> \n"
  479. " -t <target_delay> \n"
  480. " -i turns on instrumentation\n"
  481. " -v turns on printouts\n"
  482. "\n");
  483. }
  484. /**
  485. * the main function....
  486. */
  487. void
  488. sigterm_handler( int signal )
  489. {
  490. quit = 1;
  491. }
  492. int main (int argc, char *argv[]) {
  493. char jack_name[30] = "alsa_out";
  494. char alsa_device[30] = "hw:0";
  495. extern char *optarg;
  496. extern int optind, optopt;
  497. int errflg=0;
  498. int c;
  499. while ((c = getopt(argc, argv, "ivj:r:c:p:n:d:q:m:t:f:F:C:Q:s:")) != -1) {
  500. switch(c) {
  501. case 'j':
  502. strcpy(jack_name,optarg);
  503. break;
  504. case 'r':
  505. sample_rate = atoi(optarg);
  506. break;
  507. case 'c':
  508. num_channels = atoi(optarg);
  509. break;
  510. case 'p':
  511. period_size = atoi(optarg);
  512. break;
  513. case 'n':
  514. num_periods = atoi(optarg);
  515. break;
  516. case 'd':
  517. strcpy(alsa_device,optarg);
  518. break;
  519. case 't':
  520. target_delay = atoi(optarg);
  521. break;
  522. case 'q':
  523. samplerate_quality = atoi(optarg);
  524. break;
  525. case 'm':
  526. max_diff = atoi(optarg);
  527. break;
  528. case 'f':
  529. catch_factor = atoi(optarg);
  530. break;
  531. case 'F':
  532. catch_factor2 = atoi(optarg);
  533. break;
  534. case 'C':
  535. pclamp = (double) atoi(optarg);
  536. break;
  537. case 'Q':
  538. controlquant = (double) atoi(optarg);
  539. break;
  540. case 'v':
  541. verbose = 1;
  542. break;
  543. case 'i':
  544. instrument = 1;
  545. break;
  546. case 's':
  547. smooth_size = atoi(optarg);
  548. break;
  549. case ':':
  550. fprintf(stderr,
  551. "Option -%c requires an operand\n", optopt);
  552. errflg++;
  553. break;
  554. case '?':
  555. fprintf(stderr,
  556. "Unrecognized option: -%c\n", optopt);
  557. errflg++;
  558. }
  559. }
  560. if (errflg) {
  561. printUsage();
  562. exit(2);
  563. }
  564. if( (samplerate_quality < 0) || (samplerate_quality > 4) ) {
  565. fprintf (stderr, "invalid samplerate quality\n");
  566. return 1;
  567. }
  568. if ((client = jack_client_open (jack_name, 0, NULL)) == 0) {
  569. fprintf (stderr, "jack server not running?\n");
  570. return 1;
  571. }
  572. /* tell the JACK server to call `process()' whenever
  573. there is work to be done.
  574. */
  575. jack_set_process_callback (client, process, 0);
  576. /* tell the JACK server to call `jack_shutdown()' if
  577. it ever shuts down, either entirely, or if it
  578. just decides to stop calling us.
  579. */
  580. jack_on_shutdown (client, jack_shutdown, 0);
  581. if (jack_set_latency_callback)
  582. jack_set_latency_callback (client, latency_cb, 0);
  583. // get jack sample_rate
  584. jack_sample_rate = jack_get_sample_rate( client );
  585. if( !sample_rate )
  586. sample_rate = jack_sample_rate;
  587. static_resample_factor = (double) sample_rate / (double) jack_sample_rate;
  588. resample_lower_limit = static_resample_factor * 0.25;
  589. resample_upper_limit = static_resample_factor * 4.0;
  590. resample_mean = static_resample_factor;
  591. offset_array = malloc( sizeof(double) * smooth_size );
  592. if( offset_array == NULL ) {
  593. fprintf( stderr, "no memory for offset_array !!!\n" );
  594. exit(20);
  595. }
  596. window_array = malloc( sizeof(double) * smooth_size );
  597. if( window_array == NULL ) {
  598. fprintf( stderr, "no memory for window_array !!!\n" );
  599. exit(20);
  600. }
  601. int i;
  602. for( i=0; i<smooth_size; i++ ) {
  603. offset_array[i] = 0.0;
  604. window_array[i] = hann( (double) i / ((double) smooth_size - 1.0) );
  605. }
  606. jack_buffer_size = jack_get_buffer_size( client );
  607. // Setup target delay and max_diff for the normal user, who does not play with them...
  608. if( !target_delay )
  609. target_delay = (num_periods*period_size / 2) - jack_buffer_size/2;
  610. if( !max_diff )
  611. max_diff = target_delay;
  612. if( max_diff > target_delay ) {
  613. fprintf( stderr, "target_delay (%d) cant be smaller than max_diff(%d)\n", target_delay, max_diff );
  614. exit(20);
  615. }
  616. if( (target_delay+max_diff) > (num_periods*period_size) ) {
  617. fprintf( stderr, "target_delay+max_diff (%d) cant be bigger than buffersize(%d)\n", target_delay+max_diff, num_periods*period_size );
  618. exit(20);
  619. }
  620. // now open the alsa fd...
  621. alsa_handle = open_audiofd( alsa_device, 0, sample_rate, num_channels, period_size, num_periods);
  622. if( alsa_handle == 0 )
  623. exit(20);
  624. printf( "selected sample format: %s\n", formats[format].name );
  625. // alloc input ports, which are blasted out to alsa...
  626. alloc_ports( 0, num_channels );
  627. outbuf = malloc( num_periods * period_size * formats[format].sample_size * num_channels );
  628. resampbuf = malloc( num_periods * period_size * sizeof( float ) );
  629. tmpbuf = malloc( 512 * formats[format].sample_size * num_channels );
  630. if ((outbuf == NULL) || (resampbuf == NULL) || (tmpbuf == NULL))
  631. {
  632. fprintf( stderr, "no memory for buffers.\n" );
  633. exit(20);
  634. }
  635. /* tell the JACK server that we are ready to roll */
  636. if (jack_activate (client)) {
  637. fprintf (stderr, "cannot activate client");
  638. return 1;
  639. }
  640. signal( SIGTERM, sigterm_handler );
  641. signal( SIGINT, sigterm_handler );
  642. if( verbose ) {
  643. while(!quit) {
  644. usleep(500000);
  645. if( output_new_delay ) {
  646. printf( "delay = %d\n", output_new_delay );
  647. output_new_delay = 0;
  648. }
  649. printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor, output_diff, output_offset );
  650. }
  651. } else if( instrument ) {
  652. printf( "# n\tresamp\tdiff\toffseti\tintegral\n");
  653. int n=0;
  654. while(!quit) {
  655. usleep(1000);
  656. printf( "%d\t%f\t%f\t%f\t%f\n", n++, output_resampling_factor, output_diff, output_offset, output_integral );
  657. }
  658. } else {
  659. while(!quit)
  660. {
  661. usleep(500000);
  662. if( output_new_delay ) {
  663. printf( "delay = %d\n", output_new_delay );
  664. output_new_delay = 0;
  665. }
  666. }
  667. }
  668. jack_deactivate( client );
  669. jack_client_close (client);
  670. exit (0);
  671. }