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.

1028 lines
35KB

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