JackNetInterface.cpp 40.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
28
#define PACKET_AVAILABLE_SIZE (fParams.fMtu - sizeof(packet_header_t))

29
30
31
32
33
34
/*  
 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)
*/

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

39
40
41
42
43
44
45
46
    JackNetInterface::JackNetInterface() : fSocket()
    {
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
47
48
        memset(&fSendTransportData, 0, sizeof(net_transport_data_t));
        memset(&fReturnTransportData, 0, sizeof(net_transport_data_t));
49
50
    }

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

moret's avatar
moret committed
64
    JackNetInterface::JackNetInterface ( session_params_t& params, JackNetSocket& socket, const char* multicast_ip ) : fSocket ( socket )
65
    {
sletz's avatar
sletz committed
66
        jack_log("JackNetInterface ( session_params_t& params...)");
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;
    }

92
    void JackNetInterface::SetFramesPerPacket()
moret's avatar
moret committed
93
    {
moret's avatar
moret committed
94
        jack_log ( "JackNetInterface::SetFramesPerPacket" );
moret's avatar
moret committed
95

96
97
98
        if (fParams.fSendAudioChannels == 0 && fParams.fReturnAudioChannels == 0) {
            fParams.fFramesPerPacket = fParams.fPeriodSize;
        } else {
sletz's avatar
sletz committed
99
            jack_nframes_t period = ( int ) powf ( 2.f, ( int ) ( log (float (PACKET_AVAILABLE_SIZE)
100
101
102
                                               / ( max ( fParams.fReturnAudioChannels, fParams.fSendAudioChannels ) * sizeof ( sample_t ) ) ) / log ( 2. ) ) );
            fParams.fFramesPerPacket = ( period > fParams.fPeriodSize ) ? fParams.fPeriodSize : period;
        }
moret's avatar
moret committed
103
104
105
106
    }

    int JackNetInterface::SetNetBufferSize()
    {
moret's avatar
moret committed
107
        jack_log ( "JackNetInterface::SetNetBufferSize" );
moret's avatar
moret committed
108

moret's avatar
moret committed
109
        float audio_size, midi_size;
110
        int bufsize;
moret's avatar
moret committed
111
112
113
114
        //audio
        audio_size = fParams.fMtu * ( fParams.fPeriodSize / fParams.fFramesPerPacket );
        //midi
        midi_size = fParams.fMtu * ( max ( fParams.fSendMidiChannels, fParams.fReturnMidiChannels ) *
sletz's avatar
sletz committed
115
                                     fParams.fPeriodSize * sizeof(sample_t) / PACKET_AVAILABLE_SIZE);
moret's avatar
moret committed
116
        //bufsize = sync + audio + midi
117
        bufsize = MAX_LATENCY * (fParams.fMtu + ( int ) audio_size + ( int ) midi_size);
118
        jack_info("SetNetBufferSize bufsize = %d", bufsize);
moret's avatar
moret committed
119
120
121

        //tx buffer
        if ( fSocket.SetOption ( SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof ( bufsize ) ) == SOCKET_ERROR )
122
            return SOCKET_ERROR;
moret's avatar
moret committed
123
124
125

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

128
        return 0;
moret's avatar
moret committed
129
130
131
132
133
134
    }

    int JackNetInterface::GetNMidiPckt()
    {
        //even if there is no midi data, jack need an empty buffer to know there is no event to read
        //99% of the cases : all data in one packet
sletz's avatar
sletz committed
135
136
        
        if (fTxHeader.fMidiDataSize <= PACKET_AVAILABLE_SIZE) {
moret's avatar
moret committed
137
            return 1;
sletz's avatar
sletz committed
138
139
140
141
142
        } else { //get the number of needed packets (simply slice the biiig buffer)
            return (fTxHeader.fMidiDataSize % PACKET_AVAILABLE_SIZE) 
                    ? (fTxHeader.fMidiDataSize / PACKET_AVAILABLE_SIZE + 1) 
                    : fTxHeader.fMidiDataSize / PACKET_AVAILABLE_SIZE;
        }
moret's avatar
moret committed
143
144
145
146
147
148
    }

    bool JackNetInterface::IsNextPacket()
    {
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
        //ignore first cycle
149
        if ( fRxHeader.fCycle <= 1 ) {
moret's avatar
moret committed
150
            return true;
151
        }
moret's avatar
moret committed
152
        //same PcktID (cycle), next SubPcktID (subcycle)
153
154
155
        if ( ( fRxHeader.fSubCycle < ( fNSubProcess - 1 ) ) && ( rx_head->fCycle == fRxHeader.fCycle ) && ( rx_head->fSubCycle == ( fRxHeader.fSubCycle + 1 ) ) ) {
             return true;
        }
moret's avatar
moret committed
156
        //next PcktID (cycle), SubPcktID reset to 0 (first subcyle)
157
        if ( ( rx_head->fCycle == ( fRxHeader.fCycle + 1 ) ) && ( fRxHeader.fSubCycle == ( fNSubProcess - 1 ) ) && ( rx_head->fSubCycle == 0 ) ) {
moret's avatar
moret committed
158
            return true;
159
        }
moret's avatar
moret committed
160
        //else, packet(s) missing, return false
moret's avatar
moret committed
161
162
163
        return false;
    }

