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;

27
28
29
30
31
32
/*  
 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)
*/

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

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

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

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

    JackNetInterface::~JackNetInterface()
    {
moret's avatar
moret committed
78
        jack_log ( "JackNetInterface::~JackNetInterface" );
moret's avatar
moret committed
79

80
81
82
83
84
85
86
87
88
        fSocket.Close();
        delete[] fTxBuffer;
        delete[] fRxBuffer;
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
    }

89
    void JackNetInterface::SetFramesPerPacket()
moret's avatar
moret committed
90
    {
moret's avatar
moret committed
91
        jack_log ( "JackNetInterface::SetFramesPerPacket" );
moret's avatar
moret committed
92

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

    int JackNetInterface::SetNetBufferSize()
    {
moret's avatar
moret committed
104
        jack_log ( "JackNetInterface::SetNetBufferSize" );
moret's avatar
moret committed
105

moret's avatar
moret committed
106
        float audio_size, midi_size;
107
        int bufsize;
moret's avatar
moret committed
108
109
110
111
        //audio
        audio_size = fParams.fMtu * ( fParams.fPeriodSize / fParams.fFramesPerPacket );
        //midi
        midi_size = fParams.fMtu * ( max ( fParams.fSendMidiChannels, fParams.fReturnMidiChannels ) *
moret's avatar
moret committed
112
                                     fParams.fPeriodSize * sizeof ( sample_t ) / ( fParams.fMtu - sizeof ( packet_header_t ) ) );
moret's avatar
moret committed
113
        //bufsize = sync + audio + midi
114
        bufsize = MAX_LATENCY * (fParams.fMtu + ( int ) audio_size + ( int ) midi_size);
moret's avatar
moret committed
115
116
117

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

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

124
        return 0;
moret's avatar
moret committed
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    }

    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
        if ( fTxHeader.fMidiDataSize <= ( fParams.fMtu - sizeof ( packet_header_t ) ) )
            return 1;
        //else, get the number of needed packets (simply slice the biiig buffer)
        int npckt = fTxHeader.fMidiDataSize / ( fParams.fMtu - sizeof ( packet_header_t ) );
        if ( fTxHeader.fMidiDataSize % ( fParams.fMtu - sizeof ( packet_header_t ) ) )
            return ++npckt;
        return npckt;
    }

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

159
160
    void JackNetInterface::SetParams()
    {
moret's avatar
moret committed
161
        //number of audio subcycles (packets)
162
163
        fNSubProcess = fParams.fPeriodSize / fParams.fFramesPerPacket;

moret's avatar
moret committed
164
165
166
        //payload size
        fPayloadSize = fParams.fMtu - sizeof ( packet_header_t );

167
168
169
170
171
172
173
        //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
174
        fTxHeader.fIsLastPckt = 0;
175
176
177
178
179
180
181
182

        //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
183
        fRxHeader.fIsLastPckt = 0;
184
185
186
187

        //network buffers
        fTxBuffer = new char[fParams.fMtu];
        fRxBuffer = new char[fParams.fMtu];
188
189
        assert ( fTxBuffer );
        assert ( fRxBuffer );
190

moret's avatar
moret committed
191
        //net audio/midi buffers'addresses
192
193
194
195
        fTxData = fTxBuffer + sizeof ( packet_header_t );
        fRxData = fRxBuffer + sizeof ( packet_header_t );
    }

196
    // JackNetMasterInterface ************************************************************************************
197

198
    bool JackNetMasterInterface::Init()
199
    {
200
        jack_log ( "JackNetMasterInterface::Init, ID %u.", fParams.fID );
201

202
        session_params_t host_params;
203
        uint attempt = 0;
204
205
206
        int rx_bytes = 0;

        //socket
207
        if ( fSocket.NewSocket() == SOCKET_ERROR ) {
208
209
            jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
            return false;
210
211
        }

212
        //timeout on receive (for init)
213
        if ( fSocket.SetTimeOut ( MASTER_INIT_TIMEOUT ) < 0 )
214
            jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );
215
            
216
        //connect
