JackNetTool.h 17.6 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 "types.h"
23
#include "transport.h"
sletz's avatar
sletz committed
24
#ifndef WIN32
25
#include <netinet/in.h>
sletz's avatar
sletz committed
26
#endif
sletz's avatar
sletz committed
27
28
#include <cmath>

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

sletz's avatar
sletz committed
31
32
#ifndef htonll
#ifdef __BIG_ENDIAN__
33
34
#define htonll(x) (x)
#define ntohll(x) (x)
sletz's avatar
sletz committed
35
#else
36
37
#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
38
39
40
#endif
#endif

41
#define NETWORK_PROTOCOL 8
42

Stephane Letz's avatar
Stephane Letz committed
43
#define NET_SYNCHING      0
44
45
#define SYNC_PACKET_ERROR -2
#define DATA_PACKET_ERROR -3
sletz's avatar
sletz committed
46

Stephane Letz's avatar
Stephane Letz committed
47
#define OPTIMIZED_PROTOCOL 1
48

Stephane Letz's avatar
Stephane Letz committed
49
#define UDP_HEADER_SIZE 64   // 40 bytes for IP header in IPV6, 20 in IPV4, 8 for UDP, so take 64
50
#define HEADER_SIZE (sizeof(packet_header_t))
Stephane Letz's avatar
Stephane Letz committed
51
52
53

// TODO : change PACKET_AVAILABLE_SIZE definition ==> #define PACKET_AVAILABLE_SIZE(params) ((params)->fMtu - UDP_HEADER_SIZE - sizeof(packet_header_t))
#define PACKET_AVAILABLE_SIZE(params) ((params)->fMtu - HEADER_SIZE)
54

sletz's avatar
sletz committed
55
56
namespace Jack
{
57
58
    typedef struct _session_params session_params_t;
    typedef struct _packet_header packet_header_t;
59
    typedef struct _net_transport_data net_transport_data_t;
60
61
62
    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
63

64
65
66
67
68
    enum JackNetEncoder {

        JackFloatEncoder = 0,
        JackIntEncoder = 1,
        JackCeltEncoder = 2,
Robin Gareus's avatar
Robin Gareus committed
69
        JackOpusEncoder = 3,
70
    };
sletz's avatar
sletz committed
71
72
73

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

moret's avatar
moret committed
74
75
76
77
78
79
80
81
82
83
84
85
    /**
    \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
86

87
    Data encoding : headers (session_params and packet_header) are encoded using HTN kind of functions but float data
sletz's avatar
sletz committed
88
    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
89
    */
sletz's avatar
sletz committed
90

91
    PRE_PACKED_STRUCTURE
92
93
    struct _session_params
    {
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
        char fPacketType[8];                        //packet type ('param')
        uint32_t fProtocolVersion;                  //version
        int32_t fPacketID;                          //indicates the packet type
        char fName[JACK_CLIENT_NAME_SIZE];          //slave's name
        char fMasterNetName[JACK_SERVER_NAME_SIZE]; //master hostname (network)
        char fSlaveNetName[JACK_SERVER_NAME_SIZE];  //slave hostname (network)
        uint32_t fMtu;                              //connection mtu
        uint32_t fID;                               //slave's ID
        uint32_t fTransportSync;                    //is the transport synced ?
        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
        uint32_t fSampleRate;                       //session sample rate
        uint32_t fPeriodSize;                       //period size
        uint32_t fSampleEncoder;                    //samples encoder
        uint32_t fKBps;                             //KB per second for CELT encoder
        uint32_t fSlaveSyncMode;                    //is the slave in sync mode ?
        uint32_t fNetworkLatency;                   //network latency
113
    } POST_PACKED_STRUCTURE;
sletz's avatar
sletz committed
114
115
116

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

moret's avatar
moret committed
117
118
119
    /**
    \Brief This enum groups network error by type
    */
120

121
122
123
124
125
126
127
128
129
130
    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
131

132
    typedef enum _net_status net_status_t;
sletz's avatar
sletz committed
133
134
135

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

moret's avatar
moret committed
136
137
138
    /**
    \Brief This enum indicates the type of a sync packet (used in the initialization phase)
    */
139

140
141
    enum _sync_packet_type
    {
142
143
144
145
146
147
        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
148
    };
sletz's avatar
sletz committed
149

150
    typedef enum _sync_packet_type sync_packet_type_t;
sletz's avatar
sletz committed
151
152
153
154


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

moret's avatar
moret committed
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    /**
    \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

    */
173

174
    PRE_PACKED_STRUCTURE
175
176
    struct _packet_header
    {
177
        char fPacketType[8];        //packet type ('headr')
Stephane Letz's avatar
Stephane Letz committed
178
179
        uint32_t fDataType;         //'a' for audio, 'm' for midi and 's' for sync
        uint32_t fDataStream;       //'s' for send, 'r' for return
180
        uint32_t fID;               //unique ID of the slave
sletz's avatar
sletz committed
181
        uint32_t fNumPacket;        //number of data packets of the cycle
moret's avatar
moret committed
182
        uint32_t fPacketSize;       //packet size in bytes
183
        uint32_t fActivePorts;      //number of active ports
184
185
        uint32_t fCycle;            //process cycle counter
        uint32_t fSubCycle;         //midi/audio subcycle counter
Stephane Letz's avatar
Stephane Letz committed
186
        int32_t fFrames;            //process cycle size in frames (can be -1 to indicate entire buffer)
moret's avatar
moret committed
187
        uint32_t fIsLastPckt;       //is it the last packet of a given cycle ('y' or 'n')
188
    } POST_PACKED_STRUCTURE;
sletz's avatar
sletz committed
189

190
191
192
193
194
195
196
197
//net timebase master

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

