JackNetManager.cpp 32.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
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.

*/

moret's avatar
moret committed
20
21
22
23
#if defined(HAVE_CONFIG_H)
#include "config.h"
#endif

24
25
26
27
28
29
30
31
32
33
#include "JackNetManager.h"

#define DEFAULT_MULTICAST_IP "225.3.19.154"
#define DEFAULT_PORT 19000

using namespace std;

namespace Jack
{
//JackNetMaster******************************************************************************************************
34
#ifdef JACK_MONITOR
moret's avatar
moret committed
35
    uint JackNetMaster::fMeasureCnt = 128;
moret's avatar
moret committed
36
    uint JackNetMaster::fMeasurePoints = 4;
37
    string JackNetMaster::fMonitorFieldNames[] =
moret's avatar
moret committed
38
    {
39
        string ( "sync send" ),
moret's avatar
moret committed
40
        string ( "end of send" ),
41
42
        string ( "sync recv" ),
        string ( "end of cycle" )
moret's avatar
moret committed
43
    };
moret's avatar
moret committed
44
45
46
47
48
49
    uint JackNetMaster::fMonitorPlotOptionsCnt = 2;
    string JackNetMaster::fMonitorPlotOptions[] =
    {
        string ( "set xlabel \"audio cycles\"" ),
        string ( "set ylabel \"% of audio cycle\"" )
    };
moret's avatar
moret committed
50
#endif
51
52
53
54
55
56
57
58
59
60
61
62
63

    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;
64
        fSyncState = 1;
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
113
114
115
116
117
118
        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();
119
120
121

        //payload size
        fPayloadSize = fParams.fMtu - sizeof ( packet_header_t );
moret's avatar
moret committed
122
123

        //monitor
124
#ifdef JACK_MONITOR
moret's avatar
moret committed
125
        fPeriodUsecs = ( int ) ( 1000000.f * ( ( float ) fParams.fPeriodSize / ( float ) fParams.fSampleRate ) );
moret's avatar
moret committed
126
127
        string plot_name = string ( fParams.fName );
        plot_name += string ( "_master" );
moret's avatar
moret committed
128
        plot_name += string ( ( fParams.fSlaveSyncMode ) ? "_sync" : "_async" );
moret's avatar
moret committed
129
        fMonitor = new JackGnuPlotMonitor<float> ( JackNetMaster::fMeasureCnt, JackNetMaster::fMeasurePoints, plot_name );
130
131
        fMeasure = new float[JackNetMaster::fMeasurePoints];
        fMonitor->SetPlotFile ( JackNetMaster::fMonitorPlotOptions, JackNetMaster::fMonitorPlotOptionsCnt,
moret's avatar
moret committed
132
                                JackNetMaster::fMonitorFieldNames, JackNetMaster::fMeasurePoints );
moret's avatar
moret committed
133
#endif
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
    }

    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;
156
#ifdef JACK_MONITOR
157
        fMonitor->Save();
moret's avatar
moret committed
158
        delete[] fMeasure;
moret's avatar
moret committed
159
        delete fMonitor;
moret's avatar
moret committed
160
#endif
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
217
218
219
220
221
222
223
224
225
226
227
228
229
    }

    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];
230
231
        jack_nframes_t port_latency = jack_get_buffer_size ( fJackClient );
        unsigned long port_flags;
232
        //audio
233
        port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
234
235
236
        for ( i = 0; i < fParams.fSendAudioChannels; i++ )
        {
            sprintf ( name, "to_slave_%d", i+1 );
237
            if ( ( fAudioCapturePorts[i] = jack_port_register ( fJackClient, name, JACK_DEFAULT_AUDIO_TYPE, port_flags, 0 ) ) == NULL )
238
                goto fail;
moret's avatar
moret committed
239
            jack_port_set_latency ( fAudioCapturePorts[i], 0 );
240
        }
241
        port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
