JackNetManager.cpp 30.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
/*
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 "JackNetManager.h"

#define DEFAULT_MULTICAST_IP "225.3.19.154"
#define DEFAULT_PORT 19000

using namespace std;

namespace Jack
{
//JackNetMaster******************************************************************************************************
moret's avatar
moret committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#ifdef NETMONITOR
    std::string JackNetMaster::fMonitorPlotOptions[] =
    {
        std::string ( "set xlabel \"audio cycles\"" ),
        std::string ( "set ylabel \"audio frames\"" )
    };
    std::string JackNetMaster::fMonitorFieldNames[] =
    {
        std::string ( "cycle start" ),
        std::string ( "sync send" ),
        std::string ( "send end" ),
        std::string ( "sync recv" ),
        std::string ( "end of cycle" )
    };
#endif
45
46
47
48
49
50
51
52
53
54
55
56
57

    JackNetMaster::JackNetMaster ( JackNetMasterManager* manager, session_params_t& params ) : fSocket()
    {
        jack_log ( "JackNetMaster::JackNetMaster" );
        //settings
        fMasterManager = manager;
        fParams = params;
        fSocket.CopyParams ( &fMasterManager->fSocket );
        fNSubProcess = fParams.fPeriodSize / fParams.fFramesPerPacket;
        fClientName = const_cast<char*> ( fParams.fName );
        fNetJumpCnt = 0;
        fJackClient = NULL;
        fRunning = false;
58
        fSyncState = 1;
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
        uint port_index;

        //jack audio ports
        fAudioCapturePorts = new jack_port_t* [fParams.fSendAudioChannels];
        for ( port_index = 0; port_index < fParams.fSendAudioChannels; port_index++ )
            fAudioCapturePorts[port_index] = NULL;
        fAudioPlaybackPorts = new jack_port_t* [fParams.fReturnAudioChannels];
        for ( port_index = 0; port_index < fParams.fReturnAudioChannels; port_index++ )
            fAudioPlaybackPorts[port_index] = NULL;
        //jack midi ports
        fMidiCapturePorts = new jack_port_t* [fParams.fSendMidiChannels];
        for ( port_index = 0; port_index < fParams.fSendMidiChannels; port_index++ )
            fMidiCapturePorts[port_index] = NULL;
        fMidiPlaybackPorts = new jack_port_t* [fParams.fReturnMidiChannels];
        for ( port_index = 0; port_index < fParams.fReturnMidiChannels; port_index++ )
            fMidiPlaybackPorts[port_index] = NULL;

        //TX header init
        strcpy ( fTxHeader.fPacketType, "header" );
        fTxHeader.fDataStream = 's';
        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.fDataStream = 'r';
        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 buffers
        fTxData = fTxBuffer + sizeof ( packet_header_t );
        fRxData = fRxBuffer + sizeof ( packet_header_t );

        //midi net buffers
        fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fTxData );
        fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fRxData );

        //audio net buffers
        fNetAudioCaptureBuffer = new NetAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
        fNetAudioPlaybackBuffer = new NetAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );

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

        //payload size
        fPayloadSize = fParams.fMtu - sizeof ( packet_header_t );
moret's avatar
moret committed
116
117
118
119
120
121

        //monitor
#ifdef NETMONITOR
        std::string plot_file_name = std::string ( fParams.fName );
        fMonitor.SetPlotFile ( plot_file_name, fMonitorPlotOptions, 2, fMonitorFieldNames, 5 );
#endif
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
    }

    JackNetMaster::~JackNetMaster()
    {
        jack_log ( "JackNetMaster::~JackNetMaster, ID %u.", fParams.fID );
        if ( fJackClient )
        {
            jack_deactivate ( fJackClient );
            FreePorts();
            jack_client_close ( fJackClient );
        }
        fSocket.Close();
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
        delete[] fAudioCapturePorts;
        delete[] fAudioPlaybackPorts;
        delete[] fMidiCapturePorts;
        delete[] fMidiPlaybackPorts;
        delete[] fTxBuffer;
        delete[] fRxBuffer;
moret's avatar
moret committed
144
145
146
147
#ifdef NETMONITOR
		std::string filename = string ( fParams.fName );
        fMonitor.Save ( filename );
#endif
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
    }

    bool JackNetMaster::Init()
    {
        jack_log ( "JackNetMaster::Init, ID %u.", fParams.fID );
        session_params_t params;
        int msec_timeout = 1000;
        uint attempt = 0;
        int rx_bytes = 0;

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

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

        //connect
        if ( fSocket.Connect() == SOCKET_ERROR )
        {
            jack_error ( "Can't connect : %s", StrError ( NET_ERROR_CODE ) );
            return false;
        }

        //send 'SLAVE_SETUP' until 'START_MASTER' received
        jack_info ( "Sending parameters to %s ...", fParams.fSlaveNetName );
        do
        {
            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 ) )
            {
                jack_error ( "Problem with network." );
                return false;
            }
        }
        while ( ( GetPacketType ( &params ) != START_MASTER ) && ( ++attempt < 5 ) );
        if ( attempt == 5 )
        {
            jack_error ( "Slave doesn't respond, exiting." );
            return false;
        }

        //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;
        }

        //jack client and process
        jack_status_t status;
        jack_options_t options = JackNullOption;
        if ( ( fJackClient = jack_client_open ( fClientName, options, &status, NULL ) ) == NULL )
        {
            jack_error ( "Can't open a new jack client." );
            return false;
        }

        jack_set_process_callback ( fJackClient, SetProcess, this );

        //port registering
        uint i;
        char name[24];
217
218
        jack_nframes_t port_latency = jack_get_buffer_size ( fJackClient );
        unsigned long port_flags;
219
        //audio
220
        port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
221
222
223
        for ( i = 0; i < fParams.fSendAudioChannels; i++ )
        {
            sprintf ( name, "to_slave_%d", i+1 );
224
            if ( ( fAudioCapturePorts[i] = jack_port_register ( fJackClient, name, JACK_DEFAULT_AUDIO_TYPE, port_flags, 0 ) ) == NULL )
225
                goto fail;
226
            jack_port_set_latency ( fAudioCapturePorts[i], port_latency );
227
        }
228
        port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
229
230
231
        for ( i = 0; i < fParams.fReturnAudioChannels; i++ )
        {
            sprintf ( name, "from_slave_%d", i+1 );
232
            if ( ( fAudioPlaybackPorts[i] = jack_port_register ( fJackClient, name, JACK_DEFAULT_AUDIO_TYPE, port_flags, 0 ) ) == NULL )
233
                goto fail;
234
            jack_port_set_latency ( fAudioPlaybackPorts[i], port_latency );
235
236
        }
        //midi
237
        port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
238
239
240
        for ( i = 0; i < fParams.fSendMidiChannels; i++ )
        {
            sprintf ( name, "midi_to_slave_%d", i+1 );
241
            if ( ( fMidiCapturePorts[i] = jack_port_register ( fJackClient, name, JACK_DEFAULT_MIDI_TYPE, port_flags, 0 ) ) == NULL )
242
                goto fail;
243
            jack_port_set_latency ( fMidiCapturePorts[i], port_latency );
244
        }
245
        port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
246
247
248
        for ( i = 0; i < fParams.fReturnMidiChannels; i++ )
        {
            sprintf ( name, "midi_from_slave_%d", i+1 );
249
            if ( ( fMidiPlaybackPorts[i] = jack_port_register ( fJackClient, name, JACK_DEFAULT_MIDI_TYPE, port_flags, 0 ) ) == NULL )
250
                goto fail;
251
            jack_port_set_latency ( fMidiPlaybackPorts[i], port_latency );
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
        }

        fRunning = true;

        //finally activate jack client
        if ( jack_activate ( fJackClient ) != 0 )
        {
            jack_error ( "Can't activate jack client." );
            goto fail;
        }

        jack_info ( "NetJack new master started." );

        return true;

fail:
        FreePorts();
        jack_client_close ( fJackClient );
        fJackClient = NULL;
        return false;
    }

    void JackNetMaster::FreePorts()
    {
        jack_log ( "JackNetMaster::FreePorts, ID %u", fParams.fID );
        uint port_index;
        for ( port_index = 0; port_index < fParams.fSendAudioChannels; port_index++ )
            if ( fAudioCapturePorts[port_index] )
                jack_port_unregister ( fJackClient, fAudioCapturePorts[port_index] );
        for ( port_index = 0; port_index < fParams.fReturnAudioChannels; port_index++ )
            if ( fAudioPlaybackPorts[port_index] )
                jack_port_unregister ( fJackClient, fAudioPlaybackPorts[port_index] );
        for ( port_index = 0; port_index < fParams.fSendMidiChannels; port_index++ )
            if ( fMidiCapturePorts[port_index] )
                jack_port_unregister ( fJackClient, fMidiCapturePorts[port_index] );
        for ( port_index = 0; port_index < fParams.fReturnMidiChannels; port_index++ )
            if ( fMidiPlaybackPorts[port_index] )
                jack_port_unregister ( fJackClient, fMidiPlaybackPorts[port_index] );
    }

    void JackNetMaster::Exit()
    {
        jack_log ( "JackNetMaster::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 ( fMasterManager->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, fMasterManager->fMulticastIP ) == SOCKET_ERROR )
            jack_error ( "Can't send suicide request : %s", StrError ( NET_ERROR_CODE ) );
        mcast_socket.Close();
    }

308
309
310
311
312
313
314
315
316
317
318
319
    int JackNetMaster::SetSyncPacket()
    {
        if ( fParams.fTransportSync )
        {
            //set the TransportData

            //copy to TxBuffer
            memcpy ( fTxData, &fTransportData, sizeof ( net_transport_data_t ) );
        }
        return 0;
    }

320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
    int JackNetMaster::Send ( char* buffer, size_t size, int flags )
    {
        int tx_bytes;
        if ( ( tx_bytes = fSocket.Send ( buffer, size, flags ) ) == SOCKET_ERROR )
        {
            net_error_t error = fSocket.GetError();
            if ( error == NET_CONN_ERROR )
            {
                //fatal connection issue, exit
                jack_error ( "'%s' : %s, please check network connection with '%s'.",
                             fParams.fName, StrError ( NET_ERROR_CODE ), fParams.fSlaveNetName );
                Exit();
                return 0;
            }
            else
                jack_error ( "Error in send : %s", StrError ( NET_ERROR_CODE ) );
        }
        return tx_bytes;
    }

    int JackNetMaster::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();
            if ( error == NET_NO_DATA )
            {
                //too much receive failure, react...
349
                if ( ++fNetJumpCnt == 50 )
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
                {
                    jack_error ( "Connection lost, is %s still running ?", fParams.fName );
                    fNetJumpCnt = 0;
                }
                return 0;
            }
            else if ( error == NET_CONN_ERROR )
            {
                //fatal connection issue, exit
                jack_error ( "'%s' : %s, please check network connection with '%s'.",
                             fParams.fName, StrError ( NET_ERROR_CODE ), fParams.fSlaveNetName );
                Exit();
                return 0;
            }
            else
                jack_error ( "Error in receive : %s", StrError ( NET_ERROR_CODE ) );
        }
        return rx_bytes;
    }

    int JackNetMaster::SetProcess ( jack_nframes_t nframes, void* arg )
    {
        JackNetMaster* master = static_cast<JackNetMaster*> ( arg );
        return master->Process();
    }

    int JackNetMaster::Process()
    {
        if ( !fRunning )
            return 0;

        int tx_bytes, rx_bytes, copy_size;
        size_t midi_recvd_pckt = 0;
        fTxHeader.fCycle++;
        fTxHeader.fSubCycle = 0;
        fTxHeader.fIsLastPckt = 'n';
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );

moret's avatar
moret committed
388
389
390
391
392
#ifdef NETMONITOR
        NetMeasure<jack_nframes_t> measure;
        measure.fTable[0] = jack_frames_since_cycle_start( fJackClient );
#endif

393
394
395
        //buffers
        uint port_index;
        for ( port_index = 0; port_index < fParams.fSendMidiChannels; port_index++ )
sletz's avatar
Cleanup    
sletz committed
396
            fNetMidiCaptureBuffer->SetBuffer(port_index,
moret's avatar
moret committed
397
398
											static_cast<JackMidiBuffer*> ( jack_port_get_buffer ( fMidiCapturePorts[port_index],
                                            fParams.fPeriodSize )));
399
        for ( port_index = 0; port_index < fParams.fSendAudioChannels; port_index++ )
sletz's avatar
Cleanup    
sletz committed
400
            fNetAudioCaptureBuffer->SetBuffer(port_index,
moret's avatar
moret committed
401
402
                                             static_cast<sample_t*> ( jack_port_get_buffer ( fAudioCapturePorts[port_index],
                                             fParams.fPeriodSize )));
403
        for ( port_index = 0; port_index < fParams.fReturnMidiChannels; port_index++ )
sletz's avatar
Cleanup    
sletz committed
404
            fNetMidiPlaybackBuffer->SetBuffer(port_index,
moret's avatar
moret committed
405
406
                                             static_cast<JackMidiBuffer*> ( jack_port_get_buffer ( fMidiPlaybackPorts[port_index],
                                             fParams.fPeriodSize )));
407
        for ( port_index = 0; port_index < fParams.fReturnAudioChannels; port_index++ )
sletz's avatar
Cleanup    
sletz committed
408
            fNetAudioPlaybackBuffer->SetBuffer(port_index,
moret's avatar
moret committed
409
410
                                              static_cast<sample_t*> ( jack_port_get_buffer ( fAudioPlaybackPorts[port_index],
                                              fParams.fPeriodSize )));
411
412
413
414
415
416

        //send ------------------------------------------------------------------------------------------------------------------
        //sync
        fTxHeader.fDataType = 's';
        if ( !fParams.fSendMidiChannels && !fParams.fSendAudioChannels )
            fTxHeader.fIsLastPckt = 'y';
417
418
419
        memset ( fTxData, 0, fPayloadSize );
        SetSyncPacket();
        tx_bytes = Send ( fTxBuffer, fParams.fMtu, 0 );
420
421
422
        if ( ( tx_bytes == 0 ) || ( tx_bytes == SOCKET_ERROR ) )
            return tx_bytes;

moret's avatar
moret committed
423
424
425
426
#ifdef NETMONITOR
        measure.fTable[1] = jack_frames_since_cycle_start( fJackClient );
#endif

427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
        //midi
        if ( fParams.fSendMidiChannels )
        {
            fTxHeader.fDataType = 'm';
            fTxHeader.fMidiDataSize = fNetMidiCaptureBuffer->RenderFromJackPorts();
            fTxHeader.fNMidiPckt = GetNMidiPckt ( &fParams, fTxHeader.fMidiDataSize );
            for ( uint subproc = 0; subproc < fTxHeader.fNMidiPckt; subproc++ )
            {
                fTxHeader.fSubCycle = subproc;
                if ( ( subproc == ( fTxHeader.fNMidiPckt - 1 ) ) && !fParams.fSendAudioChannels )
                    fTxHeader.fIsLastPckt = 'y';
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
                copy_size = fNetMidiCaptureBuffer->RenderToNetwork ( subproc, fTxHeader.fMidiDataSize );
                tx_bytes = Send ( fTxBuffer, sizeof ( packet_header_t ) + copy_size, 0 );
                if ( tx_bytes < 1 )
                    return tx_bytes;
            }
        }

        //audio
        if ( fParams.fSendAudioChannels )
        {
            fTxHeader.fDataType = 'a';
            for ( uint subproc = 0; subproc < fNSubProcess; subproc++ )
            {
                fTxHeader.fSubCycle = subproc;
                if ( subproc == ( fNSubProcess - 1 ) )
                    fTxHeader.fIsLastPckt = 'y';
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
                fNetAudioCaptureBuffer->RenderFromJackPorts ( subproc );
                tx_bytes = Send ( fTxBuffer, fAudioTxLen, 0 );
                if ( tx_bytes < 1 )
                    return tx_bytes;
            }
        }

moret's avatar
moret committed
463
464
465
466
467
#ifdef NETMONITOR
        measure.fTable[2] = jack_frames_since_cycle_start( fJackClient );
#endif

        //receive --------------------------------------------------------------------------------------------------------------------
468
        //sync
moret's avatar
moret committed
469
        do
470
        {
moret's avatar
moret committed
471
472
473
            rx_bytes = Recv ( fParams.fMtu, 0 );
            if ( ( rx_bytes == 0 ) || ( rx_bytes == SOCKET_ERROR ) )
                return rx_bytes;
474
        }
moret's avatar
moret committed
475
        while ( !rx_bytes && ( rx_head->fDataType != 's' ) );
476

moret's avatar
moret committed
477
478
479
#ifdef NETMONITOR
        measure.fTable[3] = jack_frames_since_cycle_start( fJackClient );
#endif
480

481
482
483
484
        if ( fParams.fReturnMidiChannels || fParams.fReturnAudioChannels )
        {
            do
            {
485
                if ( ( rx_bytes = Recv ( fParams.fMtu, MSG_PEEK ) ) == SOCKET_ERROR )
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
                    return rx_bytes;
                if ( rx_bytes && ( rx_head->fDataStream == 'r' ) && ( rx_head->fID == fParams.fID ) )
                {
                    switch ( rx_head->fDataType )
                    {
                    case 'm':	//midi
                        rx_bytes = Recv ( rx_bytes, 0 );
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
                        fNetMidiPlaybackBuffer->RenderFromNetwork ( rx_head->fSubCycle, rx_bytes - sizeof ( packet_header_t ) );
                        if ( ++midi_recvd_pckt == rx_head->fNMidiPckt )
                            fNetMidiPlaybackBuffer->RenderToJackPorts();
                        fNetJumpCnt = 0;
                        break;
                    case 'a':	//audio
                        rx_bytes = Recv ( fAudioRxLen, 0 );
                        if ( !IsNextPacket ( &fRxHeader, rx_head, fNSubProcess ) )
                            jack_error ( "Packet(s) missing from '%s'...", fParams.fName );
                        fRxHeader.fCycle = rx_head->fCycle;
                        fRxHeader.fSubCycle = rx_head->fSubCycle;
                        fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
                        fNetAudioPlaybackBuffer->RenderToJackPorts ( rx_head->fSubCycle );
                        fNetJumpCnt = 0;
                        break;
509
510
511
512
                    case 's':	//sync
                        jack_error ( "NetMaster receive sync packets instead of data." );
                        fRxHeader.fCycle = rx_head->fCycle;
                        return 0;
513
514
515
516
517
                    }
                }
            }
            while ( fRxHeader.fIsLastPckt != 'y' );
        }
moret's avatar
moret committed
518
519
520
521
522

#ifdef NETMONITOR
        measure.fTable[4] = jack_frames_since_cycle_start( fJackClient );
        fMonitor.Write ( measure );
#endif
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
        return 0;
    }

//JackNetMasterManager***********************************************************************************************

    JackNetMasterManager::JackNetMasterManager ( jack_client_t* client, const JSList* params ) : fSocket()
    {
        jack_log ( "JackNetMasterManager::JackNetMasterManager" );
        fManagerClient = client;
        fManagerName = jack_get_client_name ( fManagerClient );
        fMulticastIP = DEFAULT_MULTICAST_IP;
        fSocket.SetPort ( DEFAULT_PORT );
        fGlobalID = 0;
        fRunning = true;

        const JSList* node;
        const jack_driver_param_t* param;
        for ( node = params; node; node = jack_slist_next ( node ) )
        {
            param = ( const jack_driver_param_t* ) node->data;
            switch ( param->character )
            {
            case 'a' :
                fMulticastIP = strdup ( param->value.str );
                break;
            case 'p':
                fSocket.SetPort ( param->value.ui );
            }
        }

553
554
        //set sync callback
        jack_set_sync_callback ( fManagerClient, SetSyncCallback, this );
555

556
        //activate the client (for sync callback)
557
        if ( jack_activate ( fManagerClient ) != 0 )
558
            jack_error ( "Can't activate the network manager client, transport disabled." );
559

560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
        //launch the manager thread
        if ( jack_client_create_thread ( fManagerClient, &fManagerThread, 0, 0, NetManagerThread, this ) )
            jack_error ( "Can't create the network manager control thread." );
    }

    JackNetMasterManager::~JackNetMasterManager()
    {
        jack_log ( "JackNetMasterManager::~JackNetMasterManager" );
        Exit();
        master_list_t::iterator it;
        for ( it = fMasterList.begin(); it != fMasterList.end(); it++ )
            delete ( *it );
        fSocket.Close();
        SocketAPIEnd();
    }

576
577
    int JackNetMasterManager::SetSyncCallback ( jack_transport_state_t state, jack_position_t* pos, void* arg )
    {
578
579
580
581
582
583
584
585
586
587
588
589
590
        JackNetMasterManager* master_manager = static_cast<JackNetMasterManager*>(arg);
        return master_manager->SyncCallback ( state, pos );
    }

    int JackNetMasterManager::SyncCallback ( jack_transport_state_t state, jack_position_t* pos )
    {
        //check sync state for every master in the list
        int ret = 1;
        master_list_it_t it;
        for ( it = fMasterList.begin(); it != fMasterList.end(); it++ )
            if ( ( *it )->fSyncState == 0 )
                ret = 0;
        jack_log ( "JackNetMasterManager::SyncCallback returns '%s'", ( ret ) ? "true" : "false" );
moret's avatar
moret committed
591
        return ret;
592
593
    }

594
595
596
    void* JackNetMasterManager::NetManagerThread ( void* arg )
    {
        JackNetMasterManager* master_manager = static_cast<JackNetMasterManager*> ( arg );
597
598
        jack_info ( "Starting Jack Network Manager." );
        jack_info ( "Listening on '%s:%d'", master_manager->fMulticastIP, master_manager->fSocket.GetPort() );
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
        master_manager->Run();
        return NULL;
    }

    void JackNetMasterManager::Run()
    {
        jack_log ( "JackNetMasterManager::Run" );
        //utility variables
        int msec_timeout = 2000;
        int attempt = 0;

        //data
        session_params_t params;
        int rx_bytes = 0;
        JackNetMaster* net_master;

        //init socket API (win32)
        if ( SocketAPIInit() < 0 )
        {
            jack_error ( "Can't init Socket API, exiting..." );
            return;
        }

        //socket
        if ( fSocket.NewSocket() == SOCKET_ERROR )
        {
            jack_error ( "Can't create the network management input socket : %s", StrError ( NET_ERROR_CODE ) );
            return;
        }

        //bind the socket to the local port
        if ( fSocket.Bind () == SOCKET_ERROR )
        {
            jack_error ( "Can't bind the network manager socket : %s", StrError ( NET_ERROR_CODE ) );
            fSocket.Close();
            return;
        }

        //join multicast group
        if ( fSocket.JoinMCastGroup ( fMulticastIP ) == SOCKET_ERROR )
            jack_error ( "Can't join multicast group : %s", StrError ( NET_ERROR_CODE ) );

        //local loop
        if ( fSocket.SetLocalLoop() == SOCKET_ERROR )
            jack_error ( "Can't set local loop : %s", StrError ( NET_ERROR_CODE ) );

        //set a timeout on the multicast receive (the thread can now be cancelled)
        if ( fSocket.SetTimeOut ( msec_timeout ) == SOCKET_ERROR )
            jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );

        jack_info ( "Waiting for a slave..." );

        //main loop, wait for data, deal with it and wait again
        do
        {
            rx_bytes = fSocket.CatchHost ( &params, sizeof ( session_params_t ), 0 );
            if ( ( rx_bytes == SOCKET_ERROR ) && ( fSocket.GetError() != NET_NO_DATA ) )
            {
                jack_error ( "Error in receive : %s", StrError ( NET_ERROR_CODE ) );
                if ( ++attempt == 10 )
                {
                    jack_error ( "Can't receive on the socket, exiting net manager." );
                    return;
                }
            }
            if ( rx_bytes == sizeof ( session_params_t ) )
            {
                switch ( GetPacketType ( &params ) )
                {
                case SLAVE_AVAILABLE:
                    if ( ( net_master = MasterInit ( params ) ) )
                        SessionParamsDisplay ( &net_master->fParams );
                    else
                        jack_error ( "Can't init new net master..." );
                    jack_info ( "Waiting for a slave..." );
                    break;
                case KILL_MASTER:
                    KillMaster ( &params );
                    jack_info ( "Waiting for a slave..." );
                    break;
                default:
                    break;
                }
            }
        }
        while ( fRunning );
    }

    void JackNetMasterManager::Exit()
    {
        jack_log ( "JackNetMasterManager::Exit" );
        fRunning = false;
        jack_client_stop_thread ( fManagerClient, fManagerThread );
        jack_info ( "Exiting net manager..." );
    }

    JackNetMaster* JackNetMasterManager::MasterInit ( session_params_t& params )
    {
        jack_log ( "JackNetMasterManager::MasterInit, Slave : %s", params.fName );
        //settings
        fSocket.GetName ( params.fMasterNetName );
        params.fID = ++fGlobalID;
        params.fSampleRate = jack_get_sample_rate ( fManagerClient );
        params.fPeriodSize = jack_get_buffer_size ( fManagerClient );
        params.fBitdepth = 0;
        SetFramesPerPacket ( &params );
        SetSlaveName ( params );

        //create a new master and add it to the list
        JackNetMaster* master = new JackNetMaster ( this, params );
        if ( master->Init() )
        {
            fMasterList.push_back ( master );
            return master;
        }
        delete master;
        return NULL;
    }

    void JackNetMasterManager::SetSlaveName ( session_params_t& params )
    {
        jack_log ( "JackNetMasterManager::SetSlaveName" );
        master_list_it_t it;
        for ( it = fMasterList.begin(); it != fMasterList.end(); it++ )
            if ( strcmp ( ( *it )->fParams.fName, params.fName ) == 0 )
                sprintf ( params.fName, "%s-%u", params.fName, params.fID );
    }

    master_list_it_t JackNetMasterManager::FindMaster ( uint32_t id )
    {
        jack_log ( "JackNetMasterManager::FindMaster, ID %u.", id );
        master_list_it_t it;
        for ( it = fMasterList.begin(); it != fMasterList.end(); it++ )
            if ( ( *it )->fParams.fID == id )
                return it;
        return it;
    }

    void JackNetMasterManager::KillMaster ( session_params_t* params )
    {
        jack_log ( "JackNetMasterManager::KillMaster, ID %u.", params->fID );
        master_list_it_t master = FindMaster ( params->fID );
        if ( master != fMasterList.end() )
        {
            fMasterList.erase ( master );
            delete *master;
        }
    }
}//namespace

static Jack::JackNetMasterManager* master_manager = NULL;

#ifdef __cplusplus
extern "C"
{
#endif

    EXPORT jack_driver_desc_t* jack_get_descriptor()
    {
        jack_driver_desc_t *desc;
        desc = (jack_driver_desc_t*)calloc(1, sizeof(jack_driver_desc_t));

        strcpy(desc->name, "netmanager");
        desc->nparams = 2;
        desc->params = (jack_driver_param_desc_t*)calloc(desc->nparams, sizeof(jack_driver_param_desc_t));

        int i = 0;
        strcpy ( desc->params[i].name, "multicast_ip" );
        desc->params[i].character = 'a';
        desc->params[i].type = JackDriverParamString;
        strcpy ( desc->params[i].value.str, DEFAULT_MULTICAST_IP );
        strcpy ( desc->params[i].short_desc, "Multicast Address" );
        strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );

        i++;
        strcpy ( desc->params[i].name, "udp_net_port" );
        desc->params[i].character = 'p';
        desc->params[i].type = JackDriverParamInt;
        desc->params[i].value.i = DEFAULT_PORT;
        strcpy ( desc->params[i].short_desc, "UDP port" );
        strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );

        return desc;
    }

    EXPORT int jack_internal_initialize ( jack_client_t* jack_client, const JSList* params )
    {
        if ( master_manager )
        {
            jack_error ( "Master Manager already loaded" );
            return 1;
        }
        else
        {
            jack_log ( "Loading Master Manager" );
            master_manager = new Jack::JackNetMasterManager ( jack_client, params );
            return ( master_manager ) ? 0 : 1;
        }
    }

    EXPORT int jack_initialize ( jack_client_t* jack_client, const char* load_init )
    {
        JSList* params = NULL;
        jack_driver_desc_t* desc = jack_get_descriptor();
        Jack::JackArgParser parser ( load_init );

        if ( parser.GetArgc() > 0)
        {
807
808
            if ( parser.ParseParams ( desc, &params) < 0 )
                jack_error ( "Internal client JackArgParser::ParseParams error." );
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
        }

        return jack_internal_initialize(jack_client, params);
    }

    EXPORT void jack_finish ( void* arg )
    {
        if ( master_manager )
        {
            jack_log ( "Unloading Master Manager" );
            delete master_manager;
            master_manager = NULL;
        }
    }
#ifdef __cplusplus
}
#endif