JackNetDriver.cpp 34.1 KB
Newer Older
sletz's avatar
sletz committed
1
2
/*
Copyright (C) 2001 Paul Davis
sletz's avatar
sletz committed
3
Copyright (C) 2008 Romain Moret at Grame
sletz's avatar
sletz committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

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 "JackNetDriver.h"
#include "JackEngineControl.h"
#include "JackClientControl.h"
#include "JackGraphManager.h"
#include "JackDriverLoader.h"
#include "JackThreadedDriver.h"
27
#include "JackWaitThreadedDriver.h"
sletz's avatar
sletz committed
28
29
#include "JackException.h"

sletz's avatar
Cleanup    
sletz committed
30
#define DEFAULT_MULTICAST_IP "225.3.19.154"
sletz's avatar
sletz committed
31
32
#define DEFAULT_PORT 19000

33
34
using namespace std;

sletz's avatar
sletz committed
35
36
namespace Jack
{
37
#ifdef JACK_MONITOR
moret's avatar
moret committed
38
    uint JackNetDriver::fMeasureCnt = 128;
moret's avatar
moret committed
39
40
41
42
43
44
45
46
    uint JackNetDriver::fMeasurePoints = 4;
    string JackNetDriver::fMonitorFieldNames[] =
    {
        string ( "end of read" ),
        string ( "start of write" ),
        string ( "sync send" ),
        string ( "end of write" )
    };
moret's avatar
moret committed
47
    uint JackNetDriver::fMonitorPlotOptionsCnt = 2;
48
    string JackNetDriver::fMonitorPlotOptions[] =
moret's avatar
moret committed
49
    {
50
51
        string ( "set xlabel \"audio cycles\"" ),
        string ( "set ylabel \"% of audio cycle\"" )
moret's avatar
moret committed
52
53
54
    };
#endif

55
    JackNetDriver::JackNetDriver ( const char* name, const char* alias, JackLockedEngine* engine, JackSynchro* table,
56
                                   const char* ip, int port, int mtu, int midi_input_ports, int midi_output_ports, const char* net_name, uint transport_sync )
57
58
            : JackAudioDriver ( name, alias, engine, table ), fSocket ( ip, port )
    {
moret's avatar
moret committed
59
        jack_log ( "JackNetDriver::JackNetDriver ip %s, port %d", ip, port );
60

61
62
63
64
65
66
67
        fMulticastIP = new char[strlen ( ip ) + 1];
        strcpy ( fMulticastIP, ip );
        fParams.fMtu = mtu;
        fParams.fSendMidiChannels = midi_input_ports;
        fParams.fReturnMidiChannels = midi_output_ports;
        strcpy ( fParams.fName, net_name );
        fSocket.GetName ( fParams.fSlaveNetName );
68
        fParams.fTransportSync = transport_sync;
moret's avatar
moret committed
69
#ifdef JACK_MONITOR
moret's avatar
moret committed
70
71
        fMonitor = NULL;
        fMeasure = NULL;
moret's avatar
Cleanup    
moret committed
72
#endif
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    }

    JackNetDriver::~JackNetDriver()
    {
        fSocket.Close();
        SocketAPIEnd();
        delete fNetAudioCaptureBuffer;
        delete fNetAudioPlaybackBuffer;
        delete fNetMidiCaptureBuffer;
        delete fNetMidiPlaybackBuffer;
        delete[] fTxBuffer;
        delete[] fRxBuffer;
        delete[] fMulticastIP;
        delete[] fMidiCapturePortList;
        delete[] fMidiPlaybackPortList;
moret's avatar
moret committed
88
#ifdef JACK_MONITOR
moret's avatar
moret committed
89
90
        delete[] fMeasure;
        delete fMonitor;
moret's avatar
moret committed
91
#endif
92
    }
sletz's avatar
sletz committed
93
94
95

//*************************************initialization***********************************************************************

sletz's avatar
sletz committed
96
    int JackNetDriver::Open ( jack_nframes_t buffer_size, jack_nframes_t samplerate, bool capturing, bool playing,
97
98
99
100
                              int inchannels, int outchannels, bool monitor,
                              const char* capture_driver_name, const char* playback_driver_name,
                              jack_nframes_t capture_latency, jack_nframes_t playback_latency )
    {
sletz's avatar
sletz committed
101
        int res = JackAudioDriver::Open ( buffer_size, samplerate, capturing, playing, inchannels, outchannels, monitor,
102
103
104
105
106
107
108
                                          capture_driver_name, playback_driver_name, capture_latency, playback_latency );
        fEngineControl->fPeriod = 0;
        fEngineControl->fComputation = 500 * 1000;
        fEngineControl->fConstraint = 500 * 1000;
        return res;
    }

moret's avatar
Cleanup    
moret committed
109
110
111
#ifdef JACK_MONITOR
    int JackNetDriver::Close()
    {
moret's avatar
moret committed
112
113
        if ( fMonitor )
            fMonitor->Save();
moret's avatar
Cleanup    
moret committed
114
115
116
117
        return JackDriver::Close();
    }
#endif

118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
    int JackNetDriver::Attach()
    {
        return 0;
    }

    int JackNetDriver::Detach()
    {
        return 0;
    }

    bool JackNetDriver::Init()
    {
        jack_log ( "JackNetDriver::Init()" );

        //new loading, but existing socket, restart the driver
        if ( fSocket.IsSocket() )
            Restart();

        //set the parameters to send
        strcpy ( fParams.fPacketType, "params" );
        fParams.fProtocolVersion = 'a';
        SetPacketType ( &fParams, SLAVE_AVAILABLE );
        fParams.fSendAudioChannels = fCaptureChannels;
        fParams.fReturnAudioChannels = fPlaybackChannels;
moret's avatar
moret committed
142
        fParams.fSlaveSyncMode = fEngineControl->fSyncMode;
143

144
        //is transport sync ?
145
        if ( fParams.fTransportSync )
146
147
            jack_info ( "NetDriver started with Master's Transport Sync." );

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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
        //init loop : get a master and start, do it until connection is ok
        net_status_t status;
        do
        {
            //first, get a master, do it until a valid connection is running
            jack_info ( "Initializing Net Driver..." );
            do
            {
                status = GetNetMaster();
                if ( status == NET_SOCKET_ERROR )
                    return false;
            }
            while ( status != NET_CONNECTED );

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

        //driver parametering
        if ( SetParams() )
        {
            jack_error ( "Fatal error : can't alloc net driver ports." );
            return false;
        }

        //init done, display parameters
        SessionParamsDisplay ( &fParams );

        return true;
    }

    net_status_t JackNetDriver::GetNetMaster()
    {
        jack_log ( "JackNetDriver::GetNetMaster()" );
        //utility
        session_params_t params;
        int ms_timeout = 2000;
        int rx_bytes = 0;

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

        //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 ( ms_timeout ) == SOCKET_ERROR )
            jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );

        //send 'AVAILABLE' until 'SLAVE_SETUP' received
        jack_info ( "Waiting for a master..." );
        do
        {
            //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 receiving wrong packets
            do
            {
                rx_bytes = fSocket.CatchHost ( &params, sizeof ( session_params_t ), 0 );
                if ( ( rx_bytes == SOCKET_ERROR ) && ( fSocket.GetError() != NET_NO_DATA ) )
                {
                    jack_error ( "Can't receive : %s", StrError ( NET_ERROR_CODE ) );
                    return NET_RECV_ERROR;
                }
            }
            while ( ( rx_bytes > 0 )  && strcmp ( params.fPacketType, fParams.fPacketType ) );
        }
        while ( ( GetPacketType ( &params ) != SLAVE_SETUP ) );

        //connect the socket
        if ( fSocket.Connect() == SOCKET_ERROR )
        {
            jack_error ( "Error in connect : %s", StrError ( NET_ERROR_CODE ) );
            return NET_CONNECT_ERROR;
        }

        //everything is OK, copy parameters and return
        fParams = params;

        return NET_CONNECTED;
    }

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

    void JackNetDriver::Restart()
    {
moret's avatar
moret committed
255
        jack_log ( "JackNetDriver::Restart" );
256
257
        jack_info ( "Restarting driver..." );
        delete[] fTxBuffer;
258
        fTxBuffer = NULL;
259
        delete[] fRxBuffer;
260
        fRxBuffer = NULL;
261
        delete fNetAudioCaptureBuffer;
262
        fNetAudioCaptureBuffer = NULL;
263
        delete fNetAudioPlaybackBuffer;
264
        fNetAudioPlaybackBuffer = NULL;
265
        delete fNetMidiCaptureBuffer;
266
        fNetMidiCaptureBuffer = NULL;
267
        delete fNetMidiPlaybackBuffer;
268
        fNetMidiPlaybackBuffer = NULL;
269
270
271
        FreePorts();
        delete[] fMidiCapturePortList;
        fMidiCapturePortList = NULL;
272
        delete[] fMidiPlaybackPortList;
273
        fMidiPlaybackPortList = NULL;
moret's avatar
moret committed
274
#ifdef JACK_MONITOR
275
276
277
278
        delete[] fMeasure;
        fMeasure = NULL;
        delete fMonitor;
        fMonitor = NULL;
moret's avatar
moret committed
279
#endif
280
281
282
283
284
    }

    int JackNetDriver::SetParams()
    {
        fNSubProcess = fParams.fPeriodSize / fParams.fFramesPerPacket;
moret's avatar
moret committed
285
286
        JackAudioDriver::SetBufferSize ( fParams.fPeriodSize );
        JackAudioDriver::SetSampleRate ( fParams.fSampleRate );
287

moret's avatar
moret committed
288
289
        JackDriver::NotifyBufferSize ( fParams.fPeriodSize );
        JackDriver::NotifySampleRate ( fParams.fSampleRate );
sletz's avatar
sletz committed
290

291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
        //allocate midi ports lists
        fMidiCapturePortList = new jack_port_id_t [fParams.fSendMidiChannels];
        fMidiPlaybackPortList = new jack_port_id_t [fParams.fReturnMidiChannels];

        //register jack ports
        if ( AllocPorts() != 0 )
        {
            jack_error ( "Can't allocate ports." );
            return -1;
        }

        //TX header init
        strcpy ( fTxHeader.fPacketType, "header" );
        fTxHeader.fDataStream = 'r';
        fTxHeader.fID = fParams.fID;
moret's avatar
moret committed
306
        fTxHeader.fCycle = 1;
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
        fTxHeader.fSubCycle = 0;
        fTxHeader.fMidiDataSize = 0;
        fTxHeader.fBitdepth = fParams.fBitdepth;

        //RX header init
        strcpy ( fRxHeader.fPacketType, "header" );
        fRxHeader.fDataStream = 's';
        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 );

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

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

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

moret's avatar
moret committed
340
        //payload size
341
342
        fPayloadSize = fParams.fMtu - sizeof ( packet_header_t );

343
344
        //monitor
#ifdef JACK_MONITOR
moret's avatar
moret committed
345
346
347
348
        string plot_name = string ( fParams.fName );
        plot_name += string ( "_slave" );
        plot_name += ( fEngineControl->fSyncMode ) ? string ( "_sync" ) : string ( "_async" );
        fMonitor = new JackGnuPlotMonitor<float> ( JackNetDriver::fMeasureCnt, JackNetDriver::fMeasurePoints, plot_name );
349
350
        fMeasure = new float[JackNetDriver::fMeasurePoints];
        fMonitor->SetPlotFile ( JackNetDriver::fMonitorPlotOptions, JackNetDriver::fMonitorPlotOptionsCnt,
moret's avatar
moret committed
351
                                JackNetDriver::fMonitorFieldNames, JackNetDriver::fMeasurePoints );
352
353
#endif

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
        return 0;
    }

    int JackNetDriver::AllocPorts()
    {
        jack_log ( "JackNetDriver::AllocPorts fBufferSize = %ld fSampleRate = %ld", fEngineControl->fBufferSize, fEngineControl->fSampleRate );
        JackPort* port;
        jack_port_id_t port_id;
        char name[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
        char alias[JACK_CLIENT_NAME_SIZE + JACK_PORT_NAME_SIZE];
        unsigned long port_flags;
        int audio_port_index;
        uint midi_port_index;

        //audio
        port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
        for ( audio_port_index = 0; audio_port_index < fCaptureChannels; audio_port_index++ )
        {
            snprintf ( alias, sizeof ( alias ) - 1, "%s:%s:out%d", fAliasName, fCaptureDriverName, audio_port_index + 1 );
            snprintf ( name, sizeof ( name ) - 1, "%s:capture_%d", fClientControl.fName, audio_port_index + 1 );
            if ( ( port_id = fGraphManager->AllocatePort ( fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE,
                             static_cast<JackPortFlags> ( port_flags ), fEngineControl->fBufferSize ) ) == NO_PORT )
            {
                jack_error ( "driver: cannot register port for %s", name );
                return -1;
            }
            port = fGraphManager->GetPort ( port_id );
            port->SetAlias ( alias );
382
            port->SetLatency ( fEngineControl->fBufferSize );
383
            fCapturePortList[audio_port_index] = port_id;
384
            jack_log ( "JackNetDriver::AllocPorts() fCapturePortList[%d] audio_port_index = %ld fPortLatency = %ld", audio_port_index, port_id, port->GetLatency() );
385
386
387
388
389
390
391
392
393
394
395
396
397
398
        }
        port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
        for ( audio_port_index = 0; audio_port_index < fPlaybackChannels; audio_port_index++ )
        {
            snprintf ( alias, sizeof ( alias ) - 1, "%s:%s:in%d", fAliasName, fPlaybackDriverName, audio_port_index + 1 );
            snprintf ( name, sizeof ( name ) - 1, "%s:playback_%d",fClientControl.fName, audio_port_index + 1 );
            if ( ( port_id = fGraphManager->AllocatePort ( fClientControl.fRefNum, name, JACK_DEFAULT_AUDIO_TYPE,
                             static_cast<JackPortFlags> ( port_flags ), fEngineControl->fBufferSize ) ) == NO_PORT )
            {
                jack_error ( "driver: cannot register port for %s", name );
                return -1;
            }
            port = fGraphManager->GetPort ( port_id );
            port->SetAlias ( alias );
399
            port->SetLatency ( fEngineControl->fBufferSize + ( ( fEngineControl->fSyncMode ) ? 0 : fEngineControl->fBufferSize ) );
400
            fPlaybackPortList[audio_port_index] = port_id;
401
            jack_log ( "JackNetDriver::AllocPorts() fPlaybackPortList[%d] audio_port_index = %ld fPortLatency = %ld", audio_port_index, port_id, port->GetLatency() );
402
403
404
405
406
407
408
409
410
411
412
413
414
        }
        //midi
        port_flags = JackPortIsOutput | JackPortIsPhysical | JackPortIsTerminal;
        for ( midi_port_index = 0; midi_port_index < fParams.fSendMidiChannels; midi_port_index++ )
        {
            snprintf ( alias, sizeof ( alias ) - 1, "%s:%s:out%d", fAliasName, fCaptureDriverName, midi_port_index + 1 );
            snprintf ( name, sizeof ( name ) - 1, "%s:midi_capture_%d", fClientControl.fName, midi_port_index + 1 );
            if ( ( port_id = fGraphManager->AllocatePort ( fClientControl.fRefNum, name, JACK_DEFAULT_MIDI_TYPE,
                             static_cast<JackPortFlags> ( port_flags ), fEngineControl->fBufferSize ) ) == NO_PORT )
            {
                jack_error ( "driver: cannot register port for %s", name );
                return -1;
            }
415
416
            port = fGraphManager->GetPort ( port_id );
            port->SetLatency ( fEngineControl->fBufferSize );
417
            fMidiCapturePortList[midi_port_index] = port_id;
418
            jack_log ( "JackNetDriver::AllocPorts() fMidiCapturePortList[%d] midi_port_index = %ld fPortLatency = %ld", midi_port_index, port_id, port->GetLatency() );
419
420
421
422
423
424
425
426
427
428
429
430
431
        }

        port_flags = JackPortIsInput | JackPortIsPhysical | JackPortIsTerminal;
        for ( midi_port_index = 0; midi_port_index < fParams.fReturnMidiChannels; midi_port_index++ )
        {
            snprintf ( alias, sizeof ( alias ) - 1, "%s:%s:in%d", fAliasName, fPlaybackDriverName, midi_port_index + 1 );
            snprintf ( name, sizeof ( name ) - 1, "%s:midi_playback_%d", fClientControl.fName, midi_port_index + 1 );
            if ( ( port_id = fGraphManager->AllocatePort ( fClientControl.fRefNum, name, JACK_DEFAULT_MIDI_TYPE,
                             static_cast<JackPortFlags> ( port_flags ), fEngineControl->fBufferSize ) ) == NO_PORT )
            {
                jack_error ( "driver: cannot register port for %s", name );
                return -1;
            }
432
433
            port = fGraphManager->GetPort ( port_id );
            port->SetLatency ( fEngineControl->fBufferSize + ( ( fEngineControl->fSyncMode ) ? 0 : fEngineControl->fBufferSize ) );
434
            fMidiPlaybackPortList[midi_port_index] = port_id;
435
            jack_log ( "JackNetDriver::AllocPorts() fMidiPlaybackPortList[%d] midi_port_index = %ld fPortLatency = %ld", midi_port_index, port_id, port->GetLatency() );
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
463
464
465
466
        }

        return 0;
    }

    int JackNetDriver::FreePorts()
    {
        jack_log ( "JackNetDriver::FreePorts" );
        int audio_port_index;
        uint midi_port_index;
        for ( audio_port_index = 0; audio_port_index < fCaptureChannels; audio_port_index++ )
            fGraphManager->ReleasePort ( fClientControl.fRefNum, fCapturePortList[audio_port_index] );
        for ( audio_port_index = 0; audio_port_index < fPlaybackChannels; audio_port_index++ )
            fGraphManager->ReleasePort ( fClientControl.fRefNum, fPlaybackPortList[audio_port_index] );
        for ( midi_port_index = 0; midi_port_index < fParams.fSendMidiChannels; midi_port_index++ )
            fGraphManager->ReleasePort ( fClientControl.fRefNum, fMidiCapturePortList[midi_port_index] );
        for ( midi_port_index = 0; midi_port_index < fParams.fReturnMidiChannels; midi_port_index++ )
            fGraphManager->ReleasePort ( fClientControl.fRefNum, fMidiPlaybackPortList[midi_port_index] );
        return 0;
    }

    JackMidiBuffer* JackNetDriver::GetMidiInputBuffer ( int port_index )
    {
        return static_cast<JackMidiBuffer*> ( fGraphManager->GetBuffer ( fMidiCapturePortList[port_index], fEngineControl->fBufferSize ) );
    }

    JackMidiBuffer* JackNetDriver::GetMidiOutputBuffer ( int port_index )
    {
        return static_cast<JackMidiBuffer*> ( fGraphManager->GetBuffer ( fMidiPlaybackPortList[port_index], fEngineControl->fBufferSize ) );
    }

467
468
469
470
471
472
473
474
475
476
477
478
    int JackNetDriver::SetSyncPacket()
    {
        if ( fParams.fTransportSync )
        {
            //set the TransportData

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

moret's avatar
moret committed
479
480
//***********************************network operations*************************************************************

481
482
    int JackNetDriver::Recv ( size_t size, int flags )
    {
moret's avatar
moret committed
483
484
485
        int rx_bytes = fSocket.Recv ( fRxBuffer, size, flags );
        //handle errors
        if ( rx_bytes == SOCKET_ERROR )
486
487
        {
            net_error_t error = fSocket.GetError();
488
            //no data isn't really an error in realtime processing, so just return 0
489
            if ( error == NET_NO_DATA )
moret's avatar
moret committed
490
491
                jack_error ( "No data, is the master still running ?" );
            //if a network error occurs, this exception will restart the driver
492
            else if ( error == NET_CONN_ERROR )
moret's avatar
moret committed
493
494
495
496
            {
                jack_error ( "Connection lost." );
                throw JackDriverException();
            }
497
            else
498
                jack_error ( "Fatal error in receive : %s", StrError ( NET_ERROR_CODE ) );
499
500
501
502
503
504
        }
        return rx_bytes;
    }

    int JackNetDriver::Send ( size_t size, int flags )
    {
moret's avatar
moret committed
505
506
507
        int tx_bytes = fSocket.Send ( fTxBuffer, size, flags );
        //handle errors
        if ( tx_bytes == SOCKET_ERROR )
508
509
        {
            net_error_t error = fSocket.GetError();
moret's avatar
moret committed
510
            //if a network error occurs, this exception will restart the driver
511
            if ( error == NET_CONN_ERROR )
moret's avatar
moret committed
512
513
514
515
            {
                jack_error ( "Connection lost." );
                throw JackDriverException();
            }
516
            else
517
                jack_error ( "Fatal error in send : %s", StrError ( NET_ERROR_CODE ) );
518
519
520
        }
        return tx_bytes;
    }
sletz's avatar
sletz committed
521
522
523

//*************************************process************************************************************************

524
525
526
527
528
529
530
531
532
533
534
    int JackNetDriver::Read()
    {
        int rx_bytes;
        uint recvd_midi_pckt = 0;
        packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
        fRxHeader.fIsLastPckt = 'n';
        uint midi_port_index;
        int audio_port_index;

        //buffers
        for ( midi_port_index = 0; midi_port_index < fParams.fSendMidiChannels; midi_port_index++ )
moret's avatar
moret committed
535
            fNetMidiCaptureBuffer->SetBuffer ( midi_port_index, GetMidiInputBuffer ( midi_port_index ) );
536
        for ( audio_port_index = 0; audio_port_index < fCaptureChannels; audio_port_index++ )
moret's avatar
moret committed
537
            fNetAudioCaptureBuffer->SetBuffer ( audio_port_index, GetInputBuffer ( audio_port_index ) );
538
539
540
541

        //receive sync (launch the cycle)
        do
        {
542
            rx_bytes = Recv ( fParams.fMtu, 0 );
moret's avatar
moret committed
543
544
            //no sync received during timeout,
            //if it's a connection issue, send will detect it, so don't skip the cycle (return 0)
moret's avatar
moret committed
545
546
            if ( rx_bytes == SOCKET_ERROR )
                return 0;
547
548
549
        }
        while ( !rx_bytes && ( rx_head->fDataType != 's' ) );

550
        //take the time at the beginning of the cycle
551
552
553
554
555
556
557
        JackDriver::CycleTakeBeginTime();

        //audio, midi or sync if driver is late
        if ( fParams.fSendMidiChannels || fParams.fSendAudioChannels )
        {
            do
            {
moret's avatar
moret committed
558
                rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
moret's avatar
moret committed
559
                //error here, problem with send, just skip the cycle (return -1)
moret's avatar
moret committed
560
                if ( rx_bytes == SOCKET_ERROR )
moret's avatar
moret committed
561
                    return rx_bytes;
562
563
564
565
                if ( rx_bytes && ( rx_head->fDataStream == 's' ) && ( rx_head->fID == fParams.fID ) )
                {
                    switch ( rx_head->fDataType )
                    {
moret's avatar
moret committed
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
                        case 'm':   //midi
                            rx_bytes = Recv ( rx_bytes, 0 );
                            fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
                            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 ( fAudioRxLen, 0 );
                            if ( !IsNextPacket ( &fRxHeader, rx_head, fNSubProcess ) )
                                jack_error ( "Packet(s) missing..." );
                            fRxHeader.fCycle = rx_head->fCycle;
                            fRxHeader.fSubCycle = rx_head->fSubCycle;
                            fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
                            fNetAudioCaptureBuffer->RenderToJackPorts ( rx_head->fSubCycle );
                            break;
                        case 's':   //sync
                            jack_info ( "NetDriver : driver overloaded, skipping receive." );
                            fRxHeader.fCycle = rx_head->fCycle;
                            return 0;
586
587
588
589
590
591
                    }
                }
            }
            while ( fRxHeader.fIsLastPckt != 'y' );
        }
        fRxHeader.fCycle = rx_head->fCycle;
moret's avatar
moret committed
592

593
#ifdef JACK_MONITOR
moret's avatar
moret committed
594
        fMeasure[0] = ( ( float ) ( GetMicroSeconds() - JackDriver::fBeginDateUst ) / ( float ) fEngineControl->fPeriodUsecs ) * 100.f;
moret's avatar
moret committed
595
#endif
596
597
598
599
600
        return 0;
    }

    int JackNetDriver::Write()
    {
moret's avatar
moret committed
601
602
603
604
        uint midi_port_index;
        int tx_bytes, copy_size, audio_port_index;

        //tx header
moret's avatar
moret committed
605
606
607
608
        if ( fEngineControl->fSyncMode )
            fTxHeader.fCycle = fRxHeader.fCycle;
        else
            fTxHeader.fCycle++;
609
610
611
612
613
        fTxHeader.fSubCycle = 0;
        fTxHeader.fIsLastPckt = 'n';

        //buffers
        for ( midi_port_index = 0; midi_port_index < fParams.fReturnMidiChannels; midi_port_index++ )
moret's avatar
moret committed
614
            fNetMidiPlaybackBuffer->SetBuffer ( midi_port_index, GetMidiOutputBuffer ( midi_port_index ) );
615
        for ( audio_port_index = 0; audio_port_index < fPlaybackChannels; audio_port_index++ )
moret's avatar
moret committed
616
            fNetAudioPlaybackBuffer->SetBuffer ( audio_port_index, GetOutputBuffer ( audio_port_index ) );
617

618
#ifdef JACK_MONITOR
moret's avatar
moret committed
619
        fMeasure[1] = ( ( float ) ( GetMicroSeconds() - JackDriver::fBeginDateUst ) / ( float ) fEngineControl->fPeriodUsecs ) * 100.f;
moret's avatar
moret committed
620
621
#endif

622
623
624
625
626
627
628
        //sync
        fTxHeader.fDataType = 's';
        if ( !fParams.fSendMidiChannels && !fParams.fSendAudioChannels )
            fTxHeader.fIsLastPckt = 'y';
        memset ( fTxData, 0, fPayloadSize );
        SetSyncPacket();
        tx_bytes = Send ( fParams.fMtu, 0 );
629
        if ( tx_bytes == SOCKET_ERROR )
moret's avatar
moret committed
630
            return tx_bytes;
631

632
#ifdef JACK_MONITOR
moret's avatar
moret committed
633
        fMeasure[2] = ( ( float ) ( GetMicroSeconds() - JackDriver::fBeginDateUst ) / ( float ) fEngineControl->fPeriodUsecs ) * 100.f;
moret's avatar
moret committed
634
635
#endif

636
637
638
639
640
641
642
643
644
645
646
647
648
649
        //midi
        if ( fParams.fReturnMidiChannels )
        {
            fTxHeader.fDataType = 'm';
            fTxHeader.fMidiDataSize = fNetMidiPlaybackBuffer->RenderFromJackPorts();
            fTxHeader.fNMidiPckt = GetNMidiPckt ( &fParams, fTxHeader.fMidiDataSize );
            for ( uint subproc = 0; subproc < fTxHeader.fNMidiPckt; subproc++ )
            {
                fTxHeader.fSubCycle = subproc;
                if ( ( subproc == ( fTxHeader.fNMidiPckt - 1 ) ) && !fParams.fReturnAudioChannels )
                    fTxHeader.fIsLastPckt = 'y';
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
                copy_size = fNetMidiPlaybackBuffer->RenderToNetwork ( subproc, fTxHeader.fMidiDataSize );
                tx_bytes = Send ( sizeof ( packet_header_t ) + copy_size, 0 );
moret's avatar
moret committed
650
651
                if ( tx_bytes == SOCKET_ERROR )
                    return tx_bytes;
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
            }
        }

        //audio
        if ( fParams.fReturnAudioChannels )
        {
            fTxHeader.fDataType = 'a';
            for ( uint subproc = 0; subproc < fNSubProcess; subproc++ )
            {
                fTxHeader.fSubCycle = subproc;
                if ( subproc == ( fNSubProcess - 1 ) )
                    fTxHeader.fIsLastPckt = 'y';
                fNetAudioPlaybackBuffer->RenderFromJackPorts ( subproc );
                memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
                tx_bytes = Send ( fAudioTxLen, 0 );
moret's avatar
moret committed
667
668
                if ( tx_bytes == SOCKET_ERROR )
                    return tx_bytes;
669
670
            }
        }
moret's avatar
moret committed
671

672
#ifdef JACK_MONITOR
moret's avatar
moret committed
673
        fMeasure[3] = ( ( float ) ( GetMicroSeconds() - JackDriver::fBeginDateUst ) / ( float ) fEngineControl->fPeriodUsecs ) * 100.f;
moret's avatar
moret committed
674
        fMonitor->Write ( fMeasure );
moret's avatar
moret committed
675
676
#endif

677
678
        return 0;
    }
sletz's avatar
sletz committed
679
680
681
682

//*************************************loader*******************************************************

#ifdef __cplusplus
683
684
    extern "C"
    {
sletz's avatar
sletz committed
685
#endif
686
687
688
689
        EXPORT jack_driver_desc_t* driver_get_descriptor ()
        {
            jack_driver_desc_t* desc = ( jack_driver_desc_t* ) calloc ( 1, sizeof ( jack_driver_desc_t ) );
            strcpy ( desc->name, "net" );
690
            desc->nparams = 9;
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
            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 = 19000;
            strcpy ( desc->params[i].short_desc, "UDP port" );
            strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );

            i++;
            strcpy ( desc->params[i].name, "mtu" );
            desc->params[i].character = 'M';
            desc->params[i].type = JackDriverParamInt;
            desc->params[i].value.i = 1500;
            strcpy ( desc->params[i].short_desc, "MTU to the master" );
            strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );

            i++;
            strcpy ( desc->params[i].name, "input_ports" );
            desc->params[i].character = 'C';
            desc->params[i].type = JackDriverParamInt;
            desc->params[i].value.i = 2;
            strcpy ( desc->params[i].short_desc, "Number of audio input ports" );
            strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );

            i++;
            strcpy ( desc->params[i].name, "output_ports" );
            desc->params[i].character = 'P';
            desc->params[i].type = JackDriverParamInt;
            desc->params[i].value.i = 2;
            strcpy ( desc->params[i].short_desc, "Number of audio output ports" );
            strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );

            i++;
            strcpy ( desc->params[i].name, "midi_in_ports" );
            desc->params[i].character = 'i';
            desc->params[i].type = JackDriverParamInt;
            desc->params[i].value.i = 0;
            strcpy ( desc->params[i].short_desc, "Number of midi input ports" );
            strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );

            i++;
            strcpy ( desc->params[i].name, "midi_out_ports" );
            desc->params[i].character = 'o';
            desc->params[i].type = JackDriverParamUInt;
            desc->params[i].value.i = 0;
            strcpy ( desc->params[i].short_desc, "Number of midi output ports" );
            strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );

            i++;
            strcpy ( desc->params[i].name, "client_name" );
            desc->params[i].character = 'n';
            desc->params[i].type = JackDriverParamString;
            strcpy ( desc->params[i].value.str, "'hostname'" );
            strcpy ( desc->params[i].short_desc, "Name of the jack client" );
            strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );

757
758
759
760
761
762
763
764
            i++;
            strcpy ( desc->params[i].name, "transport_sync" );
            desc->params[i].character  = 't';
            desc->params[i].type = JackDriverParamUInt;
            desc->params[i].value.ui = 1U;
            strcpy ( desc->params[i].short_desc, "Sync transport with master's" );
            strcpy ( desc->params[i].long_desc, desc->params[i].short_desc );

765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
            return desc;
        }

        EXPORT Jack::JackDriverClientInterface* driver_initialize ( Jack::JackLockedEngine* engine, Jack::JackSynchro* table, const JSList* params )
        {
            if ( SocketAPIInit() < 0 )
            {
                jack_error ( "Can't init Socket API, exiting..." );
                return NULL;
            }
            const char* multicast_ip = DEFAULT_MULTICAST_IP;
            char name[JACK_CLIENT_NAME_SIZE];
            GetHostName ( name, JACK_CLIENT_NAME_SIZE );
            int udp_port = DEFAULT_PORT;
            int mtu = 1500;
780
            uint transport_sync = 1;
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
            jack_nframes_t period_size = 128;
            jack_nframes_t sample_rate = 48000;
            int audio_capture_ports = 2;
            int audio_playback_ports = 2;
            int midi_input_ports = 0;
            int midi_output_ports = 0;
            bool monitor = false;

            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
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
                    case 'a' :
                        multicast_ip = strdup ( param->value.str );
                        break;
                    case 'p':
                        udp_port = param->value.ui;
                        break;
                    case 'M':
                        mtu = param->value.i;
                        break;
                    case 'C':
                        audio_capture_ports = param->value.i;
                        break;
                    case 'P':
                        audio_playback_ports = param->value.i;
                        break;
                    case 'i':
                        midi_input_ports = param->value.i;
                        break;
                    case 'o':
                        midi_output_ports = param->value.i;
                        break;
                    case 'n' :
                        strncpy ( name, param->value.str, JACK_CLIENT_NAME_SIZE );
                    case 't' :
                        transport_sync = param->value.ui;
821
822
823
824
825
                }
            }

            Jack::JackDriverClientInterface* driver = new Jack::JackWaitThreadedDriver (
                new Jack::JackNetDriver ( "system", "net_pcm", engine, table, multicast_ip, udp_port, mtu,
826
                                          midi_input_ports, midi_output_ports, name, transport_sync ) );
827
828
829
830
831
832
833
            if ( driver->Open ( period_size, sample_rate, 1, 1, audio_capture_ports, audio_playback_ports,
                                monitor, "from_master_", "to_master_", 0, 0 ) == 0 )
                return driver;

            delete driver;
            return NULL;
        }
sletz's avatar
sletz committed
834
835

#ifdef __cplusplus
836
    }
sletz's avatar
sletz committed
837
838
#endif
}