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.

834 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 recovery 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 recovery 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("Rate doesn't match (requested %iHz, get %iHz)\n", rate, rrate);
  160. return -EINVAL;
  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, int nperiods) {
  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, 1 );
  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, nperiods)) < 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. int num_null_samples = nperiods * period * channels;
  262. char *tmp = alloca( num_null_samples * formats[format].sample_size );
  263. memset( tmp, 0, num_null_samples * formats[format].sample_size );
  264. snd_pcm_writei( handle, tmp, num_null_samples );
  265. return handle;
  266. }
  267. double hann( double x )
  268. {
  269. return 0.5 * (1.0 - cos( 2*M_PI * x ) );
  270. }
  271. /**
  272. * The freewheel callback.
  273. */
  274. void freewheel (int starting, void* arg) {
  275. running_freewheel = starting;
  276. }
  277. /**
  278. * The process callback for this JACK application.
  279. * It is called by JACK at the appropriate times.
  280. */
  281. int process (jack_nframes_t nframes, void *arg) {
  282. if (running_freewheel) {
  283. JSList *node = playback_ports;
  284. while ( node != NULL)
  285. {
  286. jack_port_t *port = (jack_port_t *) node->data;
  287. float *buf = jack_port_get_buffer (port, nframes);
  288. memset(buf, 0, sizeof(float)*nframes);
  289. node = jack_slist_next (node);
  290. }
  291. return 0;
  292. }
  293. int rlen;
  294. int err;
  295. snd_pcm_sframes_t delay = target_delay;
  296. int i;
  297. delay = (num_periods*period_size)-snd_pcm_avail( alsa_handle ) ;
  298. delay -= jack_frames_since_cycle_start( client );
  299. // Do it the hard way.
  300. // this is for compensating xruns etc...
  301. if( delay > (target_delay+max_diff) ) {
  302. snd_pcm_rewind( alsa_handle, delay - target_delay );
  303. output_new_delay = (int) delay;
  304. delay = target_delay;
  305. // Set the resample_rate... we need to adjust the offset integral, to do this.
  306. // first look at the PI controller, this code is just a special case, which should never execute once
  307. // everything is swung in.
  308. offset_integral = - (resample_mean - static_resample_factor) * catch_factor * catch_factor2;
  309. // Also clear the array. we are beginning a new control cycle.
  310. for( i=0; i<smooth_size; i++ )
  311. offset_array[i] = 0.0;
  312. }
  313. if( delay < (target_delay-max_diff) ) {
  314. output_new_delay = (int) delay;
  315. while ((target_delay-delay) > 0) {
  316. snd_pcm_uframes_t to_write = ((target_delay-delay) > 512) ? 512 : (target_delay-delay);
  317. snd_pcm_writei( alsa_handle, tmpbuf, to_write );
  318. delay += to_write;
  319. }
  320. delay = target_delay;
  321. // Set the resample_rate... we need to adjust the offset integral, to do this.
  322. offset_integral = - (resample_mean - static_resample_factor) * catch_factor * catch_factor2;
  323. // Also clear the array. we are beginning a new control cycle.
  324. for( i=0; i<smooth_size; i++ )
  325. offset_array[i] = 0.0;
  326. }
  327. /* ok... now we should have target_delay +- max_diff on the alsa side.
  328. *
  329. * calculate the number of frames, we want to get.
  330. */
  331. double offset = delay - target_delay;
  332. // Save offset.
  333. offset_array[(offset_differential_index++)% smooth_size ] = offset;
  334. // Build the mean of the windowed offset array
  335. // basically fir lowpassing.
  336. double smooth_offset = 0.0;
  337. for( i=0; i<smooth_size; i++ )
  338. smooth_offset +=
  339. offset_array[ (i + offset_differential_index-1) % smooth_size] * window_array[i];
  340. smooth_offset /= (double) smooth_size;
  341. // this is the integral of the smoothed_offset
  342. offset_integral += smooth_offset;
  343. // Clamp offset.
  344. // the smooth offset still contains unwanted noise
  345. // which would go straigth onto the resample coeff.
  346. // it only used in the P component and the I component is used for the fine tuning anyways.
  347. if( fabs( smooth_offset ) < pclamp )
  348. smooth_offset = 0.0;
  349. // ok. now this is the PI controller.
  350. // u(t) = K * ( e(t) + 1/T \int e(t') dt' )
  351. // K = 1/catch_factor and T = catch_factor2
  352. double current_resample_factor = static_resample_factor - smooth_offset / (double) catch_factor - offset_integral / (double) catch_factor / (double)catch_factor2;
  353. // now quantize this value around resample_mean, so that the noise which is in the integral component doesnt hurt.
  354. current_resample_factor = floor( (current_resample_factor - resample_mean) * controlquant + 0.5 ) / controlquant + resample_mean;
  355. // Output "instrumentatio" gonna change that to real instrumentation in a few.
  356. output_resampling_factor = (float) current_resample_factor;
  357. output_diff = (float) smooth_offset;
  358. output_integral = (float) offset_integral;
  359. output_offset = (float) offset;
  360. // Clamp a bit.
  361. if( current_resample_factor < resample_lower_limit ) current_resample_factor = resample_lower_limit;
  362. if( current_resample_factor > resample_upper_limit ) current_resample_factor = resample_upper_limit;
  363. // Now Calculate how many samples we need.
  364. rlen = ceil( ((double)nframes) * current_resample_factor )+2;
  365. assert( rlen > 2 );
  366. // Calculate resample_mean so we can init ourselves to saner values.
  367. resample_mean = 0.9999 * resample_mean + 0.0001 * current_resample_factor;
  368. /*
  369. * now this should do it...
  370. */
  371. outbuf = alloca( rlen * formats[format].sample_size * num_channels );
  372. resampbuf = alloca( rlen * sizeof( float ) );
  373. /*
  374. * render jack ports to the outbuf...
  375. */
  376. int chn = 0;
  377. JSList *node = playback_ports;
  378. JSList *src_node = playback_srcs;
  379. SRC_DATA src;
  380. while ( node != NULL)
  381. {
  382. jack_port_t *port = (jack_port_t *) node->data;
  383. float *buf = jack_port_get_buffer (port, nframes);
  384. SRC_STATE *src_state = src_node->data;
  385. src.data_in = buf;
  386. src.input_frames = nframes;
  387. src.data_out = resampbuf;
  388. src.output_frames = rlen;
  389. src.end_of_input = 0;
  390. src.src_ratio = current_resample_factor;
  391. src_process( src_state, &src );
  392. formats[format].jack_to_soundcard( outbuf + format[formats].sample_size * chn, resampbuf, src.output_frames_gen, num_channels*format[formats].sample_size, NULL);
  393. src_node = jack_slist_next (src_node);
  394. node = jack_slist_next (node);
  395. chn++;
  396. }
  397. // now write the output...
  398. again:
  399. err = snd_pcm_writei(alsa_handle, outbuf, src.output_frames_gen);
  400. //err = snd_pcm_writei(alsa_handle, outbuf, src.output_frames_gen);
  401. if( err < 0 ) {
  402. printf( "err = %d\n", err );
  403. if (xrun_recovery(alsa_handle, err) < 0) {
  404. printf("Write error: %s\n", snd_strerror(err));
  405. exit(EXIT_FAILURE);
  406. }
  407. goto again;
  408. }
  409. return 0;
  410. }
  411. /**
  412. * the latency callback.
  413. * sets up the latencies on the ports.
  414. */
  415. void
  416. latency_cb (jack_latency_callback_mode_t mode, void *arg)
  417. {
  418. jack_latency_range_t range;
  419. JSList *node;
  420. range.min = range.max = target_delay;
  421. if (mode == JackCaptureLatency) {
  422. for (node = capture_ports; node; node = jack_slist_next (node)) {
  423. jack_port_t *port = node->data;
  424. jack_port_set_latency_range (port, mode, &range);
  425. }
  426. } else {
  427. for (node = playback_ports; node; node = jack_slist_next (node)) {
  428. jack_port_t *port = node->data;
  429. jack_port_set_latency_range (port, mode, &range);
  430. }
  431. }
  432. }
  433. /**
  434. * Allocate the necessary jack ports...
  435. */
  436. void alloc_ports( int n_capture, int n_playback ) {
  437. int port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
  438. int chn;
  439. jack_port_t *port;
  440. char buf[32];
  441. capture_ports = NULL;
  442. for (chn = 0; chn < n_capture; chn++)
  443. {
  444. snprintf (buf, sizeof(buf) - 1, "capture_%u", chn+1);
  445. port = jack_port_register (client, buf,
  446. JACK_DEFAULT_AUDIO_TYPE,
  447. port_flags, 0);
  448. if (!port)
  449. {
  450. printf( "jacknet_client: cannot register port for %s", buf);
  451. break;
  452. }
  453. capture_srcs = jack_slist_append( capture_srcs, src_new( 4-samplerate_quality, 1, NULL ) );
  454. capture_ports = jack_slist_append (capture_ports, port);
  455. }
  456. port_flags = JackPortIsInput;
  457. playback_ports = NULL;
  458. for (chn = 0; chn < n_playback; chn++)
  459. {
  460. snprintf (buf, sizeof(buf) - 1, "playback_%u", chn+1);
  461. port = jack_port_register (client, buf,
  462. JACK_DEFAULT_AUDIO_TYPE,
  463. port_flags, 0);
  464. if (!port)
  465. {
  466. printf( "jacknet_client: cannot register port for %s", buf);
  467. break;
  468. }
  469. playback_srcs = jack_slist_append( playback_srcs, src_new( 4-samplerate_quality, 1, NULL ) );
  470. playback_ports = jack_slist_append (playback_ports, port);
  471. }
  472. }
  473. /**
  474. * This is the shutdown callback for this JACK application.
  475. * It is called by JACK if the server ever shuts down or
  476. * decides to disconnect the client.
  477. */
  478. void jack_shutdown (void *arg) {
  479. exit (1);
  480. }
  481. /**
  482. * be user friendly.
  483. * be user friendly.
  484. * be user friendly.
  485. */
  486. void printUsage() {
  487. fprintf(stderr, "usage: alsa_out [options]\n"
  488. "\n"
  489. " -j <jack name> - client name\n"
  490. " -d <alsa_device> \n"
  491. " -c <channels> \n"
  492. " -p <period_size> \n"
  493. " -n <num_period> \n"
  494. " -r <sample_rate> \n"
  495. " -q <sample_rate quality [0..4]\n"
  496. " -m <max_diff> \n"
  497. " -t <target_delay> \n"
  498. " -i turns on instrumentation\n"
  499. " -v turns on printouts\n"
  500. "\n");
  501. }
  502. /**
  503. * the main function....
  504. */
  505. void
  506. sigterm_handler( int signal )
  507. {
  508. quit = 1;
  509. }
  510. int main (int argc, char *argv[]) {
  511. char jack_name[30] = "alsa_out";
  512. char alsa_device[30] = "hw:0";
  513. extern char *optarg;
  514. extern int optind, optopt;
  515. int errflg=0;
  516. int c;
  517. while ((c = getopt(argc, argv, "ivj:r:c:p:n:d:q:m:t:f:F:C:Q:s:")) != -1) {
  518. switch(c) {
  519. case 'j':
  520. strcpy(jack_name,optarg);
  521. break;
  522. case 'r':
  523. sample_rate = atoi(optarg);
  524. break;
  525. case 'c':
  526. num_channels = atoi(optarg);
  527. break;
  528. case 'p':
  529. period_size = atoi(optarg);
  530. break;
  531. case 'n':
  532. num_periods = atoi(optarg);
  533. break;
  534. case 'd':
  535. strcpy(alsa_device,optarg);
  536. break;
  537. case 't':
  538. target_delay = atoi(optarg);
  539. break;
  540. case 'q':
  541. samplerate_quality = atoi(optarg);
  542. break;
  543. case 'm':
  544. max_diff = atoi(optarg);
  545. break;
  546. case 'f':
  547. catch_factor = atoi(optarg);
  548. break;
  549. case 'F':
  550. catch_factor2 = atoi(optarg);
  551. break;
  552. case 'C':
  553. pclamp = (double) atoi(optarg);
  554. break;
  555. case 'Q':
  556. controlquant = (double) atoi(optarg);
  557. break;
  558. case 'v':
  559. verbose = 1;
  560. break;
  561. case 'i':
  562. instrument = 1;
  563. break;
  564. case 's':
  565. smooth_size = atoi(optarg);
  566. break;
  567. case ':':
  568. fprintf(stderr,
  569. "Option -%c requires an operand\n", optopt);
  570. errflg++;
  571. break;
  572. case '?':
  573. fprintf(stderr,
  574. "Unrecognized option: -%c\n", optopt);
  575. errflg++;
  576. }
  577. }
  578. if (errflg) {
  579. printUsage();
  580. exit(2);
  581. }
  582. if( (samplerate_quality < 0) || (samplerate_quality > 4) ) {
  583. fprintf (stderr, "invalid samplerate quality\n");
  584. return 1;
  585. }
  586. if ((client = jack_client_open (jack_name, 0, NULL)) == 0) {
  587. fprintf (stderr, "jack server not running?\n");
  588. return 1;
  589. }
  590. /* tell the JACK server to call `process()' whenever
  591. there is work to be done.
  592. */
  593. jack_set_process_callback (client, process, 0);
  594. /* tell the JACK server to call `freewheel()' whenever
  595. freewheel mode changes.
  596. */
  597. jack_set_freewheel_callback (client, freewheel, 0);
  598. /* tell the JACK server to call `jack_shutdown()' if
  599. it ever shuts down, either entirely, or if it
  600. just decides to stop calling us.
  601. */
  602. jack_on_shutdown (client, jack_shutdown, 0);
  603. if (jack_set_latency_callback)
  604. jack_set_latency_callback (client, latency_cb, 0);
  605. // get jack sample_rate
  606. jack_sample_rate = jack_get_sample_rate( client );
  607. if( !sample_rate )
  608. sample_rate = jack_sample_rate;
  609. static_resample_factor = (double) sample_rate / (double) jack_sample_rate;
  610. resample_lower_limit = static_resample_factor * 0.25;
  611. resample_upper_limit = static_resample_factor * 4.0;
  612. resample_mean = static_resample_factor;
  613. offset_array = malloc( sizeof(double) * smooth_size );
  614. if( offset_array == NULL ) {
  615. fprintf( stderr, "no memory for offset_array !!!\n" );
  616. exit(20);
  617. }
  618. window_array = malloc( sizeof(double) * smooth_size );
  619. if( window_array == NULL ) {
  620. fprintf( stderr, "no memory for window_array !!!\n" );
  621. exit(20);
  622. }
  623. int i;
  624. for( i=0; i<smooth_size; i++ ) {
  625. offset_array[i] = 0.0;
  626. window_array[i] = hann( (double) i / ((double) smooth_size - 1.0) );
  627. }
  628. jack_buffer_size = jack_get_buffer_size( client );
  629. // Setup target delay and max_diff for the normal user, who does not play with them...
  630. if( !target_delay )
  631. target_delay = (num_periods*period_size / 2) - jack_buffer_size/2;
  632. if( !max_diff )
  633. max_diff = target_delay;
  634. if( max_diff > target_delay ) {
  635. fprintf( stderr, "target_delay (%d) cant be smaller than max_diff(%d)\n", target_delay, max_diff );
  636. exit(20);
  637. }
  638. if( (target_delay+max_diff) > (num_periods*period_size) ) {
  639. fprintf( stderr, "target_delay+max_diff (%d) cant be bigger than buffersize(%d)\n", target_delay+max_diff, num_periods*period_size );
  640. exit(20);
  641. }
  642. // now open the alsa fd...
  643. alsa_handle = open_audiofd( alsa_device, 0, sample_rate, num_channels, period_size, num_periods);
  644. if( alsa_handle == 0 )
  645. exit(20);
  646. printf( "selected sample format: %s\n", formats[format].name );
  647. // alloc input ports, which are blasted out to alsa...
  648. alloc_ports( 0, num_channels );
  649. outbuf = malloc( num_periods * period_size * formats[format].sample_size * num_channels );
  650. resampbuf = malloc( num_periods * period_size * sizeof( float ) );
  651. tmpbuf = malloc( 512 * formats[format].sample_size * num_channels );
  652. if ((outbuf == NULL) || (resampbuf == NULL) || (tmpbuf == NULL))
  653. {
  654. fprintf( stderr, "no memory for buffers.\n" );
  655. exit(20);
  656. }
  657. /* tell the JACK server that we are ready to roll */
  658. if (jack_activate (client)) {
  659. fprintf (stderr, "cannot activate client");
  660. return 1;
  661. }
  662. signal( SIGTERM, sigterm_handler );
  663. signal( SIGINT, sigterm_handler );
  664. if( verbose ) {
  665. while(!quit) {
  666. usleep(500000);
  667. if( output_new_delay ) {
  668. printf( "delay = %d\n", output_new_delay );
  669. output_new_delay = 0;
  670. }
  671. printf( "res: %f, \tdiff = %f, \toffset = %f \n", output_resampling_factor, output_diff, output_offset );
  672. }
  673. } else if( instrument ) {
  674. printf( "# n\tresamp\tdiff\toffseti\tintegral\n");
  675. int n=0;
  676. while(!quit) {
  677. usleep(1000);
  678. printf( "%d\t%f\t%f\t%f\t%f\n", n++, output_resampling_factor, output_diff, output_offset, output_integral );
  679. }
  680. } else {
  681. while(!quit)
  682. {
  683. usleep(500000);
  684. if( output_new_delay ) {
  685. printf( "delay = %d\n", output_new_delay );
  686. output_new_delay = 0;
  687. }
  688. }
  689. }
  690. jack_deactivate( client );
  691. jack_client_close (client);
  692. exit (0);
  693. }