JackNetInterface.cpp 34.4 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
24
25
26
#if HAVE_OPUS
#include "JackNetOpus.h"
#endif

27
#include <assert.h>
28
29
30

using namespace std;

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

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

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

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

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

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

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

85
86
    JackNetInterface::~JackNetInterface()
    {
sletz's avatar
sletz committed
87
        jack_log("JackNetInterface::~JackNetInterface");
moret's avatar
moret committed
88

89
90
91
92
93
94
95
96
97
        fSocket.Close();
        delete[] fTxBuffer;
        delete[] fRxBuffer;
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
    }

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

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

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

sletz's avatar
sletz committed
116
        // tx buffer
117
        if (fSocket.SetOption(SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR) {
118
            return SOCKET_ERROR;
119
        }
moret's avatar
moret committed
120

sletz's avatar
sletz committed
121
        // rx buffer
122
        if (fSocket.SetOption(SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR) {
123
            return SOCKET_ERROR;
124
        }
moret's avatar
moret committed
125

126
        return 0;
moret's avatar
moret committed
127
128
    }

sletz's avatar
sletz committed
129
    bool JackNetInterface::SetParams()
moret's avatar
moret committed
130
    {
sletz's avatar
sletz committed
131
        // TX header init
Stephane Letz's avatar
Stephane Letz committed
132
        memset(&fTxHeader, 0, sizeof(fTxHeader));
sletz's avatar
sletz committed
133
        strcpy(fTxHeader.fPacketType, "header");
134
135
136
        fTxHeader.fID = fParams.fID;
        fTxHeader.fCycle = 0;
        fTxHeader.fSubCycle = 0;
moret's avatar
moret committed
137
        fTxHeader.fIsLastPckt = 0;
138

sletz's avatar
sletz committed
139
        // RX header init
Stephane Letz's avatar
Stephane Letz committed
140
        memset(&fRxHeader, 0, sizeof(fTxHeader));
sletz's avatar
sletz committed
141
        strcpy(fRxHeader.fPacketType, "header");
142
143
144
        fRxHeader.fID = fParams.fID;
        fRxHeader.fCycle = 0;
        fRxHeader.fSubCycle = 0;
moret's avatar
moret committed
145
        fRxHeader.fIsLastPckt = 0;
146

sletz's avatar
sletz committed
147
        // network buffers
148
149
        fTxBuffer = new char[fParams.fMtu];
        fRxBuffer = new char[fParams.fMtu];
sletz's avatar
sletz committed
150
151
        assert(fTxBuffer);
        assert(fRxBuffer);
152

sletz's avatar
sletz committed
153
        // net audio/midi buffers'addresses
sletz's avatar
sletz committed
154
155
        fTxData = fTxBuffer + HEADER_SIZE;
        fRxData = fRxBuffer + HEADER_SIZE;
sletz's avatar
sletz committed
156

sletz's avatar
sletz committed
157
        return true;
158
159
    }

sletz's avatar
sletz committed
160
161
162
163
164
165
    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();
166
            fTxHeader.fNumPacket = buffer->GetNumPackets(data_size, PACKET_AVAILABLE_SIZE(&fParams));
sletz's avatar
sletz committed
167
168
169
170
171
172

            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);
Stephane Letz's avatar
Stephane Letz committed
173
                 //PacketHeaderDisplay(&fTxHeader);
174
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
175
                    return SOCKET_ERROR;
176
                }
sletz's avatar
sletz committed
177
178
179
180
181
182
183
184
185
186
            }
        }
        return 0;
    }

    int JackNetInterface::AudioSend(NetAudioBuffer* buffer, int audio_channels)
    {
        // audio
        if (audio_channels > 0) {
            fTxHeader.fDataType = 'a';
187
            fTxHeader.fActivePorts = buffer->RenderFromJackPorts(fTxHeader.fFrames);
sletz's avatar
sletz committed
188
            fTxHeader.fNumPacket = buffer->GetNumPackets(fTxHeader.fActivePorts);
sletz's avatar
sletz committed
189
190
191
192
193
194

            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);
195
                //PacketHeaderDisplay(&fTxHeader);
196
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
197
                    return SOCKET_ERROR;
198
                }
sletz's avatar
sletz committed
199
200
201
202
203
204
205
206
207
208
209
            }
        }
        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);
