JackNetInterface.cpp 36.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"
21
#include "JackPlatformPlug.h"
22
#include <assert.h>
23
24
25

using namespace std;

sletz's avatar
sletz committed
26

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
58
59
60
61
62
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
63
64
        memset(&fSendTransportData, 0, sizeof(net_transport_data_t));
        memset(&fReturnTransportData, 0, sizeof(net_transport_data_t));
65
66
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

sletz's avatar
sletz committed
152
153
154
155
156
157
    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();
158
            fTxHeader.fNumPacket = buffer->GetNumPackets(data_size, PACKET_AVAILABLE_SIZE(&fParams));
sletz's avatar
sletz committed
159
160
161
162
163
164

            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);
165
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
166
                    return SOCKET_ERROR;
167
                }
sletz's avatar
sletz committed
168
169
170
171
172
173
174
175
176
177
            }
        }
        return 0;
    }

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

            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);
187
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
188
                    return SOCKET_ERROR;
189
                }
sletz's avatar
sletz committed
190
191
192
193
194
195
196
197
198
199
200
201
            }
        }
        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...
202
        if (++recvd_midi_pckt == rx_head->fNumPacket) {
sletz's avatar
sletz committed
203
            buffer->RenderToJackPorts();
204
        }
sletz's avatar
sletz committed
205
206
207
208
209
210
211
212
213
214
        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
215
        rx_bytes = buffer->RenderFromNetwork(rx_head->fCycle, rx_head->fSubCycle, fRxHeader.fActivePorts);
sletz's avatar
sletz committed
216
        // Last audio packet is received, so finish rendering...
217
        if (fRxHeader.fIsLastPckt) {
sletz's avatar
sletz committed
218
            buffer->RenderToJackPorts();
219
        }
sletz's avatar
sletz committed
220
221
222
223
224
225
226
227
228
229
        return rx_bytes;
    }

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

230
    // JackNetMasterInterface ************************************************************************************
231

232
    bool JackNetMasterInterface::Init()
233
    {
sletz's avatar
sletz committed
234
        jack_log("JackNetMasterInterface::Init, ID %u", fParams.fID);
235

236
        session_params_t host_params;
237
        uint attempt = 0;
238
239
        int rx_bytes = 0;

sletz's avatar
sletz committed
240
        // socket
sletz's avatar
sletz committed
241
242
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
243
            return false;
244
245
        }

sletz's avatar
sletz committed
246
        // timeout on receive (for init)
sletz's avatar
sletz committed
247
248
        if (fSocket.SetTimeOut(MASTER_INIT_TIMEOUT) < 0)
            jack_error("Can't set timeout : %s", StrError(NET_ERROR_CODE));
249

sletz's avatar
sletz committed
250
        // connect
sletz's avatar
sletz committed
251
252
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Can't connect : %s", StrError(NET_ERROR_CODE));
253
254
            return false;
        }
255

sletz's avatar
sletz committed
256
        // send 'SLAVE_SETUP' until 'START_MASTER' received
sletz's avatar
sletz committed
257
        jack_info("Sending parameters to %s...", fParams.fSlaveNetName);
258
259
        do
        {
260
            session_params_t net_params;
sletz's avatar
sletz committed
261
262
            memset(&net_params, 0, sizeof(session_params_t));
            SetPacketType(&fParams, SLAVE_SETUP);
263
            SessionParamsHToN(&fParams, &net_params);
264

265
            if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
266
                jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
267
            }
268

sletz's avatar
sletz committed
269
            memset(&net_params, 0, sizeof(session_params_t));
270
            if (((rx_bytes = fSocket.Recv(&net_params, sizeof(session_params_t), 0)) == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
sletz's avatar
sletz committed
271
                jack_error("Problem with network");
272
                return false;
273
            }
274

275
            SessionParamsNToH(&net_params, &host_params);
276
        }
