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.

650 lines
20KB

  1. /*
  2. NetJack Client
  3. Copyright (C) 2008 Marc-Olivier Barre <marco@marcochapeau.org>
  4. Copyright (C) 2008 Pieter Palmers <pieterpalmers@users.sourceforge.net>
  5. Copyright (C) 2006 Torben Hohn <torbenh@gmx.de>
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. You should have received a copy of the GNU General Public License
  15. along with this program; if not, write to the Free Software
  16. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17. */
  18. /** @file netsource.c
  19. *
  20. * @brief This client connects a remote slave JACK to a local JACK server assumed to be the master
  21. */
  22. #include "config.h"
  23. #include <stdio.h>
  24. #include <errno.h>
  25. #include <unistd.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <netinet/in.h>
  29. #include <netdb.h>
  30. /* These two required by FreeBSD. */
  31. #include <sys/types.h>
  32. #include <sys/socket.h>
  33. #if HAVE_ALLOCA_H
  34. #include <alloca.h>
  35. #endif
  36. #include <jack/jack.h>
  37. #include <net_driver.h>
  38. #include <netjack_packet.h>
  39. #if HAVE_SAMPLERATE
  40. #include <samplerate.h>
  41. #endif
  42. #if HAVE_CELT
  43. #include <celt/celt.h>
  44. #endif
  45. #include <math.h>
  46. JSList *capture_ports = NULL;
  47. JSList *capture_srcs = NULL;
  48. int capture_channels = 0;
  49. int capture_channels_audio = 2;
  50. int capture_channels_midi = 1;
  51. JSList *playback_ports = NULL;
  52. JSList *playback_srcs = NULL;
  53. int playback_channels = 0;
  54. int playback_channels_audio = 2;
  55. int playback_channels_midi = 1;
  56. int dont_htonl_floats = 0;
  57. int latency = 5;
  58. jack_nframes_t factor = 1;
  59. int bitdepth = 0;
  60. int mtu = 1400;
  61. int reply_port = 0;
  62. int redundancy = 1;
  63. jack_client_t *client;
  64. int state_connected = 0;
  65. int state_latency = 0;
  66. int state_netxruns = 0;
  67. int state_currentframe = 0;
  68. int state_recv_packet_queue_time = 0;
  69. int outsockfd;
  70. int insockfd;
  71. struct sockaddr destaddr;
  72. struct sockaddr bindaddr;
  73. int sync_state;
  74. jack_transport_state_t last_transport_state;
  75. int framecnt = 0;
  76. int cont_miss = 0;
  77. /**
  78. * This Function allocates all the I/O Ports which are added the lists.
  79. */
  80. void
  81. alloc_ports (int n_capture_audio, int n_playback_audio, int n_capture_midi, int n_playback_midi)
  82. {
  83. int port_flags = JackPortIsOutput;
  84. int chn;
  85. jack_port_t *port;
  86. char buf[32];
  87. capture_ports = NULL;
  88. /* Allocate audio capture channels */
  89. for (chn = 0; chn < n_capture_audio; chn++)
  90. {
  91. snprintf (buf, sizeof (buf) - 1, "capture_%u", chn + 1);
  92. port = jack_port_register (client, buf, JACK_DEFAULT_AUDIO_TYPE, port_flags, 0);
  93. if (!port)
  94. {
  95. printf( "jack_netsource: cannot register %s port\n", buf);
  96. break;
  97. }
  98. if( bitdepth == 1000 ) {
  99. #if HAVE_CELT
  100. // XXX: memory leak
  101. CELTMode *celt_mode = celt_mode_create( jack_get_sample_rate( client ), 1, jack_get_buffer_size(client), NULL );
  102. capture_srcs = jack_slist_append(capture_srcs, celt_decoder_create( celt_mode ) );
  103. #endif
  104. } else {
  105. #if HAVE_SAMPLERATE
  106. capture_srcs = jack_slist_append (capture_srcs, src_new (SRC_LINEAR, 1, NULL));
  107. #endif
  108. }
  109. capture_ports = jack_slist_append (capture_ports, port);
  110. }
  111. /* Allocate midi capture channels */
  112. for (chn = n_capture_audio; chn < n_capture_midi + n_capture_audio; chn++)
  113. {
  114. snprintf (buf, sizeof (buf) - 1, "capture_%u", chn + 1);
  115. port = jack_port_register (client, buf, JACK_DEFAULT_MIDI_TYPE, port_flags, 0);
  116. if (!port)
  117. {
  118. printf ("jack_netsource: cannot register %s port\n", buf);
  119. break;
  120. }
  121. capture_ports = jack_slist_append(capture_ports, port);
  122. }
  123. /* Allocate audio playback channels */
  124. port_flags = JackPortIsInput;
  125. playback_ports = NULL;
  126. for (chn = 0; chn < n_playback_audio; chn++)
  127. {
  128. snprintf (buf, sizeof (buf) - 1, "playback_%u", chn + 1);
  129. port = jack_port_register (client, buf, JACK_DEFAULT_AUDIO_TYPE, port_flags, 0);
  130. if (!port)
  131. {
  132. printf ("jack_netsource: cannot register %s port\n", buf);
  133. break;
  134. }
  135. if( bitdepth == 1000 ) {
  136. #if HAVE_CELT
  137. // XXX: memory leak
  138. CELTMode *celt_mode = celt_mode_create( jack_get_sample_rate (client), 1, jack_get_buffer_size(client), NULL );
  139. playback_srcs = jack_slist_append(playback_srcs, celt_encoder_create( celt_mode ) );
  140. #endif
  141. } else {
  142. #if HAVE_SAMPLERATE
  143. playback_srcs = jack_slist_append (playback_srcs, src_new (SRC_LINEAR, 1, NULL));
  144. #endif
  145. }
  146. playback_ports = jack_slist_append (playback_ports, port);
  147. }
  148. /* Allocate midi playback channels */
  149. for (chn = n_playback_audio; chn < n_playback_midi + n_playback_audio; chn++)
  150. {
  151. snprintf (buf, sizeof (buf) - 1, "playback_%u", chn + 1);
  152. port = jack_port_register (client, buf, JACK_DEFAULT_MIDI_TYPE, port_flags, 0);
  153. if (!port)
  154. {
  155. printf ("jack_netsource: cannot register %s port\n", buf);
  156. break;
  157. }
  158. playback_ports = jack_slist_append (playback_ports, port);
  159. }
  160. }
  161. /**
  162. * The Sync callback... sync state is set elsewhere...
  163. * we will see if this is working correctly.
  164. * i dont really believe in it yet.
  165. */
  166. int
  167. sync_cb (jack_transport_state_t state, jack_position_t *pos, void *arg)
  168. {
  169. static int latency_count = 0;
  170. int retval = sync_state;
  171. if (latency_count) {
  172. latency_count--;
  173. retval = 0;
  174. }
  175. else if (state == JackTransportStarting && last_transport_state != JackTransportStarting)
  176. {
  177. retval = 0;
  178. latency_count = latency - 1;
  179. }
  180. last_transport_state = state;
  181. return retval;
  182. }
  183. int deadline_goodness=0;
  184. /**
  185. * The process callback for this JACK application.
  186. * It is called by JACK at the appropriate times.
  187. */
  188. int
  189. process (jack_nframes_t nframes, void *arg)
  190. {
  191. jack_nframes_t net_period;
  192. int rx_bufsize, tx_bufsize;
  193. jack_default_audio_sample_t *buf;
  194. jack_port_t *port;
  195. JSList *node;
  196. channel_t chn;
  197. int size, i;
  198. const char *porttype;
  199. int input_fd;
  200. jack_position_t local_trans_pos;
  201. uint32_t *packet_buf, *packet_bufX;
  202. jack_time_t packet_recv_timestamp;
  203. if( bitdepth == 1000 )
  204. net_period = factor;
  205. else
  206. net_period = (float) nframes / (float) factor;
  207. rx_bufsize = get_sample_size (bitdepth) * capture_channels * net_period + sizeof (jacknet_packet_header);
  208. tx_bufsize = get_sample_size (bitdepth) * playback_channels * net_period + sizeof (jacknet_packet_header);
  209. /* Allocate a buffer where both In and Out Buffer will fit */
  210. packet_buf = alloca ((rx_bufsize > tx_bufsize) ? rx_bufsize : tx_bufsize);
  211. jacknet_packet_header *pkthdr = (jacknet_packet_header *) packet_buf;
  212. /*
  213. * ok... SEND code first.
  214. * needed some time to find out why latency=0
  215. * did not work ;S
  216. *
  217. */
  218. /* reset packet_bufX... */
  219. packet_bufX = packet_buf + sizeof (jacknet_packet_header) / sizeof (jack_default_audio_sample_t);
  220. /* ---------- Send ---------- */
  221. render_jack_ports_to_payload (bitdepth, playback_ports, playback_srcs, nframes,
  222. packet_bufX, net_period, dont_htonl_floats);
  223. /* fill in packet hdr */
  224. pkthdr->transport_state = jack_transport_query (client, &local_trans_pos);
  225. pkthdr->transport_frame = local_trans_pos.frame;
  226. pkthdr->framecnt = framecnt;
  227. pkthdr->latency = latency;
  228. pkthdr->reply_port = reply_port;
  229. pkthdr->sample_rate = jack_get_sample_rate (client);
  230. pkthdr->period_size = nframes;
  231. /* playback for us is capture on the other side */
  232. pkthdr->capture_channels_audio = playback_channels_audio;
  233. pkthdr->playback_channels_audio = capture_channels_audio;
  234. pkthdr->capture_channels_midi = playback_channels_midi;
  235. pkthdr->playback_channels_midi = capture_channels_midi;
  236. pkthdr->mtu = mtu;
  237. pkthdr->sync_state = (jack_nframes_t)deadline_goodness;
  238. //printf("goodness=%d\n", deadline_goodness );
  239. packet_header_hton (pkthdr);
  240. if (cont_miss < 3*latency+5) {
  241. int r;
  242. for( r=0; r<redundancy; r++ )
  243. netjack_sendto (outsockfd, (char *) packet_buf, tx_bufsize, 0, &destaddr, sizeof (destaddr), mtu);
  244. }
  245. else if (cont_miss > 50+5*latency)
  246. {
  247. state_connected = 0;
  248. packet_cache_reset_master_address( global_packcache );
  249. //printf ("Frame %d \tRealy too many packets missed (%d). Let's reset the counter\n", framecnt, cont_miss);
  250. cont_miss = 0;
  251. }
  252. /*
  253. * ok... now the RECEIVE code.
  254. *
  255. */
  256. /* reset packet_bufX... */
  257. packet_bufX = packet_buf + sizeof (jacknet_packet_header) / sizeof (jack_default_audio_sample_t);
  258. if( reply_port )
  259. input_fd = insockfd;
  260. else
  261. input_fd = outsockfd;
  262. // for latency == 0 we can poll.
  263. if( latency == 0 ) {
  264. jack_time_t deadline = jack_get_time() + 1000000 * jack_get_buffer_size(client)/jack_get_sample_rate(client);
  265. // Now loop until we get the right packet.
  266. while(1) {
  267. if ( ! netjack_poll_deadline( input_fd, deadline ) )
  268. break;
  269. packet_cache_drain_socket(global_packcache, input_fd);
  270. if (packet_cache_get_next_available_framecnt( global_packcache, framecnt - latency, NULL ))
  271. break;
  272. }
  273. } else {
  274. // normally:
  275. // only drain socket.
  276. packet_cache_drain_socket(global_packcache, input_fd);
  277. }
  278. size = packet_cache_retreive_packet( global_packcache, framecnt - latency, (char *)packet_buf, rx_bufsize, &packet_recv_timestamp );
  279. /* First alternative : we received what we expected. Render the data
  280. * to the JACK ports so it can be played. */
  281. if (size == rx_bufsize)
  282. {
  283. // calculate how much time there would have been, if this packet was sent at the deadline.
  284. int recv_time_offset = (int) (jack_get_time() - packet_recv_timestamp);
  285. packet_header_ntoh (pkthdr);
  286. deadline_goodness = recv_time_offset - (int)pkthdr->latency;
  287. //printf( "deadline goodness = %d ---> off: %d\n", deadline_goodness, recv_time_offset );
  288. if (cont_miss)
  289. {
  290. //printf("Frame %d \tRecovered from dropouts\n", framecnt);
  291. cont_miss = 0;
  292. }
  293. render_payload_to_jack_ports (bitdepth, packet_bufX, net_period,
  294. capture_ports, capture_srcs, nframes, dont_htonl_floats);
  295. state_currentframe = framecnt;
  296. state_recv_packet_queue_time = recv_time_offset;
  297. state_connected = 1;
  298. sync_state = pkthdr->sync_state;
  299. }
  300. /* Second alternative : we've received something that's not
  301. * as big as expected or we missed a packet. We render silence
  302. * to the ouput ports */
  303. else
  304. {
  305. jack_nframes_t latency_estimate;
  306. if( packet_cache_find_latency( global_packcache, framecnt, &latency_estimate ) )
  307. //if( (state_latency == 0) || (latency_estimate < state_latency) )
  308. state_latency = latency_estimate;
  309. // Set the counters up.
  310. state_currentframe = framecnt;
  311. //state_latency = framecnt - pkthdr->framecnt;
  312. state_netxruns += 1;
  313. //printf ("Frame %d \tPacket missed or incomplete (expected: %d bytes, got: %d bytes)\n", framecnt, rx_bufsize, size);
  314. //printf ("Frame %d \tPacket missed or incomplete\n", framecnt);
  315. cont_miss += 1;
  316. chn = 0;
  317. node = capture_ports;
  318. while (node != NULL)
  319. {
  320. port = (jack_port_t *) node->data;
  321. buf = jack_port_get_buffer (port, nframes);
  322. porttype = jack_port_type (port);
  323. if (strncmp (porttype, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size ()) == 0)
  324. for (i = 0; i < nframes; i++)
  325. buf[i] = 0.0;
  326. else if (strncmp (porttype, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size ()) == 0)
  327. jack_midi_clear_buffer (buf);
  328. node = jack_slist_next (node);
  329. chn++;
  330. }
  331. }
  332. framecnt++;
  333. return 0;
  334. }
  335. /**
  336. * This is the shutdown callback for this JACK application.
  337. * It is called by JACK if the server ever shuts down or
  338. * decides to disconnect the client.
  339. */
  340. void
  341. jack_shutdown (void *arg)
  342. {
  343. exit (1);
  344. }
  345. void
  346. init_sockaddr_in (struct sockaddr_in *name , const char *hostname , uint16_t port)
  347. {
  348. name->sin_family = AF_INET ;
  349. name->sin_port = htons (port);
  350. if (hostname)
  351. {
  352. struct hostent *hostinfo = gethostbyname (hostname);
  353. if (hostinfo == NULL)
  354. fprintf (stderr, "init_sockaddr_in: unknown host: %s.\n", hostname);
  355. name->sin_addr = *(struct in_addr *) hostinfo->h_addr ;
  356. }
  357. else
  358. name->sin_addr.s_addr = htonl (INADDR_ANY) ;
  359. }
  360. void
  361. printUsage ()
  362. {
  363. fprintf (stderr, "usage: jack_netsource -h <host peer> [options]\n"
  364. "\n"
  365. " -n <jack name> - Reports a different name to jack\n"
  366. " -s <server name> - The name of the local jack server\n"
  367. " -h <host_peer> - Host name of the slave JACK\n"
  368. " -p <port> - UDP port used by the slave JACK\n"
  369. " -P <num channels> - Number of audio playback channels\n"
  370. " -C <num channels> - Number of audio capture channels\n"
  371. " -o <num channels> - Number of midi playback channels\n"
  372. " -i <num channels> - Number of midi capture channels\n"
  373. " -l <latency> - Network latency in number of NetJack frames\n"
  374. " -r <reply port> - Local UDP port to use\n"
  375. " -f <downsample ratio> - Downsample data in the wire by this factor\n"
  376. " -b <bitdepth> - Set transport to use 16bit or 8bit\n"
  377. " -m <mtu> - Assume this mtu for the link\n"
  378. " -c <bytes> - Use Celt and encode <bytes> per channel and packet.\n"
  379. " -R <N> - Send out packets N times.\n"
  380. "\n");
  381. }
  382. int
  383. main (int argc, char *argv[])
  384. {
  385. /* Some startup related basics */
  386. char *client_name, *server_name = NULL, *peer_ip;
  387. int peer_port = 3000;
  388. jack_options_t options = JackNullOption;
  389. jack_status_t status;
  390. /* Torben's famous state variables, aka "the reporting API" ! */
  391. /* heh ? these are only the copies of them ;) */
  392. int statecopy_connected, statecopy_latency, statecopy_netxruns;
  393. jack_nframes_t net_period;
  394. /* Argument parsing stuff */
  395. extern char *optarg;
  396. extern int optind, optopt;
  397. int errflg=0, c;
  398. if (argc < 3)
  399. {
  400. printUsage ();
  401. return 1;
  402. }
  403. client_name = (char *) malloc (sizeof (char) * 10);
  404. peer_ip = (char *) malloc (sizeof (char) * 10);
  405. sprintf(client_name, "netsource");
  406. sprintf(peer_ip, "localhost");
  407. while ((c = getopt (argc, argv, ":H:R:n:s:h:p:C:P:i:o:l:r:f:b:m:c:")) != -1)
  408. {
  409. switch (c)
  410. {
  411. case 'n':
  412. free(client_name);
  413. client_name = (char *) malloc (sizeof (char) * strlen (optarg)+1);
  414. strcpy (client_name, optarg);
  415. break;
  416. case 's':
  417. server_name = (char *) malloc (sizeof (char) * strlen (optarg)+1);
  418. strcpy (server_name, optarg);
  419. options |= JackServerName;
  420. break;
  421. case 'h':
  422. free(peer_ip);
  423. peer_ip = (char *) malloc (sizeof (char) * strlen (optarg)+1);
  424. strcpy (peer_ip, optarg);
  425. break;
  426. case 'p':
  427. peer_port = atoi (optarg);
  428. break;
  429. case 'P':
  430. playback_channels_audio = atoi (optarg);
  431. break;
  432. case 'C':
  433. capture_channels_audio = atoi (optarg);
  434. break;
  435. case 'o':
  436. playback_channels_midi = atoi (optarg);
  437. break;
  438. case 'i':
  439. capture_channels_midi = atoi (optarg);
  440. break;
  441. case 'l':
  442. latency = atoi (optarg);
  443. break;
  444. case 'r':
  445. reply_port = atoi (optarg);
  446. break;
  447. case 'f':
  448. factor = atoi (optarg);
  449. break;
  450. case 'b':
  451. bitdepth = atoi (optarg);
  452. break;
  453. case 'c':
  454. #if HAVE_CELT
  455. bitdepth = 1000;
  456. factor = atoi (optarg);
  457. #else
  458. printf( "not built with celt supprt\n" );
  459. exit(10);
  460. #endif
  461. break;
  462. case 'm':
  463. mtu = atoi (optarg);
  464. break;
  465. case 'R':
  466. redundancy = atoi (optarg);
  467. break;
  468. case 'H':
  469. dont_htonl_floats = atoi (optarg);
  470. break;
  471. case ':':
  472. fprintf (stderr, "Option -%c requires an operand\n", optopt);
  473. errflg++;
  474. break;
  475. case '?':
  476. fprintf (stderr, "Unrecognized option: -%c\n", optopt);
  477. errflg++;
  478. }
  479. }
  480. if (errflg)
  481. {
  482. printUsage ();
  483. exit (2);
  484. }
  485. capture_channels = capture_channels_audio + capture_channels_midi;
  486. playback_channels = playback_channels_audio + playback_channels_midi;
  487. outsockfd = socket (PF_INET, SOCK_DGRAM, 0);
  488. insockfd = socket (PF_INET, SOCK_DGRAM, 0);
  489. init_sockaddr_in ((struct sockaddr_in *) &destaddr, peer_ip, peer_port);
  490. if(reply_port)
  491. {
  492. init_sockaddr_in ((struct sockaddr_in *) &bindaddr, NULL, reply_port);
  493. bind (insockfd, &bindaddr, sizeof (bindaddr));
  494. }
  495. /* try to become a client of the JACK server */
  496. client = jack_client_open (client_name, options, &status, server_name);
  497. if (client == NULL)
  498. {
  499. fprintf (stderr, "jack_client_open() failed, status = 0x%2.0x\n"
  500. "Is the JACK server running ?\n", status);
  501. return 1;
  502. }
  503. /* Set up jack callbacks */
  504. jack_set_process_callback (client, process, 0);
  505. jack_set_sync_callback (client, sync_cb, 0);
  506. jack_on_shutdown (client, jack_shutdown, 0);
  507. alloc_ports (capture_channels_audio, playback_channels_audio, capture_channels_midi, playback_channels_midi);
  508. if( bitdepth == 1000 )
  509. net_period = factor;
  510. else
  511. net_period = ceilf((float) jack_get_buffer_size (client) / (float) factor);
  512. int rx_bufsize = get_sample_size (bitdepth) * capture_channels * net_period + sizeof (jacknet_packet_header);
  513. global_packcache = packet_cache_new (latency + 50, rx_bufsize, mtu);
  514. /* tell the JACK server that we are ready to roll */
  515. if (jack_activate (client))
  516. {
  517. fprintf (stderr, "Cannot activate client");
  518. return 1;
  519. }
  520. /* Now sleep forever... and evaluate the state_ vars */
  521. statecopy_connected = 2; // make it report unconnected on start.
  522. statecopy_latency = state_latency;
  523. statecopy_netxruns = state_netxruns;
  524. while (1)
  525. {
  526. sleep (1);
  527. if (statecopy_connected != state_connected)
  528. {
  529. statecopy_connected = state_connected;
  530. if (statecopy_connected)
  531. {
  532. state_netxruns = 1; // We want to reset the netxrun count on each new connection
  533. printf ("Connected :-)\n");
  534. }
  535. else
  536. printf ("Not Connected\n");
  537. fflush(stdout);
  538. }
  539. if (statecopy_connected)
  540. {
  541. if (statecopy_netxruns != state_netxruns) {
  542. statecopy_netxruns = state_netxruns;
  543. printf ("at frame %06d -> total netxruns %d (%d%%) queue time= %d\n", state_currentframe,
  544. statecopy_netxruns,
  545. 100*statecopy_netxruns/state_currentframe,
  546. state_recv_packet_queue_time);
  547. fflush(stdout);
  548. }
  549. }
  550. else
  551. {
  552. if (statecopy_latency != state_latency)
  553. {
  554. statecopy_latency = state_latency;
  555. if (statecopy_latency > 1)
  556. printf ("current latency %d\n", statecopy_latency);
  557. fflush(stdout);
  558. }
  559. }
  560. }
  561. /* Never reached. Well we will be a GtkApp someday... */
  562. packet_cache_free (global_packcache);
  563. jack_client_close (client);
  564. exit (0);
  565. }