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
40KB

  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. }
  418. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  419. return rx_bytes;
  420. }
  421. int JackNetMasterInterface::DataRecv()
  422. {
  423. int rx_bytes = 0;
  424. uint recvd_midi_pckt = 0;
  425. uint recvd_audio_pckt = 0;
  426. packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
  427. while ( !fRxHeader.fIsLastPckt )
  428. {
  429. //how much data is queued on the rx buffer ?
  430. rx_bytes = Recv(HEADER_SIZE, MSG_PEEK);
  431. //error here, problem with recv, just skip the cycle (return -1)
  432. if ( rx_bytes == SOCKET_ERROR )
  433. return rx_bytes;
  434. if ( rx_bytes && ( rx_head->fDataStream == 'r' ) && ( rx_head->fID == fParams.fID ) )
  435. {
  436. //read data
  437. switch ( rx_head->fDataType )
  438. {
  439. case 'm': //midi
  440. rx_bytes = Recv(rx_head->fPacketSize, 0);
  441. fRxHeader.fCycle = rx_head->fCycle;
  442. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  443. fNetMidiPlaybackBuffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
  444. // Last midi packet is received, so finish rendering...
  445. if (++recvd_midi_pckt == rx_head->fNumPacket)
  446. fNetMidiPlaybackBuffer->RenderToJackPorts();
  447. break;
  448. case 'a': //audio
  449. rx_bytes = Recv(rx_head->fPacketSize, 0);
  450. fRxHeader.fCycle = rx_head->fCycle;
  451. fRxHeader.fSubCycle = rx_head->fSubCycle;
  452. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  453. fNetAudioPlaybackBuffer->RenderFromNetwork(rx_head->fCycle, rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
  454. // Last audio packet is received, so finish rendering...
  455. if (fRxHeader.fIsLastPckt)
  456. fNetAudioPlaybackBuffer->RenderToJackPorts();
  457. break;
  458. case 's': //sync
  459. jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
  460. // TODO : finish midi and audio rendering ?
  461. fNetAudioPlaybackBuffer->RenderToJackPorts();
  462. return 0;
  463. }
  464. }
  465. }
  466. return rx_bytes;
  467. }
  468. void JackNetMasterInterface::EncodeSyncPacket()
  469. {
  470. //this method contains every step of sync packet informations coding
  471. //first of all, reset sync packet
  472. memset ( fTxData, 0, PACKET_AVAILABLE_SIZE );
  473. //then, first step : transport
  474. if (fParams.fTransportSync) {
  475. EncodeTransportData();
  476. TransportDataHToN( &fSendTransportData, &fSendTransportData);
  477. //copy to TxBuffer
  478. memcpy ( fTxData, &fSendTransportData, sizeof ( net_transport_data_t ) );
  479. }
  480. //then others (freewheel etc.)
  481. //...
  482. }
  483. void JackNetMasterInterface::DecodeSyncPacket()
  484. {
  485. //this method contains every step of sync packet informations decoding process
  486. //first : transport
  487. if (fParams.fTransportSync) {
  488. //copy received transport data to transport data structure
  489. memcpy ( &fReturnTransportData, fRxData, sizeof ( net_transport_data_t ) );
  490. TransportDataNToH( &fReturnTransportData, &fReturnTransportData);
  491. DecodeTransportData();
  492. }
  493. //then others
  494. //...
  495. }
  496. // JackNetSlaveInterface ************************************************************************************************
  497. uint JackNetSlaveInterface::fSlaveCounter = 0;
  498. bool JackNetSlaveInterface::Init()
  499. {
  500. jack_log ( "JackNetSlaveInterface::Init()" );
  501. //set the parameters to send
  502. strcpy ( fParams.fPacketType, "params" );
  503. fParams.fProtocolVersion = SLAVE_PROTOCOL;
  504. SetPacketType ( &fParams, SLAVE_AVAILABLE );
  505. //init loop : get a master and start, do it until connection is ok
  506. net_status_t status;
  507. do
  508. {
  509. //first, get a master, do it until a valid connection is running
  510. do
  511. {
  512. status = SendAvailableToMaster();
  513. if ( status == NET_SOCKET_ERROR )
  514. return false;
  515. }
  516. while ( status != NET_CONNECTED );
  517. //then tell the master we are ready
  518. jack_info ( "Initializing connection with %s...", fParams.fMasterNetName );
  519. status = SendStartToMaster();
  520. if ( status == NET_ERROR )
  521. return false;
  522. }
  523. while ( status != NET_ROLLING );
  524. return true;
  525. }
  526. // Separate the connection protocol into two separated step
  527. bool JackNetSlaveInterface::InitConnection(int time_out)
  528. {
  529. jack_log("JackNetSlaveInterface::InitConnection()");
  530. int try_count = (time_out > 0) ? ((1000000 * time_out) / SLAVE_INIT_TIMEOUT) : LONG_MAX;
  531. //set the parameters to send
  532. strcpy (fParams.fPacketType, "params");
  533. fParams.fProtocolVersion = SLAVE_PROTOCOL;
  534. SetPacketType (&fParams, SLAVE_AVAILABLE);
  535. net_status_t status;
  536. do
  537. {
  538. //get a master
  539. status = SendAvailableToMaster(try_count);
  540. if (status == NET_SOCKET_ERROR)
  541. return false;
  542. }
  543. while (status != NET_CONNECTED && --try_count > 0);
  544. return (try_count != 0);
  545. }
  546. bool JackNetSlaveInterface::InitRendering()
  547. {
  548. jack_log("JackNetSlaveInterface::InitRendering()");
  549. net_status_t status;
  550. do
  551. {
  552. //then tell the master we are ready
  553. jack_info("Initializing connection with %s...", fParams.fMasterNetName);
  554. status = SendStartToMaster();
  555. if (status == NET_ERROR)
  556. return false;
  557. }
  558. while (status != NET_ROLLING);
  559. return true;
  560. }
  561. net_status_t JackNetSlaveInterface::SendAvailableToMaster(long try_count)
  562. {
  563. jack_log ( "JackNetSlaveInterface::SendAvailableToMaster()" );
  564. //utility
  565. session_params_t host_params;
  566. int rx_bytes = 0;
  567. //socket
  568. if ( fSocket.NewSocket() == SOCKET_ERROR ) {
  569. jack_error ( "Fatal error : network unreachable - %s", StrError ( NET_ERROR_CODE ) );
  570. return NET_SOCKET_ERROR;
  571. }
  572. //bind the socket
  573. if ( fSocket.Bind() == SOCKET_ERROR ) {
  574. jack_error ( "Can't bind the socket : %s", StrError ( NET_ERROR_CODE ) );
  575. return NET_SOCKET_ERROR;
  576. }
  577. //timeout on receive
  578. if ( fSocket.SetTimeOut ( SLAVE_INIT_TIMEOUT ) == SOCKET_ERROR )
  579. jack_error ( "Can't set timeout : %s", StrError ( NET_ERROR_CODE ) );
  580. //disable local loop
  581. if ( fSocket.SetLocalLoop() == SOCKET_ERROR )
  582. jack_error ( "Can't disable multicast loop : %s", StrError ( NET_ERROR_CODE ) );
  583. //send 'AVAILABLE' until 'SLAVE_SETUP' received
  584. jack_info ( "Waiting for a master..." );
  585. do
  586. {
  587. //send 'available'
  588. session_params_t net_params;
  589. memset(&net_params, 0, sizeof ( session_params_t ));
  590. SessionParamsHToN(&fParams, &net_params);
  591. if ( fSocket.SendTo ( &net_params, sizeof ( session_params_t ), 0, fMulticastIP ) == SOCKET_ERROR )
  592. jack_error ( "Error in data send : %s", StrError ( NET_ERROR_CODE ) );
  593. //filter incoming packets : don't exit while no error is detected
  594. memset(&net_params, 0, sizeof ( session_params_t ));
  595. rx_bytes = fSocket.CatchHost ( &net_params, sizeof ( session_params_t ), 0 );
  596. SessionParamsNToH(&net_params, &host_params);
  597. if ( ( rx_bytes == SOCKET_ERROR ) && ( fSocket.GetError() != NET_NO_DATA ) )
  598. {
  599. jack_error ( "Can't receive : %s", StrError ( NET_ERROR_CODE ) );
  600. return NET_RECV_ERROR;
  601. }
  602. }
  603. while (strcmp(host_params.fPacketType, fParams.fPacketType) && (GetPacketType(&host_params) != SLAVE_SETUP) && (--try_count > 0));
  604. // Time out failure..
  605. if (try_count == 0) {
  606. jack_error("Time out error in connect");
  607. return NET_CONNECT_ERROR;
  608. }
  609. //everything is OK, copy parameters
  610. SessionParamsDisplay(&host_params);
  611. fParams = host_params;
  612. //connect the socket
  613. if (fSocket.Connect() == SOCKET_ERROR) {
  614. jack_error("Error in connect : %s", StrError(NET_ERROR_CODE));
  615. return NET_CONNECT_ERROR;
  616. }
  617. return NET_CONNECTED;
  618. }
  619. net_status_t JackNetSlaveInterface::SendStartToMaster()
  620. {
  621. jack_log("JackNetSlaveInterface::SendStartToMaster");
  622. //tell the master to start
  623. session_params_t net_params;
  624. memset(&net_params, 0, sizeof ( session_params_t ));
  625. SetPacketType ( &fParams, START_MASTER );
  626. SessionParamsHToN(&fParams, &net_params);
  627. if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR)
  628. {
  629. jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
  630. return (fSocket.GetError() == NET_CONN_ERROR) ? NET_ERROR : NET_SEND_ERROR;
  631. }
  632. return NET_ROLLING;
  633. }
  634. bool JackNetSlaveInterface::SetParams()
  635. {
  636. jack_log ( "JackNetSlaveInterface::SetParams" );
  637. JackNetInterface::SetParams();
  638. fTxHeader.fDataStream = 'r';
  639. fRxHeader.fDataStream = 's';
  640. //midi net buffers
  641. if (fParams.fSendMidiChannels)
  642. fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fTxData);
  643. if (fParams.fReturnMidiChannels)
  644. fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
  645. try {
  646. //audio net buffers
  647. if (fParams.fSendAudioChannels) {
  648. switch (fParams.fSampleEncoder) {
  649. case JackFloatEncoder:
  650. fNetAudioCaptureBuffer = new NetFloatAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
  651. break;
  652. case JackIntEncoder:
  653. fNetAudioCaptureBuffer = new NetIntAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData );
  654. break;
  655. case JackCeltEncoder:
  656. #ifdef CELT
  657. fNetAudioCaptureBuffer = new NetCeltAudioBuffer ( &fParams, fParams.fSendAudioChannels, fRxData, fParams.fKBps );
  658. #endif
  659. break;
  660. }
  661. }
  662. if (fParams.fReturnAudioChannels) {
  663. switch (fParams.fSampleEncoder) {
  664. case JackFloatEncoder:
  665. fNetAudioPlaybackBuffer = new NetFloatAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData );
  666. break;
  667. case JackIntEncoder:
  668. fNetAudioPlaybackBuffer = new NetIntAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData);
  669. break;
  670. case JackCeltEncoder:
  671. #ifdef CELT
  672. fNetAudioPlaybackBuffer = new NetCeltAudioBuffer ( &fParams, fParams.fReturnAudioChannels, fTxData, fParams.fKBps );
  673. #endif
  674. break;
  675. }
  676. }
  677. } catch (exception&) {
  678. jack_error("NetAudioBuffer allocation error...");
  679. return false;
  680. }
  681. //set the new buffer sizes
  682. if ( SetNetBufferSize() == SOCKET_ERROR ) {
  683. jack_error ( "Can't set net buffer sizes : %s", StrError ( NET_ERROR_CODE ) );
  684. goto error;
  685. }
  686. return true;
  687. error:
  688. FreeNetworkBuffers();
  689. return false;
  690. }
  691. int JackNetSlaveInterface::Recv(size_t size, int flags)
  692. {
  693. int rx_bytes = fSocket.Recv(fRxBuffer, size, flags);
  694. //handle errors
  695. if ( rx_bytes == SOCKET_ERROR )
  696. {
  697. net_error_t error = fSocket.GetError();
  698. //no data isn't really an error in realtime processing, so just return 0
  699. if ( error == NET_NO_DATA ) {
  700. jack_error ( "No data, is the master still running ?" );
  701. //if a network error occurs, this exception will restart the driver
  702. } else if ( error == NET_CONN_ERROR ) {
  703. jack_error ( "Connection lost." );
  704. throw JackNetException();
  705. } else {
  706. jack_error ( "Fatal error in slave receive : %s", StrError ( NET_ERROR_CODE ) );
  707. }
  708. }
  709. packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
  710. PacketHeaderNToH(header, header);
  711. return rx_bytes;
  712. }
  713. int JackNetSlaveInterface::Send(size_t size, int flags)
  714. {
  715. packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
  716. PacketHeaderHToN(header, header);
  717. int tx_bytes = fSocket.Send ( fTxBuffer, size, flags );
  718. //handle errors
  719. if ( tx_bytes == SOCKET_ERROR )
  720. {
  721. net_error_t error = fSocket.GetError();
  722. //if a network error occurs, this exception will restart the driver
  723. if ( error == NET_CONN_ERROR ) {
  724. jack_error ( "Connection lost." );
  725. throw JackNetException();
  726. } else {
  727. jack_error ( "Fatal error in slave send : %s", StrError ( NET_ERROR_CODE ) );
  728. }
  729. }
  730. return tx_bytes;
  731. }
  732. int JackNetSlaveInterface::SyncRecv()
  733. {
  734. int rx_bytes = 0;
  735. packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
  736. //receive sync (launch the cycle)
  737. do
  738. {
  739. rx_bytes = Recv(HEADER_SIZE, 0);
  740. //connection issue, send will detect it, so don't skip the cycle (return 0)
  741. if ( rx_bytes == SOCKET_ERROR )
  742. return rx_bytes;
  743. }
  744. while ((strcmp(rx_head->fPacketType, "header") != 0) && (rx_head->fDataType != 's'));
  745. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  746. return rx_bytes;
  747. }
  748. int JackNetSlaveInterface::DataRecv()
  749. {
  750. int rx_bytes = 0;
  751. uint recvd_midi_pckt = 0;
  752. uint recvd_audio_pckt = 0;
  753. packet_header_t* rx_head = reinterpret_cast<packet_header_t*> ( fRxBuffer );
  754. while ( !fRxHeader.fIsLastPckt )
  755. {
  756. //how much data is queued on the rx buffer ?
  757. rx_bytes = Recv(HEADER_SIZE, MSG_PEEK);
  758. //error here, problem with recv, just skip the cycle (return -1)
  759. if ( rx_bytes == SOCKET_ERROR )
  760. return rx_bytes;
  761. if ( rx_bytes && ( rx_head->fDataStream == 's' ) && ( rx_head->fID == fParams.fID ) )
  762. {
  763. switch ( rx_head->fDataType )
  764. {
  765. case 'm': //midi
  766. rx_bytes = Recv(rx_head->fPacketSize, 0);
  767. fRxHeader.fCycle = rx_head->fCycle;
  768. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  769. fNetMidiCaptureBuffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
  770. // Last midi packet is received, so finish rendering...
  771. if (++recvd_midi_pckt == rx_head->fNumPacket)
  772. fNetMidiCaptureBuffer->RenderToJackPorts();
  773. break;
  774. case 'a': //audio
  775. rx_bytes = Recv(rx_head->fPacketSize, 0);
  776. fRxHeader.fCycle = rx_head->fCycle;
  777. fRxHeader.fSubCycle = rx_head->fSubCycle;
  778. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  779. fNetAudioCaptureBuffer->RenderFromNetwork (rx_head->fCycle, rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
  780. // Last audio packet is received, so finish rendering...
  781. if (fRxHeader.fIsLastPckt)
  782. fNetAudioCaptureBuffer->RenderToJackPorts();
  783. break;
  784. case 's': //sync
  785. jack_info ( "NetSlave : overloaded, skipping receive." );
  786. // TODO : finish midi and audio rendering ?
  787. fNetAudioCaptureBuffer->RenderToJackPorts();
  788. return 0;
  789. }
  790. }
  791. }
  792. fRxHeader.fCycle = rx_head->fCycle;
  793. return 0;
  794. }
  795. int JackNetSlaveInterface::SyncSend()
  796. {
  797. //tx header
  798. if ( fParams.fSlaveSyncMode ) {
  799. fTxHeader.fCycle = fRxHeader.fCycle;
  800. } else {
  801. fTxHeader.fCycle++;
  802. }
  803. fTxHeader.fSubCycle = 0;
  804. fTxHeader.fDataType = 's';
  805. fTxHeader.fIsLastPckt = (fParams.fReturnMidiChannels == 0 && fParams.fReturnAudioChannels == 0) ? 1 : 0;
  806. fTxHeader.fPacketSize = HEADER_SIZE;
  807. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  808. return Send (fTxHeader.fPacketSize, 0);
  809. }
  810. int JackNetSlaveInterface::DataSend()
  811. {
  812. uint subproc;
  813. uint data_size;
  814. //midi
  815. if (fParams.fReturnMidiChannels > 0)
  816. {
  817. //set global header fields and get the number of midi packets
  818. fTxHeader.fDataType = 'm';
  819. data_size = fNetMidiPlaybackBuffer->RenderFromJackPorts();
  820. fTxHeader.fNumPacket = fNetMidiPlaybackBuffer->GetNumPackets();
  821. for ( subproc = 0; subproc < fTxHeader.fNumPacket; subproc++ )
  822. {
  823. fTxHeader.fSubCycle = subproc;
  824. fTxHeader.fIsLastPckt = ((subproc == (fTxHeader.fNumPacket - 1)) && !fParams.fReturnAudioChannels) ? 1 : 0;
  825. fTxHeader.fPacketSize = HEADER_SIZE + fNetMidiPlaybackBuffer->RenderToNetwork(subproc, data_size);
  826. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  827. if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
  828. return SOCKET_ERROR;
  829. }
  830. }
  831. //audio
  832. if ( fParams.fReturnAudioChannels > 0)
  833. {
  834. fTxHeader.fDataType = 'a';
  835. data_size = fNetAudioPlaybackBuffer->RenderFromJackPorts();
  836. fTxHeader.fNumPacket = fNetAudioPlaybackBuffer->GetNumPackets();
  837. for ( subproc = 0; subproc < fTxHeader.fNumPacket; subproc++ )
  838. {
  839. fTxHeader.fSubCycle = subproc;
  840. fTxHeader.fIsLastPckt = (subproc == (fTxHeader.fNumPacket - 1)) ? 1 : 0;
  841. fTxHeader.fPacketSize = HEADER_SIZE + fNetAudioPlaybackBuffer->RenderToNetwork(subproc, data_size);
  842. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  843. if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR)
  844. return SOCKET_ERROR;
  845. }
  846. }
  847. return 0;
  848. }
  849. //network sync------------------------------------------------------------------------
  850. void JackNetSlaveInterface::EncodeSyncPacket()
  851. {
  852. //this method contains every step of sync packet informations coding
  853. //first of all, reset sync packet
  854. memset ( fTxData, 0, PACKET_AVAILABLE_SIZE );
  855. //then first step : transport
  856. if (fParams.fTransportSync) {
  857. EncodeTransportData();
  858. TransportDataHToN( &fReturnTransportData, &fReturnTransportData);
  859. //copy to TxBuffer
  860. memcpy ( fTxData, &fReturnTransportData, sizeof ( net_transport_data_t ) );
  861. }
  862. //then others
  863. //...
  864. }
  865. void JackNetSlaveInterface::DecodeSyncPacket()
  866. {
  867. //this method contains every step of sync packet informations decoding process
  868. //first : transport
  869. if (fParams.fTransportSync) {
  870. //copy received transport data to transport data structure
  871. memcpy ( &fSendTransportData, fRxData, sizeof ( net_transport_data_t ) );
  872. TransportDataNToH( &fSendTransportData, &fSendTransportData);
  873. DecodeTransportData();
  874. }
  875. //then others
  876. //...
  877. }
  878. }