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

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

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

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

#include "JackNetInterface.h"
#include "JackException.h"
21
#include "JackPlatformPlug.h"
22
#include <assert.h>
23
24
25

using namespace std;

sletz's avatar
sletz committed
26

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

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

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

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

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

sletz's avatar
sletz committed
55
56
    void JackNetInterface::Initialize()
    {
57
58
59
60
61
62
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
63
64
        memset(&fSendTransportData, 0, sizeof(net_transport_data_t));
        memset(&fReturnTransportData, 0, sizeof(net_transport_data_t));
65
66
    }

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

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

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

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

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

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

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

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

120
        return 0;
moret's avatar
moret committed
121
122
    }

sletz's avatar
sletz committed
123
    bool JackNetInterface::SetParams()
moret's avatar
moret committed
124
    {
sletz's avatar
sletz committed
125
        // TX header init
sletz's avatar
sletz committed
126
        strcpy(fTxHeader.fPacketType, "header");
127
128
129
        fTxHeader.fID = fParams.fID;
        fTxHeader.fCycle = 0;
        fTxHeader.fSubCycle = 0;
moret's avatar
moret committed
130
        fTxHeader.fIsLastPckt = 0;
131

sletz's avatar
sletz committed
132
        // RX header init
sletz's avatar
sletz committed
133
        strcpy(fRxHeader.fPacketType, "header");
134
135
136
        fRxHeader.fID = fParams.fID;
        fRxHeader.fCycle = 0;
        fRxHeader.fSubCycle = 0;
moret's avatar
moret committed
137
        fRxHeader.fIsLastPckt = 0;
138

sletz's avatar
sletz committed
139
        // network buffers
140
141
        fTxBuffer = new char[fParams.fMtu];
        fRxBuffer = new char[fParams.fMtu];
sletz's avatar
sletz committed
142
143
        assert(fTxBuffer);
        assert(fRxBuffer);
144

sletz's avatar
sletz committed
145
        // net audio/midi buffers'addresses
sletz's avatar
sletz committed
146
147
        fTxData = fTxBuffer + HEADER_SIZE;
        fRxData = fRxBuffer + HEADER_SIZE;
sletz's avatar
sletz committed
148

sletz's avatar
sletz committed
149
        return true;
150
151
    }

sletz's avatar
sletz committed
152
153
154
155
156
157
    int JackNetInterface::MidiSend(NetMidiBuffer* buffer, int midi_channnels, int audio_channels)
    {
        if (midi_channnels > 0) {
            // set global header fields and get the number of midi packets
            fTxHeader.fDataType = 'm';
            uint data_size = buffer->RenderFromJackPorts();
158
            fTxHeader.fNumPacket = buffer->GetNumPackets(data_size, PACKET_AVAILABLE_SIZE(&fParams));
sletz's avatar
sletz committed
159
160
161
162
163
164

            for (uint subproc = 0; subproc < fTxHeader.fNumPacket; subproc++) {
                fTxHeader.fSubCycle = subproc;
                fTxHeader.fIsLastPckt = ((subproc == (fTxHeader.fNumPacket - 1)) && audio_channels == 0) ? 1 : 0;
                fTxHeader.fPacketSize = HEADER_SIZE + buffer->RenderToNetwork(subproc, data_size);
                memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
165
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
166
                    return SOCKET_ERROR;
167
                }
sletz's avatar
sletz committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
            }
        }
        return 0;
    }

    int JackNetInterface::AudioSend(NetAudioBuffer* buffer, int audio_channels)
    {
        // audio
        if (audio_channels > 0) {
            fTxHeader.fDataType = 'a';
            buffer->RenderFromJackPorts();
            fTxHeader.fNumPacket = buffer->GetNumPackets();

            for (uint subproc = 0; subproc < fTxHeader.fNumPacket; subproc++) {
                fTxHeader.fSubCycle = subproc;
                fTxHeader.fIsLastPckt = (subproc == (fTxHeader.fNumPacket - 1)) ? 1 : 0;
                fTxHeader.fPacketSize = HEADER_SIZE + buffer->RenderToNetwork(subproc, fTxHeader.fActivePorts);
                memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
                // PacketHeaderDisplay(&fTxHeader);
187
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
188
                    return SOCKET_ERROR;
189
                }
sletz's avatar
sletz committed
190
191
192
193
194
195
196
197
198
199
200
201
            }
        }
        return 0;
    }

    int JackNetInterface::MidiRecv(packet_header_t* rx_head, NetMidiBuffer* buffer, uint& recvd_midi_pckt)
    {
        int rx_bytes = Recv(rx_head->fPacketSize, 0);
        fRxHeader.fCycle = rx_head->fCycle;
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
        buffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
        // Last midi packet is received, so finish rendering...
202
        if (++recvd_midi_pckt == rx_head->fNumPacket) {
sletz's avatar
sletz committed
203
            buffer->RenderToJackPorts();
204
        }
sletz's avatar
sletz committed
205
206
207
208
209
210
211
212
213
214
215
216
        return rx_bytes;
    }

    int JackNetInterface::AudioRecv(packet_header_t* rx_head, NetAudioBuffer* buffer)
    {
        int rx_bytes = Recv(rx_head->fPacketSize, 0);
        fRxHeader.fCycle = rx_head->fCycle;
        fRxHeader.fSubCycle = rx_head->fSubCycle;
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
        fRxHeader.fActivePorts = rx_head->fActivePorts;
        rx_bytes = buffer->RenderFromNetwork(rx_head->fCycle, rx_head->fSubCycle, rx_bytes - HEADER_SIZE, fRxHeader.fActivePorts);
        // Last audio packet is received, so finish rendering...
217
        if (fRxHeader.fIsLastPckt) {
sletz's avatar
sletz committed
218
            buffer->RenderToJackPorts();
219
        }
sletz's avatar
sletz committed
220
221
222
223
224
225
226
227
228
229
        return rx_bytes;
    }

    int JackNetInterface::FinishRecv(NetAudioBuffer* buffer)
    {
        // TODO : finish midi and audio rendering ?
        buffer->RenderToJackPorts();
        return NET_PACKET_ERROR;
    }

