JackNetInterface.cpp 32.7 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
45
46
47
    JackNetInterface::JackNetInterface() : fSocket()
    {
        fMulticastIP = NULL;
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
    }

moret's avatar
moret committed
48
    JackNetInterface::JackNetInterface ( const char* multicast_ip, int port ) : fSocket ( multicast_ip, port )
49
    {
moret's avatar
moret committed
50
        fMulticastIP = strdup ( multicast_ip );
51
52
53
54
55
56
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
57
58
    }

moret's avatar
moret committed
59
    JackNetInterface::JackNetInterface ( session_params_t& params, JackNetSocket& socket, const char* multicast_ip ) : fSocket ( socket )
60
    {
moret's avatar
moret committed
61
        fParams = params;
moret's avatar
moret committed
62
        fMulticastIP = strdup ( multicast_ip );
63
64
65
66
67
68
        fTxBuffer = NULL;
        fRxBuffer = NULL;
        fNetAudioCaptureBuffer = NULL;
        fNetAudioPlaybackBuffer = NULL;
        fNetMidiCaptureBuffer = NULL;
        fNetMidiPlaybackBuffer = NULL;
69
70
71
72
    }

    JackNetInterface::~JackNetInterface()
    {
moret's avatar
moret committed
73
        jack_log ( "JackNetInterface::~JackNetInterface" );
moret's avatar
moret committed
74

75
76
77
78
79
80
81
82
83
84
        fSocket.Close();
        delete[] fTxBuffer;
        delete[] fRxBuffer;
        delete[] fMulticastIP;
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
    }

85
    void JackNetInterface::SetFramesPerPacket()
moret's avatar
moret committed
86
    {
moret's avatar
moret committed
87
        jack_log ( "JackNetInterface::SetFramesPerPacket" );
moret's avatar
moret committed
88

89
90
91
92
93
94
95
        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
96
97
98
99
    }

    int JackNetInterface::SetNetBufferSize()
    {
moret's avatar
moret committed
100
        jack_log ( "JackNetInterface::SetNetBufferSize" );
moret's avatar
moret committed
101

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

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

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

120
        return 0;
moret's avatar
moret committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    }

    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
140
        if ( fRxHeader.fCycle <= 1 ) {
moret's avatar
moret committed
141
            return true;
142
        }
moret's avatar
moret committed
143
        //same PcktID (cycle), next SubPcktID (subcycle)
144
145
146
        if ( ( fRxHeader.fSubCycle < ( fNSubProcess - 1 ) ) && ( rx_head->fCycle == fRxHeader.fCycle ) && ( rx_head->fSubCycle == ( fRxHeader.fSubCycle + 1 ) ) ) {
             return true;
        }
moret's avatar
moret committed
147
        //next PcktID (cycle), SubPcktID reset to 0 (first subcyle)
148
        if ( ( rx_head->fCycle == ( fRxHeader.fCycle + 1 ) ) && ( fRxHeader.fSubCycle == ( fNSubProcess - 1 ) ) && ( rx_head->fSubCycle == 0 ) ) {
moret's avatar
moret committed
149
            return true;
150
        }
moret's avatar
moret committed
151
        //else, packet(s) missing, return false
moret's avatar
moret committed
152
153
154
        return false;
    }

155
156
    void JackNetInterface::SetParams()
    {
moret's avatar
moret committed
157
        //number of audio subcycles (packets)
158
159
        fNSubProcess = fParams.fPeriodSize / fParams.fFramesPerPacket;

moret's avatar
moret committed
160
161
162
        //payload size
        fPayloadSize = fParams.fMtu - sizeof ( packet_header_t );

163
164
165
166
167
168
169
        //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
170
        fTxHeader.fIsLastPckt = 0;
171
172
173
174
175
176
177
178

        //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
179
        fRxHeader.fIsLastPckt = 0;
180
181
182
183

        //network buffers
        fTxBuffer = new char[fParams.fMtu];
        fRxBuffer = new char[fParams.fMtu];
184
185
        assert ( fTxBuffer );
        assert ( fRxBuffer );
186

moret's avatar
moret committed
187
        //net audio/midi buffers'addresses
188
189
190
191
        fTxData = fTxBuffer + sizeof ( packet_header_t );
        fRxData = fRxBuffer + sizeof ( packet_header_t );
    }

