JackNetInterface.cpp 26.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
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"

#define DEFAULT_MULTICAST_IP "225.3.19.154"
#define DEFAULT_PORT 19000

using namespace std;

namespace Jack
{
    // JackNetInterface*******************************************

    JackNetInterface::JackNetInterface ( const char* ip, int port ) : fSocket ( ip, port )
    {
moret's avatar
moret committed
35
        jack_log ( "JackNetInterface::JackNetInterface ip = %s port = %d", ip, port );
36

37
        fMulticastIP = strdup ( ip );
38
39
    }

moret's avatar
moret committed
40
    JackNetInterface::JackNetInterface ( session_params_t& params, JackNetSocket& socket, const char* multicast_ip ) : fSocket ( socket )
41
    {
moret's avatar
moret committed
42
        jack_log ( "JackNetInterface::JackNetInterface ID = %d", params.fID );
43
44

        fParams = params;
moret's avatar
moret committed
45
        fMulticastIP = strdup ( multicast_ip );
46
47
48
49
    }

    JackNetInterface::~JackNetInterface()
    {
moret's avatar
moret committed
50
        jack_log ( "JackNetInterface::~JackNetInterface" );
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
        fSocket.Close();
        delete[] fTxBuffer;
        delete[] fRxBuffer;
        delete[] fMulticastIP;
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
    }

    void JackNetInterface::SetParams()
    {
        fNSubProcess = fParams.fPeriodSize / fParams.fFramesPerPacket;

        //TX header init
        strcpy ( fTxHeader.fPacketType, "header" );
        fTxHeader.fID = fParams.fID;
        fTxHeader.fCycle = 0;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fMidiDataSize = 0;
        fTxHeader.fBitdepth = fParams.fBitdepth;

        //RX header init
        strcpy ( fRxHeader.fPacketType, "header" );
        fRxHeader.fID = fParams.fID;
        fRxHeader.fCycle = 0;
        fRxHeader.fSubCycle = 0;
        fRxHeader.fMidiDataSize = 0;
        fRxHeader.fBitdepth = fParams.fBitdepth;

        //network buffers
        fTxBuffer = new char[fParams.fMtu];
        fRxBuffer = new char[fParams.fMtu];

        //net audio/midi buffers
        fTxData = fTxBuffer + sizeof ( packet_header_t );
        fRxData = fRxBuffer + sizeof ( packet_header_t );

        //payload size
        fPayloadSize = fParams.fMtu - sizeof ( packet_header_t );
    }

93
    // JackNetMasterInterface ************************************************************************************
94

95
    bool JackNetMasterInterface::Init()
96
    {
97
        jack_log ( "JackNetMasterInterface::Init, ID %u.", fParams.fID );
98
99

        session_params_t params;
100
        uint attempt = 0;
101
        int rx_bytes = 0;
102
        int rx_bufsize = 0;
103
104
105
106

        //socket
        if ( fSocket.NewSocket() == SOCKET_ERROR )
        {
107
108
            jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
            return false;
109
110
        }

111
112
        //timeout on receive (for init)
        if ( fSocket.SetTimeOut ( 1000000 ) < 0 )
113
114
            jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );

115
116
117
118
119
120
        //connect
        if ( fSocket.Connect() == SOCKET_ERROR )
        {
            jack_error ( "Can't connect : %s", StrError ( NET_ERROR_CODE ) );
            return false;
        }
121

122
123
        //send 'SLAVE_SETUP' until 'START_MASTER' received
        jack_info ( "Sending parameters to %s ...", fParams.fSlaveNetName );
124
125
        do
        {
126
127
128
129
            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 ) )
130
            {
131
132
                jack_error ( "Problem with network." );
                return false;
133
134
            }
        }
135
136
        while ( ( GetPacketType ( &params ) != START_MASTER ) && ( ++attempt < 5 ) );
        if ( attempt == 5 )
