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.

1013 lines
34KB

  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. fPacketTimeOut = PACKET_TIMEOUT * NETWORK_DEFAULT_LATENCY;
  55. }
  56. void JackNetInterface::FreeNetworkBuffers()
  57. {
  58. delete fNetMidiCaptureBuffer;
  59. delete fNetMidiPlaybackBuffer;
  60. delete fNetAudioCaptureBuffer;
  61. delete fNetAudioPlaybackBuffer;
  62. fNetMidiCaptureBuffer = NULL;
  63. fNetMidiPlaybackBuffer = NULL;
  64. fNetAudioCaptureBuffer = NULL;
  65. fNetAudioPlaybackBuffer = NULL;
  66. }
  67. JackNetInterface::~JackNetInterface()
  68. {
  69. jack_log("JackNetInterface::~JackNetInterface");
  70. fSocket.Close();
  71. delete[] fTxBuffer;
  72. delete[] fRxBuffer;
  73. delete fNetAudioCaptureBuffer;
  74. delete fNetAudioPlaybackBuffer;
  75. delete fNetMidiCaptureBuffer;
  76. delete fNetMidiPlaybackBuffer;
  77. }
  78. int JackNetInterface::SetNetBufferSize()
  79. {
  80. // audio
  81. float audio_size = (fNetAudioCaptureBuffer)
  82. ? fNetAudioCaptureBuffer->GetCycleSize()
  83. : (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->GetCycleSize() : 0;
  84. jack_log("audio_size %f", audio_size);
  85. // midi
  86. float midi_size = (fNetMidiCaptureBuffer)
  87. ? fNetMidiCaptureBuffer->GetCycleSize()
  88. : (fNetMidiPlaybackBuffer) ? fNetMidiPlaybackBuffer->GetCycleSize() : 0;
  89. jack_log("midi_size %f", midi_size);
  90. // bufsize = sync + audio + midi
  91. int bufsize = NETWORK_MAX_LATENCY * (fParams.fMtu + (int)audio_size + (int)midi_size);
  92. jack_log("SetNetBufferSize bufsize = %d", bufsize);
  93. // tx buffer
  94. if (fSocket.SetOption(SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR) {
  95. return SOCKET_ERROR;
  96. }
  97. // rx buffer
  98. if (fSocket.SetOption(SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize)) == SOCKET_ERROR) {
  99. return SOCKET_ERROR;
  100. }
  101. return 0;
  102. }
  103. bool JackNetInterface::SetParams()
  104. {
  105. // TX header init
  106. memset(&fTxHeader, 0, sizeof(fTxHeader));
  107. strcpy(fTxHeader.fPacketType, "header");
  108. fTxHeader.fID = fParams.fID;
  109. fTxHeader.fCycle = 0;
  110. fTxHeader.fSubCycle = 0;
  111. fTxHeader.fIsLastPckt = 0;
  112. // RX header init
  113. memset(&fRxHeader, 0, sizeof(fTxHeader));
  114. strcpy(fRxHeader.fPacketType, "header");
  115. fRxHeader.fID = fParams.fID;
  116. fRxHeader.fCycle = 0;
  117. fRxHeader.fSubCycle = 0;
  118. fRxHeader.fIsLastPckt = 0;
  119. // network buffers
  120. fTxBuffer = new char[fParams.fMtu];
  121. fRxBuffer = new char[fParams.fMtu];
  122. assert(fTxBuffer);
  123. assert(fRxBuffer);
  124. // net audio/midi buffers'addresses
  125. fTxData = fTxBuffer + HEADER_SIZE;
  126. fRxData = fRxBuffer + HEADER_SIZE;
  127. return true;
  128. }
  129. int JackNetInterface::MidiSend(NetMidiBuffer* buffer, int midi_channnels, int audio_channels)
  130. {
  131. if (midi_channnels > 0) {
  132. // set global header fields and get the number of midi packets
  133. fTxHeader.fDataType = 'm';
  134. uint data_size = buffer->RenderFromJackPorts();
  135. fTxHeader.fNumPacket = buffer->GetNumPackets(data_size, PACKET_AVAILABLE_SIZE(&fParams));
  136. for (uint subproc = 0; subproc < fTxHeader.fNumPacket; subproc++) {
  137. fTxHeader.fSubCycle = subproc;
  138. fTxHeader.fIsLastPckt = ((subproc == (fTxHeader.fNumPacket - 1)) && audio_channels == 0) ? 1 : 0;
  139. fTxHeader.fPacketSize = HEADER_SIZE + buffer->RenderToNetwork(subproc, data_size);
  140. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  141. //PacketHeaderDisplay(&fTxHeader);
  142. if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
  143. return SOCKET_ERROR;
  144. }
  145. }
  146. }
  147. return 0;
  148. }
  149. int JackNetInterface::AudioSend(NetAudioBuffer* buffer, int audio_channels)
  150. {
  151. // audio
  152. if (audio_channels > 0) {
  153. fTxHeader.fDataType = 'a';
  154. fTxHeader.fActivePorts = buffer->RenderFromJackPorts(fTxHeader.fFrames);
  155. fTxHeader.fNumPacket = buffer->GetNumPackets(fTxHeader.fActivePorts);
  156. for (uint subproc = 0; subproc < fTxHeader.fNumPacket; subproc++) {
  157. fTxHeader.fSubCycle = subproc;
  158. fTxHeader.fIsLastPckt = (subproc == (fTxHeader.fNumPacket - 1)) ? 1 : 0;
  159. fTxHeader.fPacketSize = HEADER_SIZE + buffer->RenderToNetwork(subproc, fTxHeader.fActivePorts);
  160. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  161. //PacketHeaderDisplay(&fTxHeader);
  162. if (Send(fTxHeader.fPacketSize, 0) == SOCKET_ERROR) {
  163. return SOCKET_ERROR;
  164. }
  165. }
  166. }
  167. return 0;
  168. }
  169. int JackNetInterface::MidiRecv(packet_header_t* rx_head, NetMidiBuffer* buffer, uint& recvd_midi_pckt)
  170. {
  171. int rx_bytes = Recv(rx_head->fPacketSize, 0);
  172. fRxHeader.fCycle = rx_head->fCycle;
  173. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  174. buffer->RenderFromNetwork(rx_head->fSubCycle, rx_bytes - HEADER_SIZE);
  175. // Last midi packet is received, so finish rendering...
  176. if (++recvd_midi_pckt == rx_head->fNumPacket) {
  177. buffer->RenderToJackPorts();
  178. }
  179. //PacketHeaderDisplay(rx_head);
  180. return rx_bytes;
  181. }
  182. int JackNetInterface::AudioRecv(packet_header_t* rx_head, NetAudioBuffer* buffer)
  183. {
  184. int rx_bytes = Recv(rx_head->fPacketSize, 0);
  185. fRxHeader.fCycle = rx_head->fCycle;
  186. fRxHeader.fSubCycle = rx_head->fSubCycle;
  187. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  188. fRxHeader.fActivePorts = rx_head->fActivePorts;
  189. fRxHeader.fFrames = rx_head->fFrames;
  190. rx_bytes = buffer->RenderFromNetwork(rx_head->fCycle, rx_head->fSubCycle, fRxHeader.fActivePorts);
  191. // Last audio packet is received, so finish rendering...
  192. if (fRxHeader.fIsLastPckt) {
  193. buffer->RenderToJackPorts(fRxHeader.fFrames);
  194. }
  195. //PacketHeaderDisplay(rx_head);
  196. return rx_bytes;
  197. }
  198. int JackNetInterface::FinishRecv(NetAudioBuffer* buffer)
  199. {
  200. if (buffer) {
  201. buffer->RenderToJackPorts(fRxHeader.fFrames);
  202. } else {
  203. jack_error("FinishRecv with null buffer...");
  204. }
  205. return DATA_PACKET_ERROR;
  206. }
  207. NetAudioBuffer* JackNetInterface::AudioBufferFactory(int nports, char* buffer)
  208. {
  209. switch (fParams.fSampleEncoder) {
  210. case JackFloatEncoder:
  211. return new NetFloatAudioBuffer(&fParams, nports, buffer);
  212. case JackIntEncoder:
  213. return new NetIntAudioBuffer(&fParams, nports, buffer);
  214. #if HAVE_CELT
  215. case JackCeltEncoder:
  216. return new NetCeltAudioBuffer(&fParams, nports, buffer, fParams.fKBps);
  217. #endif
  218. #if HAVE_OPUS
  219. case JackOpusEncoder:
  220. return new NetOpusAudioBuffer(&fParams, nports, buffer, fParams.fKBps);
  221. #endif
  222. }
  223. throw std::bad_alloc();
  224. }
  225. void JackNetInterface::SetRcvTimeOut()
  226. {
  227. if (!fSetTimeOut) {
  228. if (fSocket.SetTimeOut(fPacketTimeOut) == SOCKET_ERROR) {
  229. jack_error("Can't set rx timeout : %s", StrError(NET_ERROR_CODE));
  230. return;
  231. }
  232. fSetTimeOut = true;
  233. }
  234. }
  235. // JackNetMasterInterface ************************************************************************************
  236. bool JackNetMasterInterface::Init()
  237. {
  238. jack_log("JackNetMasterInterface::Init : ID %u", fParams.fID);
  239. session_params_t host_params;
  240. uint attempt = 0;
  241. int rx_bytes = 0;
  242. // socket
  243. if (fSocket.NewSocket() == SOCKET_ERROR) {
  244. jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
  245. return false;
  246. }
  247. // timeout on receive (for init)
  248. if (fSocket.SetTimeOut(MASTER_INIT_TIMEOUT) < 0) {
  249. jack_error("Can't set init timeout : %s", StrError(NET_ERROR_CODE));
  250. }
  251. // connect
  252. if (fSocket.Connect() == SOCKET_ERROR) {
  253. jack_error("Can't connect : %s", StrError(NET_ERROR_CODE));
  254. return false;
  255. }
  256. // send 'SLAVE_SETUP' until 'START_MASTER' received
  257. jack_info("Sending parameters to %s...", fParams.fSlaveNetName);
  258. do
  259. {
  260. session_params_t net_params;
  261. memset(&net_params, 0, sizeof(session_params_t));
  262. SetPacketType(&fParams, SLAVE_SETUP);
  263. SessionParamsHToN(&fParams, &net_params);
  264. if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
  265. jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
  266. }
  267. memset(&net_params, 0, sizeof(session_params_t));
  268. if (((rx_bytes = fSocket.Recv(&net_params, sizeof(session_params_t), 0)) == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
  269. jack_error("Problem with network");
  270. return false;
  271. }
  272. SessionParamsNToH(&net_params, &host_params);
  273. }
  274. while ((GetPacketType(&host_params) != START_MASTER) && (++attempt < SLAVE_SETUP_RETRY));
  275. if (attempt == SLAVE_SETUP_RETRY) {
  276. jack_error("Slave doesn't respond, exiting");
  277. return false;
  278. }
  279. return true;
  280. }
  281. bool JackNetMasterInterface::SetParams()
  282. {
  283. jack_log("JackNetMasterInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
  284. fParams.fSendAudioChannels, fParams.fReturnAudioChannels,
  285. fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
  286. JackNetInterface::SetParams();
  287. fTxHeader.fDataStream = 's';
  288. fRxHeader.fDataStream = 'r';
  289. fMaxCycleOffset = fParams.fNetworkLatency;
  290. // midi net buffers
  291. if (fParams.fSendMidiChannels > 0) {
  292. fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fTxData);
  293. }
  294. if (fParams.fReturnMidiChannels > 0) {
  295. fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fRxData);
  296. }
  297. try {
  298. // audio net buffers
  299. if (fParams.fSendAudioChannels > 0) {
  300. fNetAudioCaptureBuffer = AudioBufferFactory(fParams.fSendAudioChannels, fTxData);
  301. assert(fNetAudioCaptureBuffer);
  302. }
  303. if (fParams.fReturnAudioChannels > 0) {
  304. fNetAudioPlaybackBuffer = AudioBufferFactory(fParams.fReturnAudioChannels, fRxData);
  305. assert(fNetAudioPlaybackBuffer);
  306. }
  307. } catch (exception&) {
  308. jack_error("NetAudioBuffer on master allocation error...");
  309. return false;
  310. }
  311. // set the new buffer size
  312. if (SetNetBufferSize() == SOCKET_ERROR) {
  313. jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
  314. goto error;
  315. }
  316. return true;
  317. error:
  318. FreeNetworkBuffers();
  319. return false;
  320. }
  321. void JackNetMasterInterface::Exit()
  322. {
  323. jack_log("JackNetMasterInterface::Exit, ID %u", fParams.fID);
  324. // stop process
  325. fRunning = false;
  326. // send a 'multicast euthanasia request' - new socket is required on macosx
  327. jack_info("Exiting '%s' %s", fParams.fName, fMulticastIP);
  328. SetPacketType(&fParams, KILL_MASTER);
  329. JackNetSocket mcast_socket(fMulticastIP, fSocket.GetPort());
  330. session_params_t net_params;
  331. memset(&net_params, 0, sizeof(session_params_t));
  332. SessionParamsHToN(&fParams, &net_params);
  333. if (mcast_socket.NewSocket() == SOCKET_ERROR) {
  334. jack_error("Can't create socket : %s", StrError(NET_ERROR_CODE));
  335. }
  336. if (mcast_socket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR) {
  337. jack_error("Can't send suicide request : %s", StrError(NET_ERROR_CODE));
  338. }
  339. mcast_socket.Close();
  340. }
  341. void JackNetMasterInterface::FatalRecvError()
  342. {
  343. // fatal connection issue, exit
  344. jack_error("Recv connection lost error = %s, '%s' exiting", StrError(NET_ERROR_CODE), fParams.fName);
  345. // ask to the manager to properly remove the master
  346. Exit();
  347. // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
  348. ThreadExit();
  349. }
  350. void JackNetMasterInterface::FatalSendError()
  351. {
  352. // fatal connection issue, exit
  353. jack_error("Send connection lost error = %s, '%s' exiting", StrError(NET_ERROR_CODE), fParams.fName);
  354. // ask to the manager to properly remove the master
  355. Exit();
  356. // UGLY temporary way to be sure the thread does not call code possibly causing a deadlock in JackEngine.
  357. ThreadExit();
  358. }
  359. int JackNetMasterInterface::Recv(size_t size, int flags)
  360. {
  361. int rx_bytes;
  362. if (((rx_bytes = fSocket.Recv(fRxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
  363. FatalRecvError();
  364. }
  365. packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
  366. PacketHeaderNToH(header, header);
  367. return rx_bytes;
  368. }
  369. int JackNetMasterInterface::Send(size_t size, int flags)
  370. {
  371. int tx_bytes;
  372. packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
  373. PacketHeaderHToN(header, header);
  374. if (((tx_bytes = fSocket.Send(fTxBuffer, size, flags)) == SOCKET_ERROR) && fRunning) {
  375. FatalSendError();
  376. }
  377. return tx_bytes;
  378. }
  379. int JackNetMasterInterface::SyncSend()
  380. {
  381. SetRcvTimeOut();
  382. fTxHeader.fCycle++;
  383. fTxHeader.fSubCycle = 0;
  384. fTxHeader.fDataType = 's';
  385. fTxHeader.fIsLastPckt = (fParams.fSendMidiChannels == 0 && fParams.fSendAudioChannels == 0) ? 1 : 0;
  386. fTxHeader.fPacketSize = HEADER_SIZE + fTxHeader.fActivePorts * sizeof(int); // Data part is used to encode active ports
  387. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  388. //PacketHeaderDisplay(&fTxHeader);
  389. return Send(fTxHeader.fPacketSize, 0);
  390. }
  391. int JackNetMasterInterface::DataSend()
  392. {
  393. if (MidiSend(fNetMidiCaptureBuffer, fParams.fSendMidiChannels, fParams.fSendAudioChannels) == SOCKET_ERROR) {
  394. return SOCKET_ERROR;
  395. }
  396. return AudioSend(fNetAudioCaptureBuffer, fParams.fSendAudioChannels);
  397. }
  398. int JackNetMasterInterface::SyncRecv()
  399. {
  400. int rx_bytes = 0;
  401. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  402. // receive sync (launch the cycle)
  403. do {
  404. rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
  405. // connection issue (return -1)
  406. if (rx_bytes == SOCKET_ERROR) {
  407. return SOCKET_ERROR;
  408. }
  409. }
  410. while (strcmp(rx_head->fPacketType, "header") != 0);
  411. //PacketHeaderDisplay(rx_head);
  412. if (rx_head->fDataType != 's') {
  413. jack_error("Wrong packet type : %c", rx_head->fDataType);
  414. // not the last packet..
  415. fRxHeader.fIsLastPckt = 0;
  416. return SYNC_PACKET_ERROR;
  417. }
  418. fCurrentCycleOffset = fTxHeader.fCycle - rx_head->fCycle;
  419. if (fCurrentCycleOffset < fMaxCycleOffset && !fSynched) {
  420. jack_info("Syncing with latency = %d", fCurrentCycleOffset);
  421. return NET_SYNCHING;
  422. } else {
  423. if (fCurrentCycleOffset == fMaxCycleOffset) {
  424. // when the sync offset is reached
  425. fSynched = true;
  426. }
  427. rx_bytes = Recv(rx_head->fPacketSize, 0);
  428. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  429. return rx_bytes;
  430. }
  431. }
  432. int JackNetMasterInterface::DataRecv()
  433. {
  434. int rx_bytes = 0;
  435. uint recvd_midi_pckt = 0;
  436. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  437. while (!fRxHeader.fIsLastPckt) {
  438. // how much data is queued on the rx buffer ?
  439. rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
  440. // error here, problem with recv, just skip the cycle (return -1)
  441. if (rx_bytes == SOCKET_ERROR) {
  442. return rx_bytes;
  443. }
  444. if (rx_bytes && (rx_head->fDataStream == 'r') && (rx_head->fID == fParams.fID)) {
  445. // read data
  446. switch (rx_head->fDataType) {
  447. case 'm': // midi
  448. rx_bytes = MidiRecv(rx_head, fNetMidiPlaybackBuffer, recvd_midi_pckt);
  449. break;
  450. case 'a': // audio
  451. rx_bytes = AudioRecv(rx_head, fNetAudioPlaybackBuffer);
  452. break;
  453. case 's': // sync
  454. jack_info("NetMaster : missing last data packet from '%s'", fParams.fName);
  455. return FinishRecv(fNetAudioPlaybackBuffer);
  456. }
  457. }
  458. }
  459. return rx_bytes;
  460. }
  461. void JackNetMasterInterface::EncodeSyncPacket(int frames)
  462. {
  463. // This method contains every step of sync packet information coding
  464. // first of all, clear sync packet
  465. memset(fTxData, 0, PACKET_AVAILABLE_SIZE(&fParams));
  466. // Transport not used for now...
  467. /*
  468. // then, first step : transport
  469. if (fParams.fTransportSync) {
  470. EncodeTransportData();
  471. TransportDataHToN(&fSendTransportData, &fSendTransportData);
  472. // copy to TxBuffer
  473. memcpy(fTxData, &fSendTransportData, sizeof(net_transport_data_t));
  474. }
  475. // then others (freewheel etc.)
  476. // ...
  477. */
  478. // Write active ports list
  479. fTxHeader.fActivePorts = (fNetAudioPlaybackBuffer) ? fNetAudioPlaybackBuffer->ActivePortsToNetwork(fTxData) : 0;
  480. fTxHeader.fFrames = frames;
  481. }
  482. void JackNetMasterInterface::DecodeSyncPacket(int& frames)
  483. {
  484. // This method contains every step of sync packet information decoding process
  485. // Transport not used for now...
  486. /*
  487. // first : transport
  488. if (fParams.fTransportSync) {
  489. // copy received transport data to transport data structure
  490. memcpy(&fReturnTransportData, fRxData, sizeof(net_transport_data_t));
  491. TransportDataNToH(&fReturnTransportData, &fReturnTransportData);
  492. DecodeTransportData();
  493. }
  494. // then others
  495. // ...
  496. */
  497. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  498. // Read active ports list
  499. if (fNetAudioCaptureBuffer) {
  500. fNetAudioCaptureBuffer->ActivePortsFromNetwork(fRxData, rx_head->fActivePorts);
  501. }
  502. frames = rx_head->fFrames;
  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 = NETWORK_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 time_out_sec = %d", time_out_sec);
  548. int try_count = (time_out_sec > 0) ? int((1000000.f * float(time_out_sec)) / float(SLAVE_INIT_TIMEOUT)) : INT_MAX;
  549. // set the parameters to send
  550. strcpy(fParams.fPacketType, "params");
  551. fParams.fProtocolVersion = NETWORK_PROTOCOL;
  552. SetPacketType(&fParams, SLAVE_AVAILABLE);
  553. return (SendAvailableToMaster(try_count) == NET_CONNECTED);
  554. }
  555. bool JackNetSlaveInterface::InitRendering()
  556. {
  557. jack_log("JackNetSlaveInterface::InitRendering()");
  558. net_status_t status;
  559. do {
  560. // then tell the master we are ready
  561. jack_info("Initializing connection with %s...", fParams.fMasterNetName);
  562. status = SendStartToMaster();
  563. if (status == NET_ERROR) {
  564. return false;
  565. }
  566. }
  567. while (status != NET_ROLLING);
  568. return true;
  569. }
  570. net_status_t JackNetSlaveInterface::SendAvailableToMaster(int try_count)
  571. {
  572. jack_log("JackNetSlaveInterface::SendAvailableToMaster try_count = %d", try_count);
  573. // utility
  574. session_params_t host_params;
  575. int rx_bytes = 0;
  576. // socket
  577. if (fSocket.NewSocket() == SOCKET_ERROR) {
  578. jack_error("Fatal error : network unreachable - %s", StrError(NET_ERROR_CODE));
  579. return NET_SOCKET_ERROR;
  580. }
  581. if (fSocket.IsLocal(fMulticastIP)) {
  582. jack_info("Local IP is used...");
  583. } else {
  584. // bind the socket
  585. if (fSocket.Bind() == SOCKET_ERROR) {
  586. jack_error("Can't bind the socket : %s", StrError(NET_ERROR_CODE));
  587. return NET_SOCKET_ERROR;
  588. }
  589. }
  590. // timeout on receive (for init)
  591. if (fSocket.SetTimeOut(SLAVE_INIT_TIMEOUT) == SOCKET_ERROR) {
  592. jack_error("Can't set init timeout : %s", StrError(NET_ERROR_CODE));
  593. }
  594. // disable local loop
  595. if (fSocket.SetLocalLoop() == SOCKET_ERROR) {
  596. jack_error("Can't disable multicast loop : %s", StrError(NET_ERROR_CODE));
  597. }
  598. // send 'AVAILABLE' until 'SLAVE_SETUP' received
  599. jack_info("Waiting for a master...");
  600. do {
  601. // send 'available'
  602. session_params_t net_params;
  603. memset(&net_params, 0, sizeof(session_params_t));
  604. SessionParamsHToN(&fParams, &net_params);
  605. if (fSocket.SendTo(&net_params, sizeof(session_params_t), 0, fMulticastIP) == SOCKET_ERROR) {
  606. jack_error("Error in data send : %s", StrError(NET_ERROR_CODE));
  607. }
  608. // filter incoming packets : don't exit while no error is detected
  609. memset(&net_params, 0, sizeof(session_params_t));
  610. rx_bytes = fSocket.CatchHost(&net_params, sizeof(session_params_t), 0);
  611. SessionParamsNToH(&net_params, &host_params);
  612. if ((rx_bytes == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
  613. jack_error("Can't receive : %s", StrError(NET_ERROR_CODE));
  614. return NET_RECV_ERROR;
  615. }
  616. }
  617. while (strcmp(host_params.fPacketType, fParams.fPacketType) && (GetPacketType(&host_params) != SLAVE_SETUP) && (--try_count > 0));
  618. // time out failure..
  619. if (try_count == 0) {
  620. jack_error("Time out error in connect");
  621. return NET_CONNECT_ERROR;
  622. }
  623. // everything is OK, copy parameters
  624. fParams = host_params;
  625. // connect the socket
  626. if (fSocket.Connect() == SOCKET_ERROR) {
  627. jack_error("Error in connect : %s", StrError(NET_ERROR_CODE));
  628. return NET_CONNECT_ERROR;
  629. }
  630. return NET_CONNECTED;
  631. }
  632. net_status_t JackNetSlaveInterface::SendStartToMaster()
  633. {
  634. jack_log("JackNetSlaveInterface::SendStartToMaster");
  635. // tell the master to start
  636. session_params_t net_params;
  637. memset(&net_params, 0, sizeof(session_params_t));
  638. SetPacketType(&fParams, START_MASTER);
  639. SessionParamsHToN(&fParams, &net_params);
  640. if (fSocket.Send(&net_params, sizeof(session_params_t), 0) == SOCKET_ERROR) {
  641. jack_error("Error in send : %s", StrError(NET_ERROR_CODE));
  642. return (fSocket.GetError() == NET_CONN_ERROR) ? NET_ERROR : NET_SEND_ERROR;
  643. }
  644. return NET_ROLLING;
  645. }
  646. bool JackNetSlaveInterface::SetParams()
  647. {
  648. jack_log("JackNetSlaveInterface::SetParams audio in = %d audio out = %d MIDI in = %d MIDI out = %d",
  649. fParams.fSendAudioChannels, fParams.fReturnAudioChannels,
  650. fParams.fSendMidiChannels, fParams.fReturnMidiChannels);
  651. JackNetInterface::SetParams();
  652. fTxHeader.fDataStream = 'r';
  653. fRxHeader.fDataStream = 's';
  654. // midi net buffers
  655. if (fParams.fSendMidiChannels > 0) {
  656. fNetMidiCaptureBuffer = new NetMidiBuffer(&fParams, fParams.fSendMidiChannels, fRxData);
  657. }
  658. if (fParams.fReturnMidiChannels > 0) {
  659. fNetMidiPlaybackBuffer = new NetMidiBuffer(&fParams, fParams.fReturnMidiChannels, fTxData);
  660. }
  661. try {
  662. // audio net buffers
  663. if (fParams.fSendAudioChannels > 0) {
  664. fNetAudioCaptureBuffer = AudioBufferFactory(fParams.fSendAudioChannels, fRxData);
  665. assert(fNetAudioCaptureBuffer);
  666. }
  667. if (fParams.fReturnAudioChannels > 0) {
  668. fNetAudioPlaybackBuffer = AudioBufferFactory(fParams.fReturnAudioChannels, fTxData);
  669. assert(fNetAudioPlaybackBuffer);
  670. }
  671. } catch (exception&) {
  672. jack_error("NetAudioBuffer on slave allocation error...");
  673. return false;
  674. }
  675. // set the new buffer sizes
  676. if (SetNetBufferSize() == SOCKET_ERROR) {
  677. jack_error("Can't set net buffer sizes : %s", StrError(NET_ERROR_CODE));
  678. goto error;
  679. }
  680. return true;
  681. error:
  682. FreeNetworkBuffers();
  683. return false;
  684. }
  685. void JackNetSlaveInterface::FatalRecvError()
  686. {
  687. throw JackNetException("Recv connection lost error");
  688. }
  689. void JackNetSlaveInterface::FatalSendError()
  690. {
  691. throw JackNetException("Send connection lost error");
  692. }
  693. int JackNetSlaveInterface::Recv(size_t size, int flags)
  694. {
  695. int rx_bytes = fSocket.Recv(fRxBuffer, size, flags);
  696. // handle errors
  697. if (rx_bytes == SOCKET_ERROR) {
  698. FatalRecvError();
  699. }
  700. packet_header_t* header = reinterpret_cast<packet_header_t*>(fRxBuffer);
  701. PacketHeaderNToH(header, header);
  702. return rx_bytes;
  703. }
  704. int JackNetSlaveInterface::Send(size_t size, int flags)
  705. {
  706. packet_header_t* header = reinterpret_cast<packet_header_t*>(fTxBuffer);
  707. PacketHeaderHToN(header, header);
  708. int tx_bytes = fSocket.Send(fTxBuffer, size, flags);
  709. // handle errors
  710. if (tx_bytes == SOCKET_ERROR) {
  711. FatalSendError();
  712. }
  713. return tx_bytes;
  714. }
  715. int JackNetSlaveInterface::SyncRecv()
  716. {
  717. SetRcvTimeOut();
  718. int rx_bytes = 0;
  719. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  720. // receive sync (launch the cycle)
  721. do {
  722. rx_bytes = Recv(fParams.fMtu, 0);
  723. // connection issue (return -1)
  724. if (rx_bytes == SOCKET_ERROR) {
  725. return rx_bytes;
  726. }
  727. }
  728. while (strcmp(rx_head->fPacketType, "header") != 0);
  729. if (rx_head->fDataType != 's') {
  730. jack_error("Wrong packet type : %c", rx_head->fDataType);
  731. // not the last packet...
  732. fRxHeader.fIsLastPckt = 0;
  733. return SYNC_PACKET_ERROR;
  734. }
  735. //PacketHeaderDisplay(rx_head);
  736. fRxHeader.fIsLastPckt = rx_head->fIsLastPckt;
  737. return rx_bytes;
  738. }
  739. int JackNetSlaveInterface::DataRecv()
  740. {
  741. int rx_bytes = 0;
  742. uint recvd_midi_pckt = 0;
  743. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  744. while (!fRxHeader.fIsLastPckt) {
  745. // how much data is queued on the rx buffer ?
  746. rx_bytes = Recv(fParams.fMtu, MSG_PEEK);
  747. // error here, just skip the cycle (return -1)
  748. if (rx_bytes == SOCKET_ERROR) {
  749. return rx_bytes;
  750. }
  751. if (rx_bytes && (rx_head->fDataStream == 's') && (rx_head->fID == fParams.fID)) {
  752. // read data
  753. switch (rx_head->fDataType) {
  754. case 'm': // midi
  755. rx_bytes = MidiRecv(rx_head, fNetMidiCaptureBuffer, recvd_midi_pckt);
  756. break;
  757. case 'a': // audio
  758. rx_bytes = AudioRecv(rx_head, fNetAudioCaptureBuffer);
  759. break;
  760. case 's': // sync
  761. jack_info("NetSlave : missing last data packet");
  762. return FinishRecv(fNetAudioCaptureBuffer);
  763. }
  764. }
  765. }
  766. fRxHeader.fCycle = rx_head->fCycle;
  767. return rx_bytes;
  768. }
  769. int JackNetSlaveInterface::SyncSend()
  770. {
  771. // tx header
  772. if (fParams.fSlaveSyncMode) {
  773. fTxHeader.fCycle = fRxHeader.fCycle;
  774. } else {
  775. fTxHeader.fCycle++;
  776. }
  777. fTxHeader.fSubCycle = 0;
  778. fTxHeader.fDataType = 's';
  779. fTxHeader.fIsLastPckt = (fParams.fReturnMidiChannels == 0 && fParams.fReturnAudioChannels == 0) ? 1 : 0;
  780. fTxHeader.fPacketSize = HEADER_SIZE + fTxHeader.fActivePorts * sizeof(int); // Data part is used to encode active ports
  781. memcpy(fTxBuffer, &fTxHeader, HEADER_SIZE);
  782. //PacketHeaderDisplay(&fTxHeader);
  783. return Send(fTxHeader.fPacketSize, 0);
  784. }
  785. int JackNetSlaveInterface::DataSend()
  786. {
  787. if (MidiSend(fNetMidiPlaybackBuffer, fParams.fReturnMidiChannels, fParams.fReturnAudioChannels) == SOCKET_ERROR) {
  788. return SOCKET_ERROR;
  789. }
  790. return AudioSend(fNetAudioPlaybackBuffer, fParams.fReturnAudioChannels);
  791. }
  792. // network sync------------------------------------------------------------------------
  793. void JackNetSlaveInterface::EncodeSyncPacket(int frames)
  794. {
  795. // This method contains every step of sync packet information coding
  796. // first of all, clear sync packet
  797. memset(fTxData, 0, PACKET_AVAILABLE_SIZE(&fParams));
  798. // then first step : transport
  799. // Transport is not used for now...
  800. /*
  801. if (fParams.fTransportSync) {
  802. EncodeTransportData();
  803. TransportDataHToN(&fReturnTransportData, &fReturnTransportData);
  804. // copy to TxBuffer
  805. memcpy(fTxData, &fReturnTransportData, sizeof(net_transport_data_t));
  806. }
  807. // then others
  808. // ...
  809. */
  810. // Write active ports list
  811. fTxHeader.fActivePorts = (fNetAudioCaptureBuffer) ? fNetAudioCaptureBuffer->ActivePortsToNetwork(fTxData) : 0;
  812. fTxHeader.fFrames = frames;
  813. }
  814. void JackNetSlaveInterface::DecodeSyncPacket(int& frames)
  815. {
  816. // This method contains every step of sync packet information decoding process
  817. // Transport not used for now...
  818. /*
  819. // first : transport
  820. if (fParams.fTransportSync) {
  821. // copy received transport data to transport data structure
  822. memcpy(&fSendTransportData, fRxData, sizeof(net_transport_data_t));
  823. TransportDataNToH(&fSendTransportData, &fSendTransportData);
  824. DecodeTransportData();
  825. }
  826. // then others
  827. // ...
  828. */
  829. packet_header_t* rx_head = reinterpret_cast<packet_header_t*>(fRxBuffer);
  830. // Read active ports list
  831. if (fNetAudioPlaybackBuffer) {
  832. fNetAudioPlaybackBuffer->ActivePortsFromNetwork(fRxData, rx_head->fActivePorts);
  833. }
  834. frames = rx_head->fFrames;
  835. }
  836. }