JackNetInterface.cpp 34.3 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
        fSetTimeOut = false;
58
59
60
61
62
63
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
64
65
        memset(&fSendTransportData, 0, sizeof(net_transport_data_t));
        memset(&fReturnTransportData, 0, sizeof(net_transport_data_t));
66
        fPacketTimeOut = PACKET_TIMEOUT * NETWORK_DEFAULT_LATENCY;
67
68
    }

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

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

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

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

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

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

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

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

122
        return 0;
moret's avatar
moret committed
123
124
    }

sletz's avatar
sletz committed
125
    bool JackNetInterface::SetParams()
moret's avatar
moret committed
126
    {
sletz's avatar
sletz committed
127
        // TX header init
Stephane Letz's avatar
Stephane Letz committed
128
        memset(&fTxHeader, 0, sizeof(fTxHeader));
sletz's avatar
sletz committed
129
        strcpy(fTxHeader.fPacketType, "header");
130
131
132
        fTxHeader.fID = fParams.fID;
        fTxHeader.fCycle = 0;
        fTxHeader.fSubCycle = 0;
moret's avatar
moret committed
133
        fTxHeader.fIsLastPckt = 0;
134

sletz's avatar
sletz committed
135
        // RX header init
Stephane Letz's avatar
Stephane Letz committed
136
        memset(&fRxHeader, 0, sizeof(fTxHeader));
sletz's avatar
sletz committed
137
        strcpy(fRxHeader.fPacketType, "header");
138
139
140
        fRxHeader.fID = fParams.fID;
        fRxHeader.fCycle = 0;
        fRxHeader.fSubCycle = 0;
moret's avatar
moret committed
141
        fRxHeader.fIsLastPckt = 0;
142

sletz's avatar
sletz committed
143
        // network buffers
144
145
        fTxBuffer = new char[fParams.fMtu];
        fRxBuffer = new char[fParams.fMtu];
sletz's avatar
sletz committed
146
147
        assert(fTxBuffer);
        assert(fRxBuffer);
148

sletz's avatar
sletz committed
149
        // net audio/midi buffers'addresses
sletz's avatar
sletz committed
150
151
        fTxData = fTxBuffer + HEADER_SIZE;
        fRxData = fRxBuffer + HEADER_SIZE;
sletz's avatar
sletz committed
152

sletz's avatar
sletz committed
153
        return true;
154
155
    }

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

            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
169
                 //PacketHeaderDisplay(&fTxHeader);
170
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
171
                    return SOCKET_ERROR;
172
                }
