JackNetInterface.cpp 39.1 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
    }

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

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

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

sletz's avatar
sletz committed
226
        return fSocket.SetTimeOut(static_cast<int>(time));
moret's avatar
moret committed
227
228
    }

sletz's avatar
sletz committed
229
    bool JackNetMasterInterface::SetParams()
moret's avatar
moret committed
230
    {
sletz's avatar
sletz committed
231
232
        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
233
234
235

        JackNetInterface::SetParams();

236
237
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
238
239

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

sletz's avatar
sletz committed
243
        if (fParams.fReturnMidiChannels > 0)
sletz's avatar
sletz committed
244
            fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
sletz's avatar
sletz committed
245

sletz's avatar
sletz committed
246
        try {
sletz's avatar
sletz committed
247

248
            //audio net buffers
sletz's avatar
sletz committed
249
            if (fParams.fSendAudioChannels > 0) {
sletz's avatar
sletz committed
250

251
                switch (fParams.fSampleEncoder) {
sletz's avatar
sletz committed
252

253
                    case JackFloatEncoder:
sletz's avatar
sletz committed
254
                        fNetAudioCaptureBuffer = new NetFloatAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
255
                        break;
sletz's avatar
sletz committed
256

257
                    case JackIntEncoder:
sletz's avatar
sletz committed
258
                        fNetAudioCaptureBuffer = new NetIntAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
259
                        break;
sletz's avatar
sletz committed
260

261
                    case JackCeltEncoder:
nedko's avatar
nedko committed
262
                    #if HAVE_CELT
sletz's avatar
sletz committed
263
                        fNetAudioCaptureBuffer = new NetCeltAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData, fParams.fKBps);
264
265
266
                    #endif
                        break;
                }
sletz's avatar
sletz committed
267

sletz's avatar
sletz committed
268
269
                assert(fNetAudioCaptureBuffer);
            }
sletz's avatar
sletz committed
270

sletz's avatar
sletz committed
271
            if (fParams.fReturnAudioChannels > 0) {
sletz's avatar
sletz committed
272

273
                switch (fParams.fSampleEncoder) {
sletz's avatar
sletz committed
274

275
                    case JackFloatEncoder:
sletz's avatar
sletz committed
276
                        fNetAudioPlaybackBuffer = new NetFloatAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
277
                        break;
sletz's avatar
sletz committed
278

279
                    case JackIntEncoder:
sletz's avatar
sletz committed
280
                        fNetAudioPlaybackBuffer = new NetIntAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
281
                        break;
sletz's avatar
sletz committed
282

283
                    case JackCeltEncoder:
nedko's avatar
nedko committed
284
                    #if HAVE_CELT
sletz's avatar
sletz committed
285
                        fNetAudioPlaybackBuffer = new NetCeltAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData, fParams.fKBps);
286
287
288
                    #endif
                        break;
                }
sletz's avatar
sletz committed
289

sletz's avatar
sletz committed
290
291
                assert(fNetAudioPlaybackBuffer);
            }
sletz's avatar
sletz committed
292

sletz's avatar
sletz committed
293
294
295
296
        } catch (exception&) {
            jack_error("NetAudioBuffer allocation error...");
            return false;
        }
moret's avatar
moret committed
297

sletz's avatar
sletz committed
298
        //set the new timeout for the socket
sletz's avatar
sletz committed
299
300
        if (SetRxTimeout() == SOCKET_ERROR) {
            jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
301
302
            goto error;
        }
moret's avatar
moret committed
303

sletz's avatar
sletz committed
304
        //set the new rx buffer size
sletz's avatar
sletz committed
305
306
        if (SetNetBufferSize() == SOCKET_ERROR) {
            jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
307
308
            goto error;
        }
sletz's avatar
sletz committed
309

sletz's avatar
sletz committed
310
        return true;
sletz's avatar
sletz committed
311

sletz's avatar
sletz committed
312
    error:
sletz's avatar
sletz committed
313
        FreeNetworkBuffers();
sletz's avatar
sletz committed
314
        return false;
moret's avatar
moret committed
315
316
    }

317
    void JackNetMasterInterface::Exit()