230
    // JackNetMasterInterface ************************************************************************************
231

232
    bool JackNetMasterInterface::Init()
233
    {
sletz's avatar
sletz committed
234
        jack_log("JackNetMasterInterface::Init, ID %u", fParams.fID);
235

236
        session_params_t host_params;
237
        uint attempt = 0;
238
239
        int rx_bytes = 0;

sletz's avatar
sletz committed
240
        // socket
sletz's avatar
sletz committed
241
242
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
243
            return false;
244
245
        }

sletz's avatar
sletz committed
246
        // timeout on receive (for init)
sletz's avatar
sletz committed
247
248
        if (fSocket.SetTimeOut(MASTER_INIT_TIMEOUT) < 0)
            jack_error("Can't set timeout : %s", StrError(NET_ERROR_CODE));
249

sletz's avatar
sletz committed
250
        // connect
sletz's avatar
sletz committed
251
252
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Can't connect : %s", StrError(NET_ERROR_CODE));
253
254
            return false;
        }
255

sletz's avatar
sletz committed
256
        // send 'SLAVE_SETUP' until 'START_MASTER' received
sletz's avatar
sletz committed
257
        jack_info("Sending parameters to %s...", fParams.fSlaveNetName);
258
259
        do
        {
260
            session_params_t net_params;
sletz's avatar
sletz committed
261
262
            memset(&net_params, 0, sizeof(session_params_t));
            SetPacketType(&fParams, SLAVE_SETUP);
263
            SessionParamsHToN(&fParams, &net_params);
264

265
            if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
266
                jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
267
            }
268

sletz's avatar
sletz committed
269
            memset(&net_params, 0, sizeof(session_params_t));
270
            if (((rx_bytes = fSocket.Recv(&net_params, sizeof(session_params_t), 0)) == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
sletz's avatar
sletz committed
271
                jack_error("Problem with network");
272
                return false;
273
            }
274

275
            SessionParamsNToH(&net_params, &host_params);
276
        }
sletz's avatar
sletz committed
277
278
279
        while ((GetPacketType(&host_params) != START_MASTER) && (++attempt < SLAVE_SETUP_RETRY));
        if (attempt == SLAVE_SETUP_RETRY) {
            jack_error("Slave doesn't respond, exiting");
280
            return false;
281
282
        }

283
        return true;
284
285
    }

