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

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"
sletz's avatar
sletz committed
21
22
#include "JackError.h"

23
#include <assert.h>
24
25
26

using namespace std;

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

33
34
35
36
namespace Jack
{
    // JackNetInterface*******************************************

37
38
    JackNetInterface::JackNetInterface() : fSocket()
    {
sletz's avatar
sletz committed
39
        Initialize();
40
41
    }

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

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

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

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

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

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

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

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

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

sletz's avatar
sletz committed
111
        // tx buffer
112
        if (fSocket.SetOption(SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR) {
113
            return SOCKET_ERROR;
114
        }
moret's avatar
moret committed
115

sletz's avatar
sletz committed
116
        // rx buffer
117
        if (fSocket.SetOption(SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR) {
118
            return SOCKET_ERROR;
119
        }
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
    {
sletz's avatar
sletz committed
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

sletz's avatar
sletz committed
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

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

sletz's avatar
sletz 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
    }

sletz's avatar
sletz committed
153
154
155
156
157
158
    int JackNetInterface::MidiSend(NetMidiBuffer* buffer, int midi_channnels, int audio_channels)
    {
        if (midi_channnels > 0) {
            // set global header fields and get the number of midi packets
            fTxHeader.fDataType = 'm';
            uint data_size = buffer->RenderFromJackPorts();
159
            fTxHeader.fNumPacket = buffer->GetNumPackets(data_size, PACKET_AVAILABLE_SIZE(&fParams));
sletz's avatar
sletz committed
160
161
162
163
164
165

            for (uint subproc = 0; subproc < fTxHeader.fNumPacket; subproc++) {
                fTxHeader.fSubCycle = subproc;
                fTxHeader.fIsLastPckt = ((subproc == (fTxHeader.fNumPacket - 1)) && audio_channels == 0) ? 1 : 0;
                fTxHeader.fPacketSize = HEADER_SIZE + buffer->RenderToNetwork(subproc, data_size);
                memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
166
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
167
                    return SOCKET_ERROR;
168
                }
sletz's avatar
sletz committed
169
170
171
172
173
174
175
176
177
178
            }
        }
        return 0;
    }

    int JackNetInterface::AudioSend(NetAudioBuffer* buffer, int audio_channels)
    {
        // audio
        if (audio_channels > 0) {
            fTxHeader.fDataType = 'a';
sletz's avatar
sletz committed
179
180
            fTxHeader.fActivePorts = buffer->RenderFromJackPorts();
            fTxHeader.fNumPacket = buffer->GetNumPackets(fTxHeader.fActivePorts);
sletz's avatar
sletz committed
181
182
183
184
185
186
187

            for (uint subproc = 0; subproc < fTxHeader.fNumPacket; subproc++) {
                fTxHeader.fSubCycle = subproc;
                fTxHeader.fIsLastPckt = (subproc == (fTxHeader.fNumPacket - 1)) ? 1 : 0;
                fTxHeader.fPacketSize = HEADER_SIZE + buffer->RenderToNetwork(subproc, fTxHeader.fActivePorts);
                memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
                // PacketHeaderDisplay(&fTxHeader);
188
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
189
                    return SOCKET_ERROR;
190
                }
sletz's avatar
sletz committed
191
192
193
194
195
196
197
198
199
200
201
202
            }
        }
        return 0;
    }

    int JackNetInterface::MidiRecv(packet_header_t* rx_head, NetMidiBuffer* buffer, uint& recvd_midi_pckt)
    {
        int rx_bytes = Recv(rx_head->fPacketSize, 0);
        fRxHeader.fCycle = rx_head->fCycle;
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
        buffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
        // Last midi packet is received, so finish rendering...
203
        if (++recvd_midi_pckt == rx_head->fNumPacket) {
sletz's avatar
sletz committed
204
            buffer->RenderToJackPorts();
205
        }
sletz's avatar
sletz committed
206
207
208
209
210
211
212
213
214
215
        return rx_bytes;
    }