sletz's avatar
sletz committed
277
278
279
        while ((GetPacketType(&host_params) != START_MASTER) && (++attempt < SLAVE_SETUP_RETRY));
        if (attempt == SLAVE_SETUP_RETRY) {
            jack_error("Slave doesn't respond, exiting");
280
            return false;
281
282
        }

283
        return true;
284
285
    }

sletz's avatar
sletz committed
286
287
288
289
290
291
    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
292

sletz's avatar
sletz committed
293
    bool JackNetMasterInterface::SetParams()
moret's avatar
moret committed
294
    {
sletz's avatar
sletz committed
295
        jack_log("JackNetMasterInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
296
297
            fParams.fSendAudioChannels, fParams.fReturnAudioChannels,
            fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
moret's avatar
moret committed
298
299
300

        JackNetInterface::SetParams();

301
302
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
303

sletz's avatar
sletz committed
304
305
306
        fMaxCycleOffset = fParams.fNetworkLatency;

        // midi net buffers
307
        if (fParams.fSendMidiChannels > 0) {
sletz's avatar
sletz committed
308
            fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fTxData);
309
        }
sletz's avatar
sletz committed
310

311
        if (fParams.fReturnMidiChannels > 0) {
sletz's avatar
sletz committed
312
            fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
313
        }
sletz's avatar
sletz committed
314

sletz's avatar
sletz committed
315
        try {
sletz's avatar
sletz committed
316

sletz's avatar
sletz committed
317
            // audio net buffers
sletz's avatar
sletz committed
318
            if (fParams.fSendAudioChannels > 0) {
sletz's avatar
sletz committed
319

320
                switch (fParams.fSampleEncoder) {
sletz's avatar
sletz committed
321

322
                    case JackFloatEncoder:
sletz's avatar
sletz committed
323
                        fNetAudioCaptureBuffer = new NetFloatAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
324
                        break;
sletz's avatar
sletz committed
325

326
                    case JackIntEncoder:
sletz's avatar
sletz committed
327
                        fNetAudioCaptureBuffer = new NetIntAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
328
                        break;
sletz's avatar
sletz committed
329

330
                    case JackCeltEncoder:
nedko's avatar
nedko committed
331
                    #if HAVE_CELT
sletz's avatar
sletz committed
332
                        fNetAudioCaptureBuffer = new NetCeltAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData, fParams.fKBps);
333
334
335
                    #endif
                        break;
                }
sletz's avatar
sletz committed
336

sletz's avatar
sletz committed
337
338
                assert(fNetAudioCaptureBuffer);
            }
sletz's avatar
sletz committed
339

sletz's avatar
sletz committed
340
            if (fParams.fReturnAudioChannels > 0) {
sletz's avatar
sletz committed
341

342
                switch (fParams.fSampleEncoder) {
sletz's avatar
sletz committed
343

344
                    case JackFloatEncoder:
sletz's avatar
sletz committed
345
                        fNetAudioPlaybackBuffer = new NetFloatAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
346
                        break;
sletz's avatar
sletz committed
347

348
                    case JackIntEncoder:
sletz's avatar
sletz committed
349
                        fNetAudioPlaybackBuffer = new NetIntAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
350
                        break;
sletz's avatar
sletz committed
351

352
                    case JackCeltEncoder:
nedko's avatar
nedko committed
353
                    #if HAVE_CELT
sletz's avatar
sletz committed
354
                        fNetAudioPlaybackBuffer = new NetCeltAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData, fParams.fKBps);
355
356
357
                    #endif
                        break;
                }
sletz's avatar
sletz committed
358

sletz's avatar
sletz committed
359
360
                assert(fNetAudioPlaybackBuffer);
            }
sletz's avatar
sletz committed
361

sletz's avatar
sletz committed
362
363
364
365
        } catch (exception&) {
            jack_error("NetAudioBuffer allocation error...");
            return false;
        }
moret's avatar
moret committed
366

sletz's avatar
sletz committed
367
        // set the new timeout for the socket
