netjack_packet.c 43.9 KB
Newer Older
Torben Hohn's avatar
Torben Hohn committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

/*
 * NetJack - Packet Handling functions
 *
 * used by the driver and the jacknet_client
 *
 * Copyright (C) 2008 Marc-Olivier Barre <marco@marcochapeau.org>
 * Copyright (C) 2008 Pieter Palmers <pieterpalmers@users.sourceforge.net>
 * Copyright (C) 2006 Torben Hohn <torbenh@gmx.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * $Id: net_driver.c,v 1.16 2006/03/20 19:41:37 torbenh Exp $
 *
 */

29
#include "config.h"
Torben Hohn's avatar
Torben Hohn committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

#ifdef __APPLE__
#define _DARWIN_C_SOURCE
#endif

#if HAVE_PPOLL
#define _GNU_SOURCE
#endif

#include <math.h>
#include <stdio.h>
#include <memory.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <stdarg.h>

#include <jack/types.h>

#include <sys/types.h>

#ifdef WIN32
#include <winsock2.h>
53
#define socklen_t int
Torben Hohn's avatar
Torben Hohn committed
54
#include <malloc.h>
unknown's avatar
unknown committed
55
#define socklen_t int
Torben Hohn's avatar
Torben Hohn committed
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <poll.h>
#endif

#include <errno.h>
#include <signal.h>

#if HAVE_SAMPLERATE
#include <samplerate.h>
#endif

#if HAVE_CELT
#include <celt/celt.h>
#endif

#include "netjack_packet.h"

// JACK2 specific.
#include "jack/control.h"

#ifdef NO_JACK_ERROR
#define jack_error printf
#endif

int fraggo = 0;

packet_cache *global_packcache = NULL;

void
packet_header_hton (jacknet_packet_header *pkthdr)
{
    pkthdr->capture_channels_audio = htonl(pkthdr->capture_channels_audio);
    pkthdr->playback_channels_audio = htonl(pkthdr->playback_channels_audio);
    pkthdr->capture_channels_midi = htonl(pkthdr->capture_channels_midi);
    pkthdr->playback_channels_midi = htonl(pkthdr->playback_channels_midi);
    pkthdr->period_size = htonl(pkthdr->period_size);
    pkthdr->sample_rate = htonl(pkthdr->sample_rate);
    pkthdr->sync_state = htonl(pkthdr->sync_state);
    pkthdr->transport_frame = htonl(pkthdr->transport_frame);
    pkthdr->transport_state = htonl(pkthdr->transport_state);
    pkthdr->framecnt = htonl(pkthdr->framecnt);
    pkthdr->latency = htonl(pkthdr->latency);
    pkthdr->reply_port = htonl(pkthdr->reply_port);
    pkthdr->mtu = htonl(pkthdr->mtu);
    pkthdr->fragment_nr = htonl(pkthdr->fragment_nr);
}

void
packet_header_ntoh (jacknet_packet_header *pkthdr)
{
    pkthdr->capture_channels_audio = ntohl(pkthdr->capture_channels_audio);
    pkthdr->playback_channels_audio = ntohl(pkthdr->playback_channels_audio);
    pkthdr->capture_channels_midi = ntohl(pkthdr->capture_channels_midi);
    pkthdr->playback_channels_midi = ntohl(pkthdr->playback_channels_midi);
    pkthdr->period_size = ntohl(pkthdr->period_size);
    pkthdr->sample_rate = ntohl(pkthdr->sample_rate);
    pkthdr->sync_state = ntohl(pkthdr->sync_state);
    pkthdr->transport_frame = ntohl(pkthdr->transport_frame);
    pkthdr->transport_state = ntohl(pkthdr->transport_state);
    pkthdr->framecnt = ntohl(pkthdr->framecnt);
    pkthdr->latency = ntohl(pkthdr->latency);
    pkthdr->reply_port = ntohl(pkthdr->reply_port);
    pkthdr->mtu = ntohl(pkthdr->mtu);
    pkthdr->fragment_nr = ntohl(pkthdr->fragment_nr);
}

