summaryrefslogtreecommitdiff
path: root/drivers/netjack/netjack_packet.c
blob: 35b25201b99493ec0bb36efee7399cc627013ddf (plain)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
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
327
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
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
691
692
693
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
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477

/*
 * 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 $
 *
 */

#include "config.h"

#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>

// for jack_error in jack1
#include "internal.h"

#include <sys/types.h>

#ifdef WIN32
#include <winsock2.h>
#include <malloc.h>
#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;

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);
    //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 )
	return sizeof( unsigned char );
    return sizeof (int32_t);
}

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);
}


// 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)
    {
        jack_error ("could not allocate packet cache (1)");
        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)
    {
        jack_error ("could not allocate packet cache (2)");
        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))
        {
            jack_error ("could not allocate packet cache (3)");
            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)
    {
        jack_error ("errror. framecnts dont match");
        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, jack_time_t (*get_microseconds)(void))
{
    struct pollfd fds;
    int poll_err = 0;
#if HAVE_PPOLL
    struct timespec timeout_spec = { 0, 0 };
#else
    int timeout;
#endif


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

    if( (deadline-now) >= 1000000 ) {
	    jack_error( "deadline more than 1 second in the future, trimming it." );
	    deadline = now+500000;
    }
#if HAVE_PPOLL
    timeout_spec.tv_nsec = (deadline - now) * 1000;
#else
    timeout = lrintf( (float)(deadline - now) / 1000.0 );
#endif


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

#if HAVE_PPOLL
    poll_err = ppoll (&fds, 1, &timeout_spec, NULL);
#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)
{
    jack_error( "netjack_poll not implemented" );
    return 0;
}
int
netjack_poll_deadline (int sockfd, jack_time_t deadline, jack_time_t (*get_microseconds)(void))
{
    fd_set fds;
    FD_ZERO( &fds );
    FD_SET( sockfd, &fds );

    struct timeval timeout;
    while( 1 ) {
        jack_time_t now = get_microseconds();
        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;
        timeout.tv_usec = (timeout_usecs > 1000000) ? 500000 : timeout_usecs;

        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, jack_time_t (*get_microseconds)(void) )
{
    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 (pcache, framecnt);
        cache_packet_add_fragment (cpack, rx_packet, rcv_len);
	cpack->recv_timestamp = get_microseconds();
    }
}

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;
	}

	if( cpack->framecnt < expected_framecnt )
	    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 = 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
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);

        if (jack_port_is_audio (porttype))
        {
#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;

                src_set_ratio (src_state, src.src_ratio);
                src_process (src_state, &src);
                src_node = jack_slist_next (src_node);
            }
            else
#endif
            {
		if( dont_htonl_floats )
		{
		    memcpy( buf, packet_bufX, net_period_down*sizeof(jack_default_audio_sample_t));
		}
		else
		{
		    for (i = 0; i < net_period_down; i++)
		    {
			val.i = packet_bufX[i];
			val.i = ntohl (val.i);
			buf[i] = val.f;
		    }
		}
            }
        }
        else if (jack_port_is_midi (porttype))
        {
            // midi port, decode midi events
            // convert the data buffer to a standard format (uint32_t based)
            unsigned int buffer_size_uint32 = net_period_down;
            uint32_t * buffer_uint32 = (uint32_t*)packet_bufX;
            decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
        }
        packet_bufX = (packet_bufX + net_period_down);
        node = jack_slist_next (node);
        chn++;
    }
}