sletz's avatar
sletz committed
210
        
sletz's avatar
sletz committed
211
        // Last midi packet is received, so finish rendering...
212
        if (++recvd_midi_pckt == rx_head->fNumPacket) {
sletz's avatar
sletz committed
213
            buffer->RenderToJackPorts();
214
        }
Stephane Letz's avatar
Stephane Letz committed
215
        //PacketHeaderDisplay(rx_head);
sletz's avatar
sletz committed
216
217
218
219
220
221
222
223
224
225
        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;
226
        fRxHeader.fFrames = rx_head->fFrames;
sletz's avatar
sletz committed
227
        rx_bytes = buffer->RenderFromNetwork(rx_head->fCycle, rx_head->fSubCycle, fRxHeader.fActivePorts);
sletz's avatar
sletz committed
228
        
sletz's avatar
sletz committed
229
        // Last audio packet is received, so finish rendering...
230
        if (fRxHeader.fIsLastPckt) {
231
            buffer->RenderToJackPorts(fRxHeader.fFrames);
232
        }
Stephane Letz's avatar
Stephane Letz committed
233
        //PacketHeaderDisplay(rx_head);
sletz's avatar
sletz committed
234
235
236
237
238
        return rx_bytes;
    }

    int JackNetInterface::FinishRecv(NetAudioBuffer* buffer)
    {
239
240
241
242
243
        if (buffer) {
            buffer->RenderToJackPorts(fRxHeader.fFrames);
        } else {
            jack_error("FinishRecv with null buffer...");
        }
244
        return DATA_PACKET_ERROR;
sletz's avatar
sletz committed
245
246
    }

247
248
249
250
251
252
253
254
255
256
257
    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
258
            case JackCeltEncoder:
259
260
                return new NetCeltAudioBuffer(&fParams, nports, buffer, fParams.fKBps);
            #endif
Robin Gareus's avatar
Robin Gareus committed
261
262
263
264
            #if HAVE_OPUS
            case JackOpusEncoder:
                return new NetOpusAudioBuffer(&fParams, nports, buffer, fParams.fKBps);
            #endif
265
        }
266
267
        
        throw std::bad_alloc();
268
    }
269
270
271
272
    
    void JackNetInterface::SetRcvTimeOut()
    {
        if (!fSetTimeOut) {
273
            if (fSocket.SetTimeOut(fPacketTimeOut) == SOCKET_ERROR) {
274
275
276
277
278
279
                jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
                return;
            }
            fSetTimeOut = true;
        }
    }
280

281
    // JackNetMasterInterface ************************************************************************************
282

283
    bool JackNetMasterInterface::Init()
284
    {
sletz's avatar
sletz committed
285
        jack_log("JackNetMasterInterface::Init : ID %u", fParams.fID);
286

287
        session_params_t host_params;
288
        uint attempt = 0;
289
290
        int rx_bytes = 0;

sletz's avatar
sletz committed
291
        // socket
sletz's avatar
sletz committed
292
293
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
294
            return false;
295
296
        }

sletz's avatar
sletz committed
297
        // timeout on receive (for init)
298
299
300
        if (fSocket.SetTimeOut(MASTER_INIT_TIMEOUT) < 0) {
            jack_error("Can't set init timeout : %s", StrError(NET_ERROR_CODE));
        }
301

sletz's avatar
sletz committed
302
        // connect
sletz's avatar
sletz committed
303
304
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Can't connect : %s", StrError(NET_ERROR_CODE));
305
306
            return false;
        }
307

sletz's avatar
sletz committed
308
        // send 'SLAVE_SETUP' until 'START_MASTER' received
sletz's avatar
sletz committed
309
        jack_info("Sending parameters to %s...", fParams.fSlaveNetName);
310
311
        do
        {
312
            session_params_t net_params;
sletz's avatar
sletz committed
313
314
            memset(&net_params, 0, sizeof(session_params_t));
            SetPacketType(&fParams, SLAVE_SETUP);
315
            SessionParamsHToN(&fParams, &net_params);
316

317
            if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
318
                jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
319
            }
320

sletz's avatar
sletz committed
321
            memset(&net_params, 0, sizeof(session_params_t));