int get_sample_size (int bitdepth)
{
    if (bitdepth == 8)
        return sizeof (int8_t);
    if (bitdepth == 16)
        return sizeof (int16_t);
130
131
132
    //JN: why? is this for buffer sizes before or after encoding?
    //JN: if the former, why not int16_t, if the latter, shouldn't it depend on -c N?    
    if( bitdepth == CELT_MODE )
Torben Hohn's avatar
Torben Hohn committed
133
134
135
136
	return sizeof( unsigned char );
    return sizeof (int32_t);
}

137
138
139
140
141
142
143
144
145
146
147
int jack_port_is_audio(const char *porttype)
{
    return (strncmp (porttype, JACK_DEFAULT_AUDIO_TYPE, jack_port_type_size()) == 0);
}

int jack_port_is_midi(const char *porttype)
{
    return (strncmp (porttype, JACK_DEFAULT_MIDI_TYPE, jack_port_type_size()) == 0);
}


Torben Hohn's avatar
Torben Hohn committed
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
// fragment management functions.

packet_cache
*packet_cache_new (int num_packets, int pkt_size, int mtu)
{
    int fragment_payload_size = mtu - sizeof (jacknet_packet_header);
    int i, fragment_number;

    if( pkt_size == sizeof(jacknet_packet_header) )
	    fragment_number = 1;
    else
	    fragment_number = (pkt_size - sizeof (jacknet_packet_header) - 1) / fragment_payload_size + 1;

    packet_cache *pcache = malloc (sizeof (packet_cache));
    if (pcache == NULL)
    {
164
        jack_error ("could not allocate packet cache (1)");
Torben Hohn's avatar
Torben Hohn committed
165
166
167
168
169
170
171
172
173
174
175
        return NULL;
    }

    pcache->size = num_packets;
    pcache->packets = malloc (sizeof (cache_packet) * num_packets);
    pcache->master_address_valid = 0;
    pcache->last_framecnt_retreived = 0;
    pcache->last_framecnt_retreived_valid = 0;

    if (pcache->packets == NULL)
    {
176
        jack_error ("could not allocate packet cache (2)");
Torben Hohn's avatar
Torben Hohn committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
        return NULL;
    }

    for (i = 0; i < num_packets; i++)
    {
        pcache->packets[i].valid = 0;
        pcache->packets[i].num_fragments = fragment_number;
        pcache->packets[i].packet_size = pkt_size;
        pcache->packets[i].mtu = mtu;
        pcache->packets[i].framecnt = 0;
        pcache->packets[i].fragment_array = malloc (sizeof (char) * fragment_number);
        pcache->packets[i].packet_buf = malloc (pkt_size);
        if ((pcache->packets[i].fragment_array == NULL) || (pcache->packets[i].packet_buf == NULL))
        {
191
            jack_error ("could not allocate packet cache (3)");
Torben Hohn's avatar
Torben Hohn committed
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
            return NULL;
        }
    }
    pcache->mtu = mtu;

    return pcache;
}

void
packet_cache_free (packet_cache *pcache)
{
    int i;
    if( pcache == NULL )
	return;

    for (i = 0; i < pcache->size; i++)
    {
        free (pcache->packets[i].fragment_array);
        free (pcache->packets[i].packet_buf);
    }

    free (pcache->packets);
    free (pcache);
}

cache_packet
*packet_cache_get_packet (packet_cache *pcache, jack_nframes_t framecnt)
{
    int i;
    cache_packet *retval;

    for (i = 0; i < pcache->size; i++)
    {
        if (pcache->packets[i].valid && (pcache->packets[i].framecnt == framecnt))
            return &(pcache->packets[i]);
    }

    // The Packet is not in the packet cache.
    // find a free packet.

    retval = packet_cache_get_free_packet (pcache);
    if (retval != NULL)
    {
        cache_packet_set_framecnt (retval, framecnt);
        return retval;
    }

    // No Free Packet available
    // Get The Oldest packet and reset it.

    retval = packet_cache_get_oldest_packet (pcache);
    //printf( "Dropping %d from Cache :S\n", retval->framecnt );
    cache_packet_reset (retval);
    cache_packet_set_framecnt (retval, framecnt);

    return retval;
}