    int JackNetInterface::AudioRecv(packet_header_t* rx_head, NetAudioBuffer* buffer)
    {
        int rx_bytes = Recv(rx_head->fPacketSize, 0);
        fRxHeader.fCycle = rx_head->fCycle;
        fRxHeader.fSubCycle = rx_head->fSubCycle;
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
        fRxHeader.fActivePorts = rx_head->fActivePorts;
sletz's avatar
sletz committed
216
        rx_bytes = buffer->RenderFromNetwork(rx_head->fCycle, rx_head->fSubCycle, fRxHeader.fActivePorts);
sletz's avatar
sletz committed
217
        // Last audio packet is received, so finish rendering...
218
        if (fRxHeader.fIsLastPckt) {
sletz's avatar
sletz committed
219
            buffer->RenderToJackPorts();
220
        }
sletz's avatar
sletz committed
221
222
223
224
225
226
227
228
229
230
        return rx_bytes;
    }

    int JackNetInterface::FinishRecv(NetAudioBuffer* buffer)
    {
        // TODO : finish midi and audio rendering ?
        buffer->RenderToJackPorts();
        return NET_PACKET_ERROR;
    }

231
232
233
234
235
236
237
238
239
240
241
    NetAudioBuffer* JackNetInterface::AudioBufferFactory(int nports, char* buffer)
    {
         switch (fParams.fSampleEncoder) {

            case JackFloatEncoder:
                return new NetFloatAudioBuffer(&fParams, nports, buffer);

            case JackIntEncoder:
                return new NetIntAudioBuffer(&fParams, nports, buffer);

            #if HAVE_CELT
sletz's avatar
sletz committed
242
            case JackCeltEncoder:
243
244
245
246
247
                return new NetCeltAudioBuffer(&fParams, nports, buffer, fParams.fKBps);
            #endif
        }
        return NULL;
    }
248
249
250
251
252
253
254
255
256
257
258
    
    void JackNetInterface::SetRcvTimeOut()
    {
        if (!fSetTimeOut) {
            if (fSocket.SetTimeOut(PACKET_TIMEOUT) == SOCKET_ERROR) {
                jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
                return;
            }
            fSetTimeOut = true;
        }
    }
259

260
    // JackNetMasterInterface ************************************************************************************
261

262
    bool JackNetMasterInterface::Init()
263
    {
sletz's avatar
sletz committed
264
        jack_log("JackNetMasterInterface::Init, ID %u", fParams.fID);
265

266
        session_params_t host_params;
267
        uint attempt = 0;
268
269
        int rx_bytes = 0;

sletz's avatar
sletz committed
270
        // socket
sletz's avatar
sletz committed
271
272
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
273
            return false;
274
275
        }

sletz's avatar
sletz committed
276
        // timeout on receive (for init)
277
278
279
        if (fSocket.SetTimeOut(MASTER_INIT_TIMEOUT) < 0) {
            jack_error("Can't set init timeout : %s", StrError(NET_ERROR_CODE));
        }
280

sletz's avatar
sletz committed
281
        // connect
sletz's avatar
sletz committed
282
283
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Can't connect : %s", StrError(NET_ERROR_CODE));
284
285
            return false;
        }
286

sletz's avatar
sletz committed
287
        // send 'SLAVE_SETUP' until 'START_MASTER' received
sletz's avatar
sletz committed
288
        jack_info("Sending parameters to %s...", fParams.fSlaveNetName);
289
290
        do
        {
291
            session_params_t net_params;
sletz's avatar
sletz committed
292
293
            memset(&net_params, 0, sizeof(session_params_t));
            SetPacketType(&fParams, SLAVE_SETUP);
294
            SessionParamsHToN(&fParams, &net_params);
295

296
            if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
297
                jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
298
            }
299

sletz's avatar
sletz committed
300
            memset(&net_params, 0, sizeof(session_params_t));
301
            if (((rx_bytes = fSocket.Recv(&net_params, sizeof(session_params_t), 0)) == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
sletz's avatar
sletz committed
302
                jack_error("Problem with network");
303
                return false;
304
            }
305

306
            SessionParamsNToH(&net_params, &host_params);
307
        }
sletz's avatar
sletz committed
308
        while ((GetPacketType(&host_params) != START_MASTER) && (++attempt < SLAVE_SETUP_RETRY));
sletz's avatar
sletz committed
309
        
