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.

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