// TODO: fix wrapping case... need to pass
//       current expected frame here.
//
//       or just save framecount into packet_cache.

cache_packet
*packet_cache_get_oldest_packet (packet_cache *pcache)
{
    jack_nframes_t minimal_frame = JACK_MAX_FRAMES;
    cache_packet *retval = &(pcache->packets[0]);
    int i;

    for (i = 0; i < pcache->size; i++)
    {
        if (pcache->packets[i].valid && (pcache->packets[i].framecnt < minimal_frame))
        {
            minimal_frame = pcache->packets[i].framecnt;
            retval = &(pcache->packets[i]);
        }
    }

    return retval;
}

cache_packet
*packet_cache_get_free_packet (packet_cache *pcache)
{
    int i;

    for (i = 0; i < pcache->size; i++)
    {
        if (pcache->packets[i].valid == 0)
            return &(pcache->packets[i]);
    }

    return NULL;
}

void
cache_packet_reset (cache_packet *pack)
{
    int i;
    pack->valid = 0;

    // XXX: i dont think this is necessary here...
    //      fragement array is cleared in _set_framecnt()

    for (i = 0; i < pack->num_fragments; i++)
        pack->fragment_array[i] = 0;
}

void
cache_packet_set_framecnt (cache_packet *pack, jack_nframes_t framecnt)
{
    int i;

    pack->framecnt = framecnt;

    for (i = 0; i < pack->num_fragments; i++)
        pack->fragment_array[i] = 0;

    pack->valid = 1;
}

void
cache_packet_add_fragment (cache_packet *pack, char *packet_buf, int rcv_len)
{
    jacknet_packet_header *pkthdr = (jacknet_packet_header *) packet_buf;
    int fragment_payload_size = pack->mtu - sizeof (jacknet_packet_header);
    char *packet_bufX = pack->packet_buf + sizeof (jacknet_packet_header);
    char *dataX = packet_buf + sizeof (jacknet_packet_header);

    jack_nframes_t fragment_nr = ntohl (pkthdr->fragment_nr);
    jack_nframes_t framecnt    = ntohl (pkthdr->framecnt);

    if (framecnt != pack->framecnt)
    {
327
        jack_error ("errror. framecnts dont match");
Torben Hohn's avatar
Torben Hohn committed
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
        return;
    }


    if (fragment_nr == 0)
    {
        memcpy (pack->packet_buf, packet_buf, rcv_len);
        pack->fragment_array[0] = 1;

        return;
    }

    if ((fragment_nr < pack->num_fragments) && (fragment_nr > 0))
    {
        if ((fragment_nr * fragment_payload_size + rcv_len - sizeof (jacknet_packet_header)) <= (pack->packet_size - sizeof (jacknet_packet_header)))
        {
            memcpy (packet_bufX + fragment_nr * fragment_payload_size, dataX, rcv_len - sizeof (jacknet_packet_header));
            pack->fragment_array[fragment_nr] = 1;
        }
        else
            jack_error ("too long packet received...");
    }
}

int
cache_packet_is_complete (cache_packet *pack)
{
    int i;
    for (i = 0; i < pack->num_fragments; i++)
        if (pack->fragment_array[i] == 0)
            return 0;

    return 1;
}

