JackNetInterface.cpp 37.3 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
246

        //audio net buffers
247
248
249
250
251
252
        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 );     
     
253
254
        assert ( fNetAudioCaptureBuffer );
        assert ( fNetAudioPlaybackBuffer );
sletz's avatar
sletz committed
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
        
        //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
277
278
    }

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

        //stop process
        fRunning = false;
285

286
287
288
289
        //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() );
290
291
        
        session_params_t net_params;
sletz's avatar
sletz committed
292
        memset(&net_params, 0, sizeof ( session_params_t ));
293
294
        SessionParamsHToN(&fParams, &net_params);

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

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

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

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

        return 0;
416
417
    }

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

426
        fCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
427
      
428
        switch ( fParams.fNetworkMode )
429
        {
430
            case 's' :
moret's avatar
moret committed
431
432
433
434
435
                //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)
436
                if (fCycleOffset < CYCLE_OFFSET_SLOW) {
sletz's avatar
sletz committed
437
438
                    return 0;
                } else {
439
                    rx_bytes = Recv ( rx_head->fPacketSize, 0 );
sletz's avatar
sletz committed
440
                }
441
442
                
                if (fCycleOffset > CYCLE_OFFSET_SLOW) {
443
444
                    jack_info("Warning : '%s' runs in slow network mode, but data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
                }
445
                break;
446

447
448
449
450
451
            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
452
                if (fCycleOffset < CYCLE_OFFSET_NORMAL) {
453
                    return 0;
sletz's avatar
sletz committed
454
                } else {
455
                    rx_bytes = Recv ( rx_head->fPacketSize, 0 );
sletz's avatar
sletz committed
456
                }
457
                    
sletz's avatar
sletz committed
458
                if (fCycleOffset > CYCLE_OFFSET_NORMAL)  {
459
                    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
460
                }
461
                break;
462

463
464
465
466
467
468
            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 );
469
                
sletz's avatar
sletz committed
470
                if (fCycleOffset > CYCLE_OFFSET_FAST) {
471
                    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
472
                }
473
                break;
474
        }
475

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

moret's avatar
moret committed
512
                    case 'a':   //audio
513
                        rx_bytes = Recv ( rx_head->fPacketSize, 0 );
moret's avatar
moret committed
514
515
                        fRxHeader.fCycle = rx_head->fCycle;
                        fRxHeader.fSubCycle = rx_head->fSubCycle;
moret's avatar
moret committed
516
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
sletz's avatar
sletz committed
517
518
519
520
                         fNetAudioPlaybackBuffer->RenderFromNetwork (rx_head->fCycle, rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
                         // Last audio packet is received, so finish rendering...
                         if (fRxHeader.fIsLastPckt)
                            fNetAudioPlaybackBuffer->RenderToJackPorts();
moret's avatar
moret committed
521
                        break;
522

moret's avatar
moret committed
523
                    case 's':   //sync
524
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
sletz's avatar
sletz committed
525
                        // TODO : finish midi and audio rendering ?
526
                        return 0;
527
528
529
                }
            }
        }
sletz's avatar
sletz committed
530
 
531
        return rx_bytes;
532
    }
533
    
sletz's avatar
sletz committed
534
    void JackNetMasterInterface::EncodeSyncPacket()
535
536
537
    {
        //this method contains every step of sync packet informations coding
        //first of all, reset sync packet
sletz's avatar
sletz committed
538
        memset ( fTxData, 0, PACKET_AVAILABLE_SIZE );
539
540

        //then, first step : transport
sletz's avatar
sletz committed
541
542
543
        if (fParams.fTransportSync) {
            EncodeTransportData();
            TransportDataHToN( &fSendTransportData,  &fSendTransportData);
544
545
546
547
548
549
550
            //copy to TxBuffer
            memcpy ( fTxData, &fSendTransportData, sizeof ( net_transport_data_t ) );
        }
        //then others (freewheel etc.)
        //...
    }

sletz's avatar
sletz committed
551
    void JackNetMasterInterface::DecodeSyncPacket()
552
553
554
    {
        //this method contains every step of sync packet informations decoding process
        //first : transport
sletz's avatar
sletz committed
555
        if (fParams.fTransportSync) {
556
557
            //copy received transport data to transport data structure
            memcpy ( &fReturnTransportData, fRxData, sizeof ( net_transport_data_t ) );
sletz's avatar
sletz committed
558
559
            TransportDataNToH( &fReturnTransportData,  &fReturnTransportData);
            DecodeTransportData();
560
561
562
563
        }
        //then others
        //...
    }