    enum _net_timebase_master
    {
198
199
200
201
        NO_CHANGE = 0,
        RELEASE_TIMEBASEMASTER = 1,
        TIMEBASEMASTER = 2,
        CONDITIONAL_TIMEBASEMASTER = 3
202
203
204
205
206
    };

    typedef enum _net_timebase_master net_timebase_master_t;


207
208
//transport data ******************************************************************************

moret's avatar
moret committed
209
    /**
210
    \Brief This structure contains transport data to be sent over the network
moret's avatar
moret committed
211
    */
212

213
    PRE_PACKED_STRUCTURE
moret's avatar
moret committed
214
215
    struct _net_transport_data
    {
216
217
        uint32_t fNewState;             //is it a state change
        uint32_t fTimebaseMaster;       //is there a new timebase master
moret's avatar
moret committed
218
        int32_t fState;                 //current cycle state
219
        jack_position_t fPosition;      //current cycle position
220
    } POST_PACKED_STRUCTURE;
sletz's avatar
sletz committed
221

sletz's avatar
sletz committed
222
 //midi data ***********************************************************************************
sletz's avatar
sletz committed
223

moret's avatar
moret committed
224
225
    /**
    \Brief Midi buffer and operations class
226

moret's avatar
moret committed
227
228
229
230
231
232
233
234
235
    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)
236

moret's avatar
moret committed
237
    */
238

239
    class SERVER_EXPORT NetMidiBuffer
240
    {
241
        private:
sletz's avatar
sletz committed
242

243
244
245
            int fNPorts;
            size_t fMaxBufsize;
            int fMaxPcktSize;
sletz's avatar
sletz committed
246

247
248
249
            char* fBuffer;
            char* fNetBuffer;
            JackMidiBuffer** fPortBuffer;
sletz's avatar
sletz committed
250

sletz's avatar
sletz committed
251
            size_t fCycleBytesSize;  // needed size in bytes ofr an entire cycle
252
253

        public:
sletz's avatar
sletz committed
254

sletz's avatar
sletz committed
255
            NetMidiBuffer(session_params_t* params, uint32_t nports, char* net_buffer);
256
257
258
            ~NetMidiBuffer();

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

sletz's avatar
sletz committed
260
261
            // needed size in bytes for an entire cycle
            size_t GetCycleSize();
sletz's avatar
sletz committed
262
            int GetNumPackets(int data_sizen, int max_size);
sletz's avatar
sletz committed
263

sletz's avatar
sletz committed
264
265
266
            void SetBuffer(int index, JackMidiBuffer* buffer);
            JackMidiBuffer* GetBuffer(int index);

267
268
            //utility
            void DisplayEvents();
sletz's avatar
sletz committed
269

270
271
            //jack<->buffer
            int RenderFromJackPorts();
sletz's avatar
sletz committed
272
            void RenderToJackPorts();
sletz's avatar
sletz committed
273

274
            //network<->buffer
275
            void RenderFromNetwork(int sub_cycle, size_t copy_size);
276
            int RenderToNetwork(int sub_cycle, size_t total_size);
277

278
    };
sletz's avatar
sletz committed
279
280
281

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

sletz's avatar
sletz committed
282
    class SERVER_EXPORT NetAudioBuffer
283
    {
sletz's avatar
sletz committed
284

sletz's avatar
sletz committed
285
286
287
288
        protected:

            int fNPorts;
            int fLastSubCycle;
Stephane Letz's avatar
Stephane Letz committed
289
            int fNumPackets;
sletz's avatar
sletz committed
290

sletz's avatar
sletz committed
291
292
            char* fNetBuffer;
            sample_t** fPortBuffer;
293
            bool* fConnectedPorts;
sletz's avatar
sletz committed
294

sletz's avatar
sletz committed
295
296
297
298
299
300
301
302
303
304
305
            jack_nframes_t fPeriodSize;
            jack_nframes_t fSubPeriodSize;
            size_t fSubPeriodBytesSize;

            float fCycleDuration;       // in sec
            size_t fCycleBytesSize;     // needed size in bytes for an entire cycle

            int CheckPacket(int cycle, int sub_cycle);
            void NextCycle();
            void Cleanup();

306
        public:
sletz's avatar
sletz committed
307

sletz's avatar
sletz committed
308
309
            NetAudioBuffer(session_params_t* params, uint32_t nports, char* net_buffer);
            virtual ~NetAudioBuffer();
sletz's avatar
sletz committed
310

311
312
313
            bool GetConnected(int port_index) { return fConnectedPorts[port_index]; }
            void SetConnected(int port_index, bool state) { fConnectedPorts[port_index] = state; }

sletz's avatar
sletz committed
314
315
            // needed syze in bytes ofr an entire cycle
            virtual size_t GetCycleSize() = 0;
sletz's avatar
sletz committed
316

sletz's avatar
sletz committed
317
318
            // cycle duration in sec
            virtual float GetCycleDuration() = 0;
sletz's avatar
sletz committed
319

sletz's avatar
sletz committed
320
            virtual int GetNumPackets(int active_ports) = 0;
sletz's avatar
sletz committed
321

sletz's avatar
sletz committed
322
323
324
            virtual void SetBuffer(int index, sample_t* buffer);
            virtual sample_t* GetBuffer(int index);

325
            //jack<->buffer
326
327
            virtual int RenderFromJackPorts(int nframes);
            virtual void RenderToJackPorts(int nframes);
sletz's avatar
sletz committed
328

sletz's avatar
sletz committed
329
            //network<->buffer
sletz's avatar
sletz committed
330
331
            virtual int RenderFromNetwork(int cycle, int sub_cycle, uint32_t port_num) = 0;
            virtual int RenderToNetwork(int sub_cycle, uint32_t port_num) = 0;
332

sletz's avatar
sletz committed
333
334
            virtual int ActivePortsToNetwork(char* net_buffer);
            virtual void ActivePortsFromNetwork(char* net_buffer, uint32_t port_num);
335

336
337
    };

sletz's avatar
sletz committed
338
    class SERVER_EXPORT NetFloatAudioBuffer : public NetAudioBuffer
sletz's avatar
sletz committed
339
340
341
342
343
    {

        private:

            int fPacketSize;
sletz's avatar
sletz committed
344
345

            void UpdateParams(int active_ports);
346
347
348
349
        
        
            void RenderFromNetwork(char* net_buffer, int active_port, int sub_cycle);
            void RenderToNetwork(char* net_buffer, int active_port, int sub_cycle);
sletz's avatar
sletz committed
350
351
352

        public:

sletz's avatar
sletz committed
353
354
            NetFloatAudioBuffer(session_params_t* params, uint32_t nports, char* net_buffer);
            virtual ~NetFloatAudioBuffer();
sletz's avatar
sletz committed
355
356
357
358
359
360

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

            // cycle duration in sec
            float GetCycleDuration();
sletz's avatar
sletz committed
361
            int GetNumPackets(int active_ports);
sletz's avatar
sletz committed
362
363

            //jack<->buffer
sletz's avatar
sletz committed
364
365
366
            int RenderFromNetwork(int cycle, int sub_cycle, uint32_t port_num);
            int RenderToNetwork(int sub_cycle, uint32_t port_num);

sletz's avatar
sletz committed
367
368
    };

nedko's avatar
nedko committed
369
#if HAVE_CELT
sletz's avatar
sletz committed
370
371
372
373
374
375

#include <celt/celt.h>

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

377
378
379
            CELTMode** fCeltMode;
            CELTEncoder** fCeltEncoder;
            CELTDecoder** fCeltDecoder;
sletz's avatar
sletz committed
380

sletz's avatar
sletz committed
381
            int fCompressedSizeByte;
382
            unsigned char** fCompressedBuffer;
Stephane Letz's avatar
Stephane Letz committed
383
   
sletz's avatar
sletz committed
384
            size_t fLastSubPeriodBytesSize;
sletz's avatar
sletz committed
385

sletz's avatar
sletz committed
386
            void FreeCelt();
sletz's avatar
sletz committed
387

sletz's avatar
sletz committed
388
        public:
sletz's avatar
sletz committed
389

390
            NetCeltAudioBuffer(session_params_t* params, uint32_t nports, char* net_buffer, int kbps);
391
            virtual ~NetCeltAudioBuffer();
sletz's avatar
sletz committed
392

sletz's avatar
sletz committed
393
            // needed size in bytes for an entire cycle
Robin Gareus's avatar
Robin Gareus committed
394
395
396
397
398
399
400
            size_t GetCycleSize();