242
243
244
        for ( i = 0; i < fParams.fReturnAudioChannels; i++ )
        {
            sprintf ( name, "from_slave_%d", i+1 );
245
            if ( ( fAudioPlaybackPorts[i] = jack_port_register ( fJackClient, name, JACK_DEFAULT_AUDIO_TYPE, port_flags, 0 ) ) == NULL )
246
                goto fail;
moret's avatar
moret committed
247
            jack_port_set_latency ( fAudioPlaybackPorts[i], port_latency + ( fParams.fSlaveSyncMode ) ? 0 : port_latency );
248
249
        }
        //midi
250
        port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
251
252
253
        for ( i = 0; i < fParams.fSendMidiChannels; i++ )
        {
            sprintf ( name, "midi_to_slave_%d", i+1 );
254
            if ( ( fMidiCapturePorts[i] = jack_port_register ( fJackClient, name, JACK_DEFAULT_MIDI_TYPE, port_flags, 0 ) ) == NULL )
255
                goto fail;
moret's avatar
moret committed
256
            jack_port_set_latency ( fMidiCapturePorts[i], 0 );
257
        }
258
        port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
259
260
261
        for ( i = 0; i < fParams.fReturnMidiChannels; i++ )
        {
            sprintf ( name, "midi_from_slave_%d", i+1 );
262
            if ( ( fMidiPlaybackPorts[i] = jack_port_register ( fJackClient, name, JACK_DEFAULT_MIDI_TYPE, port_flags, 0 ) ) == NULL )
263
                goto fail;
moret's avatar
moret committed
264
            jack_port_set_latency ( fMidiPlaybackPorts[i], port_latency + ( fParams.fSlaveSyncMode ) ? 0 : port_latency );
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
        }

        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;

moret's avatar
moret committed
280
    fail:
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
308
309
310
311
312
313
314
315
316
317
318
319
320
        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();
    }

321
322
323
324
325
326
327
328
329
330
331
332
    int JackNetMaster::SetSyncPacket()
    {
        if ( fParams.fTransportSync )
        {
            //set the TransportData

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

333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
    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();
            }
            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 )
            {
360
                //too much receive failure, react
moret's avatar
moret committed
361
362
363
                if ( ++fNetJumpCnt < 100 )
                    return 0;
                else
364
                {
moret's avatar
moret committed
365
                    jack_error ( "No data from %s...", fParams.fName );
366
367
368
369
370
371
                    fNetJumpCnt = 0;
                }
            }
            else if ( error == NET_CONN_ERROR )
            {
                //fatal connection issue, exit
moret's avatar
moret committed
372
                jack_error ( "'%s' : %s, network connection with '%s' broken, exiting.",
373
374
                             fParams.fName, StrError ( NET_ERROR_CODE ), fParams.fSlaveNetName );   
                //ask to the manager to properly remove the master
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
                Exit();
            }
            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 );

401
#ifdef JACK_MONITOR
moret's avatar
moret committed
402
403
        jack_time_t begin_time = jack_get_time();
        fMeasureId = 0;
moret's avatar
moret committed
404
405
#endif

406
407
408
        //buffers
        uint port_index;
        for ( port_index = 0; port_index < fParams.fSendMidiChannels; port_index++ )
moret's avatar
moret committed
409
410
411
            fNetMidiCaptureBuffer->SetBuffer ( port_index,
                                               static_cast<JackMidiBuffer*> ( jack_port_get_buffer ( fMidiCapturePorts[port_index],
                                                                              fParams.fPeriodSize ) ) );
412
        for ( port_index = 0; port_index < fParams.fSendAudioChannels; port_index++ )
moret's avatar
moret committed
413
414
415
            fNetAudioCaptureBuffer->SetBuffer ( port_index,
                                                static_cast<sample_t*> ( jack_port_get_buffer ( fAudioCapturePorts[port_index],
                                                                         fParams.fPeriodSize ) ) );
416
        for ( port_index = 0; port_index < fParams.fReturnMidiChannels; port_index++ )