137
        {
138
139
            jack_error ( "Slave doesn't respond, exiting." );
            return false;
140
141
        }

142
143
144
145
146
147
        //set the new timeout for the socket
        if ( SetRxTimeout ( &fSocket, &fParams ) == SOCKET_ERROR )
        {
            jack_error ( "Can't set rx timeout : %s", StrError ( NET_ERROR_CODE ) );
            return false;
        }
148

149
150
151
        //set the new rx buffer size
        rx_bufsize = GetNetBufferSize ( &fParams );
        if ( fSocket.SetOption ( SOL_SOCKET, SO_RCVBUF, &rx_bufsize, sizeof ( rx_bufsize ) ) == SOCKET_ERROR )
152
        {
153
154
            jack_error ( "Can't set rx buffer size : %s", StrError ( NET_ERROR_CODE ) );
            return false;
155
        }
156
157

        return true;
158
159
    }

160
    void JackNetMasterInterface::SetParams()
moret's avatar
moret committed
161
    {
162
        jack_log ( "JackNetMasterInterface::SetParams" );
moret's avatar
moret committed
163
164
165

        JackNetInterface::SetParams();

166
167
        fTxHeader.fDataStream = 's';
        fRxHeader.fDataStream = 'r';
moret's avatar
moret committed
168
169

        //midi net buffers
170
171
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fTxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fRxData );
moret's avatar
moret committed
172
173

        //audio net buffers
174
175
        fNetAudioCaptureBuffer = new NetAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
        fNetAudioPlaybackBuffer = new NetAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );
moret's avatar
moret committed
176
177
178
179
180
181

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

182
    void JackNetMasterInterface::Exit()
183
    {
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
        jack_log ( "JackNetMasterInterface::Exit, ID %u", fParams.fID );

        //stop process
        fRunning = false;
        //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();
    }

    int JackNetMasterInterface::Send ( size_t size, int flags )
    {
        int tx_bytes;
        if ( ( tx_bytes = fSocket.Send ( fTxBuffer, size, flags ) ) == SOCKET_ERROR )
203
204
        {
            net_error_t error = fSocket.GetError();
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
            if ( fRunning && ( error == NET_CONN_ERROR ) )
            {
                //fatal connection issue, exit
                jack_error ( "'%s' : %s, exiting.", fParams.fName, StrError ( NET_ERROR_CODE ) );
                Exit();
            }
            else if ( fRunning )
                jack_error ( "Error in send : %s", StrError ( NET_ERROR_CODE ) );
        }
        return tx_bytes;
    }

    int JackNetMasterInterface::Recv ( size_t size, int flags )
    {
        int rx_bytes;
        if ( ( rx_bytes = fSocket.Recv ( fRxBuffer, size, flags ) ) == SOCKET_ERROR )
        {
            net_error_t error = fSocket.GetError();
            //no data isn't really a network error, so just return 0 avalaible read bytes
224
            if ( error == NET_NO_DATA )
225
226
                return 0;
            else if ( fRunning && ( error == NET_CONN_ERROR ) )
227
            {
228
229
230
231
                //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();
232
            }
233
234
            else if ( fRunning )
                jack_error ( "Error in receive : %s", StrError ( NET_ERROR_CODE ) );
235
236
237
238
        }
        return rx_bytes;
    }

239
    int JackNetMasterInterface::SyncSend()
240
    {
241
242
243
244
245
246
247
248
249
250
251
252
253
254
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
        fTxHeader.fIsLastPckt = ( !fParams.fSendMidiChannels && !fParams.fSendAudioChannels ) ?  'y' : 'n';
        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 )
