JackNetInterface.cpp 38.2 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
42
43
44
45
46
47
    JackNetInterface::JackNetInterface() : fSocket()
    {
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
48
49
        memset(&fSendTransportData, 0, sizeof(net_transport_data_t));
        memset(&fReturnTransportData, 0, sizeof(net_transport_data_t));
50
51
    }

moret's avatar
moret committed
52
    JackNetInterface::JackNetInterface ( const char* multicast_ip, int port ) : fSocket ( multicast_ip, port )
53
    {
54
        strcpy(fMulticastIP, multicast_ip);
55
56
57
58
59
60
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
61
62
        memset(&fSendTransportData, 0, sizeof(net_transport_data_t));
        memset(&fReturnTransportData, 0, sizeof(net_transport_data_t));
63
64
    }

moret's avatar
moret committed
65
    JackNetInterface::JackNetInterface ( session_params_t& params, JackNetSocket& socket, const char* multicast_ip ) : fSocket ( socket )
66
    {
moret's avatar
moret committed
67
        fParams = params;
68
        strcpy(fMulticastIP, multicast_ip);
69
70
71
72
73
74
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
75
76
        memset(&fSendTransportData, 0, sizeof(net_transport_data_t));
        memset(&fReturnTransportData, 0, sizeof(net_transport_data_t));
77
78
79
80
    }

    JackNetInterface::~JackNetInterface()
    {
moret's avatar
moret 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
94
    int JackNetInterface::SetNetBufferSize()
    {
        //audio
sletz's avatar
sletz committed
95
96
97
98
99
100
        float audio_size = (fNetAudioCaptureBuffer) 
                            ? fNetAudioCaptureBuffer->GetCycleSize() 
                            : (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->GetCycleSize() : 0;
                            
        jack_log ("audio_size %f", audio_size);
        
moret's avatar
moret committed
101
        //midi
sletz's avatar
sletz committed
102
103
104
105
106
107
        float midi_size = (fNetMidiCaptureBuffer) 
                            ? fNetMidiCaptureBuffer->GetCycleSize() 
                            : (fNetMidiPlaybackBuffer) ? fNetMidiPlaybackBuffer->GetCycleSize() : 0;
        
        jack_log ("midi_size %f", midi_size);
                                     
moret's avatar
moret committed
108
        //bufsize = sync + audio + midi
sletz's avatar
sletz committed
109
        int bufsize = MAX_LATENCY * (fParams.fMtu + (int)audio_size + (int) midi_size);
sletz's avatar
sletz committed
110
111
        
        jack_log("SetNetBufferSize bufsize = %d", bufsize);
moret's avatar
moret committed
112
113

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

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

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

sletz's avatar
sletz committed
124
    bool JackNetInterface::SetParams()
125
126
127
128
129
130
131
    {
        //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
132
        fTxHeader.fIsLastPckt = 0;
133
134
135
136
137
138
139

        //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
140
        fRxHeader.fIsLastPckt = 0;
141
142
143
144

        //network buffers
        fTxBuffer = new char[fParams.fMtu];
        fRxBuffer = new char[fParams.fMtu];
145
146
        assert ( fTxBuffer );
        assert ( fRxBuffer );
147

moret's avatar
moret committed
148
        //net audio/midi buffers'addresses
sletz's avatar
sletz committed
149
150
        fTxData = fTxBuffer + HEADER_SIZE;
        fRxData = fRxBuffer + HEADER_SIZE;
sletz's avatar
sletz committed
151
152
        
        return true;
153
154
    }

155
    // JackNetMasterInterface ************************************************************************************
156

157
    bool JackNetMasterInterface::Init()
158
    {
159
        jack_log ( "JackNetMasterInterface::Init, ID %u.", fParams.fID );
160

161
        session_params_t host_params;
162
        uint attempt = 0;
163
164
165
        int rx_bytes = 0;

        //socket
sletz's avatar
sletz committed
166
        if ( fSocket.NewSocket() == SOCKET_ERROR ) {
167
168
            jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
            return false;
169
170
        }

171
        //timeout on receive (for init)
172
        if ( fSocket.SetTimeOut ( MASTER_INIT_TIMEOUT ) < 0 )
173
            jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );
174
            
175
        //connect
sletz's avatar
sletz committed
176
        if ( fSocket.Connect() == SOCKET_ERROR ) {
177
178
179
            jack_error ( "Can't connect : %s", StrError ( NET_ERROR_CODE ) );
            return false;
        }
180

181
        //send 'SLAVE_SETUP' until 'START_MASTER' received
sletz's avatar
sletz committed
182
        jack_info ( "Sending parameters to %s...", fParams.fSlaveNetName );
183
184
        do
        {
185
            session_params_t net_params;
sletz's avatar
sletz committed
186
            memset(&net_params, 0, sizeof ( session_params_t ));
187
            SetPacketType ( &fParams, SLAVE_SETUP );
188
189
190
            SessionParamsHToN(&fParams, &net_params);
            
            if ( fSocket.Send ( &net_params, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
191
                jack_error ( "Error in send : ", StrError ( NET_ERROR_CODE ) );
192
193
194
                
            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 ) )
195
            {
196
197
                jack_error ( "Problem with network." );
                return false;
198
            }
199
200
            
            SessionParamsNToH(&net_params, &host_params);
201
        }
202
        while ( ( GetPacketType ( &host_params ) != START_MASTER ) && ( ++attempt < SLAVE_SETUP_RETRY ) );
sletz's avatar
sletz committed
203
        if ( attempt == SLAVE_SETUP_RETRY ) {
204
205
            jack_error ( "Slave doesn't respond, exiting." );
            return false;
206
207
        }

208
        return true;
209
210
    }

moret's avatar
moret committed
211
212
    int JackNetMasterInterface::SetRxTimeout()
    {
moret's avatar
moret committed
213
214
        jack_log ( "JackNetMasterInterface::SetRxTimeout" );

moret's avatar
moret committed
215
        float time = 0;
sletz's avatar
sletz committed
216
        
moret's avatar
moret committed
217
        //slow or normal mode, short timeout on recv (2 audio subcycles)
sletz's avatar
sletz committed
218
219
220
221
222
        if ((fParams.fNetworkMode == 's') || (fParams.fNetworkMode == 'n')) {
            time = 2000000.f * ((fNetAudioCaptureBuffer) 
                                ? fNetAudioCaptureBuffer->GetCycleDuration() 
                                : (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->GetCycleDuration() : 0);
        }
moret's avatar
moret committed
223
        //fast mode, wait for 75% of the entire cycle duration
sletz's avatar
sletz committed
224
225
226
227
228
        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
229
230
    }

sletz's avatar
sletz committed
231
    bool JackNetMasterInterface::SetParams()
moret's avatar
moret committed
232
    {
233
        jack_log ( "JackNetMasterInterface::SetParams" );
moret's avatar
moret committed
234
235
236

        JackNetInterface::SetParams();

237
238
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
239
240

        //midi net buffers
241
242
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fTxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fRxData );
243
244
        assert ( fNetMidiCaptureBuffer );
        assert ( fNetMidiPlaybackBuffer );
moret's avatar
moret committed
245

sletz's avatar
sletz committed
246
        try {
moret's avatar
moret committed
247
        //audio net buffers
sletz's avatar
sletz committed
248
249
250
251
252
253
254
255
256
257
258
    #ifdef CELT
            fNetAudioCaptureBuffer = new NetCeltAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
            fNetAudioPlaybackBuffer = new NetCeltAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );
    #else
            fNetAudioCaptureBuffer = new NetSingleAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
            fNetAudioPlaybackBuffer = new NetSingleAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );
    #endif    
        } catch (exception&) {
            jack_error("NetAudioBuffer allocation error...");
            return false;
        }
259
260
261
262
        
        //fNetAudioCaptureBuffer = new NetBufferedAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
        //fNetAudioPlaybackBuffer = new NetBufferedAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );     
     
263
264
        assert ( fNetAudioCaptureBuffer );
        assert ( fNetAudioPlaybackBuffer );
sletz's avatar
sletz committed
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
        
        //set the new timeout for the socket
        if ( SetRxTimeout() == SOCKET_ERROR ) {
            jack_error ( "Can't set rx timeout : %s", StrError ( NET_ERROR_CODE ) );
            goto error;
        }

        //set the new rx buffer size
        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
287
288
    }

