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

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
110
        int bufsize = NETWORK_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
210
211
212
213
214
    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
215

sletz's avatar
sletz committed
216
    bool JackNetMasterInterface::SetParams()
moret's avatar
moret committed
217
    {
sletz's avatar
sletz committed
218
219
        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
220
221
222

        JackNetInterface::SetParams();

223
224
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
225
226

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

sletz's avatar
sletz committed
230
        if (fParams.fReturnMidiChannels > 0)
sletz's avatar
sletz committed
231
            fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
sletz's avatar
sletz committed
232

sletz's avatar
sletz committed
233
        try {
sletz's avatar
sletz committed
234

235
            //audio net buffers
sletz's avatar
sletz committed
236
            if (fParams.fSendAudioChannels > 0) {
sletz's avatar
sletz committed
237

238
                switch (fParams.fSampleEncoder) {
sletz's avatar
sletz committed
239

240
                    case JackFloatEncoder:
sletz's avatar
sletz committed
241
                        fNetAudioCaptureBuffer = new NetFloatAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
242
                        break;
sletz's avatar
sletz committed
243

244
                    case JackIntEncoder:
sletz's avatar
sletz committed
245
                        fNetAudioCaptureBuffer = new NetIntAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
246
                        break;
sletz's avatar
sletz committed
247

248
                    case JackCeltEncoder:
nedko's avatar
nedko committed
249
                    #if HAVE_CELT
sletz's avatar
sletz committed
250
                        fNetAudioCaptureBuffer = new NetCeltAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData, fParams.fKBps);
251
252
253
                    #endif
                        break;
                }
sletz's avatar
sletz committed
254

sletz's avatar
sletz committed
255
256
                assert(fNetAudioCaptureBuffer);
            }
sletz's avatar
sletz committed
257

sletz's avatar
sletz committed
258
            if (fParams.fReturnAudioChannels > 0) {
sletz's avatar
sletz committed
259

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

262
                    case JackFloatEncoder:
sletz's avatar
sletz committed
263
                        fNetAudioPlaybackBuffer = new NetFloatAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
264
                        break;
sletz's avatar
sletz committed
265

266
                    case JackIntEncoder:
sletz's avatar
sletz committed
267
                        fNetAudioPlaybackBuffer = new NetIntAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
268
                        break;
sletz's avatar
sletz committed
269

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

sletz's avatar
sletz committed
277
278
                assert(fNetAudioPlaybackBuffer);
            }
sletz's avatar
sletz committed
279

sletz's avatar
sletz committed
280
281
282
283
        } catch (exception&) {
            jack_error("NetAudioBuffer allocation error...");
            return false;
        }
moret's avatar
moret committed
284

sletz's avatar
sletz committed
285
        //set the new timeout for the socket
sletz's avatar
sletz committed
286
287
        if (SetRxTimeout() == SOCKET_ERROR) {
            jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
288
            goto error;
sletz's avatar
sletz committed
289
        }
moret's avatar
moret committed
290

sletz's avatar
sletz committed
291
        //set the new rx buffer size
sletz's avatar
sletz committed
292
293
        if (SetNetBufferSize() == SOCKET_ERROR) {
            jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
294
295
            goto error;
        }
sletz's avatar
sletz committed
296

sletz's avatar
sletz committed
297
        return true;
sletz's avatar
sletz committed
298

sletz's avatar
sletz committed
299
    error:
sletz's avatar
sletz committed
300
        FreeNetworkBuffers();
sletz's avatar
sletz committed
301
        return false;
moret's avatar
moret committed
302
303
    }

304
    void JackNetMasterInterface::Exit()
