JackNetInterface.cpp 34.5 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 <assert.h>
22
23
24

using namespace std;

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

31
32
33
34
namespace Jack
{
    // JackNetInterface*******************************************

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

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

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

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

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

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

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

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

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

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

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

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

118
        return 0;
moret's avatar
moret committed
119
120
    }

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

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

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

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

sletz's avatar
sletz committed
147
        return true;
148
149
    }

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

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

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

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

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

228
229
230
231
232
233
234
235
236
237
238
    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
239
            case JackCeltEncoder:
240
241
242
243
244
245
                return new NetCeltAudioBuffer(&fParams, nports, buffer, fParams.fKBps);
            #endif
        }
        return NULL;
    }

246
    // JackNetMasterInterface ************************************************************************************
247

248
    bool JackNetMasterInterface::Init()
249
    {
sletz's avatar
sletz committed
250
        jack_log("JackNetMasterInterface::Init, ID %u", fParams.fID);
251

252
        session_params_t host_params;
253
        uint attempt = 0;
254
255
        int rx_bytes = 0;

sletz's avatar
sletz committed
256
        // socket
sletz's avatar
sletz committed
257
258
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
259
            return false;
260
261
        }

sletz's avatar
sletz committed
262
        // timeout on receive (for init)
sletz's avatar
sletz committed
263
264
        if (fSocket.SetTimeOut(MASTER_INIT_TIMEOUT) < 0)
            jack_error("Can't set timeout : %s", StrError(NET_ERROR_CODE));
265

sletz's avatar
sletz committed
266
        // connect
sletz's avatar
sletz committed
267
268
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Can't connect : %s", StrError(NET_ERROR_CODE));
269
270
            return false;
        }
271

sletz's avatar
sletz committed
272
        // send 'SLAVE_SETUP' until 'START_MASTER' received
sletz's avatar
sletz committed
273
        jack_info("Sending parameters to %s...", fParams.fSlaveNetName);
274
275
        do
        {
276
            session_params_t net_params;
sletz's avatar
sletz committed
277
278
            memset(&net_params, 0, sizeof(session_params_t));
            SetPacketType(&fParams, SLAVE_SETUP);
279
            SessionParamsHToN(&fParams, &net_params);
280

281
            if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
282
                jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
283
            }
284

sletz's avatar
sletz committed
285
            memset(&net_params, 0, sizeof(session_params_t));
286
            if (((rx_bytes = fSocket.Recv(&net_params, sizeof(session_params_t), 0)) == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
sletz's avatar
sletz committed
287
                jack_error("Problem with network");
288
                return false;
289
            }
290

291
            SessionParamsNToH(&net_params, &host_params);
292
        }
sletz's avatar
sletz committed
293
294
295
        while ((GetPacketType(&host_params) != START_MASTER) && (++attempt < SLAVE_SETUP_RETRY));
        if (attempt == SLAVE_SETUP_RETRY) {
            jack_error("Slave doesn't respond, exiting");
296
            return false;
297
298
        }

299
        return true;
300
301
    }

sletz's avatar
sletz committed
302
303
304
305
306
307
    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
308

sletz's avatar
sletz committed
309
    bool JackNetMasterInterface::SetParams()
