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

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

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

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

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

274
    // JackNetMasterInterface ************************************************************************************
275

276
    bool JackNetMasterInterface::Init()
277
    {
sletz's avatar
sletz committed
278
        jack_log("JackNetMasterInterface::Init : ID %u", fParams.fID);
279

280
        session_params_t host_params;
281
        uint attempt = 0;
282
283
        int rx_bytes = 0;

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

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

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

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

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

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

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

329
        return true;
330
331
    }

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

        JackNetInterface::SetParams();

340
341
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
342

sletz's avatar
sletz committed
343
344
345
        fMaxCycleOffset = fParams.fNetworkLatency;

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

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

sletz's avatar
sletz committed
354
        try {
sletz's avatar
sletz committed
355

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

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

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

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

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

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

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

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

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

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

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

408
409
410
        mcast_socket.Close();
    }

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

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

sletz's avatar
sletz committed
431
    int JackNetMasterInterface::Recv(size_t size, int flags)
432
    {
433
        int rx_bytes;
sletz's avatar
sletz committed
434

sletz's avatar
sletz committed
435
        if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
436
            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) {
451
            FatalSendError();
452
        }
453
        return tx_bytes;
454
    }
455

456
    int JackNetMasterInterface::SyncSend()
457
    {
458
459
        SetRcvTimeOut();
        
460
461
462
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
463
        fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ? 1 : 0;
sletz's avatar
sletz committed
464
        fTxHeader.fPacketSize = fParams.fMtu;
sletz's avatar
sletz committed
465

sletz's avatar
sletz committed
466
        memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
467
        //PacketHeaderDisplay(&fTxHeader);
sletz's avatar
sletz committed
468
        return Send(fTxHeader.fPacketSize, 0);
469
470
471
472
    }

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

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

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

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

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

sletz's avatar
sletz committed
532
533
534
535
536
537
            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
538
                        break;
539

sletz's avatar
sletz committed
540
541
                    case 'a':   // audio
                        rx_bytes = AudioRecv(rx_head, fNetAudioPlaybackBuffer);
moret's avatar
moret committed
542
                        break;
543

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

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

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

604
605
// JackNetSlaveInterface ************************************************************************************************

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

sletz's avatar
sletz committed
608
609
610
611
612
613
614
615
616
617
618
    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();
            }
        }
    }

619
    bool JackNetSlaveInterface::Init()
620
    {
sletz's avatar
sletz committed
621
        jack_log("JackNetSlaveInterface::Init()");
622

sletz's avatar
sletz committed
623
        // set the parameters to send
sletz's avatar
sletz committed
624
        strcpy(fParams.fPacketType, "params");
Stephane Letz's avatar
Stephane Letz committed
625
        fParams.fProtocolVersion = NETWORK_PROTOCOL;
sletz's avatar
sletz committed
626
        SetPacketType(&fParams, SLAVE_AVAILABLE);
627

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

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

649
650
        return true;
    }
651

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

663
        return (SendAvailableToMaster(try_count) == NET_CONNECTED);
664
    }
665

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

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

681
682
        return true;
    }
683

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

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

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

707
708
709
710
        // 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));
        }
711

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

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

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

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

moret's avatar
moret committed
758
    net_status_t JackNetSlaveInterface::SendStartToMaster()
759
    {
sletz's avatar
sletz committed
760
        jack_log("JackNetSlaveInterface::SendStartToMaster");
moret's avatar
moret committed
761

sletz's avatar
sletz committed
762
        // tell the master to start
763
        session_params_t net_params;
sletz's avatar
sletz committed
764
765
        memset(&net_params, 0, sizeof(session_params_t));
        SetPacketType(&fParams, START_MASTER);
766
        SessionParamsHToN(&fParams, &net_params);
767
        if (fSocket.Send(&net_params, sizeof(</