sletz's avatar
sletz committed
310
311
        if (attempt == SLAVE_SETUP_RETRY) {
            jack_error("Slave doesn't respond, exiting");
312
            return false;
313
314
        }

315
        return true;
316
317
    }

sletz's avatar
sletz committed
318
    bool JackNetMasterInterface::SetParams()
moret's avatar
moret committed
319
    {
sletz's avatar
sletz committed
320
        jack_log("JackNetMasterInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
321
322
            fParams.fSendAudioChannels, fParams.fReturnAudioChannels,
            fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
moret's avatar
moret committed
323
324
325

        JackNetInterface::SetParams();

326
327
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
328

sletz's avatar
sletz committed
329
330
331
        fMaxCycleOffset = fParams.fNetworkLatency;

        // midi net buffers
332
        if (fParams.fSendMidiChannels > 0) {
sletz's avatar
sletz committed
333
            fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fTxData);
334
        }
sletz's avatar
sletz committed
335

336
        if (fParams.fReturnMidiChannels > 0) {
sletz's avatar
sletz committed
337
            fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
338
        }
sletz's avatar
sletz committed
339

sletz's avatar
sletz committed
340
        try {
sletz's avatar
sletz committed
341

sletz's avatar
sletz committed
342
            // audio net buffers
sletz's avatar
sletz committed
343
            if (fParams.fSendAudioChannels > 0) {
344
                fNetAudioCaptureBuffer = AudioBufferFactory(fParams.fSendAudioChannels, fTxData);
sletz's avatar
sletz committed
345
346
                assert(fNetAudioCaptureBuffer);
            }
sletz's avatar
sletz committed
347

sletz's avatar
sletz committed
348
            if (fParams.fReturnAudioChannels > 0) {
349
                fNetAudioPlaybackBuffer = AudioBufferFactory(fParams.fReturnAudioChannels, fRxData);
sletz's avatar
sletz committed
350
351
                assert(fNetAudioPlaybackBuffer);
            }
sletz's avatar
sletz committed
352

sletz's avatar
sletz committed
353
354
355
356
        } catch (exception&) {
            jack_error("NetAudioBuffer allocation error...");
            return false;
        }
moret's avatar
moret committed
357

sletz's avatar
sletz committed
358
        // set the new rx buffer size
sletz's avatar
sletz committed
359
360
        if (SetNetBufferSize() == SOCKET_ERROR) {
            jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
361
362
            goto error;
        }
sletz's avatar
sletz committed
363

sletz's avatar
sletz committed
364
        return true;
sletz's avatar
sletz committed
365

sletz's avatar
sletz committed
366
    error:
sletz's avatar
sletz committed
367
        FreeNetworkBuffers();
sletz's avatar
sletz committed
368
        return false;
moret's avatar
moret committed
369
370
    }

371
    void JackNetMasterInterface::Exit()
372
    {
sletz's avatar
sletz committed
373
        jack_log("JackNetMasterInterface::Exit, ID %u", fParams.fID);
374

sletz's avatar
sletz committed
375
        // stop process
376
        fRunning = false;
377

sletz's avatar
sletz committed
378
        // send a 'multicast euthanasia request' - new socket is required on macosx
sletz's avatar
sletz committed
379
380
381
        jack_info("Exiting '%s'", fParams.fName);
        SetPacketType(&fParams, KILL_MASTER);
        JackNetSocket mcast_socket(fMulticastIP, fSocket.GetPort());
382

383
        session_params_t net_params;
sletz's avatar
sletz committed
384
        memset(&net_params, 0, sizeof(session_params_t));
385
386
        SessionParamsHToN(&fParams, &net_params);

387
        if (mcast_socket.NewSocket() == SOCKET_ERROR) {
sletz's avatar
sletz committed
388
            jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
389
390
        }
        if (mcast_socket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR) {
sletz's avatar
sletz committed
391
            jack_error("Can't send suicide request : %s", StrError(NET_ERROR_CODE));
392
        }
393

394
395
396
        mcast_socket.Close();
    }

397
    void JackNetMasterInterface::FatalRecvError()
