JackNetInterface.cpp 39.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
Copyright (C) 2001 Paul Davis
Copyright (C) 2008 Romain Moret at Grame

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

#include "JackNetInterface.h"
#include "JackException.h"
22
#include "JackPlatformPlug.h"
23
#include <assert.h>
24
25
26

using namespace std;

sletz's avatar
sletz committed
27
#define PACKET_AVAILABLE_SIZE (fParams.fMtu - sizeof(packet_header_t))
sletz's avatar
sletz committed
28
#define HEADER_SIZE (sizeof(packet_header_t))
sletz's avatar
sletz committed
29

30
31
32
/*
 TODO : since midi buffers now uses up to BUFFER_SIZE_MAX frames,
 probably also use BUFFER_SIZE_MAX in everything related to MIDI events
33
34
35
 handling (see MidiBufferInit in JackMidiPort.cpp)
*/

36
37
38
39
namespace Jack
{
    // JackNetInterface*******************************************

40
41
    JackNetInterface::JackNetInterface() : fSocket()
    {
sletz's avatar
sletz committed
42
        Initialize();
43
44
    }

sletz's avatar
sletz committed
45
    JackNetInterface::JackNetInterface(const char* multicast_ip, int port) : fSocket(multicast_ip, port)
46
    {
47
        strcpy(fMulticastIP, multicast_ip);
sletz's avatar
sletz committed
48
        Initialize();
49
50
    }

sletz's avatar
sletz committed
51
    JackNetInterface::JackNetInterface(session_params_t& params, JackNetSocket& socket, const char* multicast_ip) : fSocket(socket)
52
    {
moret's avatar
moret committed
53
        fParams = params;
54
        strcpy(fMulticastIP, multicast_ip);
sletz's avatar
sletz committed
55
56
        Initialize();
    }
sletz's avatar
sletz committed
57

sletz's avatar
sletz committed
58
59
    void JackNetInterface::Initialize()
    {
60
61
62
63
64
65
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
66
67
        memset(&fSendTransportData, 0, sizeof(net_transport_data_t));
        memset(&fReturnTransportData, 0, sizeof(net_transport_data_t));
68
69
    }

sletz's avatar
sletz committed
70
71
72
73
74
75
76
77
78
79
80
    void JackNetInterface::FreeNetworkBuffers()
    {
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
    }
sletz's avatar
sletz committed
81

82
83
    JackNetInterface::~JackNetInterface()
    {
sletz's avatar
sletz committed
84
        jack_log("JackNetInterface::~JackNetInterface");
moret's avatar
moret committed
85

86
87
88
89
90
91
92
93
94
        fSocket.Close();
        delete[] fTxBuffer;
        delete[] fRxBuffer;
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
    }

moret's avatar
moret committed
95
96
97
    int JackNetInterface::SetNetBufferSize()
    {
        //audio
sletz's avatar
sletz committed
98
99
        float audio_size = (fNetAudioCaptureBuffer)
                            ? fNetAudioCaptureBuffer->GetCycleSize()
sletz's avatar
sletz committed
100
                            : (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->GetCycleSize() : 0;
sletz's avatar
sletz committed
101
        jack_log("audio_size %f", audio_size);
sletz's avatar
sletz committed
102

moret's avatar
moret committed
103
        //midi
sletz's avatar
sletz committed
104
105
        float midi_size = (fNetMidiCaptureBuffer)
                            ? fNetMidiCaptureBuffer->GetCycleSize()
sletz's avatar
sletz committed
106
                            : (fNetMidiPlaybackBuffer) ? fNetMidiPlaybackBuffer->GetCycleSize() : 0;
sletz's avatar
sletz committed
107
        jack_log("midi_size %f", midi_size);
sletz's avatar
sletz committed
108

moret's avatar
moret committed
109
        //bufsize = sync + audio + midi
sletz's avatar
sletz committed
110
        int bufsize = MAX_LATENCY * (fParams.fMtu + (int)audio_size + (int) midi_size);
sletz's avatar
sletz committed
111
        jack_log("SetNetBufferSize bufsize = %d", bufsize);
moret's avatar
moret committed
112
113

        //tx buffer
sletz's avatar
sletz committed
114
        if (fSocket.SetOption(SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR)
115
            return SOCKET_ERROR;
moret's avatar
moret committed
116
117

        //rx buffer
sletz's avatar
sletz committed
118
        if (fSocket.SetOption(SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR)
119
            return SOCKET_ERROR;
moret's avatar
moret committed
120

121
        return 0;
moret's avatar
moret committed
122
123
    }

sletz's avatar
sletz committed
124
    bool JackNetInterface::SetParams()
moret's avatar
moret committed
125
    {
126
        //TX header init
sletz's avatar
sletz committed
127
        strcpy(fTxHeader.fPacketType, "header");
128
129
130
        fTxHeader.fID = fParams.fID;
        fTxHeader.fCycle = 0;
        fTxHeader.fSubCycle = 0;
moret's avatar
moret committed
131
        fTxHeader.fIsLastPckt = 0;
132
133

        //RX header init
sletz's avatar
sletz committed
134
        strcpy(fRxHeader.fPacketType, "header");
135
136
137
        fRxHeader.fID = fParams.fID;
        fRxHeader.fCycle = 0;
        fRxHeader.fSubCycle = 0;
moret's avatar
moret committed
138
        fRxHeader.fIsLastPckt = 0;
139
140
141
142

        //network buffers
        fTxBuffer = new char[fParams.fMtu];
        fRxBuffer = new char[fParams.fMtu];
sletz's avatar
sletz committed
143
144
        assert(fTxBuffer);
        assert(fRxBuffer);
145

moret's avatar
moret committed
146
        //net audio/midi buffers'addresses
sletz's avatar
sletz committed
147
148
        fTxData = fTxBuffer + HEADER_SIZE;
        fRxData = fRxBuffer + HEADER_SIZE;
sletz's avatar
sletz committed
149

sletz's avatar
sletz committed
150
        return true;
151
152
    }

153
    // JackNetMasterInterface ************************************************************************************
154

155
    bool JackNetMasterInterface::Init()
156
    {
sletz's avatar
sletz committed
157
        jack_log("JackNetMasterInterface::Init, ID %u", fParams.fID);
158

159
        session_params_t host_params;
160
        uint attempt = 0;
161
162
163
        int rx_bytes = 0;

        //socket
sletz's avatar
sletz committed
164
165
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
166
            return false;
167
168
        }

169
        //timeout on receive (for init)
sletz's avatar
sletz committed
170
171
        if (fSocket.SetTimeOut(MASTER_INIT_TIMEOUT) < 0)
            jack_error("Can't set timeout : %s", StrError(NET_ERROR_CODE));
172

173
        //connect
sletz's avatar
sletz committed
174
175
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Can't connect : %s", StrError(NET_ERROR_CODE));
176
177
            return false;
        }
178

179
        //send 'SLAVE_SETUP' until 'START_MASTER' received
sletz's avatar
sletz committed
180
        jack_info("Sending parameters to %s...", fParams.fSlaveNetName);
181
182
        do
        {
183
            session_params_t net_params;
sletz's avatar
sletz committed
184
185
            memset(&net_params, 0, sizeof(session_params_t));
            SetPacketType(&fParams, SLAVE_SETUP);
186
            SessionParamsHToN(&fParams, &net_params);
187

sletz's avatar
sletz committed
188
            if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR)
sletz's avatar
sletz committed
189
                jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
190

sletz's avatar
sletz committed
191
            memset(&net_params, 0, sizeof(session_params_t));
sletz's avatar
sletz committed
192
            if (((rx_bytes = fSocket.Recv(&net_params, sizeof(session_params_t), 0)) == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA))
193
            {
sletz's avatar
sletz committed
194
                jack_error("Problem with network");
195
                return false;
196
            }
197

198
            SessionParamsNToH(&net_params, &host_params);
199
        }
sletz's avatar
sletz committed
200
201
202
        while ((GetPacketType(&host_params) != START_MASTER) && (++attempt < SLAVE_SETUP_RETRY));
        if (attempt == SLAVE_SETUP_RETRY) {
            jack_error("Slave doesn't respond, exiting");
203
            return false;
204
205
        }

206
        return true;
207
208
    }

sletz's avatar
sletz committed
209
    /*
moret's avatar
moret committed
210
211
    int JackNetMasterInterface::SetRxTimeout()
    {
sletz's avatar
sletz committed
212
        jack_log("JackNetMasterInterface::SetRxTimeout");
moret's avatar
moret committed
213

moret's avatar
moret committed
214
        float time = 0;
sletz's avatar
sletz committed
215

moret's avatar
moret committed
216
        //slow or normal mode, short timeout on recv (2 audio subcycles)
sletz's avatar
sletz committed
217
        if ((fParams.fNetworkMode == 's') || (fParams.fNetworkMode == 'n')) {
sletz's avatar
sletz committed
218
219
            time = 2000000.f * ((fNetAudioCaptureBuffer)
                                ? fNetAudioCaptureBuffer->GetCycleDuration()
sletz's avatar
sletz committed
220
221
                                : (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->GetCycleDuration() : 0);
        }
moret's avatar
moret committed
222
        //fast mode, wait for 75% of the entire cycle duration
sletz's avatar
sletz committed
223
224
225
        else if (fParams.fNetworkMode == 'f') {
            time = 750000.f * (static_cast<float>(fParams.fPeriodSize) / static_cast<float>(fParams.fSampleRate));
        }
sletz's avatar
sletz committed
226

sletz's avatar
sletz committed
227
        return fSocket.SetTimeOut(static_cast<int>(time));
moret's avatar
moret committed
228
    }
sletz's avatar
sletz committed
229
230
231
232
233
234
235
236
237
     */
    