289
    void JackNetMasterInterface::Exit()
290
    {
291
292
293
294
        jack_log ( "JackNetMasterInterface::Exit, ID %u", fParams.fID );

        //stop process
        fRunning = false;
295

296
297
298
299
        //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() );
300
301
        
        session_params_t net_params;
sletz's avatar
sletz committed
302
        memset(&net_params, 0, sizeof ( session_params_t ));
303
304
        SessionParamsHToN(&fParams, &net_params);

305
306
        if ( mcast_socket.NewSocket() == SOCKET_ERROR )
            jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
307
        if ( mcast_socket.SendTo ( &net_params, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
308
            jack_error ( "Can't send suicide request : %s", StrError ( NET_ERROR_CODE ) );
309
            
310
311
312
        mcast_socket.Close();
    }

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

    int JackNetMasterInterface::DataSend()
    {
        uint subproc;
sletz's avatar
sletz committed
386
387
        uint data_size; 
        
388
        //midi
389
        if ( fParams.fSendMidiChannels > 0)
390
        {
391
392
            //set global header fields and get the number of midi packets
            fTxHeader.fDataType = 'm';
sletz's avatar
sletz committed
393
394
395
396
            data_size = fNetMidiCaptureBuffer->RenderFromJackPorts();
            fTxHeader.fNumPacket = fNetMidiCaptureBuffer->GetNumPackets();
            
            for ( subproc = 0; subproc < fTxHeader.fNumPacket; subproc++ )
397
            {
398
                fTxHeader.fSubCycle = subproc;
sletz's avatar
sletz committed
399
400
                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
401
402
                memcpy ( fTxBuffer, &fTxHeader, HEADER_SIZE);
                if (Send (fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
403
                    return SOCKET_ERROR;
404
405
            }
        }
406
407

        //audio
408
        if ( fParams.fSendAudioChannels > 0)
409
410
        {
            fTxHeader.fDataType = 'a';
sletz's avatar
sletz committed
411
412
413
414
            data_size = fNetAudioCaptureBuffer->RenderFromJackPorts();
            fTxHeader.fNumPacket = fNetAudioCaptureBuffer->GetNumPackets();
            
            for (subproc = 0; subproc < fTxHeader.fNumPacket; subproc++)
415
416
            {
                fTxHeader.fSubCycle = subproc;
sletz's avatar
sletz committed
417
418
                fTxHeader.fIsLastPckt = (subproc == (fTxHeader.fNumPacket - 1)) ? 1 : 0;
                fTxHeader.fPacketSize = HEADER_SIZE + fNetAudioCaptureBuffer->RenderToNetwork(subproc, data_size);
sletz's avatar
sletz committed
419
420
                memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
                if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
421
422
423
424
425
                    return SOCKET_ERROR;
            }
        }

        return 0;
426
427
    }

428
    int JackNetMasterInterface::SyncRecv()
429
430
    {
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
sletz's avatar
sletz committed
431
        int rx_bytes = Recv(HEADER_SIZE, MSG_PEEK);
432
        
433
434
435
        if ( ( rx_bytes == 0 ) || ( rx_bytes == SOCKET_ERROR ) )
            return rx_bytes;

436
        fCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
437
      
438
        switch ( fParams.fNetworkMode )
439
        {
440
            case 's' :
moret's avatar
moret committed
441
442
443
444
445
                //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)
446
                if (fCycleOffset < CYCLE_OFFSET_SLOW) {
sletz's avatar
sletz committed
447
448
                    return 0;
                } else {
449
                    rx_bytes = Recv ( rx_head->fPacketSize, 0 );
sletz's avatar
sletz committed
450
                }
451
452
                
                if (fCycleOffset > CYCLE_OFFSET_SLOW) {
453
454
                    jack_info("Warning : '%s' runs in slow network mode, but data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
                }
455
                break;
456

457
458
459
460
461
            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
462
                if (fCycleOffset < CYCLE_OFFSET_NORMAL) {
463
                    return 0;
sletz's avatar
sletz committed
464
                } else {
465
                    rx_bytes = Recv ( rx_head->fPacketSize, 0 );
sletz's avatar
sletz committed
466
                }
467
                    
sletz's avatar
sletz committed
468
                if (fCycleOffset > CYCLE_OFFSET_NORMAL)  {
469
                    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
470
                }
471
                break;
472

473
474
475
476
477
478
            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 );
479
                
sletz's avatar
sletz committed
480
                if (fCycleOffset > CYCLE_OFFSET_FAST) {
481
                    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
482
                }
483
                break;
484
        }
485

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

moret's avatar
moret committed
522
                    case 'a':   //audio
sletz's avatar
sletz committed
523
                        rx_bytes = Recv(rx_head->fPacketSize, 0);
moret's avatar
moret committed
524
525
                        fRxHeader.fCycle = rx_head->fCycle;
                        fRxHeader.fSubCycle = rx_head->fSubCycle;
moret's avatar
moret committed
526
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
sletz's avatar
sletz committed
527
528
529
                        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
530
                            fNetAudioPlaybackBuffer->RenderToJackPorts();
moret's avatar
moret committed
531
                        break;
532

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

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

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

575
576
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
577
578
    uint JackNetSlaveInterface::fSlaveCounter = 0;

579
    bool JackNetSlaveInterface::Init()
580
    {
581
        jack_log ( "JackNetSlaveInterface::Init()" );
582

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

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

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

609
610
        return true;
    }
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
    
    // 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
627
            status = SendAvailableToMaster();
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
            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;
    }
653

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

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

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

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

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

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

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

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

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

        JackNetInterface::SetParams();

739
740
        fTxHeader.fDataStream = 'r';
        fRxHeader.fDataStream = 's';
moret's avatar
moret committed
741
742

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

        //audio net buffers
sletz's avatar
sletz committed
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
        //fNetAudioCaptureBuffer = new NetSingleAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
        //fNetAudioPlaybackBuffer = new NetSingleAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
    
        try {
    #ifdef CELT
            fNetAudioCaptureBuffer = new NetCeltAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
            fNetAudioPlaybackBuffer = new NetCeltAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
    #else
            fNetAudioCaptureBuffer = new NetSingleAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
            fNetAudioPlaybackBuffer = new NetSingleAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
            //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
767
768
        assert ( fNetAudioCaptureBuffer );
        assert ( fNetAudioPlaybackBuffer );
sletz's avatar
sletz committed
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
        
         //set the new buffer sizes
        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
784
785
    }

786
    int JackNetSlaveInterface::Recv ( size_t size, int flags )
787
    {
788
789
790
791
792
793
        int rx_bytes = fSocket.Recv ( fRxBuffer, size, flags );
        //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
794
            if ( error == NET_NO_DATA ) {
795
796
                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
797
            } else if ( error == NET_CONN_ERROR ) {
798
                jack_error ( "Connection lost." );
moret's avatar
moret committed
799
                throw JackNetException();
sletz's avatar
sletz committed
800
            } else {
sletz's avatar
sletz committed
801
                jack_error ( "Fatal error in slave receive : %s", StrError ( NET_ERROR_CODE ) );
sletz's avatar
sletz committed
802
            }
803
        }
804
805
806
        
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
807
        return rx_bytes;
808
809
    }

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

831
    int JackNetSlaveInterface::SyncRecv()
832
    {
833
834
        int rx_bytes = 0;
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
sletz's avatar
sletz committed
835
        
836
837
        //receive sync (launch the cycle)
        do
838
        {
sletz's avatar
sletz committed
839
            rx_bytes = Recv(HEADER_SIZE, 0);
840
841
842
843
            //connection issue, send will detect it, so don't skip the cycle (return 0)
            if ( rx_bytes == SOCKET_ERROR )
                return rx_bytes;
        }
844
845
        while ((strcmp(rx_head->fPacketType, "header") != 0) && (rx_head->fDataType != 's'));
        
moret's avatar
moret committed
846
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
847
848
849
850
851
852
        return rx_bytes;
    }

    int JackNetSlaveInterface::DataRecv()
    {
        int rx_bytes = 0;
sletz's avatar
sletz committed
853
        uint recvd_midi_pckt = 0;
sletz's avatar
sletz committed
854
        uint recvd_audio_pckt = 0;
sletz's avatar
sletz committed
855
      
856
857
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );

moret's avatar
moret committed
858
        while ( !fRxHeader.fIsLastPckt )
859
        {
sletz's avatar
sletz committed
860
            //how much data is queued on the rx buffer ?
sletz's avatar
sletz committed
861
            rx_bytes = Recv(HEADER_SIZE, MSG_PEEK);
sletz's avatar
sletz committed
862
            
moret's avatar
moret committed
863
864
865
            //error here, problem with recv, just skip the cycle (return -1)
            if ( rx_bytes == SOCKET_ERROR )
                return rx_bytes;
sletz's avatar
sletz committed
866
                
moret's avatar
moret committed
867
            if ( rx_bytes && ( rx_head->fDataStream == 's' ) && ( rx_head->fID == fParams.fID ) )
868
            {
moret's avatar
moret committed
869
                switch ( rx_head->fDataType )
870
                {
moret's avatar
moret committed
871
                    case 'm':   //midi
sletz's avatar
sletz committed
872
                        rx_bytes = Recv(rx_head->fPacketSize, 0);
moret's avatar