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

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

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

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

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

23
24
25
26
#if HAVE_CELT
#include "JackNetCelt.h"
#endif

27
28
29
30
#if HAVE_OPUS
#include "JackNetOpus.h"
#endif

31
#include <assert.h>
32
33
34

using namespace std;

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

41
42
43
44
namespace Jack
{
    // JackNetInterface*******************************************

45
46
    JackNetInterface::JackNetInterface() : fSocket()
    {
sletz's avatar
sletz committed
47
        Initialize();
48
49
    }

sletz's avatar
sletz committed
50
    JackNetInterface::JackNetInterface(const char* multicast_ip, int port) : fSocket(multicast_ip, port)
51
    {
52
        strcpy(fMulticastIP, multicast_ip);
sletz's avatar
sletz committed
53
        Initialize();
54
55
    }

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

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

sletz's avatar
sletz committed
77
78
79
80
81
82
83
84
85
86
87
    void JackNetInterface::FreeNetworkBuffers()
    {
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
    }
sletz's avatar
sletz committed
88

89
90
    JackNetInterface::~JackNetInterface()
    {
sletz's avatar
sletz committed
91
        jack_log("JackNetInterface::~JackNetInterface");
moret's avatar
moret committed
92

93
94
95
96
97
98
99
100
101
        fSocket.Close();
        delete[] fTxBuffer;
        delete[] fRxBuffer;
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
    }

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

sletz's avatar
sletz committed
110
        // midi
sletz's avatar
sletz committed
111
        float midi_size = (fNetMidiCaptureBuffer)
sletz's avatar
sletz committed
112
113
                        ? fNetMidiCaptureBuffer->GetCycleSize()
                        : (fNetMidiPlaybackBuffer) ? fNetMidiPlaybackBuffer->GetCycleSize() : 0;
sletz's avatar
sletz committed
114
        jack_log("midi_size %f", midi_size);
sletz's avatar
sletz committed
115

sletz's avatar
sletz committed
116
117
        // bufsize = sync + audio + midi
        int bufsize = NETWORK_MAX_LATENCY * (fParams.fMtu + (int)audio_size + (int)midi_size);
sletz's avatar
sletz committed
118
        jack_log("SetNetBufferSize bufsize = %d", bufsize);
moret's avatar
moret committed
119

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

sletz's avatar
sletz committed
125
        // rx buffer
126
        if (fSocket.SetOption(SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR) {
127
            return SOCKET_ERROR;
128
        }
moret's avatar
moret committed
129

130
        return 0;
moret's avatar
moret committed
131
132
    }

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

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

sletz's avatar
sletz committed
151
        // network buffers
152
153
        fTxBuffer = new char[fParams.fMtu];
        fRxBuffer = new char[fParams.fMtu];
sletz's avatar
sletz committed
154
155
        assert(fTxBuffer);
        assert(fRxBuffer);
156

sletz's avatar
sletz committed
157
        // net audio/midi buffers'addresses
sletz's avatar
sletz committed
158
159
        fTxData = fTxBuffer + HEADER_SIZE;
        fRxData = fRxBuffer + HEADER_SIZE;
sletz's avatar
sletz committed
160

sletz's avatar
sletz committed
161
        return true;
162
163
    }

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

            for (uint subproc = 0; subproc < fTxHeader.fNumPacket; subproc++) {
                fTxHeader.fSubCycle = subproc;
                fTxHeader.fIsLastPckt = ((subproc == (fTxHeader.fNumPacket - 1)) && audio_channels == 0) ? 1 : 0;
                fTxHeader.fPacketSize = HEADER_SIZE + buffer->RenderToNetwork(subproc, data_size);
                memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
Stephane Letz's avatar
Stephane Letz committed
177
                 //PacketHeaderDisplay(&fTxHeader);
178
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
179
                    return SOCKET_ERROR;
180
                }
