JackNetTool.h 30.5 KB
Newer Older
1
/*
sletz's avatar
sletz committed
2
Copyright (C) 2008-2011 Romain Moret at Grame
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

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.

*/
sletz's avatar
sletz committed
19
20

#include "JackMidiPort.h"
21
#include "JackTools.h"
22
#include "JackPlatformPlug.h"
23
#include "types.h"
24
#include "transport.h"
sletz's avatar
sletz committed
25
#ifndef WIN32
26
#include <netinet/in.h>
sletz's avatar
sletz committed
27
#endif
sletz's avatar
sletz committed
28
29
#include <cmath>

moret's avatar
moret committed
30
31
using namespace std;

sletz's avatar
sletz committed
32
33
#ifndef htonll
#ifdef __BIG_ENDIAN__
34
35
#define htonll(x) (x)
#define ntohll(x) (x)
sletz's avatar
sletz committed
36
#else
37
38
#define htonll(x) ((((uint64_t)htonl(x)) << 32) + htonl(x >> 32))
#define ntohll(x) ((((uint64_t)ntohl(x)) << 32) + ntohl(x >> 32))
sletz's avatar
sletz committed
39
40
41
#endif
#endif

42
43
#define MASTER_PROTOCOL 4
#define SLAVE_PROTOCOL 4
44

sletz's avatar
sletz committed
45
46
#define NET_PACKET_ERROR -2

47
48
#define OPTIMIZED_PROTOCOL

49
50
51
#define HEADER_SIZE (sizeof(packet_header_t))
#define PACKET_AVAILABLE_SIZE(params) ((params)->fMtu - sizeof(packet_header_t))

sletz's avatar
sletz committed
52
53
namespace Jack
{
54
55
    typedef struct _session_params session_params_t;
    typedef struct _packet_header packet_header_t;
56
    typedef struct _net_transport_data net_transport_data_t;
57
58
59
    typedef struct sockaddr socket_address_t;
    typedef struct in_addr address_t;
    typedef jack_default_audio_sample_t sample_t;
sletz's avatar
sletz committed
60

61
62
63
64
65
66
    enum JackNetEncoder {

        JackFloatEncoder = 0,
        JackIntEncoder = 1,
        JackCeltEncoder = 2,
    };
sletz's avatar
sletz committed
67
68
69

//session params ******************************************************************************

moret's avatar
moret committed
70
71
72
73
74
75
76
77
78
79
80
81
    /**
    \brief This structure containes master/slave connection parameters, it's used to setup the whole system

    We have :
        - some info like version, type and packet id
        - names
        - network parameters (hostnames and mtu)
        - nunber of audio and midi channels
        - sample rate and buffersize
        - number of audio frames in one network packet (depends on the channel number)
        - is the NetDriver in Sync or ASync mode ?
        - is the NetDriver linked with the master's transport
sletz's avatar
sletz committed
82

83
    Data encoding : headers (session_params and packet_header) are encoded using HTN kind of functions but float data
sletz's avatar
sletz committed
84
    are kept in LITTLE_ENDIAN format (to avoid 2 conversions in the more common LITTLE_ENDIAN <==> LITTLE_ENDIAN connection case).
moret's avatar
moret committed
85
    */
sletz's avatar
sletz committed
86

87
88
    struct _session_params
    {
moret's avatar
moret committed
89
90
91
92
93
94
95
96
97
        char fPacketType[7];                //packet type ('param')
        char fProtocolVersion;              //version
        uint32_t fPacketID;                 //indicates the packet type
        char fName[JACK_CLIENT_NAME_SIZE];  //slave's name
        char fMasterNetName[256];           //master hostname (network)
        char fSlaveNetName[256];            //slave hostname (network)
        uint32_t fMtu;                      //connection mtu
        uint32_t fID;                       //slave's ID
        uint32_t fTransportSync;            //is the transport synced ?
sletz's avatar
sletz committed
98
99
100
101
        int32_t fSendAudioChannels;         //number of master->slave channels
        int32_t fReturnAudioChannels;       //number of slave->master channels
        int32_t fSendMidiChannels;          //number of master->slave midi channels
        int32_t fReturnMidiChannels;        //number of slave->master midi channels
moret's avatar
moret committed
102
103
        uint32_t fSampleRate;               //session sample rate
        uint32_t fPeriodSize;               //period size
104
        uint32_t fSampleEncoder;            //samples encoder
sletz's avatar
sletz committed
105
        uint32_t fKBps;                     //KB per second for CELT encoder
moret's avatar
moret committed
106
        uint32_t fSlaveSyncMode;            //is the slave in sync mode ?
107
        uint32_t fNetworkLatency;           //network latency
108
    };
sletz's avatar
sletz committed
109
110
111

//net status **********************************************************************************

moret's avatar
moret committed
112
113
114
    /**
    \Brief This enum groups network error by type
    */
115

116
117
118
119
120
121
122
123
124
125
    enum  _net_status
    {
        NET_SOCKET_ERROR = 0,
        NET_CONNECT_ERROR,
        NET_ERROR,
        NET_SEND_ERROR,
        NET_RECV_ERROR,
        NET_CONNECTED,
        NET_ROLLING
    };
sletz's avatar
sletz committed
126

127
    typedef enum _net_status net_status_t;
sletz's avatar
sletz committed
128
129
130

//sync packet type ****************************************************************************

moret's avatar
moret committed
131
132
133
    /**
    \Brief This enum indicates the type of a sync packet (used in the initialization phase)
    */
134

135
136
    enum _sync_packet_type
    {
137
138
139
140
141
142
        INVALID = 0,        //...
        SLAVE_AVAILABLE,    //a slave is available
        SLAVE_SETUP,        //slave configuration
        START_MASTER,       //slave is ready, start master
        START_SLAVE,        //master is ready, activate slave
        KILL_MASTER         //master must stop
143
    };
sletz's avatar
sletz committed
144

145
    typedef enum _sync_packet_type sync_packet_type_t;
sletz's avatar
sletz committed
146
147
148
149


//packet header *******************************************************************************

moret's avatar
moret committed
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
    /**
    \Brief This structure is a complete header

    A header indicates :
        - it is a header
        - the type of data the packet contains (sync, midi or audio)
        - the path of the packet (send -master->slave- or return -slave->master-)
        - the unique ID of the slave
        - the sample's bitdepth (unused for now)
        - the size of the midi data contains in the packet (indicates how much midi data will be sent)
        - the number of midi packet(s) : more than one is very unusual, it depends on the midi load
        - the ID of the current cycle (used to check missing packets)
        - the ID of the packet subcycle (for audio data)
        - a flag indicating this packet is the last of the cycle (for sync robustness, it's better to process this way)
        - a flag indicating if, in async mode, the previous graph was not finished or not
        - padding to fill 64 bytes

    */
168

169
170
    struct _packet_header
    {
sletz's avatar
sletz committed
171
        char fPacketType[7];        //packet type ('headr')
172
        char fDataType;             //a for audio, m for midi and s for sync
173
        char fDataStream;           //s for send, r for return
174
        uint32_t fID;               //unique ID of the slave
sletz's avatar
sletz committed
175
        uint32_t fNumPacket;        //number of data packets of the cycle
moret's avatar
moret committed
176
        uint32_t fPacketSize;       //packet size in bytes
177
        uint32_t fActivePorts;      //number of active ports
178
179
        uint32_t fCycle;            //process cycle counter
        uint32_t fSubCycle;         //midi/audio subcycle counter
moret's avatar
moret committed
180
        uint32_t fIsLastPckt;       //is it the last packet of a given cycle ('y' or 'n')
181
    };
sletz's avatar
sletz committed
182

183
184
185
186
187
188
189
190
//net timebase master

