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.

2168 lines
67KB

  1. /*
  2. ZynAddSubFX - a software synthesizer
  3. MiddleWare.cpp - Glue Logic And Home Of Non-RT Operations
  4. Copyright (C) 2016 Mark McCurry
  5. This program is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU General Public License
  7. as published by the Free Software Foundation; either version 2
  8. of the License, or (at your option) any later version.
  9. */
  10. #include "MiddleWare.h"
  11. #include <cstring>
  12. #include <cstdio>
  13. #include <cstdlib>
  14. #include <fstream>
  15. #include <iostream>
  16. #include <dirent.h>
  17. #include <sys/stat.h>
  18. #include <rtosc/undo-history.h>
  19. #include <rtosc/thread-link.h>
  20. #include <rtosc/ports.h>
  21. #include <lo/lo.h>
  22. #include <unistd.h>
  23. #include "../UI/Connection.h"
  24. #include "../UI/Fl_Osc_Interface.h"
  25. #include <map>
  26. #include "Util.h"
  27. #include "CallbackRepeater.h"
  28. #include "Master.h"
  29. #include "Part.h"
  30. #include "PresetExtractor.h"
  31. #include "../Containers/MultiPseudoStack.h"
  32. #include "../Params/PresetsStore.h"
  33. #include "../Params/ADnoteParameters.h"
  34. #include "../Params/SUBnoteParameters.h"
  35. #include "../Params/PADnoteParameters.h"
  36. #include "../DSP/FFTwrapper.h"
  37. #include "../Synth/OscilGen.h"
  38. #include "../Nio/Nio.h"
  39. #include <string>
  40. #include <future>
  41. #include <atomic>
  42. #include <list>
  43. #define errx(...) {}
  44. #define warnx(...) {}
  45. #ifndef errx
  46. #include <err.h>
  47. #endif
  48. using std::string;
  49. int Pexitprogram = 0;
  50. /******************************************************************************
  51. * LIBLO And Reflection Code *
  52. * *
  53. * All messages that are handled are handled in a serial fashion. *
  54. * Thus, changes in the current interface sending messages can be encoded *
  55. * into the stream via events which simply echo back the active interface *
  56. ******************************************************************************/
  57. static void liblo_error_cb(int i, const char *m, const char *loc)
  58. {
  59. fprintf(stderr, "liblo :-( %d-%s@%s\n",i,m,loc);
  60. }
  61. void path_search(const char *m, const char *url)
  62. {
  63. using rtosc::Ports;
  64. using rtosc::Port;
  65. //assumed upper bound of 32 ports (may need to be resized)
  66. char types[256+1];
  67. rtosc_arg_t args[256];
  68. size_t pos = 0;
  69. const Ports *ports = NULL;
  70. const char *str = rtosc_argument(m,0).s;
  71. const char *needle = rtosc_argument(m,1).s;
  72. //zero out data
  73. memset(types, 0, sizeof(types));
  74. memset(args, 0, sizeof(args));
  75. if(!*str) {
  76. ports = &Master::ports;
  77. } else {
  78. const Port *port = Master::ports.apropos(rtosc_argument(m,0).s);
  79. if(port)
  80. ports = port->ports;
  81. }
  82. if(ports) {
  83. //RTness not confirmed here
  84. for(const Port &p:*ports) {
  85. if(strstr(p.name, needle) != p.name || !p.name)
  86. continue;
  87. types[pos] = 's';
  88. args[pos++].s = p.name;
  89. types[pos] = 'b';
  90. if(p.metadata && *p.metadata) {
  91. args[pos].b.data = (unsigned char*) p.metadata;
  92. auto tmp = rtosc::Port::MetaContainer(p.metadata);
  93. args[pos++].b.len = tmp.length();
  94. } else {
  95. args[pos].b.data = (unsigned char*) NULL;
  96. args[pos++].b.len = 0;
  97. }
  98. }
  99. }
  100. //Reply to requester [wow, these messages are getting huge...]
  101. char buffer[1024*20];
  102. size_t length = rtosc_amessage(buffer, sizeof(buffer), "/paths", types, args);
  103. if(length) {
  104. lo_message msg = lo_message_deserialise((void*)buffer, length, NULL);
  105. lo_address addr = lo_address_new_from_url(url);
  106. if(addr)
  107. lo_send_message(addr, buffer, msg);
  108. lo_address_free(addr);
  109. lo_message_free(msg);
  110. }
  111. }
  112. static int handler_function(const char *path, const char *types, lo_arg **argv,
  113. int argc, lo_message msg, void *user_data)
  114. {
  115. (void) types;
  116. (void) argv;
  117. (void) argc;
  118. MiddleWare *mw = (MiddleWare*)user_data;
  119. lo_address addr = lo_message_get_source(msg);
  120. if(addr) {
  121. const char *tmp = lo_address_get_url(addr);
  122. if(tmp != mw->activeUrl()) {
  123. mw->transmitMsg("/echo", "ss", "OSC_URL", tmp);
  124. mw->activeUrl(tmp);
  125. }
  126. free((void*)tmp);
  127. }
  128. char buffer[2048];
  129. memset(buffer, 0, sizeof(buffer));
  130. size_t size = 2048;
  131. lo_message_serialise(msg, path, buffer, &size);
  132. if(!strcmp(buffer, "/path-search") && !strcmp("ss", rtosc_argument_string(buffer))) {
  133. path_search(buffer, mw->activeUrl().c_str());
  134. } else if(buffer[0]=='/' && strrchr(buffer, '/')[1]) {
  135. mw->transmitMsg(rtosc::Ports::collapsePath(buffer));
  136. }
  137. return 0;
  138. }
  139. typedef void(*cb_t)(void*,const char*);
  140. //utility method (should be moved to a better location)
  141. template <class T, class V>
  142. std::vector<T> keys(const std::map<T,V> &m)
  143. {
  144. std::vector<T> vec;
  145. for(auto &kv: m)
  146. vec.push_back(kv.first);
  147. return vec;
  148. }
  149. /*****************************************************************************
  150. * Memory Deallocation *
  151. *****************************************************************************/
  152. void deallocate(const char *str, void *v)
  153. {
  154. //printf("deallocating a '%s' at '%p'\n", str, v);
  155. if(!strcmp(str, "Part"))
  156. delete (Part*)v;
  157. else if(!strcmp(str, "Master"))
  158. delete (Master*)v;
  159. else if(!strcmp(str, "fft_t"))
  160. delete[] (fft_t*)v;
  161. else if(!strcmp(str, "KbmInfo"))
  162. delete (KbmInfo*)v;
  163. else if(!strcmp(str, "SclInfo"))
  164. delete (SclInfo*)v;
  165. else if(!strcmp(str, "Microtonal"))
  166. delete (Microtonal*)v;
  167. else
  168. fprintf(stderr, "Unknown type '%s', leaking pointer %p!!\n", str, v);
  169. }
  170. /*****************************************************************************
  171. * PadSynth Setup *
  172. *****************************************************************************/
  173. void preparePadSynth(string path, PADnoteParameters *p, rtosc::RtData &d)
  174. {
  175. //printf("preparing padsynth parameters\n");
  176. assert(!path.empty());
  177. path += "sample";
  178. unsigned max = 0;
  179. p->sampleGenerator([&max,&path,&d]
  180. (unsigned N, PADnoteParameters::Sample &s)
  181. {
  182. max = max<N ? N : max;
  183. //printf("sending info to '%s'\n", (path+to_s(N)).c_str());
  184. d.chain((path+to_s(N)).c_str(), "ifb",
  185. s.size, s.basefreq, sizeof(float*), &s.smp);
  186. }, []{return false;});
  187. //clear out unused samples
  188. for(unsigned i = max+1; i < PAD_MAX_SAMPLES; ++i) {
  189. d.chain((path+to_s(i)).c_str(), "ifb",
  190. 0, 440.0f, sizeof(float*), NULL);
  191. }
  192. }
  193. /******************************************************************************
  194. * MIDI Serialization *
  195. * *
  196. ******************************************************************************/
  197. void saveMidiLearn(XMLwrapper &xml, const rtosc::MidiMappernRT &midi)
  198. {
  199. xml.beginbranch("midi-learn");
  200. for(auto value:midi.inv_map) {
  201. XmlNode binding("midi-binding");
  202. auto biject = std::get<3>(value.second);
  203. binding["osc-path"] = value.first;
  204. binding["coarse-CC"] = to_s(std::get<1>(value.second));
  205. binding["fine-CC"] = to_s(std::get<2>(value.second));
  206. binding["type"] = "i";
  207. binding["minimum"] = to_s(biject.min);
  208. binding["maximum"] = to_s(biject.max);
  209. xml.add(binding);
  210. }
  211. xml.endbranch();
  212. }
  213. void loadMidiLearn(XMLwrapper &xml, rtosc::MidiMappernRT &midi)
  214. {
  215. using rtosc::Port;
  216. if(xml.enterbranch("midi-learn")) {
  217. auto nodes = xml.getBranch();
  218. //TODO clear mapper
  219. for(auto node:nodes) {
  220. if(node.name != "midi-binding" ||
  221. !node.has("osc-path") ||
  222. !node.has("coarse-CC"))
  223. continue;
  224. const string path = node["osc-path"];
  225. const int CC = atoi(node["coarse-CC"].c_str());
  226. const Port *p = Master::ports.apropos(path.c_str());
  227. if(p) {
  228. printf("loading midi port...\n");
  229. midi.addNewMapper(CC, *p, path);
  230. } else {
  231. printf("unknown midi bindable <%s>\n", path.c_str());
  232. }
  233. }
  234. xml.exitbranch();
  235. } else
  236. printf("cannot find 'midi-learn' branch...\n");
  237. }
  238. /******************************************************************************
  239. * Non-RealTime Object Store *
  240. * *
  241. * *
  242. * Storage For Objects which need to be interfaced with outside the realtime *
  243. * thread (aka they have long lived operations which can be done out-of-band) *
  244. * *
  245. * - OscilGen instances as prepare() cannot be done in realtime and PAD *
  246. * depends on these instances *
  247. * - PADnoteParameter instances as applyparameters() cannot be done in *
  248. * realtime *
  249. * *
  250. * These instances are collected on every part change and kit change *
  251. ******************************************************************************/
  252. struct NonRtObjStore
  253. {
  254. std::map<std::string, void*> objmap;
  255. void extractMaster(Master *master)
  256. {
  257. for(int i=0; i < NUM_MIDI_PARTS; ++i) {
  258. extractPart(master->part[i], i);
  259. }
  260. }
  261. void extractPart(Part *part, int i)
  262. {
  263. for(int j=0; j < NUM_KIT_ITEMS; ++j) {
  264. auto &obj = part->kit[j];
  265. extractAD(obj.adpars, i, j);
  266. extractPAD(obj.padpars, i, j);
  267. }
  268. }
  269. void extractAD(ADnoteParameters *adpars, int i, int j)
  270. {
  271. std::string base = "/part"+to_s(i)+"/kit"+to_s(j)+"/";
  272. for(int k=0; k<NUM_VOICES; ++k) {
  273. std::string nbase = base+"adpars/VoicePar"+to_s(k)+"/";
  274. if(adpars) {
  275. auto &nobj = adpars->VoicePar[k];
  276. objmap[nbase+"OscilSmp/"] = nobj.OscilSmp;
  277. objmap[nbase+"FMSmp/"] = nobj.FMSmp;
  278. } else {
  279. objmap[nbase+"OscilSmp/"] = nullptr;
  280. objmap[nbase+"FMSmp/"] = nullptr;
  281. }
  282. }
  283. }
  284. void extractPAD(PADnoteParameters *padpars, int i, int j)
  285. {
  286. std::string base = "/part"+to_s(i)+"/kit"+to_s(j)+"/";
  287. for(int k=0; k<NUM_VOICES; ++k) {
  288. if(padpars) {
  289. objmap[base+"padpars/"] = padpars;
  290. objmap[base+"padpars/oscilgen/"] = padpars->oscilgen;
  291. } else {
  292. objmap[base+"padpars/"] = nullptr;
  293. objmap[base+"padpars/oscilgen/"] = nullptr;
  294. }
  295. }
  296. }
  297. void clear(void)
  298. {
  299. objmap.clear();
  300. }
  301. bool has(std::string loc)
  302. {
  303. return objmap.find(loc) != objmap.end();
  304. }
  305. void *get(std::string loc)
  306. {
  307. return objmap[loc];
  308. }
  309. void handleOscil(const char *msg, rtosc::RtData &d) {
  310. string obj_rl(d.message, msg);
  311. void *osc = get(obj_rl);
  312. assert(osc);
  313. strcpy(d.loc, obj_rl.c_str());
  314. d.obj = osc;
  315. OscilGen::non_realtime_ports.dispatch(msg, d);
  316. }
  317. void handlePad(const char *msg, rtosc::RtData &d) {
  318. string obj_rl(d.message, msg);
  319. void *pad = get(obj_rl);
  320. if(!strcmp(msg, "prepare")) {
  321. preparePadSynth(obj_rl, (PADnoteParameters*)pad, d);
  322. d.matches++;
  323. d.reply((obj_rl+"needPrepare").c_str(), "F");
  324. } else {
  325. if(!pad)
  326. return;
  327. strcpy(d.loc, obj_rl.c_str());
  328. d.obj = pad;
  329. PADnoteParameters::non_realtime_ports.dispatch(msg, d);
  330. if(rtosc_narguments(msg)) {
  331. if(!strcmp(msg, "oscilgen/prepare"))
  332. ; //ignore
  333. else {
  334. d.reply((obj_rl+"needPrepare").c_str(), "T");
  335. }
  336. }
  337. }
  338. }
  339. };
  340. /******************************************************************************
  341. * Realtime Parameter Store *
  342. * *
  343. * Storage for AD/PAD/SUB parameters which are allocated as needed by kits. *
  344. * Two classes of events affect this: *
  345. * 1. When a message to enable a kit is observed, then the kit is allocated *
  346. * and sent prior to the enable message. *
  347. * 2. When a part is allocated all part information is rebuilt *
  348. * *
  349. * (NOTE pointers aren't really needed here, just booleans on whether it has *
  350. * been allocated) *
  351. * This may be later utilized for copy/paste support *
  352. ******************************************************************************/
  353. struct ParamStore
  354. {
  355. ParamStore(void)
  356. {
  357. memset(add, 0, sizeof(add));
  358. memset(pad, 0, sizeof(pad));
  359. memset(sub, 0, sizeof(sub));
  360. }
  361. void extractPart(Part *part, int i)
  362. {
  363. for(int j=0; j < NUM_KIT_ITEMS; ++j) {
  364. auto kit = part->kit[j];
  365. add[i][j] = kit.adpars;
  366. sub[i][j] = kit.subpars;
  367. pad[i][j] = kit.padpars;
  368. }
  369. }
  370. ADnoteParameters *add[NUM_MIDI_PARTS][NUM_KIT_ITEMS];
  371. SUBnoteParameters *sub[NUM_MIDI_PARTS][NUM_KIT_ITEMS];
  372. PADnoteParameters *pad[NUM_MIDI_PARTS][NUM_KIT_ITEMS];
  373. };
  374. //XXX perhaps move this to Nio
  375. //(there needs to be some standard Nio stub file for this sort of stuff)
  376. namespace Nio
  377. {
  378. using std::get;
  379. rtosc::Ports ports = {
  380. {"sink-list:", 0, 0, [](const char *, rtosc::RtData &d) {
  381. auto list = Nio::getSinks();
  382. char *ret = rtosc_splat(d.loc, list);
  383. d.reply(ret);
  384. delete [] ret;
  385. }},
  386. {"source-list:", 0, 0, [](const char *, rtosc::RtData &d) {
  387. auto list = Nio::getSources();
  388. char *ret = rtosc_splat(d.loc, list);
  389. d.reply(ret);
  390. delete [] ret;
  391. }},
  392. {"source::s", 0, 0, [](const char *msg, rtosc::RtData &d) {
  393. if(rtosc_narguments(msg) == 0)
  394. d.reply(d.loc, "s", Nio::getSource().c_str());
  395. else
  396. Nio::setSource(rtosc_argument(msg,0).s);}},
  397. {"sink::s", 0, 0, [](const char *msg, rtosc::RtData &d) {
  398. if(rtosc_narguments(msg) == 0)
  399. d.reply(d.loc, "s", Nio::getSink().c_str());
  400. else
  401. Nio::setSink(rtosc_argument(msg,0).s);}},
  402. };
  403. }
  404. /* Implementation */
  405. class MiddleWareImpl
  406. {
  407. public:
  408. MiddleWare *parent;
  409. private:
  410. public:
  411. Config* const config;
  412. MiddleWareImpl(MiddleWare *mw, SYNTH_T synth, Config* config,
  413. int preferred_port);
  414. ~MiddleWareImpl(void);
  415. //Check offline vs online mode in plugins
  416. void heartBeat(Master *m);
  417. int64_t start_time_sec;
  418. int64_t start_time_nsec;
  419. bool offline;
  420. //Apply function while parameters are write locked
  421. void doReadOnlyOp(std::function<void()> read_only_fn);
  422. void doReadOnlyOpPlugin(std::function<void()> read_only_fn);
  423. bool doReadOnlyOpNormal(std::function<void()> read_only_fn, bool canfail=false);
  424. void savePart(int npart, const char *filename)
  425. {
  426. //Copy is needed as filename WILL get trashed during the rest of the run
  427. std::string fname = filename;
  428. //printf("saving part(%d,'%s')\n", npart, filename);
  429. doReadOnlyOp([this,fname,npart](){
  430. int res = master->part[npart]->saveXML(fname.c_str());
  431. (void)res;
  432. /*printf("results: '%s' '%d'\n",fname.c_str(), res);*/});
  433. }
  434. void loadPendingBank(int par, Bank &bank)
  435. {
  436. if(((unsigned int)par < bank.banks.size())
  437. && (bank.banks[par].dir != bank.bankfiletitle))
  438. bank.loadbank(bank.banks[par].dir);
  439. }
  440. void loadPart(int npart, const char *filename, Master *master)
  441. {
  442. actual_load[npart]++;
  443. if(actual_load[npart] != pending_load[npart])
  444. return;
  445. assert(actual_load[npart] <= pending_load[npart]);
  446. //load part in async fashion when possible
  447. #ifndef WIN32
  448. auto alloc = std::async(std::launch::async,
  449. [master,filename,this,npart](){
  450. Part *p = new Part(*master->memory, synth,
  451. master->time,
  452. config->cfg.GzipCompression,
  453. config->cfg.Interpolation,
  454. &master->microtonal, master->fft, &master->watcher,
  455. ("/part"+to_s(npart)+"/").c_str());
  456. if(p->loadXMLinstrument(filename))
  457. fprintf(stderr, "Warning: failed to load part<%s>!\n", filename);
  458. auto isLateLoad = [this,npart]{
  459. return actual_load[npart] != pending_load[npart];
  460. };
  461. p->applyparameters(isLateLoad);
  462. return p;});
  463. //Load the part
  464. if(idle) {
  465. while(alloc.wait_for(std::chrono::seconds(0)) != std::future_status::ready) {
  466. idle(idle_ptr);
  467. }
  468. }
  469. Part *p = alloc.get();
  470. #else
  471. Part *p = new Part(*master->memory, synth, master->time,
  472. config->cfg.GzipCompression,
  473. config->cfg.Interpolation,
  474. &master->microtonal, master->fft);
  475. if(p->loadXMLinstrument(filename))
  476. fprintf(stderr, "Warning: failed to load part<%s>!\n", filename);
  477. auto isLateLoad = [this,npart]{
  478. return actual_load[npart] != pending_load[npart];
  479. };
  480. p->applyparameters(isLateLoad);
  481. #endif
  482. obj_store.extractPart(p, npart);
  483. kits.extractPart(p, npart);
  484. //Give it to the backend and wait for the old part to return for
  485. //deallocation
  486. parent->transmitMsg("/load-part", "ib", npart, sizeof(Part*), &p);
  487. GUI::raiseUi(ui, "/damage", "s", ("/part"+to_s(npart)+"/").c_str());
  488. }
  489. //Load a new cleared Part instance
  490. void loadClearPart(int npart)
  491. {
  492. if(npart == -1)
  493. return;
  494. Part *p = new Part(*master->memory, synth,
  495. master->time,
  496. config->cfg.GzipCompression,
  497. config->cfg.Interpolation,
  498. &master->microtonal, master->fft);
  499. p->applyparameters();
  500. obj_store.extractPart(p, npart);
  501. kits.extractPart(p, npart);
  502. //Give it to the backend and wait for the old part to return for
  503. //deallocation
  504. parent->transmitMsg("/load-part", "ib", npart, sizeof(Part *), &p);
  505. GUI::raiseUi(ui, "/damage", "s", ("/part" + to_s(npart) + "/").c_str());
  506. }
  507. //Well, you don't get much crazier than changing out all of your RT
  508. //structures at once... TODO error handling
  509. void loadMaster(const char *filename)
  510. {
  511. Master *m = new Master(synth, config);
  512. m->uToB = uToB;
  513. m->bToU = bToU;
  514. if(filename) {
  515. if ( m->loadXML(filename) ) {
  516. delete m;
  517. return;
  518. }
  519. m->applyparameters();
  520. }
  521. //Update resource locator table
  522. updateResources(m);
  523. master = m;
  524. //Give it to the backend and wait for the old part to return for
  525. //deallocation
  526. parent->transmitMsg("/load-master", "b", sizeof(Master*), &m);
  527. }
  528. void loadXsz(const char *filename, rtosc::RtData &d)
  529. {
  530. Microtonal *micro = new Microtonal(master->gzip_compression);
  531. int err = micro->loadXML(filename);
  532. if(err) {
  533. d.reply("/alert", "s", "Error: Could not load the xsz file.");
  534. delete micro;
  535. } else
  536. d.chain("/microtonal/paste", "b", sizeof(void*), &micro);
  537. }
  538. void saveXsz(const char *filename, rtosc::RtData &d)
  539. {
  540. int err = 0;
  541. doReadOnlyOp([this,filename,&err](){
  542. err = master->microtonal.saveXML(filename);});
  543. if(err)
  544. d.reply("/alert", "s", "Error: Could not save the xsz file.");
  545. }
  546. void loadScl(const char *filename, rtosc::RtData &d)
  547. {
  548. SclInfo *scl = new SclInfo;
  549. int err=Microtonal::loadscl(*scl, filename);
  550. if(err) {
  551. d.reply("/alert", "s", "Error: Could not load the scl file.");
  552. delete scl;
  553. } else
  554. d.chain("/microtonal/paste_scl", "b", sizeof(void*), &scl);
  555. }
  556. void loadKbm(const char *filename, rtosc::RtData &d)
  557. {
  558. KbmInfo *kbm = new KbmInfo;
  559. int err=Microtonal::loadkbm(*kbm, filename);
  560. if(err) {
  561. d.reply("/alert", "s", "Error: Could not load the kbm file.");
  562. delete kbm;
  563. } else
  564. d.chain("/microtonal/paste_kbm", "b", sizeof(void*), &kbm);
  565. }
  566. void updateResources(Master *m)
  567. {
  568. obj_store.clear();
  569. obj_store.extractMaster(m);
  570. for(int i=0; i<NUM_MIDI_PARTS; ++i)
  571. kits.extractPart(m->part[i], i);
  572. }
  573. //If currently broadcasting messages
  574. bool broadcast = false;
  575. //If message should be forwarded through snoop ports
  576. bool forward = false;
  577. //if message is in order or out-of-order execution
  578. bool in_order = false;
  579. //If accepting undo events as user driven
  580. bool recording_undo = true;
  581. void bToUhandle(const char *rtmsg);
  582. void tick(void)
  583. {
  584. if(server)
  585. while(lo_server_recv_noblock(server, 0));
  586. while(bToU->hasNext()) {
  587. const char *rtmsg = bToU->read();
  588. bToUhandle(rtmsg);
  589. }
  590. while(auto *m = multi_thread_source.read()) {
  591. handleMsg(m->memory);
  592. multi_thread_source.free(m);
  593. }
  594. autoSave.tick();
  595. heartBeat(master);
  596. //XXX This might have problems with a master swap operation
  597. if(offline)
  598. master->runOSC(0,0,true);
  599. }
  600. void kitEnable(const char *msg);
  601. void kitEnable(int part, int kit, int type);
  602. // Handle an event with special cases
  603. void handleMsg(const char *msg);
  604. void write(const char *path, const char *args, ...);
  605. void write(const char *path, const char *args, va_list va);
  606. void currentUrl(string addr)
  607. {
  608. curr_url = addr;
  609. known_remotes.insert(addr);
  610. }
  611. // Send a message to a remote client
  612. void sendToRemote(const char *msg, std::string dest);
  613. // Send a message to the current remote client
  614. void sendToCurrentRemote(const char *msg)
  615. {
  616. sendToRemote(msg, in_order ? curr_url : last_url);
  617. }
  618. // Broadcast a message to all listening remote clients
  619. void broadcastToRemote(const char *msg);
  620. /*
  621. * Provides a mapping for non-RT objects stored inside the backend
  622. * - Oscilgen almost all parameters can be safely set
  623. * - Padnote can have anything set on its oscilgen and a very small set
  624. * of general parameters
  625. */
  626. NonRtObjStore obj_store;
  627. //This code will own the pointer to master, be prepared for odd things if
  628. //this assumption is broken
  629. Master *master;
  630. //The ONLY means that any chunk of UI code should have for interacting with the
  631. //backend
  632. Fl_Osc_Interface *osc;
  633. //Synth Engine Parameters
  634. ParamStore kits;
  635. //Callback When Waiting on async events
  636. void(*idle)(void*);
  637. void* idle_ptr;
  638. //General UI callback
  639. cb_t cb;
  640. //UI handle
  641. void *ui;
  642. std::atomic_int pending_load[NUM_MIDI_PARTS];
  643. std::atomic_int actual_load[NUM_MIDI_PARTS];
  644. //Undo/Redo
  645. rtosc::UndoHistory undo;
  646. //MIDI Learn
  647. rtosc::MidiMappernRT midi_mapper;
  648. //Link To the Realtime
  649. rtosc::ThreadLink *bToU;
  650. rtosc::ThreadLink *uToB;
  651. //Link to the unknown
  652. MultiQueue multi_thread_source;
  653. //LIBLO
  654. lo_server server;
  655. string last_url, curr_url;
  656. std::set<string> known_remotes;
  657. //Synthesis Rate Parameters
  658. const SYNTH_T synth;
  659. PresetsStore presetsstore;
  660. CallbackRepeater autoSave;
  661. };
  662. /*****************************************************************************
  663. * Data Object for Non-RT Class Dispatch *
  664. *****************************************************************************/
  665. class MwDataObj:public rtosc::RtData
  666. {
  667. public:
  668. MwDataObj(MiddleWareImpl *mwi_)
  669. {
  670. loc_size = 1024;
  671. loc = new char[loc_size];
  672. memset(loc, 0, loc_size);
  673. buffer = new char[4*4096];
  674. memset(buffer, 0, 4*4096);
  675. obj = mwi_;
  676. mwi = mwi_;
  677. forwarded = false;
  678. }
  679. ~MwDataObj(void)
  680. {
  681. delete[] loc;
  682. delete[] buffer;
  683. }
  684. //Replies and broadcasts go to the remote
  685. //Chain calls repeat the call into handle()
  686. //Forward calls send the message directly to the realtime
  687. virtual void reply(const char *path, const char *args, ...)
  688. {
  689. //printf("reply building '%s'\n", path);
  690. va_list va;
  691. va_start(va,args);
  692. if(!strcmp(path, "/forward")) { //forward the information to the backend
  693. args++;
  694. path = va_arg(va, const char *);
  695. rtosc_vmessage(buffer,4*4096,path,args,va);
  696. } else {
  697. rtosc_vmessage(buffer,4*4096,path,args,va);
  698. reply(buffer);
  699. }
  700. va_end(va);
  701. }
  702. virtual void replyArray(const char *path, const char *args, rtosc_arg_t *argd) override
  703. {
  704. //printf("reply building '%s'\n", path);
  705. if(!strcmp(path, "/forward")) { //forward the information to the backend
  706. args++;
  707. rtosc_amessage(buffer,4*4096,path,args,argd);
  708. } else {
  709. rtosc_amessage(buffer,4*4096,path,args,argd);
  710. reply(buffer);
  711. }
  712. }
  713. virtual void reply(const char *msg){
  714. mwi->sendToCurrentRemote(msg);
  715. };
  716. //virtual void broadcast(const char *path, const char *args, ...){(void)path;(void)args;};
  717. //virtual void broadcast(const char *msg){(void)msg;};
  718. virtual void chain(const char *msg) override
  719. {
  720. assert(msg);
  721. // printf("chain call on <%s>\n", msg);
  722. mwi->handleMsg(msg);
  723. }
  724. virtual void chain(const char *path, const char *args, ...) override
  725. {
  726. assert(path);
  727. va_list va;
  728. va_start(va,args);
  729. rtosc_vmessage(buffer,4*4096,path,args,va);
  730. chain(buffer);
  731. va_end(va);
  732. }
  733. virtual void forward(const char *) override
  734. {
  735. forwarded = true;
  736. }
  737. bool forwarded;
  738. private:
  739. char *buffer;
  740. MiddleWareImpl *mwi;
  741. };
  742. static std::vector<std::string> getFiles(const char *folder, bool finddir)
  743. {
  744. DIR *dir = opendir(folder);
  745. if(dir == NULL) {
  746. return {};
  747. }
  748. struct dirent *fn;
  749. std::vector<string> files;
  750. while((fn = readdir(dir))) {
  751. #ifndef WIN32
  752. bool is_dir = fn->d_type & DT_DIR;
  753. //it could still be a symbolic link
  754. if(!is_dir) {
  755. string path = string(folder) + "/" + fn->d_name;
  756. struct stat buf;
  757. memset((void*)&buf, 0, sizeof(buf));
  758. int err = stat(path.c_str(), &buf);
  759. if(err)
  760. printf("[Zyn:Error] stat cannot handle <%s>:%d\n", path.c_str(), err);
  761. if(S_ISDIR(buf.st_mode)) {
  762. is_dir = true;
  763. }
  764. }
  765. #else
  766. std::string darn_windows = folder + std::string("/") + std::string(fn->d_name);
  767. printf("attr on <%s> => %x\n", darn_windows.c_str(), GetFileAttributes(darn_windows.c_str()));
  768. printf("desired mask = %x\n", mask);
  769. printf("error = %x\n", INVALID_FILE_ATTRIBUTES);
  770. bool is_dir = GetFileAttributes(darn_windows.c_str()) & FILE_ATTRIBUTE_DIRECTORY;
  771. #endif
  772. if(finddir == is_dir)
  773. files.push_back(fn->d_name);
  774. }
  775. closedir(dir);
  776. std::sort(begin(files), end(files));
  777. return files;
  778. }
  779. static int extractInt(const char *msg)
  780. {
  781. const char *mm = msg;
  782. while(*mm && !isdigit(*mm)) ++mm;
  783. if(isdigit(*mm))
  784. return atoi(mm);
  785. return -1;
  786. }
  787. static const char *chomp(const char *msg)
  788. {
  789. while(*msg && *msg!='/') ++msg; \
  790. msg = *msg ? msg+1 : msg;
  791. return msg;
  792. };
  793. using rtosc::RtData;
  794. #define rObject Bank
  795. #define rBegin [](const char *msg, RtData &d) { (void)msg;(void)d;\
  796. rObject &impl = *((rObject*)d.obj);(void)impl;
  797. #define rEnd }
  798. /*****************************************************************************
  799. * Instrument Banks *
  800. * *
  801. * Banks and presets in general are not classed as realtime safe *
  802. * *
  803. * The supported operations are: *
  804. * - Load Names *
  805. * - Load Bank *
  806. * - Refresh List of Banks *
  807. *****************************************************************************/
  808. extern const rtosc::Ports bankPorts;
  809. const rtosc::Ports bankPorts = {
  810. {"rescan:", 0, 0,
  811. rBegin;
  812. impl.rescanforbanks();
  813. //Send updated banks
  814. int i = 0;
  815. for(auto &elm : impl.banks)
  816. d.reply("/bank/bank_select", "iss", i++, elm.name.c_str(), elm.dir.c_str());
  817. d.reply("/bank/bank_select", "i", impl.bankpos);
  818. rEnd},
  819. {"bank_list:", 0, 0,
  820. rBegin;
  821. #define MAX_BANKS 256
  822. char types[MAX_BANKS*2+1]={0};
  823. rtosc_arg_t args[MAX_BANKS*2];
  824. int i = 0;
  825. for(auto &elm : impl.banks) {
  826. types[i] = types [i + 1] = 's';
  827. args[i++].s = elm.name.c_str();
  828. args[i++].s = elm.dir.c_str();
  829. }
  830. d.replyArray("/bank/bank_list", types, args);
  831. #undef MAX_BANKS
  832. rEnd},
  833. {"types:", 0, 0,
  834. rBegin;
  835. const char *types[17];
  836. types[ 0] = "None";
  837. types[ 1] = "Piano";
  838. types[ 2] = "Chromatic Percussion";
  839. types[ 3] = "Organ";
  840. types[ 4] = "Guitar";
  841. types[ 5] = "Bass";
  842. types[ 6] = "Solo Strings";
  843. types[ 7] = "Ensemble";
  844. types[ 8] = "Brass";
  845. types[ 9] = "Reed";
  846. types[10] = "Pipe";
  847. types[11] = "Synth Lead";
  848. types[12] = "Synth Pad";
  849. types[13] = "Synth Effects";
  850. types[14] = "Ethnic";
  851. types[15] = "Percussive";
  852. types[16] = "Sound Effects";
  853. char t[17+1]={0};
  854. rtosc_arg_t args[17];
  855. for(int i=0; i<17; ++i) {
  856. t[i] = 's';
  857. args[i].s = types[i];
  858. }
  859. d.replyArray("/bank/types", t, args);
  860. rEnd},
  861. {"tags:", 0, 0,
  862. rBegin;
  863. const char *types[8];
  864. types[ 0] = "fast";
  865. types[ 1] = "slow";
  866. types[ 2] = "saw";
  867. types[ 3] = "bell";
  868. types[ 4] = "lead";
  869. types[ 5] = "ambient";
  870. types[ 6] = "horn";
  871. types[ 7] = "alarm";
  872. char t[8+1]={0};
  873. rtosc_arg_t args[8];
  874. for(int i=0; i<8; ++i) {
  875. t[i] = 's';
  876. args[i].s = types[i];
  877. }
  878. d.replyArray(d.loc, t, args);
  879. rEnd},
  880. {"slot#1024:", 0, 0,
  881. rBegin;
  882. const int loc = extractInt(msg);
  883. if(loc >= BANK_SIZE)
  884. return;
  885. d.reply("/bankview", "iss",
  886. loc, impl.ins[loc].name.c_str(),
  887. impl.ins[loc].filename.c_str());
  888. rEnd},
  889. {"banks:", 0, 0,
  890. rBegin;
  891. int i = 0;
  892. for(auto &elm : impl.banks)
  893. d.reply("/bank/bank_select", "iss", i++, elm.name.c_str(), elm.dir.c_str());
  894. rEnd},
  895. {"bank_select::i", 0, 0,
  896. rBegin
  897. if(rtosc_narguments(msg)) {
  898. const int pos = rtosc_argument(msg, 0).i;
  899. d.reply(d.loc, "i", pos);
  900. if(impl.bankpos != pos) {
  901. impl.bankpos = pos;
  902. impl.loadbank(impl.banks[pos].dir);
  903. //Reload bank slots
  904. for(int i=0; i<BANK_SIZE; ++i)
  905. d.reply("/bankview", "iss",
  906. i, impl.ins[i].name.c_str(),
  907. impl.ins[i].filename.c_str());
  908. }
  909. } else
  910. d.reply("/bank/bank_select", "i", impl.bankpos);
  911. rEnd},
  912. {"rename_slot:is", 0, 0,
  913. rBegin;
  914. const int slot = rtosc_argument(msg, 0).i;
  915. const char *name = rtosc_argument(msg, 1).s;
  916. const int err = impl.setname(slot, name, -1);
  917. if(err) {
  918. d.reply("/alert", "s",
  919. "Failed To Rename Bank Slot, please check file permissions");
  920. }
  921. rEnd},
  922. {"swap_slots:ii", 0, 0,
  923. rBegin;
  924. const int slota = rtosc_argument(msg, 0).i;
  925. const int slotb = rtosc_argument(msg, 1).i;
  926. const int err = impl.swapslot(slota, slotb);
  927. if(err)
  928. d.reply("/alert", "s",
  929. "Failed To Swap Bank Slots, please check file permissions");
  930. rEnd},
  931. {"clear_slot:i", 0, 0,
  932. rBegin;
  933. const int slot = rtosc_argument(msg, 0).i;
  934. const int err = impl.clearslot(slot);
  935. if(err)
  936. d.reply("/alert", "s",
  937. "Failed To Clear Bank Slot, please check file permissions");
  938. rEnd},
  939. {"msb::i", 0, 0,
  940. rBegin;
  941. if(rtosc_narguments(msg))
  942. impl.setMsb(rtosc_argument(msg, 0).i);
  943. else
  944. d.reply(d.loc, "i", impl.bank_msb);
  945. rEnd},
  946. {"lsb::i", 0, 0,
  947. rBegin;
  948. if(rtosc_narguments(msg))
  949. impl.setLsb(rtosc_argument(msg, 0).i);
  950. else
  951. d.reply(d.loc, "i", impl.bank_lsb);
  952. rEnd},
  953. {"newbank:s", 0, 0,
  954. rBegin;
  955. int err = impl.newbank(rtosc_argument(msg, 0).s);
  956. if(err)
  957. d.reply("/alert", "s", "Error: Could not make a new bank (directory)..");
  958. rEnd},
  959. {"search:s", 0, 0,
  960. rBegin;
  961. auto res = impl.search(rtosc_argument(msg, 0).s);
  962. #define MAX_SEARCH 300
  963. char res_type[MAX_SEARCH+1] = {0};
  964. rtosc_arg_t res_dat[MAX_SEARCH] = {0};
  965. for(unsigned i=0; i<res.size() && i<MAX_SEARCH; ++i) {
  966. res_type[i] = 's';
  967. res_dat[i].s = res[i].c_str();
  968. }
  969. d.replyArray("/bank/search_results", res_type, res_dat);
  970. #undef MAX_SEARCH
  971. rEnd},
  972. {"blist:s", 0, 0,
  973. rBegin;
  974. auto res = impl.blist(rtosc_argument(msg, 0).s);
  975. #define MAX_SEARCH 300
  976. char res_type[MAX_SEARCH+1] = {0};
  977. rtosc_arg_t res_dat[MAX_SEARCH] = {0};
  978. for(unsigned i=0; i<res.size() && i<MAX_SEARCH; ++i) {
  979. res_type[i] = 's';
  980. res_dat[i].s = res[i].c_str();
  981. }
  982. d.replyArray("/bank/search_results", res_type, res_dat);
  983. #undef MAX_SEARCH
  984. rEnd},
  985. {"search_results:", 0, 0,
  986. rBegin;
  987. d.reply("/bank/search_results", "");
  988. rEnd},
  989. };
  990. /******************************************************************************
  991. * MiddleWare Snooping Ports *
  992. * *
  993. * These ports handle: *
  994. * - Events going to the realtime thread which cannot be safely handled *
  995. * there *
  996. * - Events generated by the realtime thread which are not destined for a *
  997. * user interface *
  998. ******************************************************************************/
  999. #undef rObject
  1000. #define rObject MiddleWareImpl
  1001. #ifndef STRINGIFY
  1002. #define STRINGIFY2(a) #a
  1003. #define STRINGIFY(a) STRINGIFY2(a)
  1004. #endif
  1005. /*
  1006. * BASE/part#/kititem#
  1007. * BASE/part#/kit#/adpars/voice#/oscil/\*
  1008. * BASE/part#/kit#/adpars/voice#/mod-oscil/\*
  1009. * BASE/part#/kit#/padpars/prepare
  1010. * BASE/part#/kit#/padpars/oscil/\*
  1011. */
  1012. static rtosc::Ports middwareSnoopPorts = {
  1013. {"part#" STRINGIFY(NUM_MIDI_PARTS)
  1014. "/kit#" STRINGIFY(NUM_KIT_ITEMS) "/adpars/VoicePar#"
  1015. STRINGIFY(NUM_VOICES) "/OscilSmp/", 0, &OscilGen::non_realtime_ports,
  1016. rBegin;
  1017. impl.obj_store.handleOscil(chomp(chomp(chomp(chomp(chomp(msg))))), d);
  1018. rEnd},
  1019. {"part#" STRINGIFY(NUM_MIDI_PARTS)
  1020. "/kit#" STRINGIFY(NUM_KIT_ITEMS)
  1021. "/adpars/VoicePar#" STRINGIFY(NUM_VOICES) "/FMSmp/", 0, &OscilGen::non_realtime_ports,
  1022. rBegin
  1023. impl.obj_store.handleOscil(chomp(chomp(chomp(chomp(chomp(msg))))), d);
  1024. rEnd},
  1025. {"part#" STRINGIFY(NUM_MIDI_PARTS)
  1026. "/kit#" STRINGIFY(NUM_KIT_ITEMS) "/padpars/", 0, &PADnoteParameters::non_realtime_ports,
  1027. rBegin
  1028. impl.obj_store.handlePad(chomp(chomp(chomp(msg))), d);
  1029. rEnd},
  1030. {"bank/", 0, &bankPorts,
  1031. rBegin;
  1032. d.obj = &impl.master->bank;
  1033. bankPorts.dispatch(chomp(msg),d);
  1034. rEnd},
  1035. {"bank/save_to_slot:ii", 0, 0,
  1036. rBegin;
  1037. const int part_id = rtosc_argument(msg, 0).i;
  1038. const int slot = rtosc_argument(msg, 1).i;
  1039. int err = 0;
  1040. impl.doReadOnlyOp([&impl,slot,part_id,&err](){
  1041. err = impl.master->bank.savetoslot(slot, impl.master->part[part_id]);});
  1042. if(err) {
  1043. char buffer[1024];
  1044. rtosc_message(buffer, 1024, "/alert", "s",
  1045. "Failed To Save To Bank Slot, please check file permissions");
  1046. GUI::raiseUi(impl.ui, buffer);
  1047. }
  1048. rEnd},
  1049. {"config/", 0, &Config::ports,
  1050. rBegin;
  1051. d.obj = impl.config;
  1052. Config::ports.dispatch(chomp(msg), d);
  1053. rEnd},
  1054. {"presets/", 0, &real_preset_ports, [](const char *msg, RtData &d) {
  1055. MiddleWareImpl *obj = (MiddleWareImpl*)d.obj;
  1056. d.obj = (void*)obj->parent;
  1057. real_preset_ports.dispatch(chomp(msg), d);
  1058. if(strstr(msg, "paste") && rtosc_argument_string(msg)[0] == 's')
  1059. d.reply("/damage", "s", rtosc_argument(msg, 0).s);
  1060. }},
  1061. {"io/", 0, &Nio::ports, [](const char *msg, RtData &d) {
  1062. Nio::ports.dispatch(chomp(msg), d);}},
  1063. {"part*/kit*/{Padenabled,Ppadenabled,Psubenabled}:T:F", 0, 0,
  1064. rBegin;
  1065. impl.kitEnable(msg);
  1066. d.forward();
  1067. rEnd},
  1068. {"save_xlz:s", 0, 0,
  1069. rBegin;
  1070. const char *file = rtosc_argument(msg, 0).s;
  1071. XMLwrapper xml;
  1072. saveMidiLearn(xml, impl.midi_mapper);
  1073. xml.saveXMLfile(file, impl.master->gzip_compression);
  1074. rEnd},
  1075. {"load_xlz:s", 0, 0,
  1076. rBegin;
  1077. const char *file = rtosc_argument(msg, 0).s;
  1078. XMLwrapper xml;
  1079. xml.loadXMLfile(file);
  1080. loadMidiLearn(xml, impl.midi_mapper);
  1081. rEnd},
  1082. {"clear_xlz:", 0, 0,
  1083. rBegin;
  1084. impl.midi_mapper.clear();
  1085. rEnd},
  1086. //scale file stuff
  1087. {"load_xsz:s", 0, 0,
  1088. rBegin;
  1089. const char *file = rtosc_argument(msg, 0).s;
  1090. impl.loadXsz(file, d);
  1091. rEnd},
  1092. {"save_xsz:s", 0, 0,
  1093. rBegin;
  1094. const char *file = rtosc_argument(msg, 0).s;
  1095. impl.saveXsz(file, d);
  1096. rEnd},
  1097. {"load_scl:s", 0, 0,
  1098. rBegin;
  1099. const char *file = rtosc_argument(msg, 0).s;
  1100. impl.loadScl(file, d);
  1101. rEnd},
  1102. {"load_kbm:s", 0, 0,
  1103. rBegin;
  1104. const char *file = rtosc_argument(msg, 0).s;
  1105. impl.loadKbm(file, d);
  1106. rEnd},
  1107. {"save_xmz:s", 0, 0,
  1108. rBegin;
  1109. const char *file = rtosc_argument(msg, 0).s;
  1110. //Copy is needed as filename WILL get trashed during the rest of the run
  1111. impl.doReadOnlyOp([&impl,file](){
  1112. int res = impl.master->saveXML(file);
  1113. (void)res;});
  1114. rEnd},
  1115. {"save_xiz:is", 0, 0,
  1116. rBegin;
  1117. const int part_id = rtosc_argument(msg,0).i;
  1118. const char *file = rtosc_argument(msg,1).s;
  1119. impl.savePart(part_id, file);
  1120. rEnd},
  1121. {"file_home_dir:", 0, 0,
  1122. rBegin;
  1123. const char *home = getenv("PWD");
  1124. if(!home)
  1125. home = getenv("HOME");
  1126. if(!home)
  1127. home = getenv("USERPROFILE");
  1128. if(!home)
  1129. home = getenv("HOMEPATH");
  1130. if(!home)
  1131. home = "/";
  1132. string home_ = home;
  1133. #ifndef WIN32
  1134. if(home_[home_.length()-1] != '/')
  1135. home_ += '/';
  1136. #endif
  1137. d.reply(d.loc, "s", home_.c_str());
  1138. rEnd},
  1139. {"file_list_files:s", 0, 0,
  1140. rBegin;
  1141. const char *folder = rtosc_argument(msg, 0).s;
  1142. auto files = getFiles(folder, false);
  1143. const int N = files.size();
  1144. rtosc_arg_t *args = new rtosc_arg_t[N];
  1145. char *types = new char[N+1];
  1146. types[N] = 0;
  1147. for(int i=0; i<N; ++i) {
  1148. args[i].s = files[i].c_str();
  1149. types[i] = 's';
  1150. }
  1151. d.replyArray(d.loc, types, args);
  1152. delete [] types;
  1153. delete [] args;
  1154. rEnd},
  1155. {"file_list_dirs:s", 0, 0,
  1156. rBegin;
  1157. const char *folder = rtosc_argument(msg, 0).s;
  1158. auto files = getFiles(folder, true);
  1159. const int N = files.size();
  1160. rtosc_arg_t *args = new rtosc_arg_t[N];
  1161. char *types = new char[N+1];
  1162. types[N] = 0;
  1163. for(int i=0; i<N; ++i) {
  1164. args[i].s = files[i].c_str();
  1165. types[i] = 's';
  1166. }
  1167. d.replyArray(d.loc, types, args);
  1168. delete [] types;
  1169. delete [] args;
  1170. rEnd},
  1171. {"reload_auto_save:i", 0, 0,
  1172. rBegin
  1173. const int save_id = rtosc_argument(msg,0).i;
  1174. const string save_dir = string(getenv("HOME")) + "/.local";
  1175. const string save_file = "zynaddsubfx-"+to_s(save_id)+"-autosave.xmz";
  1176. const string save_loc = save_dir + "/" + save_file;
  1177. impl.loadMaster(save_loc.c_str());
  1178. //XXX it would be better to remove the autosave after there is a new
  1179. //autosave, but this method should work for non-immediate crashes :-|
  1180. remove(save_loc.c_str());
  1181. rEnd},
  1182. {"delete_auto_save:i", 0, 0,
  1183. rBegin
  1184. const int save_id = rtosc_argument(msg,0).i;
  1185. const string save_dir = string(getenv("HOME")) + "/.local";
  1186. const string save_file = "zynaddsubfx-"+to_s(save_id)+"-autosave.xmz";
  1187. const string save_loc = save_dir + "/" + save_file;
  1188. remove(save_loc.c_str());
  1189. rEnd},
  1190. {"load_xmz:s", 0, 0,
  1191. rBegin;
  1192. const char *file = rtosc_argument(msg, 0).s;
  1193. impl.loadMaster(file);
  1194. d.reply("/damage", "s", "/");
  1195. rEnd},
  1196. {"reset_master:", 0, 0,
  1197. rBegin;
  1198. impl.loadMaster(NULL);
  1199. d.reply("/damage", "s", "/");
  1200. rEnd},
  1201. {"load_xiz:is", 0, 0,
  1202. rBegin;
  1203. const int part_id = rtosc_argument(msg,0).i;
  1204. const char *file = rtosc_argument(msg,1).s;
  1205. impl.pending_load[part_id]++;
  1206. impl.loadPart(part_id, file, impl.master);
  1207. rEnd},
  1208. {"load-part:is", 0, 0,
  1209. rBegin;
  1210. const int part_id = rtosc_argument(msg,0).i;
  1211. const char *file = rtosc_argument(msg,1).s;
  1212. impl.pending_load[part_id]++;
  1213. impl.loadPart(part_id, file, impl.master);
  1214. rEnd},
  1215. {"load-part:iss", 0, 0,
  1216. rBegin;
  1217. const int part_id = rtosc_argument(msg,0).i;
  1218. const char *file = rtosc_argument(msg,1).s;
  1219. const char *name = rtosc_argument(msg,2).s;
  1220. impl.pending_load[part_id]++;
  1221. impl.loadPart(part_id, file, impl.master);
  1222. impl.uToB->write(("/part"+to_s(part_id)+"/Pname").c_str(), "s",
  1223. name);
  1224. rEnd},
  1225. {"setprogram:i:c", 0, 0,
  1226. rBegin;
  1227. Bank &bank = impl.master->bank;
  1228. const int slot = rtosc_argument(msg, 0).i + 128*bank.bank_lsb;
  1229. if(slot < BANK_SIZE) {
  1230. impl.pending_load[0]++;
  1231. impl.loadPart(0, impl.master->bank.ins[slot].filename.c_str(), impl.master);
  1232. impl.uToB->write("/part0/Pname", "s", impl.master->bank.ins[slot].name.c_str());
  1233. }
  1234. rEnd},
  1235. {"part#16/clear:", 0, 0,
  1236. rBegin;
  1237. int id = extractInt(msg);
  1238. impl.loadClearPart(id);
  1239. d.reply("/damage", "s", ("/part"+to_s(id)).c_str());
  1240. rEnd},
  1241. {"undo:", 0, 0,
  1242. rBegin;
  1243. impl.undo.seekHistory(-1);
  1244. rEnd},
  1245. {"redo:", 0, 0,
  1246. rBegin;
  1247. impl.undo.seekHistory(+1);
  1248. rEnd},
  1249. //port to observe the midi mappings
  1250. {"midi-learn-values:", 0, 0,
  1251. rBegin;
  1252. auto &midi = impl.midi_mapper;
  1253. auto key = keys(midi.inv_map);
  1254. //cc-id, path, min, max
  1255. #define MAX_MIDI 32
  1256. rtosc_arg_t args[MAX_MIDI*4];
  1257. char argt[MAX_MIDI*4+1] = {0};
  1258. int j=0;
  1259. for(unsigned i=0; i<key.size() && i<MAX_MIDI; ++i) {
  1260. auto val = midi.inv_map[key[i]];
  1261. if(std::get<1>(val) == -1)
  1262. continue;
  1263. argt[4*j+0] = 'i';
  1264. args[4*j+0].i = std::get<1>(val);
  1265. argt[4*j+1] = 's';
  1266. args[4*j+1].s = key[i].c_str();
  1267. argt[4*j+2] = 'i';
  1268. args[4*j+2].i = 0;
  1269. argt[4*j+3] = 'i';
  1270. args[4*j+3].i = 127;
  1271. j++;
  1272. }
  1273. d.replyArray(d.loc, argt, args);
  1274. #undef MAX_MIDI
  1275. rEnd},
  1276. {"learn:s", 0, 0,
  1277. rBegin;
  1278. string addr = rtosc_argument(msg, 0).s;
  1279. auto &midi = impl.midi_mapper;
  1280. auto map = midi.getMidiMappingStrings();
  1281. if(map.find(addr) != map.end())
  1282. midi.map(addr.c_str(), false);
  1283. else
  1284. midi.map(addr.c_str(), true);
  1285. rEnd},
  1286. {"unlearn:s", 0, 0,
  1287. rBegin;
  1288. string addr = rtosc_argument(msg, 0).s;
  1289. auto &midi = impl.midi_mapper;
  1290. auto map = midi.getMidiMappingStrings();
  1291. midi.unMap(addr.c_str(), false);
  1292. midi.unMap(addr.c_str(), true);
  1293. rEnd},
  1294. //drop this message into the abyss
  1295. {"ui/title:", 0, 0, [](const char *msg, RtData &d) {}},
  1296. {"quit:", 0, 0, [](const char *, RtData&) {Pexitprogram = 1;}},
  1297. };
  1298. static rtosc::Ports middlewareReplyPorts = {
  1299. {"echo:ss", 0, 0,
  1300. rBegin;
  1301. const char *type = rtosc_argument(msg, 0).s;
  1302. const char *url = rtosc_argument(msg, 1).s;
  1303. if(!strcmp(type, "OSC_URL"))
  1304. impl.currentUrl(url);
  1305. rEnd},
  1306. {"free:sb", 0, 0,
  1307. rBegin;
  1308. const char *type = rtosc_argument(msg, 0).s;
  1309. void *ptr = *(void**)rtosc_argument(msg, 1).b.data;
  1310. deallocate(type, ptr);
  1311. rEnd},
  1312. {"request-memory:", 0, 0,
  1313. rBegin;
  1314. //Generate out more memory for the RT memory pool
  1315. //5MBi chunk
  1316. size_t N = 5*1024*1024;
  1317. void *mem = malloc(N);
  1318. impl.uToB->write("/add-rt-memory", "bi", sizeof(void*), &mem, N);
  1319. rEnd},
  1320. {"setprogram:cc:ii", 0, 0,
  1321. rBegin;
  1322. Bank &bank = impl.master->bank;
  1323. const int part = rtosc_argument(msg, 0).i;
  1324. const int program = rtosc_argument(msg, 1).i + 128*bank.bank_lsb;
  1325. impl.loadPart(part, impl.master->bank.ins[program].filename.c_str(), impl.master);
  1326. impl.uToB->write(("/part"+to_s(part)+"/Pname").c_str(), "s", impl.master->bank.ins[program].name.c_str());
  1327. rEnd},
  1328. {"setbank:c", 0, 0,
  1329. rBegin;
  1330. impl.loadPendingBank(rtosc_argument(msg,0).i, impl.master->bank);
  1331. rEnd},
  1332. {"undo_pause:", 0, 0, rBegin; impl.recording_undo = false; rEnd},
  1333. {"undo_resume:", 0, 0, rBegin; impl.recording_undo = true; rEnd},
  1334. {"undo_change", 0, 0,
  1335. rBegin;
  1336. if(impl.recording_undo)
  1337. impl.undo.recordEvent(msg);
  1338. rEnd},
  1339. {"midi-use-CC:i", 0, 0,
  1340. rBegin;
  1341. impl.midi_mapper.useFreeID(rtosc_argument(msg, 0).i);
  1342. rEnd},
  1343. {"broadcast:", 0, 0, rBegin; impl.broadcast = true; rEnd},
  1344. {"forward:", 0, 0, rBegin; impl.forward = true; rEnd},
  1345. };
  1346. #undef rBegin
  1347. #undef rEnd
  1348. /******************************************************************************
  1349. * MiddleWare Implementation *
  1350. ******************************************************************************/
  1351. MiddleWareImpl::MiddleWareImpl(MiddleWare *mw, SYNTH_T synth_,
  1352. Config* config, int preferrred_port)
  1353. :parent(mw), config(config), ui(nullptr), synth(std::move(synth_)),
  1354. presetsstore(*config), autoSave(-1, [this]() {
  1355. auto master = this->master;
  1356. this->doReadOnlyOp([master](){
  1357. std::string home = getenv("HOME");
  1358. std::string save_file = home+"/.local/zynaddsubfx-"+to_s(getpid())+"-autosave.xmz";
  1359. printf("doing an autosave <%s>...\n", save_file.c_str());
  1360. int res = master->saveXML(save_file.c_str());
  1361. (void)res;});})
  1362. {
  1363. bToU = new rtosc::ThreadLink(4096*2*16,1024/16);
  1364. uToB = new rtosc::ThreadLink(4096*2*16,1024/16);
  1365. midi_mapper.base_ports = &Master::ports;
  1366. midi_mapper.rt_cb = [this](const char *msg){handleMsg(msg);};
  1367. if(preferrred_port != -1)
  1368. server = lo_server_new_with_proto(to_s(preferrred_port).c_str(),
  1369. LO_UDP, liblo_error_cb);
  1370. else
  1371. server = lo_server_new_with_proto(NULL, LO_UDP, liblo_error_cb);
  1372. if(server) {
  1373. lo_server_add_method(server, NULL, NULL, handler_function, mw);
  1374. fprintf(stderr, "lo server running on %d\n", lo_server_get_port(server));
  1375. } else
  1376. fprintf(stderr, "lo server could not be started :-/\n");
  1377. //dummy callback for starters
  1378. cb = [](void*, const char*){};
  1379. idle = 0;
  1380. idle_ptr = 0;
  1381. master = new Master(synth, config);
  1382. master->bToU = bToU;
  1383. master->uToB = uToB;
  1384. osc = GUI::genOscInterface(mw);
  1385. //Grab objects of interest from master
  1386. updateResources(master);
  1387. //Null out Load IDs
  1388. for(int i=0; i < NUM_MIDI_PARTS; ++i) {
  1389. pending_load[i] = 0;
  1390. actual_load[i] = 0;
  1391. }
  1392. //Setup Undo
  1393. undo.setCallback([this](const char *msg) {
  1394. // printf("undo callback <%s>\n", msg);
  1395. char buf[1024];
  1396. rtosc_message(buf, 1024, "/undo_pause","");
  1397. handleMsg(buf);
  1398. handleMsg(msg);
  1399. rtosc_message(buf, 1024, "/undo_resume","");
  1400. handleMsg(buf);
  1401. });
  1402. //Setup starting time
  1403. struct timespec time;
  1404. clock_gettime(CLOCK_MONOTONIC, &time);
  1405. start_time_sec = time.tv_sec;
  1406. start_time_nsec = time.tv_nsec;
  1407. offline = false;
  1408. }
  1409. MiddleWareImpl::~MiddleWareImpl(void)
  1410. {
  1411. if(server)
  1412. lo_server_free(server);
  1413. delete master;
  1414. delete osc;
  1415. delete bToU;
  1416. delete uToB;
  1417. }
  1418. /** Threading When Saving
  1419. * ----------------------
  1420. *
  1421. * Procedure Middleware:
  1422. * 1) Middleware sends /freeze_state to backend
  1423. * 2) Middleware waits on /state_frozen from backend
  1424. * All intervening commands are held for out of order execution
  1425. * 3) Aquire memory
  1426. * At this time by the memory barrier we are guarenteed that all old
  1427. * writes are done and assuming the freezing logic is sound, then it is
  1428. * impossible for any other parameter to change at this time
  1429. * 3) Middleware performs saving operation
  1430. * 4) Middleware sends /thaw_state to backend
  1431. * 5) Restore in order execution
  1432. *
  1433. * Procedure Backend:
  1434. * 1) Observe /freeze_state and disable all mutating events (MIDI CC)
  1435. * 2) Run a memory release to ensure that all writes are complete
  1436. * 3) Send /state_frozen to Middleware
  1437. * time...
  1438. * 4) Observe /thaw_state and resume normal processing
  1439. */
  1440. void MiddleWareImpl::doReadOnlyOp(std::function<void()> read_only_fn)
  1441. {
  1442. assert(uToB);
  1443. uToB->write("/freeze_state","");
  1444. std::list<const char *> fico;
  1445. int tries = 0;
  1446. while(tries++ < 10000) {
  1447. if(!bToU->hasNext()) {
  1448. usleep(500);
  1449. continue;
  1450. }
  1451. const char *msg = bToU->read();
  1452. if(!strcmp("/state_frozen", msg))
  1453. break;
  1454. size_t bytes = rtosc_message_length(msg, bToU->buffer_size());
  1455. char *save_buf = new char[bytes];
  1456. memcpy(save_buf, msg, bytes);
  1457. fico.push_back(save_buf);
  1458. }
  1459. assert(tries < 10000);//if this happens, the backend must be dead
  1460. std::atomic_thread_fence(std::memory_order_acquire);
  1461. //Now it is safe to do any read only operation
  1462. read_only_fn();
  1463. //Now to resume normal operations
  1464. uToB->write("/thaw_state","");
  1465. for(auto x:fico) {
  1466. uToB->raw_write(x);
  1467. delete [] x;
  1468. }
  1469. }
  1470. //Offline detection code:
  1471. // - Assume that the audio callback should be run at least once every 50ms
  1472. // - Atomically provide the number of ms since start to Master
  1473. // - Every time middleware ticks provide a heart beat
  1474. // - If when the heart beat is provided the backend is more than 200ms behind
  1475. // the last heartbeat then it must be offline
  1476. // - When marked offline the backend doesn't receive another heartbeat until it
  1477. // registers the current beat that it's behind on
  1478. void MiddleWareImpl::heartBeat(Master *master)
  1479. {
  1480. //Current time
  1481. //Last provided beat
  1482. //Last acknowledged beat
  1483. //Current offline status
  1484. struct timespec time;
  1485. clock_gettime(CLOCK_MONOTONIC, &time);
  1486. uint32_t now = (time.tv_sec-start_time_sec)*100 +
  1487. (time.tv_nsec-start_time_nsec)*1e-9*100;
  1488. int32_t last_ack = master->last_ack;
  1489. int32_t last_beat = master->last_beat;
  1490. //everything is considered online for the first second
  1491. if(now < 100)
  1492. return;
  1493. if(offline) {
  1494. if(last_beat == last_ack) {
  1495. //XXX INSERT MESSAGE HERE ABOUT TRANSITION TO ONLINE
  1496. offline = false;
  1497. //Send new heart beat
  1498. master->last_beat = now;
  1499. }
  1500. } else {
  1501. //it's unquestionably alive
  1502. if(last_beat == last_ack) {
  1503. //Send new heart beat
  1504. master->last_beat = now;
  1505. return;
  1506. }
  1507. //it's pretty likely dead
  1508. if(last_beat-last_ack > 0 && now-last_beat > 20) {
  1509. //The backend has had 200 ms to acquire a new beat
  1510. //The backend instead has an older beat
  1511. //XXX INSERT MESSAGE HERE ABOUT TRANSITION TO OFFLINE
  1512. offline = true;
  1513. return;
  1514. }
  1515. //who knows if it's alive or not here, give it a few ms to acquire or
  1516. //not
  1517. }
  1518. }
  1519. void MiddleWareImpl::doReadOnlyOpPlugin(std::function<void()> read_only_fn)
  1520. {
  1521. assert(uToB);
  1522. int offline = 0;
  1523. if(offline) {
  1524. std::atomic_thread_fence(std::memory_order_acquire);
  1525. //Now it is safe to do any read only operation
  1526. read_only_fn();
  1527. } else if(!doReadOnlyOpNormal(read_only_fn, true)) {
  1528. //check if we just transitioned to offline mode
  1529. std::atomic_thread_fence(std::memory_order_acquire);
  1530. //Now it is safe to do any read only operation
  1531. read_only_fn();
  1532. }
  1533. }
  1534. bool MiddleWareImpl::doReadOnlyOpNormal(std::function<void()> read_only_fn, bool canfail)
  1535. {
  1536. assert(uToB);
  1537. uToB->write("/freeze_state","");
  1538. std::list<const char *> fico;
  1539. int tries = 0;
  1540. while(tries++ < 2000) {
  1541. if(!bToU->hasNext()) {
  1542. usleep(500);
  1543. continue;
  1544. }
  1545. const char *msg = bToU->read();
  1546. if(!strcmp("/state_frozen", msg))
  1547. break;
  1548. size_t bytes = rtosc_message_length(msg, bToU->buffer_size());
  1549. char *save_buf = new char[bytes];
  1550. memcpy(save_buf, msg, bytes);
  1551. fico.push_back(save_buf);
  1552. }
  1553. if(canfail) {
  1554. //Now to resume normal operations
  1555. uToB->write("/thaw_state","");
  1556. for(auto x:fico) {
  1557. uToB->raw_write(x);
  1558. delete [] x;
  1559. }
  1560. return false;
  1561. }
  1562. assert(tries < 10000);//if this happens, the backend must be dead
  1563. std::atomic_thread_fence(std::memory_order_acquire);
  1564. //Now it is safe to do any read only operation
  1565. read_only_fn();
  1566. //Now to resume normal operations
  1567. uToB->write("/thaw_state","");
  1568. for(auto x:fico) {
  1569. uToB->raw_write(x);
  1570. delete [] x;
  1571. }
  1572. return true;
  1573. }
  1574. void MiddleWareImpl::broadcastToRemote(const char *rtmsg)
  1575. {
  1576. //Always send to the local UI
  1577. sendToRemote(rtmsg, "GUI");
  1578. //Send to remote UI if there's one listening
  1579. for(auto rem:known_remotes)
  1580. if(rem != "GUI")
  1581. sendToRemote(rtmsg, rem);
  1582. broadcast = false;
  1583. }
  1584. void MiddleWareImpl::sendToRemote(const char *rtmsg, std::string dest)
  1585. {
  1586. if(!rtmsg || rtmsg[0] != '/' || !rtosc_message_length(rtmsg, -1)) {
  1587. printf("[Warning] Invalid message in sendToRemote <%s>...\n", rtmsg);
  1588. return;
  1589. }
  1590. //printf("sendToRemote(%s:%s,%s)\n", rtmsg, rtosc_argument_string(rtmsg),
  1591. // dest.c_str());
  1592. if(dest == "GUI") {
  1593. cb(ui, rtmsg);
  1594. } else if(!dest.empty()) {
  1595. lo_message msg = lo_message_deserialise((void*)rtmsg,
  1596. rtosc_message_length(rtmsg, bToU->buffer_size()), NULL);
  1597. if(!msg) {
  1598. printf("[ERROR] OSC to <%s> Failed To Parse In Liblo\n", rtmsg);
  1599. return;
  1600. }
  1601. //Send to known url
  1602. lo_address addr = lo_address_new_from_url(dest.c_str());
  1603. if(addr)
  1604. lo_send_message(addr, rtmsg, msg);
  1605. lo_address_free(addr);
  1606. lo_message_free(msg);
  1607. }
  1608. }
  1609. /**
  1610. * Handle all events coming from the backend
  1611. *
  1612. * This includes forwarded events which need to be retransmitted to the backend
  1613. * after the snooping code inspects the message
  1614. */
  1615. void MiddleWareImpl::bToUhandle(const char *rtmsg)
  1616. {
  1617. //Verify Message isn't a known corruption bug
  1618. assert(strcmp(rtmsg, "/part0/kit0/Ppadenableda"));
  1619. assert(strcmp(rtmsg, "/ze_state"));
  1620. //Dump Incomming Events For Debugging
  1621. if(strcmp(rtmsg, "/vu-meter") && false) {
  1622. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 1 + 30, 0 + 40);
  1623. fprintf(stdout, "frontend[%c]: '%s'<%s>\n", forward?'f':broadcast?'b':'N',
  1624. rtmsg, rtosc_argument_string(rtmsg));
  1625. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 7 + 30, 0 + 40);
  1626. }
  1627. //Activity dot
  1628. //printf(".");fflush(stdout);
  1629. MwDataObj d(this);
  1630. middlewareReplyPorts.dispatch(rtmsg, d, true);
  1631. if(!rtmsg) {
  1632. fprintf(stderr, "[ERROR] Unexpected Null OSC In Zyn\n");
  1633. return;
  1634. }
  1635. in_order = true;
  1636. //Normal message not captured by the ports
  1637. if(d.matches == 0) {
  1638. if(forward) {
  1639. forward = false;
  1640. handleMsg(rtmsg);
  1641. } if(broadcast)
  1642. broadcastToRemote(rtmsg);
  1643. else
  1644. sendToCurrentRemote(rtmsg);
  1645. }
  1646. in_order = false;
  1647. }
  1648. //Allocate kits on a as needed basis
  1649. void MiddleWareImpl::kitEnable(const char *msg)
  1650. {
  1651. const string argv = rtosc_argument_string(msg);
  1652. if(argv != "T")
  1653. return;
  1654. //Extract fields from:
  1655. //BASE/part#/kit#/Pxxxenabled
  1656. int type = -1;
  1657. if(strstr(msg, "Padenabled"))
  1658. type = 0;
  1659. else if(strstr(msg, "Ppadenabled"))
  1660. type = 1;
  1661. else if(strstr(msg, "Psubenabled"))
  1662. type = 2;
  1663. else
  1664. return;
  1665. const char *tmp = strstr(msg, "part");
  1666. if(tmp == NULL)
  1667. return;
  1668. const int part = atoi(tmp+4);
  1669. tmp = strstr(msg, "kit");
  1670. if(tmp == NULL)
  1671. return;
  1672. const int kit = atoi(tmp+3);
  1673. kitEnable(part, kit, type);
  1674. }
  1675. void MiddleWareImpl::kitEnable(int part, int kit, int type)
  1676. {
  1677. //printf("attempting a kit enable<%d,%d,%d>\n", part, kit, type);
  1678. string url = "/part"+to_s(part)+"/kit"+to_s(kit)+"/";
  1679. void *ptr = NULL;
  1680. if(type == 0 && kits.add[part][kit] == NULL) {
  1681. ptr = kits.add[part][kit] = new ADnoteParameters(synth, master->fft,
  1682. &master->time);
  1683. url += "adpars-data";
  1684. obj_store.extractAD(kits.add[part][kit], part, kit);
  1685. } else if(type == 1 && kits.pad[part][kit] == NULL) {
  1686. ptr = kits.pad[part][kit] = new PADnoteParameters(synth, master->fft,
  1687. &master->time);
  1688. url += "padpars-data";
  1689. obj_store.extractPAD(kits.pad[part][kit], part, kit);
  1690. } else if(type == 2 && kits.sub[part][kit] == NULL) {
  1691. ptr = kits.sub[part][kit] = new SUBnoteParameters(&master->time);
  1692. url += "subpars-data";
  1693. }
  1694. //Send the new memory
  1695. if(ptr)
  1696. uToB->write(url.c_str(), "b", sizeof(void*), &ptr);
  1697. }
  1698. /*
  1699. * Handle all messages traveling to the realtime side.
  1700. */
  1701. void MiddleWareImpl::handleMsg(const char *msg)
  1702. {
  1703. //Check for known bugs
  1704. assert(msg && *msg && strrchr(msg, '/')[1]);
  1705. assert(strstr(msg,"free") == NULL || strstr(rtosc_argument_string(msg), "b") == NULL);
  1706. assert(strcmp(msg, "/part0/Psysefxvol"));
  1707. assert(strcmp(msg, "/Penabled"));
  1708. assert(strcmp(msg, "part0/part0/Ppanning"));
  1709. assert(strcmp(msg, "sysefx0sysefx0/preset"));
  1710. assert(strcmp(msg, "/sysefx0preset"));
  1711. assert(strcmp(msg, "Psysefxvol0/part0"));
  1712. if(strcmp("/get-vu", msg) && false) {
  1713. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 6 + 30, 0 + 40);
  1714. fprintf(stdout, "middleware: '%s':%s\n", msg, rtosc_argument_string(msg));
  1715. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 7 + 30, 0 + 40);
  1716. }
  1717. const char *last_path = strrchr(msg, '/');
  1718. if(!last_path) {
  1719. printf("Bad message in handleMsg() <%s>\n", msg);
  1720. assert(false);
  1721. return;
  1722. }
  1723. MwDataObj d(this);
  1724. middwareSnoopPorts.dispatch(msg, d, true);
  1725. //A message unmodified by snooping
  1726. if(d.matches == 0 || d.forwarded) {
  1727. //if(strcmp("/get-vu", msg)) {
  1728. // printf("Message Continuing on<%s:%s>...\n", msg, rtosc_argument_string(msg));
  1729. //}
  1730. uToB->raw_write(msg);
  1731. } else {
  1732. //printf("Message Handled<%s:%s>...\n", msg, rtosc_argument_string(msg));
  1733. }
  1734. }
  1735. void MiddleWareImpl::write(const char *path, const char *args, ...)
  1736. {
  1737. //We have a free buffer in the threadlink, so use it
  1738. va_list va;
  1739. va_start(va, args);
  1740. write(path, args, va);
  1741. va_end(va);
  1742. }
  1743. void MiddleWareImpl::write(const char *path, const char *args, va_list va)
  1744. {
  1745. //printf("is that a '%s' I see there?\n", path);
  1746. char *buffer = uToB->buffer();
  1747. unsigned len = uToB->buffer_size();
  1748. bool success = rtosc_vmessage(buffer, len, path, args, va);
  1749. //printf("working on '%s':'%s'\n",path, args);
  1750. if(success)
  1751. handleMsg(buffer);
  1752. else
  1753. warnx("Failed to write message to '%s'", path);
  1754. }
  1755. /******************************************************************************
  1756. * MidleWare Forwarding Stubs *
  1757. ******************************************************************************/
  1758. MiddleWare::MiddleWare(SYNTH_T synth, Config* config,
  1759. int preferred_port)
  1760. :impl(new MiddleWareImpl(this, std::move(synth), config, preferred_port))
  1761. {}
  1762. MiddleWare::~MiddleWare(void)
  1763. {
  1764. delete impl;
  1765. }
  1766. void MiddleWare::updateResources(Master *m)
  1767. {
  1768. impl->updateResources(m);
  1769. }
  1770. Master *MiddleWare::spawnMaster(void)
  1771. {
  1772. assert(impl->master);
  1773. assert(impl->master->uToB);
  1774. return impl->master;
  1775. }
  1776. void MiddleWare::enableAutoSave(int interval_sec)
  1777. {
  1778. impl->autoSave.dt = interval_sec;
  1779. }
  1780. int MiddleWare::checkAutoSave(void)
  1781. {
  1782. //save spec zynaddsubfx-PID-autosave.xmz
  1783. const std::string home = getenv("HOME");
  1784. const std::string save_dir = home+"/.local/";
  1785. DIR *dir = opendir(save_dir.c_str());
  1786. if(dir == NULL)
  1787. return -1;
  1788. struct dirent *fn;
  1789. int reload_save = -1;
  1790. while((fn = readdir(dir))) {
  1791. const char *filename = fn->d_name;
  1792. const char *prefix = "zynaddsubfx-";
  1793. //check for manditory prefix
  1794. if(strstr(filename, prefix) != filename)
  1795. continue;
  1796. int id = atoi(filename+strlen(prefix));
  1797. bool in_use = false;
  1798. std::string proc_file = "/proc/" + to_s(id) + "/comm";
  1799. std::ifstream ifs(proc_file);
  1800. if(ifs.good()) {
  1801. std::string comm_name;
  1802. ifs >> comm_name;
  1803. in_use = (comm_name == "zynaddsubfx");
  1804. }
  1805. if(!in_use) {
  1806. reload_save = id;
  1807. break;
  1808. }
  1809. }
  1810. closedir(dir);
  1811. return reload_save;
  1812. }
  1813. void MiddleWare::removeAutoSave(void)
  1814. {
  1815. std::string home = getenv("HOME");
  1816. std::string save_file = home+"/.local/zynaddsubfx-"+to_s(getpid())+"-autosave.xmz";
  1817. remove(save_file.c_str());
  1818. }
  1819. Fl_Osc_Interface *MiddleWare::spawnUiApi(void)
  1820. {
  1821. return impl->osc;
  1822. }
  1823. void MiddleWare::tick(void)
  1824. {
  1825. impl->tick();
  1826. }
  1827. void MiddleWare::doReadOnlyOp(std::function<void()> fn)
  1828. {
  1829. impl->doReadOnlyOp(fn);
  1830. }
  1831. void MiddleWare::setUiCallback(void(*cb)(void*,const char *), void *ui)
  1832. {
  1833. impl->cb = cb;
  1834. impl->ui = ui;
  1835. }
  1836. void MiddleWare::setIdleCallback(void(*cb)(void*), void *ptr)
  1837. {
  1838. impl->idle = cb;
  1839. impl->idle_ptr = ptr;
  1840. }
  1841. void MiddleWare::transmitMsg(const char *msg)
  1842. {
  1843. impl->handleMsg(msg);
  1844. }
  1845. void MiddleWare::transmitMsg(const char *path, const char *args, ...)
  1846. {
  1847. char buffer[1024];
  1848. va_list va;
  1849. va_start(va,args);
  1850. if(rtosc_vmessage(buffer,1024,path,args,va))
  1851. transmitMsg(buffer);
  1852. else
  1853. fprintf(stderr, "Error in transmitMsg(...)\n");
  1854. va_end(va);
  1855. }
  1856. void MiddleWare::transmitMsg_va(const char *path, const char *args, va_list va)
  1857. {
  1858. char buffer[1024];
  1859. if(rtosc_vmessage(buffer, 1024, path, args, va))
  1860. transmitMsg(buffer);
  1861. else
  1862. fprintf(stderr, "Error in transmitMsg(va)n");
  1863. }
  1864. void MiddleWare::messageAnywhere(const char *path, const char *args, ...)
  1865. {
  1866. auto *mem = impl->multi_thread_source.alloc();
  1867. if(!mem)
  1868. fprintf(stderr, "Middleware::messageAnywhere memory pool out of memory...\n");
  1869. va_list va;
  1870. va_start(va,args);
  1871. if(rtosc_vmessage(mem->memory,mem->size,path,args,va))
  1872. impl->multi_thread_source.write(mem);
  1873. else {
  1874. fprintf(stderr, "Middleware::messageAnywhere message too big...\n");
  1875. impl->multi_thread_source.free(mem);
  1876. }
  1877. }
  1878. void MiddleWare::pendingSetBank(int bank)
  1879. {
  1880. impl->bToU->write("/setbank", "c", bank);
  1881. }
  1882. void MiddleWare::pendingSetProgram(int part, int program)
  1883. {
  1884. impl->pending_load[part]++;
  1885. impl->bToU->write("/setprogram", "cc", part, program);
  1886. }
  1887. std::string MiddleWare::activeUrl(void)
  1888. {
  1889. return impl->last_url;
  1890. }
  1891. void MiddleWare::activeUrl(std::string u)
  1892. {
  1893. impl->last_url = u;
  1894. }
  1895. const SYNTH_T &MiddleWare::getSynth(void) const
  1896. {
  1897. return impl->synth;
  1898. }
  1899. const char* MiddleWare::getServerAddress(void) const
  1900. {
  1901. if(impl->server)
  1902. return lo_server_get_url(impl->server);
  1903. else
  1904. return "NULL";
  1905. }
  1906. const PresetsStore& MiddleWare::getPresetsStore() const
  1907. {
  1908. return impl->presetsstore;
  1909. }
  1910. PresetsStore& MiddleWare::getPresetsStore()
  1911. {
  1912. return impl->presetsstore;
  1913. }