368
        /*
sletz's avatar
sletz committed
369
370
        if (SetRxTimeout() == SOCKET_ERROR) {
            jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
371
            goto error;
sletz's avatar
sletz committed
372
        }
373
        */
moret's avatar
moret committed
374

sletz's avatar
sletz committed
375
        // set the new rx buffer size
sletz's avatar
sletz committed
376
377
        if (SetNetBufferSize() == SOCKET_ERROR) {
            jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
378
379
            goto error;
        }
sletz's avatar
sletz committed
380

sletz's avatar
sletz committed
381
        return true;
sletz's avatar
sletz committed
382

sletz's avatar
sletz committed
383
    error:
sletz's avatar
sletz committed
384
        FreeNetworkBuffers();
sletz's avatar
sletz committed
385
        return false;
moret's avatar
moret committed
386
387
    }

388
    void JackNetMasterInterface::Exit()
389
    {
sletz's avatar
sletz committed
390
        jack_log("JackNetMasterInterface::Exit, ID %u", fParams.fID);
391

sletz's avatar
sletz committed
392
        // stop process
393
        fRunning = false;
394

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

400
        session_params_t net_params;
sletz's avatar
sletz committed
401
        memset(&net_params, 0, sizeof(session_params_t));
402
403
        SessionParamsHToN(&fParams, &net_params);

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

411
412
413
        mcast_socket.Close();
    }

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

sletz's avatar
sletz committed
438
        if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
439
440

            /*
441
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
442
            // no data isn't really a network error, so just return 0 available read bytes
sletz's avatar
sletz committed
443
            if (error == NET_NO_DATA) {
444
                return 0;
sletz's avatar
sletz committed
445
            } else if (error == NET_CONN_ERROR) {
446
                FatalRecvError();
sletz's avatar
sletz committed
447
            } else {
sletz's avatar
sletz committed
448
                jack_error("Error in master receive : %s", StrError(NET_ERROR_CODE));
449
            }
450
451
            */

452
            FatalRecvError();
453
        }
454

455
456
457
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
        return rx_bytes;
458
    }
459

sletz's avatar
sletz committed
460
    int JackNetMasterInterface::Send(size_t size, int flags)
461
    {
462
463
464
        int tx_bytes;
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
        PacketHeaderHToN(header, header);
465

sletz's avatar
sletz committed
466
        if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
sletz's avatar
sletz committed
467
            /*
468
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
469
            if (error == NET_CONN_ERROR) {
470
                FatalSendError();
sletz's avatar
sletz committed
471
472
            } else {
                jack_error("Error in master send : %s", StrError(NET_ERROR_CODE));
473
            }
sletz's avatar
sletz committed
474
            */
475
            FatalSendError();
476
        }
477
        return tx_bytes;
478
    }
479

480
481
    bool JackNetMasterInterface::IsSynched()
    {
sletz's avatar
sletz committed
482
        return (fCurrentCycleOffset <= fMaxCycleOffset);
483
    }
484

485
    int JackNetMasterInterface::SyncSend()
486
    {
487
488
489
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
490
        fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ? 1 : 0;
sletz's avatar
sletz committed
491
        fTxHeader.fPacketSize = fParams.fMtu;
sletz's avatar
sletz committed
492

sletz's avatar
sletz committed
493
        memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
sletz's avatar
sletz committed
494
        // PacketHeaderDisplay(&fTxHeader);
sletz's avatar
sletz committed
495
        return Send(fTxHeader.fPacketSize, 0);
496
497
498
499
    }

    int JackNetMasterInterface::DataSend()
    {
500
        if (MidiSend(fNetMidiCaptureBuffer, fParams.fSendMidiChannels, fParams.fSendAudioChannels) == SOCKET_ERROR) {
sletz's avatar
sletz committed
501
            return SOCKET_ERROR;
502
        }
sletz's avatar
sletz committed
503
        return AudioSend(fNetAudioCaptureBuffer, fParams.fSendAudioChannels);
504
505
    }

