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.

1254 lines
42KB

  1. /*
  2. Copyright (C) 2009-2013 Grame
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU Lesser General Public License as published by
  5. the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  14. */
  15. #include <assert.h>
  16. #include <stdarg.h>
  17. #include "JackNetInterface.h"
  18. #include "JackAudioAdapterInterface.h"
  19. #ifdef __cplusplus
  20. extern "C"
  21. {
  22. #endif
  23. // NetJack common API
  24. #define MASTER_NAME_SIZE 256
  25. enum JackNetEncoder {
  26. JackFloatEncoder = 0,
  27. JackIntEncoder = 1,
  28. JackCeltEncoder = 2,
  29. JackOpusEncoder = 3
  30. };
  31. typedef struct {
  32. int audio_input;
  33. int audio_output;
  34. int midi_input;
  35. int midi_output;
  36. int mtu;
  37. int time_out; // in millisecond, -1 means in infinite
  38. int encoder; // one of JackNetEncoder
  39. int kbps; // KB per second for CELT encoder
  40. int latency; // network cycles
  41. } jack_slave_t;
  42. typedef struct {
  43. int audio_input;
  44. int audio_output;
  45. int midi_input;
  46. int midi_output;
  47. jack_nframes_t buffer_size;
  48. jack_nframes_t sample_rate;
  49. char master_name[MASTER_NAME_SIZE];
  50. int time_out;
  51. int partial_cycle;
  52. } jack_master_t;
  53. // NetJack slave API
  54. typedef struct _jack_net_slave jack_net_slave_t;
  55. typedef int (* JackNetSlaveProcessCallback) (jack_nframes_t buffer_size,
  56. int audio_input,
  57. float** audio_input_buffer,
  58. int midi_input,
  59. void** midi_input_buffer,
  60. int audio_output,
  61. float** audio_output_buffer,
  62. int midi_output,
  63. void** midi_output_buffer,
  64. void* data);
  65. typedef int (*JackNetSlaveBufferSizeCallback) (jack_nframes_t nframes, void *arg);
  66. typedef int (*JackNetSlaveSampleRateCallback) (jack_nframes_t nframes, void *arg);
  67. typedef void (*JackNetSlaveShutdownCallback) (void* arg);
  68. typedef int (*JackNetSlaveRestartCallback) (void* arg);
  69. typedef void (*JackNetSlaveErrorCallback) (int error_code, void* arg);
  70. LIB_EXPORT jack_net_slave_t* jack_net_slave_open(const char* ip, int port, const char* name, jack_slave_t* request, jack_master_t* result);
  71. LIB_EXPORT int jack_net_slave_close(jack_net_slave_t* net);
  72. LIB_EXPORT int jack_net_slave_activate(jack_net_slave_t* net);
  73. LIB_EXPORT int jack_net_slave_deactivate(jack_net_slave_t* net);
  74. LIB_EXPORT int jack_net_slave_is_active(jack_net_slave_t* net);
  75. LIB_EXPORT int jack_set_net_slave_process_callback(jack_net_slave_t* net, JackNetSlaveProcessCallback net_callback, void *arg);
  76. LIB_EXPORT int jack_set_net_slave_buffer_size_callback(jack_net_slave_t* net, JackNetSlaveBufferSizeCallback bufsize_callback, void *arg);
  77. LIB_EXPORT int jack_set_net_slave_sample_rate_callback(jack_net_slave_t* net, JackNetSlaveSampleRateCallback samplerate_callback, void *arg);
  78. LIB_EXPORT int jack_set_net_slave_shutdown_callback(jack_net_slave_t* net, JackNetSlaveShutdownCallback shutdown_callback, void *arg);
  79. LIB_EXPORT int jack_set_net_slave_restart_callback(jack_net_slave_t* net, JackNetSlaveRestartCallback restart_callback, void *arg);
  80. LIB_EXPORT int jack_set_net_slave_error_callback(jack_net_slave_t* net, JackNetSlaveErrorCallback error_callback, void *arg);
  81. // NetJack master API
  82. typedef struct _jack_net_master jack_net_master_t;
  83. LIB_EXPORT jack_net_master_t* jack_net_master_open(const char* ip, int port, jack_master_t* request, jack_slave_t* result);
  84. LIB_EXPORT int jack_net_master_close(jack_net_master_t* net);
  85. LIB_EXPORT int jack_net_master_recv(jack_net_master_t* net, int audio_input, float** audio_input_buffer, int midi_input, void** midi_input_buffer);
  86. LIB_EXPORT int jack_net_master_send(jack_net_master_t* net, int audio_output, float** audio_output_buffer, int midi_output, void** midi_output_buffer);
  87. LIB_EXPORT int jack_net_master_recv_slice(jack_net_master_t* net, int audio_input, float** audio_input_buffer, int midi_input, void** midi_input_buffer, int frames);
  88. LIB_EXPORT int jack_net_master_send_slice(jack_net_master_t* net, int audio_output, float** audio_output_buffer, int midi_output, void** midi_output_buffer, int frames);
  89. // NetJack adapter API
  90. typedef struct _jack_adapter jack_adapter_t;
  91. LIB_EXPORT jack_adapter_t* jack_create_adapter(int input, int output,
  92. jack_nframes_t host_buffer_size,
  93. jack_nframes_t host_sample_rate,
  94. jack_nframes_t adapted_buffer_size,
  95. jack_nframes_t adapted_sample_rate);
  96. LIB_EXPORT int jack_destroy_adapter(jack_adapter_t* adapter);
  97. LIB_EXPORT void jack_flush_adapter(jack_adapter_t* adapter);
  98. LIB_EXPORT int jack_adapter_push_and_pull(jack_adapter_t* adapter, float** input, float** output, unsigned int frames);
  99. LIB_EXPORT int jack_adapter_pull_and_push(jack_adapter_t* adapter, float** input, float** output, unsigned int frames);
  100. #define LOG_LEVEL_INFO 1
  101. #define LOG_LEVEL_ERROR 2
  102. LIB_EXPORT void jack_error(const char *fmt, ...);
  103. LIB_EXPORT void jack_info(const char *fmt, ...);
  104. LIB_EXPORT void jack_log(const char *fmt, ...);
  105. #ifdef __cplusplus
  106. }
  107. #endif
  108. namespace Jack
  109. {
  110. struct JackNetExtMaster : public JackNetMasterInterface {
  111. jack_master_t fRequest;
  112. JackRingBuffer** fRingBuffer;
  113. JackNetExtMaster(const char* ip,
  114. int port,
  115. jack_master_t* request)
  116. {
  117. fRunning = true;
  118. assert(strlen(ip) < 32);
  119. strcpy(fMulticastIP, ip);
  120. fSocket.SetPort(port);
  121. fRequest.buffer_size = request->buffer_size;
  122. fRequest.sample_rate = request->sample_rate;
  123. fRequest.audio_input = request->audio_input;
  124. fRequest.audio_output = request->audio_output;
  125. fRequest.time_out = request->time_out;
  126. fRequest.partial_cycle = request->partial_cycle;
  127. fRingBuffer = NULL;
  128. }
  129. virtual ~JackNetExtMaster()
  130. {
  131. if (fRingBuffer) {
  132. for (int i = 0; i < fParams.fReturnAudioChannels; i++) {
  133. delete fRingBuffer[i];
  134. }
  135. delete [] fRingBuffer;
  136. }
  137. }
  138. int Open(jack_slave_t* result)
  139. {
  140. // Check buffer_size
  141. if (fRequest.buffer_size == 0) {
  142. jack_error("Incorrect buffer_size...");
  143. return -1;
  144. }
  145. // Check sample_rate
  146. if (fRequest.sample_rate == 0) {
  147. jack_error("Incorrect sample_rate...");
  148. return -1;
  149. }
  150. // Init socket API (win32)
  151. if (SocketAPIInit() < 0) {
  152. jack_error("Can't init Socket API, exiting...");
  153. return -1;
  154. }
  155. // Request socket
  156. if (fSocket.NewSocket() == SOCKET_ERROR) {
  157. jack_error("Can't create the network manager input socket : %s", StrError(NET_ERROR_CODE));
  158. return -1;
  159. }
  160. // Bind the socket to the local port
  161. if (fSocket.Bind() == SOCKET_ERROR) {
  162. jack_error("Can't bind the network manager socket : %s", StrError(NET_ERROR_CODE));
  163. fSocket.Close();
  164. return -1;
  165. }
  166. // Join multicast group
  167. if (fSocket.JoinMCastGroup(fMulticastIP) == SOCKET_ERROR) {
  168. jack_error("Can't join multicast group : %s", StrError(NET_ERROR_CODE));
  169. }
  170. // Local loop
  171. if (fSocket.SetLocalLoop() == SOCKET_ERROR) {
  172. jack_error("Can't set local loop : %s", StrError(NET_ERROR_CODE));
  173. }
  174. // Set a timeout on the multicast receive (the thread can now be cancelled)
  175. if (fSocket.SetTimeOut(MANAGER_INIT_TIMEOUT) == SOCKET_ERROR) {
  176. jack_error("Can't set timeout : %s", StrError(NET_ERROR_CODE));
  177. }
  178. // Main loop, wait for data, deal with it and wait again
  179. int attempt = 0;
  180. int rx_bytes = 0;
  181. int try_count = (fRequest.time_out > 0) ? int((1000000.f * float(fRequest.time_out)) / float(MANAGER_INIT_TIMEOUT)) : INT_MAX;
  182. do
  183. {
  184. session_params_t net_params;
  185. rx_bytes = fSocket.CatchHost(&net_params, sizeof(session_params_t), 0);
  186. SessionParamsNToH(&net_params, &fParams);
  187. if ((rx_bytes == SOCKET_ERROR) && (fSocket.GetError() != NET_NO_DATA)) {
  188. jack_error("Error in receive : %s", StrError(NET_ERROR_CODE));
  189. if (++attempt == 10) {
  190. jack_error("Can't receive on the socket, exiting net manager" );
  191. goto error;
  192. }
  193. }
  194. if (rx_bytes == sizeof(session_params_t)) {
  195. switch (GetPacketType(&fParams)) {
  196. case SLAVE_AVAILABLE:
  197. if (InitMaster(result) == 0) {
  198. SessionParamsDisplay(&fParams);
  199. fRunning = false;
  200. } else {
  201. jack_error("Can't init new net master...");
  202. goto error;
  203. }
  204. jack_info("Waiting for a slave...");
  205. break;
  206. case KILL_MASTER:
  207. break;
  208. default:
  209. break;
  210. }
  211. }
  212. }
  213. while (fRunning && (--try_count > 0));
  214. if (try_count == 0) {
  215. jack_error("Time out error in connect");
  216. return -1;
  217. }
  218. // Set result parameters
  219. result->audio_input = fParams.fSendAudioChannels;
  220. result->audio_output = fParams.fReturnAudioChannels;
  221. result->midi_input = fParams.fSendMidiChannels;
  222. result->midi_output = fParams.fReturnMidiChannels;
  223. result->mtu = fParams.fMtu;
  224. result->latency = fParams.fNetworkLatency;
  225. // Use ringbuffer in case of partial cycle and latency > 0
  226. if (fRequest.partial_cycle && result->latency > 0) {
  227. fRingBuffer = new JackRingBuffer*[fParams.fReturnAudioChannels];
  228. for (int i = 0; i < fParams.fReturnAudioChannels; i++) {
  229. fRingBuffer[i] = new JackRingBuffer(fRequest.buffer_size * result->latency * 2);
  230. }
  231. }
  232. return 0;
  233. error:
  234. fSocket.Close();
  235. return -1;
  236. }
  237. int InitMaster(jack_slave_t* result)
  238. {
  239. // Check MASTER <==> SLAVE network protocol coherency
  240. if (fParams.fProtocolVersion != NETWORK_PROTOCOL) {
  241. jack_error("Error : slave '%s' is running with a different protocol %d != %d", fParams.fName, fParams.fProtocolVersion, NETWORK_PROTOCOL);
  242. return -1;
  243. }
  244. // Settings
  245. fSocket.GetName(fParams.fMasterNetName);
  246. fParams.fID = 1;
  247. fParams.fPeriodSize = fRequest.buffer_size;
  248. fParams.fSampleRate = fRequest.sample_rate;
  249. if (fRequest.audio_input == -1) {
  250. if (fParams.fSendAudioChannels == -1) {
  251. jack_error("Error : master and slave use -1 for wanted inputs...");
  252. return -1;
  253. } else {
  254. result->audio_input = fParams.fSendAudioChannels;
  255. jack_info("Takes slave %d inputs", fParams.fSendAudioChannels);
  256. }
  257. } else if (fParams.fSendAudioChannels == -1) {
  258. fParams.fSendAudioChannels = fRequest.audio_input;
  259. jack_info("Takes master %d inputs", fRequest.audio_input);
  260. } else if (fParams.fSendAudioChannels != fRequest.audio_input) {
  261. jack_error("Error : master wants %d inputs and slave wants %d inputs...", fRequest.audio_input, fParams.fSendAudioChannels);
  262. return -1;
  263. }
  264. if (fRequest.audio_output == -1) {
  265. if (fParams.fReturnAudioChannels == -1) {
  266. jack_error("Error : master and slave use -1 for wanted outputs...");
  267. return -1;
  268. } else {
  269. result->audio_output = fParams.fReturnAudioChannels;
  270. jack_info("Takes slave %d outputs", fParams.fReturnAudioChannels);
  271. }
  272. } else if (fParams.fReturnAudioChannels == -1) {
  273. fParams.fReturnAudioChannels = fRequest.audio_output;
  274. jack_info("Takes master %d outputs", fRequest.audio_output);
  275. } else if (fParams.fReturnAudioChannels != fRequest.audio_output) {
  276. jack_error("Error : master wants %d outputs and slave wants %d outputs...", fRequest.audio_output, fParams.fReturnAudioChannels);
  277. return -1;
  278. }
  279. // Close request socket
  280. fSocket.Close();
  281. /// Network init
  282. if (!JackNetMasterInterface::Init()) {
  283. return -1;
  284. }
  285. // Set global parameters
  286. if (!SetParams()) {
  287. return -1;
  288. }
  289. return 0;
  290. }
  291. int Close()
  292. {
  293. fSocket.Close();
  294. return 0;
  295. }
  296. void UseRingBuffer(int audio_input, float** audio_input_buffer, int write, int read)
  297. {
  298. // Possibly use ringbuffer...
  299. if (fRingBuffer) {
  300. for (int i = 0; i < audio_input; i++) {
  301. fRingBuffer[i]->Write(audio_input_buffer[i], write);
  302. fRingBuffer[i]->Read(audio_input_buffer[i], read);
  303. }
  304. }
  305. }
  306. int Read(int audio_input, float** audio_input_buffer, int midi_input, void** midi_input_buffer, int frames)
  307. {
  308. try {
  309. // frames = -1 means : entire buffer
  310. if (frames < 0) frames = fParams.fPeriodSize;
  311. int read_frames = 0;
  312. assert(audio_input == fParams.fReturnAudioChannels);
  313. for (int audio_port_index = 0; audio_port_index < audio_input; audio_port_index++) {
  314. assert(audio_input_buffer[audio_port_index]);
  315. fNetAudioPlaybackBuffer->SetBuffer(audio_port_index, audio_input_buffer[audio_port_index]);
  316. }
  317. for (int midi_port_index = 0; midi_port_index < midi_input; midi_port_index++) {
  318. assert(((JackMidiBuffer**)midi_input_buffer)[midi_port_index]);
  319. fNetMidiPlaybackBuffer->SetBuffer(midi_port_index, ((JackMidiBuffer**)midi_input_buffer)[midi_port_index]);
  320. }
  321. int res1 = SyncRecv();
  322. switch (res1) {
  323. case NET_SYNCHING:
  324. // Data will not be received, so cleanup buffers...
  325. for (int audio_port_index = 0; audio_port_index < audio_input; audio_port_index++) {
  326. memset(audio_input_buffer[audio_port_index], 0, sizeof(float) * fParams.fPeriodSize);
  327. }
  328. UseRingBuffer(audio_input, audio_input_buffer, fParams.fPeriodSize, frames);
  329. return res1;
  330. case SOCKET_ERROR:
  331. return res1;
  332. case SYNC_PACKET_ERROR:
  333. // since sync packet is incorrect, don't decode it and continue with data
  334. break;
  335. default:
  336. // decode sync
  337. DecodeSyncPacket(read_frames);
  338. break;
  339. }
  340. int res2 = DataRecv();
  341. UseRingBuffer(audio_input, audio_input_buffer, read_frames, frames);
  342. return res2;
  343. } catch (JackNetException& e) {
  344. jack_error(e.what());
  345. return -1;
  346. }
  347. }
  348. int Write(int audio_output, float** audio_output_buffer, int midi_output, void** midi_output_buffer, int frames)
  349. {
  350. try {
  351. // frames = -1 means : entire buffer
  352. if (frames < 0) frames = fParams.fPeriodSize;
  353. assert(audio_output == fParams.fSendAudioChannels);
  354. for (int audio_port_index = 0; audio_port_index < audio_output; audio_port_index++) {
  355. assert(audio_output_buffer[audio_port_index]);
  356. fNetAudioCaptureBuffer->SetBuffer(audio_port_index, audio_output_buffer[audio_port_index]);
  357. }
  358. for (int midi_port_index = 0; midi_port_index < midi_output; midi_port_index++) {
  359. assert(((JackMidiBuffer**)midi_output_buffer)[midi_port_index]);
  360. fNetMidiCaptureBuffer->SetBuffer(midi_port_index, ((JackMidiBuffer**)midi_output_buffer)[midi_port_index]);
  361. }
  362. EncodeSyncPacket(frames);
  363. // send sync
  364. if (SyncSend() == SOCKET_ERROR) {
  365. return SOCKET_ERROR;
  366. }
  367. // send data
  368. if (DataSend() == SOCKET_ERROR) {
  369. return SOCKET_ERROR;
  370. }
  371. return 0;
  372. } catch (JackNetException& e) {
  373. jack_error(e.what());
  374. return -1;
  375. }
  376. }
  377. // Transport
  378. void EncodeTransportData()
  379. {}
  380. void DecodeTransportData()
  381. {}
  382. };
  383. struct JackNetExtSlave : public JackNetSlaveInterface, public JackRunnableInterface {
  384. // Data buffers
  385. float** fAudioCaptureBuffer;
  386. float** fAudioPlaybackBuffer;
  387. JackMidiBuffer** fMidiCaptureBuffer;
  388. JackMidiBuffer** fMidiPlaybackBuffer;
  389. JackThread fThread;
  390. JackNetSlaveProcessCallback fProcessCallback;
  391. void* fProcessArg;
  392. JackNetSlaveShutdownCallback fShutdownCallback;
  393. void* fShutdownArg;
  394. JackNetSlaveRestartCallback fRestartCallback;
  395. void* fRestartArg;
  396. JackNetSlaveErrorCallback fErrorCallback;
  397. void* fErrorArg;
  398. JackNetSlaveBufferSizeCallback fBufferSizeCallback;
  399. void* fBufferSizeArg;
  400. JackNetSlaveSampleRateCallback fSampleRateCallback;
  401. void* fSampleRateArg;
  402. int fConnectTimeOut;
  403. int fFrames;
  404. JackNetExtSlave(const char* ip,
  405. int port,
  406. const char* name,
  407. jack_slave_t* request)
  408. :fThread(this),
  409. fProcessCallback(NULL),fProcessArg(NULL),
  410. fShutdownCallback(NULL), fShutdownArg(NULL),
  411. fRestartCallback(NULL), fRestartArg(NULL),
  412. fErrorCallback(NULL), fErrorArg(NULL),
  413. fBufferSizeCallback(NULL), fBufferSizeArg(NULL),
  414. fSampleRateCallback(NULL), fSampleRateArg(NULL)
  415. {
  416. char host_name[JACK_CLIENT_NAME_SIZE + 1];
  417. // Request parameters
  418. assert(strlen(ip) < 32);
  419. strcpy(fMulticastIP, ip);
  420. fParams.fMtu = request->mtu;
  421. fParams.fTransportSync = 0;
  422. fParams.fSendAudioChannels = request->audio_input;
  423. fParams.fReturnAudioChannels = request->audio_output;
  424. fParams.fSendMidiChannels = request->midi_input;
  425. fParams.fReturnMidiChannels = request->midi_output;
  426. fParams.fNetworkLatency = request->latency;
  427. fParams.fSampleEncoder = request->encoder;
  428. fParams.fKBps = request->kbps;
  429. fParams.fSlaveSyncMode = 1;
  430. fConnectTimeOut = request->time_out;
  431. // Create name with hostname and client name
  432. GetHostName(host_name, JACK_CLIENT_NAME_SIZE);
  433. snprintf(fParams.fName, JACK_CLIENT_NAME_SIZE, "%s_%s", host_name, name);
  434. fSocket.GetName(fParams.fSlaveNetName);
  435. // Set the socket parameters
  436. fSocket.SetPort(port);
  437. fSocket.SetAddress(fMulticastIP, port);
  438. fAudioCaptureBuffer = NULL;
  439. fAudioPlaybackBuffer = NULL;
  440. fMidiCaptureBuffer = NULL;
  441. fMidiPlaybackBuffer = NULL;
  442. }
  443. virtual ~JackNetExtSlave()
  444. {}
  445. void AllocPorts()
  446. {
  447. // Set buffers
  448. if (fParams.fSendAudioChannels > 0) {
  449. fAudioCaptureBuffer = new float*[fParams.fSendAudioChannels];
  450. for (int audio_port_index = 0; audio_port_index < fParams.fSendAudioChannels; audio_port_index++) {
  451. fAudioCaptureBuffer[audio_port_index] = new float[fParams.fPeriodSize];
  452. memset(fAudioCaptureBuffer[audio_port_index], 0, sizeof(float) * fParams.fPeriodSize);
  453. fNetAudioCaptureBuffer->SetBuffer(audio_port_index, fAudioCaptureBuffer[audio_port_index]);
  454. }
  455. }
  456. if (fParams.fSendMidiChannels > 0) {
  457. fMidiCaptureBuffer = new JackMidiBuffer*[fParams.fSendMidiChannels];
  458. for (int midi_port_index = 0; midi_port_index < fParams.fSendMidiChannels; midi_port_index++) {
  459. fMidiCaptureBuffer[midi_port_index] = (JackMidiBuffer*)new float[fParams.fPeriodSize];
  460. memset(fMidiCaptureBuffer[midi_port_index], 0, sizeof(float) * fParams.fPeriodSize);
  461. fNetMidiCaptureBuffer->SetBuffer(midi_port_index, fMidiCaptureBuffer[midi_port_index]);
  462. }
  463. }
  464. if (fParams.fReturnAudioChannels > 0) {
  465. fAudioPlaybackBuffer = new float*[fParams.fReturnAudioChannels];
  466. for (int audio_port_index = 0; audio_port_index < fParams.fReturnAudioChannels; audio_port_index++) {
  467. fAudioPlaybackBuffer[audio_port_index] = new float[fParams.fPeriodSize];
  468. memset(fAudioPlaybackBuffer[audio_port_index], 0, sizeof(float) * fParams.fPeriodSize);
  469. fNetAudioPlaybackBuffer->SetBuffer(audio_port_index, fAudioPlaybackBuffer[audio_port_index]);
  470. }
  471. }
  472. if (fParams.fReturnMidiChannels > 0) {
  473. fMidiPlaybackBuffer = new JackMidiBuffer*[fParams.fReturnMidiChannels];
  474. for (int midi_port_index = 0; midi_port_index < fParams.fReturnMidiChannels; midi_port_index++) {
  475. fMidiPlaybackBuffer[midi_port_index] = (JackMidiBuffer*)new float[fParams.fPeriodSize];
  476. memset(fMidiPlaybackBuffer[midi_port_index], 0, sizeof(float) * fParams.fPeriodSize);
  477. fNetMidiPlaybackBuffer->SetBuffer(midi_port_index, fMidiPlaybackBuffer[midi_port_index]);
  478. }
  479. }
  480. }
  481. void FreePorts()
  482. {
  483. if (fAudioCaptureBuffer) {
  484. for (int audio_port_index = 0; audio_port_index < fParams.fSendAudioChannels; audio_port_index++) {
  485. delete[] fAudioCaptureBuffer[audio_port_index];
  486. }
  487. delete[] fAudioCaptureBuffer;
  488. fAudioCaptureBuffer = NULL;
  489. }
  490. if (fMidiCaptureBuffer) {
  491. for (int midi_port_index = 0; midi_port_index < fParams.fSendMidiChannels; midi_port_index++) {
  492. delete[] fMidiCaptureBuffer[midi_port_index];
  493. }
  494. delete[] fMidiCaptureBuffer;
  495. fMidiCaptureBuffer = NULL;
  496. }
  497. if (fAudioPlaybackBuffer) {
  498. for (int audio_port_index = 0; audio_port_index < fParams.fReturnAudioChannels; audio_port_index++) {
  499. delete[] fAudioPlaybackBuffer[audio_port_index];
  500. }
  501. delete[] fAudioPlaybackBuffer;
  502. fAudioPlaybackBuffer = NULL;
  503. }
  504. if (fMidiPlaybackBuffer) {
  505. for (int midi_port_index = 0; midi_port_index < fParams.fReturnMidiChannels; midi_port_index++) {
  506. delete[] (fMidiPlaybackBuffer[midi_port_index]);
  507. }
  508. delete[] fMidiPlaybackBuffer;
  509. fMidiPlaybackBuffer = NULL;
  510. }
  511. }
  512. int Open(jack_master_t* result)
  513. {
  514. // Check audio/midi parameters
  515. if (fParams.fSendAudioChannels == 0
  516. && fParams.fReturnAudioChannels == 0
  517. && fParams.fSendMidiChannels == 0
  518. && fParams.fReturnMidiChannels == 0) {
  519. jack_error("Incorrect audio/midi channels number...");
  520. return -1;
  521. }
  522. // Check MTU parameters
  523. if ((fParams.fMtu < DEFAULT_MTU) && (fParams.fMtu > MAX_MTU)) {
  524. jack_error("MTU is not in the expected range [%d ... %d]", DEFAULT_MTU, MAX_MTU);
  525. return -1;
  526. }
  527. // Check CELT encoder parameters
  528. if ((fParams.fSampleEncoder == JackCeltEncoder) && (fParams.fKBps == 0)) {
  529. jack_error("CELT encoder with 0 for kps...");
  530. return -1;
  531. }
  532. if ((fParams.fSampleEncoder == JackOpusEncoder) && (fParams.fKBps == 0)) {
  533. jack_error("Opus encoder with 0 for kps...");
  534. return -1;
  535. }
  536. // Check latency
  537. if (fParams.fNetworkLatency > NETWORK_MAX_LATENCY) {
  538. jack_error("Network latency is limited to %d", NETWORK_MAX_LATENCY);
  539. return -1;
  540. }
  541. // Init network connection
  542. if (!JackNetSlaveInterface::InitConnection(fConnectTimeOut)) {
  543. jack_error("Initing network fails...");
  544. return -1;
  545. }
  546. // Finish connection...
  547. if (!JackNetSlaveInterface::InitRendering()) {
  548. jack_error("Starting network fails...");
  549. return -1;
  550. }
  551. // Then set global parameters
  552. if (!SetParams()) {
  553. jack_error("SetParams error...");
  554. return -1;
  555. }
  556. // Set result
  557. if (result != NULL) {
  558. result->buffer_size = fParams.fPeriodSize;
  559. result->sample_rate = fParams.fSampleRate;
  560. result->audio_input = fParams.fSendAudioChannels;
  561. result->audio_output = fParams.fReturnAudioChannels;
  562. result->midi_input = fParams.fSendMidiChannels;
  563. result->midi_output = fParams.fReturnMidiChannels;
  564. strcpy(result->master_name, fParams.fMasterNetName);
  565. }
  566. // By default fFrames is fPeriodSize
  567. fFrames = fParams.fPeriodSize;
  568. SessionParamsDisplay(&fParams);
  569. AllocPorts();
  570. return 0;
  571. }
  572. int Restart()
  573. {
  574. // Do it until client possibly decides to stop trying to connect...
  575. while (true) {
  576. // If restart cb is set, then call it
  577. if (fRestartCallback) {
  578. if (fRestartCallback(fRestartArg) != 0) {
  579. return -1;
  580. }
  581. // Otherwise if shutdown cb is set, then call it
  582. } else if (fShutdownCallback) {
  583. fShutdownCallback(fShutdownArg);
  584. }
  585. // Init network connection
  586. if (!JackNetSlaveInterface::InitConnection(fConnectTimeOut)) {
  587. jack_error("Initing network fails after time_out, retry...");
  588. } else {
  589. break;
  590. }
  591. }
  592. // Finish connection
  593. if (!JackNetSlaveInterface::InitRendering()) {
  594. jack_error("Starting network fails...");
  595. return -1;
  596. }
  597. // Then set global parameters
  598. if (!SetParams()) {
  599. jack_error("SetParams error...");
  600. return -1;
  601. }
  602. // We need to notify possibly new buffer size and sample rate (see Execute)
  603. if (fBufferSizeCallback) {
  604. if (fBufferSizeCallback(fParams.fPeriodSize, fBufferSizeArg) != 0) {
  605. jack_error("New buffer size = %d cannot be used...", fParams.fPeriodSize);
  606. return -1;
  607. }
  608. }
  609. if (fSampleRateCallback) {
  610. if (fSampleRateCallback(fParams.fSampleRate, fSampleRateArg) != 0) {
  611. jack_error("New sample rate = %d cannot be used...", fParams.fSampleRate);
  612. return -1;
  613. }
  614. }
  615. AllocPorts();
  616. return 0;
  617. }
  618. int Close()
  619. {
  620. fSocket.Close();
  621. FreePorts();
  622. return 0;
  623. }
  624. // Transport
  625. void EncodeTransportData()
  626. {}
  627. void DecodeTransportData()
  628. {}
  629. bool Init()
  630. {
  631. // Will do "something" on OSX only...
  632. UInt64 period, constraint;
  633. period = constraint = UInt64(1000000000.f * (float(fParams.fPeriodSize) / float(fParams.fSampleRate)));
  634. UInt64 computation = JackTools::ComputationMicroSec(fParams.fPeriodSize) * 1000;
  635. fThread.SetParams(period, computation, constraint);
  636. return (fThread.AcquireSelfRealTime(80) == 0); // TODO: get a value from the server
  637. }
  638. bool IsRunning()
  639. {
  640. return (fThread.GetStatus() == JackThread::kRunning);
  641. }
  642. bool Execute()
  643. {
  644. try {
  645. /*
  646. Fist cycle use an INT_MAX time out, so that connection
  647. is considered established (with PACKET_TIMEOUT later on)
  648. when the first cycle has been done.
  649. */
  650. DummyProcess();
  651. // keep running even in case of error
  652. while (fThread.GetStatus() == JackThread::kRunning) {
  653. if (Process() == SOCKET_ERROR) {
  654. return false;
  655. }
  656. }
  657. return false;
  658. } catch (JackNetException& e) {
  659. // otherwise just restart...
  660. e.PrintMessage();
  661. jack_info("NetSlave is restarted");
  662. fThread.DropRealTime();
  663. fThread.SetStatus(JackThread::kIniting);
  664. FreePorts();
  665. if (Restart() == 0 && Init()) {
  666. fThread.SetStatus(JackThread::kRunning);
  667. return true;
  668. } else {
  669. return false;
  670. }
  671. }
  672. }
  673. int Read()
  674. {
  675. // receive sync (launch the cycle)
  676. switch (SyncRecv()) {
  677. case SOCKET_ERROR:
  678. return SOCKET_ERROR;
  679. case SYNC_PACKET_ERROR:
  680. // since sync packet is incorrect, don't decode it and continue with data
  681. if (fErrorCallback) {
  682. fErrorCallback(SYNC_PACKET_ERROR, fErrorArg);
  683. }
  684. break;
  685. default:
  686. // decode sync
  687. DecodeSyncPacket(fFrames);
  688. break;
  689. }
  690. int res = DataRecv();
  691. if (res == DATA_PACKET_ERROR && fErrorCallback) {
  692. fErrorCallback(DATA_PACKET_ERROR, fErrorArg);
  693. }
  694. return res;
  695. }
  696. int Write()
  697. {
  698. EncodeSyncPacket(fFrames);
  699. if (SyncSend() == SOCKET_ERROR) {
  700. return SOCKET_ERROR;
  701. }
  702. return DataSend();
  703. }
  704. void DummyProcess()
  705. {
  706. // First cycle with INT_MAX time out
  707. SetPacketTimeOut(INT_MAX);
  708. // One cycle
  709. Process();
  710. // Then use PACKET_TIMEOUT * fParams.fNetworkLatency for next cycles
  711. SetPacketTimeOut(std::max(int(PACKET_TIMEOUT), int(PACKET_TIMEOUT * fParams.fNetworkLatency)));
  712. }
  713. int Process()
  714. {
  715. // Read data from the network, throw JackNetException in case of network error...
  716. if (Read() == SOCKET_ERROR) {
  717. return SOCKET_ERROR;
  718. }
  719. if (fFrames < 0) fFrames = fParams.fPeriodSize;
  720. fProcessCallback(fFrames,
  721. fParams.fSendAudioChannels,
  722. fAudioCaptureBuffer,
  723. fParams.fSendMidiChannels,
  724. (void**)fMidiCaptureBuffer,
  725. fParams.fReturnAudioChannels,
  726. fAudioPlaybackBuffer,
  727. fParams.fReturnMidiChannels,
  728. (void**)fMidiPlaybackBuffer,
  729. fProcessArg);
  730. // Then write data to network, throw JackNetException in case of network error...
  731. if (Write() == SOCKET_ERROR) {
  732. return SOCKET_ERROR;
  733. }
  734. return 0;
  735. }
  736. int Start()
  737. {
  738. return (fProcessCallback == 0) ? -1 : fThread.StartSync();
  739. }
  740. int Stop()
  741. {
  742. return (fProcessCallback == 0) ? -1 : fThread.Kill();
  743. }
  744. // Callback
  745. int SetProcessCallback(JackNetSlaveProcessCallback net_callback, void *arg)
  746. {
  747. if (fThread.GetStatus() == JackThread::kRunning) {
  748. return -1;
  749. } else {
  750. fProcessCallback = net_callback;
  751. fProcessArg = arg;
  752. return 0;
  753. }
  754. }
  755. int SetShutdownCallback(JackNetSlaveShutdownCallback shutdown_callback, void *arg)
  756. {
  757. if (fThread.GetStatus() == JackThread::kRunning) {
  758. return -1;
  759. } else {
  760. fShutdownCallback = shutdown_callback;
  761. fShutdownArg = arg;
  762. return 0;
  763. }
  764. }
  765. int SetRestartCallback(JackNetSlaveRestartCallback restart_callback, void *arg)
  766. {
  767. if (fThread.GetStatus() == JackThread::kRunning) {
  768. return -1;
  769. } else {
  770. fRestartCallback = restart_callback;
  771. fRestartArg = arg;
  772. return 0;
  773. }
  774. }
  775. int SetErrorCallback(JackNetSlaveErrorCallback error_callback, void *arg)
  776. {
  777. if (fThread.GetStatus() == JackThread::kRunning) {
  778. return -1;
  779. } else {
  780. fErrorCallback = error_callback;
  781. fErrorArg = arg;
  782. return 0;
  783. }
  784. }
  785. int SetBufferSizeCallback(JackNetSlaveBufferSizeCallback bufsize_callback, void *arg)
  786. {
  787. if (fThread.GetStatus() == JackThread::kRunning) {
  788. return -1;
  789. } else {
  790. fBufferSizeCallback = bufsize_callback;
  791. fBufferSizeArg = arg;
  792. return 0;
  793. }
  794. }
  795. int SetSampleRateCallback(JackNetSlaveSampleRateCallback samplerate_callback, void *arg)
  796. {
  797. if (fThread.GetStatus() == JackThread::kRunning) {
  798. return -1;
  799. } else {
  800. fSampleRateCallback = samplerate_callback;
  801. fSampleRateArg = arg;
  802. return 0;
  803. }
  804. }
  805. };
  806. struct JackNetAdapter : public JackAudioAdapterInterface {
  807. JackNetAdapter(int input, int output,
  808. jack_nframes_t host_buffer_size,
  809. jack_nframes_t host_sample_rate,
  810. jack_nframes_t adapted_buffer_size,
  811. jack_nframes_t adapted_sample_rate)
  812. :JackAudioAdapterInterface(host_buffer_size, host_sample_rate, adapted_buffer_size, adapted_sample_rate)
  813. {
  814. fCaptureChannels = input;
  815. fPlaybackChannels = output;
  816. Create();
  817. }
  818. void Create()
  819. {
  820. //ringbuffers
  821. if (fCaptureChannels > 0) {
  822. fCaptureRingBuffer = new JackResampler*[fCaptureChannels];
  823. }
  824. if (fPlaybackChannels > 0) {
  825. fPlaybackRingBuffer = new JackResampler*[fPlaybackChannels];
  826. }
  827. if (fAdaptative) {
  828. AdaptRingBufferSize();
  829. jack_info("Ringbuffer automatic adaptative mode size = %d frames", fRingbufferCurSize);
  830. } else {
  831. if (fRingbufferCurSize > DEFAULT_RB_SIZE) {
  832. fRingbufferCurSize = DEFAULT_RB_SIZE;
  833. }
  834. jack_info("Fixed ringbuffer size = %d frames", fRingbufferCurSize);
  835. }
  836. for (int i = 0; i < fCaptureChannels; i++ ) {
  837. fCaptureRingBuffer[i] = new JackResampler();
  838. fCaptureRingBuffer[i]->Reset(fRingbufferCurSize);
  839. }
  840. for (int i = 0; i < fPlaybackChannels; i++ ) {
  841. fPlaybackRingBuffer[i] = new JackResampler();
  842. fPlaybackRingBuffer[i]->Reset(fRingbufferCurSize);
  843. }
  844. if (fCaptureChannels > 0) {
  845. jack_log("ReadSpace = %ld", fCaptureRingBuffer[0]->ReadSpace());
  846. }
  847. if (fPlaybackChannels > 0) {
  848. jack_log("WriteSpace = %ld", fPlaybackRingBuffer[0]->WriteSpace());
  849. }
  850. }
  851. virtual ~JackNetAdapter()
  852. {
  853. Destroy();
  854. }
  855. void Flush()
  856. {
  857. for (int i = 0; i < fCaptureChannels; i++ ) {
  858. fCaptureRingBuffer[i]->Reset(fRingbufferCurSize);
  859. }
  860. for (int i = 0; i < fPlaybackChannels; i++ ) {
  861. fPlaybackRingBuffer[i]->Reset(fRingbufferCurSize);
  862. }
  863. }
  864. };
  865. } // end of namespace
  866. using namespace Jack;
  867. LIB_EXPORT jack_net_slave_t* jack_net_slave_open(const char* ip, int port, const char* name, jack_slave_t* request, jack_master_t* result)
  868. {
  869. JackNetExtSlave* slave = new JackNetExtSlave(ip, port, name, request);
  870. if (slave->Open(result) == 0) {
  871. return (jack_net_slave_t*)slave;
  872. } else {
  873. delete slave;
  874. return NULL;
  875. }
  876. }
  877. LIB_EXPORT int jack_net_slave_close(jack_net_slave_t* net)
  878. {
  879. JackNetExtSlave* slave = (JackNetExtSlave*)net;
  880. slave->Close();
  881. delete slave;
  882. return 0;
  883. }
  884. LIB_EXPORT int jack_set_net_slave_process_callback(jack_net_slave_t* net, JackNetSlaveProcessCallback net_callback, void *arg)
  885. {
  886. JackNetExtSlave* slave = (JackNetExtSlave*)net;
  887. return slave->SetProcessCallback(net_callback, arg);
  888. }
  889. LIB_EXPORT int jack_net_slave_activate(jack_net_slave_t* net)
  890. {
  891. JackNetExtSlave* slave = (JackNetExtSlave*)net;
  892. return slave->Start();
  893. }
  894. LIB_EXPORT int jack_net_slave_deactivate(jack_net_slave_t* net)
  895. {
  896. JackNetExtSlave* slave = (JackNetExtSlave*)net;
  897. return slave->Stop();
  898. }
  899. LIB_EXPORT int jack_net_slave_is_active(jack_net_slave_t* net)
  900. {
  901. JackNetExtSlave* slave = (JackNetExtSlave*)net;
  902. return slave->IsRunning();
  903. }
  904. LIB_EXPORT int jack_set_net_slave_buffer_size_callback(jack_net_slave_t *net, JackNetSlaveBufferSizeCallback bufsize_callback, void *arg)
  905. {
  906. JackNetExtSlave* slave = (JackNetExtSlave*)net;
  907. return slave->SetBufferSizeCallback(bufsize_callback, arg);
  908. }
  909. LIB_EXPORT int jack_set_net_slave_sample_rate_callback(jack_net_slave_t *net, JackNetSlaveSampleRateCallback samplerate_callback, void *arg)
  910. {
  911. JackNetExtSlave* slave = (JackNetExtSlave*)net;
  912. return slave->SetSampleRateCallback(samplerate_callback, arg);
  913. }
  914. LIB_EXPORT int jack_set_net_slave_shutdown_callback(jack_net_slave_t *net, JackNetSlaveShutdownCallback shutdown_callback, void *arg)
  915. {
  916. JackNetExtSlave* slave = (JackNetExtSlave*)net;
  917. return slave->SetShutdownCallback(shutdown_callback, arg);
  918. }
  919. LIB_EXPORT int jack_set_net_slave_restart_callback(jack_net_slave_t *net, JackNetSlaveRestartCallback restart_callback, void *arg)
  920. {
  921. JackNetExtSlave* slave = (JackNetExtSlave*)net;
  922. return slave->SetRestartCallback(restart_callback, arg);
  923. }
  924. LIB_EXPORT int jack_set_net_slave_error_callback(jack_net_slave_t *net, JackNetSlaveErrorCallback error_callback, void *arg)
  925. {
  926. JackNetExtSlave* slave = (JackNetExtSlave*)net;
  927. return slave->SetErrorCallback(error_callback, arg);
  928. }
  929. // Master API
  930. LIB_EXPORT jack_net_master_t* jack_net_master_open(const char* ip, int port, jack_master_t* request, jack_slave_t* result)
  931. {
  932. JackNetExtMaster* master = new JackNetExtMaster(ip, port, request);
  933. if (master->Open(result) == 0) {
  934. return (jack_net_master_t*)master;
  935. } else {
  936. delete master;
  937. return NULL;
  938. }
  939. }
  940. LIB_EXPORT int jack_net_master_close(jack_net_master_t* net)
  941. {
  942. JackNetExtMaster* master = (JackNetExtMaster*)net;
  943. master->Close();
  944. delete master;
  945. return 0;
  946. }
  947. LIB_EXPORT int jack_net_master_recv(jack_net_master_t* net, int audio_input, float** audio_input_buffer, int midi_input, void** midi_input_buffer)
  948. {
  949. JackNetExtMaster* master = (JackNetExtMaster*)net;
  950. return master->Read(audio_input, audio_input_buffer, midi_input, midi_input_buffer, -1);
  951. }
  952. LIB_EXPORT int jack_net_master_send(jack_net_master_t* net, int audio_output, float** audio_output_buffer, int midi_output, void** midi_output_buffer)
  953. {
  954. JackNetExtMaster* master = (JackNetExtMaster*)net;
  955. return master->Write(audio_output, audio_output_buffer, midi_output, midi_output_buffer, -1);
  956. }
  957. LIB_EXPORT int jack_net_master_recv_slice(jack_net_master_t* net, int audio_input, float** audio_input_buffer, int midi_input, void** midi_input_buffer, int frames)
  958. {
  959. JackNetExtMaster* master = (JackNetExtMaster*)net;
  960. return master->Read(audio_input, audio_input_buffer, midi_input, midi_input_buffer, frames);
  961. }
  962. LIB_EXPORT int jack_net_master_send_slice(jack_net_master_t* net, int audio_output, float** audio_output_buffer, int midi_output, void** midi_output_buffer, int frames)
  963. {
  964. JackNetExtMaster* master = (JackNetExtMaster*)net;
  965. return master->Write(audio_output, audio_output_buffer, midi_output, midi_output_buffer, frames);
  966. }
  967. // Adapter API
  968. LIB_EXPORT jack_adapter_t* jack_create_adapter(int input, int output,
  969. jack_nframes_t host_buffer_size,
  970. jack_nframes_t host_sample_rate,
  971. jack_nframes_t adapted_buffer_size,
  972. jack_nframes_t adapted_sample_rate)
  973. {
  974. try {
  975. return (jack_adapter_t*)new JackNetAdapter(input, output, host_buffer_size, host_sample_rate, adapted_buffer_size, adapted_sample_rate);
  976. } catch (...) {
  977. return NULL;
  978. }
  979. }
  980. LIB_EXPORT int jack_destroy_adapter(jack_adapter_t* adapter)
  981. {
  982. delete((JackNetAdapter*)adapter);
  983. return 0;
  984. }
  985. LIB_EXPORT void jack_flush_adapter(jack_adapter_t* adapter)
  986. {
  987. JackNetAdapter* slave = (JackNetAdapter*)adapter;
  988. slave->Flush();
  989. }
  990. LIB_EXPORT int jack_adapter_push_and_pull(jack_adapter_t* adapter, float** input, float** output, unsigned int frames)
  991. {
  992. JackNetAdapter* slave = (JackNetAdapter*)adapter;
  993. return slave->PushAndPull(input, output, frames);
  994. }
  995. LIB_EXPORT int jack_adapter_pull_and_push(jack_adapter_t* adapter, float** input, float** output, unsigned int frames)
  996. {
  997. JackNetAdapter* slave = (JackNetAdapter*)adapter;
  998. return slave->PullAndPush(input, output, frames);
  999. }
  1000. static void jack_format_and_log(int level, const char *prefix, const char *fmt, va_list ap)
  1001. {
  1002. static const char* netjack_log = getenv("JACK_NETJACK_LOG");
  1003. static bool is_netjack_log = (netjack_log) ? atoi(netjack_log) : 0;
  1004. if (is_netjack_log) {
  1005. char buffer[300];
  1006. size_t len;
  1007. if (prefix != NULL) {
  1008. len = strlen(prefix);
  1009. memcpy(buffer, prefix, len);
  1010. } else {
  1011. len = 0;
  1012. }
  1013. vsnprintf(buffer + len, sizeof(buffer) - len, fmt, ap);
  1014. printf("%s", buffer);
  1015. printf("\n");
  1016. }
  1017. }
  1018. LIB_EXPORT void jack_error(const char *fmt, ...)
  1019. {
  1020. va_list ap;
  1021. va_start(ap, fmt);
  1022. jack_format_and_log(LOG_LEVEL_INFO, "Jack: ", fmt, ap);
  1023. va_end(ap);
  1024. }
  1025. LIB_EXPORT void jack_info(const char *fmt, ...)
  1026. {
  1027. va_list ap;
  1028. va_start(ap, fmt);
  1029. jack_format_and_log(LOG_LEVEL_INFO, "Jack: ", fmt, ap);
  1030. va_end(ap);
  1031. }
  1032. LIB_EXPORT void jack_log(const char *fmt, ...)
  1033. {
  1034. va_list ap;
  1035. va_start(ap, fmt);
  1036. jack_format_and_log(LOG_LEVEL_INFO, "Jack: ", fmt, ap);
  1037. va_end(ap);
  1038. }