JackNetInterface.cpp 35 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
#define PACKET_AVAILABLE_SIZE (fParams.fMtu - sizeof(packet_header_t))
sletz's avatar
sletz committed
27
#define HEADER_SIZE (sizeof(packet_header_t))
sletz's avatar
sletz committed
28

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

35
36
37
38
namespace Jack
{
    // JackNetInterface*******************************************

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

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

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

sletz's avatar
sletz committed
57
58
    void JackNetInterface::Initialize()
    {
59
60
61
62
63
64
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
65
66
        memset(&fSendTransportData, 0, sizeof(net_transport_data_t));
        memset(&fReturnTransportData, 0, sizeof(net_transport_data_t));
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
sletz's avatar
sletz committed
128
        strcpy(fTxHeader.fPacketType, "header");
129
130
131
        fTxHeader.fID = fParams.fID;
        fTxHeader.fCycle = 0;
        fTxHeader.fSubCycle = 0;
moret's avatar
moret committed
132
        fTxHeader.fIsLastPckt = 0;
133

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

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

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

sletz's avatar
sletz committed
151
        return true;
152
153
    }

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

            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);
167
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
168
                    return SOCKET_ERROR;
169
                }
sletz's avatar
sletz committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
            }
        }
        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);
189
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
sletz's avatar
sletz committed
190
                    return SOCKET_ERROR;
191
                }
sletz's avatar
sletz committed
192
193
194
195
196
197
198
199
200
201
202
203
            }
        }
        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...
204
        if (++recvd_midi_pckt == rx_head->fNumPacket) {
sletz's avatar
sletz committed
205
            buffer->RenderToJackPorts();
206
        }
sletz's avatar
sletz committed
207
208
209
210
211
212
213
214
215
216
217
218
        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...
219
        if (fRxHeader.fIsLastPckt) {
sletz's avatar
sletz committed
220
            buffer->RenderToJackPorts();
221
        }
sletz's avatar
sletz committed
222
223
224
225
226
227
228
229
230
231
        return rx_bytes;
    }

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

232
    // JackNetMasterInterface ************************************************************************************
233

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

238
        session_params_t host_params;
239
        uint attempt = 0;
240
241
        int rx_bytes = 0;

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

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

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

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

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

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

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

285
        return true;
286
287
    }

sletz's avatar
sletz committed
288
289
290
291
292
293
    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
294

sletz's avatar
sletz committed
295
    bool JackNetMasterInterface::SetParams()
moret's avatar
moret committed
296
    {
sletz's avatar
sletz committed
297
298
        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
299
300
301

        JackNetInterface::SetParams();

302
303
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
304

sletz's avatar
sletz committed
305
306
307
        fMaxCycleOffset = fParams.fNetworkLatency;

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

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

sletz's avatar
sletz committed
314
        try {
sletz's avatar
sletz committed
315

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

319
                switch (fParams.fSampleEncoder) {
sletz's avatar
sletz committed
320

321
                    case JackFloatEncoder:
sletz's avatar
sletz committed
322
                        fNetAudioCaptureBuffer = new NetFloatAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
323
                        break;
sletz's avatar
sletz committed
324

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

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

sletz's avatar
sletz committed
336
337
                assert(fNetAudioCaptureBuffer);
            }
sletz's avatar
sletz committed
338

sletz's avatar
sletz committed
339
            if (fParams.fReturnAudioChannels > 0) {
sletz's avatar
sletz committed
340

341
                switch (fParams.fSampleEncoder) {
sletz's avatar
sletz committed
342

343
                    case JackFloatEncoder:
sletz's avatar
sletz committed
344
                        fNetAudioPlaybackBuffer = new NetFloatAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
345
                        break;
sletz's avatar
sletz committed
346

347
                    case JackIntEncoder:
sletz's avatar
sletz committed
348
                        fNetAudioPlaybackBuffer = new NetIntAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
349
                        break;
sletz's avatar
sletz committed
350

351
                    case JackCeltEncoder:
nedko's avatar
nedko committed
352
                    #if HAVE_CELT
sletz's avatar
sletz committed
353
                        fNetAudioPlaybackBuffer = new NetCeltAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData, fParams.fKBps);
354
355
356
                    #endif
                        break;
                }
sletz's avatar
sletz committed
357

sletz's avatar
sletz committed
358
359
                assert(fNetAudioPlaybackBuffer);
            }
sletz's avatar
sletz committed
360

sletz's avatar
sletz committed
361
362
363
364
        } catch (exception&) {
            jack_error("NetAudioBuffer allocation error...");
            return false;
        }
