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.

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