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

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "JackNetInterface.h"
#include "JackException.h"
22
#include "JackPlatformPlug.h"
23
#include <assert.h>
24
25
26

using namespace std;

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

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

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

40
41
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
    {
sletz's avatar
sletz committed
67
        jack_log("JackNetInterface ( session_params_t& params...)");
moret's avatar
moret committed
68
        fParams = params;
69
        strcpy(fMulticastIP, multicast_ip);
70
71
72
73
74
75
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
76
77
        memset(&fSendTransportData, 0, sizeof(net_transport_data_t));
        memset(&fReturnTransportData, 0, sizeof(net_transport_data_t));
78
79
80
81
    }

    JackNetInterface::~JackNetInterface()
    {
moret's avatar
moret committed
82
        jack_log ( "JackNetInterface::~JackNetInterface" );
moret's avatar
moret committed
83

84
85
86
87
88
89
90
91
92
        fSocket.Close();
        delete[] fTxBuffer;
        delete[] fRxBuffer;
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
    }

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

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

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

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

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

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

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

    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
136
137
        
        if (fTxHeader.fMidiDataSize <= PACKET_AVAILABLE_SIZE) {
moret's avatar
moret committed
138
            return 1;
sletz's avatar
sletz committed
139
140
141
142
143
        } 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
144
145
146
147
148
149
    }

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

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

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

173
174
175
176
177
178
179
        //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
180
        fTxHeader.fIsLastPckt = 0;
181
182
183
184
185
186
187
188

        //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
189
        fRxHeader.fIsLastPckt = 0;
190
191
192
193

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

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

202
    // JackNetMasterInterface ************************************************************************************
203

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

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

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

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

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

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

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

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

        return true;
271
272
    }

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

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

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

        JackNetInterface::SetParams();

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

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

        //audio net buffers
303
304
305
306
307
308
        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 );     
     
309
310
        assert ( fNetAudioCaptureBuffer );
        assert ( fNetAudioPlaybackBuffer );
moret's avatar
moret committed
311
312

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

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

        //stop process
        fRunning = false;
323

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

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

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

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

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

        return 0;
450
451
    }

452
    int JackNetMasterInterface::SyncRecv()
453
454
    {
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
sletz's avatar
sletz committed
455
        int rx_bytes = Recv(HEADER_SIZE, MSG_PEEK);
456
        
457
458
459
        if ( ( rx_bytes == 0 ) || ( rx_bytes == SOCKET_ERROR ) )
            return rx_bytes;

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

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

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

moret's avatar
moret committed
510
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
511
512
        return rx_bytes;
    }
513
    
514
    int JackNetMasterInterface::DataRecv()
515
516
    {
        int rx_bytes = 0;
517
        uint jumpcnt = 0;
518
        uint recvd_midi_pckt = 0;
519
        uint recvd_audio_pckt = 0;
520
521
        int last_cycle = 0;
         
522
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
523
        
moret's avatar
moret committed
524
        while ( !fRxHeader.fIsLastPckt )
525
        {
moret's avatar
moret committed
526
            //how much data is queued on the rx buffer ?
sletz's avatar
sletz committed
527
            rx_bytes = Recv(HEADER_SIZE, MSG_PEEK);
528
              
moret's avatar
moret committed
529
530
            if ( rx_bytes == SOCKET_ERROR )
                return rx_bytes;
moret's avatar
moret committed
531
            //if no data
moret's avatar
moret committed
532
            if ( ( rx_bytes == 0 ) && ( ++jumpcnt == fNSubProcess ) )
533
            {
moret's avatar
moret committed
534
535
536
537
538
539
540
541
                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 )
542
                {
moret's avatar
moret committed
543
                    case 'm':   //midi
544
                        rx_bytes = Recv ( rx_head->fPacketSize, 0 );
moret's avatar
moret committed
545
                        fRxHeader.fCycle = rx_head->fCycle;
moret's avatar
moret committed
546
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
sletz's avatar
sletz committed
547
                        fNetMidiPlaybackBuffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
548
                        if ( ++recvd_midi_pckt == rx_head->fNMidiPckt )
moret's avatar
moret committed
549
550
551
                            fNetMidiPlaybackBuffer->RenderToJackPorts();
                        jumpcnt = 0;
                        break;
552

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

moret's avatar
moret committed
566
                    case 's':   //sync
567
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
568
569
                        // Finish rendering (copy to JACK ports)
                        fNetAudioPlaybackBuffer->FinishRenderToJackPorts(last_cycle); 
570
                        return 0;
571
572
573
                }
            }
        }
574
575
576
        
        // Finish rendering (copy to JACK ports)
        fNetAudioPlaybackBuffer->FinishRenderToJackPorts(last_cycle); 
577
        return rx_bytes;
578
    }
579
    
sletz's avatar
sletz committed
580
    void JackNetMasterInterface::EncodeSyncPacket()
581
582
583
584
585
586
    {
        //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
587
588
589
        if (fParams.fTransportSync) {
            EncodeTransportData();
            TransportDataHToN( &fSendTransportData,  &fSendTransportData);
590
591
592
593
594
595
596
            //copy to TxBuffer
            memcpy ( fTxData, &fSendTransportData, sizeof ( net_transport_data_t ) );
        }
        //then others (freewheel etc.)
        //...
    }

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

611
612
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
613
614
    uint JackNetSlaveInterface::fSlaveCounter = 0;

615
    bool JackNetSlaveInterface::Init()