318
    {
sletz's avatar
sletz committed
319
        jack_log("JackNetMasterInterface::Exit, ID %u", fParams.fID);
320
321
322

        //stop process
        fRunning = false;
323

324
        //send a 'multicast euthanasia request' - new socket is required on macosx
sletz's avatar
sletz committed
325
326
327
        jack_info("Exiting '%s'", fParams.fName);
        SetPacketType(&fParams, KILL_MASTER);
        JackNetSocket mcast_socket(fMulticastIP, fSocket.GetPort());
328

329
        session_params_t net_params;
sletz's avatar
sletz committed
330
        memset(&net_params, 0, sizeof(session_params_t));
331
332
        SessionParamsHToN(&fParams, &net_params);

sletz's avatar
sletz committed
333
334
335
336
        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));
337

338
339
340
        mcast_socket.Close();
    }

sletz's avatar
sletz committed
341
    int JackNetMasterInterface::Recv(size_t size, int flags)
342
    {
343
        int rx_bytes;
sletz's avatar
sletz committed
344

sletz's avatar
sletz committed
345
        if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
346
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
347
            //no data isn't really a network error, so just return 0 available read bytes
sletz's avatar
sletz committed
348
            if (error == NET_NO_DATA) {
349
                return 0;
sletz's avatar
sletz committed
350
            } else if (error == NET_CONN_ERROR) {
351
                //fatal connection issue, exit
sletz's avatar
sletz committed
352
                jack_error("'%s' : %s, exiting", fParams.fName, StrError(NET_ERROR_CODE));
353
                //ask to the manager to properly remove the master
354
                Exit();
355
356
                // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
                ThreadExit();
sletz's avatar
sletz committed
357
            } else {
sletz's avatar
sletz committed
358
                jack_error("Error in master receive : %s", StrError(NET_ERROR_CODE));
359
360
            }
        }
361

362
363
364
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
        return rx_bytes;
365
    }
366

sletz's avatar
sletz committed
367
    int JackNetMasterInterface::Send(size_t size, int flags)
368
    {
369
370
371
        int tx_bytes;
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
        PacketHeaderHToN(header, header);
372

sletz's avatar
sletz committed
373
        if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
374
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
375
            if (error == NET_CONN_ERROR) {
376
                //fatal connection issue, exit
sletz's avatar
sletz committed
377
                jack_error("'%s' : %s, exiting", fParams.fName, StrError(NET_ERROR_CODE));
378
                Exit();
379
380
                // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
                ThreadExit();
sletz's avatar
sletz committed
381
382
            } else {
                jack_error("Error in master send : %s", StrError(NET_ERROR_CODE));
383
384
            }
        }
385
        return tx_bytes;
386
    }
387

388
389
    bool JackNetMasterInterface::IsSynched()
    {
sletz's avatar
sletz committed
390
        if (fParams.fNetworkMode == 's') {
391
            return (fCycleOffset < (CYCLE_OFFSET_SLOW + 1));
sletz's avatar
sletz committed
392
        } else {
393
            return true;
sletz's avatar
sletz committed
394
        }
395
    }
396

397
    int JackNetMasterInterface::SyncSend()
398
    {
399
400
401
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
sletz's avatar
sletz committed
402
        fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ?  1 : 0;
sletz's avatar
sletz committed
403
        fTxHeader.fPacketSize = fParams.fMtu;
sletz's avatar
sletz committed
404

sletz's avatar
sletz committed
405
406
        memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
        return Send(fTxHeader.fPacketSize, 0);
407
408
409
410
411
    }

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

414
        //midi
sletz's avatar
sletz committed
415
        if (fParams.fSendMidiChannels > 0) {
416
417
            //set global header fields and get the number of midi packets
            fTxHeader.fDataType = 'm';
sletz's avatar
sletz committed
418
            data_size = fNetMidiCaptureBuffer->RenderFromJackPorts();
sletz's avatar
sletz committed
419
            fTxHeader.fNumPacket = fNetMidiCaptureBuffer->GetNumPackets(data_size, PACKET_AVAILABLE_SIZE);
sletz's avatar
sletz committed
420

sletz's avatar
sletz committed
421
            for (subproc = 0; subproc < fTxHeader.fNumPacket; subproc++) {
422
                fTxHeader.fSubCycle = subproc;
sletz's avatar
sletz committed
423
424
                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
425
426
                memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
427
                    return SOCKET_ERROR;
428
429
            }
        }
430
431

        //audio