void
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 )
{
    int chn = 0;
    JSList *node = playback_ports;
#if HAVE_SAMPLERATE
    JSList *src_node = playback_srcs;
#endif

    uint32_t *packet_bufX = (uint32_t *) packet_payload;

    while (node != NULL)
    {
#if HAVE_SAMPLERATE
        SRC_DATA src;
#endif
        int i;
        int_float_t val;
        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);

        if (jack_port_is_audio (porttype))
        {
            // audio port, resample if necessary

#if HAVE_SAMPLERATE
            if (net_period_up != nframes) {
                SRC_STATE *src_state = src_node->data;
                src.data_in = buf;
                src.input_frames = nframes;

                src.data_out = (float *) packet_bufX;
                src.output_frames = net_period_up;

                src.src_ratio = (float) net_period_up / (float) nframes;
                src.end_of_input = 0;

                src_set_ratio (src_state, src.src_ratio);
                src_process (src_state, &src);

                for (i = 0; i < net_period_up; i++)
                {
                    packet_bufX[i] = htonl (packet_bufX[i]);
                }
                src_node = jack_slist_next (src_node);
            }
            else
#endif
            {
		if( dont_htonl_floats )
		{
		    memcpy( packet_bufX, buf, net_period_up*sizeof(jack_default_audio_sample_t) );
		}
		else
		{
		    for (i = 0; i < net_period_up; i++)
		    {
			val.f = buf[i];
			val.i = htonl (val.i);
			packet_bufX[i] = val.i;
		    }
		}
            }
        }
        else if (jack_port_is_midi (porttype))
        {
            // encode midi events from port to packet
            // convert the data buffer to a standard format (uint32_t based)
            unsigned int buffer_size_uint32 = net_period_up;
            uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
            encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
        }
        packet_bufX = (packet_bufX + net_period_up);
        node = jack_slist_next (node);
        chn++;
    }
}

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

    uint16_t *packet_bufX = (uint16_t *)packet_payload;

    if( !packet_payload )
	return;

    while (node != NULL)
    {
        int i;
        //uint32_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);

#if HAVE_SAMPLERATE
        float *floatbuf = alloca (sizeof(float) * net_period_down);
#endif
        const char *porttype = jack_port_type (port);

        if (jack_port_is_audio (porttype))
        {
            // audio port, resample if necessary

#if HAVE_SAMPLERATE
            if (net_period_down != nframes)
            {
                SRC_STATE *src_state = src_node->data;
                for (i = 0; i < net_period_down; i++)
                {
                    floatbuf[i] = ((float) ntohs(packet_bufX[i])) / 32767.0 - 1.0;
                }

                src.data_in = floatbuf;
                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;

                src_set_ratio (src_state, src.src_ratio);
                src_process (src_state, &src);
                src_node = jack_slist_next (src_node);
            }
            else
#endif
                for (i = 0; i < net_period_down; i++)
                    buf[i] = ((float) ntohs (packet_bufX[i])) / 32768.0 - 1.0;
        }
        else if (jack_port_is_midi (porttype))
        {
            // midi port, decode midi events
            // convert the data buffer to a standard format (uint32_t based)
            unsigned int buffer_size_uint32 = net_period_down / 2;
            uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
            decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
        }
        packet_bufX = (packet_bufX + net_period_down);
        node = jack_slist_next (node);
        chn++;
    }
}

void
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)
{
    int chn = 0;
    JSList *node = playback_ports;
#if HAVE_SAMPLERATE
    JSList *src_node = playback_srcs;
#endif

    uint16_t *packet_bufX = (uint16_t *)packet_payload;

    while (node != NULL)
    {
#if HAVE_SAMPLERATE
        SRC_DATA src;
#endif
        int i;
        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);

        if (jack_port_is_audio (porttype))
        {
            // audio port, resample if necessary

#if HAVE_SAMPLERATE
            if (net_period_up != nframes)
            {
                SRC_STATE *src_state = src_node->data;

                float *floatbuf = alloca (sizeof(float) * net_period_up);

                src.data_in = buf;
                src.input_frames = nframes;

                src.data_out = floatbuf;
                src.output_frames = net_period_up;

                src.src_ratio = (float) net_period_up / (float) nframes;
                src.end_of_input = 0;

                src_set_ratio (src_state, src.src_ratio);
                src_process (src_state, &src);

                for (i = 0; i < net_period_up; i++)
                {
                    packet_bufX[i] = htons (((uint16_t)((floatbuf[i] + 1.0) * 32767.0)));
                }
                src_node = jack_slist_next (src_node);
            }
            else
#endif
                for (i = 0; i < net_period_up; i++)
                    packet_bufX[i] = htons(((uint16_t)((buf[i] + 1.0) * 32767.0)));
        }
        else if (jack_port_is_midi (porttype))
        {
            // encode midi events from port to packet
            // convert the data buffer to a standard format (uint32_t based)
            unsigned int buffer_size_uint32 = net_period_up / 2;
            uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
            encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
        }
        packet_bufX = (packet_bufX + net_period_up);
        node = jack_slist_next (node);
        chn++;
    }
}