             // cycle duration in sec
            float GetCycleDuration();
            int GetNumPackets(int active_ports);

            //jack<->buffer
401
402
            int RenderFromJackPorts(int nframes);
            void RenderToJackPorts(int nframes);
Robin Gareus's avatar
Robin Gareus committed
403
404
405

            //network<->buffer
            int RenderFromNetwork(int cycle, int sub_cycle, uint32_t port_num);
406
            int RenderToNetwork(int sub_cycle, uint32_t port_num);
Robin Gareus's avatar
Robin Gareus committed
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
    };

#endif

#if HAVE_OPUS

#include <opus/opus.h>
#include <opus/opus_custom.h>

    class SERVER_EXPORT NetOpusAudioBuffer : public NetAudioBuffer
    {
        private:

            OpusCustomMode** fOpusMode;
            OpusCustomEncoder** fOpusEncoder;
            OpusCustomDecoder** fOpusDecoder;

424
            int fCompressedMaxSizeByte;
425
            unsigned short* fCompressedSizesByte;
Stephane Letz's avatar
Stephane Letz committed
426
   
Robin Gareus's avatar
Robin Gareus committed
427
428
429
430
431
432
433
434
435
436
437
            size_t fLastSubPeriodBytesSize;

            unsigned char** fCompressedBuffer;
            void FreeOpus();

        public:

            NetOpusAudioBuffer(session_params_t* params, uint32_t nports, char* net_buffer, int kbps);
            virtual ~NetOpusAudioBuffer();

            // needed size in bytes for an entire cycle
sletz's avatar
sletz committed
438
            size_t GetCycleSize();
sletz's avatar
sletz committed
439

sletz's avatar
sletz committed
440
441
             // cycle duration in sec
            float GetCycleDuration();
sletz's avatar
sletz committed
442
            int GetNumPackets(int active_ports);
sletz's avatar
sletz committed
443

sletz's avatar
sletz committed
444
            //jack<->buffer
445
446
            int RenderFromJackPorts(int nframes);
            void RenderToJackPorts(int nframes);
sletz's avatar
sletz committed
447
448

            //network<->buffer
sletz's avatar
sletz committed
449
450
            int RenderFromNetwork(int cycle, int sub_cycle, uint32_t port_num);
            int RenderToNetwork(int sub_cycle, uint32_t  port_num);
sletz's avatar
sletz committed
451
452
453
    };