    /**
    \Brief This enum describes timebase master's type
    */

    enum _net_timebase_master
    {
191
192
193
194
        NO_CHANGE = 0,
        RELEASE_TIMEBASEMASTER = 1,
        TIMEBASEMASTER = 2,
        CONDITIONAL_TIMEBASEMASTER = 3
195
196
197
198
199
    };

    typedef enum _net_timebase_master net_timebase_master_t;


200
201
//transport data ******************************************************************************

moret's avatar
moret committed
202
    /**
203
    \Brief This structure contains transport data to be sent over the network
moret's avatar
moret committed
204
    */
205

moret's avatar
moret committed
206
207
    struct _net_transport_data
    {
208
209
        uint32_t fNewState;             //is it a state change
        uint32_t fTimebaseMaster;       //is there a new timebase master
moret's avatar
moret committed
210
        int32_t fState;                 //current cycle state
211
        jack_position_t fPosition;      //current cycle position
moret's avatar
moret committed
212
    };
sletz's avatar
sletz committed
213

sletz's avatar
sletz committed
214
 //midi data ***********************************************************************************
sletz's avatar
sletz committed
215

moret's avatar
moret committed
216
217
    /**
    \Brief Midi buffer and operations class
218

moret's avatar
moret committed
219
220
221
222
223
224
225
226
227
    This class is a toolset to manipulate Midi buffers.
    A JackMidiBuffer has a fixed size, which is the same than an audio buffer size.
    An intermediate fixed size buffer allows to uninterleave midi data (from jack ports).
    But for a big majority of the process cycles, this buffer is filled less than 1%,
    Sending over a network 99% of useless data seems completely unappropriate.
    The idea is to count effective midi data, and then send the smallest packet we can.
    To do it, we use an intermediate buffer.
    We have two methods to convert data from jack ports to intermediate buffer,
    And two others to convert this intermediate buffer to a network buffer (header + payload data)
228

moret's avatar
moret committed
229
    */
230

231
    class SERVER_EXPORT NetMidiBuffer
232
    {
233
        private:
sletz's avatar
sletz committed
234

235
236
237
238
239
240
            int fNPorts;
            size_t fMaxBufsize;
            int fMaxPcktSize;
            char* fBuffer;
            char* fNetBuffer;
            JackMidiBuffer** fPortBuffer;
sletz's avatar
sletz committed
241

sletz's avatar
sletz committed
242
            size_t fCycleSize;  // needed size in bytes ofr an entire cycle
243
244

        public:
sletz's avatar
sletz committed
245

sletz's avatar
sletz committed
246
            NetMidiBuffer(session_params_t* params, uint32_t nports, char* net_buffer);
247
248
249
            ~NetMidiBuffer();

            void Reset();
sletz's avatar
sletz committed
250

sletz's avatar
sletz committed
251
252
            // needed size in bytes for an entire cycle
            size_t GetCycleSize();
sletz's avatar
sletz committed
253

sletz's avatar
sletz committed
254
            int GetNumPackets(int data_sizen, int max_size);
sletz's avatar
sletz committed
255

256
257
            //utility
            void DisplayEvents();
sletz's avatar
sletz committed
258

259
260
            //jack<->buffer
            int RenderFromJackPorts();
sletz's avatar
sletz committed
261
            void RenderToJackPorts();
sletz's avatar
sletz committed
262

263
            //network<->buffer
264
            void RenderFromNetwork(int sub_cycle, size_t copy_size);
265
            int RenderToNetwork(int sub_cycle, size_t total_size);
266

sletz's avatar
sletz committed
267
268
            void SetBuffer(int index, JackMidiBuffer* buffer);
            JackMidiBuffer* GetBuffer(int index);
269
    };
sletz's avatar
sletz committed
270
271
272

// audio data *********************************************************************************

sletz's avatar
sletz committed
273
    class SERVER_EXPORT NetAudioBuffer
274
    {
sletz's avatar
sletz committed
275

sletz's avatar
sletz committed
276
277
278
279
280
281
282
        protected:

            int fNPorts;
            int fLastSubCycle;
            char* fNetBuffer;
            sample_t** fPortBuffer;

283
        public:
sletz's avatar
sletz committed
284

sletz's avatar
sletz committed
285
            NetAudioBuffer()
286
            {}
sletz's avatar
sletz committed
287
            virtual ~NetAudioBuffer()
288
            {}
sletz's avatar
sletz committed
289

sletz's avatar
sletz committed
290
291
            // needed syze in bytes ofr an entire cycle
            virtual size_t GetCycleSize() = 0;
sletz's avatar
sletz committed
292

sletz's avatar
sletz committed
293
294
            // cycle duration in sec
            virtual float GetCycleDuration() = 0;
sletz's avatar
sletz committed
295

sletz's avatar
sletz committed
296
            virtual int GetNumPackets() = 0;
sletz's avatar
sletz committed
297

298
            //jack<->buffer
sletz's avatar
sletz committed
299
300
            virtual void RenderFromJackPorts() = 0;
            virtual void RenderToJackPorts() = 0;
sletz's avatar
sletz committed
301

sletz's avatar
sletz committed
302
            //network<->buffer
sletz's avatar
sletz committed
303
            virtual int RenderFromNetwork(int cycle, int sub_cycle, size_t copy_size, uint32_t port_num) = 0;
304
305
            virtual void ActivePortsFromNetwork(char* net_buffer, uint32_t port_num) {}

sletz's avatar
sletz committed
306
            virtual int RenderToNetwork(int sub_cycle, uint32_t& port_num) = 0;
307
            virtual void ActivePortsToNetwork(char* net_buffer, uint32_t& port_num) {}
308

sletz's avatar
sletz committed
309
310
            virtual void SetBuffer(int index, sample_t* buffer) = 0;
            virtual sample_t* GetBuffer(int index) = 0;
sletz's avatar
sletz committed
311
312
313
314
315


            virtual void ActivePortsToNetwork(uint32_t& port_num);
            virtual void ActivePortsFromNetwork(uint32_t port_num);

316
317
   };

moret's avatar
moret committed
318
319
    /**
    \Brief Audio buffer and operations class
320

moret's avatar
moret committed
321
322
323
324
    This class is a toolset to manipulate audio buffers.
    The manipulation of audio buffers is similar to midi buffer, except those buffers have fixed size.
    The interleaving/uninterleaving operations are simplier here because audio buffers have fixed size,
    So there is no need of an intermediate buffer as in NetMidiBuffer.
325

moret's avatar
moret committed
326
    */
sletz's avatar
sletz committed
327

328
    struct JackPortList {
sletz's avatar
sletz committed
329

sletz's avatar
sletz committed
330
331
        // "[---Header---|--audio data--|--audio data--]..."

332
333
334
335
        jack_nframes_t fPeriodSize;
        jack_nframes_t fSubPeriodSize;
        size_t fSubPeriodBytesSize;
        sample_t** fPortBuffer;
336
        int fPacketSize;
337
        int fNPorts;
sletz's avatar
sletz committed
338
339
        size_t fCycleSize;      // needed size in bytes for an entire cycle
        float fCycleDuration;   // in sec
sletz's avatar
sletz committed
340

sletz's avatar
sletz committed
341
        int fLastSubCycle;
sletz's avatar
sletz committed
342

343
344
345
346
        JackPortList(session_params_t* params, uint32_t nports)
        {
            fNPorts = nports;
            fPeriodSize = params->fPeriodSize;
347
348
            fPacketSize = params->fMtu - sizeof(packet_header_t);

sletz's avatar
sletz committed
349
            if (params->fSendAudioChannels == 0 && params->fReturnAudioChannels == 0) {
sletz's avatar
sletz committed
350
351
                fSubPeriodSize = params->fPeriodSize;
            } else {
352
                jack_nframes_t period = (int) powf(2.f,(int)(log(float(fPacketSize)
sletz's avatar
sletz committed
353
                                                   / (max(params->fReturnAudioChannels, params->fSendAudioChannels) * sizeof(sample_t))) / log(2.)));
354
                fSubPeriodSize = (period > fPeriodSize) ? fPeriodSize : period;
sletz's avatar
sletz committed
355
            }
sletz's avatar
sletz committed
356

sletz's avatar
sletz committed
357
            fSubPeriodBytesSize = fSubPeriodSize * sizeof(sample_t);
sletz's avatar
sletz committed
358

359
            fPortBuffer = new sample_t* [fNPorts];
360
            for (int port_index = 0; port_index < fNPorts; port_index++) {
361
                fPortBuffer[port_index] = NULL;
362
            }
sletz's avatar
sletz committed
363

sletz's avatar
sletz committed
364
            fCycleDuration = float(fSubPeriodSize) / float(params->fSampleRate);
sletz's avatar
sletz committed
365
            fCycleSize = params->fMtu * (fPeriodSize / fSubPeriodSize);
sletz's avatar
sletz committed
366

sletz's avatar
sletz committed
367
368
            fLastSubCycle = -1;
        }
sletz's avatar
sletz committed
369

370
        virtual int GetNumPackets()
sletz's avatar
sletz committed
371
        {
sletz's avatar
sletz committed
372
            /*
sletz's avatar
sletz committed
373
            jack_log("GetNumPackets packet = %d  fPeriodSize = %d fSubPeriodSize = %d fSubPeriodBytesSize = %d",
374
                fPeriodSize / fSubPeriodSize, fPeriodSize, fSubPeriodSize, fSubPeriodBytesSize);
sletz's avatar
sletz committed
375
            */
sletz's avatar
sletz committed
376
            return fPeriodSize / fSubPeriodSize;
377
        }
sletz's avatar
sletz committed
378

379
380
381
382
383
384
385
386
        JackPortList()
        {
            fNPorts = 0;
            fPeriodSize = 0;
            fSubPeriodSize = 0;
            fSubPeriodBytesSize = 0;
            fPortBuffer = 0;
        }
sletz's avatar
sletz committed
387

sletz's avatar
sletz committed
388
        virtual ~JackPortList()
389
390
391
        {
            delete [] fPortBuffer;
        }
sletz's avatar
sletz committed
392

sletz's avatar
sletz committed
393
        void SetBuffer(int index, sample_t* buffer)
394
395
396
        {
            fPortBuffer[index] = buffer;
        }
sletz's avatar
sletz committed
397

sletz's avatar
sletz committed
398
        sample_t* GetBuffer(int index)
399
400
401
        {
            return fPortBuffer[index];
        }
sletz's avatar
sletz committed
402

403
404
        void Copy(sample_t** buffers)
        {
sletz's avatar
sletz committed
405
            for (int port_index = 0; port_index < fNPorts; port_index++) {
406
                memcpy(buffers[port_index], fPortBuffer[port_index], fPeriodSize * sizeof(float));
sletz's avatar
sletz committed
407
            }
408
        }
sletz's avatar
sletz committed
409

sletz's avatar
sletz committed
410
        // needed syze in bytes for an entire cycle
sletz's avatar
sletz committed
411
412
413
414
        size_t GetCycleSize()
        {
            return fCycleSize;
        }
sletz's avatar
sletz committed
415

sletz's avatar
sletz committed
416
417
418
419
420
        // cycle duration in sec
        float GetCycleDuration()
        {
            return fCycleDuration;
        }
sletz's avatar
sletz committed
421

422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
    #ifdef __BIG_ENDIAN__