moret's avatar
moret committed
365

sletz's avatar
sletz committed
366
        // set the new timeout for the socket
sletz's avatar
sletz committed
367
368
        if (SetRxTimeout() == SOCKET_ERROR) {
            jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
369
            goto error;
sletz's avatar
sletz committed
370
        }
moret's avatar
moret committed
371

sletz's avatar
sletz committed
372
        // set the new rx 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
sletz's avatar
sletz committed
393
394
395
        jack_info("Exiting '%s'", fParams.fName);
        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();
    }

sletz's avatar
sletz committed
411
412
    void JackNetMasterInterface::FatalError()
    {
sletz's avatar
sletz committed
413
        // fatal connection issue, exit
sletz's avatar
sletz committed
414
        jack_error("'%s' : %s, exiting", fParams.fName, StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
415
        // ask to the manager to properly remove the master
sletz's avatar
sletz committed
416
417
418
419
420
        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
421
    int JackNetMasterInterface::Recv(size_t size, int flags)
422
    {
423
        int rx_bytes;
sletz's avatar
sletz committed
424

sletz's avatar
sletz committed
425
        if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
426
427

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

sletz's avatar
sletz committed
439
            FatalError();
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) {
sletz's avatar
sletz committed
454
            /*
455
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
456
            if (error == NET_CONN_ERROR) {
sletz's avatar
sletz committed
457
                FatalError();
sletz's avatar
sletz committed
458
459
            } else {
                jack_error("Error in master send : %s", StrError(NET_ERROR_CODE));
460
            }
sletz's avatar
sletz committed
461
462
            */
            FatalError();
463
        }
464
        return tx_bytes;
465
    }
466

467
468
    bool JackNetMasterInterface::IsSynched()
    {
469
        return (fCycleOffset <= fMaxCycleOffset);
470
    }
471

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

480
        // Write active ports list
481
        if (fNetAudioPlaybackBuffer) {
482
            fNetAudioPlaybackBuffer->ActivePortsToNetwork(fTxData, fTxHeader.fActivePorts);
483
        }
484

sletz's avatar
sletz committed
485
        memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
sletz's avatar
sletz committed
486
        // PacketHeaderDisplay(&fTxHeader);
sletz's avatar
sletz committed
487
        return Send(fTxHeader.fPacketSize, 0);
488
489
490
491
    }

    int JackNetMasterInterface::DataSend()
    {
492
        if (MidiSend(fNetMidiCaptureBuffer, fParams.fSendMidiChannels, fParams.fSendAudioChannels) == SOCKET_ERROR) {
sletz's avatar
sletz committed
493
            return SOCKET_ERROR;
494
        }
sletz's avatar
sletz committed
495
        return AudioSend(fNetAudioCaptureBuffer, fParams.fSendAudioChannels);
496
497
    }

498
    int JackNetMasterInterface::SyncRecv()
499
    {
sletz's avatar
sletz committed
500
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
sletz's avatar
sletz committed
501
        int rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
502

sletz's avatar
sletz committed
503
        if ((rx_bytes == 0) || (rx_bytes == SOCKET_ERROR)) {
sletz's avatar
sletz committed
504
            // 0 bytes considered an error (lost connection)
sletz's avatar
sletz committed
505
506
            return SOCKET_ERROR;
        }
507

508
        fCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
509

510
        // Read active ports list
511
        if (fNetAudioCaptureBuffer) {
512
            fNetAudioCaptureBuffer->ActivePortsFromNetwork(fRxData, rx_head->fActivePorts);
513
        }
514

515
        if (fCycleOffset < fMaxCycleOffset) {
516
            jack_info("Synching with latency = %d", fCycleOffset);
517
518
519
            return 0;
        } else {
            rx_bytes = Recv(rx_head->fPacketSize, 0);
520
521
            fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
            return rx_bytes;
522
        }
523
    }
