jack1 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.

566 lines
15KB

  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 <alloca.h>
  12. #include <math.h>
  13. #include <jack/jack.h>
  14. #include <jack/jslist.h>
  15. #define ALSA_PCM_OLD_HW_PARAMS_API
  16. #define ALSA_PCM_OLD_SW_PARAMS_API
  17. #include "alsa/asoundlib.h"
  18. #include <samplerate.h>
  19. typedef signed short ALSASAMPLE;
  20. // Here are the lists of the jack ports...
  21. JSList *capture_ports = NULL;
  22. JSList *capture_srcs = NULL;
  23. JSList *playback_ports = NULL;
  24. JSList *playback_srcs = NULL;
  25. jack_client_t *client;
  26. // TODO: make the sample format configurable soon...
  27. snd_pcm_format_t format = SND_PCM_FORMAT_S16; /* sample format */
  28. snd_pcm_t *alsa_handle;
  29. int jack_sample_rate;
  30. double current_resample_factor = 1.0;
  31. // ------------------------------------------------------ commandline parameters
  32. int sample_rate = 0; /* stream rate */
  33. int num_channels = 2; /* count of channels */
  34. int period_size = 1024;
  35. int num_periods = 2;
  36. int target_delay = 0; /* the delay which the program should try to approach. */
  37. int max_diff = 0; /* the diff value, when a hard readpointer skip should occur */
  38. int catch_factor = 1000;
  39. // Debug stuff:
  40. int print_counter = 10;
  41. // Alsa stuff... i dont want to touch this bullshit in the next years.... please...
  42. static int xrun_recovery(snd_pcm_t *handle, int err) {
  43. //printf( "xrun !!!....\n" );
  44. if (err == -EPIPE) { /* under-run */
  45. err = snd_pcm_prepare(handle);
  46. if (err < 0)
  47. printf("Can't recovery from underrun, prepare failed: %s\n", snd_strerror(err));
  48. return 0;
  49. } else if (err == -ESTRPIPE) {
  50. while ((err = snd_pcm_resume(handle)) == -EAGAIN)
  51. sleep(1); /* wait until the suspend flag is released */
  52. if (err < 0) {
  53. err = snd_pcm_prepare(handle);
  54. if (err < 0)
  55. printf("Can't recovery from suspend, prepare failed: %s\n", snd_strerror(err));
  56. }
  57. return 0;
  58. }
  59. return err;
  60. }
  61. 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 ) {
  62. int err, dir=0;
  63. /* choose all parameters */
  64. err = snd_pcm_hw_params_any(handle, params);
  65. if (err < 0) {
  66. printf("Broken configuration for playback: no configurations available: %s\n", snd_strerror(err));
  67. return err;
  68. }
  69. /* set the interleaved read/write format */
  70. err = snd_pcm_hw_params_set_access(handle, params, access);
  71. if (err < 0) {
  72. printf("Access type not available for playback: %s\n", snd_strerror(err));
  73. return err;
  74. }
  75. /* set the sample format */
  76. err = snd_pcm_hw_params_set_format(handle, params, format);
  77. if (err < 0) {
  78. printf("Sample format not available for playback: %s\n", snd_strerror(err));
  79. return err;
  80. }
  81. /* set the count of channels */
  82. err = snd_pcm_hw_params_set_channels(handle, params, channels);
  83. if (err < 0) {
  84. printf("Channels count (%i) not available for record: %s\n", channels, snd_strerror(err));
  85. return err;
  86. }
  87. /* set the stream rate */
  88. err = snd_pcm_hw_params_set_rate_near(handle, params, rate, 0);
  89. if (err < 0) {
  90. printf("Rate %iHz not available for capture: %s\n", rate, snd_strerror(err));
  91. return err;
  92. }
  93. if (err != rate) {
  94. printf("Rate doesn't match (requested %iHz, get %iHz)\n", rate, err);
  95. return -EINVAL;
  96. }
  97. /* set the buffer time */
  98. err = snd_pcm_hw_params_set_buffer_time_near(handle, params, 1000000*period*nperiods/rate, &dir);
  99. if (err < 0) {
  100. printf("Unable to set buffer time %i for playback: %s\n", 1000000*period*nperiods/rate, snd_strerror(err));
  101. return err;
  102. }
  103. if( snd_pcm_hw_params_get_buffer_size(params) != nperiods * period ) {
  104. printf( "WARNING: buffer size does not match: (requested %d, got %d)\n", nperiods * period, (int) snd_pcm_hw_params_get_buffer_size(params) );
  105. }
  106. /* set the period time */
  107. err = snd_pcm_hw_params_set_period_time_near(handle, params, 1000000*period/rate, &dir);
  108. if (err < 0) {
  109. printf("Unable to set period time %i for playback: %s\n", 1000000*period/rate, snd_strerror(err));
  110. return err;
  111. }
  112. int ps = snd_pcm_hw_params_get_period_size(params, NULL );
  113. if( ps != period ) {
  114. printf( "WARNING: period size does not match: (requested %i, got %i)\n", period, ps );
  115. }
  116. /* write the parameters to device */
  117. err = snd_pcm_hw_params(handle, params);
  118. if (err < 0) {
  119. printf("Unable to set hw params for playback: %s\n", snd_strerror(err));
  120. return err;
  121. }
  122. return 0;
  123. }
  124. static int set_swparams(snd_pcm_t *handle, snd_pcm_sw_params_t *swparams, int period) {
  125. int err;
  126. /* get the current swparams */
  127. err = snd_pcm_sw_params_current(handle, swparams);
  128. if (err < 0) {
  129. printf("Unable to determine current swparams for capture: %s\n", snd_strerror(err));
  130. return err;
  131. }
  132. /* start the transfer when the buffer is full */
  133. err = snd_pcm_sw_params_set_start_threshold(handle, swparams, period );
  134. if (err < 0) {
  135. printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
  136. return err;
  137. }
  138. err = snd_pcm_sw_params_set_stop_threshold(handle, swparams, -1 );
  139. if (err < 0) {
  140. printf("Unable to set start threshold mode for capture: %s\n", snd_strerror(err));
  141. return err;
  142. }
  143. /* allow the transfer when at least period_size samples can be processed */
  144. err = snd_pcm_sw_params_set_avail_min(handle, swparams, period );
  145. if (err < 0) {
  146. printf("Unable to set avail min for capture: %s\n", snd_strerror(err));
  147. return err;
  148. }
  149. /* align all transfers to 1 sample */
  150. err = snd_pcm_sw_params_set_xfer_align(handle, swparams, 1);
  151. if (err < 0) {
  152. printf("Unable to set transfer align for capture: %s\n", snd_strerror(err));
  153. return err;
  154. }
  155. /* write the parameters to the playback device */
  156. err = snd_pcm_sw_params(handle, swparams);
  157. if (err < 0) {
  158. printf("Unable to set sw params for capture: %s\n", snd_strerror(err));
  159. return err;
  160. }
  161. return 0;
  162. }
  163. // ok... i only need this function to communicate with the alsa bloat api...
  164. static snd_pcm_t *open_audiofd( char *device_name, int capture, int rate, int channels, int period, int nperiods ) {
  165. int err;
  166. snd_pcm_t *handle;
  167. snd_pcm_hw_params_t *hwparams;
  168. snd_pcm_sw_params_t *swparams;
  169. snd_pcm_hw_params_alloca(&hwparams);
  170. snd_pcm_sw_params_alloca(&swparams);
  171. if ((err = snd_pcm_open(&(handle), device_name, capture ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK )) < 0) {
  172. printf("Capture open error: %s\n", snd_strerror(err));
  173. return NULL;
  174. }
  175. if ((err = set_hwparams(handle, hwparams,SND_PCM_ACCESS_RW_INTERLEAVED, rate, channels, period, nperiods )) < 0) {
  176. printf("Setting of hwparams failed: %s\n", snd_strerror(err));
  177. return NULL;
  178. }
  179. if ((err = set_swparams(handle, swparams, period)) < 0) {
  180. printf("Setting of swparams failed: %s\n", snd_strerror(err));
  181. return NULL;
  182. }
  183. snd_pcm_start( handle );
  184. snd_pcm_wait( handle, 200 );
  185. return handle;
  186. }
  187. /**
  188. * The process callback for this JACK application.
  189. * It is called by JACK at the appropriate times.
  190. */
  191. int process (jack_nframes_t nframes, void *arg) {
  192. ALSASAMPLE *outbuf;
  193. float *floatbuf, *resampbuf;
  194. int rlen;
  195. int err;
  196. snd_pcm_sframes_t delay;
  197. int put_back_samples=0;
  198. snd_pcm_delay( alsa_handle, &delay );
  199. delay = delay;
  200. // Do it the hard way.
  201. // this is for compensating xruns etc...
  202. if( delay > (target_delay+max_diff) ) {
  203. ALSASAMPLE *tmp = alloca( (delay-target_delay) * sizeof( ALSASAMPLE ) * num_channels );
  204. snd_pcm_readi( alsa_handle, tmp, delay-target_delay );
  205. printf( "delay = %d\n", (int) delay );
  206. delay = target_delay;
  207. // XXX: at least set it to that value.
  208. current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
  209. }
  210. if( delay < (target_delay-max_diff) ) {
  211. snd_pcm_rewind( alsa_handle, target_delay - delay );
  212. printf( "delay = %d\n", (int) delay );
  213. delay = target_delay;
  214. // XXX: at least set it to that value.
  215. current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
  216. }
  217. /* ok... now we should have target_delay +- max_diff on the alsa side.
  218. *
  219. * calculate the number of frames, we want to get.
  220. */
  221. // float resamp_rate = (float)jack_sample_rate / (float)sample_rate; // == nframes / alsa_samples.
  222. // float request_samples = nframes / resamp_rate; //== alsa_samples;
  223. //float offset = delay - target_delay;
  224. //float frlen = request_samples + offset / catch_factor;
  225. //rlen = ceil( frlen );
  226. // This is the code from the alsa_out...
  227. double resamp_rate = (double)jack_sample_rate / (double)sample_rate; // == nframes / alsa_samples.
  228. double request_samples = nframes / resamp_rate; //== alsa_samples;
  229. double offset = delay - target_delay;
  230. //double frlen = request_samples - offset / catch_factor;
  231. double frlen = request_samples + offset;
  232. //alsa_out.c: double compute_factor = frlen / (double) nframes;
  233. double compute_factor = (double) nframes / frlen;
  234. double diff_value = pow(current_resample_factor - compute_factor, 3) / (double) catch_factor;
  235. current_resample_factor -= diff_value;
  236. rlen = ceil( ((double)nframes) / current_resample_factor )+2;
  237. if( (print_counter--) == 0 ) {
  238. print_counter = 10;
  239. printf( "res: %f, \tdiff = %f, \toffset = %f \n", (float)current_resample_factor, (float)diff_value, (float) offset );
  240. }
  241. /*
  242. * now this should do it...
  243. */
  244. outbuf = alloca( rlen * sizeof( ALSASAMPLE ) * num_channels );
  245. floatbuf = alloca( rlen * sizeof( float ) );
  246. resampbuf = alloca( nframes * sizeof( float ) );
  247. // get the data...
  248. again:
  249. err = snd_pcm_readi(alsa_handle, outbuf, rlen);
  250. if( err < 0 ) {
  251. printf( "err = %d\n", err );
  252. if (xrun_recovery(alsa_handle, err) < 0) {
  253. //printf("Write error: %s\n", snd_strerror(err));
  254. //exit(EXIT_FAILURE);
  255. }
  256. goto again;
  257. }
  258. if( err != rlen ) {
  259. printf( "read = %d\n", rlen );
  260. }
  261. /*
  262. * render jack ports to the outbuf...
  263. */
  264. int chn = 0;
  265. JSList *node = capture_ports;
  266. JSList *src_node = capture_srcs;
  267. while ( node != NULL)
  268. {
  269. int i;
  270. jack_port_t *port = (jack_port_t *) node->data;
  271. float *buf = jack_port_get_buffer (port, nframes);
  272. SRC_STATE *src_state = src_node->data;
  273. SRC_DATA src;
  274. for (i=0; i < rlen; i++) {
  275. resampbuf[i] = (float) outbuf[chn+ i*num_channels] / 32767;
  276. }
  277. src.data_in = resampbuf;
  278. src.input_frames = rlen;
  279. src.data_out = buf;
  280. src.output_frames = nframes;
  281. src.end_of_input = 0;
  282. //src.src_ratio = (float) nframes / frlen;
  283. src.src_ratio = current_resample_factor;
  284. //src_set_ratio( src_state, src.src_ratio );
  285. src_process( src_state, &src );
  286. put_back_samples = rlen-src.input_frames_used;
  287. if( src.output_frames_gen != nframes )
  288. printf( "did not fill jack_buffer...\n" );
  289. src_node = jack_slist_next (src_node);
  290. node = jack_slist_next (node);
  291. chn++;
  292. }
  293. //printf( "putback = %d\n", put_back_samples );
  294. snd_pcm_rewind( alsa_handle, put_back_samples );
  295. return 0;
  296. }
  297. /**
  298. * Allocate the necessary jack ports...
  299. */
  300. void alloc_ports( int n_capture, int n_playback ) {
  301. int port_flags = JackPortIsOutput;
  302. int chn;
  303. jack_port_t *port;
  304. char buf[32];
  305. capture_ports = NULL;
  306. for (chn = 0; chn < n_capture; chn++)
  307. {
  308. snprintf (buf, sizeof(buf) - 1, "capture_%u", chn+1);
  309. port = jack_port_register (client, buf,
  310. JACK_DEFAULT_AUDIO_TYPE,
  311. port_flags, 0);
  312. if (!port)
  313. {
  314. printf( "jacknet_client: cannot register port for %s", buf);
  315. break;
  316. }
  317. capture_srcs = jack_slist_append( capture_srcs, src_new( SRC_SINC_FASTEST, 1, NULL ) );
  318. capture_ports = jack_slist_append (capture_ports, port);
  319. }
  320. port_flags = JackPortIsInput;
  321. playback_ports = NULL;
  322. for (chn = 0; chn < n_playback; chn++)
  323. {
  324. snprintf (buf, sizeof(buf) - 1, "playback_%u", chn+1);
  325. port = jack_port_register (client, buf,
  326. JACK_DEFAULT_AUDIO_TYPE,
  327. port_flags, 0);
  328. if (!port)
  329. {
  330. printf( "jacknet_client: cannot register port for %s", buf);
  331. break;
  332. }
  333. playback_srcs = jack_slist_append( playback_srcs, src_new( SRC_SINC_FASTEST, 1, NULL ) );
  334. playback_ports = jack_slist_append (playback_ports, port);
  335. }
  336. }
  337. /**
  338. * This is the shutdown callback for this JACK application.
  339. * It is called by JACK if the server ever shuts down or
  340. * decides to disconnect the client.
  341. */
  342. void jack_shutdown (void *arg) {
  343. exit (1);
  344. }
  345. /**
  346. * be user friendly.
  347. * be user friendly.
  348. * be user friendly.
  349. */
  350. void printUsage() {
  351. fprintf(stderr, "usage: alsa_out [options]\n"
  352. "\n"
  353. " -j <jack name> - reports a different name to jack\n"
  354. " -d <alsa_device> \n"
  355. " -c <channels> \n"
  356. " -p <period_size> \n"
  357. " -n <num_period> \n"
  358. " -r <sample_rate> \n"
  359. " -m <max_diff> \n"
  360. " -t <target_delay> \n"
  361. " -f <catch_factor> \n"
  362. "\n");
  363. }
  364. /**
  365. * the main function....
  366. */
  367. int main (int argc, char *argv[]) {
  368. char jack_name[30] = "alsa_in";
  369. char alsa_device[30] = "hw:0";
  370. extern char *optarg;
  371. extern int optind, optopt;
  372. int errflg=0;
  373. int c;
  374. while ((c = getopt(argc, argv, ":j:r:c:p:n:d:m:t:f:")) != -1) {
  375. switch(c) {
  376. case 'j':
  377. strcpy(jack_name,optarg);
  378. break;
  379. case 'r':
  380. sample_rate = atoi(optarg);
  381. break;
  382. case 'c':
  383. num_channels = atoi(optarg);
  384. break;
  385. case 'p':
  386. period_size = atoi(optarg);
  387. break;
  388. case 'n':
  389. num_periods = atoi(optarg);
  390. break;
  391. case 'd':
  392. strcpy(alsa_device,optarg);
  393. break;
  394. case 't':
  395. target_delay = atoi(optarg);
  396. break;
  397. case 'm':
  398. max_diff = atoi(optarg);
  399. break;
  400. case 'f':
  401. catch_factor = atoi(optarg);
  402. break;
  403. case ':':
  404. fprintf(stderr,
  405. "Option -%c requires an operand\n", optopt);
  406. errflg++;
  407. break;
  408. case '?':
  409. fprintf(stderr,
  410. "Unrecognized option: -%c\n", optopt);
  411. errflg++;
  412. }
  413. }
  414. if (errflg) {
  415. printUsage();
  416. exit(2);
  417. }
  418. // Setup target delay and max_diff for the normal user, who does not play with them...
  419. if( !target_delay )
  420. target_delay = num_periods*period_size / 2;
  421. if( !max_diff )
  422. max_diff = period_size / 2;
  423. if ((client = jack_client_new (jack_name)) == 0) {
  424. fprintf (stderr, "jack server not running?\n");
  425. return 1;
  426. }
  427. /* tell the JACK server to call `process()' whenever
  428. there is work to be done.
  429. */
  430. jack_set_process_callback (client, process, 0);
  431. /* tell the JACK server to call `jack_shutdown()' if
  432. it ever shuts down, either entirely, or if it
  433. just decides to stop calling us.
  434. */
  435. jack_on_shutdown (client, jack_shutdown, 0);
  436. // alloc input ports, which are blasted out to alsa...
  437. alloc_ports( num_channels, 0 );
  438. // get jack sample_rate
  439. jack_sample_rate = jack_get_sample_rate( client );
  440. if( !sample_rate )
  441. sample_rate = jack_sample_rate;
  442. current_resample_factor = (double) jack_sample_rate / (double) sample_rate;
  443. //// now open the alsa fd...
  444. alsa_handle = open_audiofd( alsa_device, 1, sample_rate, num_channels, period_size, num_periods);
  445. if( alsa_handle < 0 )
  446. exit(20);
  447. /* tell the JACK server that we are ready to roll */
  448. if (jack_activate (client)) {
  449. fprintf (stderr, "cannot activate client");
  450. return 1;
  451. }
  452. while(1) sleep(1);
  453. jack_client_close (client);
  454. exit (0);
  455. }