322
            if (((rx_bytes = fSocket.Recv(&net_params, sizeof(session_params_t), 0)) == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
sletz's avatar
sletz committed
323
                jack_error("Problem with network");
324
                return false;
325
            }
326

327
            SessionParamsNToH(&net_params, &host_params);
328
        }
sletz's avatar
sletz committed
329
        while ((GetPacketType(&host_params) != START_MASTER) && (++attempt < SLAVE_SETUP_RETRY));
sletz's avatar
sletz committed
330
        
sletz's avatar
sletz committed
331
332
        if (attempt == SLAVE_SETUP_RETRY) {
            jack_error("Slave doesn't respond, exiting");
333
            return false;
334
335
        }

336
        return true;
337
338
    }

sletz's avatar
sletz committed
339
    bool JackNetMasterInterface::SetParams()
moret's avatar
moret committed
340
    {
sletz's avatar
sletz committed
341
        jack_log("JackNetMasterInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
342
343
            fParams.fSendAudioChannels, fParams.fReturnAudioChannels,
            fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
moret's avatar
moret committed
344
345
346

        JackNetInterface::SetParams();

347
348
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
349

sletz's avatar
sletz committed
350
351
352
        fMaxCycleOffset = fParams.fNetworkLatency;

        // midi net buffers
353
        if (fParams.fSendMidiChannels > 0) {
sletz's avatar
sletz committed
354
            fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fTxData);
355
        }
sletz's avatar
sletz committed
356

357
        if (fParams.fReturnMidiChannels > 0) {
sletz's avatar
sletz committed
358
            fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
359
        }
sletz's avatar
sletz committed
360

sletz's avatar
sletz committed
361
        try {
sletz's avatar
sletz committed
362

sletz's avatar
sletz committed
363
            // audio net buffers
sletz's avatar
sletz committed
364
            if (fParams.fSendAudioChannels > 0) {
365
                fNetAudioCaptureBuffer = AudioBufferFactory(fParams.fSendAudioChannels, fTxData);
sletz's avatar
sletz committed
366
367
                assert(fNetAudioCaptureBuffer);
            }
sletz's avatar
sletz committed
368

sletz's avatar
sletz committed
369
            if (fParams.fReturnAudioChannels > 0) {
370
                fNetAudioPlaybackBuffer = AudioBufferFactory(fParams.fReturnAudioChannels, fRxData);
sletz's avatar
sletz committed
371
372
                assert(fNetAudioPlaybackBuffer);
            }
sletz's avatar
sletz committed
373

sletz's avatar
sletz committed
374
        } catch (exception&) {
Stephane Letz's avatar
Stephane Letz committed
375
            jack_error("NetAudioBuffer on master allocation error...");
sletz's avatar
sletz committed
376
377
            return false;
        }
moret's avatar
moret committed
378

379
        // set the new buffer size
sletz's avatar
sletz committed
380
381
        if (SetNetBufferSize() == SOCKET_ERROR) {
            jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
382
383
            goto error;
        }
sletz's avatar
sletz committed
384

sletz's avatar
sletz committed
385
        return true;
sletz's avatar
sletz committed
386

sletz's avatar
sletz committed
387
    error:
sletz's avatar
sletz committed
388
        FreeNetworkBuffers();
sletz's avatar
sletz committed
389
        return false;
moret's avatar
moret committed
390
391
    }

392
    void JackNetMasterInterface::Exit()
393
    {
sletz's avatar
sletz committed
394
        jack_log("JackNetMasterInterface::Exit, ID %u", fParams.fID);
395

sletz's avatar
sletz committed
396
        // stop process
397
        fRunning = false;
398

sletz's avatar
sletz committed
399
        // send a 'multicast euthanasia request' - new socket is required on macosx
400
        jack_info("Exiting '%s' %s", fParams.fName, fMulticastIP);
sletz's avatar
sletz committed
401
402
        SetPacketType(&fParams, KILL_MASTER);
        JackNetSocket mcast_socket(fMulticastIP, fSocket.GetPort());
403

404
        session_params_t net_params;
sletz's avatar
sletz committed
405
        memset(&net_params, 0, sizeof(session_params_t));
406
407
        SessionParamsHToN(&fParams, &net_params);

408
        if (mcast_socket.NewSocket() == SOCKET_ERROR) {
sletz's avatar
sletz committed
409
            jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
410
411
        }
        if (mcast_socket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR) {
sletz's avatar
sletz committed
412
            jack_error("Can't send suicide request : %s", StrError(NET_ERROR_CODE));
413
        }
414

415
416
417
        mcast_socket.Close();
    }

