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.

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