Support for BIG_ENDIAN machines in NetJack2.
[jack2.git] / common / JackNetInterface.cpp
blobb2f798118829cd7bb35e0987d50ad5f7762545ec
1 /*
2 Copyright (C) 2001 Paul Davis
3 Copyright (C) 2008 Romain Moret at Grame
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 #include "JackNetInterface.h"
21 #include "JackException.h"
22 #include "JackPlatformPlug.h"
23 #include <assert.h>
25 using namespace std;
27 /*
28 TODO : since midi buffers now uses up to BUFFER_SIZE_MAX frames,
29 probably also use BUFFER_SIZE_MAX in everything related to MIDI events
30 handling (see MidiBufferInit in JackMidiPort.cpp)
33 namespace Jack
35 // JackNetInterface*******************************************
37 JackNetInterface::JackNetInterface() : fSocket()
39 fMulticastIP = NULL;
40 fTxBuffer = NULL;
41 fRxBuffer = NULL;
42 fNetAudioCaptureBuffer = NULL;
43 fNetAudioPlaybackBuffer = NULL;
44 fNetMidiCaptureBuffer = NULL;
45 fNetMidiPlaybackBuffer = NULL;
48 JackNetInterface::JackNetInterface ( const char* multicast_ip, int port ) : fSocket ( multicast_ip, port )
50 fMulticastIP = strdup ( multicast_ip );
51 fTxBuffer = NULL;
52 fRxBuffer = NULL;
53 fNetAudioCaptureBuffer = NULL;
54 fNetAudioPlaybackBuffer = NULL;
55 fNetMidiCaptureBuffer = NULL;
56 fNetMidiPlaybackBuffer = NULL;
59 JackNetInterface::JackNetInterface ( session_params_t& params, JackNetSocket& socket, const char* multicast_ip ) : fSocket ( socket )
61 fParams = params;
62 fMulticastIP = strdup ( multicast_ip );
63 fTxBuffer = NULL;
64 fRxBuffer = NULL;
65 fNetAudioCaptureBuffer = NULL;
66 fNetAudioPlaybackBuffer = NULL;
67 fNetMidiCaptureBuffer = NULL;
68 fNetMidiPlaybackBuffer = NULL;
71 JackNetInterface::~JackNetInterface()
73 jack_log ( "JackNetInterface::~JackNetInterface" );
75 fSocket.Close();
76 delete[] fTxBuffer;
77 delete[] fRxBuffer;
78 delete[] fMulticastIP;
79 delete fNetAudioCaptureBuffer;
80 delete fNetAudioPlaybackBuffer;
81 delete fNetMidiCaptureBuffer;
82 delete fNetMidiPlaybackBuffer;
85 void JackNetInterface::SetFramesPerPacket()
87 jack_log ( "JackNetInterface::SetFramesPerPacket" );
89 if (fParams.fSendAudioChannels == 0 && fParams.fReturnAudioChannels == 0) {
90 fParams.fFramesPerPacket = fParams.fPeriodSize;
91 } else {
92 jack_nframes_t period = ( int ) powf ( 2.f, ( int ) ( log (float ( fParams.fMtu - sizeof ( packet_header_t ) )
93 / ( max ( fParams.fReturnAudioChannels, fParams.fSendAudioChannels ) * sizeof ( sample_t ) ) ) / log ( 2. ) ) );
94 fParams.fFramesPerPacket = ( period > fParams.fPeriodSize ) ? fParams.fPeriodSize : period;
98 int JackNetInterface::SetNetBufferSize()
100 jack_log ( "JackNetInterface::SetNetBufferSize" );
102 float audio_size, midi_size;
103 int bufsize;
104 //audio
105 audio_size = fParams.fMtu * ( fParams.fPeriodSize / fParams.fFramesPerPacket );
106 //midi
107 midi_size = fParams.fMtu * ( max ( fParams.fSendMidiChannels, fParams.fReturnMidiChannels ) *
108 fParams.fPeriodSize * sizeof ( sample_t ) / ( fParams.fMtu - sizeof ( packet_header_t ) ) );
109 //bufsize = sync + audio + midi
110 bufsize = MAX_LATENCY * (fParams.fMtu + ( int ) audio_size + ( int ) midi_size);
112 //tx buffer
113 if ( fSocket.SetOption ( SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof ( bufsize ) ) == SOCKET_ERROR )
114 return SOCKET_ERROR;
116 //rx buffer
117 if ( fSocket.SetOption ( SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof ( bufsize ) ) == SOCKET_ERROR )
118 return SOCKET_ERROR;
120 return 0;
123 int JackNetInterface::GetNMidiPckt()
125 //even if there is no midi data, jack need an empty buffer to know there is no event to read
126 //99% of the cases : all data in one packet
127 if ( fTxHeader.fMidiDataSize <= ( fParams.fMtu - sizeof ( packet_header_t ) ) )
128 return 1;
129 //else, get the number of needed packets (simply slice the biiig buffer)
130 int npckt = fTxHeader.fMidiDataSize / ( fParams.fMtu - sizeof ( packet_header_t ) );
131 if ( fTxHeader.fMidiDataSize % ( fParams.fMtu - sizeof ( packet_header_t ) ) )
132 return ++npckt;
133 return npckt;
136 bool JackNetInterface::IsNextPacket()
138 packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
139 //ignore first cycle
140 if ( fRxHeader.fCycle <= 1 ) {
141 return true;
143 //same PcktID (cycle), next SubPcktID (subcycle)
144 if ( ( fRxHeader.fSubCycle < ( fNSubProcess - 1 ) ) && ( rx_head->fCycle == fRxHeader.fCycle ) && ( rx_head->fSubCycle == ( fRxHeader.fSubCycle + 1 ) ) ) {
145 return true;
147 //next PcktID (cycle), SubPcktID reset to 0 (first subcyle)
148 if ( ( rx_head->fCycle == ( fRxHeader.fCycle + 1 ) ) && ( fRxHeader.fSubCycle == ( fNSubProcess - 1 ) ) && ( rx_head->fSubCycle == 0 ) ) {
149 return true;
151 //else, packet(s) missing, return false
152 return false;
155 void JackNetInterface::SetParams()
157 //number of audio subcycles (packets)
158 fNSubProcess = fParams.fPeriodSize / fParams.fFramesPerPacket;
160 //payload size
161 fPayloadSize = fParams.fMtu - sizeof ( packet_header_t );
163 //TX header init
164 strcpy ( fTxHeader.fPacketType, "header" );
165 fTxHeader.fID = fParams.fID;
166 fTxHeader.fCycle = 0;
167 fTxHeader.fSubCycle = 0;
168 fTxHeader.fMidiDataSize = 0;
169 fTxHeader.fBitdepth = fParams.fBitdepth;
170 fTxHeader.fIsLastPckt = 0;
172 //RX header init
173 strcpy ( fRxHeader.fPacketType, "header" );
174 fRxHeader.fID = fParams.fID;
175 fRxHeader.fCycle = 0;
176 fRxHeader.fSubCycle = 0;
177 fRxHeader.fMidiDataSize = 0;
178 fRxHeader.fBitdepth = fParams.fBitdepth;
179 fRxHeader.fIsLastPckt = 0;
181 //network buffers
182 fTxBuffer = new char[fParams.fMtu];
183 fRxBuffer = new char[fParams.fMtu];
184 assert ( fTxBuffer );
185 assert ( fRxBuffer );
187 //net audio/midi buffers'addresses
188 fTxData = fTxBuffer + sizeof ( packet_header_t );
189 fRxData = fRxBuffer + sizeof ( packet_header_t );
192 // JackNetMasterInterface ************************************************************************************
194 bool JackNetMasterInterface::Init()
196 jack_log ( "JackNetMasterInterface::Init, ID %u.", fParams.fID );
198 session_params_t host_params;
199 uint attempt = 0;
200 int rx_bytes = 0;
202 //socket
203 if ( fSocket.NewSocket() == SOCKET_ERROR )
205 jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
206 return false;
209 //timeout on receive (for init)
210 if ( fSocket.SetTimeOut ( MASTER_INIT_TIMEOUT ) < 0 )
211 jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );
213 //connect
214 if ( fSocket.Connect() == SOCKET_ERROR )
216 jack_error ( "Can't connect : %s", StrError ( NET_ERROR_CODE ) );
217 return false;
220 //set the number of complete audio frames we can put in a packet
221 SetFramesPerPacket();
223 //send 'SLAVE_SETUP' until 'START_MASTER' received
224 jack_info ( "Sending parameters to %s ...", fParams.fSlaveNetName );
227 session_params_t net_params;
228 SetPacketType ( &fParams, SLAVE_SETUP );
229 SessionParamsHToN(&fParams, &net_params);
231 if ( fSocket.Send ( &net_params, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
232 jack_error ( "Error in send : ", StrError ( NET_ERROR_CODE ) );
234 memset(&net_params, 0, sizeof ( session_params_t ));
235 if ( ( ( rx_bytes = fSocket.Recv ( &net_params, sizeof ( session_params_t ), 0 ) ) == SOCKET_ERROR ) && ( fSocket.GetError() != NET_NO_DATA ) )
237 jack_error ( "Problem with network." );
238 return false;
241 SessionParamsNToH(&net_params, &host_params);
243 while ( ( GetPacketType ( &host_params ) != START_MASTER ) && ( ++attempt < SLAVE_SETUP_RETRY ) );
244 if ( attempt == SLAVE_SETUP_RETRY )
246 jack_error ( "Slave doesn't respond, exiting." );
247 return false;
250 //set the new timeout for the socket
251 if ( SetRxTimeout() == SOCKET_ERROR )
253 jack_error ( "Can't set rx timeout : %s", StrError ( NET_ERROR_CODE ) );
254 return false;
257 //set the new rx buffer size
258 if ( SetNetBufferSize() == SOCKET_ERROR )
260 jack_error ( "Can't set net buffer sizes : %s", StrError ( NET_ERROR_CODE ) );
261 return false;
264 return true;
267 int JackNetMasterInterface::SetRxTimeout()
269 jack_log ( "JackNetMasterInterface::SetRxTimeout" );
271 float time = 0;
272 //slow or normal mode, short timeout on recv (2 audio subcycles)
273 if ( ( fParams.fNetworkMode == 's' ) || ( fParams.fNetworkMode == 'n' ) )
274 time = 2000000.f * ( static_cast<float> ( fParams.fFramesPerPacket ) / static_cast<float> ( fParams.fSampleRate ) );
275 //fast mode, wait for 75% of the entire cycle duration
276 else if ( fParams.fNetworkMode == 'f' )
277 time = 750000.f * ( static_cast<float> ( fParams.fPeriodSize ) / static_cast<float> ( fParams.fSampleRate ) );
278 return fSocket.SetTimeOut ( static_cast<int> ( time ) );
281 void JackNetMasterInterface::SetParams()
283 jack_log ( "JackNetMasterInterface::SetParams" );
285 JackNetInterface::SetParams();
287 fTxHeader.fDataStream = 's';
288 fRxHeader.fDataStream = 'r';
290 //midi net buffers
291 fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fTxData );
292 fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fRxData );
293 assert ( fNetMidiCaptureBuffer );
294 assert ( fNetMidiPlaybackBuffer );
296 //audio net buffers
297 fNetAudioCaptureBuffer = new NetAudioBuffer ( &fParams, fParams.fSendAudioChannels, fTxData );
298 fNetAudioPlaybackBuffer = new NetAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fRxData );
299 assert ( fNetAudioCaptureBuffer );
300 assert ( fNetAudioPlaybackBuffer );
302 //audio netbuffer length
303 fAudioTxLen = sizeof ( packet_header_t ) + fNetAudioPlaybackBuffer->GetSize();
304 fAudioRxLen = sizeof ( packet_header_t ) + fNetAudioCaptureBuffer->GetSize();
307 void JackNetMasterInterface::Exit()
309 jack_log ( "JackNetMasterInterface::Exit, ID %u", fParams.fID );
311 //stop process
312 fRunning = false;
314 //send a 'multicast euthanasia request' - new socket is required on macosx
315 jack_info ( "Exiting '%s'", fParams.fName );
316 SetPacketType ( &fParams, KILL_MASTER );
317 JackNetSocket mcast_socket ( fMulticastIP, fSocket.GetPort() );
319 session_params_t net_params;
320 SessionParamsHToN(&fParams, &net_params);
322 if ( mcast_socket.NewSocket() == SOCKET_ERROR )
323 jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
324 if ( mcast_socket.SendTo ( &net_params, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
325 jack_error ( "Can't send suicide request : %s", StrError ( NET_ERROR_CODE ) );
327 mcast_socket.Close();
329 // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
330 ThreadExit();
333 int JackNetMasterInterface::Recv ( size_t size, int flags )
335 int rx_bytes;
336 if ( ( ( rx_bytes = fSocket.Recv ( fRxBuffer, size, flags ) ) == SOCKET_ERROR ) && fRunning )
338 net_error_t error = fSocket.GetError();
339 //no data isn't really a network error, so just return 0 avalaible read bytes
340 if ( error == NET_NO_DATA )
341 return 0;
342 else if ( error == NET_CONN_ERROR )
344 //fatal connection issue, exit
345 jack_error ( "'%s' : %s, exiting.", fParams.fName, StrError ( NET_ERROR_CODE ) );
346 //ask to the manager to properly remove the master
347 Exit();
349 else
350 jack_error ( "Error in master receive : %s", StrError ( NET_ERROR_CODE ) );
353 packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
354 PacketHeaderNToH(header, header);
355 return rx_bytes;
358 int JackNetMasterInterface::Send ( size_t size, int flags )
360 int tx_bytes;
361 packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
362 PacketHeaderHToN(header, header);
364 if ( ( ( tx_bytes = fSocket.Send ( fTxBuffer, size, flags ) ) == SOCKET_ERROR ) && fRunning )
366 net_error_t error = fSocket.GetError();
367 if ( error == NET_CONN_ERROR )
369 //fatal connection issue, exit
370 jack_error ( "'%s' : %s, exiting.", fParams.fName, StrError ( NET_ERROR_CODE ) );
371 Exit();
373 else
374 jack_error ( "Error in master send : %s", StrError ( NET_ERROR_CODE ) );
376 return tx_bytes;
379 bool JackNetMasterInterface::IsSynched()
381 if (fParams.fNetworkMode == 's') {
382 return (fCycleOffset < 3);
383 } else {
384 return true;
388 int JackNetMasterInterface::SyncSend()
390 fTxHeader.fCycle++;
391 fTxHeader.fSubCycle = 0;
392 fTxHeader.fDataType = 's';
393 fTxHeader.fIsLastPckt = ( !fParams.fSendMidiChannels && !fParams.fSendAudioChannels ) ? 1 : 0;
394 fTxHeader.fPacketSize = fParams.fMtu;
395 memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
396 return Send ( fTxHeader.fPacketSize, 0 );
399 int JackNetMasterInterface::DataSend()
401 uint subproc;
402 //midi
403 if ( fParams.fSendMidiChannels )
405 //set global header fields and get the number of midi packets
406 fTxHeader.fDataType = 'm';
407 fTxHeader.fMidiDataSize = fNetMidiCaptureBuffer->RenderFromJackPorts();
408 fTxHeader.fNMidiPckt = GetNMidiPckt();
409 for ( subproc = 0; subproc < fTxHeader.fNMidiPckt; subproc++ )
411 fTxHeader.fSubCycle = subproc;
412 fTxHeader.fIsLastPckt = ( ( subproc == ( fTxHeader.fNMidiPckt - 1 ) ) && !fParams.fSendAudioChannels ) ? 1 : 0;
413 fTxHeader.fPacketSize = sizeof ( packet_header_t ) + fNetMidiCaptureBuffer->RenderToNetwork ( subproc, fTxHeader.fMidiDataSize );
414 memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
415 if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
416 return SOCKET_ERROR;
420 //audio
421 if ( fParams.fSendAudioChannels )
423 fTxHeader.fDataType = 'a';
424 for ( subproc = 0; subproc < fNSubProcess; subproc++ )
426 fTxHeader.fSubCycle = subproc;
427 fTxHeader.fIsLastPckt = ( subproc == ( fNSubProcess - 1 ) ) ? 1 : 0;
428 fTxHeader.fPacketSize = fAudioTxLen;
429 memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
430 fNetAudioCaptureBuffer->RenderFromJackPorts ( subproc );
431 if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
432 return SOCKET_ERROR;
436 return 0;
439 int JackNetMasterInterface::SyncRecv()
441 packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
442 int rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
444 if ( ( rx_bytes == 0 ) || ( rx_bytes == SOCKET_ERROR ) )
445 return rx_bytes;
447 fCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
449 switch ( fParams.fNetworkMode )
451 case 's' :
452 //slow mode : allow to use full bandwidth and heavy process on the slave
453 // - extra latency is set to two cycles, one cycle for send/receive operations + one cycle for heavy process on the slave
454 // - if the network is two fast, just wait the next cycle, this mode allows a shorter cycle duration for the master
455 // - this mode will skip the two first cycles, thus it lets time for data to be processed and queued on the socket rx buffer
456 //the slow mode is the safest mode because it wait twice the bandwidth relative time (send/return + process)
457 if (fCycleOffset < 2)
458 return 0;
459 else
460 rx_bytes = Recv ( rx_head->fPacketSize, 0 );
462 if (fCycleOffset > 2) {
463 jack_info("Warning : '%s' runs in slow network mode, but data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
465 break;
467 case 'n' :
468 //normal use of the network :
469 // - extra latency is set to one cycle, what is the time needed to receive streams using full network bandwidth
470 // - if the network is too fast, just wait the next cycle, the benefit here is the master's cycle is shorter
471 // - indeed, data is supposed to be on the network rx buffer, so we don't have to wait for it
472 if (fCycleOffset < 1)
473 return 0;
474 else
475 rx_bytes = Recv ( rx_head->fPacketSize, 0 );
477 if (fCycleOffset != 1)
478 jack_info("'%s' can't run in normal network mode, data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
479 break;
481 case 'f' :
482 //fast mode suppose the network bandwith is larger than required for the transmission (only a few channels for example)
483 // - packets can be quickly received, quickly is here relative to the cycle duration
484 // - here, receive data, we can't keep it queued on the rx buffer,
485 // - but if there is a cycle offset, tell the user, that means we're not in fast mode anymore, network is too slow
486 rx_bytes = Recv ( rx_head->fPacketSize, 0 );
488 if (fCycleOffset != 0)
489 jack_info("'%s' can't run in fast network mode, data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
490 break;
493 fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
494 return rx_bytes;
497 int JackNetMasterInterface::DataRecv()
499 int rx_bytes = 0;
500 uint jumpcnt = 0;
501 uint recvd_midi_pckt = 0;
502 uint recvd_audio_pckt = 0;
503 packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
505 while ( !fRxHeader.fIsLastPckt )
507 //how much data is queued on the rx buffer ?
508 rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
510 if ( rx_bytes == SOCKET_ERROR )
511 return rx_bytes;
512 //if no data
513 if ( ( rx_bytes == 0 ) && ( ++jumpcnt == fNSubProcess ) )
515 jack_error ( "No data from %s...", fParams.fName );
516 jumpcnt = 0;
518 //else if data is valid,
519 if ( rx_bytes && ( rx_head->fDataStream == 'r' ) && ( rx_head->fID == fParams.fID ) )
521 //read data
522 switch ( rx_head->fDataType )
524 case 'm': //midi
525 rx_bytes = Recv ( rx_head->fPacketSize, 0 );
526 fRxHeader.fCycle = rx_head->fCycle;
527 fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
528 fNetMidiPlaybackBuffer->RenderFromNetwork ( rx_head->fSubCycle, rx_bytes - sizeof ( packet_header_t ) );
529 if ( ++recvd_midi_pckt == rx_head->fNMidiPckt )
530 fNetMidiPlaybackBuffer->RenderToJackPorts();
531 jumpcnt = 0;
532 break;
534 case 'a': //audio
535 rx_bytes = Recv ( rx_head->fPacketSize, 0 );
536 // SL: 25/01/09
537 // if ( !IsNextPacket() )
538 // jack_error ( "Packet(s) missing from '%s'...", fParams.fName );
539 if (recvd_audio_pckt++ != rx_head->fSubCycle) {
540 jack_error("Packet(s) missing from '%s'...", fParams.fSlaveNetName);
542 fRxHeader.fCycle = rx_head->fCycle;
543 fRxHeader.fSubCycle = rx_head->fSubCycle;
544 fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
545 fNetAudioPlaybackBuffer->RenderToJackPorts ( rx_head->fSubCycle );
546 jumpcnt = 0;
547 break;
549 case 's': //sync
550 /* SL: 25/01/09
551 if ( rx_head->fCycle == fTxHeader.fCycle )
552 return 0;
554 jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
555 return 0;
559 return rx_bytes;
562 // JackNetSlaveInterface ************************************************************************************************
564 uint JackNetSlaveInterface::fSlaveCounter = 0;
566 bool JackNetSlaveInterface::Init()
568 jack_log ( "JackNetSlaveInterface::Init()" );
570 //set the parameters to send
571 strcpy ( fParams.fPacketType, "params" );
572 fParams.fProtocolVersion = 'a';
573 SetPacketType ( &fParams, SLAVE_AVAILABLE );
575 //init loop : get a master and start, do it until connection is ok
576 net_status_t status;
579 //first, get a master, do it until a valid connection is running
582 status = GetNetMaster();
583 if ( status == NET_SOCKET_ERROR )
584 return false;
586 while ( status != NET_CONNECTED );
588 //then tell the master we are ready
589 jack_info ( "Initializing connection with %s...", fParams.fMasterNetName );
590 status = SendStartToMaster();
591 if ( status == NET_ERROR )
592 return false;
594 while ( status != NET_ROLLING );
596 return true;
599 net_status_t JackNetSlaveInterface::GetNetMaster()
601 jack_log ( "JackNetSlaveInterface::GetNetMaster()" );
602 //utility
603 session_params_t host_params;
604 int rx_bytes = 0;
606 //socket
607 if ( fSocket.NewSocket() == SOCKET_ERROR )
609 jack_error ( "Fatal error : network unreachable - %s", StrError ( NET_ERROR_CODE ) );
610 return NET_SOCKET_ERROR;
613 //bind the socket
614 if ( fSocket.Bind() == SOCKET_ERROR )
615 jack_error ( "Can't bind the socket : %s", StrError ( NET_ERROR_CODE ) );
617 //timeout on receive
618 if ( fSocket.SetTimeOut ( SLAVE_INIT_TIMEOUT ) == SOCKET_ERROR )
619 jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );
621 //disable local loop
622 if ( fSocket.SetLocalLoop() == SOCKET_ERROR )
623 jack_error ( "Can't disable multicast loop : %s", StrError ( NET_ERROR_CODE ) );
625 //send 'AVAILABLE' until 'SLAVE_SETUP' received
626 jack_info ( "Waiting for a master..." );
629 //send 'available'
630 session_params_t net_params;
631 SessionParamsHToN(&fParams, &net_params);
632 if ( fSocket.SendTo ( &net_params, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
633 jack_error ( "Error in data send : %s", StrError ( NET_ERROR_CODE ) );
635 //filter incoming packets : don't exit while no error is detected
636 memset(&net_params, 0, sizeof ( session_params_t ));
637 rx_bytes = fSocket.CatchHost ( &net_params, sizeof ( session_params_t ), 0 );
638 SessionParamsNToH(&net_params, &host_params);
639 if ( ( rx_bytes == SOCKET_ERROR ) && ( fSocket.GetError() != NET_NO_DATA ) )
641 jack_error ( "Can't receive : %s", StrError ( NET_ERROR_CODE ) );
642 return NET_RECV_ERROR;
645 while ( strcmp ( host_params.fPacketType, fParams.fPacketType ) && ( GetPacketType ( &host_params ) != SLAVE_SETUP ) );
647 //everything is OK, copy parameters
648 fParams = host_params;
650 //set the new buffer sizes
651 if ( SetNetBufferSize() == SOCKET_ERROR )
652 jack_error ( "Can't set net buffer sizes : %s", StrError ( NET_ERROR_CODE ) );
654 //connect the socket
655 if ( fSocket.Connect() == SOCKET_ERROR )
657 jack_error ( "Error in connect : %s", StrError ( NET_ERROR_CODE ) );
658 return NET_CONNECT_ERROR;
661 return NET_CONNECTED;
664 net_status_t JackNetSlaveInterface::SendStartToMaster()
666 jack_log ( "JackNetSlaveInterface::SendStartToMaster" );
668 //tell the master to start
669 session_params_t net_params;
670 SetPacketType ( &fParams, START_MASTER );
671 SessionParamsHToN(&fParams, &net_params);
672 if ( fSocket.Send ( &net_params, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
674 jack_error ( "Error in send : %s", StrError ( NET_ERROR_CODE ) );
675 return ( fSocket.GetError() == NET_CONN_ERROR ) ? NET_ERROR : NET_SEND_ERROR;
677 return NET_ROLLING;
680 void JackNetSlaveInterface::SetParams()
682 jack_log ( "JackNetSlaveInterface::SetParams" );
684 JackNetInterface::SetParams();
686 fTxHeader.fDataStream = 'r';
687 fRxHeader.fDataStream = 's';
689 //midi net buffers
690 fNetMidiCaptureBuffer = new NetMidiBuffer ( &fParams, fParams.fSendMidiChannels, fRxData );
691 fNetMidiPlaybackBuffer = new NetMidiBuffer ( &fParams, fParams.fReturnMidiChannels, fTxData );
693 //audio net buffers
694 fNetAudioCaptureBuffer = new NetAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
695 fNetAudioPlaybackBuffer = new NetAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
697 //audio netbuffer length
698 fAudioTxLen = sizeof ( packet_header_t ) + fNetAudioPlaybackBuffer->GetSize();
699 fAudioRxLen = sizeof ( packet_header_t ) + fNetAudioCaptureBuffer->GetSize();
702 int JackNetSlaveInterface::Recv ( size_t size, int flags )
704 int rx_bytes = fSocket.Recv ( fRxBuffer, size, flags );
705 //handle errors
706 if ( rx_bytes == SOCKET_ERROR )
708 net_error_t error = fSocket.GetError();
709 //no data isn't really an error in realtime processing, so just return 0
710 if ( error == NET_NO_DATA )
711 jack_error ( "No data, is the master still running ?" );
712 //if a network error occurs, this exception will restart the driver
713 else if ( error == NET_CONN_ERROR )
715 jack_error ( "Connection lost." );
716 throw JackNetException();
718 else
719 jack_error ( "Fatal error in slave receive : %s", StrError ( NET_ERROR_CODE ) );
722 packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
723 PacketHeaderNToH(header, header);
724 return rx_bytes;
727 int JackNetSlaveInterface::Send ( size_t size, int flags )
729 packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
730 PacketHeaderHToN(header, header);
731 int tx_bytes = fSocket.Send ( fTxBuffer, size, flags );
733 //handle errors
734 if ( tx_bytes == SOCKET_ERROR )
736 net_error_t error = fSocket.GetError();
737 //if a network error occurs, this exception will restart the driver
738 if ( error == NET_CONN_ERROR )
740 jack_error ( "Connection lost." );
741 throw JackNetException();
743 else
744 jack_error ( "Fatal error in slave send : %s", StrError ( NET_ERROR_CODE ) );
746 return tx_bytes;
749 int JackNetSlaveInterface::SyncRecv()
751 int rx_bytes = 0;
752 packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
753 //receive sync (launch the cycle)
756 rx_bytes = Recv ( fParams.fMtu, 0 );
757 //connection issue, send will detect it, so don't skip the cycle (return 0)
758 if ( rx_bytes == SOCKET_ERROR )
759 return rx_bytes;
761 while ( !rx_bytes && ( rx_head->fDataType != 's' ) );
762 fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
763 return rx_bytes;
766 int JackNetSlaveInterface::DataRecv()
768 uint recvd_midi_pckt = 0;
769 uint recvd_audio_pckt = 0;
770 int rx_bytes = 0;
771 packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
773 while ( !fRxHeader.fIsLastPckt )
775 rx_bytes = Recv ( fParams.fMtu, MSG_PEEK );
776 //error here, problem with recv, just skip the cycle (return -1)
778 if ( rx_bytes == SOCKET_ERROR )
779 return rx_bytes;
780 if ( rx_bytes && ( rx_head->fDataStream == 's' ) && ( rx_head->fID == fParams.fID ) )
782 switch ( rx_head->fDataType )
784 case 'm': //midi
785 rx_bytes = Recv ( rx_head->fPacketSize, 0 );
786 fRxHeader.fCycle = rx_head->fCycle;
787 fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
788 fNetMidiCaptureBuffer->RenderFromNetwork ( rx_head->fSubCycle, rx_bytes - sizeof ( packet_header_t ) );
789 if ( ++recvd_midi_pckt == rx_head->fNMidiPckt )
790 fNetMidiCaptureBuffer->RenderToJackPorts();
791 break;
793 case 'a': //audio
794 rx_bytes = Recv ( rx_head->fPacketSize, 0 );
795 //SL: 25/01/09
796 // if ( !IsNextPacket() )
797 // jack_error ( "Packet(s) missing..." );
798 if (recvd_audio_pckt++ != rx_head->fSubCycle) {
799 jack_error("Packet(s) missing from '%s'...", fParams.fMasterNetName);
801 fRxHeader.fCycle = rx_head->fCycle;
802 fRxHeader.fSubCycle = rx_head->fSubCycle;
803 fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
804 fNetAudioCaptureBuffer->RenderToJackPorts ( rx_head->fSubCycle );
805 break;
807 case 's': //sync
808 jack_info ( "NetSlave : overloaded, skipping receive." );
809 return 0;
813 fRxHeader.fCycle = rx_head->fCycle;
814 return 0;
817 int JackNetSlaveInterface::SyncSend()
819 //tx header
820 if ( fParams.fSlaveSyncMode )
821 fTxHeader.fCycle = fRxHeader.fCycle;
822 else
823 fTxHeader.fCycle++;
824 fTxHeader.fSubCycle = 0;
825 fTxHeader.fDataType = 's';
826 fTxHeader.fIsLastPckt = ( !fParams.fReturnMidiChannels && !fParams.fReturnAudioChannels ) ? 1 : 0;
827 fTxHeader.fPacketSize = fParams.fMtu;
828 memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
829 return Send ( fTxHeader.fPacketSize, 0 );
832 int JackNetSlaveInterface::DataSend()
834 uint subproc;
836 //midi
837 if ( fParams.fReturnMidiChannels )
839 fTxHeader.fDataType = 'm';
840 fTxHeader.fMidiDataSize = fNetMidiPlaybackBuffer->RenderFromJackPorts();
841 fTxHeader.fNMidiPckt = GetNMidiPckt();
842 for ( subproc = 0; subproc < fTxHeader.fNMidiPckt; subproc++ )
844 fTxHeader.fSubCycle = subproc;
845 fTxHeader.fIsLastPckt = ( ( subproc == ( fTxHeader.fNMidiPckt - 1 ) ) && !fParams.fReturnAudioChannels ) ? 1 : 0;
846 fTxHeader.fPacketSize = sizeof ( packet_header_t ) + fNetMidiPlaybackBuffer->RenderToNetwork ( subproc, fTxHeader.fMidiDataSize );
847 memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
848 if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
849 return SOCKET_ERROR;
853 //audio
854 if ( fParams.fReturnAudioChannels )
856 fTxHeader.fDataType = 'a';
857 for ( subproc = 0; subproc < fNSubProcess; subproc++ )
859 fTxHeader.fSubCycle = subproc;
860 fTxHeader.fIsLastPckt = ( subproc == ( fNSubProcess - 1 ) ) ? 1 : 0;
861 fTxHeader.fPacketSize = fAudioTxLen;
862 memcpy ( fTxBuffer, &fTxHeader, sizeof ( packet_header_t ) );
863 fNetAudioPlaybackBuffer->RenderFromJackPorts ( subproc );
864 if ( Send ( fTxHeader.fPacketSize, 0 ) == SOCKET_ERROR )
865 return SOCKET_ERROR;
868 return 0;