564

565
566
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
567
568
    uint JackNetSlaveInterface::fSlaveCounter = 0;

569
    bool JackNetSlaveInterface::Init()
570
    {
571
        jack_log ( "JackNetSlaveInterface::Init()" );
572

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

578
579
580
        //init loop : get a master and start, do it until connection is ok
        net_status_t status;
        do
581
        {
582
583
            //first, get a master, do it until a valid connection is running
            do
584
            {
sletz's avatar
sletz committed
585
                status = SendAvailableToMaster();
586
587
                if ( status == NET_SOCKET_ERROR )
                    return false;
588
            }
589
            while ( status != NET_CONNECTED );
590

591
592
            //then tell the master we are ready
            jack_info ( "Initializing connection with %s...", fParams.fMasterNetName );
moret's avatar
moret committed
593
            status = SendStartToMaster();
594
595
            if ( status == NET_ERROR )
                return false;
596
        }
597
        while ( status != NET_ROLLING );
598

599
600
        return true;
    }
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
    
    // 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
617
            status = SendAvailableToMaster();
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
            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;
    }
643

sletz's avatar
sletz committed
644
    net_status_t JackNetSlaveInterface::SendAvailableToMaster()
645
    {
sletz's avatar
sletz committed
646
        jack_log ( "JackNetSlaveInterface::SendAvailableToMaster()" );
647
        //utility
648
        session_params_t host_params;
649
        int rx_bytes = 0;
sletz's avatar
sletz committed
650
651
        
        jack_log ( "sizeof (session_params_t) %d", sizeof (session_params_t) );
652
653

        //socket
sletz's avatar
sletz committed
654
        if ( fSocket.NewSocket() == SOCKET_ERROR ) {
655
656
            jack_error ( "Fatal error : network unreachable - %s", StrError ( NET_ERROR_CODE ) );
            return NET_SOCKET_ERROR;
657
658
        }

659
        //bind the socket
sletz's avatar
sletz committed
660
        if ( fSocket.Bind() == SOCKET_ERROR ) {
661
            jack_error ( "Can't bind the socket : %s", StrError ( NET_ERROR_CODE ) );
sletz's avatar
sletz committed
662
663
            return NET_SOCKET_ERROR;
        }
664
665

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

669
        //disable local loop
moret's avatar
moret committed
670
        if ( fSocket.SetLocalLoop() == SOCKET_ERROR )
671
            jack_error ( "Can't disable multicast loop : %s", StrError ( NET_ERROR_CODE ) );
672

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

700
        //connect the socket
sletz's avatar
sletz committed
701
        if ( fSocket.Connect() == SOCKET_ERROR ) {
702
703
            jack_error ( "Error in connect : %s", StrError ( NET_ERROR_CODE ) );
            return NET_CONNECT_ERROR;
704
        }
moret's avatar
moret committed
705
        return NET_CONNECTED;
706
707
    }

moret's avatar
moret committed
708
    net_status_t JackNetSlaveInterface::SendStartToMaster()
709
    {
moret's avatar
moret committed
710
        jack_log ( "JackNetSlaveInterface::SendStartToMaster" );
moret's avatar
moret committed
711

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

sletz's avatar
sletz committed
725
    bool JackNetSlaveInterface::SetParams()
moret's avatar
moret committed
726
    {
727
        jack_log ( "JackNetSlaveInterface::SetParams" );
moret's avatar
moret committed
728
729
730

        JackNetInterface::SetParams();

731
732
        fTxHeader.fDataStream = 'r';
        fRxHeader.fDataStream = 's';
moret's avatar
moret committed
733
734

        //midi net buffers
735
736
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fRxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fTxData );
sletz's avatar
sletz committed
737
738
        assert ( fNetMidiCaptureBuffer );
        assert ( fNetMidiPlaybackBuffer );
moret's avatar
moret committed
739
740

        //audio net buffers
741
742
743
744
745
        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 );
sletz's avatar
sletz committed
746
747
748
        
        assert ( fNetAudioCaptureBuffer );
        assert ( fNetAudioPlaybackBuffer );
sletz's avatar
sletz committed
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
        
         //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