sletz's avatar
sletz committed
398
    {
sletz's avatar
sletz committed
399
        // fatal connection issue, exit
400
401
402
403
404
405
406
407
408
409
410
        jack_error("Recv connection lost error = %s, '%s' exiting", StrError(NET_ERROR_CODE), fParams.fName);
        // 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();
    }

     void JackNetMasterInterface::FatalSendError()
    {
        // fatal connection issue, exit
        jack_error("Send connection lost error = %s, '%s' exiting", StrError(NET_ERROR_CODE), fParams.fName);
sletz's avatar
sletz committed
411
        // ask to the manager to properly remove the master
sletz's avatar
sletz committed
412
413
414
415
416
        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
417
    int JackNetMasterInterface::Recv(size_t size, int flags)
418
    {
419
        int rx_bytes;
sletz's avatar
sletz committed
420

sletz's avatar
sletz committed
421
        if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
422
            FatalRecvError();
423
        }
424

425
426
427
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
        return rx_bytes;
428
    }
429

sletz's avatar
sletz committed
430
    int JackNetMasterInterface::Send(size_t size, int flags)
431
    {
432
433
434
        int tx_bytes;
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
        PacketHeaderHToN(header, header);
435

sletz's avatar
sletz committed
436
        if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
437
            FatalSendError();
438
        }
439
        return tx_bytes;
440
    }
441

442
443
    bool JackNetMasterInterface::IsSynched()
    {
sletz's avatar
sletz committed
444
        return (fCurrentCycleOffset <= fMaxCycleOffset);
445
    }
446

447
    int JackNetMasterInterface::SyncSend()
448
    {
449
450
        SetRcvTimeOut();
        
451
452
453
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
454
        fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ? 1 : 0;
sletz's avatar
sletz committed
455
        fTxHeader.fPacketSize = fParams.fMtu;
sletz's avatar
sletz committed
456

sletz's avatar
sletz committed
457
        memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
sletz's avatar
sletz committed
458
        // PacketHeaderDisplay(&fTxHeader);
sletz's avatar
sletz committed
459
        return Send(fTxHeader.fPacketSize, 0);
460
461
462
463
    }

    int JackNetMasterInterface::DataSend()
    {
464
        if (MidiSend(fNetMidiCaptureBuffer, fParams.fSendMidiChannels, fParams.fSendAudioChannels) == SOCKET_ERROR) {
sletz's avatar
sletz committed
465
            return SOCKET_ERROR;
466
        }
sletz's avatar
sletz committed
467
        return AudioSend(fNetAudioCaptureBuffer, fParams.fSendAudioChannels);
468
469
    }

470
    int JackNetMasterInterface::SyncRecv()
471
    {
sletz's avatar
sletz committed
472
        int rx_bytes = 0;
sletz's avatar
sletz committed
473
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
sletz's avatar
sletz committed
474
475
476
477
478
479
480
481
482
483
484

        // receive sync (launch the cycle)
        do {
            rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
            // connection issue, send will detect it, so don't skip the cycle (return 0)
            if (rx_bytes == SOCKET_ERROR) {
                return SOCKET_ERROR;
            }
        }
        while ((strcmp(rx_head->fPacketType, "header") != 0) && (rx_head->fDataType != 's'));

sletz's avatar
sletz committed
485
        fCurrentCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
486

sletz's avatar
sletz committed
487
488
        if (fCurrentCycleOffset < fMaxCycleOffset) {
            jack_info("Synching with latency = %d", fCurrentCycleOffset);
489
490
491
            return 0;
        } else {
            rx_bytes = Recv(rx_head->fPacketSize, 0);
492
493
            fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
            return rx_bytes;
494
        }
495
    }
496

497
    int JackNetMasterInterface::DataRecv()