305
    {
sletz's avatar
sletz committed
306
        jack_log("JackNetMasterInterface::Exit, ID %u", fParams.fID);
307
308
309

        //stop process
        fRunning = false;
310

311
        //send a 'multicast euthanasia request' - new socket is required on macosx
sletz's avatar
sletz committed
312
313
314
        jack_info("Exiting '%s'", fParams.fName);
        SetPacketType(&fParams, KILL_MASTER);
        JackNetSocket mcast_socket(fMulticastIP, fSocket.GetPort());
315

316
        session_params_t net_params;
sletz's avatar
sletz committed
317
        memset(&net_params, 0, sizeof(session_params_t));
318
319
        SessionParamsHToN(&fParams, &net_params);

sletz's avatar
sletz committed
320
321
322
323
        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));
324

325
326
327
        mcast_socket.Close();
    }

sletz's avatar
sletz committed
328
329
330
331
332
333
334
335
336
337
    void JackNetMasterInterface::FatalError()
    {
        //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();
    }

sletz's avatar
sletz committed
338
    int JackNetMasterInterface::Recv(size_t size, int flags)
339
    {
340
        int rx_bytes;
sletz's avatar
sletz committed
341

sletz's avatar
sletz committed
342
        if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
343
344

            /*
345
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
346
            //no data isn't really a network error, so just return 0 available read bytes
sletz's avatar
sletz committed
347
            if (error == NET_NO_DATA) {
348
                return 0;
sletz's avatar
sletz committed
349
            } else if (error == NET_CONN_ERROR) {
sletz's avatar
sletz committed
350
                FatalError();
sletz's avatar
sletz committed
351
            } else {
sletz's avatar
sletz committed
352
                jack_error("Error in master receive : %s", StrError(NET_ERROR_CODE));
353
            }
354
355
            */

sletz's avatar
sletz committed
356
            FatalError();
357
        }
358

359
360
361
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
        return rx_bytes;
362
    }
363

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

sletz's avatar
sletz committed
370
        if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
sletz's avatar
sletz committed
371
            /*
372
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
373
            if (error == NET_CONN_ERROR) {
sletz's avatar
sletz committed
374
                FatalError();
sletz's avatar
sletz committed
375
376
            } else {
                jack_error("Error in master send : %s", StrError(NET_ERROR_CODE));
377
            }
sletz's avatar
sletz committed
378
379
            */
            FatalError();
380
        }
381
        return tx_bytes;
382
    }
383

384
385
    bool JackNetMasterInterface::IsSynched()
    {
386
        return (fCycleOffset <= fMaxCycleOffset);
387
    }
388

389
    int JackNetMasterInterface::SyncSend()
390
    {
391
392
393
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
394
        fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ? 1 : 0;
sletz's avatar
sletz committed
395
        fTxHeader.fPacketSize = fParams.fMtu;
sletz's avatar
sletz committed
396

397
398
399
400
        // Write active ports list
        if (fNetAudioPlaybackBuffer)
            fNetAudioPlaybackBuffer->ActivePortsToNetwork(fTxData, fTxHeader.fActivePorts);

sletz's avatar
sletz committed
401
        memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
402
        //PacketHeaderDisplay(&fTxHeader);
sletz's avatar
sletz committed
403
        return Send(fTxHeader.fPacketSize, 0);
404
405
406
407
408
    }

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

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

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

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

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

        return 0;
446
447
    }

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

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

458
        fCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
459

460
461
462
463
        // Read active ports list
        if (fNetAudioCaptureBuffer)
            fNetAudioCaptureBuffer->ActivePortsFromNetwork(fRxData, rx_head->fActivePorts);

464
465
466
467
468
        if (fCycleOffset < fMaxCycleOffset) {
            return 0;
        } else {
            rx_bytes = Recv(rx_head->fPacketSize, 0);
        }
469

moret's avatar
moret committed
470
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
471
472
        return rx_bytes;
    }
473

474
    int JackNetMasterInterface::DataRecv()