sletz's avatar
sletz committed
432
        if (fParams.fSendAudioChannels > 0) {
433
            fTxHeader.fDataType = 'a';
sletz's avatar
sletz committed
434
435
            data_size = fNetAudioCaptureBuffer->RenderFromJackPorts();
            fTxHeader.fNumPacket = fNetAudioCaptureBuffer->GetNumPackets();
sletz's avatar
sletz committed
436

sletz's avatar
sletz committed
437
            for (subproc = 0; subproc < fTxHeader.fNumPacket; subproc++) {
438
                fTxHeader.fSubCycle = subproc;
sletz's avatar
sletz committed
439
440
                fTxHeader.fIsLastPckt = (subproc == (fTxHeader.fNumPacket - 1)) ? 1 : 0;
                fTxHeader.fPacketSize = HEADER_SIZE + fNetAudioCaptureBuffer->RenderToNetwork(subproc, data_size);
sletz's avatar
sletz committed
441
442
                memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
443
444
445
446
447
                    return SOCKET_ERROR;
            }
        }

        return 0;
448
449
    }

450
    int JackNetMasterInterface::SyncRecv()
451
    {
sletz's avatar
sletz committed
452
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
sletz's avatar
sletz committed
453
        int rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
454

sletz's avatar
sletz committed
455
456
457
458
        if ((rx_bytes == 0) || (rx_bytes == SOCKET_ERROR)) {
            // O bytes considered an error (lost connection)
            return SOCKET_ERROR;
        }
459

460
        fCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
461

sletz's avatar
sletz committed
462
        switch (fParams.fNetworkMode)
463
        {
464
            case 's' :
moret's avatar
moret committed
465
466
467
468
469
                //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)
470

sletz's avatar
sletz committed
471
472
473
                if (fCycleOffset < CYCLE_OFFSET_SLOW) {
                    return 0;
                } else {
sletz's avatar
sletz committed
474
                    rx_bytes = Recv(rx_head->fPacketSize, 0);
sletz's avatar
sletz committed
475
476
477
                }

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

sletz's avatar
sletz committed
480
                if (fCycleOffset != fLastfCycleOffset)
481
                    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
482
                fLastfCycleOffset = fCycleOffset;
sletz's avatar
sletz committed
483
484
                */

485
                break;
486

487
488
489
490
491
            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
492
                if (fCycleOffset < CYCLE_OFFSET_NORMAL) {
493
                    return 0;
sletz's avatar
sletz committed
494
                } else {
sletz's avatar
sletz committed
495
                    rx_bytes = Recv(rx_head->fPacketSize, 0);
sletz's avatar
sletz committed
496
                }
497

sletz's avatar
sletz committed
498
                if (fCycleOffset > CYCLE_OFFSET_NORMAL)  {
499
                    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
500
                }
501
                break;
502

503
504
505
506
507
            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
508
                rx_bytes = Recv(rx_head->fPacketSize, 0);
509

sletz's avatar
sletz committed
510
                if (fCycleOffset > CYCLE_OFFSET_FAST) {
511
                    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
512
                }
513
                break;
514
        }
515

moret's avatar
moret committed
516
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
517
518
        return rx_bytes;
    }
519

520
    int JackNetMasterInterface::DataRecv()