        static inline float SwapFloat(float f)
        {
              union
              {
                float f;
                unsigned char b[4];
              } dat1, dat2;

              dat1.f = f;
              dat2.b[0] = dat1.b[3];
              dat2.b[1] = dat1.b[2];
              dat2.b[2] = dat1.b[1];
              dat2.b[3] = dat1.b[0];
              return dat2.f;
        }

sletz's avatar
sletz committed
440
441
        virtual void RenderFromJackPorts()
        {}
442

sletz's avatar
sletz committed
443
444
        virtual void RenderToJackPorts()
        {}
sletz's avatar
sletz committed
445

sletz's avatar
sletz committed
446
        //network<->buffer
sletz's avatar
sletz committed
447
        virtual int RenderFromNetwork(char* net_buffer, int cycle, int sub_cycle, size_t copy_size, uint32_t port_num)
sletz's avatar
sletz committed
448
        {
sletz's avatar
sletz committed
449
450
            int res = 0;

451
            for (int port_index = 0; port_index < fNPorts; port_index++) {
452
                float* src = (float*)(net_buffer + port_index * fSubPeriodBytesSize);
453
                float* dst = (float*)(fPortBuffer[port_index] + sub_cycle * fSubPeriodSize);
454
455
456
                for (unsigned int sample = 0; sample < fSubPeriodBytesSize / sizeof(float); sample++) {
                    dst[sample] = SwapFloat(src[sample]);
                }
sletz's avatar
sletz committed
457
            }
458
459
            if (sub_cycle != fLastSubCycle + 1) {
                jack_error("Packet(s) missing from... %d %d", fLastSubCycle, sub_cycle);
sletz's avatar
sletz committed
460
                res = NET_PACKET_ERROR;
461
            }
sletz's avatar
sletz committed
462

463
            fLastSubCycle = sub_cycle;
sletz's avatar
sletz committed
464
            return res;
sletz's avatar
sletz committed
465
        }
sletz's avatar
sletz committed
466

sletz's avatar
sletz committed
467
        virtual int RenderToNetwork(char* net_buffer, int sub_cycle, uint32_t& port_num)
sletz's avatar
sletz committed
468
        {
469
            for (int port_index = 0; port_index < fNPorts; port_index++) {
470
                float* src = (float*)(fPortBuffer[port_index] + sub_cycle * fSubPeriodSize);
sletz's avatar
sletz committed
471
472
473
474
475
                float* dst = (float*)(net_buffer + port_index * fSubPeriodBytesSize);
                for (unsigned int sample = 0; sample < fSubPeriodBytesSize / sizeof(float); sample++) {
                    dst[sample] = SwapFloat(src[sample]);
                }
            }
sletz's avatar
sletz committed
476

477
            port_num = fNPorts;
sletz's avatar
sletz committed
478
            return fNPorts * fSubPeriodBytesSize;
479
        }
sletz's avatar
sletz committed
480

481
482
    #else

sletz's avatar
sletz committed
483
484
        virtual void RenderFromJackPorts()
        {}
485

sletz's avatar
sletz committed
486
        virtual void RenderToJackPorts()
sletz's avatar
sletz committed
487
        {
sletz's avatar
sletz committed
488
            // reset for next cycle
sletz's avatar
sletz committed
489
490
            fLastSubCycle = -1;
        }
sletz's avatar
sletz committed
491

492
        //network<->buffer
sletz's avatar
sletz committed
493
        virtual int RenderFromNetwork(char* net_buffer, int cycle, int sub_cycle, size_t copy_size, uint32_t port_num)
494
        {
sletz's avatar
sletz committed
495
496
            int res = 0;

497
498
499
500
501
            for (int port_index = 0; port_index < fNPorts; port_index++) {
                memcpy(fPortBuffer[port_index] + sub_cycle * fSubPeriodSize, net_buffer + port_index * fSubPeriodBytesSize, fSubPeriodBytesSize);
            }
            if (sub_cycle != fLastSubCycle + 1) {
                jack_error("Packet(s) missing from... %d %d", fLastSubCycle, sub_cycle);
sletz's avatar
sletz committed
502
                res = NET_PACKET_ERROR;
sletz's avatar
sletz committed
503
            }
sletz's avatar
sletz committed
504

505
            fLastSubCycle = sub_cycle;
sletz's avatar
sletz committed
506
            return res;
sletz's avatar
sletz committed
507
        }
sletz's avatar
sletz committed
508

sletz's avatar
sletz committed
509
        virtual int RenderToNetwork(char* net_buffer, int sub_cycle, uint32_t& port_num)
sletz's avatar
sletz committed
510
        {
511
512
513
514
            for (int port_index = 0; port_index < fNPorts; port_index++) {
                memcpy(net_buffer + port_index * fSubPeriodBytesSize, fPortBuffer[port_index] + sub_cycle * fSubPeriodSize, fSubPeriodBytesSize);
            }
            port_num = fNPorts;
sletz's avatar
sletz committed
515
            return fNPorts * fSubPeriodBytesSize;
516
517
518
        }