475
476
    {
        int rx_bytes = 0;
477
        uint recvd_midi_pckt = 0;
sletz's avatar
sletz committed
478
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
479

sletz's avatar
sletz committed
480
        while (!fRxHeader.fIsLastPckt)
481
        {
moret's avatar
moret committed
482
            //how much data is queued on the rx buffer ?
sletz's avatar
sletz committed
483
            rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
484

sletz's avatar
sletz committed
485
            //error here, problem with recv, just skip the cycle (return -1)
sletz's avatar
sletz committed
486
            if (rx_bytes == SOCKET_ERROR)
moret's avatar
moret committed
487
                return rx_bytes;
sletz's avatar
sletz committed
488

sletz's avatar
sletz committed
489
            if (rx_bytes && (rx_head->fDataStream == 'r') && (rx_head->fID == fParams.fID))
moret's avatar
moret committed
490
491
            {
                //read data
sletz's avatar
sletz committed
492
                switch (rx_head->fDataType)
493
                {
moret's avatar
moret committed
494
                    case 'm':   //midi
sletz's avatar
sletz committed
495
                        rx_bytes = Recv(rx_head->fPacketSize, 0);
moret's avatar
moret committed
496
                        fRxHeader.fCycle = rx_head->fCycle;
moret's avatar
moret committed
497
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
sletz's avatar
sletz committed
498
                        fNetMidiPlaybackBuffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
sletz's avatar
sletz committed
499
500
                        // Last midi packet is received, so finish rendering...
                        if (++recvd_midi_pckt == rx_head->fNumPacket)
moret's avatar
moret committed
501
502
                            fNetMidiPlaybackBuffer->RenderToJackPorts();
                        break;
503

moret's avatar
moret committed
504
                    case 'a':   //audio
sletz's avatar
sletz committed
505
                        rx_bytes = Recv(rx_head->fPacketSize, 0);
moret's avatar
moret committed
506
507
                        fRxHeader.fCycle = rx_head->fCycle;
                        fRxHeader.fSubCycle = rx_head->fSubCycle;
moret's avatar
moret committed
508
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
509
                        fRxHeader.fActivePorts = rx_head->fActivePorts;
sletz's avatar
sletz committed
510
                        rx_bytes = fNetAudioPlaybackBuffer->RenderFromNetwork(rx_head->fCycle, rx_head->fSubCycle, rx_bytes - HEADER_SIZE, fRxHeader.fActivePorts);
sletz's avatar
sletz committed
511
512
                        // Last audio packet is received, so finish rendering...
                        if (fRxHeader.fIsLastPckt)
sletz's avatar
sletz committed
513
                            fNetAudioPlaybackBuffer->RenderToJackPorts();
moret's avatar
moret committed
514
                        break;
515

moret's avatar
moret committed
516
                    case 's':   //sync
517
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
sletz's avatar
sletz committed
518
                        // TODO : finish midi and audio rendering ?
sletz's avatar
sletz committed
519
                        fNetAudioPlaybackBuffer->RenderToJackPorts();
sletz's avatar
sletz committed
520
                        return NET_PACKET_ERROR;
521
522
523
                }
            }
        }
sletz's avatar
sletz committed
524

525
        return rx_bytes;
526
    }
527

528
    void JackNetMasterInterface::EncodeSyncPacket()
529
530
531
    {
        //this method contains every step of sync packet informations coding
        //first of all, reset sync packet
sletz's avatar
sletz committed
532
        memset(fTxData, 0, PACKET_AVAILABLE_SIZE);
533
534

        //then, first step : transport
535
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
536
537
538
            // desactivated...
            //EncodeTransportData();
            TransportDataHToN(&fSendTransportData,  &fSendTransportData);
539
            //copy to TxBuffer
sletz's avatar
sletz committed
540
            memcpy(fTxData, &fSendTransportData, sizeof(net_transport_data_t));
541
542
543
544
545
        }
        //then others (freewheel etc.)
        //...
    }

546
    void JackNetMasterInterface::DecodeSyncPacket()
