JackNetTool.h 15.9 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
42
#define MASTER_PROTOCOL 5
#define SLAVE_PROTOCOL 5
43

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

46
47
#define OPTIMIZED_PROTOCOL

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

sletz's avatar
sletz committed
51
52
namespace Jack
{
53
54
    typedef struct _session_params session_params_t;
    typedef struct _packet_header packet_header_t;
55
    typedef struct _net_transport_data net_transport_data_t;
56
57
58
    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
59

60
61
62
63
64
65
    enum JackNetEncoder {

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

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

moret's avatar
moret committed
69
70
71
72
73
74
75
76
77
78
79
80
    /**
    \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
81

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

86
87
    struct _session_params
    {
moret's avatar
moret committed
88
89
90
91
92
93
94
95
96
        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
97
98
99
100
        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
101
102
        uint32_t fSampleRate;               //session sample rate
        uint32_t fPeriodSize;               //period size
103
        uint32_t fSampleEncoder;            //samples encoder
sletz's avatar
sletz committed
104
        uint32_t fKBps;                     //KB per second for CELT encoder
moret's avatar
moret committed
105
        uint32_t fSlaveSyncMode;            //is the slave in sync mode ?
106
        uint32_t fNetworkLatency;           //network latency
107
    };
sletz's avatar
sletz committed
108
109
110

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

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

115
116
117
118
119
120
121
122
123
124
    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
125

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

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

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

134
135
    enum _sync_packet_type
    {
136
137
138
139
140
141
        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
142
    };
sletz's avatar
sletz committed
143

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


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

moret's avatar
moret committed
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    /**
    \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

    */
167

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

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

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

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

    typedef enum _net_timebase_master net_timebase_master_t;


199
200
//transport data ******************************************************************************

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

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

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

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

moret's avatar
moret committed
218
219
220
221
222
223
224
225
226
    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)
227

moret's avatar
moret committed
228
    */
229

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

234
235
236
            int fNPorts;
            size_t fMaxBufsize;
            int fMaxPcktSize;
sletz's avatar
sletz committed
237

238
239
240
            char* fBuffer;
            char* fNetBuffer;
            JackMidiBuffer** fPortBuffer;
sletz's avatar
sletz committed
241

sletz's avatar
sletz committed
242
            size_t fCycleBytesSize;  // 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
            int GetNumPackets(int data_sizen, int max_size);
sletz's avatar
sletz committed
254

sletz's avatar
sletz committed
255
256
257
            void SetBuffer(int index, JackMidiBuffer* buffer);
            JackMidiBuffer* GetBuffer(int index);

258
259
            //utility
            void DisplayEvents();
sletz's avatar
sletz committed
260

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

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

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
        protected:

            int fNPorts;
            int fLastSubCycle;
sletz's avatar
sletz committed
280

sletz's avatar
sletz committed
281
282
            char* fNetBuffer;
            sample_t** fPortBuffer;
283
            bool* fConnectedPorts;
sletz's avatar
sletz committed
284

sletz's avatar
sletz committed
285
286
287
288
289
290
291
292
293
294
295
            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();

296
        public:
sletz's avatar
sletz committed
297

sletz's avatar
sletz committed
298
299
            NetAudioBuffer(session_params_t* params, uint32_t nports, char* net_buffer);
            virtual ~NetAudioBuffer();
sletz's avatar
sletz committed
300

301
302
303
            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
304
305
            // needed syze in bytes ofr an entire cycle
            virtual size_t GetCycleSize() = 0;
sletz's avatar
sletz committed
306

sletz's avatar
sletz committed
307
308
            // cycle duration in sec
            virtual float GetCycleDuration() = 0;
sletz's avatar
sletz committed
309

sletz's avatar
sletz committed
310
            virtual int GetNumPackets(int active_ports) = 0;
sletz's avatar
sletz committed
311

sletz's avatar
sletz committed
312
313
314
            virtual void SetBuffer(int index, sample_t* buffer);
            virtual sample_t* GetBuffer(int index);

315
            //jack<->buffer
sletz's avatar
sletz committed
316
317
            virtual int RenderFromJackPorts();
            virtual void RenderToJackPorts();
sletz's avatar
sletz committed
318

sletz's avatar
sletz committed
319
            //network<->buffer
sletz's avatar
sletz committed
320
321
            virtual int RenderFromNetwork(int cycle, int sub_cycle, uint32_t port_num) = 0;
            virtual int RenderToNetwork(int sub_cycle, uint32_t port_num) = 0;
322

sletz's avatar
sletz committed
323
324
            virtual void RenderFromNetwork(char* net_buffer, int active_port, int sub_cycle, size_t copy_size) {}
            virtual void RenderToNetwork(char* net_buffer, int active_port, int sub_cycle, size_t copy_size) {}
325

sletz's avatar
sletz committed
326
327
            virtual int ActivePortsToNetwork(char* net_buffer);
            virtual void ActivePortsFromNetwork(char* net_buffer, uint32_t port_num);
328

329
330
    };

sletz's avatar
sletz committed
331
    class SERVER_EXPORT NetFloatAudioBuffer : public NetAudioBuffer