#ifndef WIN32
// new poll using nanoseconds resolution and
// not waiting forever.
int
netjack_poll_deadline (int sockfd, jack_time_t deadline)
{
    struct pollfd fds;
370
    int poll_err = 0;
Torben Hohn's avatar
Torben Hohn committed
371
372
373
374
375
376
377
378
379
380
381
#if HAVE_PPOLL
    struct timespec timeout_spec = { 0, 0 };
#else
    int timeout;
#endif


    jack_time_t now = jack_get_time();
    if( now >= deadline )
	return 0;

382
383
384
385
    if( (deadline-now) >= 1000000 ) {
	    jack_error( "deadline more than 1 second in the future, trimming it." );
	    deadline = now+500000;
    }
Torben Hohn's avatar
Torben Hohn committed
386
387
388
#if HAVE_PPOLL
    timeout_spec.tv_nsec = (deadline - now) * 1000;
#else
389
    timeout = (deadline - now + 500) / 1000;
Torben Hohn's avatar
Torben Hohn committed
390
391
392
393
394
395
396
#endif


    fds.fd = sockfd;
    fds.events = POLLIN;

#if HAVE_PPOLL
397
    poll_err = ppoll (&fds, 1, &timeout_spec, NULL);
Torben Hohn's avatar
Torben Hohn committed
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#else
    poll_err = poll (&fds, 1, timeout);
#endif

    if (poll_err == -1)
    {
        switch (errno)
        {
            case EBADF:
            jack_error ("Error %d: An invalid file descriptor was given in one of the sets", errno);
            break;
            case EFAULT:
            jack_error ("Error %d: The array given as argument was not contained in the calling program's address space", errno);
            break;
            case EINTR:
            jack_error ("Error %d: A signal occurred before any requested event", errno);
            break;
            case EINVAL:
            jack_error ("Error %d: The nfds value exceeds the RLIMIT_NOFILE value", errno);
            break;
            case ENOMEM:
            jack_error ("Error %d: There was no space to allocate file descriptor tables", errno);
            break;
        }
    }
    return poll_err;
}

int
netjack_poll (int sockfd, int timeout)
{
    struct pollfd fds;
    int i, poll_err = 0;
    sigset_t sigmask, rsigmask;
    struct sigaction action;

    sigemptyset(&sigmask);
	sigaddset(&sigmask, SIGHUP);
	sigaddset(&sigmask, SIGINT);
	sigaddset(&sigmask, SIGQUIT);
	sigaddset(&sigmask, SIGPIPE);
	sigaddset(&sigmask, SIGTERM);
	sigaddset(&sigmask, SIGUSR1);
	sigaddset(&sigmask, SIGUSR2);

	action.sa_handler = SIG_DFL;
	action.sa_mask = sigmask;
	action.sa_flags = SA_RESTART;

    for (i = 1; i < NSIG; i++)
        if (sigismember (&sigmask, i))
            sigaction (i, &action, 0);

    fds.fd = sockfd;
    fds.events = POLLIN;

    sigprocmask(SIG_UNBLOCK, &sigmask, &rsigmask);
    while (poll_err == 0)
    {
        poll_err = poll (&fds, 1, timeout);
    }
    sigprocmask(SIG_SETMASK, &rsigmask, NULL);

    if (poll_err == -1)
    {
        switch (errno)
        {
            case EBADF:
            jack_error ("Error %d: An invalid file descriptor was given in one of the sets", errno);
            break;
            case EFAULT:
            jack_error ("Error %d: The array given as argument was not contained in the calling program's address space", errno);
            break;
            case EINTR:
            jack_error ("Error %d: A signal occurred before any requested event", errno);
            break;
            case EINVAL:
            jack_error ("Error %d: The nfds value exceeds the RLIMIT_NOFILE value", errno);
            break;
            case ENOMEM:
            jack_error ("Error %d: There was no space to allocate file descriptor tables", errno);
            break;
        }
        return 0;
    }
    return 1;
}

#else
int
netjack_poll (int sockfd, int timeout)
{
490
    jack_error( "netjack_poll not implemented" );
Torben Hohn's avatar
Torben Hohn committed
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
    return 0;
}
int
netjack_poll_deadline (int sockfd, jack_time_t deadline)
{
    fd_set fds;
    FD_ZERO( &fds );
    FD_SET( sockfd, &fds );

    struct timeval timeout;
    while( 1 ) {
        jack_time_t now = jack_get_time();
        if( now >= deadline )
                return 0;

        int timeout_usecs = (deadline - now);
    //jack_error( "timeout = %d", timeout_usecs );
        timeout.tv_sec = 0;
        timeout.tv_usec = (timeout_usecs < 500) ? 500 : timeout_usecs;
510
        timeout.tv_usec = (timeout_usecs > 1000000) ? 500000 : timeout_usecs;
Torben Hohn's avatar
Torben Hohn committed
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690

        int poll_err = select (0, &fds, NULL, NULL, &timeout);
        if( poll_err != 0 )
            return poll_err;
    }

    return 0;
}
#endif
// This now reads all a socket has into the cache.
// replacing netjack_recv functions.

