jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1056 lines
39KB

  1. /*
  2. Copyright (C) 2001 Paul Davis
  3. Copyright (C) 2008 Romain Moret at Grame
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. */
  16. #include "JackNetInterface.h"
  17. #include "JackException.h"
  18. #include "JackPlatformPlug.h"
  19. #include <assert.h>
  20. using namespace std;
  21. #define PACKET_AVAILABLE_SIZE (fParams.fMtu - sizeof(packet_header_t))
  22. #define HEADER_SIZE (sizeof(packet_header_t))
  23. /*
  24. TODO : since midi buffers now uses up to BUFFER_SIZE_MAX frames,
  25. probably also use BUFFER_SIZE_MAX in everything related to MIDI events
  26. handling (see MidiBufferInit in JackMidiPort.cpp)
  27. */
  28. namespace Jack
  29. {
  30. // JackNetInterface*******************************************
  31. JackNetInterface::JackNetInterface() : fSocket()
  32. {
  33. Initialize();
  34. }
  35. JackNetInterface::JackNetInterface ( const char* multicast_ip, int port ) : fSocket ( multicast_ip, port )
  36. {
  37. strcpy(fMulticastIP, multicast_ip);
  38. Initialize();
  39. }
  40. JackNetInterface::JackNetInterface ( session_params_t& params, JackNetSocket& socket, const char* multicast_ip ) : fSocket ( socket )
  41. {
  42. fParams = params;
  43. strcpy(fMulticastIP, multicast_ip);
  44. Initialize();
  45. }
  46. void JackNetInterface::Initialize()
  47. {
  48. fTxBuffer = NULL;
  49. fRxBuffer = NULL;
  50. fNetAudioCaptureBuffer = NULL;
  51. fNetAudioPlaybackBuffer = NULL;
  52. fNetMidiCaptureBuffer = NULL;
  53. fNetMidiPlaybackBuffer = NULL;
  54. memset(&fSendTransportData, 0, sizeof(net_transport_data_t));
  55. memset(&fReturnTransportData, 0, sizeof(net_transport_data_t));
  56. }
  57. void JackNetInterface::FreeNetworkBuffers()
  58. {
  59. delete fNetMidiCaptureBuffer;
  60. delete fNetMidiPlaybackBuffer;
  61. delete fNetAudioCaptureBuffer;
  62. delete fNetAudioPlaybackBuffer;
  63. fNetMidiCaptureBuffer = NULL;
  64. fNetMidiPlaybackBuffer = NULL;
  65. fNetAudioCaptureBuffer = NULL;
  66. fNetAudioPlaybackBuffer = NULL;
  67. }
  68. JackNetInterface::~JackNetInterface()
  69. {
  70. jack_log ("JackNetInterface::~JackNetInterface");
  71. fSocket.Close();
  72. delete[] fTxBuffer;
  73. delete[] fRxBuffer;
  74. delete fNetAudioCaptureBuffer;
  75. delete fNetAudioPlaybackBuffer;
  76. delete fNetMidiCaptureBuffer;
  77. delete fNetMidiPlaybackBuffer;
  78. }
  79. int JackNetInterface::SetNetBufferSize()
  80. {
  81. //audio
  82. float audio_size = (fNetAudioCaptureBuffer)
  83. ? fNetAudioCaptureBuffer->GetCycleSize()
  84. : (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->GetCycleSize() : 0;
  85. jack_log ("audio_size %f", audio_size);
  86. //midi
  87. float midi_size = (fNetMidiCaptureBuffer)
  88. ? fNetMidiCaptureBuffer->GetCycleSize()
  89. : (fNetMidiPlaybackBuffer) ? fNetMidiPlaybackBuffer->GetCycleSize() : 0;
  90. jack_log ("midi_size %f", midi_size);
  91. //bufsize = sync + audio + midi
  92. int bufsize = MAX_LATENCY * (fParams.fMtu + (int)audio_size + (int) midi_size);
  93. jack_log("SetNetBufferSize bufsize = %d", bufsize);
  94. //tx buffer
  95. if (fSocket.SetOption(SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR)
  96. return SOCKET_ERROR;
  97. //rx buffer
  98. if (fSocket.SetOption(SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR)
  99. return SOCKET_ERROR;
  100. return 0;
  101. }
  102. bool JackNetInterface::SetParams()
  103. {
  104. //TX header init
  105. strcpy ( fTxHeader.fPacketType, "header" );
  106. fTxHeader.fID = fParams.fID;
  107. fTxHeader.fCycle = 0;
  108. fTxHeader.fSubCycle = 0;
  109. fTxHeader.fIsLastPckt = 0;
  110. //RX header init
  111. strcpy ( fRxHeader.fPacketType, "header" );
  112. fRxHeader.fID = fParams.fID;
  113. fRxHeader.fCycle = 0;
  114. fRxHeader.fSubCycle = 0;
  115. fRxHeader.fIsLastPckt = 0;
  116. //network buffers
  117. fTxBuffer = new char[fParams.fMtu];
  118. fRxBuffer = new char[fParams.fMtu];
  119. assert ( fTxBuffer );
  120. assert ( fRxBuffer );
  121. //net audio/midi buffers'addresses
  122. fTxData = fTxBuffer + HEADER_SIZE;
  123. fRxData = fRxBuffer + HEADER_SIZE;
  124. return true;
  125. }
  126. // JackNetMasterInterface ************************************************************************************
  127. bool JackNetMasterInterface::Init()
  128. {
  129. jack_log ( "JackNetMasterInterface::Init, ID %u.", fParams.fID );
  130. session_params_t host_params;
  131. uint attempt = 0;
  132. int rx_bytes = 0;
  133. //socket
  134. if ( fSocket.NewSocket() == SOCKET_ERROR ) {
  135. jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
  136. return false;
  137. }
  138. //timeout on receive (for init)
  139. if ( fSocket.SetTimeOut ( MASTER_INIT_TIMEOUT ) < 0 )
  140. jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );
  141. //connect
  142. if ( fSocket.Connect() == SOCKET_ERROR ) {
  143. jack_error ( "Can't connect : %s", StrError ( NET_ERROR_CODE ) );
  144. return false;
  145. }
  146. //send 'SLAVE_SETUP' until 'START_MASTER' received
  147. jack_info ( "Sending parameters to %s...", fParams.fSlaveNetName );
  148. do
  149. {
  150. session_params_t net_params;
  151. memset(&net_params, 0, sizeof ( session_params_t ));
  152. SetPacketType ( &fParams, SLAVE_SETUP );
  153. SessionParamsHToN(&fParams, &net_params);
  154. if ( fSocket.Send ( &net_params, sizeof ( session_params_t ), 0 ) == SOCKET_ERROR )
  155. jack_error ( "Error in send : ", StrError ( NET_ERROR_CODE ) );
  156. memset(&net_params, 0, sizeof (session_params_t));
  157. if (((rx_bytes = fSocket.Recv(&net_params, sizeof(session_params_t), 0)) == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA))
  158. {
  159. jack_error ( "Problem with network." );
  160. return false;
  161. }
  162. SessionParamsNToH(&net_params, &host_params);
  163. }
  164. while ( ( GetPacketType ( &host_params ) != START_MASTER ) && ( ++attempt < SLAVE_SETUP_RETRY ) );
  165. if ( attempt == SLAVE_SETUP_RETRY ) {
  166. jack_error ( "Slave doesn't respond, exiting." );
  167. return false;
  168. }
  169. return true;
  170. }
  171. int JackNetMasterInterface::SetRxTimeout()
  172. {
  173. jack_log ( "JackNetMasterInterface::SetRxTimeout" );
  174. float time = 0;
  175. //slow or normal mode, short timeout on recv (2 audio subcycles)
  176. if ((fParams.fNetworkMode == 's') || (fParams.fNetworkMode == 'n')) {
  177. time = 2000000.f * ((fNetAudioCaptureBuffer)
  178. ? fNetAudioCaptureBuffer->GetCycleDuration()
  179. : (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->GetCycleDuration() : 0);
  180. }
  181. //fast mode, wait for 75% of the entire cycle duration
  182. else if (fParams.fNetworkMode == 'f') {
  183. time = 750000.f * (static_cast<float>(fParams.fPeriodSize) / static_cast<float>(fParams.fSampleRate));
  184. }
  185. return fSocket.SetTimeOut (static_cast<int>(time));
  186. }
  187. bool JackNetMasterInterface::SetParams()
  188. {
  189. jack_log("JackNetMasterInterface::SetParams");
  190. JackNetInterface::SetParams();
  191. fTxHeader.fDataStream = 's';
  192. fRxHeader.fDataStream = 'r';
  193. //midi net buffers
  194. if (fParams.fSendMidiChannels)
  195. fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fTxData);
  196. if (fParams.fReturnMidiChannels)
  197. fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
  198. try {
  199. //audio net buffers
  200. if (fParams.fSendAudioChannels) {
  201. switch (fParams.fSampleEncoder) {
  202. case JackFloatEncoder:
  203. fNetAudioCaptureBuffer = new NetFloatAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
  204. break;
  205. case JackIntEncoder:
  206. fNetAudioCaptureBuffer = new NetIntAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData);
  207. break;
  208. case JackCeltEncoder:
  209. #ifdef CELT
  210. fNetAudioCaptureBuffer = new NetCeltAudioBuffer(&fParams, fParams.fSendAudioChannels, fTxData, fParams.fKBps);
  211. #endif
  212. break;
  213. }
  214. }
  215. if (fParams.fReturnAudioChannels) {
  216. switch (fParams.fSampleEncoder) {
  217. case JackFloatEncoder:
  218. fNetAudioPlaybackBuffer = new NetFloatAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
  219. break;
  220. case JackIntEncoder:
  221. fNetAudioPlaybackBuffer = new NetIntAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData);
  222. break;
  223. case JackCeltEncoder:
  224. #ifdef CELT
  225. fNetAudioPlaybackBuffer = new NetCeltAudioBuffer(&fParams, fParams.fReturnAudioChannels, fRxData, fParams.fKBps);
  226. #endif
  227. break;
  228. }
  229. }
  230. } catch (exception&) {
  231. jack_error("NetAudioBuffer allocation error...");
  232. return false;
  233. }
  234. //set the new timeout for the socket
  235. if (SetRxTimeout() == SOCKET_ERROR) {
  236. jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
  237. goto error;
  238. }
  239. //set the new rx buffer size
  240. if (SetNetBufferSize() == SOCKET_ERROR) {
  241. jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
  242. goto error;
  243. }
  244. return true;
  245. error:
  246. FreeNetworkBuffers();
  247. return false;
  248. }
  249. void JackNetMasterInterface::Exit()
  250. {
  251. jack_log ( "JackNetMasterInterface::Exit, ID %u", fParams.fID );
  252. //stop process
  253. fRunning = false;
  254. //send a 'multicast euthanasia request' - new socket is required on macosx
  255. jack_info ( "Exiting '%s'", fParams.fName );
  256. SetPacketType ( &fParams, KILL_MASTER );
  257. JackNetSocket mcast_socket ( fMulticastIP, fSocket.GetPort() );
  258. session_params_t net_params;
  259. memset(&net_params, 0, sizeof ( session_params_t ));
  260. SessionParamsHToN(&fParams, &net_params);
  261. if ( mcast_socket.NewSocket() == SOCKET_ERROR )
  262. jack_error ( "Can't create socket : %s", StrError ( NET_ERROR_CODE ) );
  263. if ( mcast_socket.SendTo ( &net_params, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
  264. jack_error ( "Can't send suicide request : %s", StrError ( NET_ERROR_CODE ) );
  265. mcast_socket.Close();
  266. }
  267. int JackNetMasterInterface::Recv(size_t size, int flags)
  268. {
  269. int rx_bytes;
  270. if ((( rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
  271. net_error_t error = fSocket.GetError();
  272. //no data isn't really a network error, so just return 0 available read bytes
  273. if (error == NET_NO_DATA) {
  274. return 0;
  275. } else if (error == NET_CONN_ERROR) {
  276. //fatal connection issue, exit
  277. jack_error ( "'%s' : %s, exiting.", fParams.fName, StrError(NET_ERROR_CODE));
  278. //ask to the manager to properly remove the master
  279. Exit();
  280. // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
  281. ThreadExit();
  282. } else {
  283. jack_error ( "Error in master receive : %s", StrError(NET_ERROR_CODE));
  284. }
  285. }
  286. packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
  287. PacketHeaderNToH(header, header);
  288. return rx_bytes;
  289. }
  290. int JackNetMasterInterface::Send(size_t size, int flags)
  291. {
  292. int tx_bytes;
  293. packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
  294. PacketHeaderHToN(header, header);
  295. if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
  296. net_error_t error = fSocket.GetError();
  297. if (error == NET_CONN_ERROR) {
  298. //fatal connection issue, exit
  299. jack_error ("'%s' : %s, exiting.", fParams.fName, StrError (NET_ERROR_CODE));
  300. Exit();
  301. // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
  302. ThreadExit();
  303. } else {
  304. jack_error("Error in master send : %s", StrError(NET_ERROR_CODE));
  305. }
  306. }
  307. return tx_bytes;
  308. }
  309. bool JackNetMasterInterface::IsSynched()
  310. {
  311. if (fParams.fNetworkMode == 's') {
  312. return (fCycleOffset < (CYCLE_OFFSET_SLOW + 1));
  313. } else {
  314. return true;
  315. }
  316. }
  317. int JackNetMasterInterface::SyncSend()
  318. {
  319. fTxHeader.fCycle++;
  320. fTxHeader.fSubCycle = 0;
  321. fTxHeader.fDataType = 's';
  322. fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ? 1 : 0;
  323. fTxHeader.fPacketSize = HEADER_SIZE;
  324. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  325. return Send(fTxHeader.fPacketSize, 0);
  326. }
  327. int JackNetMasterInterface::DataSend()
  328. {
  329. uint subproc;
  330. uint data_size;
  331. //midi
  332. if (fParams.fSendMidiChannels > 0)
  333. {
  334. //set global header fields and get the number of midi packets
  335. fTxHeader.fDataType = 'm';
  336. data_size = fNetMidiCaptureBuffer->RenderFromJackPorts();
  337. fTxHeader.fNumPacket = fNetMidiCaptureBuffer->GetNumPackets();
  338. for ( subproc = 0; subproc < fTxHeader.fNumPacket; subproc++ )
  339. {
  340. fTxHeader.fSubCycle = subproc;
  341. fTxHeader.fIsLastPckt = ((subproc == (fTxHeader.fNumPacket - 1)) && (fParams.fSendAudioChannels == 0)) ? 1 : 0;
  342. fTxHeader.fPacketSize = HEADER_SIZE + fNetMidiCaptureBuffer->RenderToNetwork(subproc, data_size);
  343. memcpy ( fTxBuffer, &fTxHeader, HEADER_SIZE);
  344. if (Send (fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
  345. return SOCKET_ERROR;
  346. }
  347. }
  348. //audio
  349. if (fParams.fSendAudioChannels > 0)
  350. {
  351. fTxHeader.fDataType = 'a';
  352. data_size = fNetAudioCaptureBuffer->RenderFromJackPorts();
  353. fTxHeader.fNumPacket = fNetAudioCaptureBuffer->GetNumPackets();
  354. for (subproc = 0; subproc < fTxHeader.fNumPacket; subproc++)
  355. {
  356. fTxHeader.fSubCycle = subproc;
  357. fTxHeader.fIsLastPckt = (subproc == (fTxHeader.fNumPacket - 1)) ? 1 : 0;
  358. fTxHeader.fPacketSize = HEADER_SIZE + fNetAudioCaptureBuffer->RenderToNetwork(subproc, data_size);
  359. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  360. if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
  361. return SOCKET_ERROR;
  362. }
  363. }
  364. return 0;
  365. }
  366. int JackNetMasterInterface::SyncRecv()
  367. {
  368. packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
  369. int rx_bytes = Recv(HEADER_SIZE, MSG_PEEK);
  370. if ( ( rx_bytes == 0 ) || ( rx_bytes == SOCKET_ERROR ) )
  371. return rx_bytes;
  372. fCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
  373. switch ( fParams.fNetworkMode )
  374. {
  375. case 's' :
  376. //slow mode : allow to use full bandwidth and heavy process on the slave
  377. // - extra latency is set to two cycles, one cycle for send/receive operations + one cycle for heavy process on the slave
  378. // - if the network is two fast, just wait the next cycle, this mode allows a shorter cycle duration for the master
  379. // - this mode will skip the two first cycles, thus it lets time for data to be processed and queued on the socket rx buffer
  380. //the slow mode is the safest mode because it wait twice the bandwidth relative time (send/return + process)
  381. /*
  382. if (fCycleOffset < CYCLE_OFFSET_SLOW) {
  383. return 0;
  384. } else {
  385. rx_bytes = Recv ( rx_head->fPacketSize, 0 );
  386. }
  387. */
  388. rx_bytes = Recv ( rx_head->fPacketSize, 0 );
  389. if (fCycleOffset != fLastfCycleOffset)
  390. jack_info("Warning : '%s' runs in slow network mode, but data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
  391. fLastfCycleOffset = fCycleOffset;
  392. break;
  393. case 'n' :
  394. //normal use of the network :
  395. // - extra latency is set to one cycle, what is the time needed to receive streams using full network bandwidth
  396. // - if the network is too fast, just wait the next cycle, the benefit here is the master's cycle is shorter
  397. // - indeed, data is supposed to be on the network rx buffer, so we don't have to wait for it
  398. if (fCycleOffset < CYCLE_OFFSET_NORMAL) {
  399. return 0;
  400. } else {
  401. rx_bytes = Recv ( rx_head->fPacketSize, 0 );
  402. }
  403. if (fCycleOffset > CYCLE_OFFSET_NORMAL) {
  404. jack_info("'%s' can't run in normal network mode, data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
  405. }
  406. break;
  407. case 'f' :
  408. //fast mode suppose the network bandwith is larger than required for the transmission (only a few channels for example)
  409. // - packets can be quickly received, quickly is here relative to the cycle duration
  410. // - here, receive data, we can't keep it queued on the rx buffer,
  411. // - but if there is a cycle offset, tell the user, that means we're not in fast mode anymore, network is too slow
  412. rx_bytes = Recv ( rx_head->fPacketSize, 0 );
  413. if (fCycleOffset > CYCLE_OFFSET_FAST) {
  414. jack_info("'%s' can't run in fast network mode, data received too late (%d cycle(s) offset)", fParams.fName, fCycleOffset);
  415. }
  416. break;
  417. break;
  418. }
  419. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  420. return rx_bytes;
  421. }
  422. int JackNetMasterInterface::DataRecv()
  423. {
  424. int rx_bytes = 0;
  425. uint recvd_midi_pckt = 0;
  426. uint recvd_audio_pckt = 0;
  427. packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
  428. while ( !fRxHeader.fIsLastPckt )
  429. {
  430. //how much data is queued on the rx buffer ?
  431. rx_bytes = Recv(HEADER_SIZE, MSG_PEEK);
  432. //error here, problem with recv, just skip the cycle (return -1)
  433. if ( rx_bytes == SOCKET_ERROR )
  434. return rx_bytes;
  435. if ( rx_bytes && ( rx_head->fDataStream == 'r' ) && ( rx_head->fID == fParams.fID ) )
  436. {
  437. //read data
  438. switch ( rx_head->fDataType )
  439. {
  440. case 'm': //midi
  441. rx_bytes = Recv(rx_head->fPacketSize, 0);
  442. fRxHeader.fCycle = rx_head->fCycle;
  443. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  444. fNetMidiPlaybackBuffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
  445. // Last midi packet is received, so finish rendering...
  446. if (++recvd_midi_pckt == rx_head->fNumPacket)
  447. fNetMidiPlaybackBuffer->RenderToJackPorts();
  448. break;
  449. case 'a': //audio
  450. rx_bytes = Recv(rx_head->fPacketSize, 0);
  451. fRxHeader.fCycle = rx_head->fCycle;
  452. fRxHeader.fSubCycle = rx_head->fSubCycle;
  453. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  454. fNetAudioPlaybackBuffer->RenderFromNetwork(rx_head->fCycle, rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
  455. // Last audio packet is received, so finish rendering...
  456. if (fRxHeader.fIsLastPckt)
  457. fNetAudioPlaybackBuffer->RenderToJackPorts();
  458. break;
  459. case 's': //sync
  460. jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
  461. // TODO : finish midi and audio rendering ?
  462. fNetAudioPlaybackBuffer->RenderToJackPorts();
  463. return 0;
  464. }
  465. }
  466. }
  467. return rx_bytes;
  468. }
  469. void JackNetMasterInterface::EncodeSyncPacket()
  470. {
  471. //this method contains every step of sync packet informations coding
  472. //first of all, reset sync packet
  473. memset ( fTxData, 0, PACKET_AVAILABLE_SIZE );
  474. //then, first step : transport
  475. if (fParams.fTransportSync) {
  476. EncodeTransportData();
  477. TransportDataHToN( &fSendTransportData, &fSendTransportData);
  478. //copy to TxBuffer
  479. memcpy ( fTxData, &fSendTransportData, sizeof ( net_transport_data_t ) );
  480. }
  481. //then others (freewheel etc.)
  482. //...
  483. }
  484. void JackNetMasterInterface::DecodeSyncPacket()
  485. {
  486. //this method contains every step of sync packet informations decoding process
  487. //first : transport
  488. if (fParams.fTransportSync) {
  489. //copy received transport data to transport data structure
  490. memcpy ( &fReturnTransportData, fRxData, sizeof ( net_transport_data_t ) );
  491. TransportDataNToH( &fReturnTransportData, &fReturnTransportData);
  492. DecodeTransportData();
  493. }
  494. //then others
  495. //...
  496. }
  497. // JackNetSlaveInterface ************************************************************************************************
  498. uint JackNetSlaveInterface::fSlaveCounter = 0;
  499. bool JackNetSlaveInterface::Init()
  500. {
  501. jack_log ( "JackNetSlaveInterface::Init()" );
  502. //set the parameters to send
  503. strcpy ( fParams.fPacketType, "params" );
  504. fParams.fProtocolVersion = SLAVE_PROTOCOL;
  505. SetPacketType ( &fParams, SLAVE_AVAILABLE );
  506. //init loop : get a master and start, do it until connection is ok
  507. net_status_t status;
  508. do
  509. {
  510. //first, get a master, do it until a valid connection is running
  511. do
  512. {
  513. status = SendAvailableToMaster();
  514. if ( status == NET_SOCKET_ERROR )
  515. return false;
  516. }
  517. while ( status != NET_CONNECTED );
  518. //then tell the master we are ready
  519. jack_info ( "Initializing connection with %s...", fParams.fMasterNetName );
  520. status = SendStartToMaster();
  521. if ( status == NET_ERROR )
  522. return false;
  523. }
  524. while ( status != NET_ROLLING );
  525. return true;
  526. }
  527. // Separate the connection protocol into two separated step
  528. bool JackNetSlaveInterface::InitConnection(int time_out)
  529. {
  530. jack_log("JackNetSlaveInterface::InitConnection()");
  531. int try_count = (time_out > 0) ? ((1000000 * time_out) / SLAVE_INIT_TIMEOUT) : LONG_MAX;
  532. //set the parameters to send
  533. strcpy (fParams.fPacketType, "params");
  534. fParams.fProtocolVersion = SLAVE_PROTOCOL;
  535. SetPacketType (&fParams, SLAVE_AVAILABLE);
  536. net_status_t status;
  537. do
  538. {
  539. //get a master
  540. status = SendAvailableToMaster(try_count);
  541. if (status == NET_SOCKET_ERROR)
  542. return false;
  543. }
  544. while (status != NET_CONNECTED && --try_count > 0);
  545. return (try_count != 0);
  546. }
  547. bool JackNetSlaveInterface::InitRendering()
  548. {
  549. jack_log("JackNetSlaveInterface::InitRendering()");
  550. net_status_t status;
  551. do
  552. {
  553. //then tell the master we are ready
  554. jack_info("Initializing connection with %s...", fParams.fMasterNetName);
  555. status = SendStartToMaster();
  556. if (status == NET_ERROR)
  557. return false;
  558. }
  559. while (status != NET_ROLLING);
  560. return true;
  561. }
  562. net_status_t JackNetSlaveInterface::SendAvailableToMaster(long try_count)
  563. {
  564. jack_log ( "JackNetSlaveInterface::SendAvailableToMaster()" );
  565. //utility
  566. session_params_t host_params;
  567. int rx_bytes = 0;
  568. //socket
  569. if ( fSocket.NewSocket() == SOCKET_ERROR ) {
  570. jack_error ( "Fatal error : network unreachable - %s", StrError ( NET_ERROR_CODE ) );
  571. return NET_SOCKET_ERROR;
  572. }
  573. //bind the socket
  574. if ( fSocket.Bind() == SOCKET_ERROR ) {
  575. jack_error ( "Can't bind the socket : %s", StrError ( NET_ERROR_CODE ) );
  576. return NET_SOCKET_ERROR;
  577. }
  578. //timeout on receive
  579. if ( fSocket.SetTimeOut ( SLAVE_INIT_TIMEOUT ) == SOCKET_ERROR )
  580. jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );
  581. //disable local loop
  582. if ( fSocket.SetLocalLoop() == SOCKET_ERROR )
  583. jack_error ( "Can't disable multicast loop : %s", StrError ( NET_ERROR_CODE ) );
  584. //send 'AVAILABLE' until 'SLAVE_SETUP' received
  585. jack_info ( "Waiting for a master..." );
  586. do
  587. {
  588. //send 'available'
  589. session_params_t net_params;
  590. memset(&net_params, 0, sizeof ( session_params_t ));
  591. SessionParamsHToN(&fParams, &net_params);
  592. if ( fSocket.SendTo ( &net_params, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
  593. jack_error ( "Error in data send : %s", StrError ( NET_ERROR_CODE ) );
  594. //filter incoming packets : don't exit while no error is detected
  595. memset(&net_params, 0, sizeof ( session_params_t ));
  596. rx_bytes = fSocket.CatchHost ( &net_params, sizeof ( session_params_t ), 0 );
  597. SessionParamsNToH(&net_params, &host_params);
  598. if ( ( rx_bytes == SOCKET_ERROR ) && ( fSocket.GetError() != NET_NO_DATA ) )
  599. {
  600. jack_error ( "Can't receive : %s", StrError ( NET_ERROR_CODE ) );
  601. return NET_RECV_ERROR;
  602. }
  603. }
  604. while (strcmp(host_params.fPacketType, fParams.fPacketType) && (GetPacketType(&host_params) != SLAVE_SETUP) && (--try_count > 0));
  605. // Time out failure..
  606. if (try_count == 0) {
  607. jack_error("Time out error in connect");
  608. return NET_CONNECT_ERROR;
  609. }
  610. //everything is OK, copy parameters
  611. SessionParamsDisplay(&host_params);
  612. fParams = host_params;
  613. //connect the socket
  614. if (fSocket.Connect() == SOCKET_ERROR) {
  615. jack_error("Error in connect : %s", StrError(NET_ERROR_CODE));
  616. return NET_CONNECT_ERROR;
  617. }
  618. return NET_CONNECTED;
  619. }
  620. net_status_t JackNetSlaveInterface::SendStartToMaster()
  621. {
  622. jack_log("JackNetSlaveInterface::SendStartToMaster");
  623. //tell the master to start
  624. session_params_t net_params;
  625. memset(&net_params, 0, sizeof ( session_params_t ));
  626. SetPacketType ( &fParams, START_MASTER );
  627. SessionParamsHToN(&fParams, &net_params);
  628. if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR)
  629. {
  630. jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
  631. return (fSocket.GetError() == NET_CONN_ERROR) ? NET_ERROR : NET_SEND_ERROR;
  632. }
  633. return NET_ROLLING;
  634. }
  635. bool JackNetSlaveInterface::SetParams()
  636. {
  637. jack_log("JackNetSlaveInterface::SetParams");
  638. JackNetInterface::SetParams();
  639. fTxHeader.fDataStream = 'r';
  640. fRxHeader.fDataStream = 's';
  641. //midi net buffers
  642. if (fParams.fSendMidiChannels)
  643. fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fTxData);
  644. if (fParams.fReturnMidiChannels)
  645. fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
  646. try {
  647. //audio net buffers
  648. if (fParams.fSendAudioChannels) {
  649. switch (fParams.fSampleEncoder) {
  650. case JackFloatEncoder:
  651. fNetAudioCaptureBuffer = new NetFloatAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
  652. break;
  653. case JackIntEncoder:
  654. fNetAudioCaptureBuffer = new NetIntAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
  655. break;
  656. case JackCeltEncoder:
  657. #ifdef CELT
  658. fNetAudioCaptureBuffer = new NetCeltAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData, fParams.fKBps );
  659. #endif
  660. break;
  661. }
  662. }
  663. if (fParams.fReturnAudioChannels) {
  664. switch (fParams.fSampleEncoder) {
  665. case JackFloatEncoder:
  666. fNetAudioPlaybackBuffer = new NetFloatAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
  667. break;
  668. case JackIntEncoder:
  669. fNetAudioPlaybackBuffer = new NetIntAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData);
  670. break;
  671. case JackCeltEncoder:
  672. #ifdef CELT
  673. fNetAudioPlaybackBuffer = new NetCeltAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData, fParams.fKBps );
  674. #endif
  675. break;
  676. }
  677. }
  678. } catch (exception&) {
  679. jack_error("NetAudioBuffer allocation error...");
  680. return false;
  681. }
  682. //set the new buffer sizes
  683. if ( SetNetBufferSize() == SOCKET_ERROR ) {
  684. jack_error ( "Can't set net buffer sizes : %s", StrError ( NET_ERROR_CODE ) );
  685. goto error;
  686. }
  687. return true;
  688. error:
  689. FreeNetworkBuffers();
  690. return false;
  691. }
  692. int JackNetSlaveInterface::Recv(size_t size, int flags)
  693. {
  694. int rx_bytes = fSocket.Recv(fRxBuffer, size, flags);
  695. //handle errors
  696. if ( rx_bytes == SOCKET_ERROR )
  697. {
  698. net_error_t error = fSocket.GetError();
  699. //no data isn't really an error in realtime processing, so just return 0
  700. if ( error == NET_NO_DATA ) {
  701. jack_error ( "No data, is the master still running ?" );
  702. //if a network error occurs, this exception will restart the driver
  703. } else if ( error == NET_CONN_ERROR ) {
  704. jack_error ( "Connection lost." );
  705. throw JackNetException();
  706. } else {
  707. jack_error ( "Fatal error in slave receive : %s", StrError ( NET_ERROR_CODE ) );
  708. }
  709. }
  710. packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
  711. PacketHeaderNToH(header, header);
  712. return rx_bytes;
  713. }
  714. int JackNetSlaveInterface::Send(size_t size, int flags)
  715. {
  716. packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
  717. PacketHeaderHToN(header, header);
  718. int tx_bytes = fSocket.Send ( fTxBuffer, size, flags );
  719. //handle errors
  720. if ( tx_bytes == SOCKET_ERROR )
  721. {
  722. net_error_t error = fSocket.GetError();
  723. //if a network error occurs, this exception will restart the driver
  724. if ( error == NET_CONN_ERROR ) {
  725. jack_error ( "Connection lost." );
  726. throw JackNetException();
  727. } else {
  728. jack_error ( "Fatal error in slave send : %s", StrError ( NET_ERROR_CODE ) );
  729. }
  730. }
  731. return tx_bytes;
  732. }
  733. int JackNetSlaveInterface::SyncRecv()
  734. {
  735. int rx_bytes = 0;
  736. packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
  737. //receive sync (launch the cycle)
  738. do
  739. {
  740. rx_bytes = Recv(HEADER_SIZE, 0);
  741. //connection issue, send will detect it, so don't skip the cycle (return 0)
  742. if ( rx_bytes == SOCKET_ERROR )
  743. return rx_bytes;
  744. }
  745. while ((strcmp(rx_head->fPacketType, "header") != 0) && (rx_head->fDataType != 's'));
  746. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  747. return rx_bytes;
  748. }
  749. int JackNetSlaveInterface::DataRecv()
  750. {
  751. int rx_bytes = 0;
  752. uint recvd_midi_pckt = 0;
  753. uint recvd_audio_pckt = 0;
  754. packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
  755. while ( !fRxHeader.fIsLastPckt )
  756. {
  757. //how much data is queued on the rx buffer ?
  758. rx_bytes = Recv(HEADER_SIZE, MSG_PEEK);
  759. //error here, problem with recv, just skip the cycle (return -1)
  760. if ( rx_bytes == SOCKET_ERROR )
  761. return rx_bytes;
  762. if ( rx_bytes && ( rx_head->fDataStream == 's' ) && ( rx_head->fID == fParams.fID ) )
  763. {
  764. switch ( rx_head->fDataType )
  765. {
  766. case 'm': //midi
  767. rx_bytes = Recv(rx_head->fPacketSize, 0);
  768. fRxHeader.fCycle = rx_head->fCycle;
  769. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  770. fNetMidiCaptureBuffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
  771. // Last midi packet is received, so finish rendering...
  772. if (++recvd_midi_pckt == rx_head->fNumPacket)
  773. fNetMidiCaptureBuffer->RenderToJackPorts();
  774. break;
  775. case 'a': //audio
  776. rx_bytes = Recv(rx_head->fPacketSize, 0);
  777. fRxHeader.fCycle = rx_head->fCycle;
  778. fRxHeader.fSubCycle = rx_head->fSubCycle;
  779. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  780. fNetAudioCaptureBuffer->RenderFromNetwork (rx_head->fCycle, rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
  781. // Last audio packet is received, so finish rendering...
  782. if (fRxHeader.fIsLastPckt)
  783. fNetAudioCaptureBuffer->RenderToJackPorts();
  784. break;
  785. case 's': //sync
  786. jack_info ( "NetSlave : overloaded, skipping receive." );
  787. // TODO : finish midi and audio rendering ?
  788. fNetAudioCaptureBuffer->RenderToJackPorts();
  789. return 0;
  790. }
  791. }
  792. }
  793. fRxHeader.fCycle = rx_head->fCycle;
  794. return 0;
  795. }
  796. int JackNetSlaveInterface::SyncSend()
  797. {
  798. //tx header
  799. if ( fParams.fSlaveSyncMode ) {
  800. fTxHeader.fCycle = fRxHeader.fCycle;
  801. } else {
  802. fTxHeader.fCycle++;
  803. }
  804. fTxHeader.fSubCycle = 0;
  805. fTxHeader.fDataType = 's';
  806. fTxHeader.fIsLastPckt = (fParams.fReturnMidiChannels == 0 && fParams.fReturnAudioChannels == 0) ? 1 : 0;
  807. fTxHeader.fPacketSize = HEADER_SIZE;
  808. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  809. return Send (fTxHeader.fPacketSize, 0);
  810. }
  811. int JackNetSlaveInterface::DataSend()
  812. {
  813. uint subproc;
  814. uint data_size;
  815. //midi
  816. if (fParams.fReturnMidiChannels > 0)
  817. {
  818. //set global header fields and get the number of midi packets
  819. fTxHeader.fDataType = 'm';
  820. data_size = fNetMidiPlaybackBuffer->RenderFromJackPorts();
  821. fTxHeader.fNumPacket = fNetMidiPlaybackBuffer->GetNumPackets();
  822. for ( subproc = 0; subproc < fTxHeader.fNumPacket; subproc++ )
  823. {
  824. fTxHeader.fSubCycle = subproc;
  825. fTxHeader.fIsLastPckt = ((subproc == (fTxHeader.fNumPacket - 1)) && !fParams.fReturnAudioChannels) ? 1 : 0;
  826. fTxHeader.fPacketSize = HEADER_SIZE + fNetMidiPlaybackBuffer->RenderToNetwork(subproc, data_size);
  827. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  828. if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
  829. return SOCKET_ERROR;
  830. }
  831. }
  832. //audio
  833. if ( fParams.fReturnAudioChannels > 0)
  834. {
  835. fTxHeader.fDataType = 'a';
  836. data_size = fNetAudioPlaybackBuffer->RenderFromJackPorts();
  837. fTxHeader.fNumPacket = fNetAudioPlaybackBuffer->GetNumPackets();
  838. for ( subproc = 0; subproc < fTxHeader.fNumPacket; subproc++ )
  839. {
  840. fTxHeader.fSubCycle = subproc;
  841. fTxHeader.fIsLastPckt = (subproc == (fTxHeader.fNumPacket - 1)) ? 1 : 0;
  842. fTxHeader.fPacketSize = HEADER_SIZE + fNetAudioPlaybackBuffer->RenderToNetwork(subproc, data_size);
  843. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  844. if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
  845. return SOCKET_ERROR;
  846. }
  847. }
  848. return 0;
  849. }
  850. //network sync------------------------------------------------------------------------
  851. void JackNetSlaveInterface::EncodeSyncPacket()
  852. {
  853. //this method contains every step of sync packet informations coding
  854. //first of all, reset sync packet
  855. memset ( fTxData, 0, PACKET_AVAILABLE_SIZE );
  856. //then first step : transport
  857. if (fParams.fTransportSync) {
  858. EncodeTransportData();
  859. TransportDataHToN( &fReturnTransportData, &fReturnTransportData);
  860. //copy to TxBuffer
  861. memcpy ( fTxData, &fReturnTransportData, sizeof ( net_transport_data_t ) );
  862. }
  863. //then others
  864. //...
  865. }
  866. void JackNetSlaveInterface::DecodeSyncPacket()
  867. {
  868. //this method contains every step of sync packet informations decoding process
  869. //first : transport
  870. if (fParams.fTransportSync) {
  871. //copy received transport data to transport data structure
  872. memcpy ( &fSendTransportData, fRxData, sizeof ( net_transport_data_t ) );
  873. TransportDataNToH( &fSendTransportData, &fSendTransportData);
  874. DecodeTransportData();
  875. }
  876. //then others
  877. //...
  878. }
  879. }