255
        {
256
257
258
259
260
            //set global header fields and get the number of midi packets
            fTxHeader.fDataType = 'm';
            fTxHeader.fMidiDataSize = fNetMidiCaptureBuffer->RenderFromJackPorts();
            fTxHeader.fNMidiPckt = GetNMidiPckt ( &fParams, fTxHeader.fMidiDataSize );
            for ( subproc = 0; subproc < fTxHeader.fNMidiPckt; subproc++ )
261
            {
262
263
264
265
266
267
268
269
270
271
272
                //fill the packet header fields
                fTxHeader.fSubCycle = subproc;
                if ( ( subproc == ( fTxHeader.fNMidiPckt - 1 ) ) && !fParams.fSendAudioChannels )
                    fTxHeader.fIsLastPckt = 'y';
                //get the data from buffer
                fTxHeader.fPacketSize = fNetMidiCaptureBuffer->RenderToNetwork ( subproc, fTxHeader.fMidiDataSize );
                fTxHeader.fPacketSize += sizeof ( packet_header_t );
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
                //and send
                if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
                    return SOCKET_ERROR;
273
274
            }
        }
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296

        //audio
        if ( fParams.fSendAudioChannels )
        {
            fTxHeader.fDataType = 'a';
            for ( subproc = 0; subproc < fNSubProcess; subproc++ )
            {
                //set the header
                fTxHeader.fSubCycle = subproc;
                if ( subproc == ( fNSubProcess - 1 ) )
                    fTxHeader.fIsLastPckt = 'y';
                fTxHeader.fPacketSize = fAudioTxLen;
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
                //get the data
                fNetAudioCaptureBuffer->RenderFromJackPorts ( subproc );
                //and send
                if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
                    return SOCKET_ERROR;
            }
        }

        return 0;
297
298
    }

299
    int JackNetMasterInterface::SyncRecv()
300
    {
301
302
        int rx_bytes = 0;
        int cycle_offset = 0;
303
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
304
305
306
307
308
309
310
311

        rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
        if ( ( rx_bytes == 0 ) || ( rx_bytes == SOCKET_ERROR ) )
            return rx_bytes;

        cycle_offset = fTxHeader.fCycle - rx_head->fCycle;

        switch ( fParams.fNetworkMode )
312
        {
313
            case 's' :
moret's avatar
moret committed
314
315
316
317
318
                //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)
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
                if ( cycle_offset < 2 )
                    return 0;
                else
                    rx_bytes = Recv ( rx_head->fPacketSize, 0 );
                break;
            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
                if ( cycle_offset < 1 )
                    return 0;
                else
                    rx_bytes = Recv ( rx_head->fPacketSize, 0 );
                break;
            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 );
                if ( cycle_offset )
                    jack_error ( "'%s' can't run in fast network mode, data received too late (%d cycle(s) offset)", fParams.fName, cycle_offset );
                break;
343
344
345
346
        }
        return rx_bytes;
    }

347
    int JackNetMasterInterface::DataRecv()
348
349
    {
        int rx_bytes = 0;
350
351
        uint jumpcnt = 0;
        uint midi_recvd_pckt = 0;
352
353
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );

354
        if ( fParams.fReturnMidiChannels || fParams.fReturnAudioChannels )
