Audio plugin host https://kx.studio/carla
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.

445 lines
12KB

  1. /*
  2. ZynAddSubFX - a software synthesizer
  3. JackEngine.cpp - Jack Driver
  4. Copyright (C) 2009 Alan Calvert
  5. Copyright (C) 2014 Mark McCurry
  6. This program is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU General Public License
  8. as published by the Free Software Foundation; either version 2
  9. of the License, or (at your option) any later version.
  10. */
  11. #include <iostream>
  12. #include <jack/midiport.h>
  13. #ifdef JACK_HAS_METADATA_API
  14. # include <jack/metadata.h>
  15. #endif // JACK_HAS_METADATA_API
  16. #include "jack_osc.h"
  17. #include <fcntl.h>
  18. #include <sys/stat.h>
  19. #include <cassert>
  20. #include <cstring>
  21. #include <unistd.h> // access()
  22. #include <fstream> // std::istream
  23. #include "Nio.h"
  24. #include "OutMgr.h"
  25. #include "InMgr.h"
  26. #include "Misc/Util.h"
  27. #include "JackEngine.h"
  28. extern char *instance_name;
  29. namespace zyncarla {
  30. using namespace std;
  31. JackEngine::JackEngine(const SYNTH_T &synth)
  32. :AudioOut(synth), jackClient(NULL)
  33. {
  34. name = "JACK";
  35. audio.jackSamplerate = 0;
  36. audio.jackNframes = 0;
  37. for(int i = 0; i < 2; ++i) {
  38. audio.ports[i] = NULL;
  39. audio.portBuffs[i] = NULL;
  40. }
  41. midi.inport = NULL;
  42. midi.jack_sync = false;
  43. osc.oscport = NULL;
  44. }
  45. bool JackEngine::connectServer(string server)
  46. {
  47. bool autostart_jack = true;
  48. if(jackClient)
  49. return true;
  50. string clientname = "zynaddsubfx";
  51. string postfix = Nio::getPostfix();
  52. if(!postfix.empty())
  53. clientname += "_" + postfix;
  54. if(Nio::pidInClientName)
  55. clientname += "_" + os_pid_as_padded_string();
  56. jack_status_t jackstatus;
  57. bool use_server_name = server.size() && server.compare("default") != 0;
  58. jack_options_t jopts = (jack_options_t)
  59. (((!instance_name
  60. && use_server_name) ? JackServerName :
  61. JackNullOption)
  62. | ((autostart_jack) ? JackNullOption :
  63. JackNoStartServer));
  64. if(instance_name)
  65. jackClient = jack_client_open(instance_name, jopts, &jackstatus);
  66. else {
  67. if(use_server_name)
  68. jackClient = jack_client_open(
  69. clientname.c_str(), jopts, &jackstatus,
  70. server.c_str());
  71. else
  72. jackClient = jack_client_open(
  73. clientname.c_str(), jopts, &jackstatus);
  74. }
  75. if(NULL != jackClient)
  76. return true;
  77. else
  78. cerr << "Error, failed to open jack client on server: " << server
  79. << " status " << jackstatus << endl;
  80. return false;
  81. }
  82. bool JackEngine::connectJack()
  83. {
  84. connectServer("");
  85. if(NULL != jackClient) {
  86. setBufferSize(jack_get_buffer_size(jackClient));
  87. jack_set_error_function(_errorCallback);
  88. jack_set_info_function(_infoCallback);
  89. if(jack_set_buffer_size_callback(jackClient, _bufferSizeCallback, this))
  90. cerr << "Error setting the bufferSize callback" << endl;
  91. if((jack_set_xrun_callback(jackClient, _xrunCallback, this)))
  92. cerr << "Error setting jack xrun callback" << endl;
  93. if(jack_set_process_callback(jackClient, _processCallback, this)) {
  94. cerr << "Error, JackEngine failed to set process callback" << endl;
  95. return false;
  96. }
  97. if(jack_activate(jackClient)) {
  98. cerr << "Error, failed to activate jack client" << endl;
  99. return false;
  100. }
  101. return true;
  102. }
  103. else
  104. cerr << "Error, NULL jackClient through Start()" << endl;
  105. return false;
  106. }
  107. void JackEngine::disconnectJack()
  108. {
  109. if(jackClient) {
  110. cout << "Deactivating and closing JACK client" << endl;
  111. jack_deactivate(jackClient);
  112. jack_client_close(jackClient);
  113. jackClient = NULL;
  114. }
  115. }
  116. bool JackEngine::Start()
  117. {
  118. return openMidi() && openAudio();
  119. }
  120. void JackEngine::Stop()
  121. {
  122. stopMidi();
  123. stopAudio();
  124. }
  125. void JackEngine::setMidiEn(bool nval)
  126. {
  127. if(nval)
  128. openMidi();
  129. else
  130. stopMidi();
  131. }
  132. bool JackEngine::getMidiEn() const
  133. {
  134. return midi.inport;
  135. }
  136. void JackEngine::setAudioEn(bool nval)
  137. {
  138. if(nval)
  139. openAudio();
  140. else
  141. stopAudio();
  142. }
  143. bool JackEngine::getAudioEn() const
  144. {
  145. return audio.ports[0];
  146. }
  147. bool JackEngine::openAudio()
  148. {
  149. if(getAudioEn())
  150. return true;
  151. if(!getMidiEn())
  152. if(!connectJack())
  153. return false;
  154. const char *portnames[] = { "out_1", "out_2" };
  155. for(int port = 0; port < 2; ++port)
  156. audio.ports[port] = jack_port_register(
  157. jackClient,
  158. portnames[port],
  159. JACK_DEFAULT_AUDIO_TYPE,
  160. JackPortIsOutput
  161. | JackPortIsTerminal,
  162. 0);
  163. if((NULL != audio.ports[0]) && (NULL != audio.ports[1])) {
  164. audio.jackSamplerate = jack_get_sample_rate(jackClient);
  165. audio.jackNframes = jack_get_buffer_size(jackClient);
  166. samplerate = audio.jackSamplerate;
  167. bufferSize = audio.jackNframes;
  168. //Attempt to autoConnect when specified
  169. if(Nio::autoConnect) {
  170. const char **outPorts = jack_get_ports(
  171. jackClient,
  172. NULL,
  173. NULL,
  174. JackPortIsPhysical
  175. | JackPortIsInput);
  176. if(outPorts != NULL) {
  177. //Verify that stereo is available
  178. assert(outPorts[0]);
  179. assert(outPorts[1]);
  180. //Connect to physical outputs
  181. jack_connect(jackClient, jack_port_name(
  182. audio.ports[0]), outPorts[0]);
  183. jack_connect(jackClient, jack_port_name(
  184. audio.ports[1]), outPorts[1]);
  185. }
  186. else
  187. cerr << "Warning, No outputs to autoconnect to" << endl;
  188. }
  189. midi.jack_sync = true;
  190. osc.oscport = jack_port_register(jackClient, "osc",
  191. JACK_DEFAULT_OSC_TYPE, JackPortIsInput, 0);
  192. #ifdef JACK_HAS_METADATA_API
  193. jack_uuid_t uuid = jack_port_uuid(osc.oscport);
  194. jack_set_property(jackClient, uuid, "http://jackaudio.org/metadata/event-types", JACK_EVENT_TYPE__OSC, "text/plain");
  195. #endif // JACK_HAS_METADATA_API
  196. return true;
  197. }
  198. else
  199. cerr << "Error, failed to register jack audio ports" << endl;
  200. midi.jack_sync = false;
  201. return false;
  202. }
  203. void JackEngine::stopAudio()
  204. {
  205. for(int i = 0; i < 2; ++i) {
  206. jack_port_t *port = audio.ports[i];
  207. audio.ports[i] = NULL;
  208. if(jackClient != NULL && NULL != port)
  209. jack_port_unregister(jackClient, port);
  210. }
  211. midi.jack_sync = false;
  212. if(osc.oscport) {
  213. if (jackClient != NULL) {
  214. jack_port_unregister(jackClient, osc.oscport);
  215. #ifdef JACK_HAS_METADATA_API
  216. jack_uuid_t uuid = jack_port_uuid(osc.oscport);
  217. jack_remove_property(jackClient, uuid, "http://jackaudio.org/metadata/event-types");
  218. #endif // JACK_HAS_METADATA_API
  219. }
  220. }
  221. if(!getMidiEn())
  222. disconnectJack();
  223. }
  224. bool JackEngine::openMidi()
  225. {
  226. if(getMidiEn())
  227. return true;
  228. if(!getAudioEn())
  229. if(!connectJack())
  230. return false;
  231. midi.inport = jack_port_register(jackClient, "midi_input",
  232. JACK_DEFAULT_MIDI_TYPE,
  233. JackPortIsInput | JackPortIsTerminal, 0);
  234. return midi.inport;
  235. }
  236. void JackEngine::stopMidi()
  237. {
  238. jack_port_t *port = midi.inport;
  239. midi.inport = NULL;
  240. if(port)
  241. jack_port_unregister(jackClient, port);
  242. if(!getAudioEn())
  243. disconnectJack();
  244. }
  245. int JackEngine::clientId()
  246. {
  247. if(NULL != jackClient)
  248. return (long)jack_client_thread_id(jackClient);
  249. else
  250. return -1;
  251. }
  252. string JackEngine::clientName()
  253. {
  254. if(NULL != jackClient)
  255. return string(jack_get_client_name(jackClient));
  256. else
  257. cerr << "Error, clientName() with null jackClient" << endl;
  258. return string("Oh, yoshimi :-(");
  259. }
  260. int JackEngine::_processCallback(jack_nframes_t nframes, void *arg)
  261. {
  262. return static_cast<JackEngine *>(arg)->processCallback(nframes);
  263. }
  264. int JackEngine::processCallback(jack_nframes_t nframes)
  265. {
  266. bool okaudio = true;
  267. handleMidi(nframes);
  268. if((NULL != audio.ports[0]) && (NULL != audio.ports[1]))
  269. okaudio = processAudio(nframes);
  270. return okaudio ? 0 : -1;
  271. }
  272. bool JackEngine::processAudio(jack_nframes_t nframes)
  273. {
  274. //handle rt osc events first
  275. void *oscport = jack_port_get_buffer(osc.oscport, nframes);
  276. size_t osc_packets = jack_osc_get_event_count(oscport);
  277. for(size_t i = 0; i < osc_packets; ++i) {
  278. jack_osc_event_t event;
  279. if(jack_osc_event_get(&event, oscport, i))
  280. continue;
  281. if(*event.buffer!='/') //Bundles are unhandled
  282. continue;
  283. //TODO validate message length
  284. OutMgr::getInstance().applyOscEventRt((char*)event.buffer);
  285. }
  286. for(int port = 0; port < 2; ++port) {
  287. audio.portBuffs[port] =
  288. (jsample_t *)jack_port_get_buffer(audio.ports[port], nframes);
  289. if(NULL == audio.portBuffs[port]) {
  290. cerr << "Error, failed to get jack audio port buffer: "
  291. << port << endl;
  292. return false;
  293. }
  294. }
  295. Stereo<float *> smp = getNext();
  296. //Assumes size of smp.l == nframes
  297. memcpy(audio.portBuffs[0], smp.l, bufferSize * sizeof(float));
  298. memcpy(audio.portBuffs[1], smp.r, bufferSize * sizeof(float));
  299. return true;
  300. }
  301. int JackEngine::_xrunCallback(void *)
  302. {
  303. cerr << "Jack reports xrun" << endl;
  304. return 0;
  305. }
  306. void JackEngine::_errorCallback(const char *msg)
  307. {
  308. cerr << "Jack reports error: " << msg << endl;
  309. }
  310. void JackEngine::_infoCallback(const char *msg)
  311. {
  312. cerr << "Jack info message: " << msg << endl;
  313. }
  314. int JackEngine::_bufferSizeCallback(jack_nframes_t nframes, void *arg)
  315. {
  316. return static_cast<JackEngine *>(arg)->bufferSizeCallback(nframes);
  317. }
  318. int JackEngine::bufferSizeCallback(jack_nframes_t nframes)
  319. {
  320. cerr << "Jack buffer resized" << endl;
  321. setBufferSize(nframes);
  322. return 0;
  323. }
  324. void JackEngine::handleMidi(unsigned long frames)
  325. {
  326. if(!midi.inport)
  327. return;
  328. void *midi_buf = jack_port_get_buffer(midi.inport, frames);
  329. jack_midi_event_t jack_midi_event;
  330. jack_nframes_t event_index = 0;
  331. unsigned char *midi_data;
  332. unsigned char type;
  333. while(jack_midi_event_get(&jack_midi_event, midi_buf,
  334. event_index++) == 0) {
  335. MidiEvent ev;
  336. midi_data = jack_midi_event.buffer;
  337. type = midi_data[0] & 0xF0;
  338. ev.channel = midi_data[0] & 0x0F;
  339. ev.time = midi.jack_sync ? jack_midi_event.time : 0;
  340. switch(type) {
  341. case 0x80: /* note-off */
  342. ev.type = M_NOTE;
  343. ev.num = midi_data[1];
  344. ev.value = 0;
  345. InMgr::getInstance().putEvent(ev);
  346. break;
  347. case 0x90: /* note-on */
  348. ev.type = M_NOTE;
  349. ev.num = midi_data[1];
  350. ev.value = midi_data[2];
  351. InMgr::getInstance().putEvent(ev);
  352. break;
  353. case 0xA0: /* pressure, aftertouch */
  354. ev.type = M_PRESSURE;
  355. ev.num = midi_data[1];
  356. ev.value = midi_data[2];
  357. InMgr::getInstance().putEvent(ev);
  358. break;
  359. case 0xB0: /* controller */
  360. ev.type = M_CONTROLLER;
  361. ev.num = midi_data[1];
  362. ev.value = midi_data[2];
  363. InMgr::getInstance().putEvent(ev);
  364. break;
  365. case 0xC0: /* program change */
  366. ev.type = M_PGMCHANGE;
  367. ev.num = midi_data[1];
  368. ev.value = 0;
  369. InMgr::getInstance().putEvent(ev);
  370. break;
  371. case 0xE0: /* pitch bend */
  372. ev.type = M_CONTROLLER;
  373. ev.num = C_pitchwheel;
  374. ev.value = ((midi_data[2] << 7) | midi_data[1]) - 8192;
  375. InMgr::getInstance().putEvent(ev);
  376. break;
  377. /* XXX TODO: handle MSB/LSB controllers and RPNs and NRPNs */
  378. }
  379. }
  380. }
  381. }