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.

602 lines
18KB

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