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.

843 lines
24KB

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