JackNetInterface.cpp 35.6 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
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';
            buffer->RenderFromJackPorts();
            fTxHeader.fNumPacket = buffer->GetNumPackets();

            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
215
216
        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;
        rx_bytes = buffer->RenderFromNetwork(rx_head->fCycle, rx_head->fSubCycle, rx_bytes - HEADER_SIZE, fRxHeader.fActivePorts);
        // 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
296
        jack_log("JackNetMasterInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
            fParams.fSendAudioChannels, fParams.fReturnAudioChannels, fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
moret's avatar
moret committed
297
298
299

        JackNetInterface::SetParams();

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

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

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

sletz's avatar
sletz committed
309
        if (fParams.fReturnMidiChannels > 0)
sletz's avatar
sletz committed
310
            fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
sletz's avatar
sletz committed
311

sletz's avatar
sletz committed
312
        try {
sletz's avatar
sletz committed
313

sletz's avatar
sletz committed
314
            // audio net buffers
sletz's avatar
sletz committed
315
            if (fParams.fSendAudioChannels > 0) {
sletz's avatar
sletz committed
316

317
                switch (fParams.fSampleEncoder) {
sletz's avatar
sletz committed
318

319
                    case JackFloatEncoder:
sletz's avatar
sletz committed
320
                        fNetAudioCaptureBuffer = new NetFloatAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
321
                        break;
sletz's avatar
sletz committed
322

323
                    case JackIntEncoder:
sletz's avatar
sletz committed
324
                        fNetAudioCaptureBuffer = new NetIntAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
325
                        break;
sletz's avatar
sletz committed
326

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

sletz's avatar
sletz committed
334
335
                assert(fNetAudioCaptureBuffer);
            }
sletz's avatar
sletz committed
336

sletz's avatar
sletz committed
337
            if (fParams.fReturnAudioChannels > 0) {
sletz's avatar
sletz committed
338

339
                switch (fParams.fSampleEncoder) {
sletz's avatar
sletz committed
340

341
                    case JackFloatEncoder:
sletz's avatar
sletz committed
342
                        fNetAudioPlaybackBuffer = new NetFloatAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
343
                        break;
sletz's avatar
sletz committed
344

345
                    case JackIntEncoder:
sletz's avatar
sletz committed
346
                        fNetAudioPlaybackBuffer = new NetIntAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
347
                        break;
sletz's avatar
sletz committed
348

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

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

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

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

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

sletz's avatar
sletz committed
378
        return true;
sletz's avatar
sletz committed
379

sletz's avatar
sletz committed
380
    error:
sletz's avatar
sletz committed
381
        FreeNetworkBuffers();
sletz's avatar
sletz committed
382
        return false;
moret's avatar
moret committed
383
384
    }

385
    void JackNetMasterInterface::Exit()
386
    {
sletz's avatar
sletz committed
387
        jack_log("JackNetMasterInterface::Exit, ID %u", fParams.fID);
388

sletz's avatar
sletz committed
389
        // stop process
390
        fRunning = false;
391

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

397
        session_params_t net_params;
sletz's avatar
sletz committed
398
        memset(&net_params, 0, sizeof(session_params_t));
399
400
        SessionParamsHToN(&fParams, &net_params);

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

408
409
410
        mcast_socket.Close();
    }

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

sletz's avatar
sletz committed
435
        if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
436
437

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

449
            FatalRecvError();
450
        }
451

452
453
454
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
        return rx_bytes;
455
    }
456

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

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

477
478
    bool JackNetMasterInterface::IsSynched()
    {
479
        return (fCycleOffset <= fMaxCycleOffset);
480
    }
481

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

490
        // Write active ports list
491
        if (fNetAudioPlaybackBuffer) {
492
            fNetAudioPlaybackBuffer->ActivePortsToNetwork(fTxData, fTxHeader.fActivePorts);
493
        }
494

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

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

508
    int JackNetMasterInterface::SyncRecv()
509
    {
sletz's avatar
sletz committed
510
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
sletz's avatar
sletz committed
511
        int rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
512

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

518
        fCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
519

520
        // Read active ports list
521
        if (fNetAudioCaptureBuffer) {
522
            fNetAudioCaptureBuffer->ActivePortsFromNetwork(fRxData, rx_head->fActivePorts);
523
        }
524

525
        if (fCycleOffset < fMaxCycleOffset) {
526
            jack_info("Synching with latency = %d", fCycleOffset);
527
528
529
            return 0;
        } else {
            rx_bytes = Recv(rx_head->fPacketSize, 0);
530
531
            fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
            return rx_bytes;
532
        }
533
    }
534

535
    int JackNetMasterInterface::DataRecv()
536
537
    {
        int rx_bytes = 0;
538
        uint recvd_midi_pckt = 0;
sletz's avatar
sletz committed
539
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
540

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

sletz's avatar
sletz committed
545
            // error here, problem with recv, just skip the cycle (return -1)
546
            if (rx_bytes == SOCKET_ERROR) {
moret's avatar
moret committed
547
                return rx_bytes;
548
            }
sletz's avatar
sletz committed
549

sletz's avatar
sletz committed
550
551
552
553
554
555
            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
556
                        break;
557

sletz's avatar
sletz committed
558
559
                    case 'a':   // audio
                        rx_bytes = AudioRecv(rx_head, fNetAudioPlaybackBuffer);
moret's avatar
moret committed
560
                        break;
561

sletz's avatar
sletz committed
562
                    case 's':   // sync
563
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
sletz's avatar
sletz committed
564
                        return FinishRecv(fNetAudioPlaybackBuffer);
565
566
567
                }
            }
        }
