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.

1022 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. 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. void JackNetInterface::FreeNetworkBuffers()
  55. {
  56. delete fNetMidiCaptureBuffer;
  57. delete fNetMidiPlaybackBuffer;
  58. delete fNetAudioCaptureBuffer;
  59. delete fNetAudioPlaybackBuffer;
  60. fNetMidiCaptureBuffer = NULL;
  61. fNetMidiPlaybackBuffer = NULL;
  62. fNetAudioCaptureBuffer = NULL;
  63. fNetAudioPlaybackBuffer = NULL;
  64. }
  65. JackNetInterface::~JackNetInterface()
  66. {
  67. jack_log("JackNetInterface::~JackNetInterface");
  68. fSocket.Close();
  69. delete[] fTxBuffer;
  70. delete[] fRxBuffer;
  71. delete fNetAudioCaptureBuffer;
  72. delete fNetAudioPlaybackBuffer;
  73. delete fNetMidiCaptureBuffer;
  74. delete fNetMidiPlaybackBuffer;
  75. }
  76. int JackNetInterface::SetNetBufferSize()
  77. {
  78. // audio
  79. float audio_size = (fNetAudioCaptureBuffer)
  80. ? fNetAudioCaptureBuffer->GetCycleSize()
  81. : (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->GetCycleSize() : 0;
  82. jack_log("audio_size %f", audio_size);
  83. // midi
  84. float midi_size = (fNetMidiCaptureBuffer)
  85. ? fNetMidiCaptureBuffer->GetCycleSize()
  86. : (fNetMidiPlaybackBuffer) ? fNetMidiPlaybackBuffer->GetCycleSize() : 0;
  87. jack_log("midi_size %f", midi_size);
  88. // bufsize = sync + audio + midi
  89. int bufsize = NETWORK_MAX_LATENCY * (fParams.fMtu + (int)audio_size + (int)midi_size);
  90. jack_log("SetNetBufferSize bufsize = %d", bufsize);
  91. // tx buffer
  92. if (fSocket.SetOption(SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR) {
  93. return SOCKET_ERROR;
  94. }
  95. // rx buffer
  96. if (fSocket.SetOption(SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR) {
  97. return SOCKET_ERROR;
  98. }
  99. return 0;
  100. }
  101. bool JackNetInterface::SetParams()
  102. {
  103. // TX header init
  104. strcpy(fTxHeader.fPacketType, "header");
  105. fTxHeader.fID = fParams.fID;
  106. fTxHeader.fCycle = 0;
  107. fTxHeader.fSubCycle = 0;
  108. fTxHeader.fIsLastPckt = 0;
  109. // RX header init
  110. strcpy(fRxHeader.fPacketType, "header");
  111. fRxHeader.fID = fParams.fID;
  112. fRxHeader.fCycle = 0;
  113. fRxHeader.fSubCycle = 0;
  114. fRxHeader.fIsLastPckt = 0;
  115. // network buffers
  116. fTxBuffer = new char[fParams.fMtu];
  117. fRxBuffer = new char[fParams.fMtu];
  118. assert(fTxBuffer);
  119. assert(fRxBuffer);
  120. // net audio/midi buffers'addresses
  121. fTxData = fTxBuffer + HEADER_SIZE;
  122. fRxData = fRxBuffer + HEADER_SIZE;
  123. return true;
  124. }
  125. int JackNetInterface::MidiSend(NetMidiBuffer* buffer, int midi_channnels, int audio_channels)
  126. {
  127. if (midi_channnels > 0) {
  128. // set global header fields and get the number of midi packets
  129. fTxHeader.fDataType = 'm';
  130. uint data_size = buffer->RenderFromJackPorts();
  131. fTxHeader.fNumPacket = buffer->GetNumPackets(data_size, PACKET_AVAILABLE_SIZE(&fParams));
  132. for (uint subproc = 0; subproc < fTxHeader.fNumPacket; subproc++) {
  133. fTxHeader.fSubCycle = subproc;
  134. fTxHeader.fIsLastPckt = ((subproc == (fTxHeader.fNumPacket - 1)) && audio_channels == 0) ? 1 : 0;
  135. fTxHeader.fPacketSize = HEADER_SIZE + buffer->RenderToNetwork(subproc, data_size);
  136. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  137. if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
  138. return SOCKET_ERROR;
  139. }
  140. }
  141. }
  142. return 0;
  143. }
  144. int JackNetInterface::AudioSend(NetAudioBuffer* buffer, int audio_channels)
  145. {
  146. // audio
  147. if (audio_channels > 0) {
  148. fTxHeader.fDataType = 'a';
  149. fTxHeader.fActivePorts = buffer->RenderFromJackPorts();
  150. fTxHeader.fNumPacket = buffer->GetNumPackets(fTxHeader.fActivePorts);
  151. for (uint subproc = 0; subproc < fTxHeader.fNumPacket; subproc++) {
  152. fTxHeader.fSubCycle = subproc;
  153. fTxHeader.fIsLastPckt = (subproc == (fTxHeader.fNumPacket - 1)) ? 1 : 0;
  154. fTxHeader.fPacketSize = HEADER_SIZE + buffer->RenderToNetwork(subproc, fTxHeader.fActivePorts);
  155. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  156. // PacketHeaderDisplay(&fTxHeader);
  157. if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
  158. return SOCKET_ERROR;
  159. }
  160. }
  161. }
  162. return 0;
  163. }
  164. int JackNetInterface::MidiRecv(packet_header_t* rx_head, NetMidiBuffer* buffer, uint& recvd_midi_pckt)
  165. {
  166. int rx_bytes = Recv(rx_head->fPacketSize, 0);
  167. fRxHeader.fCycle = rx_head->fCycle;
  168. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  169. buffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
  170. // Last midi packet is received, so finish rendering...
  171. if (++recvd_midi_pckt == rx_head->fNumPacket) {
  172. buffer->RenderToJackPorts();
  173. }
  174. return rx_bytes;
  175. }
  176. int JackNetInterface::AudioRecv(packet_header_t* rx_head, NetAudioBuffer* buffer)
  177. {
  178. int rx_bytes = Recv(rx_head->fPacketSize, 0);
  179. fRxHeader.fCycle = rx_head->fCycle;
  180. fRxHeader.fSubCycle = rx_head->fSubCycle;
  181. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  182. fRxHeader.fActivePorts = rx_head->fActivePorts;
  183. rx_bytes = buffer->RenderFromNetwork(rx_head->fCycle, rx_head->fSubCycle, fRxHeader.fActivePorts);
  184. // Last audio packet is received, so finish rendering...
  185. if (fRxHeader.fIsLastPckt) {
  186. buffer->RenderToJackPorts();
  187. }
  188. return rx_bytes;
  189. }
  190. int JackNetInterface::FinishRecv(NetAudioBuffer* buffer)
  191. {
  192. // TODO : finish midi and audio rendering ?
  193. buffer->RenderToJackPorts();
  194. return NET_PACKET_ERROR;
  195. }
  196. NetAudioBuffer* JackNetInterface::AudioBufferFactory(int nports, char* buffer)
  197. {
  198. switch (fParams.fSampleEncoder) {
  199. case JackFloatEncoder:
  200. return new NetFloatAudioBuffer(&fParams, nports, buffer);
  201. case JackIntEncoder:
  202. return new NetIntAudioBuffer(&fParams, nports, buffer);
  203. #if HAVE_CELT
  204. case JackCeltEncoder:
  205. return new NetCeltAudioBuffer(&fParams, nports, buffer, fParams.fKBps);
  206. #endif
  207. }
  208. return NULL;
  209. }
  210. // JackNetMasterInterface ************************************************************************************
  211. bool JackNetMasterInterface::Init()
  212. {
  213. jack_log("JackNetMasterInterface::Init, ID %u", fParams.fID);
  214. session_params_t host_params;
  215. uint attempt = 0;
  216. int rx_bytes = 0;
  217. // socket
  218. if (fSocket.NewSocket() == SOCKET_ERROR) {
  219. jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
  220. return false;
  221. }
  222. // timeout on receive (for init)
  223. if (fSocket.SetTimeOut(MASTER_INIT_TIMEOUT) < 0)
  224. jack_error("Can't set timeout : %s", StrError(NET_ERROR_CODE));
  225. // connect
  226. if (fSocket.Connect() == SOCKET_ERROR) {
  227. jack_error("Can't connect : %s", StrError(NET_ERROR_CODE));
  228. return false;
  229. }
  230. // send 'SLAVE_SETUP' until 'START_MASTER' received
  231. jack_info("Sending parameters to %s...", fParams.fSlaveNetName);
  232. do
  233. {
  234. session_params_t net_params;
  235. memset(&net_params, 0, sizeof(session_params_t));
  236. SetPacketType(&fParams, SLAVE_SETUP);
  237. SessionParamsHToN(&fParams, &net_params);
  238. if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
  239. jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
  240. }
  241. memset(&net_params, 0, sizeof(session_params_t));
  242. if (((rx_bytes = fSocket.Recv(&net_params, sizeof(session_params_t), 0)) == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
  243. jack_error("Problem with network");
  244. return false;
  245. }
  246. SessionParamsNToH(&net_params, &host_params);
  247. }
  248. while ((GetPacketType(&host_params) != START_MASTER) && (++attempt < SLAVE_SETUP_RETRY));
  249. if (attempt == SLAVE_SETUP_RETRY) {
  250. jack_error("Slave doesn't respond, exiting");
  251. return false;
  252. }
  253. return true;
  254. }
  255. int JackNetMasterInterface::SetRxTimeout()
  256. {
  257. jack_log("JackNetMasterInterface::SetRxTimeout");
  258. float time = 3 * 1000000.f * (static_cast<float>(fParams.fPeriodSize) / static_cast<float>(fParams.fSampleRate));
  259. return fSocket.SetTimeOut(static_cast<int>(time));
  260. }
  261. bool JackNetMasterInterface::SetParams()
  262. {
  263. jack_log("JackNetMasterInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
  264. fParams.fSendAudioChannels, fParams.fReturnAudioChannels,
  265. fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
  266. JackNetInterface::SetParams();
  267. fTxHeader.fDataStream = 's';
  268. fRxHeader.fDataStream = 'r';
  269. fMaxCycleOffset = fParams.fNetworkLatency;
  270. // midi net buffers
  271. if (fParams.fSendMidiChannels > 0) {
  272. fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fTxData);
  273. }
  274. if (fParams.fReturnMidiChannels > 0) {
  275. fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
  276. }
  277. try {
  278. // audio net buffers
  279. if (fParams.fSendAudioChannels > 0) {
  280. fNetAudioCaptureBuffer = AudioBufferFactory(fParams.fSendAudioChannels, fTxData);
  281. assert(fNetAudioCaptureBuffer);
  282. }
  283. if (fParams.fReturnAudioChannels > 0) {
  284. fNetAudioPlaybackBuffer = AudioBufferFactory(fParams.fReturnAudioChannels, fRxData);
  285. assert(fNetAudioPlaybackBuffer);
  286. }
  287. } catch (exception&) {
  288. jack_error("NetAudioBuffer allocation error...");
  289. return false;
  290. }
  291. // set the new timeout for the socket
  292. /*
  293. if (SetRxTimeout() == SOCKET_ERROR) {
  294. jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
  295. goto error;
  296. }
  297. */
  298. // set the new rx buffer size
  299. if (SetNetBufferSize() == SOCKET_ERROR) {
  300. jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
  301. goto error;
  302. }
  303. return true;
  304. error:
  305. FreeNetworkBuffers();
  306. return false;
  307. }
  308. void JackNetMasterInterface::Exit()
  309. {
  310. jack_log("JackNetMasterInterface::Exit, ID %u", fParams.fID);
  311. // stop process
  312. fRunning = false;
  313. // send a 'multicast euthanasia request' - new socket is required on macosx
  314. jack_info("Exiting '%s'", fParams.fName);
  315. SetPacketType(&fParams, KILL_MASTER);
  316. JackNetSocket mcast_socket(fMulticastIP, fSocket.GetPort());
  317. session_params_t net_params;
  318. memset(&net_params, 0, sizeof(session_params_t));
  319. SessionParamsHToN(&fParams, &net_params);
  320. if (mcast_socket.NewSocket() == SOCKET_ERROR) {
  321. jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
  322. }
  323. if (mcast_socket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR) {
  324. jack_error("Can't send suicide request : %s", StrError(NET_ERROR_CODE));
  325. }
  326. mcast_socket.Close();
  327. }
  328. void JackNetMasterInterface::FatalRecvError()
  329. {
  330. // fatal connection issue, exit
  331. jack_error("Recv connection lost error = %s, '%s' exiting", StrError(NET_ERROR_CODE), fParams.fName);
  332. // ask to the manager to properly remove the master
  333. Exit();
  334. // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
  335. ThreadExit();
  336. }
  337. void JackNetMasterInterface::FatalSendError()
  338. {
  339. // fatal connection issue, exit
  340. jack_error("Send connection lost error = %s, '%s' exiting", StrError(NET_ERROR_CODE), fParams.fName);
  341. // ask to the manager to properly remove the master
  342. Exit();
  343. // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
  344. ThreadExit();
  345. }
  346. int JackNetMasterInterface::Recv(size_t size, int flags)
  347. {
  348. int rx_bytes;
  349. if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
  350. /*
  351. net_error_t error = fSocket.GetError();
  352. // no data isn't really a network error, so just return 0 available read bytes
  353. if (error == NET_NO_DATA) {
  354. return 0;
  355. } else if (error == NET_CONN_ERROR) {
  356. FatalRecvError();
  357. } else {
  358. jack_error("Error in master receive : %s", StrError(NET_ERROR_CODE));
  359. }
  360. */
  361. FatalRecvError();
  362. }
  363. packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
  364. PacketHeaderNToH(header, header);
  365. return rx_bytes;
  366. }
  367. int JackNetMasterInterface::Send(size_t size, int flags)
  368. {
  369. int tx_bytes;
  370. packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
  371. PacketHeaderHToN(header, header);
  372. if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
  373. /*
  374. net_error_t error = fSocket.GetError();
  375. if (error == NET_CONN_ERROR) {
  376. FatalSendError();
  377. } else {
  378. jack_error("Error in master send : %s", StrError(NET_ERROR_CODE));
  379. }
  380. */
  381. FatalSendError();
  382. }
  383. return tx_bytes;
  384. }
  385. bool JackNetMasterInterface::IsSynched()
  386. {
  387. return (fCurrentCycleOffset <= fMaxCycleOffset);
  388. }
  389. int JackNetMasterInterface::SyncSend()
  390. {
  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
  599. if (fSocket.SetTimeOut(SLAVE_INIT_TIMEOUT) == SOCKET_ERROR)
  600. jack_error("Can't set timeout : %s", StrError(NET_ERROR_CODE));
  601. // disable local loop
  602. if (fSocket.SetLocalLoop() == SOCKET_ERROR)
  603. jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
  604. // send 'AVAILABLE' until 'SLAVE_SETUP' received
  605. jack_info("Waiting for a master...");
  606. do {
  607. // send 'available'
  608. session_params_t net_params;
  609. memset(&net_params, 0, sizeof(session_params_t));
  610. SessionParamsHToN(&fParams, &net_params);
  611. if (fSocket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR)
  612. jack_error("Error in data send : %s", StrError(NET_ERROR_CODE));
  613. // filter incoming packets : don't exit while no error is detected
  614. memset(&net_params, 0, sizeof(session_params_t));
  615. rx_bytes = fSocket.CatchHost(&net_params, sizeof(session_params_t), 0);
  616. SessionParamsNToH(&net_params, &host_params);
  617. if ((rx_bytes == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
  618. jack_error("Can't receive : %s", StrError(NET_ERROR_CODE));
  619. return NET_RECV_ERROR;
  620. }
  621. }
  622. while (strcmp(host_params.fPacketType, fParams.fPacketType) && (GetPacketType(&host_params) != SLAVE_SETUP) && (--try_count > 0));
  623. // Time out failure..
  624. if (try_count == 0) {
  625. jack_error("Time out error in connect");
  626. return NET_CONNECT_ERROR;
  627. }
  628. // everything is OK, copy parameters
  629. fParams = host_params;
  630. // connect the socket
  631. if (fSocket.Connect() == SOCKET_ERROR) {
  632. jack_error("Error in connect : %s", StrError(NET_ERROR_CODE));
  633. return NET_CONNECT_ERROR;
  634. }
  635. return NET_CONNECTED;
  636. }
  637. net_status_t JackNetSlaveInterface::SendStartToMaster()
  638. {
  639. jack_log("JackNetSlaveInterface::SendStartToMaster");
  640. // tell the master to start
  641. session_params_t net_params;
  642. memset(&net_params, 0, sizeof(session_params_t));
  643. SetPacketType(&fParams, START_MASTER);
  644. SessionParamsHToN(&fParams, &net_params);
  645. if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
  646. jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
  647. return (fSocket.GetError() == NET_CONN_ERROR) ? NET_ERROR : NET_SEND_ERROR;
  648. }
  649. return NET_ROLLING;
  650. }
  651. bool JackNetSlaveInterface::SetParams()
  652. {
  653. jack_log("JackNetSlaveInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
  654. fParams.fSendAudioChannels, fParams.fReturnAudioChannels,
  655. fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
  656. JackNetInterface::SetParams();
  657. fTxHeader.fDataStream = 'r';
  658. fRxHeader.fDataStream = 's';
  659. // midi net buffers
  660. if (fParams.fSendMidiChannels > 0) {
  661. fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fRxData);
  662. }
  663. if (fParams.fReturnMidiChannels > 0) {
  664. fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fTxData);
  665. }
  666. try {
  667. // audio net buffers
  668. if (fParams.fSendAudioChannels > 0) {
  669. fNetAudioCaptureBuffer = AudioBufferFactory(fParams.fSendAudioChannels, fRxData);
  670. assert(fNetAudioCaptureBuffer);
  671. }
  672. if (fParams.fReturnAudioChannels > 0) {
  673. fNetAudioPlaybackBuffer = AudioBufferFactory(fParams.fReturnAudioChannels, fTxData);
  674. assert(fNetAudioPlaybackBuffer);
  675. }
  676. } catch (exception&) {
  677. jack_error("NetAudioBuffer allocation error...");
  678. return false;
  679. }
  680. // set the new buffer sizes
  681. if (SetNetBufferSize() == SOCKET_ERROR) {
  682. jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
  683. goto error;
  684. }
  685. return true;
  686. error:
  687. FreeNetworkBuffers();
  688. return false;
  689. }
  690. void JackNetSlaveInterface::FatalRecvError()
  691. {
  692. jack_error("Recv connection lost error = %s", StrError(NET_ERROR_CODE));
  693. throw JackNetException();
  694. }
  695. void JackNetSlaveInterface::FatalSendError()
  696. {
  697. jack_error("Send connection lost error = %s", StrError(NET_ERROR_CODE));
  698. throw JackNetException();
  699. }
  700. int JackNetSlaveInterface::Recv(size_t size, int flags)
  701. {
  702. int rx_bytes = fSocket.Recv(fRxBuffer, size, flags);
  703. // handle errors
  704. if (rx_bytes == SOCKET_ERROR) {
  705. /*
  706. net_error_t error = fSocket.GetError();
  707. // no data isn't really an error in realtime processing, so just return 0
  708. if (error == NET_NO_DATA) {
  709. jack_error("No data, is the master still running ?");
  710. // if a network error occurs, this exception will restart the driver
  711. } else if (error == NET_CONN_ERROR) {
  712. FatalRecvError();
  713. } else {
  714. jack_error("Fatal error in slave receive : %s", StrError(NET_ERROR_CODE));
  715. }
  716. */
  717. FatalRecvError();
  718. }
  719. packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
  720. PacketHeaderNToH(header, header);
  721. return rx_bytes;
  722. }
  723. int JackNetSlaveInterface::Send(size_t size, int flags)
  724. {
  725. packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
  726. PacketHeaderHToN(header, header);
  727. int tx_bytes = fSocket.Send(fTxBuffer, size, flags);
  728. // handle errors
  729. if (tx_bytes == SOCKET_ERROR) {
  730. /*
  731. net_error_t error = fSocket.GetError();
  732. // if a network error occurs, this exception will restart the driver
  733. if (error == NET_CONN_ERROR) {
  734. FatalSendError();
  735. } else {
  736. jack_error("Fatal error in slave send : %s", StrError(NET_ERROR_CODE));
  737. }
  738. */
  739. FatalSendError();
  740. }
  741. return tx_bytes;
  742. }
  743. int JackNetSlaveInterface::SyncRecv()
  744. {
  745. int rx_bytes = 0;
  746. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  747. // receive sync (launch the cycle)
  748. do {
  749. rx_bytes = Recv(fParams.fMtu, 0);
  750. // connection issue, send will detect it, so don't skip the cycle (return 0)
  751. if (rx_bytes == SOCKET_ERROR) {
  752. return rx_bytes;
  753. }
  754. }
  755. while ((strcmp(rx_head->fPacketType, "header") != 0) && (rx_head->fDataType != 's'));
  756. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  757. return rx_bytes;
  758. }
  759. int JackNetSlaveInterface::DataRecv()
  760. {
  761. int rx_bytes = 0;
  762. uint recvd_midi_pckt = 0;
  763. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  764. while (!fRxHeader.fIsLastPckt) {
  765. // how much data is queued on the rx buffer ?
  766. rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
  767. // error here, problem with recv, just skip the cycle (return -1)
  768. if (rx_bytes == SOCKET_ERROR) {
  769. return rx_bytes;
  770. }
  771. if (rx_bytes && (rx_head->fDataStream == 's') && (rx_head->fID == fParams.fID)) {
  772. // read data
  773. switch (rx_head->fDataType) {
  774. case 'm': // midi
  775. rx_bytes = MidiRecv(rx_head, fNetMidiCaptureBuffer, recvd_midi_pckt);
  776. break;
  777. case 'a': // audio
  778. rx_bytes = AudioRecv(rx_head, fNetAudioCaptureBuffer);
  779. break;
  780. case 's': // sync
  781. jack_info("NetSlave : overloaded, skipping receive");
  782. return FinishRecv(fNetAudioCaptureBuffer);
  783. }
  784. }
  785. }
  786. fRxHeader.fCycle = rx_head->fCycle;
  787. return rx_bytes;
  788. }
  789. int JackNetSlaveInterface::SyncSend()
  790. {
  791. // tx header
  792. if (fParams.fSlaveSyncMode) {
  793. fTxHeader.fCycle = fRxHeader.fCycle;
  794. } else {
  795. fTxHeader.fCycle++;
  796. }
  797. fTxHeader.fSubCycle = 0;
  798. fTxHeader.fDataType = 's';
  799. fTxHeader.fIsLastPckt = (fParams.fReturnMidiChannels == 0 && fParams.fReturnAudioChannels == 0) ? 1 : 0;
  800. fTxHeader.fPacketSize = fParams.fMtu;
  801. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  802. // PacketHeaderDisplay(&fTxHeader);
  803. return Send(fTxHeader.fPacketSize, 0);
  804. }
  805. int JackNetSlaveInterface::DataSend()
  806. {
  807. if (MidiSend(fNetMidiPlaybackBuffer, fParams.fReturnMidiChannels, fParams.fReturnAudioChannels) == SOCKET_ERROR) {
  808. return SOCKET_ERROR;
  809. }
  810. return AudioSend(fNetAudioPlaybackBuffer, fParams.fReturnAudioChannels);
  811. }
  812. // network sync------------------------------------------------------------------------
  813. void JackNetSlaveInterface::EncodeSyncPacket()
  814. {
  815. // This method contains every step of sync packet informations coding
  816. // first of all, clear sync packet
  817. memset(fTxData, 0, PACKET_AVAILABLE_SIZE(&fParams));
  818. // then first step : transport
  819. if (fParams.fTransportSync) {
  820. EncodeTransportData();
  821. TransportDataHToN(&fReturnTransportData, &fReturnTransportData);
  822. // copy to TxBuffer
  823. memcpy(fTxData, &fReturnTransportData, sizeof(net_transport_data_t));
  824. }
  825. // then others
  826. // ...
  827. // Transport is not used for now...
  828. // Write active ports list
  829. fTxHeader.fActivePorts = (fNetAudioCaptureBuffer) ? fNetAudioCaptureBuffer->ActivePortsToNetwork(fTxData) : 0;
  830. }
  831. void JackNetSlaveInterface::DecodeSyncPacket()
  832. {
  833. // This method contains every step of sync packet informations decoding process
  834. // first : transport
  835. if (fParams.fTransportSync) {
  836. // copy received transport data to transport data structure
  837. memcpy(&fSendTransportData, fRxData, sizeof(net_transport_data_t));
  838. TransportDataNToH(&fSendTransportData, &fSendTransportData);
  839. DecodeTransportData();
  840. }
  841. // then others
  842. // ...
  843. // Transport not used for now...
  844. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  845. // Read active ports list
  846. if (fNetAudioPlaybackBuffer) {
  847. fNetAudioPlaybackBuffer->ActivePortsFromNetwork(fRxData, rx_head->fActivePorts);
  848. }
  849. }
  850. }