fix building when PATH_MAX is not defined. (should fix debian bug 320736)
[jack.git] / tools / netsource.c
blob5426cd918faccd054ff0a0cfe9da6504b5efc3b9
1 /*
2 NetJack Client
4 Copyright (C) 2008 Marc-Olivier Barre <marco@marcochapeau.org>
5 Copyright (C) 2008 Pieter Palmers <pieterpalmers@users.sourceforge.net>
6 Copyright (C) 2006 Torben Hohn <torbenh@gmx.de>
8 This program is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 /** @file netsource.c
26 * @brief This client connects a remote slave JACK to a local JACK server assumed to be the master
29 #include "config.h"
31 #include <stdio.h>
32 #include <errno.h>
33 #include <unistd.h>
34 #include <stdlib.h>
35 #include <string.h>
37 #include <netinet/in.h>
38 #include <netdb.h>
40 /* These two required by FreeBSD. */
41 #include <sys/types.h>
42 #include <sys/socket.h>
44 #if HAVE_ALLOCA_H
45 #include <alloca.h>
46 #endif
48 #include <jack/jack.h>
50 #include <net_driver.h>
51 #include <netjack_packet.h>
52 #if HAVE_SAMPLERATE
53 #include <samplerate.h>
54 #endif
56 #if HAVE_CELT
57 #include <celt/celt.h>
58 #endif
60 #include <math.h>
62 JSList *capture_ports = NULL;
63 JSList *capture_srcs = NULL;
64 int capture_channels = 0;
65 int capture_channels_audio = 2;
66 int capture_channels_midi = 1;
67 JSList *playback_ports = NULL;
68 JSList *playback_srcs = NULL;
69 int playback_channels = 0;
70 int playback_channels_audio = 2;
71 int playback_channels_midi = 1;
72 int dont_htonl_floats = 0;
74 int latency = 5;
75 jack_nframes_t factor = 1;
76 int bitdepth = 0;
77 int mtu = 1400;
78 int reply_port = 0;
79 int redundancy = 1;
80 jack_client_t *client;
82 int state_connected = 0;
83 int state_latency = 0;
84 int state_netxruns = 0;
85 int state_currentframe = 0;
86 int state_recv_packet_queue_time = 0;
89 int outsockfd;
90 int insockfd;
91 struct sockaddr destaddr;
92 struct sockaddr bindaddr;
94 int sync_state;
95 jack_transport_state_t last_transport_state;
97 int framecnt = 0;
99 int cont_miss = 0;
102 * This Function allocates all the I/O Ports which are added the lists.
104 void
105 alloc_ports (int n_capture_audio, int n_playback_audio, int n_capture_midi, int n_playback_midi)
108 int port_flags = JackPortIsOutput;
109 int chn;
110 jack_port_t *port;
111 char buf[32];
113 capture_ports = NULL;
114 /* Allocate audio capture channels */
115 for (chn = 0; chn < n_capture_audio; chn++)
117 snprintf (buf, sizeof (buf) - 1, "capture_%u", chn + 1);
118 port = jack_port_register (client, buf, JACK_DEFAULT_AUDIO_TYPE, port_flags, 0);
119 if (!port)
121 printf( "jack_netsource: cannot register %s port\n", buf);
122 break;
124 if( bitdepth == 1000 ) {
125 #if HAVE_CELT
126 // XXX: memory leak
127 CELTMode *celt_mode = celt_mode_create( jack_get_sample_rate( client ), 1, jack_get_buffer_size(client), NULL );
128 capture_srcs = jack_slist_append(capture_srcs, celt_decoder_create( celt_mode ) );
129 #endif
130 } else {
131 #if HAVE_SAMPLERATE
132 capture_srcs = jack_slist_append (capture_srcs, src_new (SRC_LINEAR, 1, NULL));
133 #endif
135 capture_ports = jack_slist_append (capture_ports, port);
138 /* Allocate midi capture channels */
139 for (chn = n_capture_audio; chn < n_capture_midi + n_capture_audio; chn++)
141 snprintf (buf, sizeof (buf) - 1, "capture_%u", chn + 1);
142 port = jack_port_register (client, buf, JACK_DEFAULT_MIDI_TYPE, port_flags, 0);
143 if (!port)
145 printf ("jack_netsource: cannot register %s port\n", buf);
146 break;
148 capture_ports = jack_slist_append(capture_ports, port);
151 /* Allocate audio playback channels */
152 port_flags = JackPortIsInput;
153 playback_ports = NULL;
154 for (chn = 0; chn < n_playback_audio; chn++)
156 snprintf (buf, sizeof (buf) - 1, "playback_%u", chn + 1);
157 port = jack_port_register (client, buf, JACK_DEFAULT_AUDIO_TYPE, port_flags, 0);
158 if (!port)
160 printf ("jack_netsource: cannot register %s port\n", buf);
161 break;
163 if( bitdepth == 1000 ) {
164 #if HAVE_CELT
165 // XXX: memory leak
166 CELTMode *celt_mode = celt_mode_create( jack_get_sample_rate (client), 1, jack_get_buffer_size(client), NULL );
167 playback_srcs = jack_slist_append(playback_srcs, celt_encoder_create( celt_mode ) );
168 #endif
169 } else {
170 #if HAVE_SAMPLERATE
171 playback_srcs = jack_slist_append (playback_srcs, src_new (SRC_LINEAR, 1, NULL));
172 #endif
174 playback_ports = jack_slist_append (playback_ports, port);
177 /* Allocate midi playback channels */
178 for (chn = n_playback_audio; chn < n_playback_midi + n_playback_audio; chn++)
180 snprintf (buf, sizeof (buf) - 1, "playback_%u", chn + 1);
181 port = jack_port_register (client, buf, JACK_DEFAULT_MIDI_TYPE, port_flags, 0);
182 if (!port)
184 printf ("jack_netsource: cannot register %s port\n", buf);
185 break;
187 playback_ports = jack_slist_append (playback_ports, port);
192 * The Sync callback... sync state is set elsewhere...
193 * we will see if this is working correctly.
194 * i dont really believe in it yet.
197 sync_cb (jack_transport_state_t state, jack_position_t *pos, void *arg)
199 static int latency_count = 0;
200 int retval = sync_state;
202 if (latency_count) {
203 latency_count--;
204 retval = 0;
207 else if (state == JackTransportStarting && last_transport_state != JackTransportStarting)
209 retval = 0;
210 latency_count = latency - 1;
213 last_transport_state = state;
214 return retval;
217 int deadline_goodness=0;
219 * The process callback for this JACK application.
220 * It is called by JACK at the appropriate times.
223 process (jack_nframes_t nframes, void *arg)
225 jack_nframes_t net_period;
226 int rx_bufsize, tx_bufsize;
228 jack_default_audio_sample_t *buf;
229 jack_port_t *port;
230 JSList *node;
231 channel_t chn;
232 int size, i;
233 const char *porttype;
234 int input_fd;
236 jack_position_t local_trans_pos;
238 uint32_t *packet_buf, *packet_bufX;
239 jack_time_t packet_recv_timestamp;
241 if( bitdepth == 1000 )
242 net_period = factor;
243 else
244 net_period = (float) nframes / (float) factor;
246 rx_bufsize = get_sample_size (bitdepth) * capture_channels * net_period + sizeof (jacknet_packet_header);
247 tx_bufsize = get_sample_size (bitdepth) * playback_channels * net_period + sizeof (jacknet_packet_header);
250 /* Allocate a buffer where both In and Out Buffer will fit */
251 packet_buf = alloca ((rx_bufsize > tx_bufsize) ? rx_bufsize : tx_bufsize);
253 jacknet_packet_header *pkthdr = (jacknet_packet_header *) packet_buf;
256 * for latency==0 we need to send out the packet before we wait on the reply.
257 * but this introduces a cycle of latency, when netsource is connected to itself.
258 * so we send out before read only in zero latency mode.
262 if( latency == 0 ) {
263 /* reset packet_bufX... */
264 packet_bufX = packet_buf + sizeof (jacknet_packet_header) / sizeof (jack_default_audio_sample_t);
266 /* ---------- Send ---------- */
267 render_jack_ports_to_payload (bitdepth, playback_ports, playback_srcs, nframes,
268 packet_bufX, net_period, dont_htonl_floats);
270 /* fill in packet hdr */
271 pkthdr->transport_state = jack_transport_query (client, &local_trans_pos);
272 pkthdr->transport_frame = local_trans_pos.frame;
273 pkthdr->framecnt = framecnt;
274 pkthdr->latency = latency;
275 pkthdr->reply_port = reply_port;
276 pkthdr->sample_rate = jack_get_sample_rate (client);
277 pkthdr->period_size = nframes;
279 /* playback for us is capture on the other side */
280 pkthdr->capture_channels_audio = playback_channels_audio;
281 pkthdr->playback_channels_audio = capture_channels_audio;
282 pkthdr->capture_channels_midi = playback_channels_midi;
283 pkthdr->playback_channels_midi = capture_channels_midi;
284 pkthdr->mtu = mtu;
285 pkthdr->sync_state = (jack_nframes_t)deadline_goodness;
286 //printf("goodness=%d\n", deadline_goodness );
288 packet_header_hton (pkthdr);
289 if (cont_miss < 3*latency+5) {
290 int r;
291 for( r=0; r<redundancy; r++ )
292 netjack_sendto (outsockfd, (char *) packet_buf, tx_bufsize, 0, &destaddr, sizeof (destaddr), mtu);
294 else if (cont_miss > 50+5*latency)
296 state_connected = 0;
297 packet_cache_reset_master_address( global_packcache );
298 //printf ("Frame %d \tRealy too many packets missed (%d). Let's reset the counter\n", framecnt, cont_miss);
299 cont_miss = 0;
304 * ok... now the RECEIVE code.
308 /* reset packet_bufX... */
309 packet_bufX = packet_buf + sizeof (jacknet_packet_header) / sizeof (jack_default_audio_sample_t);
311 if( reply_port )
312 input_fd = insockfd;
313 else
314 input_fd = outsockfd;
316 // for latency == 0 we can poll.
317 if( latency == 0 ) {
318 jack_time_t deadline = jack_get_time() + 1000000 * jack_get_buffer_size(client)/jack_get_sample_rate(client);
319 // Now loop until we get the right packet.
320 while(1) {
321 if ( ! netjack_poll_deadline( input_fd, deadline ) )
322 break;
324 packet_cache_drain_socket(global_packcache, input_fd);
326 if (packet_cache_get_next_available_framecnt( global_packcache, framecnt - latency, NULL ))
327 break;
329 } else {
330 // normally:
331 // only drain socket.
332 packet_cache_drain_socket(global_packcache, input_fd);
335 size = packet_cache_retreive_packet( global_packcache, framecnt - latency, (char *)packet_buf, rx_bufsize, &packet_recv_timestamp );
336 /* First alternative : we received what we expected. Render the data
337 * to the JACK ports so it can be played. */
338 if (size == rx_bufsize)
340 // calculate how much time there would have been, if this packet was sent at the deadline.
342 int recv_time_offset = (int) (jack_get_time() - packet_recv_timestamp);
343 packet_header_ntoh (pkthdr);
344 deadline_goodness = recv_time_offset - (int)pkthdr->latency;
345 //printf( "deadline goodness = %d ---> off: %d\n", deadline_goodness, recv_time_offset );
347 if (cont_miss)
349 //printf("Frame %d \tRecovered from dropouts\n", framecnt);
350 cont_miss = 0;
352 render_payload_to_jack_ports (bitdepth, packet_bufX, net_period,
353 capture_ports, capture_srcs, nframes, dont_htonl_floats);
355 state_currentframe = framecnt;
356 state_recv_packet_queue_time = recv_time_offset;
357 state_connected = 1;
358 sync_state = pkthdr->sync_state;
360 /* Second alternative : we've received something that's not
361 * as big as expected or we missed a packet. We render silence
362 * to the ouput ports */
363 else
365 jack_nframes_t latency_estimate;
366 if( packet_cache_find_latency( global_packcache, framecnt, &latency_estimate ) )
367 //if( (state_latency == 0) || (latency_estimate < state_latency) )
368 state_latency = latency_estimate;
370 // Set the counters up.
371 state_currentframe = framecnt;
372 //state_latency = framecnt - pkthdr->framecnt;
373 state_netxruns += 1;
375 //printf ("Frame %d \tPacket missed or incomplete (expected: %d bytes, got: %d bytes)\n", framecnt, rx_bufsize, size);
376 //printf ("Frame %d \tPacket missed or incomplete\n", framecnt);
377 cont_miss += 1;
378 chn = 0;
379 node = capture_ports;
380 while (node != NULL)
382 port = (jack_port_t *) node->data;
383 buf = jack_port_get_buffer (port, nframes);
384 porttype = jack_port_type (port);
385 if (strncmp (porttype, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size ()) == 0)
386 for (i = 0; i < nframes; i++)
387 buf[i] = 0.0;
388 else if (strncmp (porttype, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size ()) == 0)
389 jack_midi_clear_buffer (buf);
390 node = jack_slist_next (node);
391 chn++;
394 if( latency != 0 ) {
395 /* reset packet_bufX... */
396 packet_bufX = packet_buf + sizeof (jacknet_packet_header) / sizeof (jack_default_audio_sample_t);
398 /* ---------- Send ---------- */
399 render_jack_ports_to_payload (bitdepth, playback_ports, playback_srcs, nframes,
400 packet_bufX, net_period, dont_htonl_floats);
402 /* fill in packet hdr */
403 pkthdr->transport_state = jack_transport_query (client, &local_trans_pos);
404 pkthdr->transport_frame = local_trans_pos.frame;
405 pkthdr->framecnt = framecnt;
406 pkthdr->latency = latency;
407 pkthdr->reply_port = reply_port;
408 pkthdr->sample_rate = jack_get_sample_rate (client);
409 pkthdr->period_size = nframes;
411 /* playback for us is capture on the other side */
412 pkthdr->capture_channels_audio = playback_channels_audio;
413 pkthdr->playback_channels_audio = capture_channels_audio;
414 pkthdr->capture_channels_midi = playback_channels_midi;
415 pkthdr->playback_channels_midi = capture_channels_midi;
416 pkthdr->mtu = mtu;
417 pkthdr->sync_state = (jack_nframes_t)deadline_goodness;
418 //printf("goodness=%d\n", deadline_goodness );
420 packet_header_hton (pkthdr);
421 if (cont_miss < 3*latency+5) {
422 int r;
423 for( r=0; r<redundancy; r++ )
424 netjack_sendto (outsockfd, (char *) packet_buf, tx_bufsize, 0, &destaddr, sizeof (destaddr), mtu);
426 else if (cont_miss > 50+5*latency)
428 state_connected = 0;
429 packet_cache_reset_master_address( global_packcache );
430 //printf ("Frame %d \tRealy too many packets missed (%d). Let's reset the counter\n", framecnt, cont_miss);
431 cont_miss = 0;
435 framecnt++;
436 return 0;
440 * This is the shutdown callback for this JACK application.
441 * It is called by JACK if the server ever shuts down or
442 * decides to disconnect the client.
445 void
446 jack_shutdown (void *arg)
448 exit (1);
451 void
452 init_sockaddr_in (struct sockaddr_in *name , const char *hostname , uint16_t port)
454 name->sin_family = AF_INET ;
455 name->sin_port = htons (port);
456 if (hostname)
458 struct hostent *hostinfo = gethostbyname (hostname);
459 if (hostinfo == NULL)
460 fprintf (stderr, "init_sockaddr_in: unknown host: %s.\n", hostname);
461 name->sin_addr = *(struct in_addr *) hostinfo->h_addr ;
463 else
464 name->sin_addr.s_addr = htonl (INADDR_ANY) ;
467 void
468 printUsage ()
470 fprintf (stderr, "usage: jack_netsource -h <host peer> [options]\n"
471 "\n"
472 " -n <jack name> - Reports a different name to jack\n"
473 " -s <server name> - The name of the local jack server\n"
474 " -h <host_peer> - Host name of the slave JACK\n"
475 " -p <port> - UDP port used by the slave JACK\n"
476 " -P <num channels> - Number of audio playback channels\n"
477 " -C <num channels> - Number of audio capture channels\n"
478 " -o <num channels> - Number of midi playback channels\n"
479 " -i <num channels> - Number of midi capture channels\n"
480 " -l <latency> - Network latency in number of NetJack frames\n"
481 " -r <reply port> - Local UDP port to use\n"
482 " -f <downsample ratio> - Downsample data in the wire by this factor\n"
483 " -b <bitdepth> - Set transport to use 16bit or 8bit\n"
484 " -m <mtu> - Assume this mtu for the link\n"
485 " -c <bytes> - Use Celt and encode <bytes> per channel and packet.\n"
486 " -R <N> - Send out packets N times.\n"
487 "\n");
491 main (int argc, char *argv[])
493 /* Some startup related basics */
494 char *client_name, *server_name = NULL, *peer_ip;
495 int peer_port = 3000;
496 jack_options_t options = JackNullOption;
497 jack_status_t status;
499 /* Torben's famous state variables, aka "the reporting API" ! */
500 /* heh ? these are only the copies of them ;) */
501 int statecopy_connected, statecopy_latency, statecopy_netxruns;
502 jack_nframes_t net_period;
503 /* Argument parsing stuff */
504 extern char *optarg;
505 extern int optind, optopt;
506 int errflg=0, c;
508 if (argc < 3)
510 printUsage ();
511 return 1;
514 client_name = (char *) malloc (sizeof (char) * 10);
515 peer_ip = (char *) malloc (sizeof (char) * 10);
516 sprintf(client_name, "netsource");
517 sprintf(peer_ip, "localhost");
519 while ((c = getopt (argc, argv, ":H:R:n:s:h:p:C:P:i:o:l:r:f:b:m:c:")) != -1)
521 switch (c)
523 case 'n':
524 free(client_name);
525 client_name = (char *) malloc (sizeof (char) * strlen (optarg)+1);
526 strcpy (client_name, optarg);
527 break;
528 case 's':
529 server_name = (char *) malloc (sizeof (char) * strlen (optarg)+1);
530 strcpy (server_name, optarg);
531 options |= JackServerName;
532 break;
533 case 'h':
534 free(peer_ip);
535 peer_ip = (char *) malloc (sizeof (char) * strlen (optarg)+1);
536 strcpy (peer_ip, optarg);
537 break;
538 case 'p':
539 peer_port = atoi (optarg);
540 break;
541 case 'P':
542 playback_channels_audio = atoi (optarg);
543 break;
544 case 'C':
545 capture_channels_audio = atoi (optarg);
546 break;
547 case 'o':
548 playback_channels_midi = atoi (optarg);
549 break;
550 case 'i':
551 capture_channels_midi = atoi (optarg);
552 break;
553 case 'l':
554 latency = atoi (optarg);
555 break;
556 case 'r':
557 reply_port = atoi (optarg);
558 break;
559 case 'f':
560 factor = atoi (optarg);
561 break;
562 case 'b':
563 bitdepth = atoi (optarg);
564 break;
565 case 'c':
566 #if HAVE_CELT
567 bitdepth = 1000;
568 factor = atoi (optarg);
569 #else
570 printf( "not built with celt supprt\n" );
571 exit(10);
572 #endif
573 break;
574 case 'm':
575 mtu = atoi (optarg);
576 break;
577 case 'R':
578 redundancy = atoi (optarg);
579 break;
580 case 'H':
581 dont_htonl_floats = atoi (optarg);
582 break;
583 case ':':
584 fprintf (stderr, "Option -%c requires an operand\n", optopt);
585 errflg++;
586 break;
587 case '?':
588 fprintf (stderr, "Unrecognized option: -%c\n", optopt);
589 errflg++;
592 if (errflg)
594 printUsage ();
595 exit (2);
598 capture_channels = capture_channels_audio + capture_channels_midi;
599 playback_channels = playback_channels_audio + playback_channels_midi;
601 outsockfd = socket (PF_INET, SOCK_DGRAM, 0);
602 insockfd = socket (PF_INET, SOCK_DGRAM, 0);
603 init_sockaddr_in ((struct sockaddr_in *) &destaddr, peer_ip, peer_port);
604 if(reply_port)
606 init_sockaddr_in ((struct sockaddr_in *) &bindaddr, NULL, reply_port);
607 bind (insockfd, &bindaddr, sizeof (bindaddr));
610 /* try to become a client of the JACK server */
611 client = jack_client_open (client_name, options, &status, server_name);
612 if (client == NULL)
614 fprintf (stderr, "jack_client_open() failed, status = 0x%2.0x\n"
615 "Is the JACK server running ?\n", status);
616 return 1;
619 /* Set up jack callbacks */
620 jack_set_process_callback (client, process, 0);
621 jack_set_sync_callback (client, sync_cb, 0);
622 jack_on_shutdown (client, jack_shutdown, 0);
624 alloc_ports (capture_channels_audio, playback_channels_audio, capture_channels_midi, playback_channels_midi);
626 if( bitdepth == 1000 )
627 net_period = factor;
628 else
629 net_period = ceilf((float) jack_get_buffer_size (client) / (float) factor);
631 int rx_bufsize = get_sample_size (bitdepth) * capture_channels * net_period + sizeof (jacknet_packet_header);
632 global_packcache = packet_cache_new (latency + 50, rx_bufsize, mtu);
634 /* tell the JACK server that we are ready to roll */
635 if (jack_activate (client))
637 fprintf (stderr, "Cannot activate client");
638 return 1;
641 /* Now sleep forever... and evaluate the state_ vars */
643 statecopy_connected = 2; // make it report unconnected on start.
644 statecopy_latency = state_latency;
645 statecopy_netxruns = state_netxruns;
647 while (1)
649 sleep (1);
650 if (statecopy_connected != state_connected)
652 statecopy_connected = state_connected;
653 if (statecopy_connected)
655 state_netxruns = 1; // We want to reset the netxrun count on each new connection
656 printf ("Connected :-)\n");
658 else
659 printf ("Not Connected\n");
661 fflush(stdout);
664 if (statecopy_connected)
666 if (statecopy_netxruns != state_netxruns) {
667 statecopy_netxruns = state_netxruns;
668 printf ("at frame %06d -> total netxruns %d (%d%%) queue time= %d\n", state_currentframe,
669 statecopy_netxruns,
670 100*statecopy_netxruns/state_currentframe,
671 state_recv_packet_queue_time);
672 fflush(stdout);
675 else
677 if (statecopy_latency != state_latency)
679 statecopy_latency = state_latency;
680 if (statecopy_latency > 1)
681 printf ("current latency %d\n", statecopy_latency);
682 fflush(stdout);
687 /* Never reached. Well we will be a GtkApp someday... */
688 packet_cache_free (global_packcache);
689 jack_client_close (client);
690 exit (0);