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

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "JackNetInterface.h"
#include "JackException.h"
sletz's avatar
sletz committed
21
22
#include "JackError.h"

23
#include <assert.h>
24
25
26

using namespace std;

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

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

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

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

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

sletz's avatar
sletz committed
55
56
    void JackNetInterface::Initialize()
    {
57
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
231
232
233
234
235
236
237
238
239
240
    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
241
            case JackCeltEncoder:
242
243
244
245
246
247
                return new NetCeltAudioBuffer(&fParams, nports, buffer, fParams.fKBps);
            #endif
        }
        return NULL;
    }

248
    // JackNetMasterInterface ************************************************************************************
249

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

254
        session_params_t host_params;
255
        uint attempt = 0;
256
257
        int rx_bytes = 0;

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

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

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

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

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

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

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

301
        return true;
302
303
    }

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

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

        JackNetInterface::SetParams();

319
320
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
321

sletz's avatar
sletz committed
322
323
324
        fMaxCycleOffset = fParams.fNetworkLatency;

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

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

sletz's avatar
sletz committed
333
        try {
sletz's avatar
sletz committed
334

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

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

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

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

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

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

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

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

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

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

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

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

395
396
397
        mcast_socket.Close();
    }

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

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

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

436
            FatalRecvError();
437
        }
438

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

562
        return rx_bytes;
563
    }
564

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

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

        // Transport not used for now...

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

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

        // 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);
        }
607
    }
608

609
610
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
611
612
    uint JackNetSlaveInterface::fSlaveCounter = 0;

sletz's avatar
sletz committed
613
614
615
616
617
618
619
620
621
622
623
    void JackNetSlaveInterface::InitAPI()
    {
        // open Socket API with the first slave
        if (fSlaveCounter++ == 0) {
            if (SocketAPIInit() < 0) {
                jack_error("Can't init Socket API, exiting...");
                throw std::bad_alloc();
            }
        }
    }

624
    bool JackNetSlaveInterface::Init()
625
    {
sletz's avatar
sletz committed
626
        jack_log("JackNetSlaveInterface::Init()");
627

sletz's avatar
sletz committed
628
        // set the parameters to send
sletz's avatar
sletz committed
629
        strcpy(fParams.fPacketType, "params");
630
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
sletz's avatar
sletz committed
631
        SetPacketType(&fParams, SLAVE_AVAILABLE);
632

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

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

654
655
        return true;
    }
656

657
    // Separate the connection protocol into two separated step
sletz's avatar
sletz committed
658
    bool JackNetSlaveInterface::InitConnection(int time_out_sec)
659
    {
sletz's avatar
sletz committed
660
        jack_log("JackNetSlaveInterface::InitConnection()");
sletz's avatar
sletz committed
661
        uint try_count = (time_out_sec > 0) ? ((1000000 * time_out_sec) / SLAVE_INIT_TIMEOUT) : LONG_MAX;
662

sletz's avatar
sletz committed
663
        // set the parameters to send
sletz's avatar
sletz committed
664
        strcpy(fParams.fPacketType, "params");
665
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
sletz's avatar
sletz committed
666
        SetPacketType(&fParams, SLAVE_AVAILABLE);
667
668

        net_status_t status;
669
        do {
sletz's avatar
sletz committed
670
            // get a master
sletz's avatar
sletz committed
671
            status = SendAvailableToMaster(try_count);
672
            if (status == NET_SOCKET_ERROR) {
673
                return false;
674
            }
675
        }
sletz's avatar
sletz committed
676
        while (status != NET_CONNECTED && --try_count > 0);
677

sletz's avatar
sletz committed
678
        return (try_count != 0);
679
    }
680

681
682
683
684
685
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

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

695
696
        return true;
    }
697

sletz's avatar
sletz committed
698
    net_status_t JackNetSlaveInterface::SendAvailableToMaster(long try_count)
699
    {
sletz's avatar
sletz committed
700
        jack_log("JackNetSlaveInterface::SendAvailableToMaster()");
sletz's avatar
sletz committed
701
        // utility
702
        session_params_t host_params;
703
704
        int rx_bytes = 0;

sletz's avatar
sletz committed
705
        // socket
sletz's avatar
sletz committed
706
707
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Fatal error : network unreachable - %s", StrError(NET_ERROR_CODE));
708
            return NET_SOCKET_ERROR;
709
710
        }

sletz's avatar
sletz committed
711
712
713
714
715
716
717
718
        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;
            }
719
        }
720

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

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

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

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

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

sletz's avatar
sletz committed
756
        // everything is OK, copy parameters
757
        fParams = host_params;
moret's avatar
moret committed
758

sletz's avatar
sletz committed
759
        // connect the socket
sletz's avatar
sletz committed
760
761
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Error in connect : %s", StrError(NET_ERROR_CODE));
762
            return NET_CONNECT_ERROR;
763
        }
moret's avatar
moret committed
764
        return NET_CONNECTED;
765
766
    }

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

sletz's avatar
sletz committed
771
        // tell the master to start
772
        session_params_t net_params;
sletz's avatar
sletz committed
773
774
        memset(&net_params, 0, sizeof(session_params_t));
        SetPacketType(&fParams, START_MASTER);
775
        SessionParamsHToN(&fParams, &net_params);
776
        if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
777
778
            jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
            return (fSocket.GetError() == NET_CONN_ERROR) ? NET_ERROR : NET_SEND_ERROR;
779
        }