524

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

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

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

sletz's avatar
sletz committed
540
541
542
543
544
545
            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
546
                        break;
547

sletz's avatar
sletz committed
548
549
                    case 'a':   // audio
                        rx_bytes = AudioRecv(rx_head, fNetAudioPlaybackBuffer);
moret's avatar
moret committed
550
                        break;
551

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

559
        return rx_bytes;
560
    }
561

562
    void JackNetMasterInterface::EncodeSyncPacket()
563
    {
sletz's avatar
sletz committed
564
565
        // This method contains every step of sync packet informations coding
        // first of all, reset sync packet
sletz's avatar
sletz committed
566
        memset(fTxData, 0, PACKET_AVAILABLE_SIZE);
567

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

580
    void JackNetMasterInterface::DecodeSyncPacket()
581
    {
sletz's avatar
sletz committed
582
583
        // This method contains every step of sync packet informations decoding process
        // first : transport
584
        if (fParams.fTransportSync) {
sletz's avatar
sletz committed
585
            // copy received transport data to transport data structure
sletz's avatar
sletz committed
586
587
588
            memcpy(&fReturnTransportData, fRxData, sizeof(net_transport_data_t));
            TransportDataNToH(&fReturnTransportData,  &fReturnTransportData);
            // desactivated...
sletz's avatar
sletz committed
589
            // DecodeTransportData();
590
        }
sletz's avatar
sletz committed
591
592
        // then others
        // ...
593
    }
594

595
596
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
597
598
    uint JackNetSlaveInterface::fSlaveCounter = 0;

599
    bool JackNetSlaveInterface::Init()
600
    {
sletz's avatar
sletz committed
601
        jack_log("JackNetSlaveInterface::Init()");
602

sletz's avatar
sletz committed
603
        // set the parameters to send
sletz's avatar
sletz committed
604
        strcpy(fParams.fPacketType, "params");
605
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
sletz's avatar
sletz committed
606
        SetPacketType(&fParams, SLAVE_AVAILABLE);
607

sletz's avatar
sletz committed
608
        // init loop : get a master and start, do it until connection is ok
609
        net_status_t status;
610
        do {
sletz's avatar
sletz committed
611
            // first, get a master, do it until a valid connection is running
612
            do {
613
                status = SendAvailableToMaster();
614
                if (status == NET_SOCKET_ERROR) {
615
                    return false;
616
                }
617
            }
sletz's avatar
sletz committed
618
            while (status != NET_CONNECTED);
619

sletz's avatar
sletz committed
620
            // then tell the master we are ready
sletz's avatar
sletz committed
621
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
moret's avatar
moret committed
622
            status = SendStartToMaster();
623
            if (status == NET_ERROR) {
624
                return false;
625
            }
626
        }
sletz's avatar
sletz committed
627
        while (status != NET_ROLLING);
628

629
630
        return true;
    }
631

632
    // Separate the connection protocol into two separated step
sletz's avatar
sletz committed
633
    bool JackNetSlaveInterface::InitConnection(int time_out)
634
    {
sletz's avatar
sletz committed
635
        jack_log("JackNetSlaveInterface::InitConnection()");
sletz's avatar
sletz committed
636
        uint try_count = (time_out > 0) ? ((1000000 * time_out) / SLAVE_INIT_TIMEOUT) : LONG_MAX;
637

sletz's avatar
sletz committed
638
        // set the parameters to send
sletz's avatar
sletz committed
639
        strcpy(fParams.fPacketType, "params");
640
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
sletz's avatar
sletz committed
641
        SetPacketType(&fParams, SLAVE_AVAILABLE);
642
643

        net_status_t status;
644
        do {
sletz's avatar
sletz committed
645
            // get a master
sletz's avatar
sletz committed
646
            status = SendAvailableToMaster(try_count);
647
            if (status == NET_SOCKET_ERROR) {
648
                return false;
649
            }
650
        }
sletz's avatar
sletz committed
651
        while (status != NET_CONNECTED && --try_count > 0);
652

sletz's avatar
sletz committed
653
        return (try_count != 0);
654
    }
655

656
657
658
659
660
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

        net_status_t status;
661
        do {
sletz's avatar
sletz committed
662
            // then tell the master we are ready
663
664
665
666
667
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
            status = SendStartToMaster();
            if (status == NET_ERROR)
                return false;
        }
668
669
        while (status != NET_ROLLING);

670
671
        return true;
    }