498
499
    {
        int rx_bytes = 0;
500
        uint recvd_midi_pckt = 0;
sletz's avatar
sletz committed
501
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
502

sletz's avatar
sletz committed
503
504
        while (!fRxHeader.fIsLastPckt) {
            // how much data is queued on the rx buffer ?
sletz's avatar
sletz committed
505
            rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
506

sletz's avatar
sletz committed
507
            // error here, problem with recv, just skip the cycle (return -1)
508
            if (rx_bytes == SOCKET_ERROR) {
moret's avatar
moret committed
509
                return rx_bytes;
510
            }
sletz's avatar
sletz committed
511

sletz's avatar
sletz committed
512
513
514
515
516
517
            if (rx_bytes && (rx_head->fDataStream == 'r') && (rx_head->fID == fParams.fID)) {
                // read data
                switch (rx_head->fDataType) {

                    case 'm':   // midi
                        rx_bytes = MidiRecv(rx_head, fNetMidiPlaybackBuffer, recvd_midi_pckt);
moret's avatar
moret committed
518
                        break;
519

sletz's avatar
sletz committed
520
521
                    case 'a':   // audio
                        rx_bytes = AudioRecv(rx_head, fNetAudioPlaybackBuffer);
moret's avatar
moret committed
522
                        break;
523

sletz's avatar
sletz committed
524
                    case 's':   // sync
525
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
sletz's avatar
sletz committed
526
                        return FinishRecv(fNetAudioPlaybackBuffer);
527
528
529
                }
            }
        }
sletz's avatar
sletz committed
530

531
        return rx_bytes;
532
    }
533

534
    void JackNetMasterInterface::EncodeSyncPacket()
535
    {
sletz's avatar
sletz committed
536
        // This method contains every step of sync packet informations coding
sletz's avatar
sletz committed
537
        // first of all, clear sync packet
538
        memset(fTxData, 0, PACKET_AVAILABLE_SIZE(&fParams));
539

sletz's avatar
sletz committed
540
        // then, first step : transport
541
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
542
            EncodeTransportData();
sletz's avatar
sletz committed
543
            TransportDataHToN(&fSendTransportData, &fSendTransportData);
sletz's avatar
sletz committed
544
            // copy to TxBuffer
sletz's avatar
sletz committed
545
            memcpy(fTxData, &fSendTransportData, sizeof(net_transport_data_t));
546
        }
sletz's avatar
sletz committed
547
548
        // then others (freewheel etc.)
        // ...
sletz's avatar
sletz committed
549
550
551
552

        // Transport not used for now...

        // Write active ports list
sletz's avatar
sletz committed
553
        fTxHeader.fActivePorts = (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->ActivePortsToNetwork(fTxData) : 0;
554
555
    }

556
    void JackNetMasterInterface::DecodeSyncPacket()
557
    {
sletz's avatar
sletz committed
558
559
        // This method contains every step of sync packet informations decoding process
        // first : transport
560
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
561
            // copy received transport data to transport data structure
sletz's avatar
sletz committed
562
563
            memcpy(&fReturnTransportData, fRxData, sizeof(net_transport_data_t));
            TransportDataNToH(&fReturnTransportData,  &fReturnTransportData);
sletz's avatar
sletz committed
564
            DecodeTransportData();
565
        }
sletz's avatar
sletz committed
566
567
        // then others
        // ...
sletz's avatar
sletz committed
568
569
570
571
572
573
574
575

        // Transport not used for now...
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);

        // Read active ports list
        if (fNetAudioCaptureBuffer) {
            fNetAudioCaptureBuffer->ActivePortsFromNetwork(fRxData, rx_head->fActivePorts);
        }
576
    }
577

578
579
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
580
581
    uint JackNetSlaveInterface::fSlaveCounter = 0;

sletz's avatar
sletz committed
582
583
584
585
586
587
588
589
590
591
592
    void JackNetSlaveInterface::InitAPI()
    {
        // open Socket API with the first slave
        if (fSlaveCounter++ == 0) {
            if (SocketAPIInit() < 0) {
                jack_error("Can't init Socket API, exiting...");
                throw std::bad_alloc();
            }
        }
    }

593
    bool JackNetSlaveInterface::Init()
