JackNetInterface.cpp 38.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
Copyright (C) 2001 Paul Davis
Copyright (C) 2008 Romain Moret at Grame

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"
22
#include "JackPlatformPlug.h"
23
#include <assert.h>
24
25
26

using namespace std;

sletz's avatar
sletz committed
27
#define PACKET_AVAILABLE_SIZE (fParams.fMtu - sizeof(packet_header_t))
sletz's avatar
sletz committed
28
#define HEADER_SIZE (sizeof(packet_header_t))
sletz's avatar
sletz committed
29

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

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

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

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

moret's avatar
moret committed
51
    JackNetInterface::JackNetInterface ( session_params_t& params, JackNetSocket& socket, const char* multicast_ip ) : fSocket ( socket )
52
    {
moret's avatar
moret committed
53
        fParams = params;
54
        strcpy(fMulticastIP, multicast_ip);
sletz's avatar
sletz committed
55
56
57
58
59
        Initialize();
    }
    
    void JackNetInterface::Initialize()
    {
60
61
62
63
64
65
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
66
67
        memset(&fSendTransportData, 0, sizeof(net_transport_data_t));
        memset(&fReturnTransportData, 0, sizeof(net_transport_data_t));
68
    }
sletz's avatar
sletz committed
69
    
70
71
    JackNetInterface::~JackNetInterface()
    {
moret's avatar
moret committed
72
        jack_log ( "JackNetInterface::~JackNetInterface" );
moret's avatar
moret committed
73

74
75
76
77
78
79
80
81
82
        fSocket.Close();
        delete[] fTxBuffer;
        delete[] fRxBuffer;
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
    }