moret's avatar
moret committed
417
418
419
            fNetMidiPlaybackBuffer->SetBuffer ( port_index,
                                                static_cast<JackMidiBuffer*> ( jack_port_get_buffer ( fMidiPlaybackPorts[port_index],
                                                                               fParams.fPeriodSize ) ) );
420
        for ( port_index = 0; port_index < fParams.fReturnAudioChannels; port_index++ )
moret's avatar
moret committed
421
422
423
            fNetAudioPlaybackBuffer->SetBuffer ( port_index,
                                                 static_cast<sample_t*> ( jack_port_get_buffer ( fAudioPlaybackPorts[port_index],
                                                                          fParams.fPeriodSize ) ) );
424
425
426
427
428
429

        //send ------------------------------------------------------------------------------------------------------------------
        //sync
        fTxHeader.fDataType = 's';
        if ( !fParams.fSendMidiChannels && !fParams.fSendAudioChannels )
            fTxHeader.fIsLastPckt = 'y';
430
431
432
        memset ( fTxData, 0, fPayloadSize );
        SetSyncPacket();
        tx_bytes = Send ( fTxBuffer, fParams.fMtu, 0 );
moret's avatar
moret committed
433
        if ( tx_bytes == SOCKET_ERROR )
434
435
            return tx_bytes;

436
#ifdef JACK_MONITOR
moret's avatar
moret committed
437
        fMeasure[fMeasureId++] = ( ( ( float ) ( jack_get_time() - begin_time ) ) / ( float ) fPeriodUsecs ) * 100.f;
moret's avatar
moret committed
438
439
#endif

440
441
442
443
444
445
446
447
448
449
450
451
452
453
        //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 );
moret's avatar
moret committed
454
                if ( tx_bytes == SOCKET_ERROR )
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
                    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 );
moret's avatar
moret committed
471
                if ( tx_bytes == SOCKET_ERROR )
472
473
474
475
                    return tx_bytes;
            }
        }

476
#ifdef JACK_MONITOR
moret's avatar
moret committed
477
        fMeasure[fMeasureId++] = ( ( ( float ) ( jack_get_time() - begin_time ) ) / ( float ) fPeriodUsecs ) * 100.f;
moret's avatar
moret committed
478
479
480
#endif

        //receive --------------------------------------------------------------------------------------------------------------------
481
        //sync
moret's avatar
moret committed
482
        do
483
        {
moret's avatar
moret committed
484
            rx_bytes = Recv ( fParams.fMtu, 0 );
485
            if ( rx_bytes == SOCKET_ERROR )
moret's avatar
moret committed
486
                return rx_bytes;
487
        }
moret's avatar
moret committed
488
        while ( !rx_bytes && ( rx_head->fDataType != 's' ) );
489

490
#ifdef JACK_MONITOR
moret's avatar
moret committed
491
        fMeasure[fMeasureId++] = ( ( ( float ) ( jack_get_time() - begin_time ) ) / ( float ) fPeriodUsecs ) * 100.f;
moret's avatar
moret committed
492
#endif
493

494
495
496
497
        if ( fParams.fReturnMidiChannels || fParams.fReturnAudioChannels )
        {
            do
            {
498
                if ( ( rx_bytes = Recv ( fParams.fMtu, MSG_PEEK ) ) == SOCKET_ERROR )
499
500
501
502
503
                    return rx_bytes;
                if ( rx_bytes && ( rx_head->fDataStream == 'r' ) && ( rx_head->fID == fParams.fID ) )
                {
                    switch ( rx_head->fDataType )
                    {
moret's avatar
moret committed
504
505
                        case 'm':   //midi
                            rx_bytes = Recv ( rx_bytes, 0 );
506
                            fRxHeader.fCycle = rx_head->fCycle;
moret's avatar
moret committed
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
                            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;
                        case 's':   //sync
524
                            rx_bytes = Recv ( rx_bytes, 0 );
moret's avatar
moret committed
525
526
                            jack_error ( "NetMaster receive sync packets instead of data." );
                            return 0;
527
528
529
530
531
                    }
                }
            }
            while ( fRxHeader.fIsLastPckt != 'y' );
        }