sletz's avatar
sletz committed
181
182
183
184
185
186
187
188
189
190
            }
        }
        return 0;
    }

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

            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);
199
                //PacketHeaderDisplay(&fTxHeader);
200
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
201
                    return SOCKET_ERROR;
202
                }
sletz's avatar
sletz committed
203
204
205
206
207
208
209
210
211
212
213
            }
        }
        return 0;
    }

    int JackNetInterface::MidiRecv(packet_header_t* rx_head, NetMidiBuffer* buffer, uint& recvd_midi_pckt)
    {
        int rx_bytes = Recv(rx_head->fPacketSize, 0);
        fRxHeader.fCycle = rx_head->fCycle;
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
        buffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
sletz's avatar
sletz committed
214
        
sletz's avatar
sletz committed
215
        // Last midi packet is received, so finish rendering...
216
        if (++recvd_midi_pckt == rx_head->fNumPacket) {
sletz's avatar
sletz committed
217
            buffer->RenderToJackPorts();
218
        }
Stephane Letz's avatar
Stephane Letz committed
219
        //PacketHeaderDisplay(rx_head);
sletz's avatar
sletz committed
220
221
222
223
224
225
226
227
228
229
        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;
230
        fRxHeader.fFrames = rx_head->fFrames;
sletz's avatar
sletz committed
231
        rx_bytes = buffer->RenderFromNetwork(rx_head->fCycle, rx_head->fSubCycle, fRxHeader.fActivePorts);
sletz's avatar
sletz committed
232
        
sletz's avatar
sletz committed
233
        // Last audio packet is received, so finish rendering...
234
        if (fRxHeader.fIsLastPckt) {
235
            buffer->RenderToJackPorts(fRxHeader.fFrames);
236
        }
Stephane Letz's avatar
Stephane Letz committed
237
        //PacketHeaderDisplay(rx_head);
sletz's avatar
sletz committed
238
239
240
241
242
        return rx_bytes;
    }

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

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

285
    // JackNetMasterInterface ************************************************************************************
286

287
    bool JackNetMasterInterface::Init()
288
    {
sletz's avatar
sletz committed
289
        jack_log("JackNetMasterInterface::Init : ID %u", fParams.fID);
290

291
        session_params_t host_params;
292
        uint attempt = 0;
293
294
        int rx_bytes = 0;

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

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

sletz's avatar
sletz committed
306
        // connect
sletz's avatar
sletz committed
307
308
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Can't connect : %s", StrError(NET_ERROR_CODE));
309
310
            return false;
        }
311

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

321
            if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
322
                jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
323
            }
324

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

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

340
        return true;
341
342
    }

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

        JackNetInterface::SetParams();

351
352
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
353

sletz's avatar
sletz committed
354
355
356
        fMaxCycleOffset = fParams.fNetworkLatency;

        // midi net buffers
357
        if (fParams.fSendMidiChannels > 0) {
sletz's avatar
sletz committed
358
            fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fTxData);
359
        }
sletz's avatar
sletz committed
360

361
        if (fParams.fReturnMidiChannels > 0) {
sletz's avatar
sletz committed
362
            fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
363
        }
sletz's avatar
sletz committed
364

sletz's avatar
sletz committed
365
        try {
sletz's avatar
sletz committed
366

sletz's avatar
sletz committed
367
            // audio net buffers
sletz's avatar
sletz committed
368
            if (fParams.fSendAudioChannels > 0) {
369
                fNetAudioCaptureBuffer = AudioBufferFactory(fParams.fSendAudioChannels, fTxData);
sletz's avatar
sletz committed
370
371
                assert(fNetAudioCaptureBuffer);
            }
sletz's avatar
sletz committed
372

sletz's avatar
sletz committed
373
            if (fParams.fReturnAudioChannels > 0) {
374
                fNetAudioPlaybackBuffer = AudioBufferFactory(fParams.fReturnAudioChannels, fRxData);
sletz's avatar
sletz committed
375
376
                assert(fNetAudioPlaybackBuffer);
            }
sletz's avatar
sletz committed
377

sletz's avatar
sletz committed
378
        } catch (exception&) {
Stephane Letz's avatar
Stephane Letz committed
379
            jack_error("NetAudioBuffer on master allocation error...");
sletz's avatar
sletz committed
380
381
            return false;
        }
