Init engine fields, cleanup.
[jack2.git] / common / netjack_packet.c
blobdfe3b9e2626188f77884b774c298b9c32805abd7
2 /*
3 * NetJack - Packet Handling functions
5 * used by the driver and the jacknet_client
7 * Copyright (C) 2008 Marc-Olivier Barre <marco@marcochapeau.org>
8 * Copyright (C) 2008 Pieter Palmers <pieterpalmers@users.sourceforge.net>
9 * Copyright (C) 2006 Torben Hohn <torbenh@gmx.de>
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 * $Id: net_driver.c,v 1.16 2006/03/20 19:41:37 torbenh Exp $
29 #ifdef __linux__
30 #include "config.h"
31 #endif
33 #ifdef __APPLE__
34 #define _DARWIN_C_SOURCE
35 #endif
37 #if HAVE_PPOLL
38 #define _GNU_SOURCE
39 #endif
41 #include <math.h>
42 #include <stdio.h>
43 #include <memory.h>
44 #include <unistd.h>
45 #include <stdlib.h>
46 #include <errno.h>
47 #include <stdarg.h>
49 #include <jack/types.h>
51 #include <sys/types.h>
53 #ifdef WIN32
54 #include <winsock2.h>
55 #define socklen_t int
56 #include <malloc.h>
57 #define socklen_t int
58 #else
59 #include <sys/socket.h>
60 #include <netinet/in.h>
61 #include <poll.h>
62 #endif
64 #include <errno.h>
65 #include <signal.h>
67 #if HAVE_SAMPLERATE
68 #include <samplerate.h>
69 #endif
71 #if HAVE_CELT
72 #include <celt/celt.h>
73 #endif
75 #include "netjack_packet.h"
77 // JACK2 specific.
78 #include "jack/control.h"
80 #ifdef NO_JACK_ERROR
81 #define jack_error printf
82 #endif
84 int fraggo = 0;
86 packet_cache *global_packcache = NULL;
88 void
89 packet_header_hton (jacknet_packet_header *pkthdr)
91 pkthdr->capture_channels_audio = htonl(pkthdr->capture_channels_audio);
92 pkthdr->playback_channels_audio = htonl(pkthdr->playback_channels_audio);
93 pkthdr->capture_channels_midi = htonl(pkthdr->capture_channels_midi);
94 pkthdr->playback_channels_midi = htonl(pkthdr->playback_channels_midi);
95 pkthdr->period_size = htonl(pkthdr->period_size);
96 pkthdr->sample_rate = htonl(pkthdr->sample_rate);
97 pkthdr->sync_state = htonl(pkthdr->sync_state);
98 pkthdr->transport_frame = htonl(pkthdr->transport_frame);
99 pkthdr->transport_state = htonl(pkthdr->transport_state);
100 pkthdr->framecnt = htonl(pkthdr->framecnt);
101 pkthdr->latency = htonl(pkthdr->latency);
102 pkthdr->reply_port = htonl(pkthdr->reply_port);
103 pkthdr->mtu = htonl(pkthdr->mtu);
104 pkthdr->fragment_nr = htonl(pkthdr->fragment_nr);
107 void
108 packet_header_ntoh (jacknet_packet_header *pkthdr)
110 pkthdr->capture_channels_audio = ntohl(pkthdr->capture_channels_audio);
111 pkthdr->playback_channels_audio = ntohl(pkthdr->playback_channels_audio);
112 pkthdr->capture_channels_midi = ntohl(pkthdr->capture_channels_midi);
113 pkthdr->playback_channels_midi = ntohl(pkthdr->playback_channels_midi);
114 pkthdr->period_size = ntohl(pkthdr->period_size);
115 pkthdr->sample_rate = ntohl(pkthdr->sample_rate);
116 pkthdr->sync_state = ntohl(pkthdr->sync_state);
117 pkthdr->transport_frame = ntohl(pkthdr->transport_frame);
118 pkthdr->transport_state = ntohl(pkthdr->transport_state);
119 pkthdr->framecnt = ntohl(pkthdr->framecnt);
120 pkthdr->latency = ntohl(pkthdr->latency);
121 pkthdr->reply_port = ntohl(pkthdr->reply_port);
122 pkthdr->mtu = ntohl(pkthdr->mtu);
123 pkthdr->fragment_nr = ntohl(pkthdr->fragment_nr);
126 int get_sample_size (int bitdepth)
128 if (bitdepth == 8)
129 return sizeof (int8_t);
130 if (bitdepth == 16)
131 return sizeof (int16_t);
132 //JN: why? is this for buffer sizes before or after encoding?
133 //JN: if the former, why not int16_t, if the latter, shouldn't it depend on -c N?
134 if( bitdepth == CELT_MODE )
135 return sizeof( unsigned char );
136 return sizeof (int32_t);
139 int jack_port_is_audio(const char *porttype)
141 return (strncmp (porttype, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0);
144 int jack_port_is_midi(const char *porttype)
146 return (strncmp (porttype, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0);
150 // fragment management functions.
152 packet_cache
153 *packet_cache_new (int num_packets, int pkt_size, int mtu)
155 int fragment_payload_size = mtu - sizeof (jacknet_packet_header);
156 int i, fragment_number;
158 if( pkt_size == sizeof(jacknet_packet_header) )
159 fragment_number = 1;
160 else
161 fragment_number = (pkt_size - sizeof (jacknet_packet_header) - 1) / fragment_payload_size + 1;
163 packet_cache *pcache = malloc (sizeof (packet_cache));
164 if (pcache == NULL)
166 jack_error ("could not allocate packet cache (1)");
167 return NULL;
170 pcache->size = num_packets;
171 pcache->packets = malloc (sizeof (cache_packet) * num_packets);
172 pcache->master_address_valid = 0;
173 pcache->last_framecnt_retreived = 0;
174 pcache->last_framecnt_retreived_valid = 0;
176 if (pcache->packets == NULL)
178 jack_error ("could not allocate packet cache (2)");
179 return NULL;
182 for (i = 0; i < num_packets; i++)
184 pcache->packets[i].valid = 0;
185 pcache->packets[i].num_fragments = fragment_number;
186 pcache->packets[i].packet_size = pkt_size;
187 pcache->packets[i].mtu = mtu;
188 pcache->packets[i].framecnt = 0;
189 pcache->packets[i].fragment_array = malloc (sizeof (char) * fragment_number);
190 pcache->packets[i].packet_buf = malloc (pkt_size);
191 if ((pcache->packets[i].fragment_array == NULL) || (pcache->packets[i].packet_buf == NULL))
193 jack_error ("could not allocate packet cache (3)");
194 return NULL;
197 pcache->mtu = mtu;
199 return pcache;
202 void
203 packet_cache_free (packet_cache *pcache)
205 int i;
206 if( pcache == NULL )
207 return;
209 for (i = 0; i < pcache->size; i++)
211 free (pcache->packets[i].fragment_array);
212 free (pcache->packets[i].packet_buf);
215 free (pcache->packets);
216 free (pcache);
219 cache_packet
220 *packet_cache_get_packet (packet_cache *pcache, jack_nframes_t framecnt)
222 int i;
223 cache_packet *retval;
225 for (i = 0; i < pcache->size; i++)
227 if (pcache->packets[i].valid && (pcache->packets[i].framecnt == framecnt))
228 return &(pcache->packets[i]);
231 // The Packet is not in the packet cache.
232 // find a free packet.
234 retval = packet_cache_get_free_packet (pcache);
235 if (retval != NULL)
237 cache_packet_set_framecnt (retval, framecnt);
238 return retval;
241 // No Free Packet available
242 // Get The Oldest packet and reset it.
244 retval = packet_cache_get_oldest_packet (pcache);
245 //printf( "Dropping %d from Cache :S\n", retval->framecnt );
246 cache_packet_reset (retval);
247 cache_packet_set_framecnt (retval, framecnt);
249 return retval;
252 // TODO: fix wrapping case... need to pass
253 // current expected frame here.
255 // or just save framecount into packet_cache.
257 cache_packet
258 *packet_cache_get_oldest_packet (packet_cache *pcache)
260 jack_nframes_t minimal_frame = JACK_MAX_FRAMES;
261 cache_packet *retval = &(pcache->packets[0]);
262 int i;
264 for (i = 0; i < pcache->size; i++)
266 if (pcache->packets[i].valid && (pcache->packets[i].framecnt < minimal_frame))
268 minimal_frame = pcache->packets[i].framecnt;
269 retval = &(pcache->packets[i]);
273 return retval;
276 cache_packet
277 *packet_cache_get_free_packet (packet_cache *pcache)
279 int i;
281 for (i = 0; i < pcache->size; i++)
283 if (pcache->packets[i].valid == 0)
284 return &(pcache->packets[i]);
287 return NULL;
290 void
291 cache_packet_reset (cache_packet *pack)
293 int i;
294 pack->valid = 0;
296 // XXX: i dont think this is necessary here...
297 // fragement array is cleared in _set_framecnt()
299 for (i = 0; i < pack->num_fragments; i++)
300 pack->fragment_array[i] = 0;
303 void
304 cache_packet_set_framecnt (cache_packet *pack, jack_nframes_t framecnt)
306 int i;
308 pack->framecnt = framecnt;
310 for (i = 0; i < pack->num_fragments; i++)
311 pack->fragment_array[i] = 0;
313 pack->valid = 1;
316 void
317 cache_packet_add_fragment (cache_packet *pack, char *packet_buf, int rcv_len)
319 jacknet_packet_header *pkthdr = (jacknet_packet_header *) packet_buf;
320 int fragment_payload_size = pack->mtu - sizeof (jacknet_packet_header);
321 char *packet_bufX = pack->packet_buf + sizeof (jacknet_packet_header);
322 char *dataX = packet_buf + sizeof (jacknet_packet_header);
324 jack_nframes_t fragment_nr = ntohl (pkthdr->fragment_nr);
325 jack_nframes_t framecnt = ntohl (pkthdr->framecnt);
327 if (framecnt != pack->framecnt)
329 jack_error ("errror. framecnts dont match");
330 return;
334 if (fragment_nr == 0)
336 memcpy (pack->packet_buf, packet_buf, rcv_len);
337 pack->fragment_array[0] = 1;
339 return;
342 if ((fragment_nr < pack->num_fragments) && (fragment_nr > 0))
344 if ((fragment_nr * fragment_payload_size + rcv_len - sizeof (jacknet_packet_header)) <= (pack->packet_size - sizeof (jacknet_packet_header)))
346 memcpy (packet_bufX + fragment_nr * fragment_payload_size, dataX, rcv_len - sizeof (jacknet_packet_header));
347 pack->fragment_array[fragment_nr] = 1;
349 else
350 jack_error ("too long packet received...");
355 cache_packet_is_complete (cache_packet *pack)
357 int i;
358 for (i = 0; i < pack->num_fragments; i++)
359 if (pack->fragment_array[i] == 0)
360 return 0;
362 return 1;
365 #ifndef WIN32
366 // new poll using nanoseconds resolution and
367 // not waiting forever.
369 netjack_poll_deadline (int sockfd, jack_time_t deadline)
371 struct pollfd fds;
372 int poll_err = 0;
373 #if HAVE_PPOLL
374 struct timespec timeout_spec = { 0, 0 };
375 #else
376 int timeout;
377 #endif
380 jack_time_t now = jack_get_time();
381 if( now >= deadline )
382 return 0;
384 if( (deadline-now) >= 1000000 ) {
385 jack_error( "deadline more than 1 second in the future, trimming it." );
386 deadline = now+500000;
388 #if HAVE_PPOLL
389 timeout_spec.tv_nsec = (deadline - now) * 1000;
390 #else
391 timeout = (deadline - now + 500) / 1000;
392 #endif
395 fds.fd = sockfd;
396 fds.events = POLLIN;
398 #if HAVE_PPOLL
399 poll_err = ppoll (&fds, 1, &timeout_spec, NULL);
400 #else
401 poll_err = poll (&fds, 1, timeout);
402 #endif
404 if (poll_err == -1)
406 switch (errno)
408 case EBADF:
409 jack_error ("Error %d: An invalid file descriptor was given in one of the sets", errno);
410 break;
411 case EFAULT:
412 jack_error ("Error %d: The array given as argument was not contained in the calling program's address space", errno);
413 break;
414 case EINTR:
415 jack_error ("Error %d: A signal occurred before any requested event", errno);
416 break;
417 case EINVAL:
418 jack_error ("Error %d: The nfds value exceeds the RLIMIT_NOFILE value", errno);
419 break;
420 case ENOMEM:
421 jack_error ("Error %d: There was no space to allocate file descriptor tables", errno);
422 break;
425 return poll_err;
429 netjack_poll (int sockfd, int timeout)
431 struct pollfd fds;
432 int i, poll_err = 0;
433 sigset_t sigmask, rsigmask;
434 struct sigaction action;
436 sigemptyset(&sigmask);
437 sigaddset(&sigmask, SIGHUP);
438 sigaddset(&sigmask, SIGINT);
439 sigaddset(&sigmask, SIGQUIT);
440 sigaddset(&sigmask, SIGPIPE);
441 sigaddset(&sigmask, SIGTERM);
442 sigaddset(&sigmask, SIGUSR1);
443 sigaddset(&sigmask, SIGUSR2);
445 action.sa_handler = SIG_DFL;
446 action.sa_mask = sigmask;
447 action.sa_flags = SA_RESTART;
449 for (i = 1; i < NSIG; i++)
450 if (sigismember (&sigmask, i))
451 sigaction (i, &action, 0);
453 fds.fd = sockfd;
454 fds.events = POLLIN;
456 sigprocmask(SIG_UNBLOCK, &sigmask, &rsigmask);
457 while (poll_err == 0)
459 poll_err = poll (&fds, 1, timeout);
461 sigprocmask(SIG_SETMASK, &rsigmask, NULL);
463 if (poll_err == -1)
465 switch (errno)
467 case EBADF:
468 jack_error ("Error %d: An invalid file descriptor was given in one of the sets", errno);
469 break;
470 case EFAULT:
471 jack_error ("Error %d: The array given as argument was not contained in the calling program's address space", errno);
472 break;
473 case EINTR:
474 jack_error ("Error %d: A signal occurred before any requested event", errno);
475 break;
476 case EINVAL:
477 jack_error ("Error %d: The nfds value exceeds the RLIMIT_NOFILE value", errno);
478 break;
479 case ENOMEM:
480 jack_error ("Error %d: There was no space to allocate file descriptor tables", errno);
481 break;
483 return 0;
485 return 1;
488 #else
490 netjack_poll (int sockfd, int timeout)
492 jack_error( "netjack_poll not implemented" );
493 return 0;
496 netjack_poll_deadline (int sockfd, jack_time_t deadline)
498 fd_set fds;
499 FD_ZERO( &fds );
500 FD_SET( sockfd, &fds );
502 struct timeval timeout;
503 while( 1 ) {
504 jack_time_t now = jack_get_time();
505 if( now >= deadline )
506 return 0;
508 int timeout_usecs = (deadline - now);
509 //jack_error( "timeout = %d", timeout_usecs );
510 timeout.tv_sec = 0;
511 timeout.tv_usec = (timeout_usecs < 500) ? 500 : timeout_usecs;
512 timeout.tv_usec = (timeout_usecs > 1000000) ? 500000 : timeout_usecs;
514 int poll_err = select (0, &fds, NULL, NULL, &timeout);
515 if( poll_err != 0 )
516 return poll_err;
519 return 0;
521 #endif
522 // This now reads all a socket has into the cache.
523 // replacing netjack_recv functions.
525 void
526 packet_cache_drain_socket( packet_cache *pcache, int sockfd )
528 char *rx_packet = alloca (pcache->mtu);
529 jacknet_packet_header *pkthdr = (jacknet_packet_header *) rx_packet;
530 int rcv_len;
531 jack_nframes_t framecnt;
532 cache_packet *cpack;
533 struct sockaddr_in sender_address;
534 #ifdef WIN32
535 size_t senderlen = sizeof( struct sockaddr_in );
536 u_long parm = 1;
537 ioctlsocket( sockfd, FIONBIO, &parm );
538 #else
539 socklen_t senderlen = sizeof( struct sockaddr_in );
540 #endif
541 while (1)
543 #ifdef WIN32
544 rcv_len = recvfrom (sockfd, rx_packet, pcache->mtu, 0,
545 (struct sockaddr*) &sender_address, &senderlen);
546 #else
547 rcv_len = recvfrom (sockfd, rx_packet, pcache->mtu, MSG_DONTWAIT,
548 (struct sockaddr*) &sender_address, &senderlen);
549 #endif
550 if (rcv_len < 0)
551 return;
553 if (pcache->master_address_valid) {
554 // Verify its from our master.
555 if (memcmp (&sender_address, &(pcache->master_address), senderlen) != 0)
556 continue;
557 } else {
558 // Setup this one as master
559 //printf( "setup master...\n" );
560 memcpy ( &(pcache->master_address), &sender_address, senderlen );
561 pcache->master_address_valid = 1;
564 framecnt = ntohl (pkthdr->framecnt);
565 if( pcache->last_framecnt_retreived_valid && (framecnt <= pcache->last_framecnt_retreived ))
566 continue;
568 cpack = packet_cache_get_packet (global_packcache, framecnt);
569 cache_packet_add_fragment (cpack, rx_packet, rcv_len);
570 cpack->recv_timestamp = jack_get_time();
574 void
575 packet_cache_reset_master_address( packet_cache *pcache )
577 pcache->master_address_valid = 0;
578 pcache->last_framecnt_retreived = 0;
579 pcache->last_framecnt_retreived_valid = 0;
582 void
583 packet_cache_clear_old_packets (packet_cache *pcache, jack_nframes_t framecnt )
585 int i;
587 for (i = 0; i < pcache->size; i++)
589 if (pcache->packets[i].valid && (pcache->packets[i].framecnt < framecnt))
591 cache_packet_reset (&(pcache->packets[i]));
597 packet_cache_retreive_packet_pointer( packet_cache *pcache, jack_nframes_t framecnt, char **packet_buf, int pkt_size, jack_time_t *timestamp )
599 int i;
600 cache_packet *cpack = NULL;
603 for (i = 0; i < pcache->size; i++) {
604 if (pcache->packets[i].valid && (pcache->packets[i].framecnt == framecnt)) {
605 cpack = &(pcache->packets[i]);
606 break;
610 if( cpack == NULL ) {
611 //printf( "retreive packet: %d....not found\n", framecnt );
612 return -1;
615 if( !cache_packet_is_complete( cpack ) ) {
616 return -1;
619 // ok. cpack is the one we want and its complete.
620 *packet_buf = cpack->packet_buf;
621 if( timestamp )
622 *timestamp = cpack->recv_timestamp;
624 pcache->last_framecnt_retreived_valid = 1;
625 pcache->last_framecnt_retreived = framecnt;
627 return pkt_size;
631 packet_cache_release_packet( packet_cache *pcache, jack_nframes_t framecnt )
633 int i;
634 cache_packet *cpack = NULL;
637 for (i = 0; i < pcache->size; i++) {
638 if (pcache->packets[i].valid && (pcache->packets[i].framecnt == framecnt)) {
639 cpack = &(pcache->packets[i]);
640 break;
644 if( cpack == NULL ) {
645 //printf( "retreive packet: %d....not found\n", framecnt );
646 return -1;
649 if( !cache_packet_is_complete( cpack ) ) {
650 return -1;
653 cache_packet_reset (cpack);
654 packet_cache_clear_old_packets( pcache, framecnt );
656 return 0;
658 float
659 packet_cache_get_fill( packet_cache *pcache, jack_nframes_t expected_framecnt )
661 int num_packets_before_us = 0;
662 int i;
664 for (i = 0; i < pcache->size; i++)
666 cache_packet *cpack = &(pcache->packets[i]);
667 if (cpack->valid && cache_packet_is_complete( cpack ))
668 if( cpack->framecnt >= expected_framecnt )
669 num_packets_before_us += 1;
672 return 100.0 * (float)num_packets_before_us / (float)( pcache->size ) ;
675 // Returns 0 when no valid packet is inside the cache.
677 packet_cache_get_next_available_framecnt( packet_cache *pcache, jack_nframes_t expected_framecnt, jack_nframes_t *framecnt )
679 int i;
680 jack_nframes_t best_offset = JACK_MAX_FRAMES/2-1;
681 int retval = 0;
683 for (i = 0; i < pcache->size; i++)
685 cache_packet *cpack = &(pcache->packets[i]);
686 //printf( "p%d: valid=%d, frame %d\n", i, cpack->valid, cpack->framecnt );
688 if (!cpack->valid || !cache_packet_is_complete( cpack )) {
689 //printf( "invalid\n" );
690 continue;
693 if( cpack->framecnt < expected_framecnt )
694 continue;
696 if( (cpack->framecnt - expected_framecnt) > best_offset ) {
697 continue;
700 best_offset = cpack->framecnt - expected_framecnt;
701 retval = 1;
703 if( best_offset == 0 )
704 break;
706 if( retval && framecnt )
707 *framecnt = expected_framecnt + best_offset;
709 return retval;
713 packet_cache_get_highest_available_framecnt( packet_cache *pcache, jack_nframes_t *framecnt )
715 int i;
716 jack_nframes_t best_value = 0;
717 int retval = 0;
719 for (i = 0; i < pcache->size; i++)
721 cache_packet *cpack = &(pcache->packets[i]);
722 //printf( "p%d: valid=%d, frame %d\n", i, cpack->valid, cpack->framecnt );
724 if (!cpack->valid || !cache_packet_is_complete( cpack )) {
725 //printf( "invalid\n" );
726 continue;
729 if (cpack->framecnt < best_value) {
730 continue;
733 best_value = cpack->framecnt;
734 retval = 1;
737 if( retval && framecnt )
738 *framecnt = best_value;
740 return retval;
743 // Returns 0 when no valid packet is inside the cache.
745 packet_cache_find_latency( packet_cache *pcache, jack_nframes_t expected_framecnt, jack_nframes_t *framecnt )
747 int i;
748 jack_nframes_t best_offset = 0;
749 int retval = 0;
751 for (i = 0; i < pcache->size; i++)
753 cache_packet *cpack = &(pcache->packets[i]);
754 //printf( "p%d: valid=%d, frame %d\n", i, cpack->valid, cpack->framecnt );
756 if (!cpack->valid || !cache_packet_is_complete( cpack )) {
757 //printf( "invalid\n" );
758 continue;
761 if( (cpack->framecnt - expected_framecnt) < best_offset ) {
762 continue;
765 best_offset = cpack->framecnt - expected_framecnt;
766 retval = 1;
768 if( best_offset == 0 )
769 break;
771 if( retval && framecnt )
772 *framecnt = JACK_MAX_FRAMES - best_offset;
774 return retval;
776 // fragmented packet IO
778 netjack_recvfrom (int sockfd, char *packet_buf, int pkt_size, int flags, struct sockaddr *addr, size_t *addr_size, int mtu)
780 int retval;
781 socklen_t from_len = *addr_size;
782 if (pkt_size <= mtu) {
783 retval = recvfrom (sockfd, packet_buf, pkt_size, flags, addr, &from_len);
784 *addr_size = from_len;
785 return retval;
788 char *rx_packet = alloca (mtu);
789 jacknet_packet_header *pkthdr = (jacknet_packet_header *) rx_packet;
790 int rcv_len;
791 jack_nframes_t framecnt;
792 cache_packet *cpack;
795 rcv_len = recvfrom (sockfd, rx_packet, mtu, 0, addr, &from_len);
796 if (rcv_len < 0)
797 return rcv_len;
798 framecnt = ntohl (pkthdr->framecnt);
799 cpack = packet_cache_get_packet (global_packcache, framecnt);
800 cache_packet_add_fragment (cpack, rx_packet, rcv_len);
801 } while (!cache_packet_is_complete (cpack));
802 memcpy (packet_buf, cpack->packet_buf, pkt_size);
803 cache_packet_reset (cpack);
804 *addr_size = from_len;
805 return pkt_size;
809 netjack_recv (int sockfd, char *packet_buf, int pkt_size, int flags, int mtu)
811 if (pkt_size <= mtu)
812 return recv (sockfd, packet_buf, pkt_size, flags);
813 char *rx_packet = alloca (mtu);
814 jacknet_packet_header *pkthdr = (jacknet_packet_header *) rx_packet;
815 int rcv_len;
816 jack_nframes_t framecnt;
817 cache_packet *cpack;
820 rcv_len = recv (sockfd, rx_packet, mtu, flags);
821 if (rcv_len < 0)
822 return rcv_len;
823 framecnt = ntohl (pkthdr->framecnt);
824 cpack = packet_cache_get_packet (global_packcache, framecnt);
825 cache_packet_add_fragment (cpack, rx_packet, rcv_len);
826 } while (!cache_packet_is_complete (cpack));
827 memcpy (packet_buf, cpack->packet_buf, pkt_size);
828 cache_packet_reset (cpack);
829 return pkt_size;
832 void
833 netjack_sendto (int sockfd, char *packet_buf, int pkt_size, int flags, struct sockaddr *addr, int addr_size, int mtu)
835 int frag_cnt = 0;
836 char *tx_packet, *dataX;
837 jacknet_packet_header *pkthdr;
839 tx_packet = alloca (mtu + 10);
840 dataX = tx_packet + sizeof (jacknet_packet_header);
841 pkthdr = (jacknet_packet_header *) tx_packet;
843 int fragment_payload_size = mtu - sizeof (jacknet_packet_header);
845 if (pkt_size <= mtu) {
846 int err;
847 pkthdr = (jacknet_packet_header *) packet_buf;
848 pkthdr->fragment_nr = htonl (0);
849 err = sendto(sockfd, packet_buf, pkt_size, flags, addr, addr_size);
850 if( err<0 ) {
851 //printf( "error in send\n" );
852 perror( "send" );
855 else
857 int err;
858 // Copy the packet header to the tx pack first.
859 memcpy(tx_packet, packet_buf, sizeof (jacknet_packet_header));
861 // Now loop and send all
862 char *packet_bufX = packet_buf + sizeof (jacknet_packet_header);
864 while (packet_bufX < (packet_buf + pkt_size - fragment_payload_size))
866 pkthdr->fragment_nr = htonl (frag_cnt++);
867 memcpy (dataX, packet_bufX, fragment_payload_size);
868 sendto (sockfd, tx_packet, mtu, flags, addr, addr_size);
869 packet_bufX += fragment_payload_size;
872 int last_payload_size = packet_buf + pkt_size - packet_bufX;
873 memcpy (dataX, packet_bufX, last_payload_size);
874 pkthdr->fragment_nr = htonl (frag_cnt);
875 //jack_log("last fragment_count = %d, payload_size = %d\n", fragment_count, last_payload_size);
877 // sendto(last_pack_size);
878 err = sendto(sockfd, tx_packet, last_payload_size + sizeof(jacknet_packet_header), flags, addr, addr_size);
879 if( err<0 ) {
880 //printf( "error in send\n" );
881 perror( "send" );
887 void
888 decode_midi_buffer (uint32_t *buffer_uint32, unsigned int buffer_size_uint32, jack_default_audio_sample_t* buf)
890 int i;
891 jack_midi_clear_buffer (buf);
892 for (i = 0; i < buffer_size_uint32 - 3;)
894 uint32_t payload_size;
895 payload_size = buffer_uint32[i];
896 payload_size = ntohl (payload_size);
897 if (payload_size)
899 jack_midi_event_t event;
900 event.time = ntohl (buffer_uint32[i+1]);
901 event.size = ntohl (buffer_uint32[i+2]);
902 event.buffer = (jack_midi_data_t*) (&(buffer_uint32[i+3]));
903 jack_midi_event_write (buf, event.time, event.buffer, event.size);
905 // skip to the next event
906 unsigned int nb_data_quads = (((event.size-1) & ~0x3) >> 2)+1;
907 i += 3+nb_data_quads;
909 else
910 break; // no events can follow an empty event, we're done
914 void
915 encode_midi_buffer (uint32_t *buffer_uint32, unsigned int buffer_size_uint32, jack_default_audio_sample_t* buf)
917 int i;
918 unsigned int written = 0;
919 // midi port, encode midi events
920 unsigned int nevents = jack_midi_get_event_count (buf);
921 for (i = 0; i < nevents; ++i)
923 jack_midi_event_t event;
924 jack_midi_event_get (&event, buf, i);
925 unsigned int nb_data_quads = (((event.size - 1) & ~0x3) >> 2) + 1;
926 unsigned int payload_size = 3 + nb_data_quads;
927 // only write if we have sufficient space for the event
928 // otherwise drop it
929 if (written + payload_size < buffer_size_uint32 - 1)
931 // write header
932 buffer_uint32[written]=htonl (payload_size);
933 written++;
934 buffer_uint32[written]=htonl (event.time);
935 written++;
936 buffer_uint32[written]=htonl (event.size);
937 written++;
939 // write data
940 jack_midi_data_t* tmpbuff = (jack_midi_data_t*)(&(buffer_uint32[written]));
941 memcpy (tmpbuff, event.buffer, event.size);
942 written += nb_data_quads;
944 else
946 // buffer overflow
947 jack_error ("midi buffer overflow");
948 break;
951 // now put a netjack_midi 'no-payload' event, signaling EOF
952 buffer_uint32[written]=0;
955 // render functions for float
956 void
957 render_payload_to_jack_ports_float ( void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes, int dont_htonl_floats)
959 int chn = 0;
960 JSList *node = capture_ports;
961 #if HAVE_SAMPLERATE
962 JSList *src_node = capture_srcs;
963 #endif
965 uint32_t *packet_bufX = (uint32_t *)packet_payload;
967 if( !packet_payload )
968 return;
970 while (node != NULL)
972 int i;
973 int_float_t val;
974 #if HAVE_SAMPLERATE
975 SRC_DATA src;
976 #endif
978 jack_port_t *port = (jack_port_t *) node->data;
979 jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes);
981 const char *porttype = jack_port_type (port);
983 if (jack_port_is_audio (porttype))
985 #if HAVE_SAMPLERATE
986 // audio port, resample if necessary
987 if (net_period_down != nframes)
989 SRC_STATE *src_state = src_node->data;
990 for (i = 0; i < net_period_down; i++)
992 packet_bufX[i] = ntohl (packet_bufX[i]);
995 src.data_in = (float *) packet_bufX;
996 src.input_frames = net_period_down;
998 src.data_out = buf;
999 src.output_frames = nframes;
1001 src.src_ratio = (float) nframes / (float) net_period_down;
1002 src.end_of_input = 0;
1004 src_set_ratio (src_state, src.src_ratio);
1005 src_process (src_state, &src);
1006 src_node = jack_slist_next (src_node);
1008 else
1009 #endif
1011 if( dont_htonl_floats )
1013 memcpy( buf, packet_bufX, net_period_down*sizeof(jack_default_audio_sample_t));
1015 else
1017 for (i = 0; i < net_period_down; i++)
1019 val.i = packet_bufX[i];
1020 val.i = ntohl (val.i);
1021 buf[i] = val.f;
1026 else if (jack_port_is_midi (porttype))
1028 // midi port, decode midi events
1029 // convert the data buffer to a standard format (uint32_t based)
1030 unsigned int buffer_size_uint32 = net_period_down;
1031 uint32_t * buffer_uint32 = (uint32_t*)packet_bufX;
1032 decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
1034 packet_bufX = (packet_bufX + net_period_down);
1035 node = jack_slist_next (node);
1036 chn++;
1040 void
1041 render_jack_ports_to_payload_float (JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up, int dont_htonl_floats )
1043 int chn = 0;
1044 JSList *node = playback_ports;
1045 #if HAVE_SAMPLERATE
1046 JSList *src_node = playback_srcs;
1047 #endif
1049 uint32_t *packet_bufX = (uint32_t *) packet_payload;
1051 while (node != NULL)
1053 #if HAVE_SAMPLERATE
1054 SRC_DATA src;
1055 #endif
1056 int i;
1057 int_float_t val;
1058 jack_port_t *port = (jack_port_t *) node->data;
1059 jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes);
1061 const char *porttype = jack_port_type (port);
1063 if (jack_port_is_audio (porttype))
1065 // audio port, resample if necessary
1067 #if HAVE_SAMPLERATE
1068 if (net_period_up != nframes) {
1069 SRC_STATE *src_state = src_node->data;
1070 src.data_in = buf;
1071 src.input_frames = nframes;
1073 src.data_out = (float *) packet_bufX;
1074 src.output_frames = net_period_up;
1076 src.src_ratio = (float) net_period_up / (float) nframes;
1077 src.end_of_input = 0;
1079 src_set_ratio (src_state, src.src_ratio);
1080 src_process (src_state, &src);
1082 for (i = 0; i < net_period_up; i++)
1084 packet_bufX[i] = htonl (packet_bufX[i]);
1086 src_node = jack_slist_next (src_node);
1088 else
1089 #endif
1091 if( dont_htonl_floats )
1093 memcpy( packet_bufX, buf, net_period_up*sizeof(jack_default_audio_sample_t) );
1095 else
1097 for (i = 0; i < net_period_up; i++)
1099 val.f = buf[i];
1100 val.i = htonl (val.i);
1101 packet_bufX[i] = val.i;
1106 else if (jack_port_is_midi (porttype))
1108 // encode midi events from port to packet
1109 // convert the data buffer to a standard format (uint32_t based)
1110 unsigned int buffer_size_uint32 = net_period_up;
1111 uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
1112 encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
1114 packet_bufX = (packet_bufX + net_period_up);
1115 node = jack_slist_next (node);
1116 chn++;
1120 // render functions for 16bit
1121 void
1122 render_payload_to_jack_ports_16bit (void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes)
1124 int chn = 0;
1125 JSList *node = capture_ports;
1126 #if HAVE_SAMPLERATE
1127 JSList *src_node = capture_srcs;
1128 #endif
1130 uint16_t *packet_bufX = (uint16_t *)packet_payload;
1132 if( !packet_payload )
1133 return;
1135 while (node != NULL)
1137 int i;
1138 //uint32_t val;
1139 #if HAVE_SAMPLERATE
1140 SRC_DATA src;
1141 #endif
1143 jack_port_t *port = (jack_port_t *) node->data;
1144 jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes);
1146 #if HAVE_SAMPLERATE
1147 float *floatbuf = alloca (sizeof(float) * net_period_down);
1148 #endif
1149 const char *porttype = jack_port_type (port);
1151 if (jack_port_is_audio (porttype))
1153 // audio port, resample if necessary
1155 #if HAVE_SAMPLERATE
1156 if (net_period_down != nframes)
1158 SRC_STATE *src_state = src_node->data;
1159 for (i = 0; i < net_period_down; i++)
1161 floatbuf[i] = ((float) ntohs(packet_bufX[i])) / 32767.0 - 1.0;
1164 src.data_in = floatbuf;
1165 src.input_frames = net_period_down;
1167 src.data_out = buf;
1168 src.output_frames = nframes;
1170 src.src_ratio = (float) nframes / (float) net_period_down;
1171 src.end_of_input = 0;
1173 src_set_ratio (src_state, src.src_ratio);
1174 src_process (src_state, &src);
1175 src_node = jack_slist_next (src_node);
1177 else
1178 #endif
1179 for (i = 0; i < net_period_down; i++)
1180 buf[i] = ((float) ntohs (packet_bufX[i])) / 32768.0 - 1.0;
1182 else if (jack_port_is_midi (porttype))
1184 // midi port, decode midi events
1185 // convert the data buffer to a standard format (uint32_t based)
1186 unsigned int buffer_size_uint32 = net_period_down / 2;
1187 uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
1188 decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
1190 packet_bufX = (packet_bufX + net_period_down);
1191 node = jack_slist_next (node);
1192 chn++;
1196 void
1197 render_jack_ports_to_payload_16bit (JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up)
1199 int chn = 0;
1200 JSList *node = playback_ports;
1201 #if HAVE_SAMPLERATE
1202 JSList *src_node = playback_srcs;
1203 #endif
1205 uint16_t *packet_bufX = (uint16_t *)packet_payload;
1207 while (node != NULL)
1209 #if HAVE_SAMPLERATE
1210 SRC_DATA src;
1211 #endif
1212 int i;
1213 jack_port_t *port = (jack_port_t *) node->data;
1214 jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes);
1215 const char *porttype = jack_port_type (port);
1217 if (jack_port_is_audio (porttype))
1219 // audio port, resample if necessary
1221 #if HAVE_SAMPLERATE
1222 if (net_period_up != nframes)
1224 SRC_STATE *src_state = src_node->data;
1226 float *floatbuf = alloca (sizeof(float) * net_period_up);
1228 src.data_in = buf;
1229 src.input_frames = nframes;
1231 src.data_out = floatbuf;
1232 src.output_frames = net_period_up;
1234 src.src_ratio = (float) net_period_up / (float) nframes;
1235 src.end_of_input = 0;
1237 src_set_ratio (src_state, src.src_ratio);
1238 src_process (src_state, &src);
1240 for (i = 0; i < net_period_up; i++)
1242 packet_bufX[i] = htons (((uint16_t)((floatbuf[i] + 1.0) * 32767.0)));
1244 src_node = jack_slist_next (src_node);
1246 else
1247 #endif
1248 for (i = 0; i < net_period_up; i++)
1249 packet_bufX[i] = htons(((uint16_t)((buf[i] + 1.0) * 32767.0)));
1251 else if (jack_port_is_midi (porttype))
1253 // encode midi events from port to packet
1254 // convert the data buffer to a standard format (uint32_t based)
1255 unsigned int buffer_size_uint32 = net_period_up / 2;
1256 uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
1257 encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
1259 packet_bufX = (packet_bufX + net_period_up);
1260 node = jack_slist_next (node);
1261 chn++;
1265 // render functions for 8bit
1266 void
1267 render_payload_to_jack_ports_8bit (void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes)
1269 int chn = 0;
1270 JSList *node = capture_ports;
1272 #if HAVE_SAMPLERATE
1273 JSList *src_node = capture_srcs;
1274 #endif
1276 int8_t *packet_bufX = (int8_t *)packet_payload;
1278 if( !packet_payload )
1279 return;
1281 while (node != NULL)
1283 int i;
1284 //uint32_t val;
1285 #if HAVE_SAMPLERATE
1286 SRC_DATA src;
1287 #endif
1289 jack_port_t *port = (jack_port_t *) node->data;
1290 jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes);
1292 #if HAVE_SAMPLERATE
1293 float *floatbuf = alloca (sizeof (float) * net_period_down);
1294 #endif
1295 const char *porttype = jack_port_type (port);
1297 if (jack_port_is_audio(porttype))
1299 #if HAVE_SAMPLERATE
1300 // audio port, resample if necessary
1301 if (net_period_down != nframes)
1303 SRC_STATE *src_state = src_node->data;
1304 for (i = 0; i < net_period_down; i++)
1305 floatbuf[i] = ((float) packet_bufX[i]) / 127.0;
1307 src.data_in = floatbuf;
1308 src.input_frames = net_period_down;
1310 src.data_out = buf;
1311 src.output_frames = nframes;
1313 src.src_ratio = (float) nframes / (float) net_period_down;
1314 src.end_of_input = 0;
1316 src_set_ratio (src_state, src.src_ratio);
1317 src_process (src_state, &src);
1318 src_node = jack_slist_next (src_node);
1320 else
1321 #endif
1322 for (i = 0; i < net_period_down; i++)
1323 buf[i] = ((float) packet_bufX[i]) / 127.0;
1325 else if (jack_port_is_midi (porttype))
1327 // midi port, decode midi events
1328 // convert the data buffer to a standard format (uint32_t based)
1329 unsigned int buffer_size_uint32 = net_period_down / 2;
1330 uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
1331 decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
1333 packet_bufX = (packet_bufX + net_period_down);
1334 node = jack_slist_next (node);
1335 chn++;
1339 void
1340 render_jack_ports_to_payload_8bit (JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up)
1342 int chn = 0;
1343 JSList *node = playback_ports;
1344 #if HAVE_SAMPLERATE
1345 JSList *src_node = playback_srcs;
1346 #endif
1348 int8_t *packet_bufX = (int8_t *)packet_payload;
1350 while (node != NULL)
1352 #if HAVE_SAMPLERATE
1353 SRC_DATA src;
1354 #endif
1355 int i;
1356 jack_port_t *port = (jack_port_t *) node->data;
1358 jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes);
1359 const char *porttype = jack_port_type (port);
1361 if (jack_port_is_audio (porttype))
1363 #if HAVE_SAMPLERATE
1364 // audio port, resample if necessary
1365 if (net_period_up != nframes)
1368 SRC_STATE *src_state = src_node->data;
1370 float *floatbuf = alloca (sizeof (float) * net_period_up);
1372 src.data_in = buf;
1373 src.input_frames = nframes;
1375 src.data_out = floatbuf;
1376 src.output_frames = net_period_up;
1378 src.src_ratio = (float) net_period_up / (float) nframes;
1379 src.end_of_input = 0;
1381 src_set_ratio (src_state, src.src_ratio);
1382 src_process (src_state, &src);
1384 for (i = 0; i < net_period_up; i++)
1385 packet_bufX[i] = floatbuf[i] * 127.0;
1386 src_node = jack_slist_next (src_node);
1388 else
1389 #endif
1390 for (i = 0; i < net_period_up; i++)
1391 packet_bufX[i] = buf[i] * 127.0;
1393 else if (jack_port_is_midi (porttype))
1395 // encode midi events from port to packet
1396 // convert the data buffer to a standard format (uint32_t based)
1397 unsigned int buffer_size_uint32 = net_period_up / 4;
1398 uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
1399 encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
1401 packet_bufX = (packet_bufX + net_period_up);
1402 node = jack_slist_next (node);
1403 chn++;
1407 #if HAVE_CELT
1408 // render functions for celt.
1409 void
1410 render_payload_to_jack_ports_celt (void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes)
1412 int chn = 0;
1413 JSList *node = capture_ports;
1414 JSList *src_node = capture_srcs;
1416 unsigned char *packet_bufX = (unsigned char *)packet_payload;
1418 while (node != NULL)
1420 jack_port_t *port = (jack_port_t *) node->data;
1421 jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes);
1423 const char *porttype = jack_port_type (port);
1425 if (jack_port_is_audio (porttype))
1427 // audio port, decode celt data.
1429 CELTDecoder *decoder = src_node->data;
1430 if( !packet_payload )
1431 celt_decode_float( decoder, NULL, net_period_down, buf );
1432 else
1433 celt_decode_float( decoder, packet_bufX, net_period_down, buf );
1435 src_node = jack_slist_next (src_node);
1437 else if (jack_port_is_midi (porttype))
1439 // midi port, decode midi events
1440 // convert the data buffer to a standard format (uint32_t based)
1441 unsigned int buffer_size_uint32 = net_period_down / 2;
1442 uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
1443 if( packet_payload )
1444 decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
1446 packet_bufX = (packet_bufX + net_period_down);
1447 node = jack_slist_next (node);
1448 chn++;
1452 void
1453 render_jack_ports_to_payload_celt (JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up)
1455 int chn = 0;
1456 JSList *node = playback_ports;
1457 JSList *src_node = playback_srcs;
1459 unsigned char *packet_bufX = (unsigned char *)packet_payload;
1461 while (node != NULL)
1463 jack_port_t *port = (jack_port_t *) node->data;
1464 jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes);
1465 const char *porttype = jack_port_type (port);
1467 if (jack_port_is_audio (porttype))
1469 // audio port, encode celt data.
1471 int encoded_bytes;
1472 float *floatbuf = alloca (sizeof(float) * nframes );
1473 memcpy( floatbuf, buf, nframes*sizeof(float) );
1474 CELTEncoder *encoder = src_node->data;
1475 encoded_bytes = celt_encode_float( encoder, floatbuf, NULL, packet_bufX, net_period_up );
1476 if( encoded_bytes != net_period_up )
1477 printf( "something in celt changed. netjack needs to be changed to handle this.\n" );
1478 src_node = jack_slist_next( src_node );
1480 else if (jack_port_is_midi (porttype))
1482 // encode midi events from port to packet
1483 // convert the data buffer to a standard format (uint32_t based)
1484 unsigned int buffer_size_uint32 = net_period_up / 2;
1485 uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
1486 encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
1488 packet_bufX = (packet_bufX + net_period_up);
1489 node = jack_slist_next (node);
1490 chn++;
1494 #endif
1495 /* Wrapper functions with bitdepth argument... */
1496 void
1497 render_payload_to_jack_ports (int bitdepth, void *packet_payload, jack_nframes_t net_period_down, JSList *capture_ports, JSList *capture_srcs, jack_nframes_t nframes, int dont_htonl_floats)
1499 if (bitdepth == 8)
1500 render_payload_to_jack_ports_8bit (packet_payload, net_period_down, capture_ports, capture_srcs, nframes);
1501 else if (bitdepth == 16)
1502 render_payload_to_jack_ports_16bit (packet_payload, net_period_down, capture_ports, capture_srcs, nframes);
1503 #if HAVE_CELT
1504 else if (bitdepth == CELT_MODE)
1505 render_payload_to_jack_ports_celt (packet_payload, net_period_down, capture_ports, capture_srcs, nframes);
1506 #endif
1507 else
1508 render_payload_to_jack_ports_float (packet_payload, net_period_down, capture_ports, capture_srcs, nframes, dont_htonl_floats);
1511 void
1512 render_jack_ports_to_payload (int bitdepth, JSList *playback_ports, JSList *playback_srcs, jack_nframes_t nframes, void *packet_payload, jack_nframes_t net_period_up, int dont_htonl_floats)
1514 if (bitdepth == 8)
1515 render_jack_ports_to_payload_8bit (playback_ports, playback_srcs, nframes, packet_payload, net_period_up);
1516 else if (bitdepth == 16)
1517 render_jack_ports_to_payload_16bit (playback_ports, playback_srcs, nframes, packet_payload, net_period_up);
1518 #if HAVE_CELT
1519 else if (bitdepth == CELT_MODE)
1520 render_jack_ports_to_payload_celt (playback_ports, playback_srcs, nframes, packet_payload, net_period_up);
1521 #endif
1522 else
1523 render_jack_ports_to_payload_float (playback_ports, playback_srcs, nframes, packet_payload, net_period_up, dont_htonl_floats);