    #endif
sletz's avatar
sletz committed
519

520
521
522
523
524
        virtual void ActivePortsFromNetwork(char* net_buffer, uint32_t port_num)
        {}

        virtual void ActivePortsToNetwork(char* net_buffer, uint32_t& port_num)
        {
sletz's avatar
sletz committed
525
            // Default behaviour: all ports are active
526
527
528
            port_num = fNPorts;
        }

529
    };
sletz's avatar
sletz committed
530

531
532
    struct JackOptimizedPortList : JackPortList {

533
        // Consuming port list is transmitted in the Sync packed
sletz's avatar
sletz committed
534
        // "[---Header---|--active_port_num (uint32_t) ---audio data--|--active_port_num (uint32_t) ---audio data--]..."
sletz's avatar
sletz committed
535

536
537
538
539
        JackOptimizedPortList(session_params_t* params, uint32_t nports)
            :JackPortList(params, nports)
        {}

sletz's avatar
sletz committed
540
541
542
        virtual ~JackOptimizedPortList()
        {}

543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
        int GetNumPackets()
        {
            // Count active ports
            int active_ports = 0;
            for (int port_index = 0; port_index < fNPorts; port_index++) {
                if (fPortBuffer[port_index]) active_ports++;
            }

            if (active_ports == 0) {
                fSubPeriodSize = fPeriodSize;
            } else {
                jack_nframes_t period = (int) powf(2.f, (int)(log(float(fPacketSize) / (active_ports * sizeof(sample_t))) / log(2.)));
                fSubPeriodSize = (period > fPeriodSize) ? fPeriodSize : period;
            }

            fSubPeriodBytesSize = fSubPeriodSize * sizeof(sample_t) + sizeof(uint32_t); // The port number in coded on 4 bytes
sletz's avatar
sletz committed
559

sletz's avatar
sletz committed
560
            /*
sletz's avatar
sletz committed
561
562
            jack_log("GetNumPackets packet = %d  fPeriodSize = %d fSubPeriodSize = %d fSubPeriodBytesSize = %d",
                fPeriodSize / fSubPeriodSize, fPeriodSize, fSubPeriodSize, fSubPeriodBytesSize);
sletz's avatar
sletz committed
563
            */
564
            return fPeriodSize / fSubPeriodSize; // At least one packet
565
566
567
568
569
570
571
572
573
        }