547
548
549
    {
        //this method contains every step of sync packet informations decoding process
        //first : transport
550
        if (fParams.fTransportSync) {
551
            //copy received transport data to transport data structure
sletz's avatar
sletz committed
552
553
554
555
            memcpy(&fReturnTransportData, fRxData, sizeof(net_transport_data_t));
            TransportDataNToH(&fReturnTransportData,  &fReturnTransportData);
            // desactivated...
            //DecodeTransportData();
556
557
558
559
        }
        //then others
        //...
    }
560

561
562
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
563
564
    uint JackNetSlaveInterface::fSlaveCounter = 0;

565
    bool JackNetSlaveInterface::Init()
566
    {
sletz's avatar
sletz committed
567
        jack_log("JackNetSlaveInterface::Init()");
568

569
        //set the parameters to send
sletz's avatar
sletz committed
570
        strcpy(fParams.fPacketType, "params");
571
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
sletz's avatar
sletz committed
572
        SetPacketType(&fParams, SLAVE_AVAILABLE);
573

574
575
        //init loop : get a master and start, do it until connection is ok
        net_status_t status;
576
        do {
577
            //first, get a master, do it until a valid connection is running
578
            do {
579
                status = SendAvailableToMaster();
sletz's avatar
sletz committed
580
                if (status == NET_SOCKET_ERROR)
581
                    return false;
582
            }
sletz's avatar
sletz committed
583
            while (status != NET_CONNECTED);
584

585
            //then tell the master we are ready
sletz's avatar
sletz committed
586
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
moret's avatar
moret committed
587
            status = SendStartToMaster();
sletz's avatar
sletz committed
588
            if (status == NET_ERROR)
589
                return false;
590
        }
sletz's avatar
sletz committed
591
        while (status != NET_ROLLING);
592

593
594
        return true;
    }
595

596
    // Separate the connection protocol into two separated step
sletz's avatar
sletz committed
597
    bool JackNetSlaveInterface::InitConnection(int time_out)
598
    {
sletz's avatar
sletz committed
599
        jack_log("JackNetSlaveInterface::InitConnection()");
sletz's avatar
sletz committed
600
        unsigned int try_count = (time_out > 0) ? ((1000000 * time_out) / SLAVE_INIT_TIMEOUT) : LONG_MAX;
601
602

        //set the parameters to send
sletz's avatar
sletz committed
603
        strcpy(fParams.fPacketType, "params");
604
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
sletz's avatar
sletz committed
605
        SetPacketType(&fParams, SLAVE_AVAILABLE);
606
607

        net_status_t status;
608
        do {
609
            //get a master
sletz's avatar
sletz committed
610
            status = SendAvailableToMaster(try_count);
611
612
613
            if (status == NET_SOCKET_ERROR)
                return false;
        }
sletz's avatar
sletz committed
614
        while (status != NET_CONNECTED && --try_count > 0);
615

sletz's avatar
sletz committed
616
        return (try_count != 0);
617
    }
618

619
620
621
622
623
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

        net_status_t status;
624
        do {
625
626
627
628
629
630
            //then tell the master we are ready
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
            status = SendStartToMaster();
            if (status == NET_ERROR)
                return false;
        }
631
632
        while (status != NET_ROLLING);

633
634
        return true;
    }
635

sletz's avatar
sletz committed
636
    net_status_t JackNetSlaveInterface::SendAvailableToMaster(long try_count)
637
    {
sletz's avatar
sletz committed
638
        jack_log("JackNetSlaveInterface::SendAvailableToMaster()");
639
        //utility
640
        session_params_t host_params;
641
642
643
        int rx_bytes = 0;

        //socket
sletz's avatar
sletz committed
644
645
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Fatal error : network unreachable - %s", StrError(NET_ERROR_CODE));
646
            return NET_SOCKET_ERROR;
647
648
        }

649
        //bind the socket
sletz's avatar
sletz committed
650
651
        if (fSocket.Bind() == SOCKET_ERROR) {
            jack_error("Can't bind the socket : %s", StrError(NET_ERROR_CODE));
652
653
            return NET_SOCKET_ERROR;
        }