// render functions for 8bit
void
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)
{
    int chn = 0;
    JSList *node = capture_ports;

#if HAVE_SAMPLERATE
    JSList *src_node = capture_srcs;
#endif

    int8_t *packet_bufX = (int8_t *)packet_payload;

    if( !packet_payload )
	return;

    while (node != NULL)
    {
        int i;
        //uint32_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);

#if HAVE_SAMPLERATE
        float *floatbuf = alloca (sizeof (float) * net_period_down);
#endif
        const char *porttype = jack_port_type (port);

        if (jack_port_is_audio(porttype))
        {
#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++)
                    floatbuf[i] = ((float) packet_bufX[i]) / 127.0;

                src.data_in = floatbuf;
                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;

                src_set_ratio (src_state, src.src_ratio);
                src_process (src_state, &src);
                src_node = jack_slist_next (src_node);
            }
            else
#endif
                for (i = 0; i < net_period_down; i++)
                    buf[i] = ((float) packet_bufX[i]) / 127.0;
        }
        else if (jack_port_is_midi (porttype))
        {
            // midi port, decode midi events
            // convert the data buffer to a standard format (uint32_t based)
            unsigned int buffer_size_uint32 = net_period_down / 4;
            uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
            decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
        }
        packet_bufX = (packet_bufX + net_period_down);
        node = jack_slist_next (node);
        chn++;
    }
}

void
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)
{
    int chn = 0;
    JSList *node = playback_ports;
#if HAVE_SAMPLERATE
    JSList *src_node = playback_srcs;
#endif

    int8_t *packet_bufX = (int8_t *)packet_payload;

    while (node != NULL)
    {
#if HAVE_SAMPLERATE
        SRC_DATA src;
#endif
        int i;
        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);

        if (jack_port_is_audio (porttype))
        {
#if HAVE_SAMPLERATE
            // audio port, resample if necessary
            if (net_period_up != nframes)
            {

                SRC_STATE *src_state = src_node->data;

                float *floatbuf = alloca (sizeof (float) * net_period_up);

                src.data_in = buf;
                src.input_frames = nframes;

                src.data_out = floatbuf;
                src.output_frames = net_period_up;

                src.src_ratio = (float) net_period_up / (float) nframes;
                src.end_of_input = 0;

                src_set_ratio (src_state, src.src_ratio);
                src_process (src_state, &src);

                for (i = 0; i < net_period_up; i++)
                    packet_bufX[i] = floatbuf[i] * 127.0;
                src_node = jack_slist_next (src_node);
            }
            else
#endif
                for (i = 0; i < net_period_up; i++)
                    packet_bufX[i] = buf[i] * 127.0;
        }
        else if (jack_port_is_midi (porttype))
        {
            // encode midi events from port to packet
            // convert the data buffer to a standard format (uint32_t based)
            unsigned int buffer_size_uint32 = net_period_up / 4;
            uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
            encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
        }
        packet_bufX = (packet_bufX + net_period_up);
        node = jack_slist_next (node);
        chn++;
    }
}

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

    unsigned char *packet_bufX = (unsigned char *)packet_payload;

    while (node != NULL)
    {
        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);

        if (jack_port_is_audio (porttype))
        {
            // audio port, decode celt data.

	    CELTDecoder *decoder = src_node->data;
#if HAVE_CELT_API_0_8
	    if( !packet_payload )
		celt_decode_float( decoder, NULL, net_period_down, buf, nframes );
	    else
		celt_decode_float( decoder, packet_bufX, net_period_down, buf, nframes );
#else
	    if( !packet_payload )
		celt_decode_float( decoder, NULL, net_period_down, buf );
	    else
		celt_decode_float( decoder, packet_bufX, net_period_down, buf );
#endif

	    src_node = jack_slist_next (src_node);
        }
        else if (jack_port_is_midi (porttype))
        {
            // midi port, decode midi events
            // convert the data buffer to a standard format (uint32_t based)
            unsigned int buffer_size_uint32 = net_period_down / 2;
            uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
	    if( packet_payload )
		decode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
        }
        packet_bufX = (packet_bufX + net_period_down);
        node = jack_slist_next (node);
        chn++;
    }
}