    int JackNetMasterInterface::SetRxTimeout()
    {
        jack_log("JackNetMasterInterface::SetRxTimeout");
        float time = 3 * 1000000.f * (static_cast<float>(fParams.fPeriodSize) / static_cast<float>(fParams.fSampleRate));
        return fSocket.SetTimeOut(static_cast<int>(time));
    }
    
moret's avatar
moret committed
238

sletz's avatar
sletz committed
239
    bool JackNetMasterInterface::SetParams()
moret's avatar
moret committed
240
    {
sletz's avatar
sletz committed
241
242
        jack_log("JackNetMasterInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
            fParams.fSendAudioChannels, fParams.fReturnAudioChannels, fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
moret's avatar
moret committed
243
244
245

        JackNetInterface::SetParams();

246
247
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
248
249

        //midi net buffers
sletz's avatar
sletz committed
250
        if (fParams.fSendMidiChannels > 0)
sletz's avatar
sletz committed
251
            fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fTxData);
sletz's avatar
sletz committed
252

sletz's avatar
sletz committed
253
        if (fParams.fReturnMidiChannels > 0)
sletz's avatar
sletz committed
254
            fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
sletz's avatar
sletz committed
255

sletz's avatar
sletz committed
256
        try {
sletz's avatar
sletz committed
257

258
            //audio net buffers
sletz's avatar
sletz committed
259
            if (fParams.fSendAudioChannels > 0) {
sletz's avatar
sletz committed
260

261
                switch (fParams.fSampleEncoder) {
sletz's avatar
sletz committed
262

263
                    case JackFloatEncoder:
sletz's avatar
sletz committed
264
                        fNetAudioCaptureBuffer = new NetFloatAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
265
                        break;
sletz's avatar
sletz committed
266

267
                    case JackIntEncoder:
sletz's avatar
sletz committed
268
                        fNetAudioCaptureBuffer = new NetIntAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
269
                        break;
sletz's avatar
sletz committed
270

271
                    case JackCeltEncoder:
nedko's avatar
nedko committed
272
                    #if HAVE_CELT
sletz's avatar
sletz committed
273
                        fNetAudioCaptureBuffer = new NetCeltAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData, fParams.fKBps);
274
275
276
                    #endif
                        break;
                }
sletz's avatar
sletz committed
277

sletz's avatar
sletz committed
278
279
                assert(fNetAudioCaptureBuffer);
            }
sletz's avatar
sletz committed
280

sletz's avatar
sletz committed
281
            if (fParams.fReturnAudioChannels > 0) {
sletz's avatar
sletz committed
282

283
                switch (fParams.fSampleEncoder) {
sletz's avatar
sletz committed
284

285
                    case JackFloatEncoder:
sletz's avatar
sletz committed
286
                        fNetAudioPlaybackBuffer = new NetFloatAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
287
                        break;
sletz's avatar
sletz committed
288

289
                    case JackIntEncoder:
sletz's avatar
sletz committed
290
                        fNetAudioPlaybackBuffer = new NetIntAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
291
                        break;
sletz's avatar
sletz committed
292

293
                    case JackCeltEncoder:
nedko's avatar
nedko committed
294
                    #if HAVE_CELT
sletz's avatar
sletz committed
295
                        fNetAudioPlaybackBuffer = new NetCeltAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData, fParams.fKBps);
296
297
298
                    #endif
                        break;
                }
sletz's avatar
sletz committed
299

sletz's avatar
sletz committed
300
301
                assert(fNetAudioPlaybackBuffer);
            }
sletz's avatar
sletz committed
302

sletz's avatar
sletz committed
303
304
305
306
        } catch (exception&) {
            jack_error("NetAudioBuffer allocation error...");
            return false;
        }
