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.

MiddleWare.cpp 47KB

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