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.

1045 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 timeout for the socket
  298. //float time = 3 * 1000000.f * (float(fParams.fPeriodSize) / float(fParams.fSampleRate));
  299. /*
  300. if (fSocket.SetTimeOut(PACKET_TIMEOUT) == SOCKET_ERROR) {
  301. jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
  302. goto error;
  303. }
  304. */
  305. // set the new rx buffer size
  306. if (SetNetBufferSize() == SOCKET_ERROR) {
  307. jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
  308. goto error;
  309. }
  310. return true;
  311. error:
  312. FreeNetworkBuffers();
  313. return false;
  314. }
  315. void JackNetMasterInterface::Exit()
  316. {
  317. jack_log("JackNetMasterInterface::Exit, ID %u", fParams.fID);
  318. // stop process
  319. fRunning = false;
  320. // send a 'multicast euthanasia request' - new socket is required on macosx
  321. jack_info("Exiting '%s'", fParams.fName);
  322. SetPacketType(&fParams, KILL_MASTER);
  323. JackNetSocket mcast_socket(fMulticastIP, fSocket.GetPort());
  324. session_params_t net_params;
  325. memset(&net_params, 0, sizeof(session_params_t));
  326. SessionParamsHToN(&fParams, &net_params);
  327. if (mcast_socket.NewSocket() == SOCKET_ERROR) {
  328. jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
  329. }
  330. if (mcast_socket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR) {
  331. jack_error("Can't send suicide request : %s", StrError(NET_ERROR_CODE));
  332. }
  333. mcast_socket.Close();
  334. }
  335. void JackNetMasterInterface::FatalRecvError()
  336. {
  337. // fatal connection issue, exit
  338. jack_error("Recv connection lost error = %s, '%s' exiting", StrError(NET_ERROR_CODE), fParams.fName);
  339. // ask to the manager to properly remove the master
  340. Exit();
  341. // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
  342. ThreadExit();
  343. }
  344. void JackNetMasterInterface::FatalSendError()
  345. {
  346. // fatal connection issue, exit
  347. jack_error("Send connection lost error = %s, '%s' exiting", StrError(NET_ERROR_CODE), fParams.fName);
  348. // ask to the manager to properly remove the master
  349. Exit();
  350. // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
  351. ThreadExit();
  352. }
  353. int JackNetMasterInterface::Recv(size_t size, int flags)
  354. {
  355. int rx_bytes;
  356. if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
  357. /*
  358. net_error_t error = fSocket.GetError();
  359. // no data isn't really a network error, so just return 0 available read bytes
  360. if (error == NET_NO_DATA) {
  361. return 0;
  362. } else if (error == NET_CONN_ERROR) {
  363. FatalRecvError();
  364. } else {
  365. jack_error("Error in master receive : %s", StrError(NET_ERROR_CODE));
  366. }
  367. */
  368. FatalRecvError();
  369. }
  370. packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
  371. PacketHeaderNToH(header, header);
  372. return rx_bytes;
  373. }
  374. int JackNetMasterInterface::Send(size_t size, int flags)
  375. {
  376. int tx_bytes;
  377. packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
  378. PacketHeaderHToN(header, header);
  379. if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
  380. /*
  381. net_error_t error = fSocket.GetError();
  382. if (error == NET_CONN_ERROR) {
  383. FatalSendError();
  384. } else {
  385. jack_error("Error in master send : %s", StrError(NET_ERROR_CODE));
  386. }
  387. */
  388. FatalSendError();
  389. }
  390. return tx_bytes;
  391. }
  392. bool JackNetMasterInterface::IsSynched()
  393. {
  394. return (fCurrentCycleOffset <= fMaxCycleOffset);
  395. }
  396. int JackNetMasterInterface::SyncSend()
  397. {
  398. SetRcvTimeOut();
  399. fTxHeader.fCycle++;
  400. fTxHeader.fSubCycle = 0;
  401. fTxHeader.fDataType = 's';
  402. fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ? 1 : 0;
  403. fTxHeader.fPacketSize = fParams.fMtu;
  404. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  405. // PacketHeaderDisplay(&fTxHeader);
  406. return Send(fTxHeader.fPacketSize, 0);
  407. }
  408. int JackNetMasterInterface::DataSend()
  409. {
  410. if (MidiSend(fNetMidiCaptureBuffer, fParams.fSendMidiChannels, fParams.fSendAudioChannels) == SOCKET_ERROR) {
  411. return SOCKET_ERROR;
  412. }
  413. return AudioSend(fNetAudioCaptureBuffer, fParams.fSendAudioChannels);
  414. }
  415. int JackNetMasterInterface::SyncRecv()
  416. {
  417. int rx_bytes = 0;
  418. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  419. /*
  420. int rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
  421. if ((rx_bytes == 0) || (rx_bytes == SOCKET_ERROR)) {
  422. // 0 bytes considered an error (lost connection)
  423. return SOCKET_ERROR;
  424. }
  425. fCurrentCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
  426. */
  427. // receive sync (launch the cycle)
  428. do {
  429. rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
  430. // connection issue, send will detect it, so don't skip the cycle (return 0)
  431. if (rx_bytes == SOCKET_ERROR) {
  432. return SOCKET_ERROR;
  433. }
  434. }
  435. while ((strcmp(rx_head->fPacketType, "header") != 0) && (rx_head->fDataType != 's'));
  436. fCurrentCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
  437. if (fCurrentCycleOffset < fMaxCycleOffset) {
  438. jack_info("Synching with latency = %d", fCurrentCycleOffset);
  439. return 0;
  440. } else {
  441. rx_bytes = Recv(rx_head->fPacketSize, 0);
  442. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  443. return rx_bytes;
  444. }
  445. }
  446. int JackNetMasterInterface::DataRecv()
  447. {
  448. int rx_bytes = 0;
  449. uint recvd_midi_pckt = 0;
  450. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  451. while (!fRxHeader.fIsLastPckt) {
  452. // how much data is queued on the rx buffer ?
  453. rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
  454. // error here, problem with recv, just skip the cycle (return -1)
  455. if (rx_bytes == SOCKET_ERROR) {
  456. return rx_bytes;
  457. }
  458. if (rx_bytes && (rx_head->fDataStream == 'r') && (rx_head->fID == fParams.fID)) {
  459. // read data
  460. switch (rx_head->fDataType) {
  461. case 'm': // midi
  462. rx_bytes = MidiRecv(rx_head, fNetMidiPlaybackBuffer, recvd_midi_pckt);
  463. break;
  464. case 'a': // audio
  465. rx_bytes = AudioRecv(rx_head, fNetAudioPlaybackBuffer);
  466. break;
  467. case 's': // sync
  468. jack_info("NetMaster : overloaded, skipping receive from '%s'", fParams.fName);
  469. return FinishRecv(fNetAudioPlaybackBuffer);
  470. }
  471. }
  472. }
  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, clear sync packet
  479. memset(fTxData, 0, PACKET_AVAILABLE_SIZE(&fParams));
  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. // Transport not used for now...
  490. // Write active ports list
  491. fTxHeader.fActivePorts = (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->ActivePortsToNetwork(fTxData) : 0;
  492. }
  493. void JackNetMasterInterface::DecodeSyncPacket()
  494. {
  495. // This method contains every step of sync packet informations decoding process
  496. // first : transport
  497. if (fParams.fTransportSync) {
  498. // copy received transport data to transport data structure
  499. memcpy(&fReturnTransportData, fRxData, sizeof(net_transport_data_t));
  500. TransportDataNToH(&fReturnTransportData, &fReturnTransportData);
  501. DecodeTransportData();
  502. }
  503. // then others
  504. // ...
  505. // Transport not used for now...
  506. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  507. // Read active ports list
  508. if (fNetAudioCaptureBuffer) {
  509. fNetAudioCaptureBuffer->ActivePortsFromNetwork(fRxData, rx_head->fActivePorts);
  510. }
  511. }
  512. // JackNetSlaveInterface ************************************************************************************************
  513. uint JackNetSlaveInterface::fSlaveCounter = 0;
  514. void JackNetSlaveInterface::InitAPI()
  515. {
  516. // open Socket API with the first slave
  517. if (fSlaveCounter++ == 0) {
  518. if (SocketAPIInit() < 0) {
  519. jack_error("Can't init Socket API, exiting...");
  520. throw std::bad_alloc();
  521. }
  522. }
  523. }
  524. bool JackNetSlaveInterface::Init()
  525. {
  526. jack_log("JackNetSlaveInterface::Init()");
  527. // set the parameters to send
  528. strcpy(fParams.fPacketType, "params");
  529. fParams.fProtocolVersion = SLAVE_PROTOCOL;
  530. SetPacketType(&fParams, SLAVE_AVAILABLE);
  531. // init loop : get a master and start, do it until connection is ok
  532. net_status_t status;
  533. do {
  534. // first, get a master, do it until a valid connection is running
  535. do {
  536. status = SendAvailableToMaster();
  537. if (status == NET_SOCKET_ERROR) {
  538. return false;
  539. }
  540. }
  541. while (status != NET_CONNECTED);
  542. // then tell the master we are ready
  543. jack_info("Initializing connection with %s...", fParams.fMasterNetName);
  544. status = SendStartToMaster();
  545. if (status == NET_ERROR) {
  546. return false;
  547. }
  548. }
  549. while (status != NET_ROLLING);
  550. return true;
  551. }
  552. // Separate the connection protocol into two separated step
  553. bool JackNetSlaveInterface::InitConnection(int time_out_sec)
  554. {
  555. jack_log("JackNetSlaveInterface::InitConnection()");
  556. uint try_count = (time_out_sec > 0) ? ((1000000 * time_out_sec) / SLAVE_INIT_TIMEOUT) : LONG_MAX;
  557. // set the parameters to send
  558. strcpy(fParams.fPacketType, "params");
  559. fParams.fProtocolVersion = SLAVE_PROTOCOL;
  560. SetPacketType(&fParams, SLAVE_AVAILABLE);
  561. net_status_t status;
  562. do {
  563. // get a master
  564. status = SendAvailableToMaster(try_count);
  565. if (status == NET_SOCKET_ERROR) {
  566. return false;
  567. }
  568. }
  569. while (status != NET_CONNECTED && --try_count > 0);
  570. return (try_count != 0);
  571. }
  572. bool JackNetSlaveInterface::InitRendering()
  573. {
  574. jack_log("JackNetSlaveInterface::InitRendering()");
  575. net_status_t status;
  576. do {
  577. // then tell the master we are ready
  578. jack_info("Initializing connection with %s...", fParams.fMasterNetName);
  579. status = SendStartToMaster();
  580. if (status == NET_ERROR)
  581. return false;
  582. }
  583. while (status != NET_ROLLING);
  584. return true;
  585. }
  586. net_status_t JackNetSlaveInterface::SendAvailableToMaster(long try_count)
  587. {
  588. jack_log("JackNetSlaveInterface::SendAvailableToMaster()");
  589. // utility
  590. session_params_t host_params;
  591. int rx_bytes = 0;
  592. // socket
  593. if (fSocket.NewSocket() == SOCKET_ERROR) {
  594. jack_error("Fatal error : network unreachable - %s", StrError(NET_ERROR_CODE));
  595. return NET_SOCKET_ERROR;
  596. }
  597. if (fSocket.IsLocal(fMulticastIP)) {
  598. jack_info("Local IP is used...");
  599. } else {
  600. // bind the socket
  601. if (fSocket.Bind() == SOCKET_ERROR) {
  602. jack_error("Can't bind the socket : %s", StrError(NET_ERROR_CODE));
  603. return NET_SOCKET_ERROR;
  604. }
  605. }
  606. // timeout on receive (for init)
  607. if (fSocket.SetTimeOut(SLAVE_INIT_TIMEOUT) == SOCKET_ERROR) {
  608. jack_error("Can't set init timeout : %s", StrError(NET_ERROR_CODE));
  609. }
  610. // disable local loop
  611. if (fSocket.SetLocalLoop() == SOCKET_ERROR) {
  612. jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
  613. }
  614. // send 'AVAILABLE' until 'SLAVE_SETUP' received
  615. jack_info("Waiting for a master...");
  616. do {
  617. // send 'available'
  618. session_params_t net_params;
  619. memset(&net_params, 0, sizeof(session_params_t));
  620. SessionParamsHToN(&fParams, &net_params);
  621. if (fSocket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR)
  622. jack_error("Error in data send : %s", StrError(NET_ERROR_CODE));
  623. // filter incoming packets : don't exit while no error is detected
  624. memset(&net_params, 0, sizeof(session_params_t));
  625. rx_bytes = fSocket.CatchHost(&net_params, sizeof(session_params_t), 0);
  626. SessionParamsNToH(&net_params, &host_params);
  627. if ((rx_bytes == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
  628. jack_error("Can't receive : %s", StrError(NET_ERROR_CODE));
  629. return NET_RECV_ERROR;
  630. }
  631. }
  632. while (strcmp(host_params.fPacketType, fParams.fPacketType) && (GetPacketType(&host_params) != SLAVE_SETUP) && (--try_count > 0));
  633. // Time out failure..
  634. if (try_count == 0) {
  635. jack_error("Time out error in connect");
  636. return NET_CONNECT_ERROR;
  637. }
  638. // everything is OK, copy parameters
  639. fParams = host_params;
  640. // connect the socket
  641. if (fSocket.Connect() == SOCKET_ERROR) {
  642. jack_error("Error in connect : %s", StrError(NET_ERROR_CODE));
  643. return NET_CONNECT_ERROR;
  644. }
  645. return NET_CONNECTED;
  646. }
  647. net_status_t JackNetSlaveInterface::SendStartToMaster()
  648. {
  649. jack_log("JackNetSlaveInterface::SendStartToMaster");
  650. // tell the master to start
  651. session_params_t net_params;
  652. memset(&net_params, 0, sizeof(session_params_t));
  653. SetPacketType(&fParams, START_MASTER);
  654. SessionParamsHToN(&fParams, &net_params);
  655. if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
  656. jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
  657. return (fSocket.GetError() == NET_CONN_ERROR) ? NET_ERROR : NET_SEND_ERROR;
  658. }
  659. return NET_ROLLING;
  660. }
  661. bool JackNetSlaveInterface::SetParams()
  662. {
  663. jack_log("JackNetSlaveInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
  664. fParams.fSendAudioChannels, fParams.fReturnAudioChannels,
  665. fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
  666. JackNetInterface::SetParams();
  667. fTxHeader.fDataStream = 'r';
  668. fRxHeader.fDataStream = 's';
  669. // midi net buffers
  670. if (fParams.fSendMidiChannels > 0) {
  671. fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fRxData);
  672. }
  673. if (fParams.fReturnMidiChannels > 0) {
  674. fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fTxData);
  675. }
  676. try {
  677. // audio net buffers
  678. if (fParams.fSendAudioChannels > 0) {
  679. fNetAudioCaptureBuffer = AudioBufferFactory(fParams.fSendAudioChannels, fRxData);
  680. assert(fNetAudioCaptureBuffer);
  681. }
  682. if (fParams.fReturnAudioChannels > 0) {
  683. fNetAudioPlaybackBuffer = AudioBufferFactory(fParams.fReturnAudioChannels, fTxData);
  684. assert(fNetAudioPlaybackBuffer);
  685. }
  686. } catch (exception&) {
  687. jack_error("NetAudioBuffer allocation error...");
  688. return false;
  689. }
  690. /*
  691. if (fSocket.SetTimeOut(PACKET_TIMEOUT) == SOCKET_ERROR) {
  692. jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
  693. goto error;
  694. }
  695. */
  696. // set the new buffer sizes
  697. if (SetNetBufferSize() == SOCKET_ERROR) {
  698. jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
  699. goto error;
  700. }
  701. return true;
  702. error:
  703. FreeNetworkBuffers();
  704. return false;
  705. }
  706. void JackNetSlaveInterface::FatalRecvError()
  707. {
  708. jack_error("Recv connection lost error = %s", StrError(NET_ERROR_CODE));
  709. throw JackNetException();
  710. }
  711. void JackNetSlaveInterface::FatalSendError()
  712. {
  713. jack_error("Send connection lost error = %s", StrError(NET_ERROR_CODE));
  714. throw JackNetException();
  715. }
  716. int JackNetSlaveInterface::Recv(size_t size, int flags)
  717. {
  718. int rx_bytes = fSocket.Recv(fRxBuffer, size, flags);
  719. // handle errors
  720. if (rx_bytes == SOCKET_ERROR) {
  721. /*
  722. net_error_t error = fSocket.GetError();
  723. // no data isn't really an error in realtime processing, so just return 0
  724. if (error == NET_NO_DATA) {
  725. jack_error("No data, is the master still running ?");
  726. // if a network error occurs, this exception will restart the driver
  727. } else if (error == NET_CONN_ERROR) {
  728. FatalRecvError();
  729. } else {
  730. jack_error("Fatal error in slave receive : %s", StrError(NET_ERROR_CODE));
  731. }
  732. */
  733. FatalRecvError();
  734. }
  735. packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
  736. PacketHeaderNToH(header, header);
  737. return rx_bytes;
  738. }
  739. int JackNetSlaveInterface::Send(size_t size, int flags)
  740. {
  741. packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
  742. PacketHeaderHToN(header, header);
  743. int tx_bytes = fSocket.Send(fTxBuffer, size, flags);
  744. // handle errors
  745. if (tx_bytes == SOCKET_ERROR) {
  746. /*
  747. net_error_t error = fSocket.GetError();
  748. // if a network error occurs, this exception will restart the driver
  749. if (error == NET_CONN_ERROR) {
  750. FatalSendError();
  751. } else {
  752. jack_error("Fatal error in slave send : %s", StrError(NET_ERROR_CODE));
  753. }
  754. */
  755. FatalSendError();
  756. }
  757. return tx_bytes;
  758. }
  759. int JackNetSlaveInterface::SyncRecv()
  760. {
  761. int rx_bytes = 0;
  762. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  763. // receive sync (launch the cycle)
  764. do {
  765. rx_bytes = Recv(fParams.fMtu, 0);
  766. // connection issue, send will detect it, so don't skip the cycle (return 0)
  767. if (rx_bytes == SOCKET_ERROR) {
  768. return rx_bytes;
  769. }
  770. }
  771. while ((strcmp(rx_head->fPacketType, "header") != 0) && (rx_head->fDataType != 's'));
  772. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  773. SetRcvTimeOut();
  774. return rx_bytes;
  775. }
  776. int JackNetSlaveInterface::DataRecv()
  777. {
  778. int rx_bytes = 0;
  779. uint recvd_midi_pckt = 0;
  780. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  781. while (!fRxHeader.fIsLastPckt) {
  782. // how much data is queued on the rx buffer ?
  783. rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
  784. // error here, problem with recv, just skip the cycle (return -1)
  785. if (rx_bytes == SOCKET_ERROR) {
  786. return rx_bytes;
  787. }
  788. if (rx_bytes && (rx_head->fDataStream == 's') && (rx_head->fID == fParams.fID)) {
  789. // read data
  790. switch (rx_head->fDataType) {
  791. case 'm': // midi
  792. rx_bytes = MidiRecv(rx_head, fNetMidiCaptureBuffer, recvd_midi_pckt);
  793. break;
  794. case 'a': // audio
  795. rx_bytes = AudioRecv(rx_head, fNetAudioCaptureBuffer);
  796. break;
  797. case 's': // sync
  798. jack_info("NetSlave : overloaded, skipping receive");
  799. return FinishRecv(fNetAudioCaptureBuffer);
  800. }
  801. }
  802. }
  803. fRxHeader.fCycle = rx_head->fCycle;
  804. return rx_bytes;
  805. }
  806. int JackNetSlaveInterface::SyncSend()
  807. {
  808. // tx header
  809. if (fParams.fSlaveSyncMode) {
  810. fTxHeader.fCycle = fRxHeader.fCycle;
  811. } else {
  812. fTxHeader.fCycle++;
  813. }
  814. fTxHeader.fSubCycle = 0;
  815. fTxHeader.fDataType = 's';
  816. fTxHeader.fIsLastPckt = (fParams.fReturnMidiChannels == 0 && fParams.fReturnAudioChannels == 0) ? 1 : 0;
  817. fTxHeader.fPacketSize = fParams.fMtu;
  818. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  819. // PacketHeaderDisplay(&fTxHeader);
  820. return Send(fTxHeader.fPacketSize, 0);
  821. }
  822. int JackNetSlaveInterface::DataSend()
  823. {
  824. if (MidiSend(fNetMidiPlaybackBuffer, fParams.fReturnMidiChannels, fParams.fReturnAudioChannels) == SOCKET_ERROR) {
  825. return SOCKET_ERROR;
  826. }
  827. return AudioSend(fNetAudioPlaybackBuffer, fParams.fReturnAudioChannels);
  828. }
  829. // network sync------------------------------------------------------------------------
  830. void JackNetSlaveInterface::EncodeSyncPacket()
  831. {
  832. // This method contains every step of sync packet informations coding
  833. // first of all, clear sync packet
  834. memset(fTxData, 0, PACKET_AVAILABLE_SIZE(&fParams));
  835. // then first step : transport
  836. if (fParams.fTransportSync) {
  837. EncodeTransportData();
  838. TransportDataHToN(&fReturnTransportData, &fReturnTransportData);
  839. // copy to TxBuffer
  840. memcpy(fTxData, &fReturnTransportData, sizeof(net_transport_data_t));
  841. }
  842. // then others
  843. // ...
  844. // Transport is not used for now...
  845. // Write active ports list
  846. fTxHeader.fActivePorts = (fNetAudioCaptureBuffer) ? fNetAudioCaptureBuffer->ActivePortsToNetwork(fTxData) : 0;
  847. }
  848. void JackNetSlaveInterface::DecodeSyncPacket()
  849. {
  850. // This method contains every step of sync packet informations decoding process
  851. // first : transport
  852. if (fParams.fTransportSync) {
  853. // copy received transport data to transport data structure
  854. memcpy(&fSendTransportData, fRxData, sizeof(net_transport_data_t));
  855. TransportDataNToH(&fSendTransportData, &fSendTransportData);
  856. DecodeTransportData();
  857. }
  858. // then others
  859. // ...
  860. // Transport not used for now...
  861. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  862. // Read active ports list
  863. if (fNetAudioPlaybackBuffer) {
  864. fNetAudioPlaybackBuffer->ActivePortsFromNetwork(fRxData, rx_head->fActivePorts);
  865. }
  866. }
  867. }