594
    {
sletz's avatar
sletz committed
595
        jack_log("JackNetSlaveInterface::Init()");
596

sletz's avatar
sletz committed
597
        // set the parameters to send
sletz's avatar
sletz committed
598
        strcpy(fParams.fPacketType, "params");
599
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
sletz's avatar
sletz committed
600
        SetPacketType(&fParams, SLAVE_AVAILABLE);
601

sletz's avatar
sletz committed
602
        // init loop : get a master and start, do it until connection is ok
603
        net_status_t status;
604
        do {
sletz's avatar
sletz committed
605
            // first, get a master, do it until a valid connection is running
606
            do {
607
                status = SendAvailableToMaster();
608
                if (status == NET_SOCKET_ERROR) {
609
                    return false;
610
                }
611
            }
sletz's avatar
sletz committed
612
            while (status != NET_CONNECTED);
613

sletz's avatar
sletz committed
614
            // then tell the master we are ready
sletz's avatar
sletz committed
615
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
moret's avatar
moret committed
616
            status = SendStartToMaster();
617
            if (status == NET_ERROR) {
618
                return false;
619
            }
620
        }
sletz's avatar
sletz committed
621
        while (status != NET_ROLLING);
622

623
624
        return true;
    }
625

626
    // Separate the connection protocol into two separated step
sletz's avatar
sletz committed
627
    bool JackNetSlaveInterface::InitConnection(int time_out_sec)
628
    {
sletz's avatar
sletz committed
629
        jack_log("JackNetSlaveInterface::InitConnection()");
sletz's avatar
sletz committed
630
        uint try_count = (time_out_sec > 0) ? ((1000000 * time_out_sec) / SLAVE_INIT_TIMEOUT) : LONG_MAX;
631

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

        net_status_t status;
638
        do {
sletz's avatar
sletz committed
639
            // get a master
sletz's avatar
sletz committed
640
            status = SendAvailableToMaster(try_count);
641
            if (status == NET_SOCKET_ERROR) {
642
                return false;
643
            }
644
        }
sletz's avatar
sletz committed
645
        while (status != NET_CONNECTED && --try_count > 0);
646

sletz's avatar
sletz committed
647
        return (try_count != 0);
648
    }
649

650
651
652
653
654
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

        net_status_t status;
655
        do {
sletz's avatar
sletz committed
656
            // then tell the master we are ready
657
658
659
660
661
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
            status = SendStartToMaster();
            if (status == NET_ERROR)
                return false;
        }
662
663
        while (status != NET_ROLLING);

664
665
        return true;
    }
666

sletz's avatar
sletz committed
667
    net_status_t JackNetSlaveInterface::SendAvailableToMaster(long try_count)
668
    {
sletz's avatar
sletz committed
669
        jack_log("JackNetSlaveInterface::SendAvailableToMaster()");
sletz's avatar
sletz committed
670
        // utility
671
        session_params_t host_params;
672
673
        int rx_bytes = 0;

sletz's avatar
sletz committed
674
        // socket
sletz's avatar
sletz committed
675
676
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Fatal error : network unreachable - %s", StrError(NET_ERROR_CODE));
677
            return NET_SOCKET_ERROR;
678
679
        }

sletz's avatar
sletz committed
680
681
682
683
684
685
686
687
        if (fSocket.IsLocal(fMulticastIP)) {
            jack_info("Local IP is used...");
        } else {
            // bind the socket
            if (fSocket.Bind() == SOCKET_ERROR) {
                jack_error("Can't bind the socket : %s", StrError(NET_ERROR_CODE));
                return NET_SOCKET_ERROR;
            }
688
        }
689

690
691
692
693
        // timeout on receive (for init)
        if (fSocket.SetTimeOut(SLAVE_INIT_TIMEOUT) == SOCKET_ERROR) {
            jack_error("Can't set init timeout : %s", StrError(NET_ERROR_CODE));
        }
694

sletz's avatar
sletz committed
695
        // disable local loop
696
        if (fSocket.SetLocalLoop() == SOCKET_ERROR) {
sletz's avatar
sletz committed
697
            jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
698
        }
699

sletz's avatar
sletz committed
700
        // send 'AVAILABLE' until 'SLAVE_SETUP' received
sletz's avatar
sletz committed
701
        jack_info("Waiting for a master...");