sletz's avatar
sletz committed
286
287
288
289
290
291
    int JackNetMasterInterface::SetRxTimeout()
    {
        jack_log("JackNetMasterInterface::SetRxTimeout");
        float time = 3 * 1000000.f * (static_cast<float>(fParams.fPeriodSize) / static_cast<float>(fParams.fSampleRate));
        return fSocket.SetTimeOut(static_cast<int>(time));
    }
moret's avatar
moret committed
292

sletz's avatar
sletz committed
293
    bool JackNetMasterInterface::SetParams()
moret's avatar
moret committed
294
    {
sletz's avatar
sletz committed
295
296
        jack_log("JackNetMasterInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
            fParams.fSendAudioChannels, fParams.fReturnAudioChannels, fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
moret's avatar
moret committed
297
298
299

        JackNetInterface::SetParams();

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

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

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

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

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

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

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

319
                    case JackFloatEncoder:
sletz's avatar
sletz committed
320
321
322
                    #ifdef NEW_FLOAT_CONVERTER
                        fNetAudioCaptureBuffer = new NetFloatAudioBuffer1(&fParams, fParams.fSendAudioChannels, fTxData);
                    #else
sletz's avatar
sletz committed
323
                        fNetAudioCaptureBuffer = new NetFloatAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
sletz's avatar
sletz committed
324
                    #endif
325
                        break;
sletz's avatar
sletz committed
326

327
                    case JackIntEncoder:
sletz's avatar
sletz committed
328
                        fNetAudioCaptureBuffer = new NetIntAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
329
                        break;
sletz's avatar
sletz committed
330

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

sletz's avatar
sletz committed
338
339
                assert(fNetAudioCaptureBuffer);
            }
sletz's avatar
sletz committed
340

sletz's avatar
sletz committed
341
            if (fParams.fReturnAudioChannels > 0) {
sletz's avatar
sletz committed
342

343
                switch (fParams.fSampleEncoder) {
sletz's avatar
sletz committed
344

345
                    case JackFloatEncoder:
sletz's avatar
sletz committed
346
347
348
                    #ifdef NEW_FLOAT_CONVERTER
                        fNetAudioPlaybackBuffer = new NetFloatAudioBuffer1(&fParams, fParams.fReturnAudioChannels, fRxData);
                    #else
sletz's avatar
sletz committed
349
                        fNetAudioPlaybackBuffer = new NetFloatAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
sletz's avatar
sletz committed
350
                    #endif
351
                        break;
sletz's avatar
sletz committed
352

353
                    case JackIntEncoder:
sletz's avatar
sletz committed
354
                        fNetAudioPlaybackBuffer = new NetIntAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
355
                        break;
sletz's avatar
sletz committed
356

357
                    case JackCeltEncoder:
nedko's avatar
nedko committed
358
                    #if HAVE_CELT
sletz's avatar
sletz committed
359
                        fNetAudioPlaybackBuffer = new NetCeltAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData, fParams.fKBps);
360
361
362
                    #endif
                        break;
                }
sletz's avatar
sletz committed
363

sletz's avatar
sletz committed
364
365
                assert(fNetAudioPlaybackBuffer);
            }
sletz's avatar
sletz committed
366

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

sletz's avatar
sletz committed
372
        // set the new timeout for the socket
373
        /*
sletz's avatar
sletz committed
374
375
        if (SetRxTimeout() == SOCKET_ERROR) {
            jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
376
            goto error;
sletz's avatar
sletz committed
377
        }
378
        */
moret's avatar
moret committed
379

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

sletz's avatar
sletz committed
386
        return true;
sletz's avatar
sletz committed
387

sletz's avatar
sletz committed
388
    error:
sletz's avatar
sletz committed
389
        FreeNetworkBuffers();
sletz's avatar
sletz committed
390
        return false;
moret's avatar
moret committed
391
392
    }

393
    void JackNetMasterInterface::Exit()
394
    {
sletz's avatar
sletz committed
395
        jack_log("JackNetMasterInterface::Exit, ID %u", fParams.fID);
396

sletz's avatar
sletz committed
397
        // stop process
398
        fRunning = false;
399

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

405
        session_params_t net_params;
sletz's avatar
sletz committed
406
        memset(&net_params, 0, sizeof(session_params_t));
407
408
        SessionParamsHToN(&fParams, &net_params);

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

416
417
418
        mcast_socket.Close();
    }

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

