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.

1710 lines
54KB

  1. /*
  2. ZynAddSubFX - a software synthesizer
  3. Master.cpp - It sends Midi Messages to Parts, receives samples from parts,
  4. process them with system/insertion effects and mix them
  5. Copyright (C) 2002-2005 Nasca Octavian Paul
  6. Author: Nasca Octavian Paul
  7. This program is free software; you can redistribute it and/or
  8. modify it under the terms of the GNU General Public License
  9. as published by the Free Software Foundation; either version 2
  10. of the License, or (at your option) any later version.
  11. */
  12. #include "Master.h"
  13. #include "Part.h"
  14. #include "zyn-version.h"
  15. #include "../Misc/Stereo.h"
  16. #include "../Misc/Util.h"
  17. #include "../Params/LFOParams.h"
  18. #include "../Effects/EffectMgr.h"
  19. #include "../DSP/FFTwrapper.h"
  20. #include "../Misc/Allocator.h"
  21. #include "../Containers/ScratchString.h"
  22. #include "../Nio/Nio.h"
  23. #include "PresetExtractor.h"
  24. #include <rtosc/ports.h>
  25. #include <rtosc/port-sugar.h>
  26. #include <rtosc/thread-link.h>
  27. #include <stdio.h>
  28. #include <sys/stat.h>
  29. #include <sys/types.h>
  30. #include <fstream>
  31. #include <iostream>
  32. #include <algorithm>
  33. #include <cmath>
  34. #include <atomic>
  35. #include <unistd.h>
  36. using namespace std;
  37. using namespace rtosc;
  38. namespace zyncarla {
  39. #define rObject Master
  40. static const Ports sysefxPort =
  41. {
  42. {"part#" STRINGIFY(NUM_MIDI_PARTS) "::i", rProp(parameter)
  43. rDoc("gain on part to sysefx routing"), 0,
  44. [](const char *m, RtData&d)
  45. {
  46. //we know that if we are here the location must
  47. //be ...Psysefxvol#N/part#M
  48. //and the number "N" is one or two digits at most
  49. // go backto the '/'
  50. const char* m_findslash = m + strlen(m),
  51. * loc_findslash = d.loc + strlen(d.loc);
  52. for(;*loc_findslash != '/'; --m_findslash, --loc_findslash)
  53. assert(*loc_findslash == *m_findslash);
  54. assert(m_findslash + 1 == m);
  55. const char *index_1 = loc_findslash-1;
  56. assert(isdigit(*index_1));
  57. if(isdigit(index_1[-1]))
  58. index_1--;
  59. int ind1 = atoi(index_1);
  60. //Now get the second index like normal
  61. while(!isdigit(*m)) m++;
  62. int ind2 = atoi(m);
  63. Master &mast = *(Master*)d.obj;
  64. if(rtosc_narguments(m)) {
  65. mast.setPsysefxvol(ind2, ind1, rtosc_argument(m,0).i);
  66. d.broadcast(d.loc, "i", mast.Psysefxvol[ind1][ind2]);
  67. } else
  68. d.reply(d.loc, "i", mast.Psysefxvol[ind1][ind2]);
  69. }}
  70. };
  71. static const Ports sysefsendto =
  72. {
  73. {"to#" STRINGIFY(NUM_SYS_EFX) "::i",
  74. rProp(parameter) rDoc("sysefx to sysefx routing gain"), 0, [](const char *m, RtData&d)
  75. {
  76. //same workaround as before
  77. //go backto the '/'
  78. const char* m_findslash = m + strlen(m),
  79. * loc_findslash = d.loc + strlen(d.loc);
  80. for(;*loc_findslash != '/'; --m_findslash, --loc_findslash)
  81. assert(*loc_findslash == *m_findslash);
  82. assert(m_findslash + 1 == m);
  83. const char *index_1 = loc_findslash-1;
  84. assert(isdigit(*index_1));
  85. if(isdigit(index_1[-1]))
  86. index_1--;
  87. int ind1 = atoi(index_1);
  88. //Now get the second index like normal
  89. while(!isdigit(*m)) m++;
  90. int ind2 = atoi(m);
  91. Master &master = *(Master*)d.obj;
  92. if(rtosc_narguments(m))
  93. master.setPsysefxsend(ind1, ind2, rtosc_argument(m,0).i);
  94. else
  95. d.reply(d.loc, "i", master.Psysefxsend[ind1][ind2]);
  96. }}
  97. };
  98. #define rBegin [](const char *msg, RtData &d) { rtosc::AutomationMgr &a = *(AutomationMgr*)d.obj
  99. #define rEnd }
  100. static int extract_num(const char *&msg)
  101. {
  102. while(*msg && !isdigit(*msg)) msg++;
  103. int num = atoi(msg);
  104. while(isdigit(*msg)) msg++;
  105. return num;
  106. }
  107. static int get_next_int(const char *msg)
  108. {
  109. return extract_num(msg);
  110. }
  111. static const Ports mapping_ports = {
  112. {"offset::f", rProp(parameter) rDefault(0) rShort("off") rLinear(-50, 50) rMap(unit, percent), 0,
  113. rBegin;
  114. int slot = d.idx[1];
  115. int param = d.idx[0];
  116. if(!strcmp("f",rtosc_argument_string(msg))) {
  117. a.setSlotSubOffset(slot, param, rtosc_argument(msg, 0).f);
  118. a.updateMapping(slot, param);
  119. d.broadcast(d.loc, "f", a.getSlotSubOffset(slot, param));
  120. } else
  121. d.reply(d.loc, "f", a.getSlotSubOffset(slot, param));
  122. rEnd},
  123. {"gain::f", rProp(parameter) rDefault(100) rShort("gain") rLinear(-200, 200) rMap(unit, percent), 0,
  124. rBegin;
  125. int slot = d.idx[1];
  126. int param = d.idx[0];
  127. if(!strcmp("f",rtosc_argument_string(msg))) {
  128. a.setSlotSubGain(slot, param, rtosc_argument(msg, 0).f);
  129. a.updateMapping(slot, param);
  130. d.broadcast(d.loc, "f", a.getSlotSubGain(slot, param));
  131. } else
  132. d.reply(d.loc, "f", a.getSlotSubGain(slot, param));
  133. rEnd},
  134. };
  135. static const Ports auto_param_ports = {
  136. {"used::T:F", rProp(parameter) rProp(read-only) rDoc("If automation is assigned to anything"), 0,
  137. rBegin;
  138. int slot = d.idx[1];
  139. int param = d.idx[0];
  140. d.reply(d.loc, a.slots[slot].automations[param].used ? "T" : "F");
  141. rEnd},
  142. {"active::T:F", rProp(parameter) rDoc("If automation is being actively used"), 0,
  143. rBegin;
  144. int slot = d.idx[1];
  145. int param = d.idx[0];
  146. if(rtosc_narguments(msg))
  147. a.slots[slot].automations[param].active = rtosc_argument(msg, 0).T;
  148. else
  149. d.reply(d.loc, a.slots[slot].automations[param].active ? "T" : "F");
  150. rEnd},
  151. {"path::s", rProp(parameter) rProp(read-only) rDoc("Path of parameter"), 0,
  152. rBegin;
  153. int slot = d.idx[1];
  154. int param = d.idx[0];
  155. d.reply(d.loc, "s", a.slots[slot].automations[param].param_path);
  156. rEnd},
  157. {"clear:", rDoc("Clear automation param"), 0,
  158. rBegin;
  159. int slot = d.idx[1];
  160. int param = d.idx[0];
  161. a.clearSlotSub(slot, param);
  162. rEnd},
  163. {"mapping/", 0, &mapping_ports,
  164. rBegin;
  165. (void) a;
  166. SNIP;
  167. mapping_ports.dispatch(msg, d);
  168. rEnd},
  169. //{"mapping", rDoc("Parameter mapping control"), 0,
  170. // rBegin;
  171. // int slot = d.idx[1];
  172. // int param = d.idx[0];
  173. // if(!strcmp("b", rtosc_argument_string(msg))) {
  174. // int len = rtosc_argument(msg, 0).b.len / sizeof(float);
  175. // float *data = (float*)rtosc_argument(msg, 0).b.data;
  176. // } else {
  177. // d.reply(d.loc, "b",
  178. // a.slots[slot].automations[param].map.npoints*sizeof(float),
  179. // a.slots[slot].automations[param].map.control_points);
  180. // }
  181. // rEnd},
  182. };
  183. static const Ports slot_ports = {
  184. //{"learn-binding:s", rDoc("Create binding for automation path with midi-learn"), 0,
  185. // rBegin;
  186. // (void) m;
  187. // //m->automate.createBinding(rtosc_argument(msg, 0).i,
  188. // // rtosc_argument(msg, 1).s,
  189. // // rtosc_argument(msg, 2).T);
  190. // rEnd},
  191. //{"create-binding:s", rDoc("Create binding for automation path"), 0,
  192. // rBegin;
  193. // m->automate.createBinding(rtosc_argument(msg, 0).i,
  194. // rtosc_argument(msg, 1).s,
  195. // rtosc_argument(msg, 2).T);
  196. // rEnd},
  197. {"value::f", rProp(no learn) rProp(parameter) rMap(default, 0.5) rLinear(0, 1) rDoc("Access current value in slot 'i' (0..1)"), 0,
  198. rBegin;
  199. int num = d.idx[0];
  200. if(!strcmp("f",rtosc_argument_string(msg))) {
  201. a.setSlot(num, rtosc_argument(msg, 0).f);
  202. d.broadcast(d.loc, "f", a.getSlot(num));
  203. } else
  204. d.reply(d.loc, "f", a.getSlot(num));
  205. rEnd},
  206. {"name::s", rProp(parameter) rDoc("Access name of automation slot"), 0,
  207. rBegin;
  208. int num = d.idx[0];
  209. if(!strcmp("s",rtosc_argument_string(msg))) {
  210. a.setName(num, rtosc_argument(msg, 0).s);
  211. d.broadcast(d.loc, "s", a.getName(num));
  212. } else
  213. d.reply(d.loc, "s", a.getName(num));
  214. rEnd},
  215. {"midi-cc::i", rProp(parameter) rMap(default, -1) rDoc("Access assigned midi CC slot") , 0,
  216. rBegin;
  217. int slot = d.idx[0];
  218. if(rtosc_narguments(msg))
  219. a.slots[slot].midi_cc = rtosc_argument(msg, 0).i;
  220. else
  221. d.reply(d.loc, "i", a.slots[slot].midi_cc);
  222. rEnd},
  223. {"active::T:F", rProp(parameter) rMap(default, F) rDoc("If Slot is enabled"), 0,
  224. rBegin;
  225. int slot = d.idx[0];
  226. if(rtosc_narguments(msg))
  227. a.slots[slot].active = rtosc_argument(msg, 0).T;
  228. else
  229. d.reply(d.loc, a.slots[slot].active ? "T" : "F");
  230. rEnd},
  231. {"learning::i", rProp(parameter) rMap(default, -1) rDoc("If slot is trying to find a midi learn binding"), 0,
  232. rBegin;
  233. int slot = d.idx[0];
  234. d.reply(d.loc, "i", a.slots[slot].learning);
  235. rEnd},
  236. {"clear:", rDoc("Clear automation slot"), 0,
  237. rBegin;
  238. int slot = d.idx[0];
  239. a.clearSlot(slot);
  240. rEnd},
  241. {"param#4/", rDoc("Info on individual param mappings"), &auto_param_ports,
  242. rBegin;
  243. (void)a;
  244. d.push_index(get_next_int(msg));
  245. SNIP;
  246. auto_param_ports.dispatch(msg, d);
  247. d.pop_index();
  248. rEnd},
  249. };
  250. static const Ports automate_ports = {
  251. {"active-slot::i", rProp(parameter) rMap(min, -1) rMap(max, 16) rDoc("Active Slot for macro learning"), 0,
  252. rBegin;
  253. if(!strcmp("i",rtosc_argument_string(msg))) {
  254. a.active_slot = rtosc_argument(msg, 0).i;
  255. d.broadcast(d.loc, "i", a.active_slot);
  256. } else
  257. d.reply(d.loc, "i", a.active_slot);
  258. rEnd},
  259. {"learn-binding-new-slot:s", rDoc("Learn a parameter assigned to a new slot"), 0,
  260. rBegin;
  261. int free_slot = a.free_slot();
  262. if(free_slot >= 0) {
  263. a.createBinding(free_slot, rtosc_argument(msg, 0).s, true);
  264. a.active_slot = free_slot;
  265. }
  266. rEnd},
  267. {"learn-binding-same-slot:s", rDoc("Learn a parameter appending to the active-slot"), 0,
  268. rBegin;
  269. if(a.active_slot >= 0)
  270. a.createBinding(a.active_slot, rtosc_argument(msg, 0).s, true);
  271. rEnd},
  272. // TODO: remove rNoWalk
  273. {"slot#16/", rNoWalk rDoc("Parameters of individual automation slots"), &slot_ports,
  274. rBegin;
  275. (void)a;
  276. d.push_index(get_next_int(msg));
  277. SNIP;
  278. slot_ports.dispatch(msg, d);
  279. d.pop_index();
  280. rEnd},
  281. {"clear", rDoc("Clear all automation slots"), 0,
  282. rBegin;
  283. for(int i=0; i<a.nslots; ++i)
  284. a.clearSlot(i);
  285. rEnd},
  286. {"load-blob:b", rProp(internal) rDoc("Load blob from middleware"), 0,
  287. rBegin;
  288. auto &b = **(rtosc::AutomationMgr **)rtosc_argument(msg, 0).b.data;
  289. //XXX this code should likely be in rtosc
  290. for(int i=0; i<a.nslots; ++i) {
  291. auto &slota = a.slots[i];
  292. auto &slotb = b.slots[i];
  293. std::swap(slota.learning, slotb.learning);
  294. std::swap(slota.midi_cc, slotb.midi_cc);
  295. std::swap(slota.used, slotb.used);
  296. std::swap(slota.active, slotb.active);
  297. for(int j=0; j<a.per_slot; ++j) {
  298. auto &aa = slota.automations[j];
  299. auto &ab = slotb.automations[j];
  300. std::swap(aa.used, ab.used);
  301. std::swap(aa.active, ab.active);
  302. std::swap(aa.param_path, ab.param_path);
  303. std::swap(aa.param_min, ab.param_min);
  304. std::swap(aa.param_max, ab.param_max);
  305. std::swap(aa.param_step, ab.param_step);
  306. std::swap(aa.param_type, ab.param_type);
  307. std::swap(aa.map.offset, ab.map.offset);
  308. std::swap(aa.map.gain, ab.map.gain);
  309. std::swap(aa.map.upoints, ab.map.upoints);
  310. for(int k=0; k<aa.map.npoints; ++k)
  311. std::swap(aa.map.control_points[k], ab.map.control_points[k]);
  312. }
  313. }
  314. rEnd},
  315. };
  316. #undef rBegin
  317. #undef rEnd
  318. #define rBegin [](const char *msg, RtData &d) { Master *m = (Master*)d.obj
  319. #define rEnd }
  320. static const Ports watchPorts = {
  321. {"add:s", rDoc("Add synthesis state to watch"), 0,
  322. rBegin;
  323. m->watcher.add_watch(rtosc_argument(msg,0).s);
  324. rEnd},
  325. };
  326. extern const Ports bankPorts;
  327. static const Ports master_ports = {
  328. rString(last_xmz, XMZ_PATH_MAX, "File name for last name loaded if any."),
  329. rRecursp(part, 16, "Part"),//NUM_MIDI_PARTS
  330. rRecursp(sysefx, 4, "System Effect"),//NUM_SYS_EFX
  331. rRecursp(insefx, 8, "Insertion Effect"),//NUM_INS_EFX
  332. rRecur(microtonal, "Microtonal Mapping Functionality"),
  333. rRecur(ctl, "Controller"),
  334. rArrayOption(Pinsparts, NUM_INS_EFX, rOpt(-2, Master), rOpt(-1, Off),
  335. rOptions(Part1, Part2, Part3, Part4, Part5, Part6,
  336. Part7, Part8, Part9, Part10, Part11, Part12,
  337. Part13, Part14, Part15, Part16) rDefault(Off),
  338. "Part to insert part onto"),
  339. {"Pkeyshift::i", rShort("key shift") rProp(parameter) rLinear(0,127)
  340. rDefault(64) rDoc("Global Key Shift"), 0, [](const char *m, RtData&d) {
  341. if(rtosc_narguments(m)==0) {
  342. d.reply(d.loc, "i", ((Master*)d.obj)->Pkeyshift);
  343. } else if(rtosc_narguments(m)==1 && rtosc_type(m,0)=='i') {
  344. ((Master*)d.obj)->setPkeyshift(limit<char>(rtosc_argument(m,0).i,0,127));
  345. d.broadcast(d.loc, "i", ((Master*)d.obj)->Pkeyshift);}}},
  346. {"echo", rDoc("Hidden port to echo messages"), 0, [](const char *m, RtData&d) {
  347. d.reply(m-1);}},
  348. {"get-vu:", rDoc("Grab VU Data"), 0, [](const char *, RtData &d) {
  349. Master *m = (Master*)d.obj;
  350. d.reply("/vu-meter", "bb", sizeof(m->vu), &m->vu, sizeof(float)*NUM_MIDI_PARTS, m->vuoutpeakpart);}},
  351. {"vu-meter:", rDoc("Grab VU Data"), 0, [](const char *, RtData &d) {
  352. Master *m = (Master*)d.obj;
  353. char types[6+NUM_MIDI_PARTS+1] = {0};
  354. rtosc_arg_t args[6+NUM_MIDI_PARTS+1];
  355. for(int i=0; i<6+NUM_MIDI_PARTS; ++i)
  356. types[i] = 'f';
  357. args[0].f = m->vu.outpeakl;
  358. args[1].f = m->vu.outpeakr;
  359. args[2].f = m->vu.maxoutpeakl;
  360. args[3].f = m->vu.maxoutpeakr;
  361. args[4].f = m->vu.rmspeakl;
  362. args[5].f = m->vu.rmspeakr;
  363. for(int i=0; i<NUM_MIDI_PARTS; ++i)
  364. args[6+i].f = m->vuoutpeakpart[i];
  365. d.replyArray("/vu-meter", types, args);}},
  366. {"reset-vu:", rDoc("Grab VU Data"), 0, [](const char *, RtData &d) {
  367. Master *m = (Master*)d.obj;
  368. m->vuresetpeaks();}},
  369. {"load-part:ib", rProp(internal) rDoc("Load Part From Middleware"), 0, [](const char *msg, RtData &d) {
  370. Master *m = (Master*)d.obj;
  371. Part *p = *(Part**)rtosc_argument(msg, 1).b.data;
  372. int i = rtosc_argument(msg, 0).i;
  373. m->part[i]->cloneTraits(*p);
  374. m->part[i]->kill_rt();
  375. d.reply("/free", "sb", "Part", sizeof(void*), &m->part[i]);
  376. m->part[i] = p;
  377. p->initialize_rt();
  378. for(int i=0; i<128; ++i)
  379. m->activeNotes[i] = 0;
  380. }},
  381. {"active_keys:", rProp("Obtain a list of active notes"), 0,
  382. rBegin;
  383. char keys[129] = {0};
  384. for(int i=0; i<128; ++i)
  385. keys[i] = m->activeNotes[i] ? 'T' : 'F';
  386. d.broadcast(d.loc, keys);
  387. rEnd},
  388. {"Pvolume::i", rShort("volume") rProp(parameter) rLinear(0,127)
  389. rDefault(80) rDoc("Master Volume"), 0,
  390. [](const char *m, rtosc::RtData &d) {
  391. if(rtosc_narguments(m)==0) {
  392. d.reply(d.loc, "i", ((Master*)d.obj)->Pvolume);
  393. } else if(rtosc_narguments(m)==1 && rtosc_type(m,0)=='i') {
  394. ((Master*)d.obj)->setPvolume(limit<char>(rtosc_argument(m,0).i,0,127));
  395. d.broadcast(d.loc, "i", ((Master*)d.obj)->Pvolume);}}},
  396. {"volume::i", rShort("volume") rProp(parameter) rLinear(0,127)
  397. rDefault(80) rDoc("Master Volume"), 0,
  398. [](const char *m, rtosc::RtData &d) {
  399. if(rtosc_narguments(m)==0) {
  400. d.reply(d.loc, "i", ((Master*)d.obj)->Pvolume);
  401. } else if(rtosc_narguments(m)==1 && rtosc_type(m,0)=='i') {
  402. ((Master*)d.obj)->setPvolume(limit<char>(rtosc_argument(m,0).i,0,127));
  403. d.broadcast(d.loc, "i", ((Master*)d.obj)->Pvolume);}}},
  404. {"Psysefxvol#" STRINGIFY(NUM_SYS_EFX) "/::i", 0, &sysefxPort,
  405. [](const char *msg, rtosc::RtData &d) {
  406. SNIP;
  407. sysefxPort.dispatch(msg, d);
  408. }},
  409. {"sysefxfrom#" STRINGIFY(NUM_SYS_EFX) "/", rDoc("Routing Between System Effects"), &sysefsendto,
  410. [](const char *msg, RtData&d) {
  411. SNIP;
  412. sysefsendto.dispatch(msg, d);
  413. }},
  414. {"noteOn:iii", rDoc("Noteon Event"), 0,
  415. [](const char *m,RtData &d){
  416. Master *M = (Master*)d.obj;
  417. M->noteOn(rtosc_argument(m,0).i,rtosc_argument(m,1).i,rtosc_argument(m,2).i);}},
  418. {"noteOff:ii", rDoc("Noteoff Event"), 0,
  419. [](const char *m,RtData &d){
  420. Master *M = (Master*)d.obj;
  421. M->noteOff(rtosc_argument(m,0).i,rtosc_argument(m,1).i);}},
  422. {"virtual_midi_cc:iii", rDoc("MIDI CC Event"), 0,
  423. [](const char *m,RtData &d){
  424. Master *M = (Master*)d.obj;
  425. M->setController(rtosc_argument(m,0).i,rtosc_argument(m,1).i,rtosc_argument(m,2).i);}},
  426. {"setController:iii", rDoc("MIDI CC Event"), 0,
  427. [](const char *m,RtData &d){
  428. Master *M = (Master*)d.obj;
  429. M->setController(rtosc_argument(m,0).i,rtosc_argument(m,1).i,rtosc_argument(m,2).i);}},
  430. {"Panic:", rDoc("Stop all sound"), 0,
  431. [](const char *, RtData &d) {
  432. Master &M = *(Master*)d.obj;
  433. M.ShutUp();
  434. }},
  435. {"freeze_state:", rProp(internal) rDoc("Disable OSC event handling\n"
  436. "This sets up a read-only mode from which it's safe for another"
  437. " thread to save parameters"), 0,
  438. [](const char *,RtData &d) {
  439. Master *M = (Master*)d.obj;
  440. std::atomic_thread_fence(std::memory_order_release);
  441. M->frozenState = true;
  442. d.reply("/state_frozen", "");}},
  443. {"thaw_state:", rProp(internal) rDoc("Resume handling OSC messages\n"
  444. "See /freeze_state for more information"), 0,
  445. [](const char *,RtData &d) {
  446. Master *M = (Master*)d.obj;
  447. M->frozenState = false;}},
  448. {"automate/", rDoc("MIDI Learn/Plugin Automation support"), &automate_ports,
  449. [](const char *msg, RtData &d) {
  450. SNIP;
  451. d.obj = (void*)&((Master*)d.obj)->automate;
  452. automate_ports.dispatch(msg, d);
  453. }},
  454. {"close-ui:", rDoc("Request to close any connection named \"GUI\""), 0,
  455. [](const char *, RtData &d) {
  456. d.reply("/close-ui", "");}},
  457. {"add-rt-memory:bi", rProp(internal) rDoc("Add Additional Memory To RT MemPool"), 0,
  458. [](const char *msg, RtData &d)
  459. {
  460. Master &m = *(Master*)d.obj;
  461. char *mem = *(char**)rtosc_argument(msg, 0).b.data;
  462. int i = rtosc_argument(msg, 1).i;
  463. m.memory->addMemory(mem, i);
  464. m.pendingMemory = false;
  465. }},
  466. {"samplerate:", rMap(unit, Hz) rDoc("Get synthesizer sample rate"), 0, [](const char *, RtData &d) {
  467. Master &m = *(Master*)d.obj;
  468. d.reply("/samplerate", "f", m.synth.samplerate_f);
  469. }},
  470. {"oscilsize:", rDoc("Get synthesizer oscillator size"), 0, [](const char *, RtData &d) {
  471. Master &m = *(Master*)d.obj;
  472. d.reply("/oscilsize", "f", m.synth.oscilsize_f);
  473. d.reply("/oscilsize", "i", m.synth.oscilsize);
  474. }},
  475. {"undo_pause:",rProp(internal) rDoc("pause undo event recording"),0,
  476. [](const char *, rtosc::RtData &d) {d.reply("/undo_pause", "");}},
  477. {"undo_resume:",rProp(internal) rDoc("resume undo event recording"),0,
  478. [](const char *, rtosc::RtData &d) {d.reply("/undo_resume", "");}},
  479. {"config/", rNoWalk rDoc("Top Level Application Configuration Parameters"),
  480. &Config::ports, [](const char *, rtosc::RtData &d){d.forward();}},
  481. {"presets/", rDoc("Parameter Presets"), &preset_ports, rBOIL_BEGIN
  482. SNIP
  483. preset_ports.dispatch(msg, data);
  484. rBOIL_END},
  485. {"HDDRecorder/preparefile:s", rDoc("Init WAV file"), 0, [](const char *msg, RtData &d) {
  486. Master *m = (Master*)d.obj;
  487. m->HDDRecorder.preparefile(rtosc_argument(msg, 0).s, 1);}},
  488. {"HDDRecorder/start:", rDoc("Start recording"), 0, [](const char *, RtData &d) {
  489. Master *m = (Master*)d.obj;
  490. m->HDDRecorder.start();}},
  491. {"HDDRecorder/stop:", rDoc("Stop recording"), 0, [](const char *, RtData &d) {
  492. Master *m = (Master*)d.obj;
  493. m->HDDRecorder.stop();}},
  494. {"HDDRecorder/pause:", rDoc("Pause recording"), 0, [](const char *, RtData &d) {
  495. Master *m = (Master*)d.obj;
  496. m->HDDRecorder.pause();}},
  497. {"watch/", rDoc("Interface to grab out live synthesis state"), &watchPorts,
  498. rBOIL_BEGIN;
  499. SNIP;
  500. watchPorts.dispatch(msg, data);
  501. rBOIL_END},
  502. {"bank/", rDoc("Controls for instrument banks"), &bankPorts,
  503. [](const char*,RtData&) {}},
  504. {"learn:s", rProp(depricated) rDoc("MIDI Learn"), 0,
  505. rBegin;
  506. int free_slot = m->automate.free_slot();
  507. if(free_slot >= 0) {
  508. m->automate.createBinding(free_slot, rtosc_argument(msg, 0).s, true);
  509. m->automate.active_slot = free_slot;
  510. }
  511. rEnd},
  512. };
  513. #undef rBegin
  514. #undef rEnd
  515. const Ports &Master::ports = master_ports;
  516. class DataObj:public rtosc::RtData
  517. {
  518. public:
  519. DataObj(char *loc_, size_t loc_size_, void *obj_, rtosc::ThreadLink *bToU_)
  520. {
  521. memset(loc_, 0, loc_size_);
  522. loc = loc_;
  523. loc_size = loc_size_;
  524. obj = obj_;
  525. bToU = bToU_;
  526. forwarded = false;
  527. }
  528. virtual void replyArray(const char *path, const char *args, rtosc_arg_t *vals) override
  529. {
  530. char *buffer = bToU->buffer();
  531. rtosc_amessage(buffer,bToU->buffer_size(),path,args,vals);
  532. reply(buffer);
  533. }
  534. virtual void reply(const char *path, const char *args, ...) override
  535. {
  536. va_list va;
  537. va_start(va,args);
  538. char *buffer = bToU->buffer();
  539. rtosc_vmessage(buffer,bToU->buffer_size(),path,args,va);
  540. reply(buffer);
  541. va_end(va);
  542. }
  543. virtual void reply(const char *msg) override
  544. {
  545. if(rtosc_message_length(msg, -1) == 0)
  546. fprintf(stderr, "Warning: Invalid Rtosc message '%s'\n", msg);
  547. bToU->raw_write(msg);
  548. }
  549. virtual void broadcast(const char *path, const char *args, ...) override{
  550. va_list va;
  551. va_start(va,args);
  552. reply("/broadcast", "");
  553. char *buffer = bToU->buffer();
  554. rtosc_vmessage(buffer,bToU->buffer_size(),path,args,va);
  555. reply(buffer);
  556. va_end(va);
  557. }
  558. virtual void broadcast(const char *msg) override
  559. {
  560. reply("/broadcast", "");
  561. reply(msg);
  562. }
  563. virtual void forward(const char *reason) override
  564. {
  565. assert(message);
  566. reply("/forward", "");
  567. printf("forwarding '%s'\n", message);
  568. forwarded = true;
  569. }
  570. bool forwarded;
  571. private:
  572. rtosc::ThreadLink *bToU;
  573. };
  574. vuData::vuData(void)
  575. :outpeakl(0.0f), outpeakr(0.0f), maxoutpeakl(0.0f), maxoutpeakr(0.0f),
  576. rmspeakl(0.0f), rmspeakr(0.0f), clipped(0)
  577. {}
  578. void Master::saveAutomation(XMLwrapper &xml, const rtosc::AutomationMgr &midi)
  579. {
  580. xml.beginbranch("automation");
  581. {
  582. XmlNode metadata("mgr-info");
  583. metadata["nslots"] = to_s(midi.nslots);
  584. metadata["nautomations"] = to_s(midi.per_slot);
  585. metadata["ncontrol"] = to_s(midi.slots[0].automations[0].map.npoints);
  586. xml.add(metadata);
  587. for(int i=0; i<midi.nslots; ++i) {
  588. const auto &slot = midi.slots[i];
  589. if(!slot.used)
  590. continue;
  591. xml.beginbranch("slot", i);
  592. XmlNode params("params");
  593. params["midi-cc"] = to_s(slot.midi_cc);
  594. xml.add(params);
  595. for(int j=0; j<midi.per_slot; ++j) {
  596. const auto &au = slot.automations[j];
  597. if(!au.used)
  598. continue;
  599. xml.beginbranch("automation", j);
  600. XmlNode automation("params");
  601. automation["path"] = au.param_path;
  602. XmlNode mapping("mapping");
  603. mapping["gain"] = to_s(au.map.gain);
  604. mapping["offset"] = to_s(au.map.offset);
  605. xml.add(automation);
  606. xml.add(mapping);
  607. xml.endbranch();
  608. }
  609. xml.endbranch();
  610. }
  611. }
  612. xml.endbranch();
  613. }
  614. void Master::loadAutomation(XMLwrapper &xml, rtosc::AutomationMgr &midi)
  615. {
  616. if(xml.enterbranch("automation")) {
  617. for(int i=0; i<midi.nslots; ++i) {
  618. auto &slot = midi.slots[i];
  619. if(xml.enterbranch("slot", i)) {
  620. for(int j=0; j<midi.per_slot; ++j) {
  621. if(xml.enterbranch("automation", j)) {
  622. float gain = 1.0;
  623. float offset = 0.0;
  624. std::string path = "";
  625. for(auto node:xml.getBranch()) {
  626. if(node.name == "params")
  627. path = node["path"];
  628. else if(node.name == "mapping") {
  629. gain = atof(node["gain"].c_str());
  630. offset = atof(node["offset"].c_str());
  631. }
  632. }
  633. printf("createBinding(%d, %s, false)\n", i, path.c_str());
  634. midi.createBinding(i, path.c_str(), false);
  635. midi.setSlotSubGain(i, j, gain);
  636. midi.setSlotSubOffset(i, j, offset);
  637. xml.exitbranch();
  638. }
  639. }
  640. for(auto node:xml.getBranch())
  641. if(node.name == "params")
  642. slot.midi_cc = atoi(node["midi-cc"].c_str());
  643. xml.exitbranch();
  644. }
  645. }
  646. xml.exitbranch();
  647. }
  648. }
  649. Master::Master(const SYNTH_T &synth_, Config* config)
  650. :HDDRecorder(synth_), time(synth_), ctl(synth_, &time),
  651. microtonal(config->cfg.GzipCompression), bank(config),
  652. automate(16,4,8),
  653. frozenState(false), pendingMemory(false),
  654. synth(synth_), gzip_compression(config->cfg.GzipCompression)
  655. {
  656. bToU = NULL;
  657. uToB = NULL;
  658. //Setup MIDI Learn
  659. automate.set_ports(master_ports);
  660. automate.set_instance(this);
  661. //midi.frontend = [this](const char *msg) {bToU->raw_write(msg);};
  662. automate.backend = [this](const char *msg) {applyOscEvent(msg);};
  663. memory = new AllocatorClass();
  664. swaplr = 0;
  665. off = 0;
  666. smps = 0;
  667. bufl = new float[synth.buffersize];
  668. bufr = new float[synth.buffersize];
  669. last_xmz[0] = 0;
  670. fft = new FFTwrapper(synth.oscilsize);
  671. shutup = 0;
  672. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  673. vuoutpeakpart[npart] = 1e-9;
  674. fakepeakpart[npart] = 0;
  675. }
  676. ScratchString ss;
  677. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  678. part[npart] = new Part(*memory, synth, time, config->cfg.GzipCompression,
  679. config->cfg.Interpolation, &microtonal, fft, &watcher,
  680. (ss+"/part"+npart+"/").c_str);
  681. //Insertion Effects init
  682. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx)
  683. insefx[nefx] = new EffectMgr(*memory, synth, 1, &time);
  684. //System Effects init
  685. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx)
  686. sysefx[nefx] = new EffectMgr(*memory, synth, 0, &time);
  687. //Note Visualization
  688. for(int i=0; i<128; ++i)
  689. activeNotes[i] = 0;
  690. defaults();
  691. mastercb = 0;
  692. mastercb_ptr = 0;
  693. }
  694. void Master::applyOscEvent(const char *msg)
  695. {
  696. char loc_buf[1024];
  697. DataObj d{loc_buf, 1024, this, bToU};
  698. memset(loc_buf, 0, sizeof(loc_buf));
  699. d.matches = 0;
  700. if(strcmp(msg, "/get-vu") && false) {
  701. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 5 + 30, 0 + 40);
  702. fprintf(stdout, "backend[*]: '%s'<%s>\n", msg,
  703. rtosc_argument_string(msg));
  704. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 7 + 30, 0 + 40);
  705. }
  706. ports.dispatch(msg, d, true);
  707. if(d.matches == 0 && !d.forwarded)
  708. fprintf(stderr, "Unknown path '%s:%s'\n", msg, rtosc_argument_string(msg));
  709. if(d.forwarded)
  710. bToU->raw_write(msg);
  711. }
  712. void Master::defaults()
  713. {
  714. volume = 1.0f;
  715. setPvolume(80);
  716. setPkeyshift(64);
  717. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  718. part[npart]->defaults();
  719. part[npart]->partno = npart % NUM_MIDI_CHANNELS;
  720. part[npart]->Prcvchn = npart % NUM_MIDI_CHANNELS;
  721. }
  722. partonoff(0, 1); //enable the first part
  723. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx) {
  724. insefx[nefx]->defaults();
  725. Pinsparts[nefx] = -1;
  726. }
  727. //System Effects init
  728. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx) {
  729. sysefx[nefx]->defaults();
  730. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  731. setPsysefxvol(npart, nefx, 0);
  732. for(int nefxto = 0; nefxto < NUM_SYS_EFX; ++nefxto)
  733. setPsysefxsend(nefx, nefxto, 0);
  734. }
  735. microtonal.defaults();
  736. ShutUp();
  737. }
  738. /*
  739. * Note On Messages (velocity=0 for NoteOff)
  740. */
  741. void Master::noteOn(char chan, char note, char velocity)
  742. {
  743. if(velocity) {
  744. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  745. if(chan == part[npart]->Prcvchn) {
  746. fakepeakpart[npart] = velocity * 2;
  747. if(part[npart]->Penabled)
  748. part[npart]->NoteOn(note, velocity, keyshift);
  749. }
  750. }
  751. activeNotes[(int)note] = 1;
  752. }
  753. else
  754. this->noteOff(chan, note);
  755. HDDRecorder.triggernow();
  756. }
  757. /*
  758. * Note Off Messages
  759. */
  760. void Master::noteOff(char chan, char note)
  761. {
  762. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  763. if((chan == part[npart]->Prcvchn) && part[npart]->Penabled)
  764. part[npart]->NoteOff(note);
  765. activeNotes[(int)note] = 0;
  766. }
  767. /*
  768. * Pressure Messages (velocity=0 for NoteOff)
  769. */
  770. void Master::polyphonicAftertouch(char chan, char note, char velocity)
  771. {
  772. if(velocity) {
  773. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  774. if(chan == part[npart]->Prcvchn)
  775. if(part[npart]->Penabled)
  776. part[npart]->PolyphonicAftertouch(note, velocity, keyshift);
  777. }
  778. else
  779. this->noteOff(chan, note);
  780. }
  781. /*
  782. * Controllers
  783. */
  784. void Master::setController(char chan, int type, int par)
  785. {
  786. if(frozenState)
  787. return;
  788. automate.handleMidi(chan, type, par);
  789. if((type == C_dataentryhi) || (type == C_dataentrylo)
  790. || (type == C_nrpnhi) || (type == C_nrpnlo)) { //Process RPN and NRPN by the Master (ignore the chan)
  791. ctl.setparameternumber(type, par);
  792. int parhi = -1, parlo = -1, valhi = -1, vallo = -1;
  793. if(ctl.getnrpn(&parhi, &parlo, &valhi, &vallo) == 0) { //this is NRPN
  794. switch(parhi) {
  795. case 0x04: //System Effects
  796. if(parlo < NUM_SYS_EFX)
  797. sysefx[parlo]->seteffectparrt(valhi, vallo);
  798. break;
  799. case 0x08: //Insertion Effects
  800. if(parlo < NUM_INS_EFX)
  801. insefx[parlo]->seteffectparrt(valhi, vallo);
  802. break;
  803. }
  804. }
  805. } else { //other controllers
  806. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) //Send the controller to all part assigned to the channel
  807. if((chan == part[npart]->Prcvchn) && (part[npart]->Penabled != 0))
  808. part[npart]->SetController(type, par);
  809. if(type == C_allsoundsoff) { //cleanup insertion/system FX
  810. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx)
  811. sysefx[nefx]->cleanup();
  812. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx)
  813. insefx[nefx]->cleanup();
  814. }
  815. }
  816. }
  817. void Master::vuUpdate(const float *outl, const float *outr)
  818. {
  819. //Peak computation (for vumeters)
  820. vu.outpeakl = 1e-12;
  821. vu.outpeakr = 1e-12;
  822. for(int i = 0; i < synth.buffersize; ++i) {
  823. if(fabs(outl[i]) > vu.outpeakl)
  824. vu.outpeakl = fabs(outl[i]);
  825. if(fabs(outr[i]) > vu.outpeakr)
  826. vu.outpeakr = fabs(outr[i]);
  827. }
  828. if((vu.outpeakl > 1.0f) || (vu.outpeakr > 1.0f))
  829. vu.clipped = 1;
  830. if(vu.maxoutpeakl < vu.outpeakl)
  831. vu.maxoutpeakl = vu.outpeakl;
  832. if(vu.maxoutpeakr < vu.outpeakr)
  833. vu.maxoutpeakr = vu.outpeakr;
  834. //RMS Peak computation (for vumeters)
  835. vu.rmspeakl = 1e-12;
  836. vu.rmspeakr = 1e-12;
  837. for(int i = 0; i < synth.buffersize; ++i) {
  838. vu.rmspeakl += outl[i] * outl[i];
  839. vu.rmspeakr += outr[i] * outr[i];
  840. }
  841. vu.rmspeakl = sqrt(vu.rmspeakl / synth.buffersize_f);
  842. vu.rmspeakr = sqrt(vu.rmspeakr / synth.buffersize_f);
  843. //Part Peak computation (for Part vumeters or fake part vumeters)
  844. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  845. vuoutpeakpart[npart] = 1.0e-12f;
  846. if(part[npart]->Penabled != 0) {
  847. float *outl = part[npart]->partoutl,
  848. *outr = part[npart]->partoutr;
  849. for(int i = 0; i < synth.buffersize; ++i) {
  850. float tmp = fabs(outl[i] + outr[i]);
  851. if(tmp > vuoutpeakpart[npart])
  852. vuoutpeakpart[npart] = tmp;
  853. }
  854. vuoutpeakpart[npart] *= volume;
  855. }
  856. else
  857. if(fakepeakpart[npart] > 1)
  858. fakepeakpart[npart]--;
  859. }
  860. }
  861. /*
  862. * Enable/Disable a part
  863. */
  864. void Master::partonoff(int npart, int what)
  865. {
  866. if(npart >= NUM_MIDI_PARTS)
  867. return;
  868. if(what == 0) { //disable part
  869. fakepeakpart[npart] = 0;
  870. part[npart]->Penabled = 0;
  871. part[npart]->cleanup();
  872. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx) {
  873. if(Pinsparts[nefx] == npart)
  874. insefx[nefx]->cleanup();
  875. }
  876. }
  877. else { //enabled
  878. part[npart]->Penabled = 1;
  879. fakepeakpart[npart] = 0;
  880. }
  881. }
  882. void Master::setMasterChangedCallback(void(*cb)(void*,Master*), void *ptr)
  883. {
  884. mastercb = cb;
  885. mastercb_ptr = ptr;
  886. }
  887. #if 0
  888. template <class T>
  889. struct def_skip
  890. {
  891. static void skip(const char*& argptr) { argptr += sizeof(T); }
  892. };
  893. template <class T>
  894. struct str_skip
  895. {
  896. static void skip(const char*& argptr) { while(argptr++); /*TODO: 4 padding */ }
  897. };
  898. template<class T, class Display = T, template<class TMP> class SkipsizeFunc = def_skip>
  899. void _dump_prim_arg(const char*& argptr, std::ostream& os)
  900. {
  901. os << ' ' << (Display)*(const T*)argptr;
  902. SkipsizeFunc<T>::skip(argptr);
  903. }
  904. void dump_msg(const char* ptr, std::ostream& os = std::cerr)
  905. {
  906. assert(*ptr == '/');
  907. os << ptr;
  908. while(*++ptr) ; // skip address
  909. while(!*++ptr) ; // skip 0s
  910. assert(*ptr == ',');
  911. os << ' ' << (ptr + 1);
  912. const char* argptr = ptr;
  913. while(*++argptr) ; // skip type string
  914. while(!*++argptr) ; // skip 0s
  915. char c;
  916. while((c = *++ptr))
  917. {
  918. switch(c)
  919. {
  920. case 'i':
  921. _dump_prim_arg<int32_t>(argptr, os); break;
  922. case 'c':
  923. _dump_prim_arg<int32_t, char>(argptr, os); break;
  924. // case 's':
  925. // _dump_prim_arg<char, const char*>(argptr, os); break;
  926. default:
  927. exit(1);
  928. }
  929. }
  930. }
  931. #endif
  932. int msg_id=0;
  933. bool Master::runOSC(float *outl, float *outr, bool offline)
  934. {
  935. //Handle user events TODO move me to a proper location
  936. char loc_buf[1024];
  937. DataObj d{loc_buf, 1024, this, bToU};
  938. memset(loc_buf, 0, sizeof(loc_buf));
  939. int events = 0;
  940. while(uToB && uToB->hasNext() && events < 100) {
  941. const char *msg = uToB->read();
  942. if(!strcmp(msg, "/load-master")) {
  943. Master *this_master = this;
  944. Master *new_master = *(Master**)rtosc_argument(msg, 0).b.data;
  945. if(!offline)
  946. new_master->AudioOut(outl, outr);
  947. Nio::masterSwap(new_master);
  948. if (mastercb)
  949. mastercb(mastercb_ptr, new_master);
  950. bToU->write("/free", "sb", "Master", sizeof(Master*), &this_master);
  951. return false;
  952. }
  953. //XXX yes, this is not realtime safe, but it is useful...
  954. if(strcmp(msg, "/get-vu") && false) {
  955. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 5 + 30, 0 + 40);
  956. fprintf(stdout, "backend[%d]: '%s'<%s>\n", msg_id++, msg,
  957. rtosc_argument_string(msg));
  958. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 7 + 30, 0 + 40);
  959. }
  960. ports.dispatch(msg, d, true);
  961. events++;
  962. if(!d.matches) {
  963. //workaround for requesting voice status
  964. int a=0, b=0, c=0;
  965. char e=0;
  966. if(4 == sscanf(msg, "/part%d/kit%d/adpars/VoicePar%d/Enable%c", &a, &b, &c, &e)) {
  967. d.reply(msg, "F");
  968. d.matches++;
  969. }
  970. }
  971. if(!d.matches) {// && !ports.apropos(msg)) {
  972. fprintf(stderr, "%c[%d;%d;%dm", 0x1B, 1, 7 + 30, 0 + 40);
  973. fprintf(stderr, "Unknown address<BACKEND:%s> '%s:%s'\n",
  974. offline ? "offline" : "online",
  975. uToB->peak(),
  976. rtosc_argument_string(uToB->peak()));
  977. fprintf(stderr, "%c[%d;%d;%dm", 0x1B, 0, 7 + 30, 0 + 40);
  978. }
  979. }
  980. if(automate.damaged) {
  981. d.broadcast("/damage", "s", "/automate/");
  982. automate.damaged = 0;
  983. }
  984. if(events>1 && false)
  985. fprintf(stderr, "backend: %d events per cycle\n",events);
  986. return true;
  987. }
  988. /*
  989. * Master audio out (the final sound)
  990. */
  991. bool Master::AudioOut(float *outr, float *outl)
  992. {
  993. //Danger Limits
  994. if(memory->lowMemory(2,1024*1024))
  995. printf("QUITE LOW MEMORY IN THE RT POOL BE PREPARED FOR WEIRD BEHAVIOR!!\n");
  996. //Normal Limits
  997. if(!pendingMemory && memory->lowMemory(4,1024*1024)) {
  998. printf("Requesting more memory\n");
  999. bToU->write("/request-memory", "");
  1000. pendingMemory = true;
  1001. }
  1002. //work through events
  1003. if(!runOSC(outl, outr, false))
  1004. return false;
  1005. //Handle watch points
  1006. if(bToU)
  1007. watcher.write_back = bToU;
  1008. watcher.tick();
  1009. //Swaps the Left channel with Right Channel
  1010. if(swaplr)
  1011. swap(outl, outr);
  1012. //clean up the output samples (should not be needed?)
  1013. memset(outl, 0, synth.bufferbytes);
  1014. memset(outr, 0, synth.bufferbytes);
  1015. //Compute part samples and store them part[npart]->partoutl,partoutr
  1016. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  1017. if(part[npart]->Penabled)
  1018. part[npart]->ComputePartSmps();
  1019. //Insertion effects
  1020. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx)
  1021. if(Pinsparts[nefx] >= 0) {
  1022. int efxpart = Pinsparts[nefx];
  1023. if(part[efxpart]->Penabled)
  1024. insefx[nefx]->out(part[efxpart]->partoutl,
  1025. part[efxpart]->partoutr);
  1026. }
  1027. //Apply the part volumes and pannings (after insertion effects)
  1028. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  1029. if(!part[npart]->Penabled)
  1030. continue;
  1031. Stereo<float> newvol(part[npart]->volume),
  1032. oldvol(part[npart]->oldvolumel,
  1033. part[npart]->oldvolumer);
  1034. float pan = part[npart]->panning;
  1035. if(pan < 0.5f)
  1036. newvol.l *= pan * 2.0f;
  1037. else
  1038. newvol.r *= (1.0f - pan) * 2.0f;
  1039. //if(npart==0)
  1040. //printf("[%d]vol = %f->%f\n", npart, oldvol.l, newvol.l);
  1041. //the volume or the panning has changed and needs interpolation
  1042. if(ABOVE_AMPLITUDE_THRESHOLD(oldvol.l, newvol.l)
  1043. || ABOVE_AMPLITUDE_THRESHOLD(oldvol.r, newvol.r)) {
  1044. for(int i = 0; i < synth.buffersize; ++i) {
  1045. Stereo<float> vol(INTERPOLATE_AMPLITUDE(oldvol.l, newvol.l,
  1046. i, synth.buffersize),
  1047. INTERPOLATE_AMPLITUDE(oldvol.r, newvol.r,
  1048. i, synth.buffersize));
  1049. part[npart]->partoutl[i] *= vol.l;
  1050. part[npart]->partoutr[i] *= vol.r;
  1051. }
  1052. part[npart]->oldvolumel = newvol.l;
  1053. part[npart]->oldvolumer = newvol.r;
  1054. }
  1055. else {
  1056. for(int i = 0; i < synth.buffersize; ++i) { //the volume did not changed
  1057. part[npart]->partoutl[i] *= newvol.l;
  1058. part[npart]->partoutr[i] *= newvol.r;
  1059. }
  1060. }
  1061. }
  1062. //System effects
  1063. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx) {
  1064. if(sysefx[nefx]->geteffect() == 0)
  1065. continue; //the effect is disabled
  1066. float tmpmixl[synth.buffersize];
  1067. float tmpmixr[synth.buffersize];
  1068. //Clean up the samples used by the system effects
  1069. memset(tmpmixl, 0, synth.bufferbytes);
  1070. memset(tmpmixr, 0, synth.bufferbytes);
  1071. //Mix the channels according to the part settings about System Effect
  1072. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  1073. //skip if the part has no output to effect
  1074. if(Psysefxvol[nefx][npart] == 0)
  1075. continue;
  1076. //skip if the part is disabled
  1077. if(part[npart]->Penabled == 0)
  1078. continue;
  1079. //the output volume of each part to system effect
  1080. const float vol = sysefxvol[nefx][npart];
  1081. for(int i = 0; i < synth.buffersize; ++i) {
  1082. tmpmixl[i] += part[npart]->partoutl[i] * vol;
  1083. tmpmixr[i] += part[npart]->partoutr[i] * vol;
  1084. }
  1085. }
  1086. // system effect send to next ones
  1087. for(int nefxfrom = 0; nefxfrom < nefx; ++nefxfrom)
  1088. if(Psysefxsend[nefxfrom][nefx] != 0) {
  1089. const float vol = sysefxsend[nefxfrom][nefx];
  1090. for(int i = 0; i < synth.buffersize; ++i) {
  1091. tmpmixl[i] += sysefx[nefxfrom]->efxoutl[i] * vol;
  1092. tmpmixr[i] += sysefx[nefxfrom]->efxoutr[i] * vol;
  1093. }
  1094. }
  1095. sysefx[nefx]->out(tmpmixl, tmpmixr);
  1096. //Add the System Effect to sound output
  1097. const float outvol = sysefx[nefx]->sysefxgetvolume();
  1098. for(int i = 0; i < synth.buffersize; ++i) {
  1099. outl[i] += tmpmixl[i] * outvol;
  1100. outr[i] += tmpmixr[i] * outvol;
  1101. }
  1102. }
  1103. //Mix all parts
  1104. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  1105. if(part[npart]->Penabled) //only mix active parts
  1106. for(int i = 0; i < synth.buffersize; ++i) { //the volume did not changed
  1107. outl[i] += part[npart]->partoutl[i];
  1108. outr[i] += part[npart]->partoutr[i];
  1109. }
  1110. //Insertion effects for Master Out
  1111. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx)
  1112. if(Pinsparts[nefx] == -2)
  1113. insefx[nefx]->out(outl, outr);
  1114. //Master Volume
  1115. for(int i = 0; i < synth.buffersize; ++i) {
  1116. outl[i] *= volume;
  1117. outr[i] *= volume;
  1118. }
  1119. vuUpdate(outl, outr);
  1120. //Shutup if it is asked (with fade-out)
  1121. if(shutup) {
  1122. for(int i = 0; i < synth.buffersize; ++i) {
  1123. float tmp = (synth.buffersize_f - i) / synth.buffersize_f;
  1124. outl[i] *= tmp;
  1125. outr[i] *= tmp;
  1126. }
  1127. ShutUp();
  1128. }
  1129. //update the global frame timer
  1130. time++;
  1131. #ifdef DEMO_VERSION
  1132. double seconds = time.time()*synth.buffersize_f/synth.samplerate_f;
  1133. if(seconds > 10*60) {//10 minute trial
  1134. shutup = true;
  1135. for(int i = 0; i < synth.buffersize; ++i) {
  1136. float tmp = (synth.buffersize_f - i) / synth.buffersize_f;
  1137. outl[i] *= 0.0f;
  1138. outr[i] *= 0.0f;
  1139. }
  1140. }
  1141. #endif
  1142. //Update pulse
  1143. last_ack = last_beat;
  1144. return true;
  1145. }
  1146. //TODO review the respective code from yoshimi for this
  1147. //If memory serves correctly, libsamplerate was used
  1148. void Master::GetAudioOutSamples(size_t nsamples,
  1149. unsigned samplerate,
  1150. float *outl,
  1151. float *outr)
  1152. {
  1153. off_t out_off = 0;
  1154. //Fail when resampling rather than doing a poor job
  1155. if(synth.samplerate != samplerate) {
  1156. printf("darn it: %d vs %d\n", synth.samplerate, samplerate);
  1157. return;
  1158. }
  1159. while(nsamples) {
  1160. //use all available samples
  1161. if(nsamples >= smps) {
  1162. memcpy(outl + out_off, bufl + off, sizeof(float) * smps);
  1163. memcpy(outr + out_off, bufr + off, sizeof(float) * smps);
  1164. nsamples -= smps;
  1165. //generate samples
  1166. if (! AudioOut(bufl, bufr))
  1167. return;
  1168. off = 0;
  1169. out_off += smps;
  1170. smps = synth.buffersize;
  1171. }
  1172. else { //use some samples
  1173. memcpy(outl + out_off, bufl + off, sizeof(float) * nsamples);
  1174. memcpy(outr + out_off, bufr + off, sizeof(float) * nsamples);
  1175. smps -= nsamples;
  1176. off += nsamples;
  1177. nsamples = 0;
  1178. }
  1179. }
  1180. }
  1181. Master::~Master()
  1182. {
  1183. delete []bufl;
  1184. delete []bufr;
  1185. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  1186. delete part[npart];
  1187. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx)
  1188. delete insefx[nefx];
  1189. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx)
  1190. delete sysefx[nefx];
  1191. delete fft;
  1192. delete memory;
  1193. }
  1194. /*
  1195. * Parameter control
  1196. */
  1197. void Master::setPvolume(char Pvolume_)
  1198. {
  1199. Pvolume = Pvolume_;
  1200. volume = dB2rap((Pvolume - 96.0f) / 96.0f * 40.0f);
  1201. }
  1202. void Master::setPkeyshift(char Pkeyshift_)
  1203. {
  1204. Pkeyshift = Pkeyshift_;
  1205. keyshift = (int)Pkeyshift - 64;
  1206. }
  1207. void Master::setPsysefxvol(int Ppart, int Pefx, char Pvol)
  1208. {
  1209. Psysefxvol[Pefx][Ppart] = Pvol;
  1210. sysefxvol[Pefx][Ppart] = powf(0.1f, (1.0f - Pvol / 96.0f) * 2.0f);
  1211. }
  1212. void Master::setPsysefxsend(int Pefxfrom, int Pefxto, char Pvol)
  1213. {
  1214. Psysefxsend[Pefxfrom][Pefxto] = Pvol;
  1215. sysefxsend[Pefxfrom][Pefxto] = powf(0.1f, (1.0f - Pvol / 96.0f) * 2.0f);
  1216. }
  1217. /*
  1218. * Panic! (Clean up all parts and effects)
  1219. */
  1220. void Master::ShutUp()
  1221. {
  1222. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  1223. part[npart]->cleanup();
  1224. fakepeakpart[npart] = 0;
  1225. }
  1226. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx)
  1227. insefx[nefx]->cleanup();
  1228. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx)
  1229. sysefx[nefx]->cleanup();
  1230. for(int i = 0; i < int(sizeof(activeNotes)/sizeof(activeNotes[0])); ++i)
  1231. activeNotes[i] = 0;
  1232. vuresetpeaks();
  1233. shutup = 0;
  1234. }
  1235. /*
  1236. * Reset peaks and clear the "cliped" flag (for VU-meter)
  1237. */
  1238. void Master::vuresetpeaks()
  1239. {
  1240. vu.outpeakl = 1e-9;
  1241. vu.outpeakr = 1e-9;
  1242. vu.maxoutpeakl = 1e-9;
  1243. vu.maxoutpeakr = 1e-9;
  1244. vu.clipped = 0;
  1245. }
  1246. void Master::applyparameters(void)
  1247. {
  1248. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  1249. part[npart]->applyparameters();
  1250. }
  1251. void Master::initialize_rt(void)
  1252. {
  1253. for(int i=0; i<NUM_SYS_EFX; ++i)
  1254. sysefx[i]->init();
  1255. for(int i=0; i<NUM_INS_EFX; ++i)
  1256. insefx[i]->init();
  1257. for(int i=0; i<NUM_MIDI_PARTS; ++i)
  1258. part[i]->initialize_rt();
  1259. }
  1260. void Master::add2XML(XMLwrapper& xml)
  1261. {
  1262. xml.addpar("volume", Pvolume);
  1263. xml.addpar("key_shift", Pkeyshift);
  1264. xml.addparbool("nrpn_receive", ctl.NRPN.receive);
  1265. xml.beginbranch("MICROTONAL");
  1266. microtonal.add2XML(xml);
  1267. xml.endbranch();
  1268. saveAutomation(xml, automate);
  1269. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  1270. xml.beginbranch("PART", npart);
  1271. part[npart]->add2XML(xml);
  1272. xml.endbranch();
  1273. }
  1274. xml.beginbranch("SYSTEM_EFFECTS");
  1275. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx) {
  1276. xml.beginbranch("SYSTEM_EFFECT", nefx);
  1277. xml.beginbranch("EFFECT");
  1278. sysefx[nefx]->add2XML(xml);
  1279. xml.endbranch();
  1280. for(int pefx = 0; pefx < NUM_MIDI_PARTS; ++pefx) {
  1281. xml.beginbranch("VOLUME", pefx);
  1282. xml.addpar("vol", Psysefxvol[nefx][pefx]);
  1283. xml.endbranch();
  1284. }
  1285. for(int tonefx = nefx + 1; tonefx < NUM_SYS_EFX; ++tonefx) {
  1286. xml.beginbranch("SENDTO", tonefx);
  1287. xml.addpar("send_vol", Psysefxsend[nefx][tonefx]);
  1288. xml.endbranch();
  1289. }
  1290. xml.endbranch();
  1291. }
  1292. xml.endbranch();
  1293. xml.beginbranch("INSERTION_EFFECTS");
  1294. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx) {
  1295. xml.beginbranch("INSERTION_EFFECT", nefx);
  1296. xml.addpar("part", Pinsparts[nefx]);
  1297. xml.beginbranch("EFFECT");
  1298. insefx[nefx]->add2XML(xml);
  1299. xml.endbranch();
  1300. xml.endbranch();
  1301. }
  1302. xml.endbranch();
  1303. }
  1304. int Master::getalldata(char **data)
  1305. {
  1306. XMLwrapper xml;
  1307. xml.beginbranch("MASTER");
  1308. add2XML(xml);
  1309. xml.endbranch();
  1310. *data = xml.getXMLdata();
  1311. return strlen(*data) + 1;
  1312. }
  1313. void Master::putalldata(const char *data)
  1314. {
  1315. XMLwrapper xml;
  1316. if(!xml.putXMLdata(data)) {
  1317. return;
  1318. }
  1319. if(xml.enterbranch("MASTER") == 0)
  1320. return;
  1321. getfromXML(xml);
  1322. xml.exitbranch();
  1323. }
  1324. int Master::saveXML(const char *filename)
  1325. {
  1326. XMLwrapper xml;
  1327. xml.beginbranch("MASTER");
  1328. add2XML(xml);
  1329. xml.endbranch();
  1330. return xml.saveXMLfile(filename, gzip_compression);
  1331. }
  1332. int Master::loadXML(const char *filename)
  1333. {
  1334. XMLwrapper xml;
  1335. if(xml.loadXMLfile(filename) < 0) {
  1336. return -1;
  1337. }
  1338. if(xml.enterbranch("MASTER") == 0)
  1339. return -10;
  1340. getfromXML(xml);
  1341. xml.exitbranch();
  1342. initialize_rt();
  1343. return 0;
  1344. }
  1345. void Master::getfromXML(XMLwrapper& xml)
  1346. {
  1347. setPvolume(xml.getpar127("volume", Pvolume));
  1348. setPkeyshift(xml.getpar127("key_shift", Pkeyshift));
  1349. ctl.NRPN.receive = xml.getparbool("nrpn_receive", ctl.NRPN.receive);
  1350. part[0]->Penabled = 0;
  1351. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  1352. if(xml.enterbranch("PART", npart) == 0)
  1353. continue;
  1354. part[npart]->getfromXML(xml);
  1355. xml.exitbranch();
  1356. }
  1357. if(xml.enterbranch("MICROTONAL")) {
  1358. microtonal.getfromXML(xml);
  1359. xml.exitbranch();
  1360. }
  1361. loadAutomation(xml, automate);
  1362. sysefx[0]->changeeffect(0);
  1363. if(xml.enterbranch("SYSTEM_EFFECTS")) {
  1364. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx) {
  1365. if(xml.enterbranch("SYSTEM_EFFECT", nefx) == 0)
  1366. continue;
  1367. if(xml.enterbranch("EFFECT")) {
  1368. sysefx[nefx]->getfromXML(xml);
  1369. xml.exitbranch();
  1370. }
  1371. for(int partefx = 0; partefx < NUM_MIDI_PARTS; ++partefx) {
  1372. if(xml.enterbranch("VOLUME", partefx) == 0)
  1373. continue;
  1374. setPsysefxvol(partefx, nefx,
  1375. xml.getpar127("vol", Psysefxvol[partefx][nefx]));
  1376. xml.exitbranch();
  1377. }
  1378. for(int tonefx = nefx + 1; tonefx < NUM_SYS_EFX; ++tonefx) {
  1379. if(xml.enterbranch("SENDTO", tonefx) == 0)
  1380. continue;
  1381. setPsysefxsend(nefx, tonefx,
  1382. xml.getpar127("send_vol",
  1383. Psysefxsend[nefx][tonefx]));
  1384. xml.exitbranch();
  1385. }
  1386. xml.exitbranch();
  1387. }
  1388. xml.exitbranch();
  1389. }
  1390. if(xml.enterbranch("INSERTION_EFFECTS")) {
  1391. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx) {
  1392. if(xml.enterbranch("INSERTION_EFFECT", nefx) == 0)
  1393. continue;
  1394. Pinsparts[nefx] = xml.getpar("part",
  1395. Pinsparts[nefx],
  1396. -2,
  1397. NUM_MIDI_PARTS);
  1398. if(xml.enterbranch("EFFECT")) {
  1399. insefx[nefx]->getfromXML(xml);
  1400. xml.exitbranch();
  1401. }
  1402. xml.exitbranch();
  1403. }
  1404. xml.exitbranch();
  1405. }
  1406. }
  1407. static rtosc_version version_in_rtosc_fmt()
  1408. {
  1409. return rtosc_version
  1410. {
  1411. (unsigned char) version.get_major(),
  1412. (unsigned char) version.get_minor(),
  1413. (unsigned char) version.get_revision()
  1414. };
  1415. }
  1416. char* Master::getXMLData()
  1417. {
  1418. XMLwrapper xml;
  1419. xml.beginbranch("MASTER");
  1420. add2XML(xml);
  1421. xml.endbranch();
  1422. return xml.getXMLdata();
  1423. }
  1424. int Master::saveOSC(const char *filename)
  1425. {
  1426. std::string savefile = rtosc::save_to_file(ports, this,
  1427. "ZynAddSubFX",
  1428. version_in_rtosc_fmt());
  1429. zyncarla::Config config;
  1430. zyncarla::SYNTH_T* synth = new zyncarla::SYNTH_T;
  1431. synth->buffersize = 256;
  1432. synth->samplerate = 48000;
  1433. synth->alias();
  1434. zyncarla::Master master2(*synth, &config);
  1435. int rval = master2.loadOSCFromStr(savefile.c_str());
  1436. if(rval < 0)
  1437. {
  1438. std::cerr << "invalid savefile!" << std::endl;
  1439. std::cerr << "complete savefile:" << std::endl;
  1440. std::cerr << savefile << std::endl;
  1441. std::cerr << "first entry that could not be parsed:" << std::endl;
  1442. for(int i = -rval + 1; savefile[i]; ++i)
  1443. if(savefile[i] == '\n')
  1444. {
  1445. savefile.resize(i);
  1446. break;
  1447. }
  1448. std::cerr << (savefile.c_str() - rval) << std::endl;
  1449. rval = -1;
  1450. }
  1451. else
  1452. {
  1453. char* xml = getXMLData(),
  1454. * xml2 = master2.getXMLData();
  1455. rval = strcmp(xml, xml2) ? -1 : 0;
  1456. if(rval == 0)
  1457. {
  1458. if(filename)
  1459. {
  1460. std::ofstream ofs(filename);
  1461. ofs << savefile;
  1462. }
  1463. else if(!filename)
  1464. std::cout << savefile << std::endl;
  1465. }
  1466. else
  1467. {
  1468. std::cout << savefile << std::endl;
  1469. std::cerr << "Can not write OSC savefile!! (see tmp1.txt and tmp2.txt)"
  1470. << std::endl;
  1471. std::ofstream tmp1("tmp1.txt"), tmp2("tmp2.txt");
  1472. tmp1 << xml;
  1473. tmp2 << xml2;
  1474. }
  1475. free(xml);
  1476. free(xml2);
  1477. }
  1478. return rval;
  1479. }
  1480. int Master::loadOSCFromStr(const char *filename)
  1481. {
  1482. return rtosc::load_from_file(filename,
  1483. ports, this,
  1484. "ZynAddSubFX", version_in_rtosc_fmt());
  1485. }
  1486. string loadfile(string fname)
  1487. {
  1488. std::ifstream t(fname.c_str());
  1489. std::string str((std::istreambuf_iterator<char>(t)),
  1490. std::istreambuf_iterator<char>());
  1491. return str;
  1492. }
  1493. int Master::loadOSC(const char *filename)
  1494. {
  1495. int rval = loadOSCFromStr(loadfile(filename).c_str());
  1496. return rval < 0 ? rval : 0;
  1497. }
  1498. }