moret's avatar
moret committed
532

533
#ifdef JACK_MONITOR
moret's avatar
moret committed
534
        fMeasure[fMeasureId++] = ( ( ( float ) ( jack_get_time() - begin_time ) ) / ( float ) fPeriodUsecs ) * 100.f;
moret's avatar
moret committed
535
        fMonitor->Write ( fMeasure );
moret's avatar
moret committed
536
537
538
539
        if ( fParams.fSlaveSyncMode && ( fTxHeader.fCycle - fRxHeader.fCycle ) )
            jack_log ( "Monitor::SyncModeCycleOffset %d", fTxHeader.fCycle - fRxHeader.fCycle );
        else if ( !fParams.fSlaveSyncMode && ( ( fTxHeader.fCycle - fRxHeader.fCycle ) != 1 ) )
            jack_log ( "Monitor::ASyncModeCycleOffset %d", fTxHeader.fCycle - fRxHeader.fCycle );
moret's avatar
moret committed
540
#endif
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
        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 )
            {
moret's avatar
moret committed
563
564
565
566
567
                case 'a' :
                    fMulticastIP = strdup ( param->value.str );
                    break;
                case 'p':
                    fSocket.SetPort ( param->value.ui );
568
569
570
            }
        }

571
572
        //set sync callback
        jack_set_sync_callback ( fManagerClient, SetSyncCallback, this );
573

574
        //activate the client (for sync callback)
575
        if ( jack_activate ( fManagerClient ) != 0 )
576
            jack_error ( "Can't activate the network manager client, transport disabled." );
577

578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
        //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();
    }

594
595
    int JackNetMasterManager::SetSyncCallback ( jack_transport_state_t state, jack_position_t* pos, void* arg )
    {
moret's avatar
moret committed
596
        JackNetMasterManager* master_manager = static_cast<JackNetMasterManager*> ( arg );
597
598
599
600
601
602
603
604
605
606
607
608
        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
609
        return ret;
610
611
    }

612
613
614
    void* JackNetMasterManager::NetManagerThread ( void* arg )
    {
        JackNetMasterManager* master_manager = static_cast<JackNetMasterManager*> ( arg );
615
616
        jack_info ( "Starting Jack Network Manager." );
        jack_info ( "Listening on '%s:%d'", master_manager->fMulticastIP, master_manager->fSocket.GetPort() );
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
        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 ) )
                {
moret's avatar
moret committed
686
687
688
689
690
691
692
693
                    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:
694
695
                        if ( KillMaster ( &params ) )
                            jack_info ( "Waiting for a slave..." );
moret's avatar
moret committed
696
697
698
                        break;
                    default:
                        break;
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
                }
            }
        }
        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;
    }

755
    int JackNetMasterManager::KillMaster ( session_params_t* params )
756
757
758
759
760
761
762
    {
        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;
763
            return 1;
764
        }
765
        return 0;
766
767
768
769
770
771
772
773
774
775
776
777
778
    }
}//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;
moret's avatar
moret committed
779
        desc = ( jack_driver_desc_t* ) calloc ( 1, sizeof ( jack_driver_desc_t ) );
780

moret's avatar
moret committed
781
        strcpy ( desc->name, "netmanager" );
782
        desc->nparams = 2;
moret's avatar
moret committed
783
        desc->params = ( jack_driver_param_desc_t* ) calloc ( desc->nparams, sizeof ( jack_driver_param_desc_t ) );
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824

        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 );

moret's avatar
moret committed
825
        if ( parser.GetArgc() > 0 )
826
        {
moret's avatar
moret committed
827
            if ( parser.ParseParams ( desc, &params ) < 0 )
828
                jack_error ( "Internal client JackArgParser::ParseParams error." );
829
830
        }

moret's avatar
moret committed
831
        return jack_internal_initialize ( jack_client, params );
832
833
834
835
836
837
838
839
840
841
842
843
844
845
    }

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