521
522
    {
        int rx_bytes = 0;
523
        uint recvd_midi_pckt = 0;
sletz's avatar
sletz committed
524
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
525

sletz's avatar
sletz committed
526
        while (!fRxHeader.fIsLastPckt)
527
        {
moret's avatar
moret committed
528
            //how much data is queued on the rx buffer ?
sletz's avatar
sletz committed
529
            rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
530

sletz's avatar
sletz committed
531
            //error here, problem with recv, just skip the cycle (return -1)
sletz's avatar
sletz committed
532
            if (rx_bytes == SOCKET_ERROR)
moret's avatar
moret committed
533
                return rx_bytes;
sletz's avatar
sletz committed
534

sletz's avatar
sletz committed
535
            if (rx_bytes && (rx_head->fDataStream == 'r') && (rx_head->fID == fParams.fID))
moret's avatar
moret committed
536
537
            {
                //read data
sletz's avatar
sletz committed
538
                switch (rx_head->fDataType)
539
                {
moret's avatar
moret committed
540
                    case 'm':   //midi
sletz's avatar
sletz committed
541
                        rx_bytes = Recv(rx_head->fPacketSize, 0);
moret's avatar
moret committed
542
                        fRxHeader.fCycle = rx_head->fCycle;
moret's avatar
moret committed
543
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
sletz's avatar
sletz committed
544
                        fNetMidiPlaybackBuffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
sletz's avatar
sletz committed
545
546
                        // Last midi packet is received, so finish rendering...
                        if (++recvd_midi_pckt == rx_head->fNumPacket)
moret's avatar
moret committed
547
548
                            fNetMidiPlaybackBuffer->RenderToJackPorts();
                        break;
549

moret's avatar
moret committed
550
                    case 'a':   //audio
sletz's avatar
sletz committed
551
                        rx_bytes = Recv(rx_head->fPacketSize, 0);
moret's avatar
moret committed
552
553
                        fRxHeader.fCycle = rx_head->fCycle;
                        fRxHeader.fSubCycle = rx_head->fSubCycle;
moret's avatar
moret committed
554
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
sletz's avatar
sletz committed
555
                        fNetAudioPlaybackBuffer->RenderFromNetwork(rx_head->fCycle, rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
sletz's avatar
sletz committed
556
557
                        // Last audio packet is received, so finish rendering...
                        if (fRxHeader.fIsLastPckt)
sletz's avatar
sletz committed
558
                            fNetAudioPlaybackBuffer->RenderToJackPorts();
moret's avatar
moret committed
559
                        break;
560

moret's avatar
moret committed
561
                    case 's':   //sync
562
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
sletz's avatar
sletz committed
563
                        // TODO : finish midi and audio rendering ?
sletz's avatar
sletz committed
564
                        fNetAudioPlaybackBuffer->RenderToJackPorts();
565
                        return 0;
566
567
568
                }
            }
        }
sletz's avatar
sletz committed
569

570
        return rx_bytes;
571
    }
572

573
    void JackNetMasterInterface::EncodeSyncPacket()
574
575
576
    {
        //this method contains every step of sync packet informations coding
        //first of all, reset sync packet
sletz's avatar
sletz committed
577
        memset(fTxData, 0, PACKET_AVAILABLE_SIZE);
578
579

        //then, first step : transport
580
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
581
582
583
            // desactivated...
            //EncodeTransportData();
            TransportDataHToN(&fSendTransportData,  &fSendTransportData);
584
            //copy to TxBuffer
sletz's avatar
sletz committed
585
            memcpy(fTxData, &fSendTransportData, sizeof(net_transport_data_t));
586
587
588
589
590
        }
        //then others (freewheel etc.)
        //...
    }

591
    void JackNetMasterInterface::DecodeSyncPacket()
592
593
594
    {
        //this method contains every step of sync packet informations decoding process
        //first : transport
595
        if (fParams.fTransportSync) {
596
            //copy received transport data to transport data structure
sletz's avatar
sletz committed
597
598
599
600
            memcpy(&fReturnTransportData, fRxData, sizeof(net_transport_data_t));
            TransportDataNToH(&fReturnTransportData,  &fReturnTransportData);
            // desactivated...
            //DecodeTransportData();
601
602
603
604
        }
        //then others
        //...
    }
605

606
607
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
608
609
    uint JackNetSlaveInterface::fSlaveCounter = 0;

610
    bool JackNetSlaveInterface::Init()
611
    {
sletz's avatar
sletz committed
612
        jack_log("JackNetSlaveInterface::Init()");
613

614
        //set the parameters to send
sletz's avatar
sletz committed
615
        strcpy(fParams.fPacketType, "params");
616
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
sletz's avatar
sletz committed
617
        SetPacketType(&fParams, SLAVE_AVAILABLE);
618

619
620
621
        //init loop : get a master and start, do it until connection is ok
        net_status_t status;
        do
622
        {
623
624
            //first, get a master, do it until a valid connection is running
            do
625
            {
626
                status = SendAvailableToMaster();
sletz's avatar
sletz committed
627
                if (status == NET_SOCKET_ERROR)
628
                    return false;
629
            }
sletz's avatar
sletz committed
630
            while (status != NET_CONNECTED);
631

632
            //then tell the master we are ready
sletz's avatar
sletz committed
633
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
moret's avatar
moret committed
634
            status = SendStartToMaster();
sletz's avatar
sletz committed
635
            if (status == NET_ERROR)
636
                return false;
637
        }
sletz's avatar
sletz committed
638
        while (status != NET_ROLLING);
639

640
641
        return true;
    }