moret's avatar
moret committed
382

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

sletz's avatar
sletz committed
389
        return true;
sletz's avatar
sletz committed
390

sletz's avatar
sletz committed
391
    error:
sletz's avatar
sletz committed
392
        FreeNetworkBuffers();
sletz's avatar
sletz committed
393
        return false;
moret's avatar
moret committed
394
395
    }

396
    void JackNetMasterInterface::Exit()
397
    {
sletz's avatar
sletz committed
398
        jack_log("JackNetMasterInterface::Exit, ID %u", fParams.fID);
399

sletz's avatar
sletz committed
400
        // stop process
401
        fRunning = false;
402

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

408
        session_params_t net_params;
sletz's avatar
sletz committed
409
        memset(&net_params, 0, sizeof(session_params_t));
410
411
        SessionParamsHToN(&fParams, &net_params);

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

419
420
421
        mcast_socket.Close();
    }

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

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

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

sletz's avatar
sletz committed
461
        if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
462
            FatalSendError();
463
        }
464
        return tx_bytes;
465
    }
466

467
    int JackNetMasterInterface::SyncSend()
468
    {
469
470
        SetRcvTimeOut();
        
471
472
473
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
474
        fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ? 1 : 0;
Stephane Letz's avatar
Stephane Letz committed
475
476
        fTxHeader.fPacketSize = HEADER_SIZE + fTxHeader.fActivePorts * sizeof(int); // Data part is used to encode active ports
      
sletz's avatar
sletz committed
477
        memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
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
496
497

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

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

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

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

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

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

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

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

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

616
617
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
618
619
    uint JackNetSlaveInterface::fSlaveCounter = 0;

sletz's avatar
sletz committed
620
621
622
623
624
625
626
627
628
629
630
    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();
            }
        }
    }

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

sletz's avatar
sletz committed
635
        // set the parameters to send
sletz's avatar
sletz committed
636
        strcpy(fParams.fPacketType, "params");
Stephane Letz's avatar
Stephane Letz committed
637
        fParams.fProtocolVersion = NETWORK_PROTOCOL;
sletz's avatar
sletz committed
638
        SetPacketType(&fParams, SLAVE_AVAILABLE);
639

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

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

661
662
        return true;
    }
663

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

675
        return (SendAvailableToMaster(try_count) == NET_CONNECTED);
676
    }
677

678
679
680
681
682
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

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

693
694
        return true;
    }
695

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

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

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

719
720
721
722
        // timeout on receive (for init)
        if (fSocket.SetTimeOut(SLAVE_INIT_TIMEOUT) == SOCKET_ERROR) {
            jack_error("Can't set init timeout : %s", StrError(NET_ERROR_CODE));
        }
723

sletz's avatar
sletz committed
724
        // disable local loop
725
        if (fSocket.SetLocalLoop() == SOCKET_ERROR) {
sletz's avatar
sletz committed
726
            jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
727
        }
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
        
732
        do {
sletz's avatar
sletz committed
733
            // send 'available'
734
            session_params_t net_params;
sletz's avatar
sletz committed
735
            memset(&net_params, 0, sizeof(session_params_t));
736
            SessionParamsHToN(&fParams, &net_params);
sletz's avatar
sletz committed
737
            if (fSocket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR) {
sletz's avatar
sletz committed
738
                jack_error("Error in data send : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
739
            }
740

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

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

moret's avatar
moret committed
770
    net_status_t JackNetSlaveInterface::SendStartToMaster()
771
    {
sletz's avatar
sletz committed