void
packet_cache_drain_socket( packet_cache *pcache, int sockfd )
{
    char *rx_packet = alloca (pcache->mtu);
    jacknet_packet_header *pkthdr = (jacknet_packet_header *) rx_packet;
    int rcv_len;
    jack_nframes_t framecnt;
    cache_packet *cpack;
    struct sockaddr_in sender_address;
#ifdef WIN32
    size_t senderlen = sizeof( struct sockaddr_in );
    u_long parm = 1;
    ioctlsocket( sockfd, FIONBIO, &parm );
#else
    socklen_t senderlen = sizeof( struct sockaddr_in );
#endif
    while (1)
    {
#ifdef WIN32
        rcv_len = recvfrom (sockfd, rx_packet, pcache->mtu, 0,
			    (struct sockaddr*) &sender_address, &senderlen);
#else
        rcv_len = recvfrom (sockfd, rx_packet, pcache->mtu, MSG_DONTWAIT,
			    (struct sockaddr*) &sender_address, &senderlen);
#endif
        if (rcv_len < 0)
            return;

	if (pcache->master_address_valid) {
	    // Verify its from our master.
	    if (memcmp (&sender_address, &(pcache->master_address), senderlen) != 0)
		continue;
	} else {
	    // Setup this one as master
	    //printf( "setup master...\n" );
	    memcpy ( &(pcache->master_address), &sender_address, senderlen );
	    pcache->master_address_valid = 1;
	}

        framecnt = ntohl (pkthdr->framecnt);
	if( pcache->last_framecnt_retreived_valid && (framecnt <= pcache->last_framecnt_retreived ))
	    continue;

        cpack = packet_cache_get_packet (global_packcache, framecnt);
        cache_packet_add_fragment (cpack, rx_packet, rcv_len);
	cpack->recv_timestamp = jack_get_time();
    }
}

void
packet_cache_reset_master_address( packet_cache *pcache )
{
    pcache->master_address_valid = 0;
    pcache->last_framecnt_retreived = 0;
    pcache->last_framecnt_retreived_valid = 0;
}

void
packet_cache_clear_old_packets (packet_cache *pcache, jack_nframes_t framecnt )
{
    int i;

    for (i = 0; i < pcache->size; i++)
    {
        if (pcache->packets[i].valid && (pcache->packets[i].framecnt < framecnt))
        {
            cache_packet_reset (&(pcache->packets[i]));
        }
    }
}

int
packet_cache_retreive_packet_pointer( packet_cache *pcache, jack_nframes_t framecnt, char **packet_buf, int pkt_size, jack_time_t *timestamp )
{
    int i;
    cache_packet *cpack = NULL;


    for (i = 0; i < pcache->size; i++) {
        if (pcache->packets[i].valid && (pcache->packets[i].framecnt == framecnt)) {
	    cpack = &(pcache->packets[i]);
            break;
	}
    }

    if( cpack == NULL ) {
	//printf( "retreive packet: %d....not found\n", framecnt );
	return -1;
    }

    if( !cache_packet_is_complete( cpack ) ) {
	return -1;
    }

    // ok. cpack is the one we want and its complete.
    *packet_buf = cpack->packet_buf;
    if( timestamp )
	*timestamp = cpack->recv_timestamp;

    pcache->last_framecnt_retreived_valid = 1;
    pcache->last_framecnt_retreived = framecnt;

    return pkt_size;
}