    #ifdef __BIG_ENDIAN__

        // TODO

    #else

        //network<->buffer
sletz's avatar
sletz committed
574
        virtual int RenderFromNetwork(char* net_buffer, int cycle, int sub_cycle, size_t copy_size, uint32_t port_num)
575
        {
sletz's avatar
sletz committed
576
577
            int res = 0;

sletz's avatar
sletz committed
578
579
580
            // Cleanup all JACK ports at the beginning of the cycle
            if (sub_cycle == 0) {
                for (int port_index = 0; port_index < fNPorts; port_index++) {
581
                    if (fPortBuffer[port_index]) {
sletz's avatar
sletz committed
582
                        memset(fPortBuffer[port_index], 0, fPeriodSize * sizeof(sample_t));
583
                    }
sletz's avatar
sletz committed
584
585
586
                }
            }

587
588
589
590
591
592
593
594
595
596
597
            if (port_num > 0)  {

                /// Setup rendering parameters
                int sub_period_size, sub_period_bytes_size;
                if (port_num == 0) {
                    sub_period_size = fPeriodSize;
                } else {
                    jack_nframes_t period = (int) powf(2.f, (int)(log(float(fPacketSize) / (port_num * sizeof(sample_t))) / log(2.)));
                    sub_period_size = (period > fPeriodSize) ? fPeriodSize : period;
                }
                sub_period_bytes_size = sub_period_size * sizeof(sample_t) + sizeof(uint32_t); // The port number in coded on 4 bytes
598

599
600
                for (uint32_t port_index = 0; port_index < port_num; port_index++) {
                    // Only copy to active ports : read the active port number then audio data
sletz's avatar
sletz committed
601
602
                    uint32_t* active_port_address = (uint32_t*)(net_buffer + port_index * sub_period_bytes_size);
                    uint32_t active_port = (uint32_t)(*active_port_address);
603
                    if (fPortBuffer[port_index]) {
sletz's avatar
sletz committed
604
                        memcpy(fPortBuffer[active_port] + sub_cycle * sub_period_size, (char*)(active_port_address + 1), sub_period_bytes_size - sizeof(uint32_t));
605
                    }
606
                }
607

608
609
                if (sub_cycle != fLastSubCycle + 1) {
                    jack_error("Packet(s) missing from... %d %d", fLastSubCycle, sub_cycle);
sletz's avatar
sletz committed
610
                    res = NET_PACKET_ERROR;
611
                }
sletz's avatar
sletz committed
612

613
                fLastSubCycle = sub_cycle;
614
            }
sletz's avatar
sletz committed
615
616

            return res;
617
618
        }

sletz's avatar
sletz committed
619
        virtual int RenderToNetwork(char* net_buffer,int sub_cycle, uint32_t& port_num)
620
        {
sletz's avatar
sletz committed
621
            // Init active port count
622
623
624
            port_num = 0;

            for (int port_index = 0; port_index < fNPorts; port_index++) {
sletz's avatar
sletz committed
625
                // Only copy from active ports : write the active port number then audio data
626
                if (fPortBuffer[port_index]) {
sletz's avatar
sletz committed
627
                    uint32_t* active_port_address = (uint32_t*)(net_buffer + port_num * fSubPeriodBytesSize);
628
629
630
631
632
633
634
635
636
637
638
                    *active_port_address = port_index;
                    memcpy((char*)(active_port_address + 1), fPortBuffer[port_index] + sub_cycle * fSubPeriodSize, fSubPeriodBytesSize - sizeof(uint32_t));
                    port_num++;
                }
            }

            return port_num * fSubPeriodBytesSize;
        }