#endif
sletz's avatar
sletz committed
454
455
456
457

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

sletz's avatar
sletz committed
459
            int fCompressedSizeByte;
Stephane Letz's avatar
Stephane Letz committed
460
 
sletz's avatar
sletz committed
461
            size_t fLastSubPeriodBytesSize;
sletz's avatar
sletz committed
462

463
            short** fIntBuffer;
sletz's avatar
sletz committed
464

sletz's avatar
sletz committed
465
        public:
sletz's avatar
sletz committed
466

sletz's avatar
sletz committed
467
            NetIntAudioBuffer(session_params_t* params, uint32_t nports, char* net_buffer);
468
            virtual ~NetIntAudioBuffer();
sletz's avatar
sletz committed
469

sletz's avatar
sletz committed
470
471
            // needed size in bytes for an entire cycle
            size_t GetCycleSize();
sletz's avatar
sletz committed
472

sletz's avatar
sletz committed
473
474
             // cycle duration in sec
            float GetCycleDuration();
sletz's avatar
sletz committed
475
            int GetNumPackets(int active_ports);
sletz's avatar
sletz committed
476

sletz's avatar
sletz committed
477
            //jack<->buffer
478
479
            int RenderFromJackPorts(int nframes);
            void RenderToJackPorts(int nframes);
