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