void
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)
{
    int chn = 0;
    JSList *node = playback_ports;
    JSList *src_node = playback_srcs;

    unsigned char *packet_bufX = (unsigned char *)packet_payload;

    while (node != NULL)
    {
        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);

        if (jack_port_is_audio (porttype))
        {
            // audio port, encode celt data.

	    int encoded_bytes;
	    float *floatbuf = alloca (sizeof(float) * nframes );
	    memcpy( floatbuf, buf, nframes*sizeof(float) );
	    CELTEncoder *encoder = src_node->data;
#if HAVE_CELT_API_0_8
	    encoded_bytes = celt_encode_float( encoder, floatbuf, nframes, packet_bufX, net_period_up );
#else
	    encoded_bytes = celt_encode_float( encoder, floatbuf, NULL, packet_bufX, net_period_up );
#endif
	    if( encoded_bytes != net_period_up )
		printf( "something in celt changed. netjack needs to be changed to handle this.\n" );
	    src_node = jack_slist_next( src_node );
        }
        else if (jack_port_is_midi (porttype))
        {
            // encode midi events from port to packet
            // convert the data buffer to a standard format (uint32_t based)
            unsigned int buffer_size_uint32 = net_period_up / 2;
            uint32_t * buffer_uint32 = (uint32_t*) packet_bufX;
            encode_midi_buffer (buffer_uint32, buffer_size_uint32, buf);
        }
        packet_bufX = (packet_bufX + net_period_up);
        node = jack_slist_next (node);
        chn++;
    }
}

#endif
/* Wrapper functions with bitdepth argument... */
void
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)
{
    if (bitdepth == 8)
        render_payload_to_jack_ports_8bit (packet_payload, net_period_down, capture_ports, capture_srcs, nframes);
    else if (bitdepth == 16)
        render_payload_to_jack_ports_16bit (packet_payload, net_period_down, capture_ports, capture_srcs, nframes);
#if HAVE_CELT
    else if (bitdepth == CELT_MODE)
        render_payload_to_jack_ports_celt (packet_payload, net_period_down, capture_ports, capture_srcs, nframes);
#endif
    else
        render_payload_to_jack_ports_float (packet_payload, net_period_down, capture_ports, capture_srcs, nframes, dont_htonl_floats);
}

void
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)
{
    if (bitdepth == 8)
        render_jack_ports_to_payload_8bit (playback_ports, playback_srcs, nframes, packet_payload, net_period_up);
    else if (bitdepth == 16)
        render_jack_ports_to_payload_16bit (playback_ports, playback_srcs, nframes, packet_payload, net_period_up);
#if HAVE_CELT
    else if (bitdepth == CELT_MODE)
        render_jack_ports_to_payload_celt (playback_ports, playback_srcs, nframes, packet_payload, net_period_up);
#endif
    else
        render_jack_ports_to_payload_float (playback_ports, playback_srcs, nframes, packet_payload, net_period_up, dont_htonl_floats);
}