sletz's avatar
sletz committed
332
333
334
335
336
    {

        private:

            int fPacketSize;
sletz's avatar
sletz committed
337
338

            void UpdateParams(int active_ports);
sletz's avatar
sletz committed
339
340
341

        public:

sletz's avatar
sletz committed
342
343
            NetFloatAudioBuffer(session_params_t* params, uint32_t nports, char* net_buffer);
            virtual ~NetFloatAudioBuffer();
sletz's avatar
sletz committed
344
345
346
347
348
349

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

            // cycle duration in sec
            float GetCycleDuration();
sletz's avatar
sletz committed
350
            int GetNumPackets(int active_ports);
sletz's avatar
sletz committed
351
352

            //jack<->buffer
sletz's avatar
sletz committed
353
354
355
            int RenderFromNetwork(int cycle, int sub_cycle, uint32_t port_num);
            int RenderToNetwork(int sub_cycle, uint32_t port_num);

356
357
            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
358
359
360

    };

nedko's avatar
nedko committed
361
#if HAVE_CELT
sletz's avatar
sletz committed
362
363
364
365
366
367

#include <celt/celt.h>

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

369
370
371
            CELTMode** fCeltMode;
            CELTEncoder** fCeltEncoder;
            CELTDecoder** fCeltDecoder;
sletz's avatar
sletz committed
372

sletz's avatar
sletz committed
373
374
            int fCompressedSizeByte;
            int fNumPackets;
sletz's avatar
sletz committed
375

sletz's avatar
sletz committed
376
            size_t fLastSubPeriodBytesSize;
sletz's avatar
sletz committed
377

378
            unsigned char** fCompressedBuffer;
sletz's avatar
sletz committed
379

sletz's avatar
sletz committed
380
            void FreeCelt();
sletz's avatar
sletz committed
381

sletz's avatar
sletz committed
382
        public:
sletz's avatar
sletz committed
383

384
            NetCeltAudioBuffer(session_params_t* params, uint32_t nports, char* net_buffer, int kbps);
385
            virtual ~NetCeltAudioBuffer();
sletz's avatar
sletz committed
386

sletz's avatar
sletz committed
387
388
            // needed size in bytes for an entire cycle
            size_t GetCycleSize();
sletz's avatar
sletz committed
389

sletz's avatar
sletz committed
390
391
             // cycle duration in sec
            float GetCycleDuration();
sletz's avatar
sletz committed
392
            int GetNumPackets(int active_ports);
sletz's avatar
sletz committed
393

sletz's avatar
sletz committed
394
            //jack<->buffer
sletz's avatar
sletz committed
395
            int RenderFromJackPorts();
sletz's avatar
sletz committed
396
            void RenderToJackPorts();
sletz's avatar
sletz committed
397
398

            //network<->buffer
sletz's avatar
sletz committed
399
400
            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
401
402
403
    };

#endif
sletz's avatar
sletz committed
404
405
406
407

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

sletz's avatar
sletz committed
409
410
            int fCompressedSizeByte;
            int fNumPackets;
sletz's avatar
sletz committed
411

sletz's avatar
sletz committed
412
            size_t fLastSubPeriodBytesSize;
sletz's avatar
sletz committed
413

414
            short** fIntBuffer;
sletz's avatar
sletz committed
415

sletz's avatar
sletz committed
416
        public:
sletz's avatar
sletz committed
417

sletz's avatar
sletz committed
418
            NetIntAudioBuffer(session_params_t* params, uint32_t nports, char* net_buffer);
419
            virtual ~NetIntAudioBuffer();
sletz's avatar
sletz committed
420

sletz's avatar
sletz committed
421
422
            // needed size in bytes for an entire cycle
            size_t GetCycleSize();
sletz's avatar
sletz committed
423

sletz's avatar
sletz committed
424
425
             // cycle duration in sec
            float GetCycleDuration();
sletz's avatar
sletz committed
426
            int GetNumPackets(int active_ports);
sletz's avatar
sletz committed
427

sletz's avatar
sletz committed
428
            //jack<->buffer
sletz's avatar
sletz committed
429
            int RenderFromJackPorts();
sletz's avatar
sletz committed
430
            void RenderToJackPorts();
sletz's avatar
sletz committed
431
432

            //network<->buffer
sletz's avatar
sletz committed
433
434
            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
435
436
    };

sletz's avatar
sletz committed
437
    //utility *************************************************************************************
438
439

    //socket API management
440
441
    SERVER_EXPORT int SocketAPIInit();
    SERVER_EXPORT int SocketAPIEnd();
442
    //n<-->h functions
sletz's avatar
sletz committed
443
444
445
446
447
448
449
450
    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);
451
    //display session parameters
sletz's avatar
sletz committed
452
    SERVER_EXPORT void SessionParamsDisplay(session_params_t* params);
453
    //display packet header
sletz's avatar
sletz committed
454
    SERVER_EXPORT void PacketHeaderDisplay(packet_header_t* header);
455
    //get the packet type from a sesion parameters
sletz's avatar
sletz committed
456
    SERVER_EXPORT sync_packet_type_t GetPacketType(session_params_t* params);
457
    //set the packet type in a session parameters
sletz's avatar
sletz committed
458
    SERVER_EXPORT int SetPacketType(session_params_t* params, sync_packet_type_t packet_type);
459
    //transport utility
sletz's avatar
sletz committed
460
461
    SERVER_EXPORT const char* GetTransportState(int transport_state);
    SERVER_EXPORT void NetTransportDataDisplay(net_transport_data_t* data);
sletz's avatar
sletz committed
462
}