164
165
    void JackNetInterface::SetParams()
    {
moret's avatar
moret committed
166
        //number of audio subcycles (packets)
167
168
        fNSubProcess = fParams.fPeriodSize / fParams.fFramesPerPacket;

moret's avatar
moret committed
169
        //payload size
sletz's avatar
sletz committed
170
        fPayloadSize = PACKET_AVAILABLE_SIZE;
moret's avatar
moret committed
171

172
173
174
175
176
177
178
        //TX header init
        strcpy ( fTxHeader.fPacketType, "header" );
        fTxHeader.fID = fParams.fID;
        fTxHeader.fCycle = 0;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fMidiDataSize = 0;
        fTxHeader.fBitdepth = fParams.fBitdepth;
moret's avatar
moret committed
179
        fTxHeader.fIsLastPckt = 0;
180
181
182
183
184
185
186
187

        //RX header init
        strcpy ( fRxHeader.fPacketType, "header" );
        fRxHeader.fID = fParams.fID;
        fRxHeader.fCycle = 0;
        fRxHeader.fSubCycle = 0;
        fRxHeader.fMidiDataSize = 0;
        fRxHeader.fBitdepth = fParams.fBitdepth;
moret's avatar
moret committed
188
        fRxHeader.fIsLastPckt = 0;
189
190
191
192

        //network buffers
        fTxBuffer = new char[fParams.fMtu];
        fRxBuffer = new char[fParams.fMtu];
193
194
        assert ( fTxBuffer );
        assert ( fRxBuffer );
195

moret's avatar
moret committed
196
        //net audio/midi buffers'addresses
197
198
199
200
        fTxData = fTxBuffer + sizeof ( packet_header_t );
        fRxData = fRxBuffer + sizeof ( packet_header_t );
    }

201
    // JackNetMasterInterface ************************************************************************************
202

203
    bool JackNetMasterInterface::Init()
204
    {
205
        jack_log ( "JackNetMasterInterface::Init, ID %u.", fParams.fID );
206

207
        session_params_t host_params;
208
        uint attempt = 0;
209
210
211
        int rx_bytes = 0;

        //socket
sletz's avatar
sletz committed
212
        if ( fSocket.NewSocket() == SOCKET_ERROR ) {
213
214
            jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
            return false;
215
216
        }

217
        //timeout on receive (for init)
218
        if ( fSocket.SetTimeOut ( MASTER_INIT_TIMEOUT ) < 0 )
219
            jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );
220
            
221
        //connect
sletz's avatar
sletz committed
222
        if ( fSocket.Connect() == SOCKET_ERROR ) {
223
224
225
            jack_error ( "Can't connect : %s", StrError ( NET_ERROR_CODE ) );
            return false;
        }
226

moret's avatar
moret committed
227
        //set the number of complete audio frames we can put in a packet