int
packet_cache_release_packet( packet_cache *pcache, jack_nframes_t framecnt )
{
    int i;
    cache_packet *cpack = NULL;


    for (i = 0; i < pcache->size; i++) {
        if (pcache->packets[i].valid && (pcache->packets[i].framecnt == framecnt)) {
	    cpack = &(pcache->packets[i]);
            break;
	}
    }

    if( cpack == NULL ) {
	//printf( "retreive packet: %d....not found\n", framecnt );
	return -1;
    }

    if( !cache_packet_is_complete( cpack ) ) {
	return -1;
    }

    cache_packet_reset (cpack);
    packet_cache_clear_old_packets( pcache, framecnt );

    return 0;
}
float
packet_cache_get_fill( packet_cache *pcache, jack_nframes_t expected_framecnt )
{
    int num_packets_before_us = 0;
    int i;

    for (i = 0; i < pcache->size; i++)
    {
	cache_packet *cpack = &(pcache->packets[i]);
        if (cpack->valid && cache_packet_is_complete( cpack ))
	    if( cpack->framecnt >= expected_framecnt )
		num_packets_before_us += 1;
    }

    return 100.0 * (float)num_packets_before_us / (float)( pcache->size ) ;
}

// Returns 0 when no valid packet is inside the cache.
int
packet_cache_get_next_available_framecnt( packet_cache *pcache, jack_nframes_t expected_framecnt, jack_nframes_t *framecnt )
{
    int i;
    jack_nframes_t best_offset = JACK_MAX_FRAMES/2-1;
    int retval = 0;

    for (i = 0; i < pcache->size; i++)
    {
	cache_packet *cpack = &(pcache->packets[i]);
	//printf( "p%d: valid=%d, frame %d\n", i, cpack->valid, cpack->framecnt );

        if (!cpack->valid || !cache_packet_is_complete( cpack )) {
	    //printf( "invalid\n" );
	    continue;
	}

691
692
693
	if( cpack->framecnt < expected_framecnt )
	    continue;

Torben Hohn's avatar
Torben Hohn committed
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
	if( (cpack->framecnt - expected_framecnt) > best_offset ) {
	    continue;
	}

	best_offset = cpack->framecnt - expected_framecnt;
	retval = 1;

	if( best_offset == 0 )
	    break;
    }
    if( retval && framecnt )
	*framecnt = expected_framecnt + best_offset;

    return retval;
}

int
packet_cache_get_highest_available_framecnt( packet_cache *pcache, jack_nframes_t *framecnt )
{
    int i;
    jack_nframes_t best_value = 0;
    int retval = 0;

    for (i = 0; i < pcache->size; i++)
    {
	cache_packet *cpack = &(pcache->packets[i]);
	//printf( "p%d: valid=%d, frame %d\n", i, cpack->valid, cpack->framecnt );

        if (!cpack->valid || !cache_packet_is_complete( cpack )) {
	    //printf( "invalid\n" );
	    continue;
	}

	if (cpack->framecnt < best_value) {
	    continue;
	}

	best_value = cpack->framecnt;
	retval = 1;

    }
    if( retval && framecnt )
	*framecnt = best_value;

    return retval;
}