sletz's avatar
sletz committed
173
174
175
176
177
178
179
180
181
182
            }
        }
        return 0;
    }

    int JackNetInterface::AudioSend(NetAudioBuffer* buffer, int audio_channels)
    {
        // audio
        if (audio_channels > 0) {
            fTxHeader.fDataType = 'a';
183
            fTxHeader.fActivePorts = buffer->RenderFromJackPorts(fTxHeader.fFrames);
sletz's avatar
sletz committed
184
            fTxHeader.fNumPacket = buffer->GetNumPackets(fTxHeader.fActivePorts);
sletz's avatar
sletz committed
185
186
187
188
189
190

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

    int JackNetInterface::FinishRecv(NetAudioBuffer* buffer)
    {
235
236
237
238
239
        if (buffer) {
            buffer->RenderToJackPorts(fRxHeader.fFrames);
        } else {
            jack_error("FinishRecv with null buffer...");
        }
240
        return DATA_PACKET_ERROR;
sletz's avatar
sletz committed
241
242
    }

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

277
    // JackNetMasterInterface ************************************************************************************
278

279
    bool JackNetMasterInterface::Init()
280
    {
sletz's avatar
sletz committed
281
        jack_log("JackNetMasterInterface::Init : ID %u", fParams.fID);
282

283
        session_params_t host_params;
284
        uint attempt = 0;
285
286
        int rx_bytes = 0;

sletz's avatar
sletz committed
287
        // socket
sletz's avatar
sletz committed
288
289
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
290
            return false;
291
292
        }

sletz's avatar
sletz committed
293
        // timeout on receive (for init)
294
295
296
        if (fSocket.SetTimeOut(MASTER_INIT_TIMEOUT) < 0) {
            jack_error("Can't set init timeout : %s", StrError(NET_ERROR_CODE));
        }
297

sletz's avatar
sletz committed
298
        // connect
sletz's avatar
sletz committed
299
300
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Can't connect : %s", StrError(NET_ERROR_CODE));
301
302
            return false;
        }
303

sletz's avatar
sletz committed
304
        // send 'SLAVE_SETUP' until 'START_MASTER' received
sletz's avatar
sletz committed
305
        jack_info("Sending parameters to %s...", fParams.fSlaveNetName);
306
307
        do
        {
308
            session_params_t net_params;
sletz's avatar
sletz committed
309
310
            memset(&net_params, 0, sizeof(session_params_t));
            SetPacketType(&fParams, SLAVE_SETUP);
311
            SessionParamsHToN(&fParams, &net_params);
312

313
            if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
314
                jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
315
            }
316

sletz's avatar
sletz committed
317
            memset(&net_params, 0, sizeof(session_params_t));
318
            if (((rx_bytes = fSocket.Recv(&net_params, sizeof(session_params_t), 0)) == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
sletz's avatar
sletz committed
319
                jack_error("Problem with network");
320
                return false;
321
            }
322

323
            SessionParamsNToH(&net_params, &host_params);
324
        }
sletz's avatar
sletz committed
325
        while ((GetPacketType(&host_params) != START_MASTER) && (++attempt < SLAVE_SETUP_RETRY));
sletz's avatar
sletz committed
326
        
sletz's avatar
sletz committed
327
328
        if (attempt == SLAVE_SETUP_RETRY) {
            jack_error("Slave doesn't respond, exiting");
329
            return false;
330
331
        }

332
        return true;
333
334
    }

sletz's avatar
sletz committed
335
    bool JackNetMasterInterface::SetParams()
moret's avatar
moret committed
336
    {
sletz's avatar
sletz committed
337
        jack_log("JackNetMasterInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
338
339
            fParams.fSendAudioChannels, fParams.fReturnAudioChannels,
            fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
moret's avatar
moret committed
340
341
342

        JackNetInterface::SetParams();

343
344
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
345

sletz's avatar
sletz committed
346
347
348
        fMaxCycleOffset = fParams.fNetworkLatency;

        // midi net buffers
349
        if (fParams.fSendMidiChannels > 0) {
sletz's avatar
sletz committed
350
            fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fTxData);
351
        }
sletz's avatar
sletz committed
352

353
        if (fParams.fReturnMidiChannels > 0) {
sletz's avatar
sletz committed
354
            fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
355
        }
sletz's avatar
sletz committed
356

sletz's avatar
sletz committed
357
        try {
sletz's avatar
sletz committed
358

sletz's avatar
sletz committed
359
            // audio net buffers
sletz's avatar
sletz committed
360
            if (fParams.fSendAudioChannels > 0) {
361
                fNetAudioCaptureBuffer = AudioBufferFactory(fParams.fSendAudioChannels, fTxData);
sletz's avatar
sletz committed
362
363
                assert(fNetAudioCaptureBuffer);
            }
sletz's avatar
sletz committed
364

sletz's avatar
sletz committed
365
            if (fParams.fReturnAudioChannels > 0) {
366
                fNetAudioPlaybackBuffer = AudioBufferFactory(fParams.fReturnAudioChannels, fRxData);
sletz's avatar
sletz committed
367
368
                assert(fNetAudioPlaybackBuffer);
            }
sletz's avatar
sletz committed
369

sletz's avatar
sletz committed
370
        } catch (exception&) {
Stephane Letz's avatar
Stephane Letz committed
371
            jack_error("NetAudioBuffer on master allocation error...");
sletz's avatar
sletz committed
372
373
            return false;
        }
moret's avatar
moret committed
374

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

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

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

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

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

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

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

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

411
412
413
        mcast_socket.Close();
    }