192
    // JackNetMasterInterface ************************************************************************************
193

194
    bool JackNetMasterInterface::Init()
195
    {
196
        jack_log ( "JackNetMasterInterface::Init, ID %u.", fParams.fID );
197
198

        session_params_t params;
199
        uint attempt = 0;
200
201
202
203
204
        int rx_bytes = 0;

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

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

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

223
224
        //send 'SLAVE_SETUP' until 'START_MASTER' received
        jack_info ( "Sending parameters to %s ...", fParams.fSlaveNetName );
225
226
        do
        {
227
228
229
230
            SetPacketType ( &fParams, SLAVE_SETUP );
            if ( fSocket.Send ( &fParams, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
                jack_error ( "Error in send : ", StrError ( NET_ERROR_CODE ) );
            if ( ( ( rx_bytes = fSocket.Recv ( &params, sizeof ( session_params_t ), 0 ) ) == SOCKET_ERROR ) && ( fSocket.GetError() != NET_NO_DATA ) )
231
            {
232
233
                jack_error ( "Problem with network." );
                return false;
234
235
            }
        }
236
237
        while ( ( GetPacketType ( &params ) != START_MASTER ) && ( ++attempt < SLAVE_SETUP_RETRY ) );
        if ( attempt == SLAVE_SETUP_RETRY )
238
        {
239
240
            jack_error ( "Slave doesn't respond, exiting." );
            return false;
241
242
        }

243
        //set the new timeout for the socket
moret's avatar
moret committed
244
        if ( SetRxTimeout() == SOCKET_ERROR )
245
246
247
248
        {
            jack_error ( "Can't set rx timeout : %s", StrError ( NET_ERROR_CODE ) );
            return false;
        }
249

250
        //set the new rx buffer size
moret's avatar
moret committed
251
        if ( SetNetBufferSize() == SOCKET_ERROR )
252
        {
moret's avatar
moret committed
253
            jack_error ( "Can't set net buffer sizes : %s", StrError ( NET_ERROR_CODE ) );
254
            return false;
255
        }
256
257

        return true;
258
259
    }

moret's avatar
moret committed
260
261
    int JackNetMasterInterface::SetRxTimeout()
    {
moret's avatar
moret committed
262
263
        jack_log ( "JackNetMasterInterface::SetRxTimeout" );

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

274
    void JackNetMasterInterface::SetParams()
moret's avatar
moret committed
275
    {
276
        jack_log ( "JackNetMasterInterface::SetParams" );
moret's avatar
moret committed
277
278
279

        JackNetInterface::SetParams();

280
281
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
282
283

        //midi net buffers
284
285
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fTxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fRxData );
286
287
        assert ( fNetMidiCaptureBuffer );
        assert ( fNetMidiPlaybackBuffer );
moret's avatar
moret committed
288
289

        //audio net buffers
290
291
        fNetAudioCaptureBuffer = new NetAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
        fNetAudioPlaybackBuffer = new NetAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );
292
293
        assert ( fNetAudioCaptureBuffer );
        assert ( fNetAudioPlaybackBuffer );
moret's avatar
moret committed
294
295
296
297
298
299

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

300
    void JackNetMasterInterface::Exit()
301
    {
302
303
304
305
        jack_log ( "JackNetMasterInterface::Exit, ID %u", fParams.fID );

        //stop process
        fRunning = false;
306

307
308
309
310
311
312
313
314
315
        //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() );
        if ( mcast_socket.NewSocket() == SOCKET_ERROR )
            jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
        if ( mcast_socket.SendTo ( &fParams, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
            jack_error ( "Can't send suicide request : %s", StrError ( NET_ERROR_CODE ) );
        mcast_socket.Close();
316

317
318
        // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
        ThreadExit();
319
320
321
322
323
    }

    int JackNetMasterInterface::Send ( size_t size, int flags )
    {
        int tx_bytes;
moret's avatar
moret committed
324
        if ( ( ( tx_bytes = fSocket.Send ( fTxBuffer, size, flags ) ) == SOCKET_ERROR ) && fRunning )
325
326
        {
            net_error_t error = fSocket.GetError();
moret's avatar
moret committed
327
            if ( error == NET_CONN_ERROR )
328
329
330
331
332
            {
                //fatal connection issue, exit
                jack_error ( "'%s' : %s, exiting.", fParams.fName, StrError ( NET_ERROR_CODE ) );
                Exit();
            }
moret's avatar
moret committed
333
            else
sletz's avatar
sletz committed
334
                jack_error ( "Error in master send : %s", StrError ( NET_ERROR_CODE ) );
335
336
337
338
339
340
341
        }
        return tx_bytes;
    }

    int JackNetMasterInterface::Recv ( size_t size, int flags )
    {
        int rx_bytes;
moret's avatar
moret committed
342
        if ( ( ( rx_bytes = fSocket.Recv ( fRxBuffer, size, flags ) ) == SOCKET_ERROR ) && fRunning )
343
344
345
        {
            net_error_t error = fSocket.GetError();
            //no data isn't really a network error, so just return 0 avalaible read bytes
346
            if ( error == NET_NO_DATA )
347
                return 0;
moret's avatar
moret committed
348
            else if ( error == NET_CONN_ERROR )
349
            {
350
351
352
353
                //fatal connection issue, exit
                jack_error ( "'%s' : %s, exiting.", fParams.fName, StrError ( NET_ERROR_CODE ) );
                //ask to the manager to properly remove the master
                Exit();
354
            }
moret's avatar
moret committed
355
            else
sletz's avatar
sletz committed
356
                jack_error ( "Error in master receive : %s", StrError ( NET_ERROR_CODE ) );
357
358
359
        }
        return rx_bytes;
    }
360
361
362
    
    bool JackNetMasterInterface::IsSynched()
    {
sletz's avatar
sletz committed
363
        if (fParams.fNetworkMode == 's') {
364
            return (fCycleOffset < 3);
sletz's avatar
sletz committed
365
        } else {
366
            return true;
sletz's avatar
sletz committed
367
        }
368
369
    }
    
370
    int JackNetMasterInterface::SyncSend()
371
    {
372
373
374
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
moret's avatar
moret committed
375
        fTxHeader.fIsLastPckt = ( !fParams.fSendMidiChannels && !fParams.fSendAudioChannels ) ?  1 : 0;
376
377
378
379
380
381
382
383
384
385
        fTxHeader.fPacketSize = fParams.fMtu;
        memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
        return Send ( fTxHeader.fPacketSize, 0 );
    }

    int JackNetMasterInterface::DataSend()
    {
        uint subproc;
        //midi
        if ( fParams.fSendMidiChannels )
386
        {
387
388
389
            //set global header fields and get the number of midi packets
            fTxHeader.fDataType = 'm';
            fTxHeader.fMidiDataSize = fNetMidiCaptureBuffer->RenderFromJackPorts();
moret's avatar
moret committed
390
            fTxHeader.fNMidiPckt = GetNMidiPckt();
391
            for ( subproc = 0; subproc < fTxHeader.fNMidiPckt; subproc++ )
392
            {
393
                fTxHeader.fSubCycle = subproc;
moret's avatar
moret committed
394
                fTxHeader.fIsLastPckt = ( ( subproc == ( fTxHeader.fNMidiPckt - 1 ) ) && !fParams.fSendAudioChannels ) ? 1 : 0;
395
                fTxHeader.fPacketSize = sizeof ( packet_header_t ) + fNetMidiCaptureBuffer->RenderToNetwork ( subproc, fTxHeader.fMidiDataSize );
396
397
398
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
                if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
                    return SOCKET_ERROR;
399
400
            }
        }
401
402
403
404
405
406
407
408

        //audio
        if ( fParams.fSendAudioChannels )
        {
            fTxHeader.fDataType = 'a';
            for ( subproc = 0; subproc < fNSubProcess; subproc++ )
            {
                fTxHeader.fSubCycle = subproc;
moret's avatar
moret committed
409
                fTxHeader.fIsLastPckt = ( subproc == ( fNSubProcess - 1 ) ) ? 1 : 0;
410
411
412
413
414
415
416
417
418
                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;
419
420
    }

421
    int JackNetMasterInterface::SyncRecv()
422
423
    {
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
424
425
        int rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
        
426
427
428
        if ( ( rx_bytes == 0 ) || ( rx_bytes == SOCKET_ERROR ) )
            return rx_bytes;

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

449
450
451
452
453
            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
454
                if (fCycleOffset < 1)
455
456
457
                    return 0;
                else
                    rx_bytes = Recv ( rx_head->fPacketSize, 0 );
458
459
460
                    
                if (fCycleOffset != 1) 
                    jack_info("'%s' can't run in normal network mode, data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
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
470
471
                
                if (fCycleOffset != 0)
                    jack_info("'%s' can't run in fast network mode, data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
472
                break;
473
        }
474

moret's avatar
moret committed
475
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
476
477
        return rx_bytes;
    }
478
    
479
    int JackNetMasterInterface::DataRecv()
480
481
    {
        int rx_bytes = 0;
482
        uint jumpcnt = 0;
483
        uint recvd_midi_pckt = 0;
484
        uint recvd_audio_pckt = 0;
485
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
486
        
moret's avatar
moret committed
487
        while ( !fRxHeader.fIsLastPckt )
488
        {
moret's avatar
moret committed
489
490
            //how much data is queued on the rx buffer ?
            rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
491
              
moret's avatar
moret committed
492
493
            if ( rx_bytes == SOCKET_ERROR )
                return rx_bytes;
moret's avatar
moret committed
494
            //if no data
moret's avatar
moret committed
495
            if ( ( rx_bytes == 0 ) && ( ++jumpcnt == fNSubProcess ) )
496
            {
moret's avatar
moret committed
497
498
499
500
501
502
503
504
                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 )
505
                {
moret's avatar
moret committed
506
                    case 'm':   //midi
507
                        rx_bytes = Recv ( rx_head->fPacketSize, 0 );
moret's avatar
moret committed
508
                        fRxHeader.fCycle = rx_head->fCycle;
moret's avatar
moret committed
509
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
moret's avatar
moret committed
510
                        fNetMidiPlaybackBuffer->RenderFromNetwork ( rx_head->fSubCycle, rx_bytes - sizeof ( packet_header_t ) );
511
                        if ( ++recvd_midi_pckt == rx_head->fNMidiPckt )
moret's avatar
moret committed
512
513
514
                            fNetMidiPlaybackBuffer->RenderToJackPorts();
                        jumpcnt = 0;
                        break;
515

moret's avatar
moret committed
516
                    case 'a':   //audio
517
                        rx_bytes = Recv ( rx_head->fPacketSize, 0 );
518
519
520
                        // SL: 25/01/09
                        // if ( !IsNextPacket() )
                        //    jack_error ( "Packet(s) missing from '%s'...", fParams.fName );
521
522
523
                        if (recvd_audio_pckt++ != rx_head->fSubCycle) {
                            jack_error("Packet(s) missing from '%s'...", fParams.fSlaveNetName);
                        }
moret's avatar
moret committed
524
525
                        fRxHeader.fCycle = rx_head->fCycle;
                        fRxHeader.fSubCycle = rx_head->fSubCycle;
moret's avatar
moret committed
526
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
moret's avatar
moret committed
527
528
529
                        fNetAudioPlaybackBuffer->RenderToJackPorts ( rx_head->fSubCycle );
                        jumpcnt = 0;
                        break;
530

moret's avatar
moret committed
531
                    case 's':   //sync
532
                        /* SL: 25/01/09
moret's avatar
moret committed
533
534
                        if ( rx_head->fCycle == fTxHeader.fCycle )
                            return 0;
535
                        */
536
                        jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
537
                        return 0;
538
539
540
                }
            }
        }
541
        return rx_bytes;
542
543
    }

544
545
// JackNetSlaveInterface ************************************************************************************************

moret's avatar
moret committed
546
547
    uint JackNetSlaveInterface::fSlaveCounter = 0;

548
    bool JackNetSlaveInterface::Init()
549
    {
550
        jack_log ( "JackNetSlaveInterface::Init()" );
551

552
553
554
555
        //set the parameters to send
        strcpy ( fParams.fPacketType, "params" );
        fParams.fProtocolVersion = 'a';
        SetPacketType ( &fParams, SLAVE_AVAILABLE );
556

557
558
559
        //init loop : get a master and start, do it until connection is ok
        net_status_t status;
        do
560
        {
561
562
            //first, get a master, do it until a valid connection is running
            do
563
            {
564
565
566
                status = GetNetMaster();
                if ( status == NET_SOCKET_ERROR )
                    return false;
567
            }
568
            while ( status != NET_CONNECTED );
569

570
571
            //then tell the master we are ready
            jack_info ( "Initializing connection with %s...", fParams.fMasterNetName );
moret's avatar
moret committed
572
            status = SendStartToMaster();
573
574
            if ( status == NET_ERROR )
                return false;
575
        }
576
        while ( status != NET_ROLLING );
577

578
579
        return true;
    }
580

581
    net_status_t JackNetSlaveInterface::GetNetMaster()
582
    {
583
584
        jack_log ( "JackNetSlaveInterface::GetNetMaster()" );
        //utility
585
586
587
588
589
590
        session_params_t params;
        int rx_bytes = 0;

        //socket
        if ( fSocket.NewSocket() == SOCKET_ERROR )
        {
591
592
            jack_error ( "Fatal error : network unreachable - %s", StrError ( NET_ERROR_CODE ) );
            return NET_SOCKET_ERROR;
593
594
        }

595
596
597
598
599
        //bind the socket
        if ( fSocket.Bind() == SOCKET_ERROR )
            jack_error ( "Can't bind the socket : %s", StrError ( NET_ERROR_CODE ) );

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

603
        //disable local loop
moret's avatar
moret committed
604
        if ( fSocket.SetLocalLoop() == SOCKET_ERROR )
605
            jack_error ( "Can't disable multicast loop : %s", StrError ( NET_ERROR_CODE ) );
606

607
608
        //send 'AVAILABLE' until 'SLAVE_SETUP' received
        jack_info ( "Waiting for a master..." );
609
610
        do
        {
611
612
613
614
615
616
            //send 'available'
            if ( fSocket.SendTo ( &fParams, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
                jack_error ( "Error in data send : %s", StrError ( NET_ERROR_CODE ) );
            //filter incoming packets : don't exit while no error is detected
            rx_bytes = fSocket.CatchHost ( &params, sizeof ( session_params_t ), 0 );
            if ( ( rx_bytes == SOCKET_ERROR ) && ( fSocket.GetError() != NET_NO_DATA ) )
617
            {
618
619
                jack_error ( "Can't receive : %s", StrError ( NET_ERROR_CODE ) );
                return NET_RECV_ERROR;
620
621
            }
        }
622
        while ( strcmp ( params.fPacketType, fParams.fPacketType ) && ( GetPacketType ( &params ) != SLAVE_SETUP ) );
623

moret's avatar
moret committed
624
625
626
627
628
629
630
        //everything is OK, copy parameters
        fParams = params;

        //set the new buffer sizes
        if ( SetNetBufferSize() == SOCKET_ERROR )
            jack_error ( "Can't set net buffer sizes : %s", StrError ( NET_ERROR_CODE ) );

631
632
        //connect the socket
        if ( fSocket.Connect() == SOCKET_ERROR )
633
        {
634
635
            jack_error ( "Error in connect : %s", StrError ( NET_ERROR_CODE ) );
            return NET_CONNECT_ERROR;
636
637
        }

moret's avatar
moret committed
638
        return NET_CONNECTED;
639
640
    }

moret's avatar
moret committed
641
    net_status_t JackNetSlaveInterface::SendStartToMaster()
642
    {
moret's avatar
moret committed
643
        jack_log ( "JackNetSlaveInterface::SendStartToMaster" );
moret's avatar
moret committed
644

645
646
647
        //tell the master to start
        SetPacketType ( &fParams, START_MASTER );
        if ( fSocket.Send ( &fParams, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
648
        {
649
650
            jack_error ( "Error in send : %s", StrError ( NET_ERROR_CODE ) );
            return ( fSocket.GetError() == NET_CONN_ERROR ) ? NET_ERROR : NET_SEND_ERROR;
651
        }
652
        return NET_ROLLING;
653
654
    }

655
    void JackNetSlaveInterface::SetParams()
moret's avatar
moret committed
656
    {
657
        jack_log ( "JackNetSlaveInterface::SetParams" );
moret's avatar
moret committed
658
659
660

        JackNetInterface::SetParams();

661
662
        fTxHeader.fDataStream = 'r';
        fRxHeader.fDataStream = 's';
moret's avatar
moret committed
663
664

        //midi net buffers
665
666
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fRxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fTxData );
moret's avatar
moret committed
667
668

        //audio net buffers
669
670
        fNetAudioCaptureBuffer = new NetAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
        fNetAudioPlaybackBuffer = new NetAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
moret's avatar
moret committed
671
672
673
674
675
676

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

677
    int JackNetSlaveInterface::Recv ( size_t size, int flags )
678
    {
679
680
681
682
683
684
685
686
687
688
689
690
        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
691
                throw JackNetException();
692
693
            }
            else
sletz's avatar
sletz committed
694
                jack_error ( "Fatal error in slave receive : %s", StrError ( NET_ERROR_CODE ) );
695
696
        }
        return rx_bytes;
697
698
    }

699
    int JackNetSlaveInterface::Send ( size_t size, int flags )
700
    {
701
702
703
        int tx_bytes = fSocket.Send ( fTxBuffer, size, flags );
        //handle errors
        if ( tx_bytes == SOCKET_ERROR )
704
705
        {
            net_error_t error = fSocket.GetError();
706
707
            //if a network error occurs, this exception will restart the driver
            if ( error == NET_CONN_ERROR )
708
            {
709
                jack_error ( "Connection lost." );
moret's avatar
moret committed
710
                throw JackNetException();
711
            }
712
            else
sletz's avatar
sletz committed
713
                jack_error ( "Fatal error in slave send : %s", StrError ( NET_ERROR_CODE ) );
714
715
716
717
        }
        return tx_bytes;
    }

718
    int JackNetSlaveInterface::SyncRecv()
719
    {
720
721
722
723
        int rx_bytes = 0;
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
        //receive sync (launch the cycle)
        do
724
        {
725
726
727
728
729
730
            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;
        }
        while ( !rx_bytes && ( rx_head->fDataType != 's' ) );
moret's avatar
moret committed
731
        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
732
733
734
735
736
737
        return rx_bytes;
    }

    int JackNetSlaveInterface::DataRecv()
    {
        uint recvd_midi_pckt = 0;
738
        uint recvd_audio_pckt = 0;
739
740
741
        int rx_bytes = 0;
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );

moret's avatar
moret committed
742
        while ( !fRxHeader.fIsLastPckt )
743
        {
moret's avatar
moret committed
744
745
            rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
            //error here, problem with recv, just skip the cycle (return -1)
moret's avatar
moret committed
746

moret's avatar
moret committed
747
748
749
            if ( rx_bytes == SOCKET_ERROR )
                return rx_bytes;
            if ( rx_bytes && ( rx_head->fDataStream == 's' ) && ( rx_head->fID == fParams.fID ) )
750
            {
moret's avatar
moret committed
751
                switch ( rx_head->fDataType )
752
                {
moret's avatar
moret committed
753
754
755
                    case 'm':   //midi
                        rx_bytes = Recv ( rx_head->fPacketSize, 0 );
                        fRxHeader.fCycle = rx_head->fCycle;
moret's avatar
moret committed
756
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
moret's avatar
moret committed
757
758
759
760
                        fNetMidiCaptureBuffer->RenderFromNetwork ( rx_head->fSubCycle, rx_bytes - sizeof ( packet_header_t ) );
                        if ( ++recvd_midi_pckt == rx_head->fNMidiPckt )
                            fNetMidiCaptureBuffer->RenderToJackPorts();
                        break;
761

moret's avatar
moret committed
762
763
                    case 'a':   //audio
                        rx_bytes = Recv ( rx_head->fPacketSize, 0 );
764
765
766
                        //SL: 25/01/09
                        // if ( !IsNextPacket() )
                        //    jack_error ( "Packet(s) missing..." );
767
768
769
                        if (recvd_audio_pckt++ != rx_head->fSubCycle) {
                            jack_error("Packet(s) missing from '%s'...", fParams.fMasterNetName);
                        }
moret's avatar
moret committed
770
771
                        fRxHeader.fCycle = rx_head->fCycle;
                        fRxHeader.fSubCycle = rx_head->fSubCycle;
moret's avatar
moret committed
772
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
moret's avatar
moret committed
773
774
                        fNetAudioCaptureBuffer->RenderToJackPorts ( rx_head->fSubCycle );
                        break;
775

moret's avatar
moret committed
776
777
778
                    case 's':   //sync
                        jack_info ( "NetSlave : overloaded, skipping receive." );
                        return 0;
779
                }
780
781
            }
        }
782
783
        fRxHeader.fCycle = rx_head->fCycle;
        return 0;
784
785
    }

786
    int JackNetSlaveInterface::SyncSend()
787
    {
788
789
790
791
792
        //tx header
        if ( fParams.fSlaveSyncMode )
            fTxHeader.fCycle = fRxHeader.fCycle;
        else
            fTxHeader.fCycle++;
793
794
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
moret's avatar
moret committed
795
        fTxHeader.fIsLastPckt = ( !fParams.fReturnMidiChannels && !fParams.fReturnAudioChannels ) ?  1 : 0;
796
797
798
799
800
        fTxHeader.fPacketSize = fParams.fMtu;
        memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
        return Send ( fTxHeader.fPacketSize, 0 );
    }

801
    int JackNetSlaveInterface::DataSend()
802
803
    {
        uint subproc;
804

805
        //midi
806
        if ( fParams.fReturnMidiChannels )
807
808
        {
            fTxHeader.fDataType = 'm';
809
            fTxHeader.fMidiDataSize = fNetMidiPlaybackBuffer->RenderFromJackPorts();
moret's avatar
moret committed
810
            fTxHeader.fNMidiPckt = GetNMidiPckt();
811
812
813
            for ( subproc = 0; subproc < fTxHeader.fNMidiPckt; subproc++ )
            {
                fTxHeader.fSubCycle = subproc;
moret's avatar
moret committed
814
                fTxHeader.fIsLastPckt = ( ( subproc == ( fTxHeader.fNMidiPckt - 1 ) ) && !fParams.fReturnAudioChannels ) ? 1 : 0;
815
                fTxHeader.fPacketSize = sizeof ( packet_header_t ) + fNetMidiPlaybackBuffer->RenderToNetwork ( subproc, fTxHeader.fMidiDataSize );
816
817
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
                if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
moret's avatar
moret committed
818
                    return SOCKET_ERROR;
819
820
821
822
            }
        }

        //audio
823
        if ( fParams.fReturnAudioChannels )
824
825
826
827
828
        {
            fTxHeader.fDataType = 'a';
            for ( subproc = 0; subproc < fNSubProcess; subproc++ )
            {
                fTxHeader.fSubCycle = subproc;
moret's avatar
moret committed
829
                fTxHeader.fIsLastPckt = ( subproc == ( fNSubProcess - 1 ) ) ? 1 : 0;
830
831
                fTxHeader.fPacketSize = fAudioTxLen;
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
832
                fNetAudioPlaybackBuffer->RenderFromJackPorts ( subproc );
833
                if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
moret's avatar
moret committed
834
                    return SOCKET_ERROR;
835
836
837
838
839
            }
        }
        return 0;
    }
}