418
    void JackNetMasterInterface::FatalRecvError()
sletz's avatar
sletz committed
419
    {
sletz's avatar
sletz committed
420
        // fatal connection issue, exit
421
422
423
424
425
426
427
428
429
430
431
        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
432
        // ask to the manager to properly remove the master
sletz's avatar
sletz committed
433
434
435
436
437
        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
438
    int JackNetMasterInterface::Recv(size_t size, int flags)
439
    {
440
        int rx_bytes;
sletz's avatar
sletz committed
441

sletz's avatar
sletz committed
442
        if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
443
            FatalRecvError();
444
        }
445
  
446
447
448
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
        return rx_bytes;
449
    }
450

sletz's avatar
sletz committed
451
    int JackNetMasterInterface::Send(size_t size, int flags)
452
    {
453
454
455
        int tx_bytes;
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
        PacketHeaderHToN(header, header);
456

sletz's avatar
sletz committed
457
        if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
458
            FatalSendError();
459
        }
460
        return tx_bytes;
461
    }
462

463
    int JackNetMasterInterface::SyncSend()
464
    {
465
466
        SetRcvTimeOut();
        
467
468
469
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
470
        fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ? 1 : 0;
Stephane Letz's avatar
Stephane Letz committed
471
472
        fTxHeader.fPacketSize = HEADER_SIZE + fTxHeader.fActivePorts * sizeof(int); // Data part is used to encode active ports
      
sletz's avatar
sletz committed
473
        memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
474
        //PacketHeaderDisplay(&fTxHeader);
sletz's avatar
sletz committed
475
        return Send(fTxHeader.fPacketSize, 0);
476
477
478
479
    }

    int JackNetMasterInterface::DataSend()
    {
480
        if (MidiSend(fNetMidiCaptureBuffer, fParams.fSendMidiChannels, fParams.fSendAudioChannels) == SOCKET_ERROR) {
sletz's avatar
sletz committed
481
            return SOCKET_ERROR;
482
        }
sletz's avatar
sletz committed
483
        return AudioSend(fNetAudioCaptureBuffer, fParams.fSendAudioChannels);
484
485
    }

486
    int JackNetMasterInterface::SyncRecv()
487
    {
sletz's avatar
sletz committed
488
        int rx_bytes = 0;
sletz's avatar
sletz committed
489
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
sletz's avatar
sletz committed
490
491
492
493

        // receive sync (launch the cycle)
        do {
            rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
494
            // connection issue (return -1)
sletz's avatar
sletz committed
495
496
497
498
            if (rx_bytes == SOCKET_ERROR) {
                return SOCKET_ERROR;
            }
        }
499
        while (strcmp(rx_head->fPacketType, "header") != 0);
Stephane Letz's avatar
Stephane Letz committed
500
        //PacketHeaderDisplay(rx_head);
501
502
        
        if (rx_head->fDataType != 's') {
503
            jack_error("Wrong packet type : %c", rx_head->fDataType);
504
            // not the last packet..
Stephane Letz's avatar
Stephane Letz committed
505
            fRxHeader.fIsLastPckt = 0;
506
            return SYNC_PACKET_ERROR;
507
508
        }
    
sletz's avatar
sletz committed
509
        fCurrentCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
510

511
        if (fCurrentCycleOffset < fMaxCycleOffset && !fSynched) {
sletz's avatar
sletz committed
512
            jack_info("Synching with latency = %d", fCurrentCycleOffset);
Stephane Letz's avatar
Stephane Letz committed
513
            return NET_SYNCHING;
514
        } else {
515
516
517
518
            if (fCurrentCycleOffset == fMaxCycleOffset) {
                // when the sync offset is reached 
                fSynched = true;
            }
519
            rx_bytes = Recv(rx_head->fPacketSize, 0);
520
521
            fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
            return rx_bytes;
522
        }
523
    }
524

525
    int JackNetMasterInterface::DataRecv()