355
356
357
        {
            do
            {
358
                //how much data is queued on the rx buffer ?
359
360
361
                rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
                if ( rx_bytes == SOCKET_ERROR )
                    return rx_bytes;
362
363
                //if no data,
                if ( ( rx_bytes == 0 ) && ( ++jumpcnt == fNSubProcess ) )
364
                {
365
366
367
368
369
370
371
                    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
372
373
                    switch ( rx_head->fDataType )
                    {
moret's avatar
moret committed
374
                        case 'm':   //midi
375
                            Recv ( rx_head->fPacketSize, 0 );
moret's avatar
moret committed
376
                            fRxHeader.fCycle = rx_head->fCycle;
377
378
379
380
                            fNetMidiPlaybackBuffer->RenderFromNetwork ( rx_head->fSubCycle, rx_bytes - sizeof ( packet_header_t ) );
                            if ( ++midi_recvd_pckt == rx_head->fNMidiPckt )
                                fNetMidiPlaybackBuffer->RenderToJackPorts();
                            jumpcnt = 0;
moret's avatar
moret committed
381
382
                            break;
                        case 'a':   //audio
383
                            Recv ( rx_head->fPacketSize, 0 );
moret's avatar
moret committed
384
                            if ( !IsNextPacket ( &fRxHeader, rx_head, fNSubProcess ) )
385
                                jack_error ( "Packet(s) missing from '%s'...", fParams.fName );
moret's avatar
moret committed
386
387
                            fRxHeader.fCycle = rx_head->fCycle;
                            fRxHeader.fSubCycle = rx_head->fSubCycle;
388
389
                            fNetAudioPlaybackBuffer->RenderToJackPorts ( rx_head->fSubCycle );
                            jumpcnt = 0;
moret's avatar
moret committed
390
391
                            break;
                        case 's':   //sync
392
393
                            if ( rx_head->fCycle == fTxHeader.fCycle )
                                return 0;
394
395
396
                    }
                }
            }
397
            while ( rx_head->fIsLastPckt != 'y' );
398
        }
399
        return rx_bytes;
400
401
    }

402
403
404
// JackNetSlaveInterface ************************************************************************************************

    bool JackNetSlaveInterface::Init()
405
    {
406
        jack_log ( "JackNetSlaveInterface::Init()" );
407

408
409
410
411
        //set the parameters to send
        strcpy ( fParams.fPacketType, "params" );
        fParams.fProtocolVersion = 'a';
        SetPacketType ( &fParams, SLAVE_AVAILABLE );
412

413
414
415
        //init loop : get a master and start, do it until connection is ok
        net_status_t status;
        do
416
        {
417
418
419
            //first, get a master, do it until a valid connection is running
            jack_info ( "Initializing Net Slave..." );
            do
420
            {
421
422
423
                status = GetNetMaster();
                if ( status == NET_SOCKET_ERROR )
                    return false;
424
            }
425
            while ( status != NET_CONNECTED );
426

427
428
429
430
431
            //then tell the master we are ready
            jack_info ( "Initializing connection with %s...", fParams.fMasterNetName );
            status = SendMasterStartSync();
            if ( status == NET_ERROR )
                return false;
432
        }
433
        while ( status != NET_ROLLING );
434

435
436
        return true;
    }
437

438
    net_status_t JackNetSlaveInterface::GetNetMaster()
439
    {
440
441
        jack_log ( "JackNetSlaveInterface::GetNetMaster()" );
        //utility
442
443
        session_params_t params;
        int rx_bytes = 0;
444
        unsigned char loop = 0;
445
446
447
448

        //socket
        if ( fSocket.NewSocket() == SOCKET_ERROR )
        {
449
450
            jack_error ( "Fatal error : network unreachable - %s", StrError ( NET_ERROR_CODE ) );
            return NET_SOCKET_ERROR;
451
452
        }

453
454
455
456
457
458
        //bind the socket
        if ( fSocket.Bind() == SOCKET_ERROR )
            jack_error ( "Can't bind the socket : %s", StrError ( NET_ERROR_CODE ) );

        //timeout on receive
        if ( fSocket.SetTimeOut ( 2000000 ) == SOCKET_ERROR )
459
460
            jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );

461
462
463
        //disable local loop
        if ( fSocket.SetOption ( IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof ( loop ) ) == SOCKET_ERROR )
            jack_error ( "Can't disable multicast loop : %s", StrError ( NET_ERROR_CODE ) );
464

465
466
        //send 'AVAILABLE' until 'SLAVE_SETUP' received
        jack_info ( "Waiting for a master..." );
467
468
        do
        {
469
470
471
472
473
474
            //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 ) )
475
            {
476
477
                jack_error ( "Can't receive : %s", StrError ( NET_ERROR_CODE ) );
                return NET_RECV_ERROR;
478
479
            }
        }