217
        if ( fSocket.Connect() == SOCKET_ERROR ) {
218
219
220
            jack_error ( "Can't connect : %s", StrError ( NET_ERROR_CODE ) );
            return false;
        }
221

moret's avatar
moret committed
222
        //set the number of complete audio frames we can put in a packet
moret's avatar
moret committed
223
224
        SetFramesPerPacket();

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

251
        //set the new timeout for the socket
252
        if ( SetRxTimeout() == SOCKET_ERROR ) {
253
254
255
            jack_error ( "Can't set rx timeout : %s", StrError ( NET_ERROR_CODE ) );
            return false;
        }
256

257
        //set the new rx buffer size
258
        if ( SetNetBufferSize() == SOCKET_ERROR ) {
moret's avatar
moret committed
259
            jack_error ( "Can't set net buffer sizes : %s", StrError ( NET_ERROR_CODE ) );
260
            return false;
261
        }
262
263

        return true;
264
265
    }

moret's avatar
moret committed
266
267
    int JackNetMasterInterface::SetRxTimeout()
    {
moret's avatar
moret committed
268
269
        jack_log ( "JackNetMasterInterface::SetRxTimeout" );

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

280
    void JackNetMasterInterface::SetParams()
moret's avatar
moret committed
281
    {
282
        jack_log ( "JackNetMasterInterface::SetParams" );
moret's avatar
moret committed
283
284
285

        JackNetInterface::SetParams();

286
287
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
288
289

        //midi net buffers
290
291
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fTxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fRxData );
292
293
        assert ( fNetMidiCaptureBuffer );
        assert ( fNetMidiPlaybackBuffer );
moret's avatar
moret committed
294
295

        //audio net buffers
296
297
        fNetAudioCaptureBuffer = new NetAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
        fNetAudioPlaybackBuffer = new NetAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );
298
299
        assert ( fNetAudioCaptureBuffer );
        assert ( fNetAudioPlaybackBuffer );
moret's avatar
moret committed
300
301

        //audio netbuffer length
302
303
        fAudioTxLen = sizeof ( packet_header_t ) + fNetAudioCaptureBuffer->GetSize();
        fAudioRxLen = sizeof ( packet_header_t ) + fNetAudioPlaybackBuffer->GetSize();
moret's avatar
moret committed
304
305
    }

306
    void JackNetMasterInterface::Exit()