414
    void JackNetMasterInterface::FatalRecvError()
sletz's avatar
sletz committed
415
    {
sletz's avatar
sletz committed
416
        // fatal connection issue, exit
417
418
419
420
421
422
423
424
425
426
427
        jack_error("Recv connection lost error = %s, '%s' exiting", StrError(NET_ERROR_CODE), fParams.fName);
        // ask to the manager to properly remove the master
        Exit();
        // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
        ThreadExit();
    }

     void JackNetMasterInterface::FatalSendError()
    {
        // fatal connection issue, exit
        jack_error("Send connection lost error = %s, '%s' exiting", StrError(NET_ERROR_CODE), fParams.fName);
sletz's avatar
sletz committed
428
        // ask to the manager to properly remove the master
sletz's avatar
sletz committed
429
430
431
432
433
        Exit();
        // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
        ThreadExit();
    }

sletz's avatar
sletz committed
434
    int JackNetMasterInterface::Recv(size_t size, int flags)
435
    {
436
        int rx_bytes;
sletz's avatar
sletz committed
437

sletz's avatar
sletz committed
438
        if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
439
            FatalRecvError();
440
        }
441
  
442
443
444
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
        return rx_bytes;
445
    }
446

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

sletz's avatar
sletz committed
453
        if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
454
            FatalSendError();
455
        }
456
        return tx_bytes;
457
    }
458

459
    int JackNetMasterInterface::SyncSend()
460
    {
461
462
        SetRcvTimeOut();
        
463
464
465
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
466
        fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ? 1 : 0;
Stephane Letz's avatar
Stephane Letz committed
467
468
        fTxHeader.fPacketSize = HEADER_SIZE + fTxHeader.fActivePorts * sizeof(int); // Data part is used to encode active ports
      
sletz's avatar
sletz committed
469
        memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
470
        //PacketHeaderDisplay(&fTxHeader);
sletz's avatar
sletz committed
471
        return Send(fTxHeader.fPacketSize, 0);
472
473
474
475
    }

    int JackNetMasterInterface::DataSend()
    {
476
        if (MidiSend(fNetMidiCaptureBuffer, fParams.fSendMidiChannels, fParams.fSendAudioChannels) == SOCKET_ERROR) {
sletz's avatar
sletz committed
477
            return SOCKET_ERROR;
478
        }
sletz's avatar
sletz committed
479
        return AudioSend(fNetAudioCaptureBuffer, fParams.fSendAudioChannels);
480
481
    }

482
    int JackNetMasterInterface::SyncRecv()
483
    {
sletz's avatar
sletz committed
484
        int rx_bytes = 0;
sletz's avatar
sletz committed
485
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
sletz's avatar
sletz committed
486
487
488
489

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

507
        if (fCurrentCycleOffset < fMaxCycleOffset && !fSynched) {
sletz's avatar
sletz committed
508
            jack_info("Synching with latency = %d", fCurrentCycleOffset);
Stephane Letz's avatar
Stephane Letz committed
509
            return NET_SYNCHING;
510
        } else {
511
512
513
514
            if (fCurrentCycleOffset == fMaxCycleOffset) {
                // when the sync offset is reached 
                fSynched = true;
            }
515
            rx_bytes = Recv(rx_head->fPacketSize, 0);
516
517
            fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
            return rx_bytes;
518
        }
519
    }
520

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

sletz's avatar
sletz committed
536
537
538
539
540
541
            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
542
                        break;
543

sletz's avatar
sletz committed
544
545
                    case 'a':   // audio
                        rx_bytes = AudioRecv(rx_head, fNetAudioPlaybackBuffer);
moret's avatar
moret committed
546
                        break;
547

sletz's avatar
sletz committed
548
                    case 's':   // sync
549
                        jack_info("NetMaster : missing last data packet from '%s'", fParams.fName);
sletz's avatar
sletz committed
550
                        return FinishRecv(fNetAudioPlaybackBuffer);