moret's avatar
moret committed
307

sletz's avatar
sletz committed
308
        //set the new timeout for the socket
sletz's avatar
sletz committed
309
310
        if (SetRxTimeout() == SOCKET_ERROR) {
            jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
311
            goto error;
sletz's avatar
sletz committed
312
        }
moret's avatar
moret committed
313

sletz's avatar
sletz committed
314
        //set the new rx buffer size
sletz's avatar
sletz committed
315
316
        if (SetNetBufferSize() == SOCKET_ERROR) {
            jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
317
318
            goto error;
        }
sletz's avatar
sletz committed
319

sletz's avatar
sletz committed
320
        return true;
sletz's avatar
sletz committed
321

sletz's avatar
sletz committed
322
    error:
sletz's avatar
sletz committed
323
        FreeNetworkBuffers();
sletz's avatar
sletz committed
324
        return false;
moret's avatar
moret committed
325
326
    }

327
    void JackNetMasterInterface::Exit()
328
    {
sletz's avatar
sletz committed
329
        jack_log("JackNetMasterInterface::Exit, ID %u", fParams.fID);
330
331
332

        //stop process
        fRunning = false;
333

334
        //send a 'multicast euthanasia request' - new socket is required on macosx
sletz's avatar
sletz committed
335
336
337
        jack_info("Exiting '%s'", fParams.fName);
        SetPacketType(&fParams, KILL_MASTER);
        JackNetSocket mcast_socket(fMulticastIP, fSocket.GetPort());
338

339
        session_params_t net_params;
sletz's avatar
sletz committed
340
        memset(&net_params, 0, sizeof(session_params_t));
341
342
        SessionParamsHToN(&fParams, &net_params);

sletz's avatar
sletz committed
343
344
345
346
        if (mcast_socket.NewSocket() == SOCKET_ERROR)
            jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
        if (mcast_socket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR)
            jack_error("Can't send suicide request : %s", StrError(NET_ERROR_CODE));
347

348
349
350
        mcast_socket.Close();
    }