sletz's avatar
sletz committed
568

569
        return rx_bytes;
570
    }
571

572
    void JackNetMasterInterface::EncodeSyncPacket()
573
    {
sletz's avatar
sletz committed
574
575
        // This method contains every step of sync packet informations coding
        // first of all, reset sync packet
576
        memset(fTxData, 0, PACKET_AVAILABLE_SIZE(&fParams));
577

sletz's avatar
sletz committed
578
        // then, first step : transport
579
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
580
            // desactivated...
sletz's avatar
sletz committed
581
            // EncodeTransportData();
sletz's avatar
sletz committed
582
            TransportDataHToN(&fSendTransportData,  &fSendTransportData);
sletz's avatar
sletz committed
583
            // copy to TxBuffer
sletz's avatar
sletz committed
584
            memcpy(fTxData, &fSendTransportData, sizeof(net_transport_data_t));
585
        }
sletz's avatar
sletz committed
586
587
        // then others (freewheel etc.)
        // ...
588
589
    }

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

605
606
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
607
608
    uint JackNetSlaveInterface::fSlaveCounter = 0;

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

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

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

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

639
640
        return true;
    }
641

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

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

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

sletz's avatar
sletz committed
663
        return (try_count != 0);
664
    }
665

666
667
668
669
670
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

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

680
681
        return true;
    }
682

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

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

sletz's avatar
sletz committed
696
        // bind the socket
sletz's avatar
sletz committed
697
698
        if (fSocket.Bind() == SOCKET_ERROR) {
            jack_error("Can't bind the socket : %s", StrError(NET_ERROR_CODE));
699
700
            return NET_SOCKET_ERROR;
        }
701

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

sletz's avatar
sletz committed
706
        // disable local loop
sletz's avatar
sletz committed
707
708
        if (fSocket.SetLocalLoop() == SOCKET_ERROR)
            jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
709

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

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

sletz's avatar
sletz committed
731
        // Time out failure..
sletz's avatar
sletz committed
732
733
        if (try_count == 0) {
            jack_error("Time out error in connect");
sletz's avatar
sletz committed
734
735
            return NET_CONNECT_ERROR;
        }
736

sletz's avatar
sletz committed
737
        // everything is OK, copy parameters
738
        fParams = host_params;
moret's avatar
moret committed
739

sletz's avatar
sletz committed
740