    #endif

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
        virtual void ActivePortsToNetwork(char* net_buffer, uint32_t& port_num)
        {
            // Init active port count
            port_num = 0;
            short* active_port_address = (short*)net_buffer;

            for (int port_index = 0; port_index < fNPorts; port_index++) {
                // Write the active port number
                if (fPortBuffer[port_index]) {
                    *active_port_address = port_index;
                    active_port_address++;
                    port_num++;
                    assert(port_num < 512);
                }
            }
        }

        virtual void ActivePortsFromNetwork(char* net_buffer, uint32_t port_num)
        {
            short* active_port_address = (short*)net_buffer;

            for (int port_index = 0; port_index < fNPorts; port_index++) {
                fPortBuffer[port_index] = NULL;
            }

            for (uint port_index = 0; port_index < port_num; port_index++) {
665
                // Use -1 when port is actually connected on other side
sletz's avatar
sletz committed
666
667
668
669
670
                if (*active_port_address >= 0 && *active_port_address < fNPorts) {
                    fPortBuffer[*active_port_address] = (sample_t*)-1;
                } else {
                    jack_error("ActivePortsFromNetwork: incorrect port = %d", *active_port_address);
                }
671
672
673
674
                active_port_address++;
            }
        }

675
676
    };

sletz's avatar
sletz committed
677
    class SERVER_EXPORT NetFloatAudioBuffer : public NetAudioBuffer
678
    {
679
        private:
sletz's avatar
sletz committed
680

681
        #ifdef OPTIMIZED_PROTOCOL
sletz's avatar
sletz committed
682
            JackOptimizedPortList fPortBuffer1;
683
        #else
sletz's avatar
sletz committed
684
            JackPortList fPortBuffer1;
685
        #endif
sletz's avatar
sletz committed
686

687
        public:
sletz's avatar
sletz committed
688

sletz's avatar
sletz committed
689
            NetFloatAudioBuffer(session_params_t* params, uint32_t nports, char* net_buffer);
sletz's avatar
sletz committed
690
            virtual ~NetFloatAudioBuffer();
sletz's avatar
sletz committed
691

sletz's avatar
sletz committed
692
693
            // needed size in bytes for an entire cycle
            size_t GetCycleSize();
sletz's avatar
sletz committed
694

sletz's avatar
sletz committed
695
            // cycle duration in sec
sletz's avatar
sletz committed
696
697
            float GetCycleDuration()
            {
sletz's avatar
sletz committed
698
                return fPortBuffer1.GetCycleDuration();
sletz's avatar
sletz committed
699
            }
sletz's avatar
sletz committed
700

sletz's avatar
sletz committed
701
702
            int GetNumPackets()
            {
sletz's avatar
sletz committed
703
                return fPortBuffer1.GetNumPackets();
sletz's avatar
sletz committed
704
            }
sletz's avatar
sletz committed
705

706
            //jack<->buffer
sletz's avatar
sletz committed
707
708
            void RenderFromJackPorts();
            void RenderToJackPorts();
709

sletz's avatar
sletz committed
710
711
            void SetBuffer(int index, sample_t* buffer);
            sample_t* GetBuffer(int index);
sletz's avatar
sletz committed
712

sletz's avatar
sletz committed
713
            //network<->buffer
sletz's avatar
sletz committed
714
            int RenderFromNetwork(int cycle, int sub_cycle, size_t copy_size, uint32_t port_num);
715
716
717
718
            void ActivePortsFromNetwork(char* net_buffer, uint32_t port_num);

            int RenderToNetwork(int sub_cycle, uint32_t&  ort_num);
            void ActivePortsToNetwork(char* net_buffer, uint32_t& port_num);
719
    };
sletz's avatar
sletz committed
720

sletz's avatar
sletz committed
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
    class SERVER_EXPORT NetFloatAudioBuffer1 : public NetAudioBuffer
    {

