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.

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