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.

644 lines
19KB

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