moret's avatar
moret committed
228
229
        SetFramesPerPacket();

230
231
        //send 'SLAVE_SETUP' until 'START_MASTER' received
        jack_info ( "Sending parameters to %s ...", fParams.fSlaveNetName );
232
233
        do
        {
234
            session_params_t net_params;
sletz's avatar
sletz committed
235
            memset(&net_params, 0, sizeof ( session_params_t ));
236
            SetPacketType ( &fParams, SLAVE_SETUP );
237
238
239
            SessionParamsHToN(&fParams, &net_params);
            
            if ( fSocket.Send ( &net_params, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
240
                jack_error ( "Error in send : ", StrError ( NET_ERROR_CODE ) );
241
242
243
                
            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 ) )
244
            {
245
246
                jack_error ( "Problem with network." );
                return false;
247
            }
248
249
            
            SessionParamsNToH(&net_params, &host_params);
250
        }
251
        while ( ( GetPacketType ( &host_params ) != START_MASTER ) && ( ++attempt < SLAVE_SETUP_RETRY ) );
sletz's avatar
sletz committed
252
        if ( attempt == SLAVE_SETUP_RETRY ) {
253
254
            jack_error ( "Slave doesn't respond, exiting." );
            return false;
255
256
        }

257
        //set the new timeout for the socket
sletz's avatar
sletz committed
258
        if ( SetRxTimeout() == SOCKET_ERROR ) {
259
260
261
            jack_error ( "Can't set rx timeout : %s", StrError ( NET_ERROR_CODE ) );
            return false;
        }
262

263
        //set the new rx buffer size
sletz's avatar
sletz committed
264
        if ( SetNetBufferSize() == SOCKET_ERROR ) {
moret's avatar
moret committed
265
            jack_error ( "Can't set net buffer sizes : %s", StrError ( NET_ERROR_CODE ) );
266
            return false;
267
        }
268
269

        return true;
270
271
    }

moret's avatar
moret committed
272
273
    int JackNetMasterInterface::SetRxTimeout()
    {
moret's avatar
moret committed
274
275
        jack_log ( "JackNetMasterInterface::SetRxTimeout" );

moret's avatar
moret committed
276
        float time = 0;
moret's avatar
moret committed
277
278
        //slow or normal mode, short timeout on recv (2 audio subcycles)
        if ( ( fParams.fNetworkMode == 's' ) || ( fParams.fNetworkMode == 'n' ) )
moret's avatar
moret committed
279
            time = 2000000.f * ( static_cast<float> ( fParams.fFramesPerPacket ) / static_cast<float> ( fParams.fSampleRate ) );
moret's avatar
moret committed
280
        //fast mode, wait for 75% of the entire cycle duration
moret's avatar
moret committed
281
282
283
284
285
        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 ) );
    }

286
    void JackNetMasterInterface::SetParams()
moret's avatar
moret committed
287
    {
288
        jack_log ( "JackNetMasterInterface::SetParams" );
moret's avatar
moret committed
289
290
291

        JackNetInterface::SetParams();

292
293
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
294
295

        //midi net buffers
296
297
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fTxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fRxData );
298
299
        assert ( fNetMidiCaptureBuffer );
        assert ( fNetMidiPlaybackBuffer );
moret's avatar
moret committed
300
301

        //audio net buffers
302
303
304
305
306
307
        fNetAudioCaptureBuffer = new NetSingleAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
        fNetAudioPlaybackBuffer = new NetSingleAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );
        
        //fNetAudioCaptureBuffer = new NetBufferedAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
        //fNetAudioPlaybackBuffer = new NetBufferedAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );     
     
308
309
        assert ( fNetAudioCaptureBuffer );
        assert ( fNetAudioPlaybackBuffer );
moret's avatar
moret committed
310
311

        //audio netbuffer length
312
313
        fAudioTxLen = sizeof ( packet_header_t ) + fNetAudioCaptureBuffer->GetSize();
        fAudioRxLen = sizeof ( packet_header_t ) + fNetAudioPlaybackBuffer->GetSize();