sletz's avatar
sletz committed
443
        if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
444
445

            /*
446
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
447
            // no data isn't really a network error, so just return 0 available read bytes
sletz's avatar
sletz committed
448
            if (error == NET_NO_DATA) {
449
                return 0;
sletz's avatar
sletz committed
450
            } else if (error == NET_CONN_ERROR) {
451
                FatalRecvError();
sletz's avatar
sletz committed
452
            } else {
sletz's avatar
sletz committed
453
                jack_error("Error in master receive : %s", StrError(NET_ERROR_CODE));
454
            }
455
456
            */

457
            FatalRecvError();
458
        }
459

460
461
462
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
        return rx_bytes;
463
    }
464

sletz's avatar
sletz committed
465
    int JackNetMasterInterface::Send(size_t size, int flags)
466
    {
467
468
469
        int tx_bytes;
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
        PacketHeaderHToN(header, header);
470

sletz's avatar
sletz committed
471
        if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
sletz's avatar
sletz committed
472
            /*
473
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
474
            if (error == NET_CONN_ERROR) {
475
                FatalSendError();
sletz's avatar
sletz committed
476
477
            } else {
                jack_error("Error in master send : %s", StrError(NET_ERROR_CODE));
478
            }
sletz's avatar
sletz committed
479
            */
480
            FatalSendError();
481
        }
482
        return tx_bytes;
483
    }
484

485
486
    bool JackNetMasterInterface::IsSynched()
    {
sletz's avatar
sletz committed
487
        return (fCurrentCycleOffset <= fMaxCycleOffset);
488
    }
489

490
    int JackNetMasterInterface::SyncSend()
491
    {
492
493
494
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
495
        fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ? 1 : 0;
sletz's avatar
sletz committed
496
        fTxHeader.fPacketSize = fParams.fMtu;
sletz's avatar
sletz committed
497

sletz's avatar
sletz committed
498
        /*
499
        // Write active ports list
500
        if (fNetAudioPlaybackBuffer) {
501
            fNetAudioPlaybackBuffer->ActivePortsToNetwork(fTxData, fTxHeader.fActivePorts);
502
        }
sletz's avatar
sletz committed
503
        */
504

sletz's avatar
sletz committed
505
        memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
sletz's avatar
sletz committed
506
        // PacketHeaderDisplay(&fTxHeader);
sletz's avatar
sletz committed
507
        return Send(fTxHeader.fPacketSize, 0);
508
509
510
511
    }

    int JackNetMasterInterface::DataSend()
    {
512
        if (MidiSend(fNetMidiCaptureBuffer, fParams.fSendMidiChannels, fParams.fSendAudioChannels) == SOCKET_ERROR) {
sletz's avatar
sletz committed
513
            return SOCKET_ERROR;
514
        }
sletz's avatar
sletz committed
515
        return AudioSend(fNetAudioCaptureBuffer, fParams.fSendAudioChannels);
516
517
    }

518
    int JackNetMasterInterface::SyncRecv()
519
    {
sletz's avatar
sletz committed
520
        int rx_bytes = 0;
sletz's avatar
sletz committed
521
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
sletz's avatar
sletz committed
522
523

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

sletz's avatar
sletz committed
526
        if ((rx_bytes == 0) || (rx_bytes == SOCKET_ERROR)) {
sletz's avatar
sletz committed
527
            // 0 bytes considered an error (lost connection)
sletz's avatar
sletz committed
528
529
            return SOCKET_ERROR;
        }
530

sletz's avatar
sletz committed
531
        fCurrentCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
sletz's avatar
sletz committed
532
533
534
535
536
537
538
539
540
541
542
543
        */

        // receive sync (launch the cycle)
        do {
            rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
            // connection issue, send will detect it, so don't skip the cycle (return 0)
            if (rx_bytes == SOCKET_ERROR) {
                return SOCKET_ERROR;
            }
        }
        while ((strcmp(rx_head->fPacketType, "header") != 0) && (rx_head->fDataType != 's'));

sletz's avatar
sletz committed
544
        fCurrentCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
545

sletz's avatar
sletz committed
546
        /*
547
        // Read active ports list
548
        if (fNetAudioCaptureBuffer) {
549
            fNetAudioCaptureBuffer->ActivePortsFromNetwork(fRxData, rx_head->fActivePorts);
550
        }
sletz's avatar
sletz committed
551
        */
552

sletz's avatar
sletz committed
553
554
        if (fCurrentCycleOffset < fMaxCycleOffset) {
            jack_info("Synching with latency = %d", fCurrentCycleOffset);
555
556
557
            return 0;
        } else {
            rx_bytes = Recv(rx_head->fPacketSize, 0);
558
559
            fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
            return rx_bytes;
560
        }
561
    }