// Returns 0 when no valid packet is inside the cache.
int
packet_cache_find_latency( packet_cache *pcache, jack_nframes_t expected_framecnt, jack_nframes_t *framecnt )
{
    int i;
    jack_nframes_t best_offset = 0;
    int retval = 0;

    for (i = 0; i < pcache->size; i++)
    {
	cache_packet *cpack = &(pcache->packets[i]);
	//printf( "p%d: valid=%d, frame %d\n", i, cpack->valid, cpack->framecnt );

        if (!cpack->valid || !cache_packet_is_complete( cpack )) {
	    //printf( "invalid\n" );
	    continue;
	}

	if( (cpack->framecnt - expected_framecnt) < best_offset ) {
	    continue;
	}

	best_offset = cpack->framecnt - expected_framecnt;
	retval = 1;

	if( best_offset == 0 )
	    break;
    }
    if( retval && framecnt )
	*framecnt = JACK_MAX_FRAMES - best_offset;

    return retval;
}
// fragmented packet IO
int
netjack_recvfrom (int sockfd, char *packet_buf, int pkt_size, int flags, struct sockaddr *addr, size_t *addr_size, int mtu)
{
    int retval;
    socklen_t from_len = *addr_size;
    if (pkt_size <= mtu) {
        retval = recvfrom (sockfd, packet_buf, pkt_size, flags, addr, &from_len);
	*addr_size = from_len;
	return retval;
    }

    char *rx_packet = alloca (mtu);
    jacknet_packet_header *pkthdr = (jacknet_packet_header *) rx_packet;
    int rcv_len;
    jack_nframes_t framecnt;
    cache_packet *cpack;
    do
    {
        rcv_len = recvfrom (sockfd, rx_packet, mtu, 0, addr, &from_len);
        if (rcv_len < 0)
            return rcv_len;
        framecnt = ntohl (pkthdr->framecnt);
        cpack = packet_cache_get_packet (global_packcache, framecnt);
        cache_packet_add_fragment (cpack, rx_packet, rcv_len);
    } while (!cache_packet_is_complete (cpack));
    memcpy (packet_buf, cpack->packet_buf, pkt_size);
    cache_packet_reset (cpack);
    *addr_size = from_len;
    return pkt_size;
}

int
netjack_recv (int sockfd, char *packet_buf, int pkt_size, int flags, int mtu)
{
    if (pkt_size <= mtu)
        return recv (sockfd, packet_buf, pkt_size, flags);
    char *rx_packet = alloca (mtu);
    jacknet_packet_header *pkthdr = (jacknet_packet_header *) rx_packet;
    int rcv_len;
    jack_nframes_t framecnt;
    cache_packet *cpack;
    do
    {
        rcv_len = recv (sockfd, rx_packet, mtu, flags);
        if (rcv_len < 0)
            return rcv_len;
        framecnt = ntohl (pkthdr->framecnt);
        cpack = packet_cache_get_packet (global_packcache, framecnt);
        cache_packet_add_fragment (cpack, rx_packet, rcv_len);
    } while (!cache_packet_is_complete (cpack));
    memcpy (packet_buf, cpack->packet_buf, pkt_size);
    cache_packet_reset (cpack);
    return pkt_size;
}

void
netjack_sendto (int sockfd, char *packet_buf, int pkt_size, int flags, struct sockaddr *addr, int addr_size, int mtu)
{
    int frag_cnt = 0;
    char *tx_packet, *dataX;
    jacknet_packet_header *pkthdr;

    tx_packet = alloca (mtu + 10);
    dataX = tx_packet + sizeof (jacknet_packet_header);
    pkthdr = (jacknet_packet_header *) tx_packet;

    int fragment_payload_size = mtu - sizeof (jacknet_packet_header);

    if (pkt_size <= mtu) {
	int err;
	pkthdr = (jacknet_packet_header *) packet_buf;
        pkthdr->fragment_nr = htonl (0);
        err = sendto(sockfd, packet_buf, pkt_size, flags, addr, addr_size);
	if( err<0 ) {
	    //printf( "error in send\n" );
	    perror( "send" );
	}
    }
    else
    {
	int err;
        // Copy the packet header to the tx pack first.
        memcpy(tx_packet, packet_buf, sizeof (jacknet_packet_header));

        // Now loop and send all
        char *packet_bufX = packet_buf + sizeof (jacknet_packet_header);

        while (packet_bufX < (packet_buf + pkt_size - fragment_payload_size))
        {
            pkthdr->fragment_nr = htonl (frag_cnt++);
            memcpy (dataX, packet_bufX, fragment_payload_size);
            sendto (sockfd, tx_packet, mtu, flags, addr, addr_size);
            packet_bufX += fragment_payload_size;
        }

        int last_payload_size = packet_buf + pkt_size - packet_bufX;
        memcpy (dataX, packet_bufX, last_payload_size);
        pkthdr->fragment_nr = htonl (frag_cnt);
        //jack_log("last fragment_count = %d, payload_size = %d\n", fragment_count, last_payload_size);

        // sendto(last_pack_size);
        err = sendto(sockfd, tx_packet, last_payload_size + sizeof(jacknet_packet_header), flags, addr, addr_size);
	if( err<0 ) {
	    //printf( "error in send\n" );
	    perror( "send" );
	}
    }
}


