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.

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