526
527
    {
        int rx_bytes = 0;
528
        uint recvd_midi_pckt = 0;
sletz's avatar
sletz committed
529
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
Stephane Letz's avatar
Stephane Letz committed
530
     
sletz's avatar
sletz committed
531
532
        while (!fRxHeader.fIsLastPckt) {
            // how much data is queued on the rx buffer ?
sletz's avatar
sletz committed
533
            rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
sletz's avatar
sletz committed
534
         
sletz's avatar
sletz committed
535
            // error here, problem with recv, just skip the cycle (return -1)
536
            if (rx_bytes == SOCKET_ERROR) {
moret's avatar
moret committed
537
                return rx_bytes;
538
            }
sletz's avatar
sletz committed
539

sletz's avatar
sletz committed
540
541
542
543
544
545
            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
546
                        break;
547

sletz's avatar
sletz committed
548
549
                    case 'a':   // audio
                        rx_bytes = AudioRecv(rx_head, fNetAudioPlaybackBuffer);
moret's avatar
moret committed
550
                        break;
551

sletz's avatar
sletz committed
552
                    case 's':   // sync
553
                        jack_info("NetMaster : missing last data packet from '%s'", fParams.fName);
sletz's avatar
sletz committed
554
                        return FinishRecv(fNetAudioPlaybackBuffer);
555
556
557
                }
            }
        }
sletz's avatar
sletz committed
558
   
559
        return rx_bytes;
560
    }
561

Stephane Letz's avatar
Stephane Letz committed
562
    void JackNetMasterInterface::EncodeSyncPacket(int frames)
563
    {
sletz's avatar
sletz committed
564
        // This method contains every step of sync packet informations coding
sletz's avatar
sletz committed
565
        // first of all, clear sync packet
566
        memset(fTxData, 0, PACKET_AVAILABLE_SIZE(&fParams));
567
568
569
    
        // Transport not used for now...
        /*
sletz's avatar
sletz committed
570
        // then, first step : transport
571
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
572
            EncodeTransportData();
sletz's avatar
sletz committed
573
            TransportDataHToN(&fSendTransportData, &fSendTransportData);
sletz's avatar
sletz committed
574
            // copy to TxBuffer
sletz's avatar
sletz committed
575
            memcpy(fTxData, &fSendTransportData, sizeof(net_transport_data_t));
576
        }
sletz's avatar
sletz committed
577
578
        // then others (freewheel etc.)
        // ...
579
580
        */
   
sletz's avatar
sletz committed
581
        // Write active ports list
sletz's avatar
sletz committed
582
        fTxHeader.fActivePorts = (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->ActivePortsToNetwork(fTxData) : 0;
Stephane Letz's avatar
Stephane Letz committed
583
        fTxHeader.fFrames = frames;
584
585
    }

Stephane Letz's avatar
Stephane Letz committed
586
    void JackNetMasterInterface::DecodeSyncPacket(int& frames)
587
    {
sletz's avatar
sletz committed
588
        // This method contains every step of sync packet informations decoding process
589
590
591
        
        // Transport not used for now...
        /*
sletz's avatar
sletz committed
592
        // first : transport
593
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
594
            // copy received transport data to transport data structure
sletz's avatar
sletz committed
595
596
            memcpy(&fReturnTransportData, fRxData, sizeof(net_transport_data_t));
            TransportDataNToH(&fReturnTransportData,  &fReturnTransportData);
sletz's avatar
sletz committed
597
            DecodeTransportData();
598
        }
sletz's avatar
sletz committed
599
600
        // then others
        // ...
601
602
        */
       
sletz's avatar
sletz committed
603
604
605
606
607
608
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);

        // Read active ports list
        if (fNetAudioCaptureBuffer) {
            fNetAudioCaptureBuffer->ActivePortsFromNetwork(fRxData, rx_head->fActivePorts);
        }
Stephane Letz's avatar
Stephane Letz committed
609
        frames = rx_head->fFrames;
610
    }
611

612
613
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
614
615
    uint JackNetSlaveInterface::fSlaveCounter = 0;

sletz's avatar
sletz committed
616
617
618
619
620
621
622
623
624
625
626
    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();
            }
        }
    }

627
    bool JackNetSlaveInterface::Init()
628
    {
sletz's avatar
sletz committed
629
        jack_log("JackNetSlaveInterface::Init()");
630

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

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

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

657
658
        return true;
    }