480
        while ( strcmp ( params.fPacketType, fParams.fPacketType ) && ( GetPacketType ( &params ) != SLAVE_SETUP ) );
481

482
483
        //connect the socket
        if ( fSocket.Connect() == SOCKET_ERROR )
484
        {
485
486
            jack_error ( "Error in connect : %s", StrError ( NET_ERROR_CODE ) );
            return NET_CONNECT_ERROR;
487
488
        }

489
490
491
492
493
494
495
496
497
498
499
500
        //everything is OK, copy parameters and return
        fParams = params;

        return NET_CONNECTED;
    }

    net_status_t JackNetSlaveInterface::SendMasterStartSync()
    {
        jack_log ( "JackNetSlaveInterface::GetNetMasterStartSync()" );
        //tell the master to start
        SetPacketType ( &fParams, START_MASTER );
        if ( fSocket.Send ( &fParams, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
501
        {
502
503
            jack_error ( "Error in send : %s", StrError ( NET_ERROR_CODE ) );
            return ( fSocket.GetError() == NET_CONN_ERROR ) ? NET_ERROR : NET_SEND_ERROR;
504
        }
505
        return NET_ROLLING;
506
507
    }

508
    void JackNetSlaveInterface::SetParams()
moret's avatar
moret committed
509
    {
510
        jack_log ( "JackNetSlaveInterface::SetParams" );
moret's avatar
moret committed
511
512
513

        JackNetInterface::SetParams();

514
515
        fTxHeader.fDataStream = 'r';
        fRxHeader.fDataStream = 's';
moret's avatar
moret committed
516
517

        //midi net buffers
518
519
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fRxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fTxData );
moret's avatar
moret committed
520
521

        //audio net buffers
522
523
        fNetAudioCaptureBuffer = new NetAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
        fNetAudioPlaybackBuffer = new NetAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
moret's avatar
moret committed
524
525
526
527
528
529

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

530
    int JackNetSlaveInterface::Recv ( size_t size, int flags )
531
    {
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
        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." );
                throw JackDriverException();
            }
            else
                jack_error ( "Fatal error in receive : %s", StrError ( NET_ERROR_CODE ) );
        }
        return rx_bytes;
550
551
    }

552
    int JackNetSlaveInterface::Send ( size_t size, int flags )
553
    {
554
555
556
        int tx_bytes = fSocket.Send ( fTxBuffer, size, flags );
        //handle errors
        if ( tx_bytes == SOCKET_ERROR )
557
558
        {
            net_error_t error = fSocket.GetError();
559
560
            //if a network error occurs, this exception will restart the driver
            if ( error == NET_CONN_ERROR )
561
            {
562
563
                jack_error ( "Connection lost." );
                throw JackDriverException();
564
            }
565
566
            else
                jack_error ( "Fatal error in send : %s", StrError ( NET_ERROR_CODE ) );
567
568
569
570
        }
        return tx_bytes;
    }

571
    int JackNetSlaveInterface::SyncRecv()