562

563
    int JackNetMasterInterface::DataRecv()
564
565
    {
        int rx_bytes = 0;
566
        uint recvd_midi_pckt = 0;
sletz's avatar
sletz committed
567
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
568

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

sletz's avatar
sletz committed
573
            // error here, problem with recv, just skip the cycle (return -1)
574
            if (rx_bytes == SOCKET_ERROR) {
moret's avatar
moret committed
575
                return rx_bytes;
576
            }
sletz's avatar
sletz committed
577

sletz's avatar
sletz committed
578
579
580
581
582
583
            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
584
                        break;
585

sletz's avatar
sletz committed
586
587
                    case 'a':   // audio
                        rx_bytes = AudioRecv(rx_head, fNetAudioPlaybackBuffer);
moret's avatar
moret committed
588
                        break;
589

sletz's avatar
sletz committed
590
                    case 's':   // sync
591
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
sletz's avatar
sletz committed
592
                        return FinishRecv(fNetAudioPlaybackBuffer);
593
594
595
                }
            }
        }
sletz's avatar
sletz committed
596

597
        return rx_bytes;
598
    }
599

600
    void JackNetMasterInterface::EncodeSyncPacket()
601
    {
sletz's avatar
sletz committed
602
        // This method contains every step of sync packet informations coding
sletz's avatar
sletz committed
603
        // first of all, clear sync packet
604
        memset(fTxData, 0, PACKET_AVAILABLE_SIZE(&fParams));
605

sletz's avatar
sletz committed
606
        // then, first step : transport
607
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
608
            EncodeTransportData();
sletz's avatar
sletz committed
609
            TransportDataHToN(&fSendTransportData, &fSendTransportData);
sletz's avatar
sletz committed
610
            // copy to TxBuffer
sletz's avatar
sletz committed
611
            memcpy(fTxData, &fSendTransportData, sizeof(net_transport_data_t));
612
        }
sletz's avatar
sletz committed
613
614
        // then others (freewheel etc.)
        // ...
sletz's avatar
sletz committed
615
616
617
618
619
620
621
622
623

        // Transport not used for now...

        // Write active ports list
        if (fNetAudioPlaybackBuffer) {
            fNetAudioPlaybackBuffer->ActivePortsToNetwork(fTxData, fTxHeader.fActivePorts);
        } else {
            fTxHeader.fActivePorts = 0;
        }
624
625
    }

626
    void JackNetMasterInterface::DecodeSyncPacket()
627
    {
sletz's avatar
sletz committed
628
629
        // This method contains every step of sync packet informations decoding process
        // first : transport
630
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
631
            // copy received transport data to transport data structure
sletz's avatar
sletz committed
632
633
            memcpy(&fReturnTransportData, fRxData, sizeof(net_transport_data_t));
            TransportDataNToH(&fReturnTransportData,  &fReturnTransportData);
sletz's avatar
sletz committed
634
            DecodeTransportData();
635
        }
sletz's avatar
sletz committed
636
637
        // then others
        // ...
sletz's avatar
sletz committed
638
639
640
641
642
643
644
645
646

        // Transport not used for now...

        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);

        // Read active ports list
        if (fNetAudioCaptureBuffer) {
            fNetAudioCaptureBuffer->ActivePortsFromNetwork(fRxData, rx_head->fActivePorts);
        }
647
    }
648

649
650
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
651
652
    uint JackNetSlaveInterface::fSlaveCounter = 0;

653
    bool JackNetSlaveInterface::Init()