642

643
    // Separate the connection protocol into two separated step
sletz's avatar
sletz committed
644
    bool JackNetSlaveInterface::InitConnection(int time_out)
645
    {
sletz's avatar
sletz committed
646
        jack_log("JackNetSlaveInterface::InitConnection()");
sletz's avatar
sletz committed
647
        unsigned int try_count = (time_out > 0) ? ((1000000 * time_out) / SLAVE_INIT_TIMEOUT) : LONG_MAX;
648
649

        //set the parameters to send
sletz's avatar
sletz committed
650
        strcpy(fParams.fPacketType, "params");
651
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
sletz's avatar
sletz committed
652
        SetPacketType(&fParams, SLAVE_AVAILABLE);
653
654
655
656
657

        net_status_t status;
        do
        {
            //get a master
sletz's avatar
sletz committed
658
            status = SendAvailableToMaster(try_count);
659
660
661
            if (status == NET_SOCKET_ERROR)
                return false;
        }
sletz's avatar
sletz committed
662
        while (status != NET_CONNECTED && --try_count > 0);
663

sletz's avatar
sletz committed
664
        return (try_count != 0);
665
    }
666

667
668
669
670
671
672
673
674
675
676
677
678
679
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

        net_status_t status;
        do
        {
            //then tell the master we are ready
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
            status = SendStartToMaster();
            if (status == NET_ERROR)
                return false;
        }
680
681
        while (status != NET_ROLLING);

682
683
        return true;
    }
684

sletz's avatar
sletz committed
685
    net_status_t JackNetSlaveInterface::SendAvailableToMaster(long try_count)
686
    {
sletz's avatar
sletz committed
687
        jack_log("JackNetSlaveInterface::SendAvailableToMaster()");
688
        //utility
689
        session_params_t host_params;
690
691
692
        int rx_bytes = 0;

        //socket
sletz's avatar
sletz committed
693
694
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Fatal error : network unreachable - %s", StrError(NET_ERROR_CODE));
695
            return NET_SOCKET_ERROR;
696
697
        }

698
        //bind the socket
sletz's avatar
sletz committed
699
700
        if (fSocket.Bind() == SOCKET_ERROR) {
            jack_error("Can't bind the socket : %s", StrError(NET_ERROR_CODE));
701
702
            return NET_SOCKET_ERROR;
        }
703
704

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

708
        //disable local loop
sletz's avatar
sletz committed
709
710
        if (fSocket.SetLocalLoop() == SOCKET_ERROR)
            jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
711

712
        //send 'AVAILABLE' until 'SLAVE_SETUP' received
sletz's avatar
sletz committed
713
        jack_info("Waiting for a master...");
714
715
        do
        {
716
            //send 'available'
717
            session_params_t net_params;
sletz's avatar
sletz committed
718
            memset(&net_params, 0, sizeof(session_params_t));
719
            SessionParamsHToN(&fParams, &net_params);
sletz's avatar
sletz committed
720
721
            if (fSocket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR)
                jack_error("Error in data send : %s", StrError(NET_ERROR_CODE));
722

723
            //filter incoming packets : don't exit while no error is detected
sletz's avatar
sletz committed
724
725
            memset(&net_params, 0, sizeof(session_params_t));
            rx_bytes = fSocket.CatchHost(&net_params, sizeof(session_params_t), 0);
726
            SessionParamsNToH(&net_params, &host_params);
sletz's avatar
sletz committed
727
            if ((rx_bytes == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA))
728
            {
sletz's avatar
sletz committed
729
                jack_error("Can't receive : %s", StrError(NET_ERROR_CODE));
730
                return NET_RECV_ERROR;
731
732
            }
        }
sletz's avatar
sletz committed
733
        while (strcmp(host_params.fPacketType, fParams.fPacketType)  && (GetPacketType(&host_params) != SLAVE_SETUP)  && (--try_count > 0));
sletz's avatar
sletz committed
734

sletz's avatar
sletz committed
735
        // Time out failure..
sletz's avatar
sletz committed
736
737
        if (try_count == 0) {
            jack_error("Time out error in connect");
sletz's avatar
sletz committed
738
739
            return NET_CONNECT_ERROR;
        }