307
    {
308
309
310
311
        jack_log ( "JackNetMasterInterface::Exit, ID %u", fParams.fID );

        //stop process
        fRunning = false;
312

313
314
315
316
        //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() );
317
318
319
320
        
        session_params_t net_params;
        SessionParamsHToN(&fParams, &net_params);

321
322
        if ( mcast_socket.NewSocket() == SOCKET_ERROR )
            jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
323
        if ( mcast_socket.SendTo ( &net_params, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
324
            jack_error ( "Can't send suicide request : %s", StrError ( NET_ERROR_CODE ) );
325
            
326
327
328
        mcast_socket.Close();
    }

329
    int JackNetMasterInterface::Recv ( size_t size, int flags )
330
    {
331
332
        int rx_bytes;
        if ( ( ( rx_bytes = fSocket.Recv ( fRxBuffer, size, flags ) ) == SOCKET_ERROR ) && fRunning )
333
334
        {
            net_error_t error = fSocket.GetError();
335
336
337
338
            //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 )
339
340
341
            {
                //fatal connection issue, exit
                jack_error ( "'%s' : %s, exiting.", fParams.fName, StrError ( NET_ERROR_CODE ) );
342
                //ask to the manager to properly remove the master
343
                Exit();
344
345
346
                
                // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
                ThreadExit();
347
            }
moret's avatar
moret committed
348
            else
349
                jack_error ( "Error in master receive : %s", StrError ( NET_ERROR_CODE ) );
350
        }
351
352
353
354
        
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
        return rx_bytes;
355
    }
356
357
    
    int JackNetMasterInterface::Send ( size_t size, int flags )
358
    {
359
360
361
362
363
        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 )
364
365
        {
            net_error_t error = fSocket.GetError();
366
            if ( error == NET_CONN_ERROR )
367
            {
368
369
370
                //fatal connection issue, exit
                jack_error ( "'%s' : %s, exiting.", fParams.fName, StrError ( NET_ERROR_CODE ) );
                Exit();
371
372
373
                
                // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
                ThreadExit();
374
            }
moret's avatar
moret committed
375
            else
376
                jack_error ( "Error in master send : %s", StrError ( NET_ERROR_CODE ) );
377
        }
378
        return tx_bytes;
379
    }
380
381
382
    
    bool JackNetMasterInterface::IsSynched()
    {
sletz's avatar
sletz committed
383
        if (fParams.fNetworkMode == 's') {
384
            return (fCycleOffset < 3);
sletz's avatar
sletz committed
385
        } else {
386
            return true;
sletz's avatar
sletz committed
387
        }
388
389
    }
    
390
    int JackNetMasterInterface::SyncSend()
391
    {
392
393
394
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
395
        fTxHeader.fIsLastPckt = ( fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ?  1 : 0;
396
397
398
399
400
401
402
403
404
        fTxHeader.fPacketSize = fParams.fMtu;
        memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
        return Send ( fTxHeader.fPacketSize, 0 );
    }

    int JackNetMasterInterface::DataSend()
    {
        uint subproc;
        //midi
405
        if ( fParams.fSendMidiChannels > 0)
406
        {
407
408
409
            //set global header fields and get the number of midi packets
            fTxHeader.fDataType = 'm';
            fTxHeader.fMidiDataSize = fNetMidiCaptureBuffer->RenderFromJackPorts();
moret's avatar
moret committed
410
            fTxHeader.fNMidiPckt = GetNMidiPckt();
411
            for ( subproc = 0; subproc < fTxHeader.fNMidiPckt; subproc++ )
412
            {
413
                fTxHeader.fSubCycle = subproc;
414
                fTxHeader.fIsLastPckt = ( ( subproc == ( fTxHeader.fNMidiPckt - 1 ) ) && (fParams.fSendAudioChannels == 0)) ? 1 : 0;
415
                fTxHeader.fPacketSize = sizeof ( packet_header_t ) + fNetMidiCaptureBuffer->RenderToNetwork ( subproc, fTxHeader.fMidiDataSize );
416
417
418
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
                if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
                    return SOCKET_ERROR;
419
420
            }
        }
421
422

        //audio
423
        if ( fParams.fSendAudioChannels > 0)
424
425
        {
            fTxHeader.fDataType = 'a';
426
427
            fTxHeader.fMidiDataSize = 0;
            fTxHeader.fNMidiPckt = 0;
428
429
430
            for ( subproc = 0; subproc < fNSubProcess; subproc++ )
            {
                fTxHeader.fSubCycle = subproc;
moret's avatar
moret committed
431
                fTxHeader.fIsLastPckt = ( subproc == ( fNSubProcess - 1 ) ) ? 1 : 0;
432
433
434
435
436
437
438
439
440
                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;
441
442
    }

443
    int JackNetMasterInterface::SyncRecv()
444
445
    {
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
446
447
        int rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
        
448
449
450
        if ( ( rx_bytes == 0 ) || ( rx_bytes == SOCKET_ERROR ) )
            return rx_bytes;

451
        fCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
452
      
453
        switch ( fParams.fNetworkMode )
454
        {
455
            case 's' :
moret's avatar
moret committed
456
457
458
459
460
                //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)
461
                if (fCycleOffset < 2)
462
                     return 0;
463
464
                else
                    rx_bytes = Recv ( rx_head->fPacketSize, 0 );
465
466
467
468
                    
                if (fCycleOffset > 2) {
                    jack_info("Warning : '%s' runs in slow network mode, but data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
                }
469
                break;
470

471
472
473
474
475
            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
476
                if (fCycleOffset < 1)
477
478
479
                    return 0;
                else
                    rx_bytes = Recv ( rx_head->fPacketSize, 0 );
480
481
482
                    
                if (fCycleOffset != 1) 
                    jack_info("'%s' can't run in normal network mode, data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
483
                break;
484

485
486
487
488
489
490
            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 );
491
492
493
                
                if (fCycleOffset != 0)
                    jack_info("'%s' can't run in fast network mode, data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
494
                break;
495
        }
496

moret's avatar
moret committed
497
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
498
499
        return rx_bytes;
    }
500
    
501
    int JackNetMasterInterface::DataRecv()
502
503
    {
        int rx_bytes = 0;
504
        uint jumpcnt = 0;
505
        uint recvd_midi_pckt = 0;
506
        uint recvd_audio_pckt = 0;
507
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
508
        
moret's avatar
moret committed
509
        while ( !fRxHeader.fIsLastPckt )
510
        {
moret's avatar
moret committed
511
512
            //how much data is queued on the rx buffer ?
            rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
513
              
moret's avatar
moret committed
514
515
            if ( rx_bytes == SOCKET_ERROR )
                return rx_bytes;
moret's avatar
moret committed
516
            //if no data
moret's avatar
moret committed
517
            if ( ( rx_bytes == 0 ) && ( ++jumpcnt == fNSubProcess ) )
518
            {
moret's avatar
moret committed
519
520
521
522
523
524
525
526
                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 )
527
                {
moret's avatar
moret committed
528
                    case 'm':   //midi
529
                        rx_bytes = Recv ( rx_head->fPacketSize, 0 );
moret's avatar
moret committed
530
                        fRxHeader.fCycle = rx_head->fCycle;
moret's avatar
moret committed
531
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
moret's avatar
moret committed
532
                        fNetMidiPlaybackBuffer->RenderFromNetwork ( rx_head->fSubCycle, rx_bytes - sizeof ( packet_header_t ) );
533
                        if ( ++recvd_midi_pckt == rx_head->fNMidiPckt )
moret's avatar
moret committed
534
535
536
                            fNetMidiPlaybackBuffer->RenderToJackPorts();
                        jumpcnt = 0;
                        break;
537

moret's avatar
moret committed
538
                    case 'a':   //audio
539
                        rx_bytes = Recv ( rx_head->fPacketSize, 0 );
540
541
542
                        // SL: 25/01/09
                        // if ( !IsNextPacket() )
                        //    jack_error ( "Packet(s) missing from '%s'...", fParams.fName );
543
544
545
                        if (recvd_audio_pckt++ != rx_head->fSubCycle) {
                            jack_error("Packet(s) missing from '%s'...", fParams.fSlaveNetName);
                        }
moret's avatar
moret committed
546
547
                        fRxHeader.fCycle = rx_head->fCycle;
                        fRxHeader.fSubCycle = rx_head->fSubCycle;
moret's avatar
moret committed
548
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
moret's avatar
moret committed
549
550
551
                        fNetAudioPlaybackBuffer->RenderToJackPorts ( rx_head->fSubCycle );
                        jumpcnt = 0;
                        break;
552

moret's avatar
moret committed
553
                    case 's':   //sync
554
                        /* SL: 25/01/09
moret's avatar
moret committed
555
556
                        if ( rx_head->fCycle == fTxHeader.fCycle )
                            return 0;
557
                        */
558
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
559
                        return 0;
560
561
562
                }
            }
        }
563
        return rx_bytes;
564
    }
565
    
566
    void JackNetMasterInterface::EncodeSyncPacket()
567
568
569
570
571
572
    {
        //this method contains every step of sync packet informations coding
        //first of all, reset sync packet
        memset ( fTxData, 0, fPayloadSize );

        //then, first step : transport
573
574
        if (fParams.fTransportSync) {
            EncodeTransportData();
575
            TransportDataHToN( &fSendTransportData,  &fSendTransportData);
576
577
578
579
580
581
582
            //copy to TxBuffer
            memcpy ( fTxData, &fSendTransportData, sizeof ( net_transport_data_t ) );
        }
        //then others (freewheel etc.)
        //...
    }

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

597
598
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
599
600
    uint JackNetSlaveInterface::fSlaveCounter = 0;

601
    bool JackNetSlaveInterface::Init()
602
    {
603
        jack_log ( "JackNetSlaveInterface::Init()" );
604

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

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

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

631
632
        return true;
    }
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
    
    // 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
649
            status = SendAvailableToMaster();
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
            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;
    }
675

676
    net_status_t JackNetSlaveInterface::SendAvailableToMaster()
677
    {
678
        jack_log ( "JackNetSlaveInterface::SendAvailableToMaster()" );
679
        //utility
680
        session_params_t host_params;
681
682
683
        int rx_bytes = 0;

        //socket
684
        if ( fSocket.NewSocket() == SOCKET_ERROR ) {
685
686
            jack_error ( "Fatal error : network unreachable - %s", StrError ( NET_ERROR_CODE ) );
            return NET_SOCKET_ERROR;
687
688
        }

689
        //bind the socket
690
        if ( fSocket.Bind() == SOCKET_ERROR ) {
691
            jack_error ( "Can't bind the socket : %s", StrError ( NET_ERROR_CODE ) );
692
693
            return NET_SOCKET_ERROR;
        }
694
695

        //timeout on receive
696
        if ( fSocket.SetTimeOut ( SLAVE_INIT_TIMEOUT ) == SOCKET_ERROR ) 
697
698
            jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );

699
        //disable local loop
moret's avatar
moret committed
700
        if ( fSocket.SetLocalLoop() == SOCKET_ERROR )
701
            jack_error ( "Can't disable multicast loop : %s", StrError ( NET_ERROR_CODE ) );
702

703
704
        //send 'AVAILABLE' until 'SLAVE_SETUP' received
        jack_info ( "Waiting for a master..." );
705
706
        do
        {
707
            //send 'available'
708
709
710
            session_params_t net_params;
            SessionParamsHToN(&fParams, &net_params);
            if ( fSocket.SendTo ( &net_params, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
711
                jack_error ( "Error in data send : %s", StrError ( NET_ERROR_CODE ) );
712
                
713
            //filter incoming packets : don't exit while no error is detected
714
715
716
            memset(&net_params, 0, sizeof ( session_params_t ));
            rx_bytes = fSocket.CatchHost ( &net_params, sizeof ( session_params_t ), 0 );
            SessionParamsNToH(&net_params, &host_params);
717
            if ( ( rx_bytes == SOCKET_ERROR ) && ( fSocket.GetError() != NET_NO_DATA ) )
718
            {
719
720
                jack_error ( "Can't receive : %s", StrError ( NET_ERROR_CODE ) );
                return NET_RECV_ERROR;
721
722
            }
        }
723
        while ( strcmp ( host_params.fPacketType, fParams.fPacketType )  && ( GetPacketType ( &host_params ) != SLAVE_SETUP ) );
724

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

        //set the new buffer sizes
729
        if ( SetNetBufferSize() == SOCKET_ERROR ) {
moret's avatar
moret committed
730
            jack_error ( "Can't set net buffer sizes : %s", StrError ( NET_ERROR_CODE ) );
731
732
             return NET_SOCKET_ERROR;
        }
moret's avatar
moret committed
733

734
        //connect the socket
735
        if ( fSocket.Connect() == SOCKET_ERROR ) {
736
737
            jack_error ( "Error in connect : %s", StrError ( NET_ERROR_CODE ) );
            return NET_CONNECT_ERROR;
738
739
        }

moret's avatar
moret committed
740
        return NET_CONNECTED;
741
742
    }

moret's avatar
moret committed
743
    net_status_t JackNetSlaveInterface::SendStartToMaster()
744
    {
moret's avatar
moret committed
745
        jack_log ( "JackNetSlaveInterface::SendStartToMaster" );
moret's avatar
moret committed
746

747
        //tell the master to start
748
        session_params_t net_params;
749
        SetPacketType ( &fParams, START_MASTER );
750
751
        SessionParamsHToN(&fParams, &net_params);
        if ( fSocket.Send ( &net_params, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
752
        {
753
754
            jack_error ( "Error in send : %s", StrError ( NET_ERROR_CODE ) );
            return ( fSocket.GetError() == NET_CONN_ERROR ) ? NET_ERROR : NET_SEND_ERROR;
755
        }
756
        return NET_ROLLING;
757
758
    }

759
    void JackNetSlaveInterface::SetParams()
moret's avatar
moret committed
760
    {
761
        jack_log ( "JackNetSlaveInterface::SetParams" );
moret's avatar
moret committed
762
763
764

        JackNetInterface::SetParams();

765
766
        fTxHeader.fDataStream = 'r';
        fRxHeader.fDataStream = 's';
moret's avatar
moret committed
767
768

        //midi net buffers
769
770
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fRxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fTxData );
moret's avatar
moret committed
771
772

        //audio net buffers
773
774
        fNetAudioCaptureBuffer = new NetAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
        fNetAudioPlaybackBuffer = new NetAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
moret's avatar
moret committed
775
776
777
778
779
780

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

781
    int JackNetSlaveInterface::Recv ( size_t size, int flags )
782
    {
783
784
785
786
787
788
789
790
791
792
793
794
        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
            if ( error == NET_NO_DATA )
                jack_error ( "No data, is the master still running ?" );
            //if a network error occurs, this exception will restart the driver
            else if ( error == NET_CONN_ERROR )
            {
                jack_error ( "Connection lost." );
moret's avatar
moret committed
795
                throw JackNetException();
796
797
            }
            else
sletz's avatar
sletz committed
798
                jack_error ( "Fatal error in slave receive : %s", StrError ( NET_ERROR_CODE ) );
799
        }
800
801
802
        
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
803
        return rx_bytes;
804
805
    }

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

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

    int JackNetSlaveInterface::DataRecv()
    {
        uint recvd_midi_pckt = 0;
849
        uint recvd_audio_pckt = 0;
850
851
852
        int rx_bytes = 0;
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );

moret's avatar
moret committed
853
        while ( !fRxHeader.fIsLastPckt )
854
        {
moret's avatar
moret committed
855
856
            rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
            //error here, problem with recv, just skip the cycle (return -1)
moret's avatar
moret committed
857

moret's avatar
moret committed
858
859
860
            if ( rx_bytes == SOCKET_ERROR )
                return rx_bytes;
            if ( rx_bytes && ( rx_head->fDataStream == 's' ) && ( rx_head->fID == fParams.fID ) )
861
            {
moret's avatar
moret committed
862
                switch ( rx_head->fDataType )
863
                {
moret's avatar
moret committed
864
865
866
                    case 'm':   //midi
                        rx_bytes = Recv ( rx_head->fPacketSize, 0 );
                        fRxHeader.fCycle = rx_head->fCycle;
moret's avatar
moret committed
867
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
moret's avatar
moret committed
868
869
870
871
                        fNetMidiCaptureBuffer->RenderFromNetwork ( rx_head->fSubCycle, rx_bytes - sizeof ( packet_header_t ) );
                        if ( ++recvd_midi_pckt == rx_head->fNMidiPckt )
                            fNetMidiCaptureBuffer->RenderToJackPorts();
                        break;
872

moret's avatar
moret committed
873
874
                    case 'a':   //audio
                        rx_bytes = Recv ( rx_head->fPacketSize, 0 );
875
876
877
                        //SL: 25/01/09
                        // if ( !IsNextPacket() )
                        //    jack_error ( "Packet(s) missing..." );
878
879
880
                        if (recvd_audio_pckt++ != rx_head->fSubCycle) {
                            jack_error("Packet(s) missing from '%s'...", fParams.fMasterNetName);
                        }
moret's avatar
moret committed
881
882
                        fRxHeader.fCycle = rx_head->fCycle;
                        fRxHeader.fSubCycle = rx_head->fSubCycle;
moret's avatar
moret committed
883
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
moret's avatar
moret committed
884
885
                        fNetAudioCaptureBuffer->RenderToJackPorts ( rx_head->fSubCycle );
                        break;
886

moret's avatar
moret committed
887
888
889
                    case 's':   //sync
                        jack_info ( "NetSlave : overloaded, skipping receive." );
                        return 0;