        private:

            jack_nframes_t fPeriodSize;
            jack_nframes_t fSubPeriodSize;
            size_t fSubPeriodBytesSize;
            //sample_t** fPortBuffer;
            int fPacketSize;
            //int fNPorts;
            size_t fCycleSize;      // needed size in bytes for an entire cycle
            float fCycleDuration;   // in sec

            //int fLastSubCycle;

        public:

            NetFloatAudioBuffer1(session_params_t* params, uint32_t nports, char* net_buffer);
            virtual ~NetFloatAudioBuffer1();

            // needed size in bytes for an entire cycle
            size_t GetCycleSize();

            // cycle duration in sec
            float GetCycleDuration();

            int GetNumPackets();

            void SetBuffer(int index, sample_t* buffer);
            sample_t* GetBuffer(int index);

            virtual void RenderFromJackPorts()
            {}

            virtual void RenderToJackPorts()
            {
                // reset for next cycle
                fLastSubCycle = -1;
            }

            //jack<->buffer
            int RenderFromNetwork(int cycle, int sub_cycle, size_t copy_size, uint32_t port_num);
            int RenderToNetwork(int sub_cycle, uint32_t& port_num);

            /*
            void ActivePortsToNetwork(uint32_t& port_num);
            void ActivePortsFromNetwork(uint32_t port_num);
            */


    };

nedko's avatar
nedko committed
774
#if HAVE_CELT
sletz's avatar
sletz committed
775
776
777
778
779
780

#include <celt/celt.h>

    class SERVER_EXPORT NetCeltAudioBuffer : public NetAudioBuffer
    {
        private:
sletz's avatar
sletz committed
781

782
783
784
            CELTMode** fCeltMode;
            CELTEncoder** fCeltEncoder;
            CELTDecoder** fCeltDecoder;
sletz's avatar
sletz committed
785

sletz's avatar
sletz committed
786
787
            int fCompressedSizeByte;
            jack_nframes_t fPeriodSize;
788

sletz's avatar
sletz committed
789
            int fNumPackets;
sletz's avatar
sletz committed
790
791
            float fCycleDuration;   // in sec
            size_t fCycleSize;      // needed size in bytes for an entire cycle
sletz's avatar
sletz committed
792

sletz's avatar
sletz committed
793
794
            size_t fSubPeriodBytesSize;
            size_t fLastSubPeriodBytesSize;
sletz's avatar
sletz committed
795

sletz's avatar
sletz committed
796
            //sample_t** fPortBuffer;
797
            unsigned char** fCompressedBuffer;
sletz's avatar
sletz committed
798

sletz's avatar
sletz committed
799
            void FreeCelt();
sletz's avatar
sletz committed
800

sletz's avatar
sletz committed
801
        public:
sletz's avatar
sletz committed
802

803
            NetCeltAudioBuffer(session_params_t* params, uint32_t nports, char* net_buffer, int kbps);
804
            virtual ~NetCeltAudioBuffer();
sletz's avatar
sletz committed
805

sletz's avatar
sletz committed
806
807
            // needed size in bytes for an entire cycle
            size_t GetCycleSize();
sletz's avatar
sletz committed
808

sletz's avatar
sletz committed
809
810
811
             // cycle duration in sec
            float GetCycleDuration();
            int GetNumPackets();
sletz's avatar
sletz committed
812

sletz's avatar
sletz committed
813
814
            void SetBuffer(int index, sample_t* buffer);
            sample_t* GetBuffer(int index);
sletz's avatar
sletz committed
815

sletz's avatar
sletz committed
816
            //jack<->buffer
sletz's avatar
sletz committed
817
818
            void RenderFromJackPorts();
            void RenderToJackPorts();
sletz's avatar
sletz committed
819
820