672

sletz's avatar
sletz committed
673
    net_status_t JackNetSlaveInterface::SendAvailableToMaster(long try_count)
674
    {
sletz's avatar
sletz committed
675
        jack_log("JackNetSlaveInterface::SendAvailableToMaster()");
sletz's avatar
sletz committed
676
        // utility
677
        session_params_t host_params;
678
679
        int rx_bytes = 0;

sletz's avatar
sletz committed
680
        // socket
sletz's avatar
sletz committed
681
682
        if (fSocket.NewSocket() == SOCKET_ERROR) {
            jack_error("Fatal error : network unreachable - %s", StrError(NET_ERROR_CODE));
683
            return NET_SOCKET_ERROR;
684
685
        }

sletz's avatar
sletz committed
686
        // bind the socket
sletz's avatar
sletz committed
687
688
        if (fSocket.Bind() == SOCKET_ERROR) {
            jack_error("Can't bind the socket : %s", StrError(NET_ERROR_CODE));
689
690
            return NET_SOCKET_ERROR;
        }
691

sletz's avatar
sletz committed
692
        // timeout on receive
sletz's avatar
sletz committed
693
694
        if (fSocket.SetTimeOut(SLAVE_INIT_TIMEOUT) == SOCKET_ERROR)
            jack_error("Can't set timeout : %s", StrError(NET_ERROR_CODE));
695

sletz's avatar
sletz committed
696
        // disable local loop
sletz's avatar
sletz committed
697
698
        if (fSocket.SetLocalLoop() == SOCKET_ERROR)
            jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
699

sletz's avatar
sletz committed
700
        // send 'AVAILABLE' until 'SLAVE_SETUP' received
sletz's avatar
sletz committed
701
        jack_info("Waiting for a master...");
702
        do {
sletz's avatar
sletz committed
703
            // send 'available'
704
            session_params_t net_params;
sletz's avatar
sletz committed
705
            memset(&net_params, 0, sizeof(session_params_t));
706
            SessionParamsHToN(&fParams, &net_params);
sletz's avatar
sletz committed
707
708
            if (fSocket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR)
                jack_error("Error in data send : %s", StrError(NET_ERROR_CODE));
709

sletz's avatar
sletz committed
710
            // filter incoming packets : don't exit while no error is detected
sletz's avatar
sletz committed
711
712
            memset(&net_params, 0, sizeof(session_params_t));
            rx_bytes = fSocket.CatchHost(&net_params, sizeof(session_params_t), 0);
713
            SessionParamsNToH(&net_params, &host_params);
714
            if ((rx_bytes == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
sletz's avatar
sletz committed
715
                jack_error("Can't receive : %s", StrError(NET_ERROR_CODE));
716
                return NET_RECV_ERROR;
717
718
            }
        }
sletz's avatar
sletz committed
719
        while (strcmp(host_params.fPacketType, fParams.fPacketType)  && (GetPacketType(&host_params) != SLAVE_SETUP)  && (--try_count > 0));
sletz's avatar
sletz committed
720

sletz's avatar
sletz committed
721
        // Time out failure..
sletz's avatar
sletz committed
722
723
        if (try_count == 0) {
            jack_error("Time out error in connect");
sletz's avatar
sletz committed
724
725
            return NET_CONNECT_ERROR;
        }
726

sletz's avatar
sletz committed
727
        // everything is OK, copy parameters
728
        fParams = host_params;
moret's avatar
moret committed
729

sletz's avatar
sletz committed
730
        // connect the socket
sletz's avatar
sletz committed
731
732
        if (fSocket.Connect() == SOCKET_ERROR) {
            jack_error("Error in connect : %s", StrError(NET_ERROR_CODE));
733
            return NET_CONNECT_ERROR;
734
        }
moret's avatar
moret committed
735
        return NET_CONNECTED;