moret's avatar
moret committed
310
    {
sletz's avatar
sletz committed
311
        jack_log("JackNetMasterInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
312
313
            fParams.fSendAudioChannels, fParams.fReturnAudioChannels,
            fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
moret's avatar
moret committed
314
315
316

        JackNetInterface::SetParams();

317
318
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
319

sletz's avatar
sletz committed
320
321
322
        fMaxCycleOffset = fParams.fNetworkLatency;

        // midi net buffers
323
        if (fParams.fSendMidiChannels > 0) {
sletz's avatar
sletz committed
324
            fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fTxData);
325
        }
sletz's avatar
sletz committed
326

327
        if (fParams.fReturnMidiChannels > 0) {
sletz's avatar
sletz committed
328
            fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
329
        }
sletz's avatar
sletz committed
330

sletz's avatar
sletz committed
331
        try {
sletz's avatar
sletz committed
332

sletz's avatar
sletz committed
333
            // audio net buffers
sletz's avatar
sletz committed
334
            if (fParams.fSendAudioChannels > 0) {
335
                fNetAudioCaptureBuffer = AudioBufferFactory(fParams.fSendAudioChannels, fTxData);
sletz's avatar
sletz committed
336
337
                assert(fNetAudioCaptureBuffer);
            }
sletz's avatar
sletz committed
338

sletz's avatar
sletz committed
339
            if (fParams.fReturnAudioChannels > 0) {
340
                fNetAudioPlaybackBuffer = AudioBufferFactory(fParams.fReturnAudioChannels, fRxData);
sletz's avatar
sletz committed
341
342
                assert(fNetAudioPlaybackBuffer);
            }
sletz's avatar
sletz committed
343

sletz's avatar
sletz committed
344
345
346
347
        } catch (exception&) {
            jack_error("NetAudioBuffer allocation error...");
            return false;
        }
moret's avatar
moret committed
348

sletz's avatar
sletz committed
349
        // set the new timeout for the socket
350
        /*
sletz's avatar
sletz committed
351
352
        if (SetRxTimeout() == SOCKET_ERROR) {
            jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
353
            goto error;
sletz's avatar
sletz committed
354
        }
355
        */
moret's avatar
moret committed
356

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

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

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

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

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

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

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

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

393
394
395
        mcast_socket.Close();
    }

396
    void JackNetMasterInterface::FatalRecvError()
sletz's avatar
sletz committed
397
    {
sletz's avatar
sletz committed
398
        // fatal connection issue, exit
399
400
401
402
403
404
405
406
407
408
409
        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
410
        // ask to the manager to properly remove the master
sletz's avatar
sletz committed
411
412
413
414
415
        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
416
    int JackNetMasterInterface::Recv(size_t size, int flags)
417
    {
418
        int rx_bytes;
sletz's avatar
sletz committed
419

sletz's avatar
sletz committed
420
        if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
421
422

            /*
423
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
424
            // no data isn't really a network error, so just return 0 available read bytes
sletz's avatar
sletz committed
425
            if (error == NET_NO_DATA) {
426
                return 0;
sletz's avatar
sletz committed
427
            } else if (error == NET_CONN_ERROR) {
428
                FatalRecvError();
sletz's avatar
sletz committed
429
            } else {
sletz's avatar
sletz committed
430
                jack_error("Error in master receive : %s", StrError(NET_ERROR_CODE));
431
            }
432
433
            */

434
            FatalRecvError();
435
        }
436

437
438
439
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
        return rx_bytes;
440
    }
441

sletz's avatar
sletz committed
442
    int JackNetMasterInterface::Send(size_t size, int flags)
443
    {
444
445
446
        int tx_bytes;
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
        PacketHeaderHToN(header, header);
447

sletz's avatar
sletz committed
448
        if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
sletz's avatar
sletz committed
449
            /*
450
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
451
            if (error == NET_CONN_ERROR) {
452
                FatalSendError();
sletz's avatar
sletz committed
453
454
            } else {
                jack_error("Error in master send : %s", StrError(NET_ERROR_CODE));
455
            }
sletz's avatar
sletz committed
456
            */
457
            FatalSendError();
458
        }
459
        return tx_bytes;
460
    }
461

462
463
    bool JackNetMasterInterface::IsSynched()
    {
sletz's avatar
sletz committed
464
        return (fCurrentCycleOffset <= fMaxCycleOffset);
465
    }
466

467
    int JackNetMasterInterface::SyncSend()
468
    {
469
470
471
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
472
        fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ? 1 : 0;
sletz's avatar
sletz committed
473
        fTxHeader.fPacketSize = fParams.fMtu;
sletz's avatar
sletz committed
474

sletz's avatar
sletz committed
475
        memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
sletz's avatar
sletz committed
476
        // PacketHeaderDisplay(&fTxHeader);
sletz's avatar
sletz committed
477
        return Send(fTxHeader.fPacketSize, 0);
478
479
480
481
    }

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

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

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

sletz's avatar
sletz committed
496
        if ((rx_bytes == 0) || (rx_bytes == SOCKET_ERROR)) {
sletz's avatar
sletz committed
497
            // 0 bytes considered an error (lost connection)
sletz's avatar
sletz committed
498
499
            return SOCKET_ERROR;
        }
500

sletz's avatar
sletz committed
501
        fCurrentCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
sletz's avatar
sletz committed
502
503
504
505
506
507
508
509
510
511
512
513
        */

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