654
    {
sletz's avatar
sletz committed
655
        jack_log("JackNetSlaveInterface::Init()");
656

sletz's avatar
sletz committed
657
        // set the parameters to send
sletz's avatar
sletz committed
658
        strcpy(fParams.fPacketType, "params");
659
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
sletz's avatar
sletz committed
660
        SetPacketType(&fParams, SLAVE_AVAILABLE);
661

sletz's avatar
sletz committed
662
        // init loop : get a master and start, do it until connection is ok
663
        net_status_t status;
664
        do {
sletz's avatar
sletz committed
665
            // first, get a master, do it until a valid connection is running
666
            do {
667
                status = SendAvailableToMaster();
668
                if (status == NET_SOCKET_ERROR) {
669
                    return false;
670
                }
671
            }
sletz's avatar
sletz committed
672
            while (status != NET_CONNECTED);
673

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

683
684
        return true;
    }
685

686
    // Separate the connection protocol into two separated step
sletz's avatar
sletz committed
687
    bool JackNetSlaveInterface::InitConnection(int time_out_sec)
688
    {
sletz's avatar
sletz committed
689
        jack_log("JackNetSlaveInterface::InitConnection()");
sletz's avatar
sletz committed
690
        uint try_count = (time_out_sec > 0) ? ((1000000 * time_out_sec) / SLAVE_INIT_TIMEOUT) : LONG_MAX;
691

sletz's avatar
sletz committed
692
        // set the parameters to send
sletz's avatar
sletz committed
693
        strcpy(fParams.fPacketType, "params");
694
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
sletz's avatar
sletz committed
695
        SetPacketType(&fParams, SLAVE_AVAILABLE);
696
697

        net_status_t status;
698
        do {
sletz's avatar
sletz committed
699
            // get a master
sletz's avatar
sletz committed
700
            status = SendAvailableToMaster(try_count);
701
            if (status == NET_SOCKET_ERROR) {
702
                return false;
703
            }
704
        }
sletz's avatar
sletz committed
705
        while (status != NET_CONNECTED && --try_count > 0);
706

sletz's avatar
sletz committed
707
        return (try_count != 0);
708
    }
709

710
711
712
713
714
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

        net_status_t status;
715
        do {
sletz's avatar
sletz committed
716
            // then tell the master we are ready
717
718
719
720
721
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
            status = SendStartToMaster();
            if (status == NET_ERROR)
                return false;
        }
722
723
        while (status != NET_ROLLING);

724
725
        return true;
    }
726

sletz's avatar
sletz committed
727
    net_status_t JackNetSlaveInterface::SendAvailableToMaster(long try_count)
728
    {
sletz's avatar
sletz committed
729
        jack_log("JackNetSlaveInterface::SendAvailableToMaster()");
sletz's avatar
sletz committed
730
        // utility
731
        session_params_t host_params;
732
733
        int rx_bytes = 0;

sletz's avatar
sletz committed
734
        // socket
sletz's avatar
sletz committed
735
736
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Fatal error : network unreachable - %s", StrError(NET_ERROR_CODE));
737
            return NET_SOCKET_ERROR;
738
739
        }

sletz's avatar
sletz committed
740
        // bind the socket
sletz's avatar
sletz committed
741
742
        if (fSocket.Bind() == SOCKET_ERROR) {
            jack_error("Can't bind the socket : %s", StrError(NET_ERROR_CODE));
743
744
            return NET_SOCKET_ERROR;
        }
745

sletz's avatar
sletz committed
746
        // timeout on receive
sletz's avatar
sletz committed
747
748
        if (fSocket.SetTimeOut(SLAVE_INIT_TIMEOUT) == SOCKET_ERROR)
            jack_error("Can't set timeout : %s", StrError(NET_ERROR_CODE));
749

sletz's avatar
sletz committed
750
        // disable local loop
sletz's avatar
sletz committed
751
752
        if (fSocket.SetLocalLoop() == SOCKET_ERROR)
            jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
753

sletz's avatar
sletz committed
754
        // send 'AVAILABLE' until 'SLAVE_SETUP' received
sletz's avatar
sletz committed
755
        jack_info("Waiting for a master...");
756
        do {
sletz's avatar
sletz committed
757
            // send 'available'
758
            session_params_t net_params;
sletz's avatar
sletz committed
759
            memset(&net_params, 0, sizeof(session_params_t));
760
            SessionParamsHToN(&fParams, &net_params);
sletz's avatar
sletz committed
761
762
            if (fSocket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR)
                jack_error("Error in data send : %s", StrError(NET_ERROR_CODE));
763