            //network<->buffer
sletz's avatar
sletz committed
821
            int RenderFromNetwork(int cycle, int sub_cycle, size_t copy_size, uint32_t port_num);
sletz's avatar
sletz committed
822
            int RenderToNetwork(int sub_cycle, uint32_t&  port_num);
sletz's avatar
sletz committed
823
824
825
    };

#endif
sletz's avatar
sletz committed
826
827
828
829

    class SERVER_EXPORT NetIntAudioBuffer : public NetAudioBuffer
    {
        private:
sletz's avatar
sletz committed
830

sletz's avatar
sletz committed
831
832
            int fCompressedSizeByte;
            jack_nframes_t fPeriodSize;
sletz's avatar
sletz committed
833

sletz's avatar
sletz committed
834
            int fNumPackets;
sletz's avatar
sletz committed
835

sletz's avatar
sletz committed
836
837
            float fCycleDuration;   // in sec
            size_t fCycleSize;      // needed size in bytes for an entire cycle
sletz's avatar
sletz committed
838

sletz's avatar
sletz committed
839
840
            size_t fSubPeriodSize;
            size_t fSubPeriodBytesSize;
sletz's avatar
sletz committed
841

842
            size_t fLastSubPeriodSize;
sletz's avatar
sletz committed
843
            size_t fLastSubPeriodBytesSize;
sletz's avatar
sletz committed
844

sletz's avatar
sletz committed
845
            //sample_t** fPortBuffer;
846
            short** fIntBuffer;
sletz's avatar
sletz committed
847

sletz's avatar
sletz committed
848
        public:
sletz's avatar
sletz committed
849

sletz's avatar
sletz committed
850
            NetIntAudioBuffer(session_params_t* params, uint32_t nports, char* net_buffer);
851
            virtual ~NetIntAudioBuffer();
sletz's avatar
sletz committed
852

sletz's avatar
sletz committed
853
854
            // needed size in bytes for an entire cycle
            size_t GetCycleSize();
sletz's avatar
sletz committed
855

sletz's avatar
sletz committed
856
857
858
             // cycle duration in sec
            float GetCycleDuration();
            int GetNumPackets();
sletz's avatar
sletz committed
859

sletz's avatar
sletz committed
860
861
            void SetBuffer(int index, sample_t* buffer);
            sample_t* GetBuffer(int index);
sletz's avatar
sletz committed
862

sletz's avatar
sletz committed
863
            //jack<->buffer
sletz's avatar
sletz committed
864
865
            void RenderFromJackPorts();
            void RenderToJackPorts();
sletz's avatar
sletz committed
866
867

            //network<->buffer
sletz's avatar
sletz committed
868
            int RenderFromNetwork(int cycle, int sub_cycle, size_t copy_size, uint32_t port_num);
sletz's avatar
sletz committed
869
            int RenderToNetwork(int sub_cycle, uint32_t& port_num);
sletz's avatar
sletz committed
870
871
    };

sletz's avatar
sletz committed
872
    //utility *************************************************************************************
873
874

    //socket API management
875
876
    SERVER_EXPORT int SocketAPIInit();
    SERVER_EXPORT int SocketAPIEnd();
877
    //n<-->h functions
sletz's avatar
sletz committed
878
879
880
881
882
883
884
885
    SERVER_EXPORT void SessionParamsHToN(session_params_t* src_params, session_params_t* dst_params);
    SERVER_EXPORT void SessionParamsNToH(session_params_t* src_params, session_params_t* dst_params);
    SERVER_EXPORT void PacketHeaderHToN(packet_header_t* src_header, packet_header_t* dst_header);
    SERVER_EXPORT void PacketHeaderNToH(packet_header_t* src_header, packet_header_t* dst_header);
    SERVER_EXPORT void MidiBufferHToN(JackMidiBuffer* src_buffer, JackMidiBuffer* dst_buffer);
    SERVER_EXPORT void MidiBufferNToH(JackMidiBuffer* src_buffer, JackMidiBuffer* dst_buffer);
    SERVER_EXPORT void TransportDataHToN(net_transport_data_t* src_params, net_transport_data_t* dst_params);
    SERVER_EXPORT void TransportDataNToH(net_transport_data_t* src_params, net_transport_data_t* dst_params);
886
    //display session parameters
sletz's avatar
sletz committed
887
    SERVER_EXPORT void SessionParamsDisplay(session_params_t* params);
888
    //display packet header
sletz's avatar
sletz committed
889
    SERVER_EXPORT void PacketHeaderDisplay(packet_header_t* header);
890
    //get the packet type from a sesion parameters
sletz's avatar
sletz committed
891
    SERVER_EXPORT sync_packet_type_t GetPacketType(session_params_t* params);
892
    //set the packet type in a session parameters
sletz's avatar
sletz committed
893
    SERVER_EXPORT int SetPacketType(session_params_t* params, sync_packet_type_t packet_type);
894
    //transport utility
sletz's avatar
sletz committed
895
896
    SERVER_EXPORT const char* GetTransportState(int transport_state);
    SERVER_EXPORT void NetTransportDataDisplay(net_transport_data_t* data);
sletz's avatar
sletz committed
897
}