702
        do {
sletz's avatar
sletz committed
703
            // send 'available'
704
            session_params_t net_params;
sletz's avatar
sletz committed
705
            memset(&net_params, 0, sizeof(session_params_t));
706
            SessionParamsHToN(&fParams, &net_params);
sletz's avatar
sletz committed
707
708
            if (fSocket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR)
                jack_error("Error in data send : %s", StrError(NET_ERROR_CODE));
709

sletz's avatar
sletz committed
710
            // filter incoming packets : don't exit while no error is detected
sletz's avatar
sletz committed
711
712
            memset(&net_params, 0, sizeof(session_params_t));
            rx_bytes = fSocket.CatchHost(&net_params, sizeof(session_params_t), 0);
713
            SessionParamsNToH(&net_params, &host_params);
714
            if ((rx_bytes == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
sletz's avatar
sletz committed
715
                jack_error("Can't receive : %s", StrError(NET_ERROR_CODE));
716
                return NET_RECV_ERROR;
717
718
            }
        }
sletz's avatar
sletz committed
719
        while (strcmp(host_params.fPacketType, fParams.fPacketType)  && (GetPacketType(&host_params) != SLAVE_SETUP)  && (--try_count > 0));
sletz's avatar
sletz committed
720

sletz's avatar
sletz committed
721
        // Time out failure..
sletz's avatar
sletz committed
722
723
        if (try_count == 0) {
            jack_error("Time out error in connect");
sletz's avatar
sletz committed
724
725
            return NET_CONNECT_ERROR;
        }
726

sletz's avatar
sletz committed
727
        // everything is OK, copy parameters
728
        fParams = host_params;
moret's avatar
moret committed
729

sletz's avatar
sletz committed
730
        // connect the socket
sletz's avatar
sletz committed
731
732
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Error in connect : %s", StrError(NET_ERROR_CODE));
733
            return NET_CONNECT_ERROR;
734
        }
moret's avatar
moret committed
735
        return NET_CONNECTED;
736
737
    }

moret's avatar
moret committed
738
    net_status_t JackNetSlaveInterface::SendStartToMaster()
739
    {
sletz's avatar
sletz committed
740
        jack_log("JackNetSlaveInterface::SendStartToMaster");
moret's avatar
moret committed
741

sletz's avatar
sletz committed
742
        // tell the master to start
743
        session_params_t net_params;
sletz's avatar
sletz committed
744
745
        memset(&net_params, 0, sizeof(session_params_t));
        SetPacketType(&fParams, START_MASTER);
746
        SessionParamsHToN(&fParams, &net_params);
747
        if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
748
749
            jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
            return (fSocket.GetError() == NET_CONN_ERROR) ? NET_ERROR : NET_SEND_ERROR;
750
        }
751
        return NET_ROLLING;
752
753
    }

sletz's avatar
sletz committed
754
    bool JackNetSlaveInterface::SetParams()
moret's avatar
moret committed
755
    {
sletz's avatar
sletz committed
756
        jack_log("JackNetSlaveInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
sletz's avatar
sletz committed
757
758
                fParams.fSendAudioChannels, fParams.fReturnAudioChannels,
                fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
moret's avatar
moret committed
759
760
761

        JackNetInterface::SetParams();

762
763
        fTxHeader.fDataStream = 'r';
        fRxHeader.fDataStream = 's';
moret's avatar
moret committed
764

sletz's avatar
sletz committed
765
        // midi net buffers
766
        if (fParams.fSendMidiChannels > 0) {
sletz's avatar
sletz committed
767
            fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fRxData);
768
        }
sletz's avatar
sletz committed
769

770
        if (fParams.fReturnMidiChannels > 0) {
sletz's avatar
sletz committed
771
            fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fTxData);
772
        }
sletz's avatar
sletz committed
773
774

        try {
sletz's avatar
sletz committed
775

sletz's avatar
sletz committed
776
            // audio net buffers
sletz's avatar
sletz committed
777
            if (fParams.fSendAudioChannels > 0) {
778
                fNetAudioCaptureBuffer = AudioBufferFactory(fParams.fSendAudioChannels, fRxData);
sletz's avatar
sletz committed
779
780
                assert(fNetAudioCaptureBuffer);
            }
sletz's avatar
sletz committed
781

sletz's avatar
sletz committed
782
            if (fParams.fReturnAudioChannels > 0) {
783
                fNetAudioPlaybackBuffer = AudioBufferFactory(fParams.fReturnAudioChannels, fTxData);