506
    int JackNetMasterInterface::SyncRecv()
507
    {
sletz's avatar
sletz committed
508
        int rx_bytes = 0;
sletz's avatar
sletz committed
509
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
sletz's avatar
sletz committed
510
511

        /*
sletz's avatar
sletz committed
512
        int rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
513

sletz's avatar
sletz committed
514
        if ((rx_bytes == 0) || (rx_bytes == SOCKET_ERROR)) {
sletz's avatar
sletz committed
515
            // 0 bytes considered an error (lost connection)
sletz's avatar
sletz committed
516
517
            return SOCKET_ERROR;
        }
518

sletz's avatar
sletz committed
519
        fCurrentCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
sletz's avatar
sletz committed
520
521
522
523
524
525
526
527
528
529
530
531
        */

        // 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
532
        fCurrentCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
533

sletz's avatar
sletz committed
534
535
        if (fCurrentCycleOffset < fMaxCycleOffset) {
            jack_info("Synching with latency = %d", fCurrentCycleOffset);
536
537
538
            return 0;
        } else {
            rx_bytes = Recv(rx_head->fPacketSize, 0);
539
540
            fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
            return rx_bytes;
541
        }
542
    }
543

544
    int JackNetMasterInterface::DataRecv()
545
546
    {
        int rx_bytes = 0;
547
        uint recvd_midi_pckt = 0;
sletz's avatar
sletz committed
548
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
549

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

sletz's avatar
sletz committed
554
            // error here, problem with recv, just skip the cycle (return -1)
555
            if (rx_bytes == SOCKET_ERROR) {
moret's avatar
moret committed
556
                return rx_bytes;
557
            }
sletz's avatar
sletz committed
558

sletz's avatar
sletz committed
559
560
561
562
563
564
            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
565
                        break;
566

sletz's avatar
sletz committed
567
568
                    case 'a':   // audio
                        rx_bytes = AudioRecv(rx_head, fNetAudioPlaybackBuffer);
moret's avatar
moret committed
569
                        break;
570

sletz's avatar
sletz committed
571
                    case 's':   // sync
572
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
sletz's avatar
sletz committed
573
                        return FinishRecv(fNetAudioPlaybackBuffer);
574
575
576
                }
            }
        }
sletz's avatar
sletz committed
577

578
        return rx_bytes;
579
    }
580

581
    void JackNetMasterInterface::EncodeSyncPacket()
582
    {
sletz's avatar
sletz committed
583
        // This method contains every step of sync packet informations coding
sletz's avatar
sletz committed
584
        // first of all, clear sync packet
585
        memset(fTxData, 0, PACKET_AVAILABLE_SIZE(&fParams));
586

sletz's avatar
sletz committed
587
        // then, first step : transport
588
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
589
            EncodeTransportData();
sletz's avatar
sletz committed
590
            TransportDataHToN(&fSendTransportData, &fSendTransportData);
sletz's avatar
sletz committed
591
            // copy to TxBuffer
sletz's avatar
sletz committed
592
            memcpy(fTxData, &fSendTransportData, sizeof(net_transport_data_t));
593
        }
sletz's avatar
sletz committed
594
595
        // then others (freewheel etc.)
        // ...
sletz's avatar
sletz committed
596
597
598
599

        // Transport not used for now...

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

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

        // 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);
        }
623
    }
624

625
626
// JackNetSlaveInterface ************************************************************************************************

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

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

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

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

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

659
660
        return true;
    }
661

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

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

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

sletz's avatar
sletz committed
683
        return (try_count != 0);
684
    }
685

686
687
688
689
690
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

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

700
701
        return true;
    }
702

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

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

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

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

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

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

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

sletz's avatar
sletz committed
751
        // Time out failure..
sletz's avatar
sletz committed
752
753
        if (try_count == 0) {
            jack_error("Time out error in connect");