sletz's avatar
sletz committed
351
    int JackNetMasterInterface::Recv(size_t size, int flags)
352
    {
353
        int rx_bytes;
sletz's avatar
sletz committed
354

sletz's avatar
sletz committed
355
        if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
356
357

            /*
358
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
359
            //no data isn't really a network error, so just return 0 available read bytes
sletz's avatar
sletz committed
360
            if (error == NET_NO_DATA) {
361
                return 0;
sletz's avatar
sletz committed
362
            } else if (error == NET_CONN_ERROR) {
363
                //fatal connection issue, exit
sletz's avatar
sletz committed
364
                jack_error("'%s' : %s, exiting", fParams.fName, StrError(NET_ERROR_CODE));
365
                //ask to the manager to properly remove the master
366
                Exit();
367
368
                // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
                ThreadExit();
sletz's avatar
sletz committed
369
            } else {
sletz's avatar
sletz committed
370
                jack_error("Error in master receive : %s", StrError(NET_ERROR_CODE));
371
            }
372
373
374
375
376
377
378
379
            */

            //fatal connection issue, exit
            jack_error("'%s' : %s, exiting", fParams.fName, StrError(NET_ERROR_CODE));
            //ask to the manager to properly remove the master
            Exit();
            // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
            ThreadExit();
380
        }
381

382
383
384
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
        return rx_bytes;
385
    }
386