659

660
    // Separate the connection protocol into two separated step
sletz's avatar
sletz committed
661
    bool JackNetSlaveInterface::InitConnection(int time_out_sec)
662
    {
663
        jack_log("JackNetSlaveInterface::InitConnection time_out_sec = %d", time_out_sec);
664
        int try_count = (time_out_sec > 0) ? int((1000000.f * float(time_out_sec)) / float(SLAVE_INIT_TIMEOUT)) : INT_MAX;
665
  
sletz's avatar
sletz committed
666
        // set the parameters to send
sletz's avatar
sletz committed
667
        strcpy(fParams.fPacketType, "params");
Stephane Letz's avatar
Stephane Letz committed
668
        fParams.fProtocolVersion = NETWORK_PROTOCOL;
sletz's avatar
sletz committed
669
        SetPacketType(&fParams, SLAVE_AVAILABLE);
670

671
        return (SendAvailableToMaster(try_count) == NET_CONNECTED);
672
    }
673

674
675
676
677
678
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

        net_status_t status;
679
        do {
sletz's avatar
sletz committed
680
            // then tell the master we are ready
681
682
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
            status = SendStartToMaster();
sletz's avatar
sletz committed
683
            if (status == NET_ERROR) {
684
                return false;
sletz's avatar
sletz committed
685
            }
686
        }
687
688
        while (status != NET_ROLLING);

689
690
        return true;
    }
691

Stephane Letz's avatar
Stephane Letz committed
692
    net_status_t JackNetSlaveInterface::SendAvailableToMaster(int try_count)
693
    {
694
        jack_log("JackNetSlaveInterface::SendAvailableToMaster try_count = %d", try_count);
sletz's avatar
sletz committed
695
        // utility
696
        session_params_t host_params;
697
698
        int rx_bytes = 0;

sletz's avatar
sletz committed
699
        // socket
sletz's avatar
sletz committed
700
701
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Fatal error : network unreachable - %s", StrError(NET_ERROR_CODE));
702
            return NET_SOCKET_ERROR;
703
704
        }

sletz's avatar
sletz committed
705
706
707
708
709
710
711
712
        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;
            }
713
        }
714

715
716
717
718
        // 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));
        }
719

sletz's avatar
sletz committed
720
        // disable local loop
721
        if (fSocket.SetLocalLoop() == SOCKET_ERROR) {
sletz's avatar
sletz committed
722
            jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
723
        }
724

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

sletz's avatar
sletz committed
737
            // filter incoming packets : don't exit while no error is detected
sletz's avatar
sletz committed
738
739
            memset(&net_params, 0, sizeof(session_params_t));
            rx_bytes = fSocket.CatchHost(&net_params, sizeof(session_params_t), 0);
740
            SessionParamsNToH(&net_params, &host_params);
741
            if ((rx_bytes == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
sletz's avatar
sletz committed
742
                jack_error("Can't receive : %s", StrError(NET_ERROR_CODE));
743
                return NET_RECV_ERROR;
744
745
            }
        }
746
        while (strcmp(host_params.fPacketType, fParams.fPacketType) && (GetPacketType(&host_params) != SLAVE_SETUP)  && (--try_count > 0));
747
    
748
        // time out failure..
sletz's avatar
sletz committed
749
750
        if (try_count == 0) {
            jack_error("Time out error in connect");
sletz's avatar
sletz committed
751
752
            return NET_CONNECT_ERROR;
        }
753

sletz's avatar
sletz committed
754
        // everything is OK, copy parameters
755
        fParams = host_params;
Stephane Letz's avatar
Stephane Letz committed
756
     
sletz's avatar
sletz committed
757
        // connect the socket
sletz's avatar
sletz committed
758
759
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Error in connect : %s", StrError(NET_ERROR_CODE));
760
            return NET_CONNECT_ERROR;
761
        }
762
        
moret's avatar
moret committed
763
        return NET_CONNECTED;
764
765
    }

moret's avatar
moret committed
766
    net_status_t JackNetSlaveInterface::SendStartToMaster()
767
    {
sletz's avatar
sletz committed
768
        jack_log("JackNetSlaveInterface::SendStartToMaster");
moret's avatar
moret committed
769