sletz's avatar
sletz committed
516
517
        if (fCurrentCycleOffset < fMaxCycleOffset) {
            jack_info("Synching with latency = %d", fCurrentCycleOffset);
518
519
520
            return 0;
        } else {
            rx_bytes = Recv(rx_head->fPacketSize, 0);
521
522
            fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
            return rx_bytes;
523
        }
524
    }
525

526
    int JackNetMasterInterface::DataRecv()
527
528
    {
        int rx_bytes = 0;
529
        uint recvd_midi_pckt = 0;
sletz's avatar
sletz committed
530
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
531

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

sletz's avatar
sletz committed
536
            // error here, problem with recv, just skip the cycle (return -1)
537
            if (rx_bytes == SOCKET_ERROR) {
moret's avatar
moret committed
538
                return rx_bytes;
539
            }
sletz's avatar
sletz committed
540

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

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

sletz's avatar
sletz committed
553
                    case 's':   // sync
554
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
sletz's avatar
sletz committed
555
                        return FinishRecv(fNetAudioPlaybackBuffer);
556
557
558
                }
            }
        }
sletz's avatar
sletz committed
559

560
        return rx_bytes;
561
    }
562

563
    void JackNetMasterInterface::EncodeSyncPacket()
564
    {
sletz's avatar
sletz committed
565
        // This method contains every step of sync packet informations coding
sletz's avatar
sletz committed
566
        // first of all, clear sync packet
567
        memset(fTxData, 0, PACKET_AVAILABLE_SIZE(&fParams));
568

sletz's avatar
sletz committed
569
        // then, first step : transport
570
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
571
            EncodeTransportData();
sletz's avatar
sletz committed
572
            TransportDataHToN(&fSendTransportData, &fSendTransportData);
sletz's avatar
sletz committed
573
            // copy to TxBuffer
sletz's avatar
sletz committed
574
            memcpy(fTxData, &fSendTransportData, sizeof(net_transport_data_t));
575
        }
sletz's avatar
sletz committed
576
577
        // then others (freewheel etc.)
        // ...
sletz's avatar
sletz committed
578
579
580
581

        // Transport not used for now...

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

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

        // 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);
        }
605
    }
606

607
608
// JackNetSlaveInterface ************************************************************************************************

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

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

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

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

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

641
642
        return true;
    }
643

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

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

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

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

668
669
670
671
672
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

        net_status_t status;
673
        do {
sletz's avatar
sletz committed
674
            // then tell the master we are ready
675
676
677
678
679
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
            status = SendStartToMaster();
            if (status == NET_ERROR)
                return false;
        }
680
681
        while (status != NET_ROLLING);

682
683
        return true;
    }
684

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

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

sletz's avatar
sletz committed
698
699
700
701
702
703
704
705
        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;
            }
706
        }
707

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

sletz's avatar
sletz committed
712
        // disable local loop
sletz's avatar
sletz committed
713
714
        if (fSocket.SetLocalLoop() == SOCKET_ERROR)
            jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
715

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

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

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

sletz's avatar
sletz committed
743
        // everything is OK, copy parameters
744
        fParams = host_params;
moret's avatar
moret committed
745

sletz's avatar
sletz committed
746
        // connect the socket
sletz's avatar
sletz committed
747
748
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Error in connect : %s", StrError(NET_ERROR_CODE));
749
            return NET_CONNECT_ERROR;
750
        }
moret's avatar
moret committed
751
        return NET_CONNECTED;
752
753
    }

moret's avatar
moret committed
754
    net_status_t JackNetSlaveInterface::SendStartToMaster()
755
    {
sletz's avatar
sletz committed
756
        jack_log("JackNetSlaveInterface::SendStartToMaster");
moret's avatar
moret committed
757

sletz's avatar
sletz committed
758
        // tell the master to start
759
        session_params_t net_params;
sletz's avatar
sletz committed
760
761
        memset(&net_params, 0, sizeof(session_params_t));
        SetPacketType(&fParams, START_MASTER);
762
        SessionParamsHToN(&fParams, &net_params);
763
        if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
764
765
            jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
            return (fSocket.GetError() == NET_CONN_ERROR) ? NET_ERROR : NET_SEND_ERROR;
766
        }
767
        return NET_ROLLING;
768
769
    }

sletz's avatar
sletz committed
770
    bool JackNetSlaveInterface::SetParams()
moret's avatar
moret committed
771
    {