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.

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