654
655

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

659
        //disable local loop
sletz's avatar
sletz committed
660
661
        if (fSocket.SetLocalLoop() == SOCKET_ERROR)
            jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
662

663
        //send 'AVAILABLE' until 'SLAVE_SETUP' received
sletz's avatar
sletz committed
664
        jack_info("Waiting for a master...");
665
        do {
666
            //send 'available'
667
            session_params_t net_params;
sletz's avatar
sletz committed
668
            memset(&net_params, 0, sizeof(session_params_t));
669
            SessionParamsHToN(&fParams, &net_params);
sletz's avatar
sletz committed
670
671
            if (fSocket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR)
                jack_error("Error in data send : %s", StrError(NET_ERROR_CODE));
672

673
            //filter incoming packets : don't exit while no error is detected
sletz's avatar
sletz committed
674
675
            memset(&net_params, 0, sizeof(session_params_t));
            rx_bytes = fSocket.CatchHost(&net_params, sizeof(session_params_t), 0);
676
            SessionParamsNToH(&net_params, &host_params);
677
            if ((rx_bytes == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
sletz's avatar
sletz committed
678
                jack_error("Can't receive : %s", StrError(NET_ERROR_CODE));
679
                return NET_RECV_ERROR;
680
681
            }
        }
sletz's avatar
sletz committed
682
        while (strcmp(host_params.fPacketType, fParams.fPacketType)  && (GetPacketType(&host_params) != SLAVE_SETUP)  && (--try_count > 0));
sletz's avatar
sletz committed
683

sletz's avatar
sletz committed
684
        // Time out failure..
sletz's avatar
sletz committed
685
686
        if (try_count == 0) {
            jack_error("Time out error in connect");
sletz's avatar
sletz committed
687
688
            return NET_CONNECT_ERROR;
        }
689

moret's avatar
moret committed
690
        //everything is OK, copy parameters
691
        fParams = host_params;
moret's avatar
moret committed
692

693
        //connect the socket
sletz's avatar
sletz committed
694
695
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Error in connect : %s", StrError(NET_ERROR_CODE));
696
            return NET_CONNECT_ERROR;
697
        }
moret's avatar
moret committed
698
        return NET_CONNECTED;
699
700
    }

moret's avatar
moret committed
701
    net_status_t JackNetSlaveInterface::SendStartToMaster()
702
    {
sletz's avatar
sletz committed
703
        jack_log("JackNetSlaveInterface::SendStartToMaster");
moret's avatar
moret committed
704

705
        //tell the master to start
706
        session_params_t net_params;
sletz's avatar
sletz committed
707
708
        memset(&net_params, 0, sizeof(session_params_t));
        SetPacketType(&fParams, START_MASTER);
709
        SessionParamsHToN(&fParams, &net_params);
710
        if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
711
712
            jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
            return (fSocket.GetError() == NET_CONN_ERROR) ? NET_ERROR : NET_SEND_ERROR;
713
        }
714
        return NET_ROLLING;
715
716
    }

sletz's avatar
sletz committed
717
    bool JackNetSlaveInterface::SetParams()
moret's avatar
moret committed
718
    {
sletz's avatar
sletz committed
719
720
        jack_log("JackNetSlaveInterface::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
721
722
723

        JackNetInterface::SetParams();

724
725
        fTxHeader.fDataStream = 'r';
        fRxHeader.fDataStream = 's';
moret's avatar
moret committed
726

sletz's avatar
sletz committed
727
       //midi net buffers
sletz's avatar
sletz committed
728
        if (fParams.fSendMidiChannels > 0)
sletz's avatar
sletz committed
729
            fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fRxData);
sletz's avatar
sletz committed
730

sletz's avatar
sletz committed
731
        if (fParams.fReturnMidiChannels > 0)
sletz's avatar
sletz committed