551
552
553
                }
            }
        }
sletz's avatar
sletz committed
554
   
555
        return rx_bytes;
556
    }
557

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

Stephane Letz's avatar
Stephane Letz committed
582
    void JackNetMasterInterface::DecodeSyncPacket(int& frames)
583
    {
sletz's avatar
sletz committed
584
        // This method contains every step of sync packet informations decoding process
585
586
587
        
        // Transport not used for now...
        /*
sletz's avatar
sletz committed
588
        // first : transport
589
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
590
            // copy received transport data to transport data structure
sletz's avatar
sletz committed
591
592
            memcpy(&fReturnTransportData, fRxData, sizeof(net_transport_data_t));
            TransportDataNToH(&fReturnTransportData,  &fReturnTransportData);
sletz's avatar
sletz committed
593
            DecodeTransportData();
594
        }
sletz's avatar
sletz committed
595
596
        // then others
        // ...
597
598
        */
       
sletz's avatar
sletz committed
599
600
601
602
603
604
        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
605
        frames = rx_head->fFrames;
606
    }
607

608
609
// JackNetSlaveInterface ************************************************************************************************

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

sletz's avatar
sletz committed
612
613
614
615
616
617
618
619
620
621
622
    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();
            }
        }
    }

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

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

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

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

653
654
        return true;
    }
655

656
    // Separate the connection protocol into two separated step
sletz's avatar
sletz committed
657
    bool JackNetSlaveInterface::InitConnection(int time_out_sec)
658
    {
659
        jack_log("JackNetSlaveInterface::InitConnection time_out_sec = %d", time_out_sec);
660
        int try_count = (time_out_sec > 0) ? int((1000000.f * float(time_out_sec)) / float(SLAVE_INIT_TIMEOUT)) : INT_MAX;
661
  
sletz's avatar
sletz committed
662
        // set the parameters to send
sletz's avatar
sletz committed
663
        strcpy(fParams.fPacketType, "params");
Stephane Letz's avatar
Stephane Letz committed
664
        fParams.fProtocolVersion = NETWORK_PROTOCOL;
sletz's avatar
sletz committed
665
        SetPacketType(&fParams, SLAVE_AVAILABLE);
666

667
        return (SendAvailableToMaster(try_count) == NET_CONNECTED);
668
    }
669

670
671
672
673
674
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

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

685
686
        return true;
    }
687

Stephane Letz's avatar
Stephane Letz committed
688
    net_status_t JackNetSlaveInterface::SendAvailableToMaster(int try_count)
689
    {
690
        jack_log("JackNetSlaveInterface::SendAvailableToMaster try_count = %d", try_count);
sletz's avatar
sletz committed
691
        // utility
692
        session_params_t host_params;
693
694
        int rx_bytes = 0;

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

sletz's avatar
sletz committed
701
702
703
704
705
706
707
708
        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;
            }
709
        }
710

711
712
713
714
        // 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));
        }
715

sletz's avatar
sletz committed
716
        // disable local loop
717
        if (fSocket.SetLocalLoop() == SOCKET_ERROR) {
sletz's avatar
sletz committed
718
            jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
719
        }
720

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

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

sletz's avatar
sletz committed
750
        // everything is OK, copy parameters
751
        fParams = host_params;
Stephane Letz's avatar
Stephane Letz committed
752
     
sletz's avatar
sletz committed
753
        // connect the socket
sletz's avatar
sletz committed
754
755
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Error in connect : %s", StrError(NET_ERROR_CODE));
756
            return NET_CONNECT_ERROR;
757
        }
758
        
moret's avatar
moret committed
759
        return NET_CONNECTED;
760
761
    }

moret's avatar
moret committed
762
    net_status_t JackNetSlaveInterface::SendStartToMaster()
763
    {
sletz's avatar
sletz committed
764
        jack_log("JackNetSlaveInterface::SendStartToMaster");
moret's avatar
moret committed
765

sletz's avatar
sletz committed
766
        // tell the master to start