void
decode_midi_buffer (uint32_t *buffer_uint32, unsigned int buffer_size_uint32, jack_default_audio_sample_t* buf)
{
    int i;
    jack_midi_clear_buffer (buf);
    for (i = 0; i < buffer_size_uint32 - 3;)
    {
        uint32_t payload_size;
        payload_size = buffer_uint32[i];
        payload_size = ntohl (payload_size);
        if (payload_size)
        {
            jack_midi_event_t event;
            event.time = ntohl (buffer_uint32[i+1]);
            event.size = ntohl (buffer_uint32[i+2]);
            event.buffer = (jack_midi_data_t*) (&(buffer_uint32[i+3]));
            jack_midi_event_write (buf, event.time, event.buffer, event.size);

            // skip to the next event
            unsigned int nb_data_quads = (((event.size-1) & ~0x3) >> 2)+1;
            i += 3+nb_data_quads;
        }
        else
            break; // no events can follow an empty event, we're done
    }
}

void
encode_midi_buffer (uint32_t *buffer_uint32, unsigned int buffer_size_uint32, jack_default_audio_sample_t* buf)
{
    int i;
    unsigned int written = 0;
    // midi port, encode midi events
    unsigned int nevents = jack_midi_get_event_count (buf);
    for (i = 0; i < nevents; ++i)
    {
        jack_midi_event_t event;
        jack_midi_event_get (&event, buf, i);
        unsigned int nb_data_quads = (((event.size - 1) & ~0x3) >> 2) + 1;
        unsigned int payload_size = 3 + nb_data_quads;
        // only write if we have sufficient space for the event
        // otherwise drop it
        if (written + payload_size < buffer_size_uint32 - 1)
        {
            // write header
            buffer_uint32[written]=htonl (payload_size);
            written++;
            buffer_uint32[written]=htonl (event.time);
            written++;
            buffer_uint32[written]=htonl (event.size);
            written++;

            // write data
            jack_midi_data_t* tmpbuff = (jack_midi_data_t*)(&(buffer_uint32[written]));
            memcpy (tmpbuff, event.buffer, event.size);
            written += nb_data_quads;
        }
        else
        {
            // buffer overflow
            jack_error ("midi buffer overflow");
            break;
        }
    }
    // now put a netjack_midi 'no-payload' event, signaling EOF
    buffer_uint32[written]=0;
}

// render functions for float
void
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)
{
    int chn = 0;
    JSList *node = capture_ports;
#if HAVE_SAMPLERATE
    JSList *src_node = capture_srcs;
#endif

    uint32_t *packet_bufX = (uint32_t *)packet_payload;

    if( !packet_payload )
	return;

    while (node != NULL)
    {
        int i;
        int_float_t val;
#if HAVE_SAMPLERATE
        SRC_DATA src;
#endif

        jack_port_t *port = (jack_port_t *) node->data;
        jack_default_audio_sample_t* buf = jack_port_get_buffer (port, nframes);

        const char *porttype = jack_port_type (port);

981
        if (jack_port_is_audio (porttype))
Torben Hohn's avatar
Torben Hohn committed
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
        {
#if HAVE_SAMPLERATE
            // audio port, resample if necessary
            if (net_period_down != nframes)
            {
                SRC_STATE *src_state = src_node->data;
                for (i = 0; i < net_period_down; i++)
                {
                    packet_bufX[i] = ntohl (packet_bufX[i]);
                }

                src.data_in = (float *) packet_bufX;
                src.input_frames = net_period_down;

                src.data_out = buf;
                src.output_frames = nframes;

                src.src_ratio = (float) nframes / (float) net_period_down;
                src.end_of_input = 0;
For faster browsing, not all history is shown. View entire blame