sletz's avatar
sletz committed
480
481

            //network<->buffer
sletz's avatar
sletz committed
482
483
            int RenderFromNetwork(int cycle, int sub_cycle, uint32_t port_num);
            int RenderToNetwork(int sub_cycle, uint32_t port_num);
sletz's avatar
sletz committed
484
485
    };

sletz's avatar
sletz committed
486
    //utility *************************************************************************************
487
488

    //socket API management
489
490
    SERVER_EXPORT int SocketAPIInit();
    SERVER_EXPORT int SocketAPIEnd();
491
    //n<-->h functions
sletz's avatar
sletz committed
492
493
494
495
496
497
498
499
    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);
500
    //display session parameters
sletz's avatar
sletz committed
501
    SERVER_EXPORT void SessionParamsDisplay(session_params_t* params);
502
    //display packet header
sletz's avatar
sletz committed
503
    SERVER_EXPORT void PacketHeaderDisplay(packet_header_t* header);
504
    //get the packet type from a sesion parameters
sletz's avatar
sletz committed
505
    SERVER_EXPORT sync_packet_type_t GetPacketType(session_params_t* params);
506
    //set the packet type in a session parameters
sletz's avatar
sletz committed
507
    SERVER_EXPORT int SetPacketType(session_params_t* params, sync_packet_type_t packet_type);
508
    //transport utility
sletz's avatar
sletz committed
509
510
    SERVER_EXPORT const char* GetTransportState(int transport_state);
    SERVER_EXPORT void NetTransportDataDisplay(net_transport_data_t* data);
sletz's avatar
sletz committed
511
}