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.

1552 lines
49KB

  1. #include "MiddleWare.h"
  2. #include <cstring>
  3. #include <cstdio>
  4. #include <cstdlib>
  5. #include <fstream>
  6. #include <rtosc/undo-history.h>
  7. #include <rtosc/thread-link.h>
  8. #include <rtosc/ports.h>
  9. #include <lo/lo.h>
  10. #include <unistd.h>
  11. #include "../UI/Connection.h"
  12. #include "../UI/Fl_Osc_Interface.h"
  13. #include <map>
  14. #include "Util.h"
  15. #include "Master.h"
  16. #include "Part.h"
  17. #include "PresetExtractor.h"
  18. #include "../Containers/MultiPseudoStack.h"
  19. #include "../Params/PresetsStore.h"
  20. #include "../Params/ADnoteParameters.h"
  21. #include "../Params/SUBnoteParameters.h"
  22. #include "../Params/PADnoteParameters.h"
  23. #include "../DSP/FFTwrapper.h"
  24. #include "../Synth/OscilGen.h"
  25. #include "../Nio/Nio.h"
  26. #include <string>
  27. #include <future>
  28. #include <atomic>
  29. #include <list>
  30. #ifndef errx
  31. #include <err.h>
  32. #endif
  33. using std::string;
  34. /******************************************************************************
  35. * LIBLO And Reflection Code *
  36. * *
  37. * All messages that are handled are handled in a serial fashion. *
  38. * Thus, changes in the current interface sending messages can be encoded *
  39. * into the stream via events which simply echo back the active interface *
  40. ******************************************************************************/
  41. static void liblo_error_cb(int i, const char *m, const char *loc)
  42. {
  43. fprintf(stderr, "liblo :-( %d-%s@%s\n",i,m,loc);
  44. }
  45. void path_search(const char *m, const char *url)
  46. {
  47. using rtosc::Ports;
  48. using rtosc::Port;
  49. //assumed upper bound of 32 ports (may need to be resized)
  50. char types[129];
  51. rtosc_arg_t args[128];
  52. size_t pos = 0;
  53. const Ports *ports = NULL;
  54. const char *str = rtosc_argument(m,0).s;
  55. const char *needle = rtosc_argument(m,1).s;
  56. //zero out data
  57. memset(types, 0, sizeof(types));
  58. memset(args, 0, sizeof(args));
  59. if(!*str) {
  60. ports = &Master::ports;
  61. } else {
  62. const Port *port = Master::ports.apropos(rtosc_argument(m,0).s);
  63. if(port)
  64. ports = port->ports;
  65. }
  66. if(ports) {
  67. //RTness not confirmed here
  68. for(const Port &p:*ports) {
  69. if(strstr(p.name, needle)!=p.name)
  70. continue;
  71. types[pos] = 's';
  72. args[pos++].s = p.name;
  73. types[pos] = 'b';
  74. if(p.metadata && *p.metadata) {
  75. args[pos].b.data = (unsigned char*) p.metadata;
  76. auto tmp = rtosc::Port::MetaContainer(p.metadata);
  77. args[pos++].b.len = tmp.length();
  78. } else {
  79. args[pos].b.data = (unsigned char*) NULL;
  80. args[pos++].b.len = 0;
  81. }
  82. }
  83. }
  84. //Reply to requester [wow, these messages are getting huge...]
  85. char buffer[1024*20];
  86. size_t length = rtosc_amessage(buffer, sizeof(buffer), "/paths", types, args);
  87. if(length) {
  88. lo_message msg = lo_message_deserialise((void*)buffer, length, NULL);
  89. lo_address addr = lo_address_new_from_url(url);
  90. if(addr)
  91. lo_send_message(addr, buffer, msg);
  92. }
  93. }
  94. static int handler_function(const char *path, const char *types, lo_arg **argv,
  95. int argc, lo_message msg, void *user_data)
  96. {
  97. (void) types;
  98. (void) argv;
  99. (void) argc;
  100. MiddleWare *mw = (MiddleWare*)user_data;
  101. lo_address addr = lo_message_get_source(msg);
  102. if(addr) {
  103. const char *tmp = lo_address_get_url(addr);
  104. if(tmp != mw->activeUrl()) {
  105. mw->transmitMsg("/echo", "ss", "OSC_URL", tmp);
  106. mw->activeUrl(tmp);
  107. }
  108. }
  109. char buffer[2048];
  110. memset(buffer, 0, sizeof(buffer));
  111. size_t size = 2048;
  112. lo_message_serialise(msg, path, buffer, &size);
  113. if(!strcmp(buffer, "/path-search") && !strcmp("ss", rtosc_argument_string(buffer))) {
  114. path_search(buffer, mw->activeUrl().c_str());
  115. } else if(buffer[0]=='/' && rindex(buffer, '/')[1]) {
  116. mw->transmitMsg(rtosc::Ports::collapsePath(buffer));
  117. }
  118. return 0;
  119. }
  120. typedef void(*cb_t)(void*,const char*);
  121. /*****************************************************************************
  122. * Memory Deallocation *
  123. *****************************************************************************/
  124. void deallocate(const char *str, void *v)
  125. {
  126. //printf("deallocating a '%s' at '%p'\n", str, v);
  127. if(!strcmp(str, "Part"))
  128. delete (Part*)v;
  129. else if(!strcmp(str, "Master"))
  130. delete (Master*)v;
  131. else if(!strcmp(str, "fft_t"))
  132. delete[] (fft_t*)v;
  133. else
  134. fprintf(stderr, "Unknown type '%s', leaking pointer %p!!\n", str, v);
  135. }
  136. /*****************************************************************************
  137. * PadSynth Setup *
  138. *****************************************************************************/
  139. void preparePadSynth(string path, PADnoteParameters *p, rtosc::RtData &d)
  140. {
  141. //printf("preparing padsynth parameters\n");
  142. assert(!path.empty());
  143. path += "sample";
  144. unsigned max = 0;
  145. p->sampleGenerator([&max,&path,&d]
  146. (unsigned N, PADnoteParameters::Sample &s)
  147. {
  148. max = max<N ? N : max;
  149. //printf("sending info to '%s'\n", (path+to_s(N)).c_str());
  150. d.chain((path+to_s(N)).c_str(), "ifb",
  151. s.size, s.basefreq, sizeof(float*), &s.smp);
  152. }, []{return false;});
  153. //clear out unused samples
  154. for(unsigned i = max+1; i < PAD_MAX_SAMPLES; ++i) {
  155. d.chain((path+to_s(i)).c_str(), "ifb",
  156. 0, 440.0f, sizeof(float*), NULL);
  157. }
  158. }
  159. /******************************************************************************
  160. * MIDI Serialization *
  161. * *
  162. ******************************************************************************/
  163. void saveMidiLearn(XMLwrapper &xml, const rtosc::MidiMappernRT &midi)
  164. {
  165. xml.beginbranch("midi-learn");
  166. for(auto value:midi.inv_map) {
  167. XmlNode binding("midi-binding");
  168. auto biject = std::get<3>(value.second);
  169. binding["osc-path"] = value.first;
  170. binding["coarse-CC"] = to_s(std::get<1>(value.second));
  171. binding["fine-CC"] = to_s(std::get<2>(value.second));
  172. binding["type"] = "i";
  173. binding["minimum"] = to_s(biject.min);
  174. binding["maximum"] = to_s(biject.max);
  175. xml.add(binding);
  176. }
  177. xml.endbranch();
  178. }
  179. void loadMidiLearn(XMLwrapper &xml, rtosc::MidiMappernRT &midi)
  180. {
  181. using rtosc::Port;
  182. if(xml.enterbranch("midi-learn")) {
  183. auto nodes = xml.getBranch();
  184. //TODO clear mapper
  185. for(auto node:nodes) {
  186. if(node.name != "midi-binding" ||
  187. !node.has("osc-path") ||
  188. !node.has("coarse-CC"))
  189. continue;
  190. const string path = node["osc-path"];
  191. const int CC = atoi(node["coarse-CC"].c_str());
  192. const Port *p = Master::ports.apropos(path.c_str());
  193. if(p) {
  194. printf("loading midi port...\n");
  195. midi.addNewMapper(CC, *p, path);
  196. } else {
  197. printf("unknown midi bindable <%s>\n", path.c_str());
  198. }
  199. }
  200. xml.exitbranch();
  201. } else
  202. printf("cannot find 'midi-learn' branch...\n");
  203. }
  204. /******************************************************************************
  205. * Non-RealTime Object Store *
  206. * *
  207. * *
  208. * Storage For Objects which need to be interfaced with outside the realtime *
  209. * thread (aka they have long lived operations which can be done out-of-band) *
  210. * *
  211. * - OscilGen instances as prepare() cannot be done in realtime and PAD *
  212. * depends on these instances *
  213. * - PADnoteParameter instances as applyparameters() cannot be done in *
  214. * realtime *
  215. * *
  216. * These instances are collected on every part change and kit change *
  217. ******************************************************************************/
  218. struct NonRtObjStore
  219. {
  220. std::map<std::string, void*> objmap;
  221. void extractMaster(Master *master)
  222. {
  223. for(int i=0; i < NUM_MIDI_PARTS; ++i) {
  224. extractPart(master->part[i], i);
  225. }
  226. }
  227. void extractPart(Part *part, int i)
  228. {
  229. for(int j=0; j < NUM_KIT_ITEMS; ++j) {
  230. auto &obj = part->kit[j];
  231. extractAD(obj.adpars, i, j);
  232. extractPAD(obj.padpars, i, j);
  233. }
  234. }
  235. void extractAD(ADnoteParameters *adpars, int i, int j)
  236. {
  237. std::string base = "/part"+to_s(i)+"/kit"+to_s(j)+"/";
  238. for(int k=0; k<NUM_VOICES; ++k) {
  239. std::string nbase = base+"adpars/VoicePar"+to_s(k)+"/";
  240. if(adpars) {
  241. auto &nobj = adpars->VoicePar[k];
  242. objmap[nbase+"OscilSmp/"] = nobj.OscilSmp;
  243. objmap[nbase+"FMSmp/"] = nobj.FMSmp;
  244. } else {
  245. objmap[nbase+"OscilSmp/"] = nullptr;
  246. objmap[nbase+"FMSmp/"] = nullptr;
  247. }
  248. }
  249. }
  250. void extractPAD(PADnoteParameters *padpars, int i, int j)
  251. {
  252. std::string base = "/part"+to_s(i)+"/kit"+to_s(j)+"/";
  253. for(int k=0; k<NUM_VOICES; ++k) {
  254. if(padpars) {
  255. objmap[base+"padpars/"] = padpars;
  256. objmap[base+"padpars/oscilgen/"] = padpars->oscilgen;
  257. } else {
  258. objmap[base+"padpars/"] = nullptr;
  259. objmap[base+"padpars/oscilgen/"] = nullptr;
  260. }
  261. }
  262. }
  263. void clear(void)
  264. {
  265. objmap.clear();
  266. }
  267. bool has(std::string loc)
  268. {
  269. return objmap.find(loc) != objmap.end();
  270. }
  271. void *get(std::string loc)
  272. {
  273. return objmap[loc];
  274. }
  275. void handleOscil(const char *msg, rtosc::RtData &d) {
  276. string obj_rl(d.message, msg);
  277. void *osc = get(obj_rl);
  278. assert(osc);
  279. strcpy(d.loc, obj_rl.c_str());
  280. d.obj = osc;
  281. OscilGen::non_realtime_ports.dispatch(msg, d);
  282. }
  283. void handlePad(const char *msg, rtosc::RtData &d) {
  284. string obj_rl(d.message, msg);
  285. void *pad = get(obj_rl);
  286. if(!strcmp(msg, "prepare")) {
  287. preparePadSynth(obj_rl, (PADnoteParameters*)pad, d);
  288. d.matches++;
  289. d.reply((obj_rl+"needPrepare").c_str(), "F");
  290. } else {
  291. assert(pad);
  292. strcpy(d.loc, obj_rl.c_str());
  293. d.obj = pad;
  294. PADnoteParameters::non_realtime_ports.dispatch(msg, d);
  295. if(rtosc_narguments(msg)) {
  296. if(!strcmp(msg, "oscilgen/prepare"))
  297. ; //ignore
  298. else {
  299. d.reply((obj_rl+"needPrepare").c_str(), "T");
  300. }
  301. }
  302. }
  303. }
  304. };
  305. /******************************************************************************
  306. * Realtime Parameter Store *
  307. * *
  308. * Storage for AD/PAD/SUB parameters which are allocated as needed by kits. *
  309. * Two classes of events affect this: *
  310. * 1. When a message to enable a kit is observed, then the kit is allocated *
  311. * and sent prior to the enable message. *
  312. * 2. When a part is allocated all part information is rebuilt *
  313. * *
  314. * (NOTE pointers aren't really needed here, just booleans on whether it has *
  315. * been allocated) *
  316. * This may be later utilized for copy/paste support *
  317. ******************************************************************************/
  318. struct ParamStore
  319. {
  320. ParamStore(void)
  321. {
  322. memset(add, 0, sizeof(add));
  323. memset(pad, 0, sizeof(pad));
  324. memset(sub, 0, sizeof(sub));
  325. }
  326. void extractPart(Part *part, int i)
  327. {
  328. for(int j=0; j < NUM_KIT_ITEMS; ++j) {
  329. auto kit = part->kit[j];
  330. add[i][j] = kit.adpars;
  331. sub[i][j] = kit.subpars;
  332. pad[i][j] = kit.padpars;
  333. }
  334. }
  335. ADnoteParameters *add[NUM_MIDI_PARTS][NUM_KIT_ITEMS];
  336. SUBnoteParameters *sub[NUM_MIDI_PARTS][NUM_KIT_ITEMS];
  337. PADnoteParameters *pad[NUM_MIDI_PARTS][NUM_KIT_ITEMS];
  338. };
  339. //XXX perhaps move this to Nio
  340. //(there needs to be some standard Nio stub file for this sort of stuff)
  341. namespace Nio
  342. {
  343. using std::get;
  344. rtosc::Ports ports = {
  345. {"sink-list:", 0, 0, [](const char *, rtosc::RtData &d) {
  346. auto list = Nio::getSinks();
  347. char *ret = rtosc_splat(d.loc, list);
  348. d.reply(ret);
  349. delete [] ret;
  350. }},
  351. {"source-list:", 0, 0, [](const char *, rtosc::RtData &d) {
  352. auto list = Nio::getSources();
  353. char *ret = rtosc_splat(d.loc, list);
  354. d.reply(ret);
  355. delete [] ret;
  356. }},
  357. {"source::s", 0, 0, [](const char *msg, rtosc::RtData &d) {
  358. if(rtosc_narguments(msg) == 0)
  359. d.reply(d.loc, "s", Nio::getSource().c_str());
  360. else
  361. Nio::setSource(rtosc_argument(msg,0).s);}},
  362. {"sink::s", 0, 0, [](const char *msg, rtosc::RtData &d) {
  363. if(rtosc_narguments(msg) == 0)
  364. d.reply(d.loc, "s", Nio::getSink().c_str());
  365. else
  366. Nio::setSink(rtosc_argument(msg,0).s);}},
  367. };
  368. }
  369. /* Implementation */
  370. class MiddleWareImpl
  371. {
  372. public:
  373. MiddleWare *parent;
  374. private:
  375. //Detect if the name of the process is 'zynaddsubfx'
  376. bool isPlugin() const
  377. {
  378. std::string proc_file = "/proc/" + to_s(getpid()) + "/comm";
  379. std::ifstream ifs(proc_file);
  380. if(ifs.good()) {
  381. std::string comm_name;
  382. ifs >> comm_name;
  383. return comm_name != "zynaddsubfx";
  384. }
  385. return true;
  386. }
  387. public:
  388. Config* const config;
  389. MiddleWareImpl(MiddleWare *mw, SYNTH_T synth, Config* config,
  390. int preferred_port);
  391. ~MiddleWareImpl(void);
  392. //Apply function while parameters are write locked
  393. void doReadOnlyOp(std::function<void()> read_only_fn);
  394. void savePart(int npart, const char *filename)
  395. {
  396. //Copy is needed as filename WILL get trashed during the rest of the run
  397. std::string fname = filename;
  398. //printf("saving part(%d,'%s')\n", npart, filename);
  399. doReadOnlyOp([this,fname,npart](){
  400. int res = master->part[npart]->saveXML(fname.c_str());
  401. (void)res;
  402. /*printf("results: '%s' '%d'\n",fname.c_str(), res);*/});
  403. }
  404. void loadPendingBank(int par, Bank &bank)
  405. {
  406. if(((unsigned int)par < bank.banks.size())
  407. && (bank.banks[par].dir != bank.bankfiletitle))
  408. bank.loadbank(bank.banks[par].dir);
  409. }
  410. void loadPart(int npart, const char *filename, Master *master)
  411. {
  412. actual_load[npart]++;
  413. if(actual_load[npart] != pending_load[npart])
  414. return;
  415. assert(actual_load[npart] <= pending_load[npart]);
  416. //load part in async fashion when possible
  417. #if HAVE_ASYNC
  418. auto alloc = std::async(std::launch::async,
  419. [master,filename,this,npart](){
  420. Part *p = new Part(*master->memory, synth,
  421. master->time,
  422. config->cfg.GzipCompression,
  423. config->cfg.Interpolation,
  424. &master->microtonal, master->fft);
  425. if(p->loadXMLinstrument(filename))
  426. fprintf(stderr, "Warning: failed to load part<%s>!\n", filename);
  427. auto isLateLoad = [this,npart]{
  428. return actual_load[npart] != pending_load[npart];
  429. };
  430. p->applyparameters(isLateLoad);
  431. return p;});
  432. //Load the part
  433. if(idle) {
  434. while(alloc.wait_for(std::chrono::seconds(0)) != std::future_status::ready) {
  435. idle(idle_ptr);
  436. }
  437. }
  438. Part *p = alloc.get();
  439. #else
  440. Part *p = new Part(*master->memory, synth, master->time,
  441. config->cfg.GzipCompression,
  442. config->cfg.Interpolation,
  443. &master->microtonal, master->fft);
  444. if(p->loadXMLinstrument(filename))
  445. fprintf(stderr, "Warning: failed to load part<%s>!\n", filename);
  446. auto isLateLoad = [this,npart]{
  447. return actual_load[npart] != pending_load[npart];
  448. };
  449. p->applyparameters(isLateLoad);
  450. #endif
  451. obj_store.extractPart(p, npart);
  452. kits.extractPart(p, npart);
  453. //Give it to the backend and wait for the old part to return for
  454. //deallocation
  455. parent->transmitMsg("/load-part", "ib", npart, sizeof(Part*), &p);
  456. GUI::raiseUi(ui, "/damage", "s", ("/part"+to_s(npart)+"/").c_str());
  457. }
  458. //Load a new cleared Part instance
  459. void loadClearPart(int npart)
  460. {
  461. if(npart == -1)
  462. return;
  463. Part *p = new Part(*master->memory, synth,
  464. master->time,
  465. config->cfg.GzipCompression,
  466. config->cfg.Interpolation,
  467. &master->microtonal, master->fft);
  468. p->applyparameters();
  469. obj_store.extractPart(p, npart);
  470. kits.extractPart(p, npart);
  471. //Give it to the backend and wait for the old part to return for
  472. //deallocation
  473. parent->transmitMsg("/load-part", "ib", npart, sizeof(Part*), &p);
  474. GUI::raiseUi(ui, "/damage", "s", ("/part"+to_s(npart)+"/").c_str());
  475. }
  476. //Well, you don't get much crazier than changing out all of your RT
  477. //structures at once... TODO error handling
  478. void loadMaster(const char *filename)
  479. {
  480. Master *m = new Master(synth, config);
  481. m->uToB = uToB;
  482. m->bToU = bToU;
  483. if(filename) {
  484. if ( m->loadXML(filename) ) {
  485. delete m;
  486. return;
  487. }
  488. m->applyparameters();
  489. }
  490. //Update resource locator table
  491. updateResources(m);
  492. master = m;
  493. //Give it to the backend and wait for the old part to return for
  494. //deallocation
  495. parent->transmitMsg("/load-master", "b", sizeof(Master*), &m);
  496. }
  497. void updateResources(Master *m)
  498. {
  499. obj_store.clear();
  500. obj_store.extractMaster(m);
  501. for(int i=0; i<NUM_MIDI_PARTS; ++i)
  502. kits.extractPart(m->part[i], i);
  503. }
  504. //If currently broadcasting messages
  505. bool broadcast = false;
  506. //If message should be forwarded through snoop ports
  507. bool forward = false;
  508. //if message is in order or out-of-order execution
  509. bool in_order = false;
  510. //If accepting undo events as user driven
  511. bool recording_undo = true;
  512. void bToUhandle(const char *rtmsg);
  513. void tick(void)
  514. {
  515. if(server)
  516. while(lo_server_recv_noblock(server, 0));
  517. while(bToU->hasNext()) {
  518. const char *rtmsg = bToU->read();
  519. bToUhandle(rtmsg);
  520. }
  521. while(auto *m = multi_thread_source.read()) {
  522. handleMsg(m->memory);
  523. multi_thread_source.free(m);
  524. }
  525. }
  526. void kitEnable(const char *msg);
  527. void kitEnable(int part, int kit, int type);
  528. // Handle an event with special cases
  529. void handleMsg(const char *msg);
  530. void write(const char *path, const char *args, ...);
  531. void write(const char *path, const char *args, va_list va);
  532. // Send a message to a remote client
  533. void sendToRemote(const char *msg, std::string dest);
  534. // Send a message to the current remote client
  535. void sendToCurrentRemote(const char *msg)
  536. {
  537. sendToRemote(msg, in_order ? curr_url : last_url);
  538. }
  539. // Broadcast a message to all listening remote clients
  540. void broadcastToRemote(const char *msg);
  541. /*
  542. * Provides a mapping for non-RT objects stored inside the backend
  543. * - Oscilgen almost all parameters can be safely set
  544. * - Padnote can have anything set on its oscilgen and a very small set
  545. * of general parameters
  546. */
  547. NonRtObjStore obj_store;
  548. //This code will own the pointer to master, be prepared for odd things if
  549. //this assumption is broken
  550. Master *master;
  551. //The ONLY means that any chunk of UI code should have for interacting with the
  552. //backend
  553. Fl_Osc_Interface *osc;
  554. //Synth Engine Parameters
  555. ParamStore kits;
  556. //Callback When Waiting on async events
  557. void(*idle)(void*);
  558. void* idle_ptr;
  559. //General UI callback
  560. cb_t cb;
  561. //UI handle
  562. void *ui;
  563. std::atomic_int pending_load[NUM_MIDI_PARTS];
  564. std::atomic_int actual_load[NUM_MIDI_PARTS];
  565. //Undo/Redo
  566. rtosc::UndoHistory undo;
  567. //MIDI Learn
  568. rtosc::MidiMappernRT midi_mapper;
  569. //Link To the Realtime
  570. rtosc::ThreadLink *bToU;
  571. rtosc::ThreadLink *uToB;
  572. //Link to the unknown
  573. MultiQueue multi_thread_source;
  574. //LIBLO
  575. lo_server server;
  576. string last_url, curr_url;
  577. //Synthesis Rate Parameters
  578. const SYNTH_T synth;
  579. PresetsStore presetsstore;
  580. };
  581. /*****************************************************************************
  582. * Data Object for Non-RT Class Dispatch *
  583. *****************************************************************************/
  584. class MwDataObj:public rtosc::RtData
  585. {
  586. public:
  587. MwDataObj(MiddleWareImpl *mwi_)
  588. {
  589. loc_size = 1024;
  590. loc = new char[loc_size];
  591. memset(loc, 0, loc_size);
  592. buffer = new char[4*4096];
  593. memset(buffer, 0, 4*4096);
  594. obj = mwi_;
  595. mwi = mwi_;
  596. forwarded = false;
  597. }
  598. ~MwDataObj(void)
  599. {
  600. delete[] buffer;
  601. }
  602. //Replies and broadcasts go to the remote
  603. //Chain calls repeat the call into handle()
  604. //Forward calls send the message directly to the realtime
  605. virtual void reply(const char *path, const char *args, ...)
  606. {
  607. //printf("reply building '%s'\n", path);
  608. va_list va;
  609. va_start(va,args);
  610. if(!strcmp(path, "/forward")) { //forward the information to the backend
  611. args++;
  612. path = va_arg(va, const char *);
  613. rtosc_vmessage(buffer,4*4096,path,args,va);
  614. } else {
  615. rtosc_vmessage(buffer,4*4096,path,args,va);
  616. reply(buffer);
  617. }
  618. va_end(va);
  619. }
  620. virtual void reply(const char *msg){
  621. mwi->sendToCurrentRemote(msg);
  622. };
  623. //virtual void broadcast(const char *path, const char *args, ...){(void)path;(void)args;};
  624. //virtual void broadcast(const char *msg){(void)msg;};
  625. virtual void chain(const char *msg) override
  626. {
  627. assert(msg);
  628. // printf("chain call on <%s>\n", msg);
  629. mwi->handleMsg(msg);
  630. }
  631. virtual void chain(const char *path, const char *args, ...) override
  632. {
  633. assert(path);
  634. va_list va;
  635. va_start(va,args);
  636. rtosc_vmessage(buffer,4*4096,path,args,va);
  637. chain(buffer);
  638. va_end(va);
  639. }
  640. virtual void forward(const char *) override
  641. {
  642. forwarded = true;
  643. }
  644. bool forwarded;
  645. private:
  646. char *buffer;
  647. MiddleWareImpl *mwi;
  648. };
  649. static int extractInt(const char *msg)
  650. {
  651. const char *mm = msg;
  652. while(*mm && !isdigit(*mm)) ++mm;
  653. if(isdigit(*mm))
  654. return atoi(mm);
  655. return -1;
  656. }
  657. static const char *chomp(const char *msg)
  658. {
  659. while(*msg && *msg!='/') ++msg; \
  660. msg = *msg ? msg+1 : msg;
  661. return msg;
  662. };
  663. using rtosc::RtData;
  664. #define rObject Bank
  665. #define rBegin [](const char *msg, RtData &d) { (void)msg;(void)d;\
  666. rObject &impl = *((rObject*)d.obj);(void)impl;
  667. #define rEnd }
  668. /*****************************************************************************
  669. * Instrument Banks *
  670. * *
  671. * Banks and presets in general are not classed as realtime safe *
  672. * *
  673. * The supported operations are: *
  674. * - Load Names *
  675. * - Load Bank *
  676. * - Refresh List of Banks *
  677. *****************************************************************************/
  678. rtosc::Ports bankPorts = {
  679. {"rescan:", 0, 0,
  680. rBegin;
  681. impl.rescanforbanks();
  682. //Send updated banks
  683. int i = 0;
  684. for(auto &elm : impl.banks)
  685. d.reply("/bank/bank_select", "iss", i++, elm.name.c_str(), elm.dir.c_str());
  686. d.reply("/bank/bank_select", "i", impl.bankpos);
  687. rEnd},
  688. {"slot#1024:", 0, 0,
  689. rBegin;
  690. const int loc = extractInt(msg);
  691. if(loc >= BANK_SIZE)
  692. return;
  693. d.reply("/bankview", "iss",
  694. loc, impl.ins[loc].name.c_str(),
  695. impl.ins[loc].filename.c_str());
  696. rEnd},
  697. {"banks:", 0, 0,
  698. rBegin;
  699. int i = 0;
  700. for(auto &elm : impl.banks)
  701. d.reply("/bank/bank_select", "iss", i++, elm.name.c_str(), elm.dir.c_str());
  702. rEnd},
  703. {"bank_select::i", 0, 0,
  704. rBegin
  705. if(rtosc_narguments(msg)) {
  706. const int pos = rtosc_argument(msg, 0).i;
  707. d.reply(d.loc, "i", pos);
  708. if(impl.bankpos != pos) {
  709. impl.bankpos = pos;
  710. impl.loadbank(impl.banks[pos].dir);
  711. //Reload bank slots
  712. for(int i=0; i<BANK_SIZE; ++i)
  713. d.reply("/bankview", "iss",
  714. i, impl.ins[i].name.c_str(),
  715. impl.ins[i].filename.c_str());
  716. }
  717. } else
  718. d.reply("/bank/bank_select", "i", impl.bankpos);
  719. rEnd},
  720. {"rename_slot:is", 0, 0,
  721. rBegin;
  722. const int slot = rtosc_argument(msg, 0).i;
  723. const char *name = rtosc_argument(msg, 1).s;
  724. const int err = impl.setname(slot, name, -1);
  725. if(err) {
  726. d.reply("/alert", "s",
  727. "Failed To Rename Bank Slot, please check file permissions");
  728. }
  729. rEnd},
  730. {"swap_slots:ii", 0, 0,
  731. rBegin;
  732. const int slota = rtosc_argument(msg, 0).i;
  733. const int slotb = rtosc_argument(msg, 1).i;
  734. const int err = impl.swapslot(slota, slotb);
  735. if(err)
  736. d.reply("/alert", "s",
  737. "Failed To Swap Bank Slots, please check file permissions");
  738. rEnd},
  739. {"clear_slot:i", 0, 0,
  740. rBegin;
  741. const int slot = rtosc_argument(msg, 0).i;
  742. const int err = impl.clearslot(slot);
  743. if(err)
  744. d.reply("/alert", "s",
  745. "Failed To Clear Bank Slot, please check file permissions");
  746. rEnd},
  747. {"msb:i", 0, 0,
  748. rBegin;
  749. impl.setMsb(rtosc_argument(msg, 0).i);
  750. rEnd},
  751. {"lsb:i", 0, 0,
  752. rBegin;
  753. impl.setLsb(rtosc_argument(msg, 0).i);
  754. rEnd},
  755. };
  756. /******************************************************************************
  757. * MiddleWare Snooping Ports *
  758. * *
  759. * These ports handle: *
  760. * - Events going to the realtime thread which cannot be safely handled *
  761. * there *
  762. * - Events generated by the realtime thread which are not destined for a *
  763. * user interface *
  764. ******************************************************************************/
  765. #undef rObject
  766. #define rObject MiddleWareImpl
  767. #ifndef STRINGIFY
  768. #define STRINGIFY2(a) #a
  769. #define STRINGIFY(a) STRINGIFY2(a)
  770. #endif
  771. /*
  772. * BASE/part#/kititem#
  773. * BASE/part#/kit#/adpars/voice#/oscil/\*
  774. * BASE/part#/kit#/adpars/voice#/mod-oscil/\*
  775. * BASE/part#/kit#/padpars/prepare
  776. * BASE/part#/kit#/padpars/oscil/\*
  777. */
  778. static rtosc::Ports middwareSnoopPorts = {
  779. {"part#" STRINGIFY(NUM_MIDI_PARTS)
  780. "/kit#" STRINGIFY(NUM_KIT_ITEMS) "/adpars/VoicePar#"
  781. STRINGIFY(NUM_VOICES) "/OscilSmp/", 0, &OscilGen::non_realtime_ports,
  782. rBegin;
  783. impl.obj_store.handleOscil(chomp(chomp(chomp(chomp(chomp(msg))))), d);
  784. rEnd},
  785. {"part#" STRINGIFY(NUM_MIDI_PARTS)
  786. "/kit#" STRINGIFY(NUM_KIT_ITEMS)
  787. "/adpars/VoicePar#" STRINGIFY(NUM_VOICES) "/FMSmp/", 0, &OscilGen::non_realtime_ports,
  788. rBegin
  789. impl.obj_store.handleOscil(chomp(chomp(chomp(chomp(chomp(msg))))), d);
  790. rEnd},
  791. {"part#" STRINGIFY(NUM_MIDI_PARTS)
  792. "/kit#" STRINGIFY(NUM_KIT_ITEMS) "/padpars/", 0, &PADnoteParameters::non_realtime_ports,
  793. rBegin
  794. impl.obj_store.handlePad(chomp(chomp(chomp(msg))), d);
  795. rEnd},
  796. {"bank/", 0, &bankPorts,
  797. rBegin;
  798. d.obj = &impl.master->bank;
  799. bankPorts.dispatch(chomp(msg),d);
  800. rEnd},
  801. {"bank/save_to_slot:ii", 0, 0,
  802. rBegin;
  803. const int part_id = rtosc_argument(msg, 0).i;
  804. const int slot = rtosc_argument(msg, 1).i;
  805. int err = 0;
  806. impl.doReadOnlyOp([&impl,slot,part_id,&err](){
  807. err = impl.master->bank.savetoslot(slot, impl.master->part[part_id]);});
  808. if(err) {
  809. char buffer[1024];
  810. rtosc_message(buffer, 1024, "/alert", "s",
  811. "Failed To Save To Bank Slot, please check file permissions");
  812. GUI::raiseUi(impl.ui, buffer);
  813. }
  814. rEnd},
  815. {"config/", 0, &Config::ports,
  816. rBegin;
  817. d.obj = impl.config;
  818. Config::ports.dispatch(chomp(msg), d);
  819. rEnd},
  820. {"presets/", 0, &real_preset_ports, [](const char *msg, RtData &d) {
  821. MiddleWareImpl *obj = (MiddleWareImpl*)d.obj;
  822. d.obj = (void*)obj->parent;
  823. real_preset_ports.dispatch(chomp(msg), d);
  824. if(strstr(msg, "paste") && rtosc_argument_string(msg)[0] == 's')
  825. d.reply("/damage", "s", rtosc_argument(msg, 0).s);
  826. }},
  827. {"io/", 0, &Nio::ports, [](const char *msg, RtData &d) {
  828. Nio::ports.dispatch(chomp(msg), d);}},
  829. {"part*/kit*/{Padenabled,Ppadenabled,Psubenabled}:T:F", 0, 0,
  830. rBegin;
  831. impl.kitEnable(msg);
  832. d.forward();
  833. rEnd},
  834. {"save_xlz:s", 0, 0,
  835. rBegin;
  836. const char *file = rtosc_argument(msg, 0).s;
  837. XMLwrapper xml;
  838. saveMidiLearn(xml, impl.midi_mapper);
  839. xml.saveXMLfile(file, impl.master->gzip_compression);
  840. rEnd},
  841. {"load_xlz:s", 0, 0,
  842. rBegin;
  843. const char *file = rtosc_argument(msg, 0).s;
  844. XMLwrapper xml;
  845. xml.loadXMLfile(file);
  846. loadMidiLearn(xml, impl.midi_mapper);
  847. rEnd},
  848. {"save_xmz:s", 0, 0,
  849. rBegin;
  850. const char *file = rtosc_argument(msg, 0).s;
  851. //Copy is needed as filename WILL get trashed during the rest of the run
  852. impl.doReadOnlyOp([&impl,file](){
  853. int res = impl.master->saveXML(file);
  854. (void)res;});
  855. rEnd},
  856. {"save_xiz:is", 0, 0,
  857. rBegin;
  858. const int part_id = rtosc_argument(msg,0).i;
  859. const char *file = rtosc_argument(msg,1).s;
  860. impl.savePart(part_id, file);
  861. rEnd},
  862. {"load_xmz:s", 0, 0,
  863. rBegin;
  864. const char *file = rtosc_argument(msg, 0).s;
  865. impl.loadMaster(file);
  866. rEnd},
  867. {"reset_master:", 0, 0,
  868. rBegin;
  869. impl.loadMaster(NULL);
  870. rEnd},
  871. {"load_xiz:is", 0, 0,
  872. rBegin;
  873. const int part_id = rtosc_argument(msg,0).i;
  874. const char *file = rtosc_argument(msg,1).s;
  875. impl.pending_load[part_id]++;
  876. impl.loadPart(part_id, file, impl.master);
  877. rEnd},
  878. {"load-part:is", 0, 0,
  879. rBegin;
  880. const int part_id = rtosc_argument(msg,0).i;
  881. const char *file = rtosc_argument(msg,1).s;
  882. impl.pending_load[part_id]++;
  883. impl.loadPart(part_id, file, impl.master);
  884. rEnd},
  885. {"load-part:iss", 0, 0,
  886. rBegin;
  887. const int part_id = rtosc_argument(msg,0).i;
  888. const char *file = rtosc_argument(msg,1).s;
  889. const char *name = rtosc_argument(msg,2).s;
  890. impl.pending_load[part_id]++;
  891. impl.loadPart(part_id, file, impl.master);
  892. impl.uToB->write(("/part"+to_s(part_id)+"/Pname").c_str(), "s",
  893. name);
  894. rEnd},
  895. {"setprogram:i:c", 0, 0,
  896. rBegin;
  897. Bank &bank = impl.master->bank;
  898. const int slot = rtosc_argument(msg, 0).i + 128*bank.bank_lsb;
  899. if(slot < BANK_SIZE) {
  900. impl.pending_load[0]++;
  901. impl.loadPart(0, impl.master->bank.ins[slot].filename.c_str(), impl.master);
  902. impl.uToB->write("/part0/Pname", "s", impl.master->bank.ins[slot].name.c_str());
  903. }
  904. rEnd},
  905. {"part#16/clear:", 0, 0,
  906. rBegin;
  907. impl.loadClearPart(extractInt(msg));
  908. rEnd},
  909. {"undo:", 0, 0,
  910. rBegin;
  911. impl.undo.seekHistory(-1);
  912. rEnd},
  913. {"redo:", 0, 0,
  914. rBegin;
  915. impl.undo.seekHistory(+1);
  916. rEnd},
  917. {"learn:s", 0, 0,
  918. rBegin;
  919. string addr = rtosc_argument(msg, 0).s;
  920. auto &midi = impl.midi_mapper;
  921. auto map = midi.getMidiMappingStrings();
  922. if(map.find(addr) != map.end())
  923. midi.map(addr.c_str(), false);
  924. else
  925. midi.map(addr.c_str(), true);
  926. rEnd},
  927. //drop this message into the abyss
  928. {"ui/title:", 0, 0, [](const char *msg, RtData &d) {}}
  929. };
  930. static rtosc::Ports middlewareReplyPorts = {
  931. {"echo:ss", 0, 0,
  932. rBegin;
  933. const char *type = rtosc_argument(msg, 0).s;
  934. const char *url = rtosc_argument(msg, 1).s;
  935. if(!strcmp(type, "OSC_URL"))
  936. impl.curr_url = url;
  937. rEnd},
  938. {"free:sb", 0, 0,
  939. rBegin;
  940. const char *type = rtosc_argument(msg, 0).s;
  941. void *ptr = *(void**)rtosc_argument(msg, 1).b.data;
  942. deallocate(type, ptr);
  943. rEnd},
  944. {"request_memory:", 0, 0,
  945. rBegin;
  946. //Generate out more memory for the RT memory pool
  947. //5MBi chunk
  948. size_t N = 5*1024*1024;
  949. void *mem = malloc(N);
  950. impl.uToB->write("/add-rt-memory", "bi", sizeof(void*), &mem, N);
  951. rEnd},
  952. {"setprogram:cc:ii", 0, 0,
  953. rBegin;
  954. const int part = rtosc_argument(msg, 0).i;
  955. const int program = rtosc_argument(msg, 1).i;
  956. impl.loadPart(part, impl.master->bank.ins[program].filename.c_str(), impl.master);
  957. impl.uToB->write(("/part"+to_s(part)+"/Pname").c_str(), "s", impl.master->bank.ins[program].name.c_str());
  958. rEnd},
  959. {"setbank:c", 0, 0,
  960. rBegin;
  961. impl.loadPendingBank(rtosc_argument(msg,0).i, impl.master->bank);
  962. rEnd},
  963. {"undo_pause:", 0, 0, rBegin; impl.recording_undo = false; rEnd},
  964. {"undo_resume:", 0, 0, rBegin; impl.recording_undo = true; rEnd},
  965. {"undo_change", 0, 0,
  966. rBegin;
  967. if(impl.recording_undo)
  968. impl.undo.recordEvent(msg);
  969. rEnd},
  970. {"midi-use-CC:i", 0, 0,
  971. rBegin;
  972. impl.midi_mapper.useFreeID(rtosc_argument(msg, 0).i);
  973. rEnd},
  974. {"broadcast:", 0, 0, rBegin; impl.broadcast = true; rEnd},
  975. {"forward:", 0, 0, rBegin; impl.forward = true; rEnd},
  976. };
  977. #undef rBegin
  978. #undef rEnd
  979. /******************************************************************************
  980. * MiddleWare Implementation *
  981. ******************************************************************************/
  982. MiddleWareImpl::MiddleWareImpl(MiddleWare *mw, SYNTH_T synth_,
  983. Config* config, int preferrred_port)
  984. :parent(mw), config(config), ui(nullptr), synth(std::move(synth_)),
  985. presetsstore(*config)
  986. {
  987. bToU = new rtosc::ThreadLink(4096*2,1024);
  988. uToB = new rtosc::ThreadLink(4096*2,1024);
  989. midi_mapper.base_ports = &Master::ports;
  990. midi_mapper.rt_cb = [this](const char *msg){handleMsg(msg);};
  991. if(preferrred_port != -1)
  992. server = lo_server_new_with_proto(to_s(preferrred_port).c_str(),
  993. LO_UDP, liblo_error_cb);
  994. else
  995. server = lo_server_new_with_proto(NULL, LO_UDP, liblo_error_cb);
  996. if(server) {
  997. lo_server_add_method(server, NULL, NULL, handler_function, mw);
  998. fprintf(stderr, "lo server running on %d\n", lo_server_get_port(server));
  999. } else
  1000. fprintf(stderr, "lo server could not be started :-/\n");
  1001. //dummy callback for starters
  1002. cb = [](void*, const char*){};
  1003. idle = 0;
  1004. idle_ptr = 0;
  1005. master = new Master(synth, config);
  1006. master->bToU = bToU;
  1007. master->uToB = uToB;
  1008. osc = GUI::genOscInterface(mw);
  1009. //Grab objects of interest from master
  1010. updateResources(master);
  1011. //Null out Load IDs
  1012. for(int i=0; i < NUM_MIDI_PARTS; ++i) {
  1013. pending_load[i] = 0;
  1014. actual_load[i] = 0;
  1015. }
  1016. //Setup Undo
  1017. undo.setCallback([this](const char *msg) {
  1018. // printf("undo callback <%s>\n", msg);
  1019. char buf[1024];
  1020. rtosc_message(buf, 1024, "/undo_pause","");
  1021. handleMsg(buf);
  1022. handleMsg(msg);
  1023. rtosc_message(buf, 1024, "/undo_resume","");
  1024. handleMsg(buf);
  1025. });
  1026. }
  1027. MiddleWareImpl::~MiddleWareImpl(void)
  1028. {
  1029. if(server)
  1030. lo_server_free(server);
  1031. delete master;
  1032. delete osc;
  1033. delete bToU;
  1034. delete uToB;
  1035. }
  1036. /** Threading When Saving
  1037. * ----------------------
  1038. *
  1039. * Procedure Middleware:
  1040. * 1) Middleware sends /freeze_state to backend
  1041. * 2) Middleware waits on /state_frozen from backend
  1042. * All intervening commands are held for out of order execution
  1043. * 3) Aquire memory
  1044. * At this time by the memory barrier we are guarenteed that all old
  1045. * writes are done and assuming the freezing logic is sound, then it is
  1046. * impossible for any other parameter to change at this time
  1047. * 3) Middleware performs saving operation
  1048. * 4) Middleware sends /thaw_state to backend
  1049. * 5) Restore in order execution
  1050. *
  1051. * Procedure Backend:
  1052. * 1) Observe /freeze_state and disable all mutating events (MIDI CC)
  1053. * 2) Run a memory release to ensure that all writes are complete
  1054. * 3) Send /state_frozen to Middleware
  1055. * time...
  1056. * 4) Observe /thaw_state and resume normal processing
  1057. */
  1058. void MiddleWareImpl::doReadOnlyOp(std::function<void()> read_only_fn)
  1059. {
  1060. assert(uToB);
  1061. uToB->write("/freeze_state","");
  1062. std::list<const char *> fico;
  1063. int tries = 0;
  1064. while(tries++ < 10000) {
  1065. if(!bToU->hasNext()) {
  1066. usleep(500);
  1067. continue;
  1068. }
  1069. const char *msg = bToU->read();
  1070. if(!strcmp("/state_frozen", msg))
  1071. break;
  1072. size_t bytes = rtosc_message_length(msg, bToU->buffer_size());
  1073. char *save_buf = new char[bytes];
  1074. memcpy(save_buf, msg, bytes);
  1075. fico.push_back(save_buf);
  1076. }
  1077. assert(tries < 10000);//if this happens, the backend must be dead
  1078. std::atomic_thread_fence(std::memory_order_acquire);
  1079. //Now it is safe to do any read only operation
  1080. read_only_fn();
  1081. //Now to resume normal operations
  1082. uToB->write("/thaw_state","");
  1083. for(auto x:fico) {
  1084. uToB->raw_write(x);
  1085. delete [] x;
  1086. }
  1087. }
  1088. void MiddleWareImpl::broadcastToRemote(const char *rtmsg)
  1089. {
  1090. //Always send to the local UI
  1091. sendToRemote(rtmsg, "GUI");
  1092. //Send to remote UI if there's one listening
  1093. if(curr_url != "GUI")
  1094. sendToRemote(rtmsg, curr_url);
  1095. broadcast = false;
  1096. }
  1097. void MiddleWareImpl::sendToRemote(const char *rtmsg, std::string dest)
  1098. {
  1099. //printf("sendToRemote(%s:%s,%s)\n", rtmsg, rtosc_argument_string(rtmsg),
  1100. // dest.c_str());
  1101. if(dest == "GUI") {
  1102. cb(ui, rtmsg);
  1103. } else if(!dest.empty()) {
  1104. lo_message msg = lo_message_deserialise((void*)rtmsg,
  1105. rtosc_message_length(rtmsg, bToU->buffer_size()), NULL);
  1106. //Send to known url
  1107. lo_address addr = lo_address_new_from_url(dest.c_str());
  1108. if(addr)
  1109. lo_send_message(addr, rtmsg, msg);
  1110. }
  1111. }
  1112. /**
  1113. * Handle all events coming from the backend
  1114. *
  1115. * This includes forwarded events which need to be retransmitted to the backend
  1116. * after the snooping code inspects the message
  1117. */
  1118. void MiddleWareImpl::bToUhandle(const char *rtmsg)
  1119. {
  1120. //Verify Message isn't a known corruption bug
  1121. assert(strcmp(rtmsg, "/part0/kit0/Ppadenableda"));
  1122. assert(strcmp(rtmsg, "/ze_state"));
  1123. //Dump Incomming Events For Debugging
  1124. if(strcmp(rtmsg, "/vu-meter") && false) {
  1125. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 1 + 30, 0 + 40);
  1126. fprintf(stdout, "frontend[%c]: '%s'<%s>\n", forward?'f':broadcast?'b':'N',
  1127. rtmsg, rtosc_argument_string(rtmsg));
  1128. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 7 + 30, 0 + 40);
  1129. }
  1130. //Activity dot
  1131. //printf(".");fflush(stdout);
  1132. MwDataObj d(this);
  1133. middlewareReplyPorts.dispatch(rtmsg, d, true);
  1134. in_order = true;
  1135. //Normal message not captured by the ports
  1136. if(d.matches == 0) {
  1137. if(forward) {
  1138. forward = false;
  1139. handleMsg(rtmsg);
  1140. } if(broadcast)
  1141. broadcastToRemote(rtmsg);
  1142. else
  1143. sendToCurrentRemote(rtmsg);
  1144. }
  1145. in_order = false;
  1146. }
  1147. //Allocate kits on a as needed basis
  1148. void MiddleWareImpl::kitEnable(const char *msg)
  1149. {
  1150. const string argv = rtosc_argument_string(msg);
  1151. if(argv != "T")
  1152. return;
  1153. //Extract fields from:
  1154. //BASE/part#/kit#/Pxxxenabled
  1155. int type = -1;
  1156. if(strstr(msg, "Padenabled"))
  1157. type = 0;
  1158. else if(strstr(msg, "Ppadenabled"))
  1159. type = 1;
  1160. else if(strstr(msg, "Psubenabled"))
  1161. type = 2;
  1162. else
  1163. return;
  1164. const char *tmp = strstr(msg, "part");
  1165. if(tmp == NULL)
  1166. return;
  1167. const int part = atoi(tmp+4);
  1168. tmp = strstr(msg, "kit");
  1169. if(tmp == NULL)
  1170. return;
  1171. const int kit = atoi(tmp+3);
  1172. kitEnable(part, kit, type);
  1173. }
  1174. void MiddleWareImpl::kitEnable(int part, int kit, int type)
  1175. {
  1176. //printf("attempting a kit enable<%d,%d,%d>\n", part, kit, type);
  1177. string url = "/part"+to_s(part)+"/kit"+to_s(kit)+"/";
  1178. void *ptr = NULL;
  1179. if(type == 0 && kits.add[part][kit] == NULL) {
  1180. ptr = kits.add[part][kit] = new ADnoteParameters(synth, master->fft);
  1181. url += "adpars-data";
  1182. obj_store.extractAD(kits.add[part][kit], part, kit);
  1183. } else if(type == 1 && kits.pad[part][kit] == NULL) {
  1184. ptr = kits.pad[part][kit] = new PADnoteParameters(synth, master->fft);
  1185. url += "padpars-data";
  1186. obj_store.extractPAD(kits.pad[part][kit], part, kit);
  1187. } else if(type == 2 && kits.sub[part][kit] == NULL) {
  1188. ptr = kits.sub[part][kit] = new SUBnoteParameters();
  1189. url += "subpars-data";
  1190. }
  1191. //Send the new memory
  1192. if(ptr)
  1193. uToB->write(url.c_str(), "b", sizeof(void*), &ptr);
  1194. }
  1195. /*
  1196. * Handle all messages traveling to the realtime side.
  1197. */
  1198. void MiddleWareImpl::handleMsg(const char *msg)
  1199. {
  1200. //Check for known bugs
  1201. assert(msg && *msg && rindex(msg, '/')[1]);
  1202. assert(strstr(msg,"free") == NULL || strstr(rtosc_argument_string(msg), "b") == NULL);
  1203. assert(strcmp(msg, "/part0/Psysefxvol"));
  1204. assert(strcmp(msg, "/Penabled"));
  1205. assert(strcmp(msg, "part0/part0/Ppanning"));
  1206. assert(strcmp(msg, "sysefx0sysefx0/preset"));
  1207. assert(strcmp(msg, "/sysefx0preset"));
  1208. assert(strcmp(msg, "Psysefxvol0/part0"));
  1209. if(strcmp("/get-vu", msg) && false) {
  1210. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 6 + 30, 0 + 40);
  1211. fprintf(stdout, "middleware: '%s':%s\n", msg, rtosc_argument_string(msg));
  1212. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 7 + 30, 0 + 40);
  1213. }
  1214. const char *last_path = rindex(msg, '/');
  1215. if(!last_path) {
  1216. printf("Bad message in handleMsg() <%s>\n", msg);
  1217. assert(false);
  1218. return;
  1219. }
  1220. MwDataObj d(this);
  1221. middwareSnoopPorts.dispatch(msg, d, true);
  1222. //A message unmodified by snooping
  1223. if(d.matches == 0 || d.forwarded) {
  1224. //if(strcmp("/get-vu", msg)) {
  1225. // printf("Message Continuing on<%s:%s>...\n", msg, rtosc_argument_string(msg));
  1226. //}
  1227. uToB->raw_write(msg);
  1228. } else {
  1229. //printf("Message Handled<%s:%s>...\n", msg, rtosc_argument_string(msg));
  1230. }
  1231. }
  1232. void MiddleWareImpl::write(const char *path, const char *args, ...)
  1233. {
  1234. //We have a free buffer in the threadlink, so use it
  1235. va_list va;
  1236. va_start(va, args);
  1237. write(path, args, va);
  1238. va_end(va);
  1239. }
  1240. void MiddleWareImpl::write(const char *path, const char *args, va_list va)
  1241. {
  1242. //printf("is that a '%s' I see there?\n", path);
  1243. char *buffer = uToB->buffer();
  1244. unsigned len = uToB->buffer_size();
  1245. bool success = rtosc_vmessage(buffer, len, path, args, va);
  1246. //printf("working on '%s':'%s'\n",path, args);
  1247. if(success)
  1248. handleMsg(buffer);
  1249. else
  1250. warnx("Failed to write message to '%s'", path);
  1251. }
  1252. /******************************************************************************
  1253. * MidleWare Forwarding Stubs *
  1254. ******************************************************************************/
  1255. MiddleWare::MiddleWare(SYNTH_T synth, Config* config,
  1256. int preferred_port)
  1257. :impl(new MiddleWareImpl(this, std::move(synth), config, preferred_port))
  1258. {}
  1259. MiddleWare::~MiddleWare(void)
  1260. {
  1261. delete impl;
  1262. }
  1263. void MiddleWare::updateResources(Master *m)
  1264. {
  1265. impl->updateResources(m);
  1266. }
  1267. Master *MiddleWare::spawnMaster(void)
  1268. {
  1269. assert(impl->master);
  1270. assert(impl->master->uToB);
  1271. return impl->master;
  1272. }
  1273. Fl_Osc_Interface *MiddleWare::spawnUiApi(void)
  1274. {
  1275. return impl->osc;
  1276. }
  1277. void MiddleWare::tick(void)
  1278. {
  1279. impl->tick();
  1280. }
  1281. void MiddleWare::doReadOnlyOp(std::function<void()> fn)
  1282. {
  1283. impl->doReadOnlyOp(fn);
  1284. }
  1285. void MiddleWare::setUiCallback(void(*cb)(void*,const char *), void *ui)
  1286. {
  1287. impl->cb = cb;
  1288. impl->ui = ui;
  1289. }
  1290. void MiddleWare::setIdleCallback(void(*cb)(void*), void *ptr)
  1291. {
  1292. impl->idle = cb;
  1293. impl->idle_ptr = ptr;
  1294. }
  1295. void MiddleWare::transmitMsg(const char *msg)
  1296. {
  1297. impl->handleMsg(msg);
  1298. }
  1299. void MiddleWare::transmitMsg(const char *path, const char *args, ...)
  1300. {
  1301. char buffer[1024];
  1302. va_list va;
  1303. va_start(va,args);
  1304. if(rtosc_vmessage(buffer,1024,path,args,va))
  1305. transmitMsg(buffer);
  1306. else
  1307. fprintf(stderr, "Error in transmitMsg(...)\n");
  1308. va_end(va);
  1309. }
  1310. void MiddleWare::transmitMsg_va(const char *path, const char *args, va_list va)
  1311. {
  1312. char buffer[1024];
  1313. if(rtosc_vmessage(buffer, 1024, path, args, va))
  1314. transmitMsg(buffer);
  1315. else
  1316. fprintf(stderr, "Error in transmitMsg(va)n");
  1317. }
  1318. void MiddleWare::messageAnywhere(const char *path, const char *args, ...)
  1319. {
  1320. auto *mem = impl->multi_thread_source.alloc();
  1321. if(!mem)
  1322. fprintf(stderr, "Middleware::messageAnywhere memory pool out of memory...\n");
  1323. va_list va;
  1324. va_start(va,args);
  1325. if(rtosc_vmessage(mem->memory,mem->size,path,args,va))
  1326. impl->multi_thread_source.write(mem);
  1327. else {
  1328. fprintf(stderr, "Middleware::messageAnywhere message too big...\n");
  1329. impl->multi_thread_source.free(mem);
  1330. }
  1331. }
  1332. void MiddleWare::pendingSetBank(int bank)
  1333. {
  1334. impl->bToU->write("/setbank", "c", bank);
  1335. }
  1336. void MiddleWare::pendingSetProgram(int part, int program)
  1337. {
  1338. impl->pending_load[part]++;
  1339. impl->bToU->write("/setprogram", "cc", part, program);
  1340. }
  1341. std::string MiddleWare::activeUrl(void)
  1342. {
  1343. return impl->last_url;
  1344. }
  1345. void MiddleWare::activeUrl(std::string u)
  1346. {
  1347. impl->last_url = u;
  1348. }
  1349. const SYNTH_T &MiddleWare::getSynth(void) const
  1350. {
  1351. return impl->synth;
  1352. }
  1353. const char* MiddleWare::getServerAddress(void) const
  1354. {
  1355. if(impl->server)
  1356. return lo_server_get_url(impl->server);
  1357. else
  1358. return "NULL";
  1359. }
  1360. const PresetsStore& MiddleWare::getPresetsStore() const
  1361. {
  1362. return impl->presetsstore;
  1363. }
  1364. PresetsStore& MiddleWare::getPresetsStore()
  1365. {
  1366. return impl->presetsstore;
  1367. }