moret's avatar
moret committed
314
315
    }

316
    void JackNetMasterInterface::Exit()
317
    {
318
319
320
321
        jack_log ( "JackNetMasterInterface::Exit, ID %u", fParams.fID );

        //stop process
        fRunning = false;
322

323
324
325
326
        //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() );
327
328
        
        session_params_t net_params;
sletz's avatar
sletz committed
329
        memset(&net_params, 0, sizeof ( session_params_t ));
330
331
        SessionParamsHToN(&fParams, &net_params);

332
333
        if ( mcast_socket.NewSocket() == SOCKET_ERROR )
            jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
334
        if ( mcast_socket.SendTo ( &net_params, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
335
            jack_error ( "Can't send suicide request : %s", StrError ( NET_ERROR_CODE ) );
336
            
337
338
339
        mcast_socket.Close();
    }

340
    int JackNetMasterInterface::Recv ( size_t size, int flags )
341
    {
342
343
        int rx_bytes;
        if ( ( ( rx_bytes = fSocket.Recv ( fRxBuffer, size, flags ) ) == SOCKET_ERROR ) && fRunning )
344
345
        {
            net_error_t error = fSocket.GetError();
346
347
348
349
            //no data isn't really a network error, so just return 0 avalaible read bytes
            if ( error == NET_NO_DATA )
                return 0;
            else if ( error == NET_CONN_ERROR )
350
351
352
            {
                //fatal connection issue, exit
                jack_error ( "'%s' : %s, exiting.", fParams.fName, StrError ( NET_ERROR_CODE ) );
353
                //ask to the manager to properly remove the master
354
                Exit();
sletz's avatar
sletz committed
355
356
357
                
                // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
                ThreadExit();
358
            }
moret's avatar
moret committed
359
            else
360
                jack_error ( "Error in master receive : %s", StrError ( NET_ERROR_CODE ) );
361
        }
362
363
364
365
        
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
        return rx_bytes;
366
    }
367
368
    
    int JackNetMasterInterface::Send ( size_t size, int flags )
369
    {
370
371
372
373
374
        int tx_bytes;
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
        PacketHeaderHToN(header, header);
        
        if ( ( ( tx_bytes = fSocket.Send ( fTxBuffer, size, flags ) ) == SOCKET_ERROR ) && fRunning )
375
376
        {
            net_error_t error = fSocket.GetError();
377
            if ( error == NET_CONN_ERROR )
378
            {
379
380
381
                //fatal connection issue, exit
                jack_error ( "'%s' : %s, exiting.", fParams.fName, StrError ( NET_ERROR_CODE ) );
                Exit();
sletz's avatar
sletz committed
382
383
384
                
                // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
                ThreadExit();
385
            }
moret's avatar
moret committed
386
            else
387
                jack_error ( "Error in master send : %s", StrError ( NET_ERROR_CODE ) );
388
        }
389
        return tx_bytes;
390
    }
391
392
393
    
    bool JackNetMasterInterface::IsSynched()
    {
sletz's avatar
sletz committed
394
        if (fParams.fNetworkMode == 's') {
395
            return (fCycleOffset < (CYCLE_OFFSET_SLOW + 1));
sletz's avatar
sletz committed
396
        } else {
397
            return true;
sletz's avatar
sletz committed
398
        }
399
400
    }
    
401
    int JackNetMasterInterface::SyncSend()
402
    {
403
404
405
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
406
        fTxHeader.fIsLastPckt = ( fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ?  1 : 0;
407
408
409
410
411
412
413
414
415
        fTxHeader.fPacketSize = fParams.fMtu;
        memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
        return Send ( fTxHeader.fPacketSize, 0 );
    }

    int JackNetMasterInterface::DataSend()
    {
        uint subproc;
        //midi
416
        if ( fParams.fSendMidiChannels > 0)
417
        {
418
419
420
            //set global header fields and get the number of midi packets
            fTxHeader.fDataType = 'm';
            fTxHeader.fMidiDataSize = fNetMidiCaptureBuffer->RenderFromJackPorts();
moret's avatar
moret committed
421
            fTxHeader.fNMidiPckt = GetNMidiPckt();
422
            for ( subproc = 0; subproc < fTxHeader.fNMidiPckt; subproc++ )
423
            {
424
                fTxHeader.fSubCycle = subproc;
425
                fTxHeader.fIsLastPckt = ( ( subproc == ( fTxHeader.fNMidiPckt - 1 ) ) && (fParams.fSendAudioChannels == 0)) ? 1 : 0;
426
                fTxHeader.fPacketSize = sizeof ( packet_header_t ) + fNetMidiCaptureBuffer->RenderToNetwork ( subproc, fTxHeader.fMidiDataSize );
427
428
429
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
                if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
                    return SOCKET_ERROR;
430
431
            }
        }
432
433

        //audio
434
        if ( fParams.fSendAudioChannels > 0)
435
436
        {
            fTxHeader.fDataType = 'a';
437
438
            fTxHeader.fMidiDataSize = 0;
            fTxHeader.fNMidiPckt = 0;
439
440
441
            for ( subproc = 0; subproc < fNSubProcess; subproc++ )
            {
                fTxHeader.fSubCycle = subproc;
moret's avatar
moret committed
442
                fTxHeader.fIsLastPckt = ( subproc == ( fNSubProcess - 1 ) ) ? 1 : 0;
443
444
445
446
447
448
449
450
451
                fTxHeader.fPacketSize = fAudioTxLen;
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
                fNetAudioCaptureBuffer->RenderFromJackPorts ( subproc );
                if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
                    return SOCKET_ERROR;
            }
        }

        return 0;
452
453
    }

454
    int JackNetMasterInterface::SyncRecv()
455
456
    {
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
457
458
        int rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
        
459
460
461
        if ( ( rx_bytes == 0 ) || ( rx_bytes == SOCKET_ERROR ) )
            return rx_bytes;

462
        fCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
463
      
464
        switch ( fParams.fNetworkMode )
465
        {
466
            case 's' :
moret's avatar
moret committed
467
468
469
470
471
                //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)
472
                if (fCycleOffset < CYCLE_OFFSET_SLOW) {
sletz's avatar
sletz committed
473
474
                    return 0;
                } else {
475
                    rx_bytes = Recv ( rx_head->fPacketSize, 0 );
sletz's avatar
sletz committed
476
                }
477
478
                
                if (fCycleOffset > CYCLE_OFFSET_SLOW) {
479
480
                    jack_info("Warning : '%s' runs in slow network mode, but data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
                }
481
                break;
482

483
484
485
486
487
            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
488
                if (fCycleOffset < 1) {
489
                    return 0;
sletz's avatar
sletz committed
490
                } else {
491
                    rx_bytes = Recv ( rx_head->fPacketSize, 0 );
sletz's avatar
sletz committed
492
                }
493
                    
sletz's avatar
sletz committed
494
                if (fCycleOffset != 1)  {
495
                    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
496
                }
497
                break;
498

499
500
501
502
503
504
            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 );
505
                
sletz's avatar
sletz committed
506
                if (fCycleOffset != 0) {
507
                    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
508
                }
509
                break;
510
        }
511

moret's avatar
moret committed
512
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
513
514
        return rx_bytes;
    }
515
    
516
    int JackNetMasterInterface::DataRecv()
517
518
    {
        int rx_bytes = 0;
519
        uint jumpcnt = 0;
520
        uint recvd_midi_pckt = 0;
521
        uint recvd_audio_pckt = 0;
522
523
        int last_cycle = 0;
         
524
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
525
        
moret's avatar
moret committed
526
        while ( !fRxHeader.fIsLastPckt )
527
        {
moret's avatar
moret committed
528
529
            //how much data is queued on the rx buffer ?
            rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
530
              
moret's avatar
moret committed
531
532
            if ( rx_bytes == SOCKET_ERROR )
                return rx_bytes;
moret's avatar
moret committed
533
            //if no data
moret's avatar
moret committed
534
            if ( ( rx_bytes == 0 ) && ( ++jumpcnt == fNSubProcess ) )
535
            {
moret's avatar
moret committed
536
537
538
539
540
541
542
543
                jack_error ( "No data from %s...", fParams.fName );
                jumpcnt = 0;
            }
            //else if data is valid,
            if ( rx_bytes && ( rx_head->fDataStream == 'r' ) && ( rx_head->fID == fParams.fID ) )
            {
                //read data
                switch ( rx_head->fDataType )
544
                {
moret's avatar
moret committed
545
                    case 'm':   //midi
546
                        rx_bytes = Recv ( rx_head->fPacketSize, 0 );
moret's avatar
moret committed
547
                        fRxHeader.fCycle = rx_head->fCycle;
moret's avatar
moret committed
548
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
moret's avatar
moret committed
549
                        fNetMidiPlaybackBuffer->RenderFromNetwork ( rx_head->fSubCycle, rx_bytes - sizeof ( packet_header_t ) );
550
                        if ( ++recvd_midi_pckt == rx_head->fNMidiPckt )
moret's avatar
moret committed
551
552
553
                            fNetMidiPlaybackBuffer->RenderToJackPorts();
                        jumpcnt = 0;
                        break;
554

moret's avatar
moret committed
555
                    case 'a':   //audio
556
                        rx_bytes = Recv ( rx_head->fPacketSize, 0 );
557
558
559
                        if (recvd_audio_pckt++ != rx_head->fSubCycle) {
                            jack_error("Packet(s) missing from '%s'...", fParams.fSlaveNetName);
                        }
moret's avatar
moret committed
560
561
                        fRxHeader.fCycle = rx_head->fCycle;
                        fRxHeader.fSubCycle = rx_head->fSubCycle;
moret's avatar
moret committed
562
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
563
                        fNetAudioPlaybackBuffer->RenderToJackPorts ( rx_head->fCycle,  rx_head->fSubCycle);
moret's avatar
moret committed
564
                        jumpcnt = 0;
565
                        last_cycle = rx_head->fCycle;
moret's avatar
moret committed
566
                        break;
567

moret's avatar
moret committed
568
                    case 's':   //sync
569
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
570
571
                        // Finish rendering (copy to JACK ports)
                        fNetAudioPlaybackBuffer->FinishRenderToJackPorts(last_cycle); 
572
                        return 0;
573
574
575
                }
            }
        }
576
577
578
        
        // Finish rendering (copy to JACK ports)
        fNetAudioPlaybackBuffer->FinishRenderToJackPorts(last_cycle); 
579
        return rx_bytes;
580
    }
581
    
sletz's avatar
sletz committed
582
    void JackNetMasterInterface::EncodeSyncPacket()
583
584
585
586
587
588
    {
        //this method contains every step of sync packet informations coding
        //first of all, reset sync packet
        memset ( fTxData, 0, fPayloadSize );

        //then, first step : transport
sletz's avatar
sletz committed
589
590
591
        if (fParams.fTransportSync) {
            EncodeTransportData();
            TransportDataHToN( &fSendTransportData,  &fSendTransportData);
592
593
594
595
596
597
598
            //copy to TxBuffer
            memcpy ( fTxData, &fSendTransportData, sizeof ( net_transport_data_t ) );
        }
        //then others (freewheel etc.)
        //...
    }

sletz's avatar
sletz committed
599
    void JackNetMasterInterface::DecodeSyncPacket()
600
601
602
    {
        //this method contains every step of sync packet informations decoding process
        //first : transport
sletz's avatar
sletz committed
603
        if (fParams.fTransportSync) {
604
605
            //copy received transport data to transport data structure
            memcpy ( &fReturnTransportData, fRxData, sizeof ( net_transport_data_t ) );
sletz's avatar
sletz committed
606
607
            TransportDataNToH( &fReturnTransportData,  &fReturnTransportData);
            DecodeTransportData();
608
609
610
611
        }
        //then others
        //...
    }
612

613
614
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
615
616
    uint JackNetSlaveInterface::fSlaveCounter = 0;

617
    bool JackNetSlaveInterface::Init()
618
    {
619
        jack_log ( "JackNetSlaveInterface::Init()" );
620

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

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

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

647
648
        return true;
    }
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
    
    // 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
665
            status = SendAvailableToMaster();
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
            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;
    }
691

sletz's avatar
sletz committed
692
    net_status_t JackNetSlaveInterface::SendAvailableToMaster()
693
    {
sletz's avatar
sletz committed
694
        jack_log ( "JackNetSlaveInterface::SendAvailableToMaster()" );
695
        //utility
696
        session_params_t host_params;
697
        int rx_bytes = 0;
sletz's avatar
sletz committed
698
699
        
        jack_log ( "sizeof (session_params_t) %d", sizeof (session_params_t) );
700
701

        //socket
sletz's avatar
sletz committed
702
        if ( fSocket.NewSocket() == SOCKET_ERROR ) {
703
704
            jack_error ( "Fatal error : network unreachable - %s", StrError ( NET_ERROR_CODE ) );
            return NET_SOCKET_ERROR;
705
706
        }

707
        //bind the socket
sletz's avatar
sletz committed
708
        if ( fSocket.Bind() == SOCKET_ERROR ) {
709
            jack_error ( "Can't bind the socket : %s", StrError ( NET_ERROR_CODE ) );
sletz's avatar
sletz committed
710
711
            return NET_SOCKET_ERROR;
        }
712
713

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

717
        //disable local loop
moret's avatar
moret committed
718
        if ( fSocket.SetLocalLoop() == SOCKET_ERROR )
719
            jack_error ( "Can't disable multicast loop : %s", StrError ( NET_ERROR_CODE ) );
720

721
722
        //send 'AVAILABLE' until 'SLAVE_SETUP' received
        jack_info ( "Waiting for a master..." );
723
724
        do
        {
725
            //send 'available'
726
            session_params_t net_params;
sletz's avatar
sletz committed
727
            memset(&net_params, 0, sizeof ( session_params_t ));
728
729
            SessionParamsHToN(&fParams, &net_params);
            if ( fSocket.SendTo ( &net_params, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
730
                jack_error ( "Error in data send : %s", StrError ( NET_ERROR_CODE ) );
731
                
732
            //filter incoming packets : don't exit while no error is detected
733
734
            memset(&net_params, 0, sizeof ( session_params_t ));
            rx_bytes = fSocket.CatchHost ( &net_params, sizeof ( session_params_t ), 0 );
sletz's avatar
sletz committed
735
736
737
738
739
            
            SessionParamsDisplay(&net_params);
            jack_error ( "rx_bytes %d %d", rx_bytes, errno );
            
            
740
            SessionParamsNToH(&net_params, &host_params);
741
            if ( ( rx_bytes == SOCKET_ERROR ) && ( fSocket.GetError() != NET_NO_DATA ) )
742
            {
743
744
                jack_error ( "Can't receive : %s", StrError ( NET_ERROR_CODE ) );
                return NET_RECV_ERROR;
745
            }
sletz's avatar
sletz committed
746
747
748
749
750
751
            for (int i = 0; i < 7; i++) {
                jack_info ( " fPacketType %d", host_params.fPacketType[i]);
            }
            jack_info ( " received... host_params param %s %s %d %d",  net_params.fPacketType, fParams.fPacketType, net_params.fPacketID, GetPacketType ( &host_params ));
        
            SessionParamsDisplay(&host_params);
752
        }
753
        while ( strcmp ( host_params.fPacketType, fParams.fPacketType )  && ( GetPacketType ( &host_params ) != SLAVE_SETUP ) );
754

sletz's avatar
sletz committed
755
756
        jack_info ( "SLAVE_SETUP received..." );
        
moret's avatar
moret committed
757
        //everything is OK, copy parameters
758
        fParams = host_params;
moret's avatar
moret committed
759
760

        //set the new buffer sizes
sletz's avatar
sletz committed
761
        if ( SetNetBufferSize() == SOCKET_ERROR ) {
moret's avatar
moret committed
762
            jack_error ( "Can't set net buffer sizes : %s", StrError ( NET_ERROR_CODE ) );
sletz's avatar
sletz committed
763
764
             return NET_SOCKET_ERROR;
        }
moret's avatar
moret committed
765

766
        //connect the socket
sletz's avatar
sletz committed
767
        if ( fSocket.Connect() == SOCKET_ERROR ) {
768
769
            jack_error ( "Error in connect : %s", StrError ( NET_ERROR_CODE ) );
            return NET_CONNECT_ERROR;
770
771
        }

moret's avatar
moret committed
772
        return NET_CONNECTED;
773
774
    }

moret's avatar
moret committed
775
    net_status_t JackNetSlaveInterface::SendStartToMaster()
776
    {
moret's avatar
moret committed
777
        jack_log ( "JackNetSlaveInterface::SendStartToMaster" );
moret's avatar
moret committed
778

779
        //tell the master to start
780
        session_params_t net_params;
sletz's avatar
sletz committed
781
        memset(&net_params, 0, sizeof ( session_params_t ));
782
        SetPacketType ( &fParams, START_MASTER );
783
784
        SessionParamsHToN(&fParams, &net_params);
        if ( fSocket.Send ( &net_params, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
785
        {
786
787
            jack_error ( "Error in send : %s", StrError ( NET_ERROR_CODE ) );
            return ( fSocket.GetError() == NET_CONN_ERROR ) ? NET_ERROR : NET_SEND_ERROR;
788
        }
789
        return NET_ROLLING;
790
791
    }

792
    void JackNetSlaveInterface::SetParams()
moret's avatar
moret committed
793
    {
794
        jack_log ( "JackNetSlaveInterface::SetParams" );
moret's avatar
moret committed
795
796
797

        JackNetInterface::SetParams();

798
799
        fTxHeader.fDataStream = 'r';
        fRxHeader.fDataStream = 's';
moret's avatar
moret committed
800
801

        //midi net buffers
802
803
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fRxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fTxData );
moret's avatar
moret committed
804
805

        //audio net buffers
806
807
808
809
810
        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 );
moret's avatar
moret committed
811
812
813
814
815
816

        //audio netbuffer length
        fAudioTxLen = sizeof ( packet_header_t ) + fNetAudioPlaybackBuffer->GetSize();
        fAudioRxLen = sizeof ( packet_header_t ) + fNetAudioCaptureBuffer->GetSize();
    }

817
    int JackNetSlaveInterface::Recv ( size_t size, int flags )
818
    {
819
820
821
822
823
824
        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
825
            if ( error == NET_NO_DATA ) {
826
827
                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
828
            } else if ( error == NET_CONN_ERROR ) {
829
                jack_error ( "Connection lost." );
moret's avatar
moret committed
830
                throw JackNetException();
sletz's avatar
sletz committed
831
            } else {
sletz's avatar
sletz committed
832
                jack_error ( "Fatal error in slave receive : %s", StrError ( NET_ERROR_CODE ) );
sletz's avatar
sletz committed
833
            }
834
        }
835
836
837
        
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
838
        return rx_bytes;
839
840
    }

841
    int JackNetSlaveInterface::Send ( size_t size, int flags )
842
    {
843
844
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
        PacketHeaderHToN(header, header);
845
        int tx_bytes = fSocket.Send ( fTxBuffer, size, flags );
846
         
847
848
        //handle errors
        if ( tx_bytes == SOCKET_ERROR )
849
850
        {
            net_error_t error = fSocket.GetError();
851
            //if a network error occurs, this exception will restart the driver
sletz's avatar
sletz committed
852
            if ( error == NET_CONN_ERROR ) {
853
                jack_error ( "Connection lost." );
moret's avatar
moret committed
854
                throw JackNetException();
sletz's avatar
sletz committed
855
            } else {
sletz's avatar
sletz committed
856
                jack_error ( "Fatal error in slave send : %s", StrError ( NET_ERROR_CODE ) );
sletz's avatar
sletz committed
857
            }