764
765
    }

766
    int JackNetSlaveInterface::Recv ( size_t size, int flags )
767
    {
768
769
770
771
772
773
        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
774
            if ( error == NET_NO_DATA ) {
775
776
                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
777
            } else if ( error == NET_CONN_ERROR ) {
778
                jack_error ( "Connection lost." );
moret's avatar
moret committed
779
                throw JackNetException();
sletz's avatar
sletz committed
780
            } else {
sletz's avatar
sletz committed
781
                jack_error ( "Fatal error in slave receive : %s", StrError ( NET_ERROR_CODE ) );
sletz's avatar
sletz committed
782
            }
783
        }
784
785
786
        
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
787
        return rx_bytes;
788
789
    }

790
    int JackNetSlaveInterface::Send ( size_t size, int flags )
791
    {
792
793
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
        PacketHeaderHToN(header, header);
794
        int tx_bytes = fSocket.Send ( fTxBuffer, size, flags );
795
         
796
797
        //handle errors
        if ( tx_bytes == SOCKET_ERROR )
798
799
        {
            net_error_t error = fSocket.GetError();
800
            //if a network error occurs, this exception will restart the driver
sletz's avatar
sletz committed
801
            if ( error == NET_CONN_ERROR ) {
802
                jack_error ( "Connection lost." );
moret's avatar
moret committed
803
                throw JackNetException();
sletz's avatar
sletz committed
804
            } else {
sletz's avatar
sletz committed
805
                jack_error ( "Fatal error in slave send : %s", StrError ( NET_ERROR_CODE ) );
sletz's avatar
sletz committed
806
            }
807
808
809
810
        }
        return tx_bytes;
    }

811
    int JackNetSlaveInterface::SyncRecv()
812
    {
813
814
        int rx_bytes = 0;
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
sletz's avatar
sletz committed
815
        
816
817
        //receive sync (launch the cycle)
        do
818
        {
sletz's avatar
sletz committed
819
            rx_bytes = Recv(HEADER_SIZE, 0);
820
821
822
823
            //connection issue, send will detect it, so don't skip the cycle (return 0)
            if ( rx_bytes == SOCKET_ERROR )
                return rx_bytes;
        }
824
825
        while ((strcmp(rx_head->fPacketType, "header") != 0) && (rx_head->fDataType != 's'));
        
moret's avatar
moret committed
826
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
827
828
829
830
831
832
        return rx_bytes;
    }

    int JackNetSlaveInterface::DataRecv()
    {
        int rx_bytes = 0;
sletz's avatar
sletz committed
833
        //int last_cycle = 0;
sletz's avatar
sletz committed
834
        uint recvd_midi_pckt = 0;
sletz's avatar
sletz committed
835
        uint recvd_audio_pckt = 0;
sletz's avatar
sletz committed
836
      
837
838
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );

moret's avatar
moret committed
839
        while ( !fRxHeader.fIsLastPckt )
840
        {
sletz's avatar
sletz committed
841
            //how much data is queued on the rx buffer ?
sletz's avatar
sletz committed
842
            rx_bytes = Recv(HEADER_SIZE, MSG_PEEK);
sletz's avatar
sletz committed
843
            
moret's avatar
moret committed
844
845
846
            //error here, problem with recv, just skip the cycle (return -1)
            if ( rx_bytes == SOCKET_ERROR )
                return rx_bytes;
sletz's avatar
sletz committed
847
                
moret's avatar
moret committed
848
            if ( rx_bytes && ( rx_head->fDataStream == 's' ) && ( rx_head->fID == fParams.fID ) )
849
            {
moret's avatar
moret committed
850
                switch ( rx_head->fDataType )
851
                {
moret's avatar
moret committed
852
853
854
                    case 'm':   //midi
                        rx_bytes = Recv ( rx_head->fPacketSize, 0 );
                        fRxHeader.fCycle = rx_head->fCycle;
moret's avatar
moret committed
855
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
sletz's avatar
sletz committed
856
                        fNetMidiCaptureBuffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
sletz's avatar
sletz committed
857
                        // Last midi packet is received, so finish rendering...
sletz's avatar
sletz committed
858
                        if ( ++recvd_midi_pckt == rx_head->fNumPacket )
moret's avatar
moret committed
859
860
                            fNetMidiCaptureBuffer->RenderToJackPorts();
                        break;
861