sletz's avatar
sletz committed
387
    int JackNetMasterInterface::Send(size_t size, int flags)
388
    {
389
390
391
        int tx_bytes;
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
        PacketHeaderHToN(header, header);
392

sletz's avatar
sletz committed
393
        if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
394
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
395
            if (error == NET_CONN_ERROR) {
396
                //fatal connection issue, exit
sletz's avatar
sletz committed
397
                jack_error("'%s' : %s, exiting", fParams.fName, StrError(NET_ERROR_CODE));
398
                Exit();
399
400
                // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
                ThreadExit();
sletz's avatar
sletz committed
401
402
            } else {
                jack_error("Error in master send : %s", StrError(NET_ERROR_CODE));
403
404
            }
        }
405
        return tx_bytes;
406
    }
407

408
409
    bool JackNetMasterInterface::IsSynched()
    {
sletz's avatar
sletz committed
410
        if (fParams.fNetworkMode == 's') {
411
            return (fCycleOffset < (CYCLE_OFFSET_SLOW + 1));
sletz's avatar
sletz committed
412
        } else {
413
            return true;
sletz's avatar
sletz committed
414
        }
415
    }
416

417
    int JackNetMasterInterface::SyncSend()
418
    {
419
420
421
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
sletz's avatar
sletz committed
422
        fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ?  1 : 0;
sletz's avatar
sletz committed
423
        fTxHeader.fPacketSize = fParams.fMtu;
sletz's avatar
sletz committed
424

sletz's avatar
sletz committed
425
426
        memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
        return Send(fTxHeader.fPacketSize, 0);
427
428
429
430
431
    }

    int JackNetMasterInterface::DataSend()
    {
        uint subproc;
sletz's avatar
sletz committed
432
433
        uint data_size;

434
        //midi
sletz's avatar
sletz committed
435
        if (fParams.fSendMidiChannels > 0) {
436
437
            //set global header fields and get the number of midi packets
            fTxHeader.fDataType = 'm';
sletz's avatar
sletz committed
438
            data_size = fNetMidiCaptureBuffer->RenderFromJackPorts();
sletz's avatar
sletz committed
439
            fTxHeader.fNumPacket = fNetMidiCaptureBuffer->GetNumPackets(data_size, PACKET_AVAILABLE_SIZE);
sletz's avatar
sletz committed
440

sletz's avatar
sletz committed
441
            for (subproc = 0; subproc < fTxHeader.fNumPacket; subproc++) {
442
                fTxHeader.fSubCycle = subproc;
sletz's avatar
sletz committed
443
444
                fTxHeader.fIsLastPckt = ((subproc == (fTxHeader.fNumPacket - 1)) && (fParams.fSendAudioChannels == 0)) ? 1 : 0;
                fTxHeader.fPacketSize = HEADER_SIZE + fNetMidiCaptureBuffer->RenderToNetwork(subproc, data_size);
sletz's avatar
sletz committed
445
446
                memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
447
                    return SOCKET_ERROR;
448
449
            }
        }
450
451

        //audio
sletz's avatar
sletz committed
452
        if (fParams.fSendAudioChannels > 0) {
453
            fTxHeader.fDataType = 'a';
sletz's avatar
sletz committed
454
455
            data_size = fNetAudioCaptureBuffer->RenderFromJackPorts();
            fTxHeader.fNumPacket = fNetAudioCaptureBuffer->GetNumPackets();
sletz's avatar
sletz committed
456

sletz's avatar
sletz committed
457
            for (subproc = 0; subproc < fTxHeader.fNumPacket; subproc++) {
458
                fTxHeader.fSubCycle = subproc;
sletz's avatar
sletz committed
459
460
                fTxHeader.fIsLastPckt = (subproc == (fTxHeader.fNumPacket - 1)) ? 1 : 0;
                fTxHeader.fPacketSize = HEADER_SIZE + fNetAudioCaptureBuffer->RenderToNetwork(subproc, data_size);
sletz's avatar
sletz committed
461
462
                memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
463
464
465
466
467
                    return SOCKET_ERROR;
            }
        }

        return 0;
468
469
    }

470
    int JackNetMasterInterface::SyncRecv()