572
    {
573
574
575
576
        int rx_bytes = 0;
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
        //receive sync (launch the cycle)
        do
577
        {
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
            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' ) );
        return rx_bytes;
    }

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

        //audio, midi or sync if driver is late
        if ( fParams.fSendMidiChannels || fParams.fSendAudioChannels )
        {
            do
597
            {
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
                rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
                //error here, problem with recv, just skip the cycle (return -1)
                if ( rx_bytes == SOCKET_ERROR )
                    return rx_bytes;
                if ( rx_bytes && ( rx_head->fDataStream == 's' ) && ( rx_head->fID == fParams.fID ) )
                {
                    switch ( rx_head->fDataType )
                    {
                        case 'm':   //midi
                            rx_bytes = Recv ( rx_head->fPacketSize, 0 );
                            fRxHeader.fCycle = rx_head->fCycle;
                            fNetMidiCaptureBuffer->RenderFromNetwork ( rx_head->fSubCycle, rx_bytes - sizeof ( packet_header_t ) );
                            if ( ++recvd_midi_pckt == rx_head->fNMidiPckt )
                                fNetMidiCaptureBuffer->RenderToJackPorts();
                            break;
                        case 'a':   //audio
                            rx_bytes = Recv ( rx_head->fPacketSize, 0 );
                            if ( !IsNextPacket ( &fRxHeader, rx_head, fNSubProcess ) )
                                jack_error ( "Packet(s) missing..." );
                            fRxHeader.fCycle = rx_head->fCycle;
                            fRxHeader.fSubCycle = rx_head->fSubCycle;
                            fNetAudioCaptureBuffer->RenderToJackPorts ( rx_head->fSubCycle );
                            break;
                        case 's':   //sync
                            jack_info ( "NetSlave : overloaded, skipping receive." );
                            return 0;
                    }
                }
626
            }
627
            while ( rx_head->fIsLastPckt != 'y' );
628
        }
629
630
        fRxHeader.fCycle = rx_head->fCycle;
        return 0;
631
632
    }

633
    int JackNetSlaveInterface::SyncSend()
634
    {
635
636
637
638
639
        //tx header
        if ( fParams.fSlaveSyncMode )
            fTxHeader.fCycle = fRxHeader.fCycle;
        else
            fTxHeader.fCycle++;
640
641
        fTxHeader.fSubCycle = 0;
        fTxHeader.fDataType = 's';
642
        fTxHeader.fIsLastPckt = ( !fParams.fReturnMidiChannels && !fParams.fReturnAudioChannels ) ?  'y' : 'n';
643
644
645
646
647
        fTxHeader.fPacketSize = fParams.fMtu;
        memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
        return Send ( fTxHeader.fPacketSize, 0 );
    }

648
    int JackNetSlaveInterface::DataSend()
649
650
    {
        uint subproc;
651

652
        //midi
653
        if ( fParams.fReturnMidiChannels )
654
655
        {
            fTxHeader.fDataType = 'm';
656
            fTxHeader.fMidiDataSize = fNetMidiPlaybackBuffer->RenderFromJackPorts();
657
658
659
660
            fTxHeader.fNMidiPckt = GetNMidiPckt ( &fParams, fTxHeader.fMidiDataSize );
            for ( subproc = 0; subproc < fTxHeader.fNMidiPckt; subproc++ )
            {
                fTxHeader.fSubCycle = subproc;
661
                if ( ( subproc == ( fTxHeader.fNMidiPckt - 1 ) ) && !fParams.fReturnAudioChannels )
662
                    fTxHeader.fIsLastPckt = 'y';
663
                fTxHeader.fPacketSize = fNetMidiPlaybackBuffer->RenderToNetwork ( subproc, fTxHeader.fMidiDataSize );
664
665
666
                fTxHeader.fPacketSize += sizeof ( packet_header_t );
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
                if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
moret's avatar
moret committed
667
                    return SOCKET_ERROR;
668
669
670
671
            }
        }

        //audio
672
        if ( fParams.fReturnAudioChannels )
673
674
675
676
677
678
679
680
681
        {
            fTxHeader.fDataType = 'a';
            for ( subproc = 0; subproc < fNSubProcess; subproc++ )
            {
                fTxHeader.fSubCycle = subproc;
                if ( subproc == ( fNSubProcess - 1 ) )
                    fTxHeader.fIsLastPckt = 'y';
                fTxHeader.fPacketSize = fAudioTxLen;
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
682
                fNetAudioPlaybackBuffer->RenderFromJackPorts ( subproc );
683
                if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
moret's avatar
moret committed
684
                    return SOCKET_ERROR;
685
686
687
688
689
            }
        }
        return 0;
    }
}
690