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.

527 lines
19KB

  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 "JackNetAdapter.h"
  16. #include "JackException.h"
  17. #include "JackServerGlobals.h"
  18. #include "JackEngineControl.h"
  19. #include "JackArgParser.h"
  20. #include <assert.h>
  21. namespace Jack
  22. {
  23. JackNetAdapter::JackNetAdapter(jack_client_t* jack_client, jack_nframes_t buffer_size, jack_nframes_t sample_rate, const JSList* params)
  24. : JackAudioAdapterInterface(buffer_size, sample_rate), JackNetSlaveInterface(), fThread(this)
  25. {
  26. jack_log("JackNetAdapter::JackNetAdapter");
  27. /*
  28. Global parameter setting : we can't call JackNetSlaveInterface constructor with some parameters before,
  29. because we don't have full parametering right now, parameters will be parsed from the param list,
  30. and then JackNetSlaveInterface will be filled with proper values.
  31. */
  32. char multicast_ip[32];
  33. uint udp_port;
  34. GetHostName(fParams.fName, JACK_CLIENT_NAME_SIZE);
  35. fSocket.GetName(fParams.fSlaveNetName);
  36. fParams.fMtu = DEFAULT_MTU;
  37. // Deactivated for now...
  38. fParams.fTransportSync = 0;
  39. int send_audio = -1;
  40. int return_audio = -1;
  41. fParams.fSendMidiChannels = 0;
  42. fParams.fReturnMidiChannels = 0;
  43. fParams.fSampleRate = sample_rate;
  44. fParams.fPeriodSize = buffer_size;
  45. fParams.fSlaveSyncMode = 1;
  46. fParams.fNetworkLatency = NETWORK_DEFAULT_LATENCY;
  47. fParams.fSampleEncoder = JackFloatEncoder;
  48. fClient = jack_client;
  49. // Possibly use env variable
  50. const char* default_udp_port = getenv("JACK_NETJACK_PORT");
  51. udp_port = (default_udp_port) ? atoi(default_udp_port) : DEFAULT_PORT;
  52. const char* default_multicast_ip = getenv("JACK_NETJACK_MULTICAST");
  53. if (default_multicast_ip) {
  54. strcpy(multicast_ip, default_multicast_ip);
  55. } else {
  56. strcpy(multicast_ip, DEFAULT_MULTICAST_IP);
  57. }
  58. //options parsing
  59. const JSList* node;
  60. const jack_driver_param_t* param;
  61. for (node = params; node; node = jack_slist_next(node))
  62. {
  63. param = (const jack_driver_param_t*) node->data;
  64. switch (param->character) {
  65. case 'a' :
  66. assert(strlen(param->value.str) < 32);
  67. strcpy(multicast_ip, param->value.str);
  68. break;
  69. case 'p' :
  70. udp_port = param->value.ui;
  71. break;
  72. case 'M' :
  73. fParams.fMtu = param->value.i;
  74. break;
  75. case 'C' :
  76. send_audio = param->value.i;
  77. break;
  78. case 'P' :
  79. return_audio = param->value.i;
  80. break;
  81. case 'n' :
  82. strncpy(fParams.fName, param->value.str, JACK_CLIENT_NAME_SIZE);
  83. break;
  84. case 't' :
  85. fParams.fTransportSync = param->value.ui;
  86. break;
  87. #if HAVE_CELT
  88. case 'c':
  89. if (param->value.i > 0) {
  90. fParams.fSampleEncoder = JackCeltEncoder;
  91. fParams.fKBps = param->value.i;
  92. }
  93. break;
  94. #endif
  95. #if HAVE_OPUS
  96. case 'O':
  97. if (param->value.i > 0) {
  98. fParams.fSampleEncoder = JackOpusEncoder;
  99. fParams.fKBps = param->value.i;
  100. }
  101. break;
  102. #endif
  103. case 'l' :
  104. fParams.fNetworkLatency = param->value.i;
  105. if (fParams.fNetworkLatency > NETWORK_MAX_LATENCY) {
  106. jack_error("Error : network latency is limited to %d\n", NETWORK_MAX_LATENCY);
  107. throw std::bad_alloc();
  108. }
  109. break;
  110. case 'q':
  111. fQuality = param->value.ui;
  112. break;
  113. case 'g':
  114. fRingbufferCurSize = param->value.ui;
  115. fAdaptative = false;
  116. break;
  117. }
  118. }
  119. strcpy(fMulticastIP, multicast_ip);
  120. // Set the socket parameters
  121. fSocket.SetPort(udp_port);
  122. fSocket.SetAddress(fMulticastIP, udp_port);
  123. // If not set, takes default
  124. fParams.fSendAudioChannels = (send_audio == -1) ? 2 : send_audio;
  125. // If not set, takes default
  126. fParams.fReturnAudioChannels = (return_audio == -1) ? 2 : return_audio;
  127. // Set the audio adapter interface channel values
  128. SetInputs(fParams.fSendAudioChannels);
  129. SetOutputs(fParams.fReturnAudioChannels);
  130. // Soft buffers will be allocated later (once network initialization done)
  131. fSoftCaptureBuffer = NULL;
  132. fSoftPlaybackBuffer = NULL;
  133. }
  134. JackNetAdapter::~JackNetAdapter()
  135. {
  136. jack_log("JackNetAdapter::~JackNetAdapter");
  137. if (fSoftCaptureBuffer) {
  138. for (int port_index = 0; port_index < fCaptureChannels; port_index++) {
  139. delete[] fSoftCaptureBuffer[port_index];
  140. }
  141. delete[] fSoftCaptureBuffer;
  142. }
  143. if (fSoftPlaybackBuffer) {
  144. for (int port_index = 0; port_index < fPlaybackChannels; port_index++) {
  145. delete[] fSoftPlaybackBuffer[port_index];
  146. }
  147. delete[] fSoftPlaybackBuffer;
  148. }
  149. }
  150. //open/close--------------------------------------------------------------------------
  151. int JackNetAdapter::Open()
  152. {
  153. jack_info("NetAdapter started in %s mode %s Master's transport sync.",
  154. (fParams.fSlaveSyncMode) ? "sync" : "async", (fParams.fTransportSync) ? "with" : "without");
  155. if (fThread.StartSync() < 0) {
  156. jack_error("Cannot start netadapter thread");
  157. return -1;
  158. }
  159. return 0;
  160. }
  161. int JackNetAdapter::Close()
  162. {
  163. int res = 0;
  164. jack_log("JackNetAdapter::Close");
  165. #ifdef JACK_MONITOR
  166. fTable.Save(fHostBufferSize, fHostSampleRate, fAdaptedSampleRate, fAdaptedBufferSize);
  167. #endif
  168. if (fThread.Kill() < 0) {
  169. jack_error("Cannot kill thread");
  170. res = -1;
  171. }
  172. fSocket.Close();
  173. return res;
  174. }
  175. int JackNetAdapter::SetBufferSize(jack_nframes_t buffer_size)
  176. {
  177. JackAudioAdapterInterface::SetHostBufferSize(buffer_size);
  178. return 0;
  179. }
  180. //thread------------------------------------------------------------------------------
  181. // TODO : if failure, thread exist... need to restart ?
  182. bool JackNetAdapter::Init()
  183. {
  184. jack_log("JackNetAdapter::Init");
  185. //init network connection
  186. if (!JackNetSlaveInterface::Init()) {
  187. jack_error("JackNetSlaveInterface::Init() error...");
  188. return false;
  189. }
  190. //then set global parameters
  191. if (!SetParams()) {
  192. jack_error("SetParams error...");
  193. return false;
  194. }
  195. //set buffers
  196. if (fCaptureChannels > 0) {
  197. fSoftCaptureBuffer = new sample_t*[fCaptureChannels];
  198. for (int port_index = 0; port_index < fCaptureChannels; port_index++) {
  199. fSoftCaptureBuffer[port_index] = new sample_t[fParams.fPeriodSize];
  200. fNetAudioCaptureBuffer->SetBuffer(port_index, fSoftCaptureBuffer[port_index]);
  201. }
  202. }
  203. if (fPlaybackChannels > 0) {
  204. fSoftPlaybackBuffer = new sample_t*[fPlaybackChannels];
  205. for (int port_index = 0; port_index < fPlaybackChannels; port_index++) {
  206. fSoftPlaybackBuffer[port_index] = new sample_t[fParams.fPeriodSize];
  207. fNetAudioPlaybackBuffer->SetBuffer(port_index, fSoftPlaybackBuffer[port_index]);
  208. }
  209. }
  210. //set audio adapter parameters
  211. SetAdaptedBufferSize(fParams.fPeriodSize);
  212. SetAdaptedSampleRate(fParams.fSampleRate);
  213. // Will do "something" on OSX only...
  214. fThread.SetParams(GetEngineControl()->fPeriod, GetEngineControl()->fComputation, GetEngineControl()->fConstraint);
  215. if (fThread.AcquireSelfRealTime(GetEngineControl()->fClientPriority) < 0) {
  216. jack_error("AcquireSelfRealTime error");
  217. } else {
  218. set_threaded_log_function();
  219. }
  220. //init done, display parameters
  221. SessionParamsDisplay(&fParams);
  222. return true;
  223. }
  224. bool JackNetAdapter::Execute()
  225. {
  226. try {
  227. // Keep running even in case of error
  228. while (fThread.GetStatus() == JackThread::kRunning) {
  229. if (Process() == SOCKET_ERROR) {
  230. return false;
  231. }
  232. }
  233. return false;
  234. } catch (JackNetException& e) {
  235. // Otherwise just restart...
  236. e.PrintMessage();
  237. jack_info("NetAdapter is restarted");
  238. Reset();
  239. fThread.DropSelfRealTime();
  240. fThread.SetStatus(JackThread::kIniting);
  241. if (Init()) {
  242. fThread.SetStatus(JackThread::kRunning);
  243. return true;
  244. } else {
  245. return false;
  246. }
  247. }
  248. }
  249. //transport---------------------------------------------------------------------------
  250. void JackNetAdapter::DecodeTransportData()
  251. {
  252. //TODO : we need here to get the actual timebase master to eventually release it from its duty (see JackNetDriver)
  253. //is there a new transport state ?
  254. if (fSendTransportData.fNewState &&(fSendTransportData.fState != jack_transport_query(fClient, NULL))) {
  255. switch (fSendTransportData.fState)
  256. {
  257. case JackTransportStopped :
  258. jack_transport_stop(fClient);
  259. jack_info("NetMaster : transport stops");
  260. break;
  261. case JackTransportStarting :
  262. jack_transport_reposition(fClient, &fSendTransportData.fPosition);
  263. jack_transport_start(fClient);
  264. jack_info("NetMaster : transport starts");
  265. break;
  266. case JackTransportRolling :
  267. // TODO, we need to :
  268. // - find a way to call TransportEngine->SetNetworkSync()
  269. // - turn the transport state to JackTransportRolling
  270. jack_info("NetMaster : transport rolls");
  271. break;
  272. }
  273. }
  274. }
  275. void JackNetAdapter::EncodeTransportData()
  276. {
  277. //is there a timebase master change ?
  278. int refnum = -1;
  279. bool conditional = 0;
  280. //TODO : get the actual timebase master
  281. if (refnum != fLastTimebaseMaster) {
  282. //timebase master has released its function
  283. if (refnum == -1) {
  284. fReturnTransportData.fTimebaseMaster = RELEASE_TIMEBASEMASTER;
  285. jack_info("Sending a timebase master release request.");
  286. } else {
  287. //there is a new timebase master
  288. fReturnTransportData.fTimebaseMaster = (conditional) ? CONDITIONAL_TIMEBASEMASTER : TIMEBASEMASTER;
  289. jack_info("Sending a %s timebase master request.", (conditional) ? "conditional" : "non-conditional");
  290. }
  291. fLastTimebaseMaster = refnum;
  292. } else {
  293. fReturnTransportData.fTimebaseMaster = NO_CHANGE;
  294. }
  295. //update transport state and position
  296. fReturnTransportData.fState = jack_transport_query(fClient, &fReturnTransportData.fPosition);
  297. //is it a new state (that the master need to know...) ?
  298. fReturnTransportData.fNewState = ((fReturnTransportData.fState != fLastTransportState) &&
  299. (fReturnTransportData.fState != fSendTransportData.fState));
  300. if (fReturnTransportData.fNewState) {
  301. jack_info("Sending transport state '%s'.", GetTransportState(fReturnTransportData.fState));
  302. }
  303. fLastTransportState = fReturnTransportData.fState;
  304. }
  305. //read/write operations---------------------------------------------------------------
  306. int JackNetAdapter::Read()
  307. {
  308. switch (SyncRecv()) {
  309. case SOCKET_ERROR:
  310. return SOCKET_ERROR;
  311. case SYNC_PACKET_ERROR:
  312. // Since sync packet is incorrect, don't decode it and continue with data
  313. break;
  314. default:
  315. //decode sync
  316. int unused_frames;
  317. DecodeSyncPacket(unused_frames);
  318. break;
  319. }
  320. return DataRecv();
  321. }
  322. int JackNetAdapter::Write()
  323. {
  324. EncodeSyncPacket();
  325. if (SyncSend() == SOCKET_ERROR) {
  326. return SOCKET_ERROR;
  327. }
  328. return DataSend();
  329. }
  330. //process-----------------------------------------------------------------------------
  331. int JackNetAdapter::Process()
  332. {
  333. //read data from the network
  334. //in case of fatal network error, stop the process
  335. if (Read() == SOCKET_ERROR) {
  336. return SOCKET_ERROR;
  337. }
  338. PushAndPull(fSoftCaptureBuffer, fSoftPlaybackBuffer, fAdaptedBufferSize);
  339. //then write data to network
  340. //in case of failure, stop process
  341. if (Write() == SOCKET_ERROR) {
  342. return SOCKET_ERROR;
  343. }
  344. return 0;
  345. }
  346. } // namespace Jack
  347. //loader------------------------------------------------------------------------------
  348. #ifdef __cplusplus
  349. extern "C"
  350. {
  351. #endif
  352. #include "driver_interface.h"
  353. #include "JackAudioAdapter.h"
  354. using namespace Jack;
  355. SERVER_EXPORT jack_driver_desc_t* jack_get_descriptor()
  356. {
  357. jack_driver_desc_t * desc;
  358. jack_driver_desc_filler_t filler;
  359. jack_driver_param_value_t value;
  360. desc = jack_driver_descriptor_construct("netadapter", JackDriverNone, "netjack net <==> audio backend adapter", &filler);
  361. strcpy(value.str, DEFAULT_MULTICAST_IP);
  362. jack_driver_descriptor_add_parameter(desc, &filler, "multicast-ip", 'a', JackDriverParamString, &value, NULL, "Multicast address, or explicit IP of the master", NULL);
  363. value.i = DEFAULT_PORT;
  364. jack_driver_descriptor_add_parameter(desc, &filler, "udp-net-port", 'p', JackDriverParamInt, &value, NULL, "UDP port", NULL);
  365. value.i = DEFAULT_MTU;
  366. jack_driver_descriptor_add_parameter(desc, &filler, "mtu", 'M', JackDriverParamInt, &value, NULL, "MTU to the master", NULL);
  367. value.i = 2;
  368. jack_driver_descriptor_add_parameter(desc, &filler, "input-ports", 'C', JackDriverParamInt, &value, NULL, "Number of audio input ports", NULL);
  369. jack_driver_descriptor_add_parameter(desc, &filler, "output-ports", 'P', JackDriverParamInt, &value, NULL, "Number of audio output ports", NULL);
  370. #if HAVE_CELT
  371. value.i = -1;
  372. jack_driver_descriptor_add_parameter(desc, &filler, "celt", 'c', JackDriverParamInt, &value, NULL, "Set CELT encoding and number of kBits per channel", NULL);
  373. #endif
  374. #if HAVE_OPUS
  375. value.i = -1;
  376. jack_driver_descriptor_add_parameter(desc, &filler, "opus", 'O', JackDriverParamInt, &value, NULL, "Set Opus encoding and number of kBits per channel", NULL);
  377. #endif
  378. strcpy(value.str, "'hostname'");
  379. jack_driver_descriptor_add_parameter(desc, &filler, "client-name", 'n', JackDriverParamString, &value, NULL, "Name of the jack client", NULL);
  380. value.ui = 0U;
  381. jack_driver_descriptor_add_parameter(desc, &filler, "transport-sync", 't', JackDriverParamUInt, &value, NULL, "Sync transport with master's", NULL);
  382. value.ui = 5U;
  383. jack_driver_descriptor_add_parameter(desc, &filler, "latency", 'l', JackDriverParamUInt, &value, NULL, "Network latency", NULL);
  384. value.i = 0;
  385. jack_driver_descriptor_add_parameter(desc, &filler, "quality", 'q', JackDriverParamInt, &value, NULL, "Resample algorithm quality (0 - 4)", NULL);
  386. value.i = 32768;
  387. jack_driver_descriptor_add_parameter(desc, &filler, "ring-buffer", 'g', JackDriverParamInt, &value, NULL, "Fixed ringbuffer size", "Fixed ringbuffer size (if not set => automatic adaptative)");
  388. value.i = false;
  389. jack_driver_descriptor_add_parameter(desc, &filler, "auto-connect", 'c', JackDriverParamBool, &value, NULL, "Auto connect netadapter to system ports", NULL);
  390. return desc;
  391. }
  392. SERVER_EXPORT int jack_internal_initialize(jack_client_t* client, const JSList* params)
  393. {
  394. jack_log("Loading netadapter");
  395. Jack::JackAudioAdapter* adapter;
  396. jack_nframes_t buffer_size = jack_get_buffer_size(client);
  397. jack_nframes_t sample_rate = jack_get_sample_rate(client);
  398. try {
  399. adapter = new Jack::JackAudioAdapter(client, new Jack::JackNetAdapter(client, buffer_size, sample_rate, params), params);
  400. assert(adapter);
  401. if (adapter->Open() == 0) {
  402. return 0;
  403. } else {
  404. delete adapter;
  405. return 1;
  406. }
  407. } catch (...) {
  408. jack_info("netadapter allocation error");
  409. return 1;
  410. }
  411. }
  412. SERVER_EXPORT int jack_initialize(jack_client_t* jack_client, const char* load_init)
  413. {
  414. JSList* params = NULL;
  415. bool parse_params = true;
  416. int res = 1;
  417. jack_driver_desc_t* desc = jack_get_descriptor();
  418. Jack::JackArgParser parser(load_init);
  419. if (parser.GetArgc() > 0) {
  420. parse_params = parser.ParseParams(desc, &params);
  421. }
  422. if (parse_params) {
  423. res = jack_internal_initialize(jack_client, params);
  424. parser.FreeParams(params);
  425. }
  426. return res;
  427. }
  428. SERVER_EXPORT void jack_finish(void* arg)
  429. {
  430. Jack::JackAudioAdapter* adapter = static_cast<Jack::JackAudioAdapter*>(arg);
  431. if (adapter) {
  432. jack_log("Unloading netadapter");
  433. adapter->Close();
  434. delete adapter;
  435. }
  436. }
  437. #ifdef __cplusplus
  438. }
  439. #endif