471
    {
sletz's avatar
sletz committed
472
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
sletz's avatar
sletz committed
473
        int rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
474

sletz's avatar
sletz committed
475
476
477
478
        if ((rx_bytes == 0) || (rx_bytes == SOCKET_ERROR)) {
            // O bytes considered an error (lost connection)
            return SOCKET_ERROR;
        }
479

480
        fCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
481

sletz's avatar
sletz committed
482
        switch (fParams.fNetworkMode)
483
        {
484
            case 's' :
moret's avatar
moret committed
485
486
487
488
489
                //slow mode : allow to use full bandwidth and heavy process on the slave
                //  - extra latency is set to two cycles, one cycle for send/receive operations + one cycle for heavy process on the slave
                //  - if the network is two fast, just wait the next cycle, this mode allows a shorter cycle duration for the master
                //  - this mode will skip the two first cycles, thus it lets time for data to be processed and queued on the socket rx buffer
                //the slow mode is the safest mode because it wait twice the bandwidth relative time (send/return + process)
490

sletz's avatar
sletz committed
491
492
493
                if (fCycleOffset < CYCLE_OFFSET_SLOW) {
                    return 0;
                } else {
sletz's avatar
sletz committed
494
                    rx_bytes = Recv(rx_head->fPacketSize, 0);
sletz's avatar
sletz committed
495
496
497
                }

                /*
sletz's avatar
sletz committed
498
                rx_bytes = Recv(rx_head->fPacketSize, 0);
sletz's avatar
sletz committed
499

sletz's avatar
sletz committed
500
                if (fCycleOffset != fLastfCycleOffset)
501
                    jack_info("Warning : '%s' runs in slow network mode, but data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
sletz's avatar
sletz committed
502
                fLastfCycleOffset = fCycleOffset;
sletz's avatar
sletz committed
503
504
                */

505
                break;
506

507
508
509
510
511
            case 'n' :
                //normal use of the network :
                //  - extra latency is set to one cycle, what is the time needed to receive streams using full network bandwidth
                //  - if the network is too fast, just wait the next cycle, the benefit here is the master's cycle is shorter
                //  - indeed, data is supposed to be on the network rx buffer, so we don't have to wait for it
sletz's avatar
sletz committed
512
                if (fCycleOffset < CYCLE_OFFSET_NORMAL) {
513
                    return 0;
sletz's avatar
sletz committed
514
                } else {
sletz's avatar
sletz committed
515
                    rx_bytes = Recv(rx_head->fPacketSize, 0);
sletz's avatar
sletz committed
516
                }
517

sletz's avatar
sletz committed
518
                if (fCycleOffset > CYCLE_OFFSET_NORMAL)  {
519
                    jack_info("'%s' can't run in normal network mode, data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
sletz's avatar
sletz committed
520
                }
521
                break;
522

523
524
525
526
527
            case 'f' :
                //fast mode suppose the network bandwith is larger than required for the transmission (only a few channels for example)
                //    - packets can be quickly received, quickly is here relative to the cycle duration
                //    - here, receive data, we can't keep it queued on the rx buffer,
                //    - but if there is a cycle offset, tell the user, that means we're not in fast mode anymore, network is too slow
sletz's avatar
sletz committed
528
                rx_bytes = Recv(rx_head->fPacketSize, 0);
529

sletz's avatar
sletz committed
530
                if (fCycleOffset > CYCLE_OFFSET_FAST) {
531
                    jack_info("'%s' can't run in fast network mode, data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
sletz's avatar
sletz committed
532
                }
533
                break;
534
        }
535

moret's avatar
moret committed
536
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
537
538
        return rx_bytes;
    }
539

540
    int JackNetMasterInterface::DataRecv()
541
542
    {
        int rx_bytes = 0;
543
        uint recvd_midi_pckt = 0;
sletz's avatar
sletz committed
544
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
545

sletz's avatar
sletz committed
546
        while (!fRxHeader.fIsLastPckt)
547
        {
moret's avatar
moret committed
548
            //how much data is queued on the rx buffer ?
sletz's avatar
sletz committed
549
            rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
550

sletz's avatar
sletz committed
551
            //error here, problem with recv, just skip the cycle (return -1)
sletz's avatar
sletz committed
552
            if (rx_bytes == SOCKET_ERROR)
moret's avatar
moret committed
553
                return rx_bytes;
sletz's avatar
sletz committed
554

sletz's avatar
sletz committed
555
            if (rx_bytes && (rx_head->fDataStream == 'r') && (rx_head->fID == fParams.fID))
moret's avatar
moret committed
556
557
            {
                //read data
sletz's avatar
sletz committed
558
                switch (rx_head->fDataType)
559
                {
moret's avatar
moret committed
560
                    case 'm':   //midi
sletz's avatar
sletz committed
561
                        rx_bytes = Recv(rx_head->fPacketSize, 0);
moret's avatar
moret committed
562
                        fRxHeader.fCycle = rx_head->fCycle;
moret's avatar
moret committed
563
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
sletz's avatar
sletz committed
564
                        fNetMidiPlaybackBuffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
sletz's avatar
sletz committed
565
566
                        // Last midi packet is received, so finish rendering...
                        if (++recvd_midi_pckt == rx_head->fNumPacket)
moret's avatar
moret committed
567
568
                            fNetMidiPlaybackBuffer->RenderToJackPorts();
                        break;
569

moret's avatar
moret committed
570
                    case 'a':   //audio
sletz's avatar
sletz committed
571
                        rx_bytes = Recv(rx_head->fPacketSize, 0);
moret's avatar
moret committed
572
573
                        fRxHeader.fCycle = rx_head->fCycle;
                        fRxHeader.fSubCycle = rx_head->fSubCycle;
moret's avatar
moret committed
574
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
sletz's avatar
sletz committed
575
                        fNetAudioPlaybackBuffer->RenderFromNetwork(rx_head->fCycle, rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
sletz's avatar
sletz committed
576
577
                        // Last audio packet is received, so finish rendering...
                        if (fRxHeader.fIsLastPckt)
sletz's avatar
sletz committed
578
                            fNetAudioPlaybackBuffer->RenderToJackPorts();
moret's avatar
moret committed
579
                        break;
580

moret's avatar
moret committed
581
                    case 's':   //sync
582
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
sletz's avatar
sletz committed
583
                        // TODO : finish midi and audio rendering ?
sletz's avatar
sletz committed
584
                        fNetAudioPlaybackBuffer->RenderToJackPorts();
585
                        return 0;
586
587
588
                }
            }
        }
sletz's avatar
sletz committed
589

590
        return rx_bytes;
591
    }
592

593
    void JackNetMasterInterface::EncodeSyncPacket()
594
595
596
    {
        //this method contains every step of sync packet informations coding
        //first of all, reset sync packet
sletz's avatar
sletz committed
597
        memset(fTxData, 0, PACKET_AVAILABLE_SIZE);
598
599

        //then, first step : transport
600
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
601
602
603
            // desactivated...
            //EncodeTransportData();
            TransportDataHToN(&fSendTransportData,  &fSendTransportData);
604
            //copy to TxBuffer
sletz's avatar
sletz committed
605
            memcpy(fTxData, &fSendTransportData, sizeof(net_transport_data_t));
606
607
608
609
610
        }
        //then others (freewheel etc.)
        //...
    }

611
    void JackNetMasterInterface::DecodeSyncPacket()
612
613
614
    {
        //this method contains every step of sync packet informations decoding process
        //first : transport
615
        if (fParams.fTransportSync) {
616
            //copy received transport data to transport data structure
sletz's avatar
sletz committed
617
618
619
620
            memcpy(&fReturnTransportData, fRxData, sizeof(net_transport_data_t));
            TransportDataNToH(&fReturnTransportData,  &fReturnTransportData);
            // desactivated...
            //DecodeTransportData();
621
622
623
624
        }
        //then others
        //...
    }
625

626
627
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
628
629
    uint JackNetSlaveInterface::fSlaveCounter = 0;

630
    bool JackNetSlaveInterface::Init()
631
    {
sletz's avatar
sletz committed
632
        jack_log("JackNetSlaveInterface::Init()");
633

634
        //set the parameters to send
sletz's avatar
sletz committed
635
        strcpy(fParams.fPacketType, "params");
636
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
sletz's avatar
sletz committed
637
        SetPacketType(&fParams, SLAVE_AVAILABLE);
638

639
640
        //init loop : get a master and start, do it until connection is ok
        net_status_t status;
641
        do {
642
            //first, get a master, do it until a valid connection is running
643
            do {
644
                status = SendAvailableToMaster();
sletz's avatar
sletz committed
645
                if (status == NET_SOCKET_ERROR)
646
                    return false;
647
            }
sletz's avatar
sletz committed
648
            while (status != NET_CONNECTED);
649

650
            //then tell the master we are ready
sletz's avatar
sletz committed
651
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
moret's avatar
moret committed
652
            status = SendStartToMaster();
sletz's avatar
sletz committed
653
            if (status == NET_ERROR)
654
                return false;
655
        }
sletz's avatar
sletz committed
656
        while (status != NET_ROLLING);
657

658
659
        return true;
    }
660

661
    // Separate the connection protocol into two separated step
sletz's avatar
sletz committed
662
    bool JackNetSlaveInterface::InitConnection(int time_out)
663
    {
sletz's avatar
sletz committed
664
        jack_log("JackNetSlaveInterface::InitConnection()");
sletz's avatar
sletz committed
665
        unsigned int try_count = (time_out > 0) ? ((1000000 * time_out) / SLAVE_INIT_TIMEOUT) : LONG_MAX;
666
667

        //set the parameters to send
sletz's avatar
sletz committed
668
        strcpy(fParams.fPacketType, "params");
669
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
sletz's avatar
sletz committed
670
        SetPacketType(&fParams, SLAVE_AVAILABLE);
671
672

        net_status_t status;
673
        do {
674
            //get a master
sletz's avatar
sletz committed
675
            status = SendAvailableToMaster(try_count);
676
677
678
            if (status == NET_SOCKET_ERROR)
                return false;
        }
sletz's avatar
sletz committed
679
        while (status != NET_CONNECTED && --try_count > 0);
680

sletz's avatar
sletz committed
681
        return (try_count != 0);
682
    }
683

684
685
686
687
688
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

        net_status_t status;
689
        do {
690
691
692
693
694
695
            //then tell the master we are ready
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
            status = SendStartToMaster();
            if (status == NET_ERROR)
                return false;
        }
696
697
        while (status != NET_ROLLING);

698
699
        return true;
    }
700

sletz's avatar
sletz committed
701
    net_status_t JackNetSlaveInterface::SendAvailableToMaster(long try_count)
702
    {
sletz's avatar
sletz committed
703
        jack_log("JackNetSlaveInterface::SendAvailableToMaster()");
704
        //utility
705
        session_params_t host_params;
706
707
708
        int rx_bytes = 0;

        //socket
sletz's avatar
sletz committed
709
710
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Fatal error : network unreachable - %s", StrError(NET_ERROR_CODE));
711
            return NET_SOCKET_ERROR;
712
713
        }

714
        //bind the socket
sletz's avatar
sletz committed
715
716
        if (fSocket.Bind() == SOCKET_ERROR) {
            jack_error("Can't bind the socket : %s", StrError(NET_ERROR_CODE));
717
718
            return NET_SOCKET_ERROR;
        }
719
720

        //timeout on receive
sletz's avatar
sletz committed
721
722
        if (fSocket.SetTimeOut(SLAVE_INIT_TIMEOUT) == SOCKET_ERROR)
            jack_error("Can't set timeout : %s", StrError(NET_ERROR_CODE));
723

724
        //disable local loop
sletz's avatar
sletz committed
725
726
        if (fSocket.SetLocalLoop() == SOCKET_ERROR)
            jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
727

728
        //send 'AVAILABLE' until 'SLAVE_SETUP' received
sletz's avatar
sletz committed
729
        jack_info("Waiting for a master...");
730
        do {
731
            //send 'available'
732
            session_params_t net_params;
sletz's avatar
sletz committed
733
            memset(&net_params, 0, sizeof(session_params_t));
734
            SessionParamsHToN(&fParams, &net_params);
sletz's avatar
sletz committed
735
736
            if (fSocket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR)
                jack_error("Error in data send : %s", StrError(NET_ERROR_CODE));
737

738
            //filter incoming packets : don't exit while no error is detected
sletz's avatar
sletz committed
739
740
            memset(&net_params, 0, sizeof(session_params_t));
            rx_bytes = fSocket.CatchHost(&net_params, sizeof(session_params_t), 0);