moret's avatar
moret committed
83
84
85
    int JackNetInterface::SetNetBufferSize()
    {
        //audio
sletz's avatar
sletz committed
86
87
88
89
90
        float audio_size = (fNetAudioCaptureBuffer) 
                            ? fNetAudioCaptureBuffer->GetCycleSize() 
                            : (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->GetCycleSize() : 0;
        jack_log ("audio_size %f", audio_size);
        
moret's avatar
moret committed
91
        //midi
sletz's avatar
sletz committed
92
93
94
95
96
        float midi_size = (fNetMidiCaptureBuffer) 
                            ? fNetMidiCaptureBuffer->GetCycleSize() 
                            : (fNetMidiPlaybackBuffer) ? fNetMidiPlaybackBuffer->GetCycleSize() : 0;
        jack_log ("midi_size %f", midi_size);
                                     
moret's avatar
moret committed
97
        //bufsize = sync + audio + midi
sletz's avatar
sletz committed
98
        int bufsize = MAX_LATENCY * (fParams.fMtu + (int)audio_size + (int) midi_size);
sletz's avatar
sletz committed
99
        jack_log("SetNetBufferSize bufsize = %d", bufsize);
moret's avatar
moret committed
100
101

        //tx buffer
sletz's avatar
sletz committed
102
        if (fSocket.SetOption(SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR)
103
            return SOCKET_ERROR;
moret's avatar
moret committed
104
105

        //rx buffer
sletz's avatar
sletz committed
106
        if (fSocket.SetOption(SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR)
107
            return SOCKET_ERROR;
moret's avatar
moret committed
108

109
        return 0;
moret's avatar
moret committed
110
111
    }

sletz's avatar
sletz committed
112
    bool JackNetInterface::SetParams()
113
114
115
116
117
118
119
    {
        //TX header init
        strcpy ( fTxHeader.fPacketType, "header" );
        fTxHeader.fID = fParams.fID;
        fTxHeader.fCycle = 0;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fBitdepth = fParams.fBitdepth;
moret's avatar
moret committed
120
        fTxHeader.fIsLastPckt = 0;
121
122
123
124
125
126
127

        //RX header init
        strcpy ( fRxHeader.fPacketType, "header" );
        fRxHeader.fID = fParams.fID;
        fRxHeader.fCycle = 0;
        fRxHeader.fSubCycle = 0;
        fRxHeader.fBitdepth = fParams.fBitdepth;
moret's avatar
moret committed
128
        fRxHeader.fIsLastPckt = 0;
129
130
131
132

        //network buffers
        fTxBuffer = new char[fParams.fMtu];
        fRxBuffer = new char[fParams.fMtu];
133
134
        assert ( fTxBuffer );
        assert ( fRxBuffer );
135

moret's avatar
moret committed
136
        //net audio/midi buffers'addresses
sletz's avatar
sletz committed
137
138
        fTxData = fTxBuffer + HEADER_SIZE;
        fRxData = fRxBuffer + HEADER_SIZE;
sletz's avatar
sletz committed
139
140
        
        return true;
141
142
    }

143
    // JackNetMasterInterface ************************************************************************************
144

145
    bool JackNetMasterInterface::Init()
146
    {
147
        jack_log ( "JackNetMasterInterface::Init, ID %u.", fParams.fID );
148

149
        session_params_t host_params;
150
        uint attempt = 0;
151
152
153
        int rx_bytes = 0;

        //socket
sletz's avatar
sletz committed
154
        if ( fSocket.NewSocket() == SOCKET_ERROR ) {
155
156
            jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
            return false;
157
158
        }

159
        //timeout on receive (for init)
160
        if ( fSocket.SetTimeOut ( MASTER_INIT_TIMEOUT ) < 0 )
161
            jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );
162
            
163
        //connect
sletz's avatar
sletz committed
164
        if ( fSocket.Connect() == SOCKET_ERROR ) {
165
166
167
            jack_error ( "Can't connect : %s", StrError ( NET_ERROR_CODE ) );
            return false;
        }
168

169
        //send 'SLAVE_SETUP' until 'START_MASTER' received
sletz's avatar
sletz committed
170
        jack_info ( "Sending parameters to %s...", fParams.fSlaveNetName );
171
172
        do
        {
173
            session_params_t net_params;
sletz's avatar
sletz committed
174
            memset(&net_params, 0, sizeof ( session_params_t ));
175
            SetPacketType ( &fParams, SLAVE_SETUP );
176
177
178
            SessionParamsHToN(&fParams, &net_params);
            
            if ( fSocket.Send ( &net_params, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
179
                jack_error ( "Error in send : ", StrError ( NET_ERROR_CODE ) );
180
                
sletz's avatar
sletz committed
181
182
            memset(&net_params, 0, sizeof (session_params_t));
            if (((rx_bytes = fSocket.Recv(&net_params, sizeof(session_params_t), 0)) == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA))
183
            {
184
185
                jack_error ( "Problem with network." );
                return false;
186
            }
187
188
            
            SessionParamsNToH(&net_params, &host_params);
189
        }
190
        while ( ( GetPacketType ( &host_params ) != START_MASTER ) && ( ++attempt < SLAVE_SETUP_RETRY ) );
sletz's avatar
sletz committed
191
        if ( attempt == SLAVE_SETUP_RETRY ) {
192
193
            jack_error ( "Slave doesn't respond, exiting." );
            return false;
194
195
        }

196
        return true;
197
198
    }

moret's avatar
moret committed
199
200
    int JackNetMasterInterface::SetRxTimeout()
    {
moret's avatar
moret committed
201
202
        jack_log ( "JackNetMasterInterface::SetRxTimeout" );

moret's avatar
moret committed
203
        float time = 0;
sletz's avatar
sletz committed
204
        
moret's avatar
moret committed
205
        //slow or normal mode, short timeout on recv (2 audio subcycles)
sletz's avatar
sletz committed
206
207
208
209
210
        if ((fParams.fNetworkMode == 's') || (fParams.fNetworkMode == 'n')) {
            time = 2000000.f * ((fNetAudioCaptureBuffer) 
                                ? fNetAudioCaptureBuffer->GetCycleDuration() 
                                : (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->GetCycleDuration() : 0);
        }
moret's avatar
moret committed
211
        //fast mode, wait for 75% of the entire cycle duration
sletz's avatar
sletz committed
212
213
214
215
216
        else if (fParams.fNetworkMode == 'f') {
            time = 750000.f * (static_cast<float>(fParams.fPeriodSize) / static_cast<float>(fParams.fSampleRate));
        }
        
        return fSocket.SetTimeOut (static_cast<int>(time));
moret's avatar
moret committed
217
218
    }

sletz's avatar
sletz committed
219
    bool JackNetMasterInterface::SetParams()
moret's avatar
moret committed
220
    {
221
        jack_log ( "JackNetMasterInterface::SetParams" );
moret's avatar
moret committed
222
223
224

        JackNetInterface::SetParams();

225
226
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
227
228

        //midi net buffers
229
230
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fTxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fRxData );
231
232
        assert ( fNetMidiCaptureBuffer );
        assert ( fNetMidiPlaybackBuffer );
moret's avatar
moret committed
233

sletz's avatar
sletz committed
234
        try {
moret's avatar
moret committed
235
        //audio net buffers
sletz's avatar
sletz committed
236
    #ifdef CELT
sletz's avatar
sletz committed
237
238
239
240
241
            if (fParams.fSendAudioChannels)
                fNetAudioCaptureBuffer = new NetCeltAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
                
            if (fParams.fReturnAudioChannels)
                fNetAudioPlaybackBuffer = new NetCeltAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );
sletz's avatar
sletz committed
242
243
244
            
            //fNetAudioCaptureBuffer = new NetIntAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
            //fNetAudioPlaybackBuffer = new NetIntAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );
sletz's avatar
sletz committed
245
    #else
sletz's avatar
sletz committed
246
247
            fNetAudioCaptureBuffer = new NetFloatAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
            fNetAudioPlaybackBuffer = new NetFloatAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );
sletz's avatar
sletz committed
248
    #endif    
sletz's avatar
sletz committed
249
250
251
252
    
            //fNetAudioCaptureBuffer = new NetBufferedAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
            //fNetAudioPlaybackBuffer = new NetBufferedAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );     
     
sletz's avatar
sletz committed
253
254
255
256
        } catch (exception&) {
            jack_error("NetAudioBuffer allocation error...");
            return false;
        }
sletz's avatar
sletz committed
257
       
sletz's avatar
sletz committed
258
        //set the new timeout for the socket
sletz's avatar
sletz committed
259
260
        if (SetRxTimeout() == SOCKET_ERROR) {
            jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
261
262
263
264
            goto error;
        }

        //set the new rx buffer size
sletz's avatar
sletz committed
265
266
        if (SetNetBufferSize() == SOCKET_ERROR) {
            jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
sletz's avatar
sletz committed
267
268
269
270
271
272
273
274
275
276
277
278
            goto error;
        }
        
        return true;
            
    error:
    
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        return false;
moret's avatar
moret committed
279
280
    }

281
    void JackNetMasterInterface::Exit()
282
    {
283
284
285
286
        jack_log ( "JackNetMasterInterface::Exit, ID %u", fParams.fID );

        //stop process
        fRunning = false;
287

288
289
290
291
        //send a 'multicast euthanasia request' - new socket is required on macosx
        jack_info ( "Exiting '%s'", fParams.fName );
        SetPacketType ( &fParams, KILL_MASTER );
        JackNetSocket mcast_socket ( fMulticastIP, fSocket.GetPort() );
292
293
        
        session_params_t net_params;
sletz's avatar
sletz committed
294
        memset(&net_params, 0, sizeof ( session_params_t ));
295
296
        SessionParamsHToN(&fParams, &net_params);

297
298
        if ( mcast_socket.NewSocket() == SOCKET_ERROR )
            jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
299
        if ( mcast_socket.SendTo ( &net_params, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
300
            jack_error ( "Can't send suicide request : %s", StrError ( NET_ERROR_CODE ) );
301
            
302
303
304
        mcast_socket.Close();
    }

sletz's avatar
sletz committed
305
    int JackNetMasterInterface::Recv(size_t size, int flags)
306
    {
307
        int rx_bytes;
sletz's avatar
sletz committed
308
309
        
        if ((( rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
310
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
311
            //no data isn't really a network error, so just return 0 available read bytes
sletz's avatar
sletz committed
312
            if (error == NET_NO_DATA) {
313
                return 0;
sletz's avatar
sletz committed
314
            } else if (error == NET_CONN_ERROR) {
315
                //fatal connection issue, exit
sletz's avatar
sletz committed
316
                jack_error ( "'%s' : %s, exiting.", fParams.fName, StrError(NET_ERROR_CODE));
317
                //ask to the manager to properly remove the master
318
                Exit();
sletz's avatar
sletz committed
319
320
321
                
                // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
                ThreadExit();
sletz's avatar
sletz committed
322
323
            } else {
                jack_error ( "Error in master receive : %s", StrError(NET_ERROR_CODE));
324
325
            }
        }
326
327
328
329
        
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
        return rx_bytes;
330
    }
331
    
sletz's avatar
sletz committed
332
    int JackNetMasterInterface::Send(size_t size, int flags)
333
    {
334
335
336
337
        int tx_bytes;
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
        PacketHeaderHToN(header, header);
        
sletz's avatar
sletz committed
338
        if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
339
            net_error_t error = fSocket.GetError();
sletz's avatar
sletz committed
340
            if (error == NET_CONN_ERROR) {
341
                //fatal connection issue, exit
sletz's avatar
sletz committed
342
                jack_error ("'%s' : %s, exiting.", fParams.fName, StrError (NET_ERROR_CODE));
343
                Exit();
sletz's avatar
sletz committed
344
345
346
                
                // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
                ThreadExit();
sletz's avatar
sletz committed
347
348
            } else {
                jack_error("Error in master send : %s", StrError(NET_ERROR_CODE));
349
350
            }
        }
351
        return tx_bytes;
352
    }
353
354
355
    
    bool JackNetMasterInterface::IsSynched()
    {
sletz's avatar
sletz committed
356
        if (fParams.fNetworkMode == 's') {
357
            return (fCycleOffset < (CYCLE_OFFSET_SLOW + 1));
sletz's avatar
sletz committed
358
        } else {
359
            return true;
sletz's avatar
sletz committed
360
        }
361
362
    }
    
363
    int JackNetMasterInterface::SyncSend()
364
    {
365
366
367
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
sletz's avatar
sletz committed
368
        fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ?  1 : 0;
sletz's avatar
sletz committed
369
        fTxHeader.fPacketSize = HEADER_SIZE;
sletz's avatar
sletz committed
370
        
sletz's avatar
sletz committed
371
372
        memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
        return Send(fTxHeader.fPacketSize, 0);
373
374
375
376
377
    }

    int JackNetMasterInterface::DataSend()
    {
        uint subproc;
sletz's avatar
sletz committed
378
379
        uint data_size; 
        
380
        //midi
sletz's avatar
sletz committed
381
        if (fParams.fSendMidiChannels > 0)
382
        {
383
384
            //set global header fields and get the number of midi packets
            fTxHeader.fDataType = 'm';
sletz's avatar
sletz committed
385
386
387
388
            data_size = fNetMidiCaptureBuffer->RenderFromJackPorts();
            fTxHeader.fNumPacket = fNetMidiCaptureBuffer->GetNumPackets();
            
            for ( subproc = 0; subproc < fTxHeader.fNumPacket; subproc++ )
389
            {
390
                fTxHeader.fSubCycle = subproc;
sletz's avatar
sletz committed
391
392
                fTxHeader.fIsLastPckt = ((subproc == (fTxHeader.fNumPacket - 1)) && (fParams.fSendAudioChannels == 0)) ? 1 : 0;
                fTxHeader.fPacketSize = HEADER_SIZE + fNetMidiCaptureBuffer->RenderToNetwork(subproc, data_size);
sletz's avatar
sletz committed
393
394
                memcpy ( fTxBuffer, &fTxHeader, HEADER_SIZE);
                if (Send (fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
395
                    return SOCKET_ERROR;
396
397
            }
        }
398
399

        //audio
sletz's avatar
sletz committed
400
        if (fParams.fSendAudioChannels > 0)
401
402
        {
            fTxHeader.fDataType = 'a';
sletz's avatar
sletz committed
403
404
405
406
            data_size = fNetAudioCaptureBuffer->RenderFromJackPorts();
            fTxHeader.fNumPacket = fNetAudioCaptureBuffer->GetNumPackets();
            
            for (subproc = 0; subproc < fTxHeader.fNumPacket; subproc++)
407
408
            {
                fTxHeader.fSubCycle = subproc;
sletz's avatar
sletz committed
409
410
                fTxHeader.fIsLastPckt = (subproc == (fTxHeader.fNumPacket - 1)) ? 1 : 0;
                fTxHeader.fPacketSize = HEADER_SIZE + fNetAudioCaptureBuffer->RenderToNetwork(subproc, data_size);
sletz's avatar
sletz committed
411
412
                memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
413
414
415
416
417
                    return SOCKET_ERROR;
            }
        }

        return 0;
418
    }
sletz's avatar
sletz committed
419
    
420
    int JackNetMasterInterface::SyncRecv()
421
422
    {
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
sletz's avatar
sletz committed
423
        int rx_bytes = Recv(HEADER_SIZE, MSG_PEEK);
424
        
425
426
427
        if ( ( rx_bytes == 0 ) || ( rx_bytes == SOCKET_ERROR ) )
            return rx_bytes;

428
        fCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
429
      
430
        switch ( fParams.fNetworkMode )
431
        {
432
            case 's' :
moret's avatar
moret committed
433
434
435
436
437
                //slow mode : allow to use full bandwidth and heavy process on the slave
                //  - extra latency is set to two cycles, one cycle for send/receive operations + one cycle for heavy process on the slave
                //  - if the network is two fast, just wait the next cycle, this mode allows a shorter cycle duration for the master
                //  - this mode will skip the two first cycles, thus it lets time for data to be processed and queued on the socket rx buffer
                //the slow mode is the safest mode because it wait twice the bandwidth relative time (send/return + process)
sletz's avatar
sletz committed
438
                
sletz's avatar
sletz committed
439
                /*
440
                if (fCycleOffset < CYCLE_OFFSET_SLOW) {
sletz's avatar
sletz committed
441
442
                    return 0;
                } else {
443
                    rx_bytes = Recv ( rx_head->fPacketSize, 0 );
sletz's avatar
sletz committed
444
                }
sletz's avatar
sletz committed
445
                */
446
                
sletz's avatar
sletz committed
447
                rx_bytes = Recv ( rx_head->fPacketSize, 0 );
sletz's avatar
sletz committed
448
449
                
                if (fCycleOffset != fLastfCycleOffset)
450
                    jack_info("Warning : '%s' runs in slow network mode, but data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
sletz's avatar
sletz committed
451
                fLastfCycleOffset = fCycleOffset;
452
                break;
453

454
455
456
457
458
            case 'n' :
                //normal use of the network :
                //  - extra latency is set to one cycle, what is the time needed to receive streams using full network bandwidth
                //  - if the network is too fast, just wait the next cycle, the benefit here is the master's cycle is shorter
                //  - indeed, data is supposed to be on the network rx buffer, so we don't have to wait for it
sletz's avatar
sletz committed
459
                if (fCycleOffset < CYCLE_OFFSET_NORMAL) {
460
                    return 0;
sletz's avatar
sletz committed
461
                } else {
462
                    rx_bytes = Recv ( rx_head->fPacketSize, 0 );
sletz's avatar
sletz committed
463
                }
464
                    
sletz's avatar
sletz committed
465
                if (fCycleOffset > CYCLE_OFFSET_NORMAL)  {
466
                    jack_info("'%s' can't run in normal network mode, data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
sletz's avatar
sletz committed
467
                }
468
                break;
469

470
471
472
473
474
475
            case 'f' :
                //fast mode suppose the network bandwith is larger than required for the transmission (only a few channels for example)
                //    - packets can be quickly received, quickly is here relative to the cycle duration
                //    - here, receive data, we can't keep it queued on the rx buffer,
                //    - but if there is a cycle offset, tell the user, that means we're not in fast mode anymore, network is too slow
                rx_bytes = Recv ( rx_head->fPacketSize, 0 );
476
                
sletz's avatar
sletz committed
477
                if (fCycleOffset > CYCLE_OFFSET_FAST) {
478
                    jack_info("'%s' can't run in fast network mode, data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
sletz's avatar
sletz committed
479
                }
480
                break;
481
        }
482

moret's avatar
moret committed
483
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
484
485
        return rx_bytes;
    }
486
    
487
    int JackNetMasterInterface::DataRecv()
488
489
    {
        int rx_bytes = 0;
sletz's avatar
sletz committed
490
        uint recvd_midi_pckt = 0;
sletz's avatar
sletz committed
491
        uint recvd_audio_pckt = 0;
sletz's avatar
sletz committed
492
      
493
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
494
        
moret's avatar
moret committed
495
        while ( !fRxHeader.fIsLastPckt )
496
        {
moret's avatar
moret committed
497
            //how much data is queued on the rx buffer ?
sletz's avatar
sletz committed
498
            rx_bytes = Recv(HEADER_SIZE, MSG_PEEK);
499
              
sletz's avatar
sletz committed
500
            //error here, problem with recv, just skip the cycle (return -1)
moret's avatar
moret committed
501
502
            if ( rx_bytes == SOCKET_ERROR )
                return rx_bytes;
sletz's avatar
sletz committed
503
          
moret's avatar
moret committed
504
505
506
507
            if ( rx_bytes && ( rx_head->fDataStream == 'r' ) && ( rx_head->fID == fParams.fID ) )
            {
                //read data
                switch ( rx_head->fDataType )
508
                {
moret's avatar
moret committed
509
                    case 'm':   //midi
sletz's avatar
sletz committed
510
                        rx_bytes = Recv(rx_head->fPacketSize, 0);
moret's avatar
moret committed
511
                        fRxHeader.fCycle = rx_head->fCycle;
moret's avatar
moret committed
512
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
sletz's avatar
sletz committed
513
                        fNetMidiPlaybackBuffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
sletz's avatar
sletz committed
514
515
                        // Last midi packet is received, so finish rendering...
                        if (++recvd_midi_pckt == rx_head->fNumPacket)
moret's avatar
moret committed
516
517
                            fNetMidiPlaybackBuffer->RenderToJackPorts();
                        break;
518

moret's avatar
moret committed
519
                    case 'a':   //audio
sletz's avatar
sletz committed
520
                        rx_bytes = Recv(rx_head->fPacketSize, 0);
moret's avatar
moret committed
521
522
                        fRxHeader.fCycle = rx_head->fCycle;
                        fRxHeader.fSubCycle = rx_head->fSubCycle;
moret's avatar
moret committed
523
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
sletz's avatar
sletz committed
524
525
526
                        fNetAudioPlaybackBuffer->RenderFromNetwork (rx_head->fCycle, rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
                        // Last audio packet is received, so finish rendering...
                        if (fRxHeader.fIsLastPckt)
sletz's avatar
sletz committed
527
                            fNetAudioPlaybackBuffer->RenderToJackPorts();
moret's avatar
moret committed
528
                        break;
529

moret's avatar
moret committed
530
                    case 's':   //sync
531
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
sletz's avatar
sletz committed
532
                        // TODO : finish midi and audio rendering ?
sletz's avatar
sletz committed
533
                        fNetAudioPlaybackBuffer->RenderToJackPorts();
534
                        return 0;
535
536
537
                }
            }
        }
sletz's avatar
sletz committed
538
 
539
        return rx_bytes;
540
    }
541
    
sletz's avatar
sletz committed
542
    void JackNetMasterInterface::EncodeSyncPacket()
543
544
545
    {
        //this method contains every step of sync packet informations coding
        //first of all, reset sync packet
sletz's avatar
sletz committed
546
        memset ( fTxData, 0, PACKET_AVAILABLE_SIZE );
547
548

        //then, first step : transport
sletz's avatar
sletz committed
549
550
551
        if (fParams.fTransportSync) {
            EncodeTransportData();
            TransportDataHToN( &fSendTransportData,  &fSendTransportData);
552
553
554
555
556
557
558
            //copy to TxBuffer
            memcpy ( fTxData, &fSendTransportData, sizeof ( net_transport_data_t ) );
        }
        //then others (freewheel etc.)
        //...
    }

sletz's avatar
sletz committed
559
    void JackNetMasterInterface::DecodeSyncPacket()
560
561
562
    {
        //this method contains every step of sync packet informations decoding process
        //first : transport
sletz's avatar
sletz committed
563
        if (fParams.fTransportSync) {
564
565
            //copy received transport data to transport data structure
            memcpy ( &fReturnTransportData, fRxData, sizeof ( net_transport_data_t ) );
sletz's avatar
sletz committed
566
567
            TransportDataNToH( &fReturnTransportData,  &fReturnTransportData);
            DecodeTransportData();
568
569
570
571
        }
        //then others
        //...
    }
572

573
574
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
575
576
    uint JackNetSlaveInterface::fSlaveCounter = 0;

577
    bool JackNetSlaveInterface::Init()
578
    {
579
        jack_log ( "JackNetSlaveInterface::Init()" );
580

581
582
        //set the parameters to send
        strcpy ( fParams.fPacketType, "params" );
583
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
584
        SetPacketType ( &fParams, SLAVE_AVAILABLE );
585

586
587
588
        //init loop : get a master and start, do it until connection is ok
        net_status_t status;
        do
589
        {
590
591
            //first, get a master, do it until a valid connection is running
            do
592
            {
sletz's avatar
sletz committed
593
                status = SendAvailableToMaster();
594
595
                if ( status == NET_SOCKET_ERROR )
                    return false;
596
            }
597
            while ( status != NET_CONNECTED );
598

599
600
            //then tell the master we are ready
            jack_info ( "Initializing connection with %s...", fParams.fMasterNetName );
moret's avatar
moret committed
601
            status = SendStartToMaster();
602
603
            if ( status == NET_ERROR )
                return false;
604
        }
605
        while ( status != NET_ROLLING );
606

607
608
        return true;
    }
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
    
    // Separate the connection protocol into two separated step
    
    bool JackNetSlaveInterface::InitConnection()
    {
        jack_log ( "JackNetSlaveInterface::InitConnection()" );

        //set the parameters to send
        strcpy (fParams.fPacketType, "params");
        fParams.fProtocolVersion = SLAVE_PROTOCOL;
        SetPacketType (&fParams, SLAVE_AVAILABLE);

        net_status_t status;
        do
        {
            //get a master
sletz's avatar
sletz committed
625
            status = SendAvailableToMaster();
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
            if (status == NET_SOCKET_ERROR)
                return false;
        }
        while (status != NET_CONNECTED);
  
        return true;
    }
    
    bool JackNetSlaveInterface::InitRendering()
    {
        jack_log("JackNetSlaveInterface::InitRendering()");

        net_status_t status;
        do
        {
            //then tell the master we are ready
            jack_info("Initializing connection with %s...", fParams.fMasterNetName);
            status = SendStartToMaster();
            if (status == NET_ERROR)
                return false;
        }
        while (status != NET_ROLLING);   
        
        return true;
    }
651

sletz's avatar
sletz committed
652
    net_status_t JackNetSlaveInterface::SendAvailableToMaster()
653
    {
sletz's avatar
sletz committed
654
        jack_log ( "JackNetSlaveInterface::SendAvailableToMaster()" );
655
        //utility
656
        session_params_t host_params;
657
        int rx_bytes = 0;
sletz's avatar
sletz committed
658
     
659
        //socket
sletz's avatar
sletz committed
660
        if ( fSocket.NewSocket() == SOCKET_ERROR ) {
661
662
            jack_error ( "Fatal error : network unreachable - %s", StrError ( NET_ERROR_CODE ) );
            return NET_SOCKET_ERROR;
663
664
        }

665
        //bind the socket
sletz's avatar
sletz committed
666
        if ( fSocket.Bind() == SOCKET_ERROR ) {
667
            jack_error ( "Can't bind the socket : %s", StrError ( NET_ERROR_CODE ) );
sletz's avatar
sletz committed
668
669
            return NET_SOCKET_ERROR;
        }
670
671

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

675
        //disable local loop
moret's avatar
moret committed
676
        if ( fSocket.SetLocalLoop() == SOCKET_ERROR )
677
            jack_error ( "Can't disable multicast loop : %s", StrError ( NET_ERROR_CODE ) );
678

679
680
        //send 'AVAILABLE' until 'SLAVE_SETUP' received
        jack_info ( "Waiting for a master..." );
681
682
        do
        {
683
            //send 'available'
684
            session_params_t net_params;
sletz's avatar
sletz committed
685
            memset(&net_params, 0, sizeof ( session_params_t ));
686
687
            SessionParamsHToN(&fParams, &net_params);
            if ( fSocket.SendTo ( &net_params, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
688
                jack_error ( "Error in data send : %s", StrError ( NET_ERROR_CODE ) );
689
                
690
            //filter incoming packets : don't exit while no error is detected
691
692
693
            memset(&net_params, 0, sizeof ( session_params_t ));
            rx_bytes = fSocket.CatchHost ( &net_params, sizeof ( session_params_t ), 0 );
            SessionParamsNToH(&net_params, &host_params);
694
            if ( ( rx_bytes == SOCKET_ERROR ) && ( fSocket.GetError() != NET_NO_DATA ) )
695
            {
696
697
                jack_error ( "Can't receive : %s", StrError ( NET_ERROR_CODE ) );
                return NET_RECV_ERROR;
698
699
            }
        }
700
        while ( strcmp ( host_params.fPacketType, fParams.fPacketType )  && ( GetPacketType ( &host_params ) != SLAVE_SETUP ) );
sletz's avatar
sletz committed
701
   
moret's avatar
moret committed
702
        //everything is OK, copy parameters
sletz's avatar
sletz committed
703
        SessionParamsDisplay(&host_params);
704
        fParams = host_params;
moret's avatar
moret committed
705

706
        //connect the socket
sletz's avatar
sletz committed
707
        if ( fSocket.Connect() == SOCKET_ERROR ) {
708
709
            jack_error ( "Error in connect : %s", StrError ( NET_ERROR_CODE ) );
            return NET_CONNECT_ERROR;
710
        }
moret's avatar
moret committed
711
        return NET_CONNECTED;
712
713
    }

moret's avatar
moret committed
714
    net_status_t JackNetSlaveInterface::SendStartToMaster()
715
    {
moret's avatar
moret committed
716
        jack_log ( "JackNetSlaveInterface::SendStartToMaster" );
moret's avatar
moret committed
717

718
        //tell the master to start
719
        session_params_t net_params;
sletz's avatar
sletz committed
720
        memset(&net_params, 0, sizeof ( session_params_t ));
721
        SetPacketType ( &fParams, START_MASTER );
722
723
        SessionParamsHToN(&fParams, &net_params);
        if ( fSocket.Send ( &net_params, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
724
        {
725
726
            jack_error ( "Error in send : %s", StrError ( NET_ERROR_CODE ) );
            return ( fSocket.GetError() == NET_CONN_ERROR ) ? NET_ERROR : NET_SEND_ERROR;
727
        }
728
        return NET_ROLLING;
729
730
    }

sletz's avatar
sletz committed
731
    bool JackNetSlaveInterface::SetParams()
moret's avatar
moret committed
732
    {
733
        jack_log ( "JackNetSlaveInterface::SetParams" );
moret's avatar
moret committed
734
735
736

        JackNetInterface::SetParams();

737
738
        fTxHeader.fDataStream = 'r';
        fRxHeader.fDataStream = 's';
moret's avatar
moret committed
739
740

        //midi net buffers
741
742
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fRxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fTxData );
sletz's avatar
sletz committed
743
744
        assert ( fNetMidiCaptureBuffer );
        assert ( fNetMidiPlaybackBuffer );
moret's avatar
moret committed
745
746

        //audio net buffers
sletz's avatar
sletz committed
747
748
        //fNetAudioCaptureBuffer = new NetFloatAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
        //fNetAudioPlaybackBuffer = new NetFloatAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
sletz's avatar
sletz committed
749
750
751
    
        try {
    #ifdef CELT
sletz's avatar
sletz committed
752
753
754
755
756
            if (fParams.fSendAudioChannels)
                fNetAudioCaptureBuffer = new NetCeltAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
                
            if (fParams.fReturnAudioChannels)
                fNetAudioPlaybackBuffer = new NetCeltAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
sletz's avatar
sletz committed
757
758
759
            
            // fNetAudioCaptureBuffer = new NetIntAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
           // fNetAudioPlaybackBuffer = new NetIntAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
sletz's avatar
sletz committed
760
    #else
sletz's avatar
sletz committed
761
762
763
            fNetAudioCaptureBuffer = new NetFloatAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
            fNetAudioPlaybackBuffer = new NetFloatAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
            
sletz's avatar
sletz committed
764
765
766
767
768
769
770
771
            //fNetAudioCaptureBuffer = new NetBufferedAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
            //fNetAudioPlaybackBuffer = new NetBufferedAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
    #endif     
        } catch (exception&) {
            jack_error("NetAudioBuffer allocation error...");
            return false;
        }
    
sletz's avatar
sletz committed
772
        //set the new buffer sizes
sletz's avatar
sletz committed
773
774
775
776
777
778
779
780
781
782
783
784
785
        if ( SetNetBufferSize() == SOCKET_ERROR ) {
            jack_error ( "Can't set net buffer sizes : %s", StrError ( NET_ERROR_CODE ) );
            goto error;
        }
     
        return true;
        
    error:
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        return false;
moret's avatar
moret committed
786
787
    }

sletz's avatar
sletz committed
788
    int JackNetSlaveInterface::Recv(size_t size, int flags)
789
    {
sletz's avatar
sletz committed
790
        int rx_bytes = fSocket.Recv(fRxBuffer, size, flags);
791
792
793
794
795
        //handle errors
        if ( rx_bytes == SOCKET_ERROR )
        {
            net_error_t error = fSocket.GetError();
            //no data isn't really an error in realtime processing, so just return 0
sletz's avatar
sletz committed
796
            if ( error == NET_NO_DATA ) {
797
798
                jack_error ( "No data, is the master still running ?" );
            //if a network error occurs, this exception will restart the driver
sletz's avatar
sletz committed
799
            } else if ( error == NET_CONN_ERROR ) {
800
                jack_error ( "Connection lost." );
moret's avatar
moret committed
801
                throw JackNetException();
sletz's avatar
sletz committed
802
            } else {
sletz's avatar
sletz committed
803
                jack_error ( "Fatal error in slave receive : %s", StrError ( NET_ERROR_CODE ) );
sletz's avatar
sletz committed
804
            }
805
        }
806
807
808
        
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
809
        return rx_bytes;
810
811
    }

sletz's avatar
sletz committed
812
    int JackNetSlaveInterface::Send(size_t size, int flags)
813
    {
814
815
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
        PacketHeaderHToN(header, header);
816
        int tx_bytes = fSocket.Send ( fTxBuffer, size, flags );
817
         
818
819
        //handle errors
        if ( tx_bytes == SOCKET_ERROR )
820
821
        {
            net_error_t error = fSocket.GetError();
822
            //if a network error occurs, this exception will restart the driver
sletz's avatar
sletz committed
823
            if ( error == NET_CONN_ERROR ) {
824
                jack_error ( "Connection lost." );
moret's avatar
moret committed
825
                throw JackNetException();
sletz's avatar
sletz committed
826
            } else {
sletz's avatar
sletz committed
827
                jack_error ( "Fatal error in slave send : %s", StrError ( NET_ERROR_CODE ) );
sletz's avatar
sletz committed
828
            }
829
830
831
832
        }
        return tx_bytes;
    }

833
    int JackNetSlaveInterface::SyncRecv()
834
    {
835
836
        int rx_bytes = 0;
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
sletz's avatar
sletz committed
837
        
838
839
        //receive sync (launch the cycle)
        do
840
        {
sletz's avatar
sletz committed
841
            rx_bytes = Recv(HEADER_SIZE, 0);
842
843
844
845
            //connection issue, send will detect it, so don't skip the cycle (return 0)
            if ( rx_bytes == SOCKET_ERROR )
                return rx_bytes;
        }