616
    {
617
        jack_log ( "JackNetSlaveInterface::Init()" );
618

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

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

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

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

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

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

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

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

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

719
720
        //send 'AVAILABLE' until 'SLAVE_SETUP' received
        jack_info ( "Waiting for a master..." );
721
722
        do
        {
723
            //send 'available'
724
            session_params_t net_params;
sletz's avatar
sletz committed
725
            memset(&net_params, 0, sizeof ( session_params_t ));
726
727
            SessionParamsHToN(&fParams, &net_params);
            if ( fSocket.SendTo ( &net_params, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
728
                jack_error ( "Error in data send : %s", StrError ( NET_ERROR_CODE ) );
729
                
730
            //filter incoming packets : don't exit while no error is detected
731
732
733
            memset(&net_params, 0, sizeof ( session_params_t ));
            rx_bytes = fSocket.CatchHost ( &net_params, sizeof ( session_params_t ), 0 );
            SessionParamsNToH(&net_params, &host_params);
734
            if ( ( rx_bytes == SOCKET_ERROR ) && ( fSocket.GetError() != NET_NO_DATA ) )
735
            {
736
737
                jack_error ( "Can't receive : %s", StrError ( NET_ERROR_CODE ) );
                return NET_RECV_ERROR;
738
739
            }
        }
740
        while ( strcmp ( host_params.fPacketType, fParams.fPacketType )  && ( GetPacketType ( &host_params ) != SLAVE_SETUP ) );
sletz's avatar
sletz committed
741
   
moret's avatar
moret committed
742
        //everything is OK, copy parameters
sletz's avatar
sletz committed
743
        SessionParamsDisplay(&host_params);
744
        fParams = host_params;
moret's avatar
moret committed
745
746

        //set the new buffer sizes
sletz's avatar
sletz committed
747
        if ( SetNetBufferSize() == SOCKET_ERROR ) {
moret's avatar
moret committed
748
            jack_error ( "Can't set net buffer sizes : %s", StrError ( NET_ERROR_CODE ) );
sletz's avatar
sletz committed
749
750
             return NET_SOCKET_ERROR;
        }
moret's avatar
moret committed
751

752
        //connect the socket
sletz's avatar
sletz committed
753
        if ( fSocket.Connect() == SOCKET_ERROR ) {
754
755
            jack_error ( "Error in connect : %s", StrError ( NET_ERROR_CODE ) );
            return NET_CONNECT_ERROR;
756
757
        }

moret's avatar
moret committed
758
        return NET_CONNECTED;
759
760
    }

moret's avatar
moret committed
761
    net_status_t JackNetSlaveInterface::SendStartToMaster()
762
    {
moret's avatar
moret committed
763
        jack_log ( "JackNetSlaveInterface::SendStartToMaster" );
moret's avatar
moret committed
764

765
        //tell the master to start
766
        session_params_t net_params;
sletz's avatar
sletz committed
767
        memset(&net_params, 0, sizeof ( session_params_t ));
768
        SetPacketType ( &fParams, START_MASTER );
769
770
        SessionParamsHToN(&fParams, &net_params);
        if ( fSocket.Send ( &net_params, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
771
        {
772
773
            jack_error ( "Error in send : %s", StrError ( NET_ERROR_CODE ) );
            return ( fSocket.GetError() == NET_CONN_ERROR ) ? NET_ERROR : NET_SEND_ERROR;
774
        }
775
        return NET_ROLLING;
776
777
    }

778
    void JackNetSlaveInterface::SetParams()
moret's avatar
moret committed
779
    {
780
        jack_log ( "JackNetSlaveInterface::SetParams" );
moret's avatar
moret committed
781
782
783

        JackNetInterface::SetParams();

784
785
        fTxHeader.fDataStream = 'r';
        fRxHeader.fDataStream = 's';
moret's avatar
moret committed
786
787

        //midi net buffers
788
789
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fRxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fTxData );
moret's avatar
moret committed
790
791

        //audio net buffers
792
793
794
795
796
        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
797
798

        //audio netbuffer length
sletz's avatar
sletz committed
799
800
        fAudioTxLen = HEADER_SIZE + fNetAudioPlaybackBuffer->GetSize();
        fAudioRxLen = HEADER_SIZE + fNetAudioCaptureBuffer->GetSize();
moret's avatar
moret committed
801
802
    }

803
    int JackNetSlaveInterface::Recv ( size_t size, int flags )
804
    {
805
806
807
808
809
810
        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
811
            if ( error == NET_NO_DATA ) {
812
813
                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
814
            } else if ( error == NET_CONN_ERROR ) {
815
                jack_error ( "Connection lost." );
moret's avatar
moret committed
816
                throw JackNetException();
sletz's avatar
sletz committed
817
            } else {
sletz's avatar
sletz committed
818
                jack_error ( "Fatal error in slave receive : %s", StrError ( NET_ERROR_CODE ) );
sletz's avatar
sletz committed
819
            }
820
        }
821
822
823
        
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
        PacketHeaderNToH(header, header);
824
        return rx_bytes;
825
826
    }

827
    int JackNetSlaveInterface::Send ( size_t size, int flags )
828
    {
829
830
        packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
        PacketHeaderHToN(header, header);
831
        int tx_bytes = fSocket.Send ( fTxBuffer, size, flags );
832
         
833
834
        //handle errors
        if ( tx_bytes == SOCKET_ERROR )
835
836
        {
            net_error_t error = fSocket.GetError();
837
            //if a network error occurs, this exception will restart the driver
sletz's avatar
sletz committed
838
            if ( error == NET_CONN_ERROR ) {
839
                jack_error ( "Connection lost." );
moret's avatar
moret committed