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.

Master.cpp 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140
  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 modify
  8. it under the terms of version 2 of the GNU General Public License
  9. as published by the Free Software Foundation.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License (version 2 or later) for more details.
  14. You should have received a copy of the GNU General Public License (version 2)
  15. along with this program; if not, write to the Free Software Foundation,
  16. Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  17. */
  18. #include "Master.h"
  19. #include "Part.h"
  20. #include "../Misc/Stereo.h"
  21. #include "../Misc/Util.h"
  22. #include "../Params/LFOParams.h"
  23. #include "../Effects/EffectMgr.h"
  24. #include "../DSP/FFTwrapper.h"
  25. #include "../Misc/Allocator.h"
  26. #include "../Nio/Nio.h"
  27. #include "PresetExtractor.h"
  28. #include <rtosc/ports.h>
  29. #include <rtosc/port-sugar.h>
  30. #include <rtosc/thread-link.h>
  31. #include <stdio.h>
  32. #include <sys/stat.h>
  33. #include <sys/types.h>
  34. #include <iostream>
  35. #include <algorithm>
  36. #include <cmath>
  37. #include <atomic>
  38. #include <unistd.h>
  39. using namespace std;
  40. using namespace rtosc;
  41. #define rObject Master
  42. static const Ports sysefxPort =
  43. {
  44. {"part#" STRINGIFY(NUM_MIDI_PARTS) "::i", rProp(parameter)
  45. rDoc("gain on part to sysefx routing"), 0,
  46. [](const char *m, RtData&d)
  47. {
  48. //ok, this is going to be an ugly workaround
  49. //we know that if we are here the message previously MUST have
  50. //matched Psysefxvol#/
  51. //and the number is one or two digits at most
  52. const char *index_1 = m;
  53. index_1 -=2;
  54. assert(isdigit(*index_1));
  55. if(isdigit(index_1[-1]))
  56. index_1--;
  57. int ind1 = atoi(index_1);
  58. //Now get the second index like normal
  59. while(!isdigit(*m)) m++;
  60. int ind2 = atoi(m);
  61. Master &mast = *(Master*)d.obj;
  62. if(rtosc_narguments(m))
  63. mast.setPsysefxvol(ind2, ind1, rtosc_argument(m,0).i);
  64. else
  65. d.reply(d.loc, "i", mast.Psysefxvol[ind2][ind1]);
  66. }}
  67. };
  68. static const Ports sysefsendto =
  69. {
  70. {"to#" STRINGIFY(NUM_SYS_EFX) "::i",
  71. rProp(parameter) rDoc("sysefx to sysefx routing gain"), 0, [](const char *m, RtData&d)
  72. {
  73. //same ugly workaround as before
  74. const char *index_1 = m;
  75. index_1 -=2;
  76. assert(isdigit(*index_1));
  77. if(isdigit(index_1[-1]))
  78. index_1--;
  79. int ind1 = atoi(index_1);
  80. //Now get the second index like normal
  81. while(!isdigit(*m)) m++;
  82. int ind2 = atoi(m);
  83. Master &master = *(Master*)d.obj;
  84. if(rtosc_narguments(m))
  85. master.setPsysefxsend(ind1, ind2, rtosc_argument(m,0).i);
  86. else
  87. d.reply(d.loc, "i", master.Psysefxsend[ind1][ind2]);
  88. }}
  89. };
  90. static const Ports master_ports = {
  91. rString(last_xmz, XMZ_PATH_MAX, "File name for last name loaded if any."),
  92. rRecursp(part, 16, "Part"),//NUM_MIDI_PARTS
  93. rRecursp(sysefx, 4, "System Effect"),//NUM_SYS_EFX
  94. rRecursp(insefx, 8, "Insertion Effect"),//NUM_INS_EFX
  95. rRecur(microtonal, "Micrtonal Mapping Functionality"),
  96. rRecur(ctl, "Controller"),
  97. rParamZyn(Pkeyshift, "Global Key Shift"),
  98. rArrayI(Pinsparts, NUM_INS_EFX, "Part to insert part onto"),
  99. {"echo", rDoc("Hidden port to echo messages"), 0, [](const char *m, RtData&d) {
  100. d.reply(m-1);}},
  101. {"get-vu:", rDoc("Grab VU Data"), 0, [](const char *, RtData &d) {
  102. Master *m = (Master*)d.obj;
  103. d.reply("/vu-meter", "bb", sizeof(m->vu), &m->vu, sizeof(float)*NUM_MIDI_PARTS, m->vuoutpeakpart);}},
  104. {"reset-vu:", rDoc("Grab VU Data"), 0, [](const char *, RtData &d) {
  105. Master *m = (Master*)d.obj;
  106. m->vuresetpeaks();}},
  107. {"load-part:ib", rProp(internal) rDoc("Load Part From Middleware"), 0, [](const char *msg, RtData &d) {
  108. Master *m = (Master*)d.obj;
  109. Part *p = *(Part**)rtosc_argument(msg, 1).b.data;
  110. int i = rtosc_argument(msg, 0).i;
  111. m->part[i]->cloneTraits(*p);
  112. m->part[i]->kill_rt();
  113. d.reply("/free", "sb", "Part", sizeof(void*), &m->part[i]);
  114. m->part[i] = p;
  115. p->initialize_rt();
  116. }},
  117. {"Pvolume::i", rProp(parameter) rLinear(0,127) rDoc("Master Volume"), 0,
  118. [](const char *m, rtosc::RtData &d) {
  119. if(rtosc_narguments(m)==0) {
  120. d.reply(d.loc, "i", ((Master*)d.obj)->Pvolume);
  121. } else if(rtosc_narguments(m)==1 && rtosc_type(m,0)=='i') {
  122. ((Master*)d.obj)->setPvolume(limit<char>(rtosc_argument(m,0).i,0,127));
  123. d.broadcast(d.loc, "i", ((Master*)d.obj)->Pvolume);}}},
  124. {"volume::i", rProp(parameter) rLinear(0,127) rDoc("Master Volume"), 0,
  125. [](const char *m, rtosc::RtData &d) {
  126. if(rtosc_narguments(m)==0) {
  127. d.reply(d.loc, "i", ((Master*)d.obj)->Pvolume);
  128. } else if(rtosc_narguments(m)==1 && rtosc_type(m,0)=='i') {
  129. ((Master*)d.obj)->setPvolume(limit<char>(rtosc_argument(m,0).i,0,127));
  130. d.broadcast(d.loc, "i", ((Master*)d.obj)->Pvolume);}}},
  131. {"Psysefxvol#" STRINGIFY(NUM_SYS_EFX) "/::i", 0, &sysefxPort,
  132. [](const char *msg, rtosc::RtData &d) {
  133. SNIP;
  134. sysefxPort.dispatch(msg, d);
  135. }},
  136. {"sysefxfrom#" STRINGIFY(NUM_SYS_EFX) "/", rDoc("Routing Between System Effects"), &sysefsendto,
  137. [](const char *msg, RtData&d) {
  138. SNIP;
  139. sysefsendto.dispatch(msg, d);
  140. }},
  141. {"noteOn:iii", rDoc("Noteon Event"), 0,
  142. [](const char *m,RtData &d){
  143. Master *M = (Master*)d.obj;
  144. M->noteOn(rtosc_argument(m,0).i,rtosc_argument(m,1).i,rtosc_argument(m,2).i);}},
  145. {"noteOff:ii", rDoc("Noteoff Event"), 0,
  146. [](const char *m,RtData &d){
  147. Master *M = (Master*)d.obj;
  148. M->noteOff(rtosc_argument(m,0).i,rtosc_argument(m,1).i);}},
  149. {"virtual_midi_cc:iii", rDoc("MIDI CC Event"), 0,
  150. [](const char *m,RtData &d){
  151. Master *M = (Master*)d.obj;
  152. M->setController(rtosc_argument(m,0).i,rtosc_argument(m,1).i,rtosc_argument(m,2).i);}},
  153. {"setController:iii", rDoc("MIDI CC Event"), 0,
  154. [](const char *m,RtData &d){
  155. Master *M = (Master*)d.obj;
  156. M->setController(rtosc_argument(m,0).i,rtosc_argument(m,1).i,rtosc_argument(m,2).i);}},
  157. {"Panic:", rDoc("Stop all sound"), 0,
  158. [](const char *, RtData &d) {
  159. Master &M = *(Master*)d.obj;
  160. M.ShutUp();
  161. }},
  162. {"freeze_state:", rProp(internal) rDoc("Disable OSC event handling\n"
  163. "This sets up a read-only mode from which it's safe for another"
  164. " thread to save parameters"), 0,
  165. [](const char *,RtData &d) {
  166. Master *M = (Master*)d.obj;
  167. std::atomic_thread_fence(std::memory_order_release);
  168. M->frozenState = true;
  169. d.reply("/state_frozen", "");}},
  170. {"thaw_state:", rProp(internal) rDoc("Resume handling OSC messages\n"
  171. "See /freeze_state for more information"), 0,
  172. [](const char *,RtData &d) {
  173. Master *M = (Master*)d.obj;
  174. M->frozenState = false;}},
  175. {"midi-learn/", 0, &rtosc::MidiMapperRT::ports,
  176. [](const char *msg, RtData &d) {
  177. Master *M = (Master*)d.obj;
  178. SNIP;
  179. printf("residue message = <%s>\n", msg);
  180. d.obj = &M->midi;
  181. rtosc::MidiMapperRT::ports.dispatch(msg,d);}},
  182. {"close-ui:", rDoc("Request to close any connection named \"GUI\""), 0,
  183. [](const char *, RtData &d) {
  184. d.reply("/close-ui", "");}},
  185. {"add-rt-memory:bi", rProp(internal) rDoc("Add Additional Memory To RT MemPool"), 0,
  186. [](const char *msg, RtData &d)
  187. {
  188. Master &m = *(Master*)d.obj;
  189. char *mem = *(char**)rtosc_argument(msg, 0).b.data;
  190. int i = rtosc_argument(msg, 1).i;
  191. m.memory->addMemory(mem, i);
  192. m.pendingMemory = false;
  193. }},
  194. {"samplerate:", rMap(unit, Hz) rDoc("Get synthesizer sample rate"), 0, [](const char *, RtData &d) {
  195. Master &m = *(Master*)d.obj;
  196. d.reply("/samplerate", "f", m.synth.samplerate_f);
  197. }},
  198. {"oscilsize:", rDoc("Get synthesizer oscillator size"), 0, [](const char *, RtData &d) {
  199. Master &m = *(Master*)d.obj;
  200. d.reply("/oscilsize", "f", m.synth.oscilsize_f);
  201. d.reply("/oscilsize", "i", m.synth.oscilsize);
  202. }},
  203. {"undo_pause:",rProp(internal) rDoc("pause undo event recording"),0,
  204. [](const char *, rtosc::RtData &d) {d.reply("/undo_pause", "");}},
  205. {"undo_resume:",rProp(internal) rDoc("resume undo event recording"),0,
  206. [](const char *, rtosc::RtData &d) {d.reply("/undo_resume", "");}},
  207. {"config/", rDoc("Top Level Application Configuration Parameters"), &Config::ports,
  208. [](const char *, rtosc::RtData &d){d.forward();}},
  209. {"presets/", rDoc("Parameter Presets"), &preset_ports, rBOIL_BEGIN
  210. SNIP
  211. preset_ports.dispatch(msg, data);
  212. rBOIL_END},
  213. };
  214. const Ports &Master::ports = master_ports;
  215. class DataObj:public rtosc::RtData
  216. {
  217. public:
  218. DataObj(char *loc_, size_t loc_size_, void *obj_, rtosc::ThreadLink *bToU_)
  219. {
  220. memset(loc_, 0, loc_size_);
  221. loc = loc_;
  222. loc_size = loc_size_;
  223. obj = obj_;
  224. bToU = bToU_;
  225. forwarded = false;
  226. }
  227. virtual void reply(const char *path, const char *args, ...) override
  228. {
  229. va_list va;
  230. va_start(va,args);
  231. char *buffer = bToU->buffer();
  232. rtosc_vmessage(buffer,bToU->buffer_size(),path,args,va);
  233. reply(buffer);
  234. va_end(va);
  235. }
  236. virtual void reply(const char *msg) override
  237. {
  238. if(rtosc_message_length(msg, -1) == 0)
  239. fprintf(stderr, "Warning: Invalid Rtosc message '%s'\n", msg);
  240. bToU->raw_write(msg);
  241. }
  242. virtual void broadcast(const char *path, const char *args, ...) override{
  243. va_list va;
  244. va_start(va,args);
  245. reply("/broadcast", "");
  246. char *buffer = bToU->buffer();
  247. rtosc_vmessage(buffer,bToU->buffer_size(),path,args,va);
  248. reply(buffer);
  249. va_end(va);
  250. }
  251. virtual void broadcast(const char *msg) override
  252. {
  253. reply("/broadcast", "");
  254. reply(msg);
  255. }
  256. virtual void forward(const char *reason) override
  257. {
  258. assert(message);
  259. reply("/forward", "");
  260. printf("forwarding '%s'\n", message);
  261. forwarded = true;
  262. }
  263. bool forwarded;
  264. private:
  265. rtosc::ThreadLink *bToU;
  266. };
  267. vuData::vuData(void)
  268. :outpeakl(0.0f), outpeakr(0.0f), maxoutpeakl(0.0f), maxoutpeakr(0.0f),
  269. rmspeakl(0.0f), rmspeakr(0.0f), clipped(0)
  270. {}
  271. Master::Master(const SYNTH_T &synth_, Config* config)
  272. :HDDRecorder(synth_), ctl(synth_),
  273. microtonal(config->cfg.GzipCompression), bank(config),
  274. frozenState(false), pendingMemory(false),
  275. synth(synth_), time(synth), gzip_compression(config->cfg.GzipCompression)
  276. {
  277. bToU = NULL;
  278. uToB = NULL;
  279. //Setup MIDI
  280. midi.frontend = [this](const char *msg) {bToU->raw_write(msg);};
  281. midi.backend = [this](const char *msg) {applyOscEvent(msg);};
  282. memory = new AllocatorClass();
  283. swaplr = 0;
  284. off = 0;
  285. smps = 0;
  286. bufl = new float[synth.buffersize];
  287. bufr = new float[synth.buffersize];
  288. last_xmz[0] = 0;
  289. fft = new FFTwrapper(synth.oscilsize);
  290. shutup = 0;
  291. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  292. vuoutpeakpart[npart] = 1e-9;
  293. fakepeakpart[npart] = 0;
  294. }
  295. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  296. part[npart] = new Part(*memory, synth, time, config->cfg.GzipCompression,
  297. config->cfg.Interpolation, &microtonal, fft);
  298. //Insertion Effects init
  299. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx)
  300. insefx[nefx] = new EffectMgr(*memory, synth, 1);
  301. //System Effects init
  302. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx)
  303. sysefx[nefx] = new EffectMgr(*memory, synth, 0);
  304. defaults();
  305. mastercb = 0;
  306. mastercb_ptr = 0;
  307. }
  308. void Master::applyOscEvent(const char *msg)
  309. {
  310. char loc_buf[1024];
  311. DataObj d{loc_buf, 1024, this, bToU};
  312. memset(loc_buf, 0, sizeof(loc_buf));
  313. d.matches = 0;
  314. if(strcmp(msg, "/get-vu") && false) {
  315. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 5 + 30, 0 + 40);
  316. fprintf(stdout, "backend[*]: '%s'<%s>\n", msg,
  317. rtosc_argument_string(msg));
  318. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 7 + 30, 0 + 40);
  319. }
  320. ports.dispatch(msg, d, true);
  321. if(d.matches == 0 && !d.forwarded)
  322. fprintf(stderr, "Unknown path '%s:%s'\n", msg, rtosc_argument_string(msg));
  323. if(d.forwarded)
  324. bToU->raw_write(msg);
  325. }
  326. void Master::defaults()
  327. {
  328. volume = 1.0f;
  329. setPvolume(80);
  330. setPkeyshift(64);
  331. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  332. part[npart]->defaults();
  333. part[npart]->Prcvchn = npart % NUM_MIDI_CHANNELS;
  334. }
  335. partonoff(0, 1); //enable the first part
  336. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx) {
  337. insefx[nefx]->defaults();
  338. Pinsparts[nefx] = -1;
  339. }
  340. //System Effects init
  341. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx) {
  342. sysefx[nefx]->defaults();
  343. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  344. setPsysefxvol(npart, nefx, 0);
  345. for(int nefxto = 0; nefxto < NUM_SYS_EFX; ++nefxto)
  346. setPsysefxsend(nefx, nefxto, 0);
  347. }
  348. microtonal.defaults();
  349. ShutUp();
  350. }
  351. /*
  352. * Note On Messages (velocity=0 for NoteOff)
  353. */
  354. void Master::noteOn(char chan, char note, char velocity)
  355. {
  356. if(velocity) {
  357. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  358. if(chan == part[npart]->Prcvchn) {
  359. fakepeakpart[npart] = velocity * 2;
  360. if(part[npart]->Penabled)
  361. part[npart]->NoteOn(note, velocity, keyshift);
  362. }
  363. }
  364. else
  365. this->noteOff(chan, note);
  366. HDDRecorder.triggernow();
  367. }
  368. /*
  369. * Note Off Messages
  370. */
  371. void Master::noteOff(char chan, char note)
  372. {
  373. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  374. if((chan == part[npart]->Prcvchn) && part[npart]->Penabled)
  375. part[npart]->NoteOff(note);
  376. }
  377. /*
  378. * Pressure Messages (velocity=0 for NoteOff)
  379. */
  380. void Master::polyphonicAftertouch(char chan, char note, char velocity)
  381. {
  382. if(velocity) {
  383. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  384. if(chan == part[npart]->Prcvchn)
  385. if(part[npart]->Penabled)
  386. part[npart]->PolyphonicAftertouch(note, velocity, keyshift);
  387. }
  388. else
  389. this->noteOff(chan, note);
  390. }
  391. /*
  392. * Controllers
  393. */
  394. void Master::setController(char chan, int type, int par)
  395. {
  396. if(frozenState)
  397. return;
  398. //TODO add chan back
  399. midi.handleCC(type,par);
  400. if((type == C_dataentryhi) || (type == C_dataentrylo)
  401. || (type == C_nrpnhi) || (type == C_nrpnlo)) { //Process RPN and NRPN by the Master (ignore the chan)
  402. ctl.setparameternumber(type, par);
  403. int parhi = -1, parlo = -1, valhi = -1, vallo = -1;
  404. if(ctl.getnrpn(&parhi, &parlo, &valhi, &vallo) == 0) { //this is NRPN
  405. switch(parhi) {
  406. case 0x04: //System Effects
  407. if(parlo < NUM_SYS_EFX)
  408. sysefx[parlo]->seteffectparrt(valhi, vallo);
  409. break;
  410. case 0x08: //Insertion Effects
  411. if(parlo < NUM_INS_EFX)
  412. insefx[parlo]->seteffectparrt(valhi, vallo);
  413. break;
  414. }
  415. }
  416. } else { //other controllers
  417. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) //Send the controller to all part assigned to the channel
  418. if((chan == part[npart]->Prcvchn) && (part[npart]->Penabled != 0))
  419. part[npart]->SetController(type, par);
  420. if(type == C_allsoundsoff) { //cleanup insertion/system FX
  421. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx)
  422. sysefx[nefx]->cleanup();
  423. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx)
  424. insefx[nefx]->cleanup();
  425. }
  426. }
  427. }
  428. void Master::vuUpdate(const float *outl, const float *outr)
  429. {
  430. //Peak computation (for vumeters)
  431. vu.outpeakl = 1e-12;
  432. vu.outpeakr = 1e-12;
  433. for(int i = 0; i < synth.buffersize; ++i) {
  434. if(fabs(outl[i]) > vu.outpeakl)
  435. vu.outpeakl = fabs(outl[i]);
  436. if(fabs(outr[i]) > vu.outpeakr)
  437. vu.outpeakr = fabs(outr[i]);
  438. }
  439. if((vu.outpeakl > 1.0f) || (vu.outpeakr > 1.0f))
  440. vu.clipped = 1;
  441. if(vu.maxoutpeakl < vu.outpeakl)
  442. vu.maxoutpeakl = vu.outpeakl;
  443. if(vu.maxoutpeakr < vu.outpeakr)
  444. vu.maxoutpeakr = vu.outpeakr;
  445. //RMS Peak computation (for vumeters)
  446. vu.rmspeakl = 1e-12;
  447. vu.rmspeakr = 1e-12;
  448. for(int i = 0; i < synth.buffersize; ++i) {
  449. vu.rmspeakl += outl[i] * outl[i];
  450. vu.rmspeakr += outr[i] * outr[i];
  451. }
  452. vu.rmspeakl = sqrt(vu.rmspeakl / synth.buffersize_f);
  453. vu.rmspeakr = sqrt(vu.rmspeakr / synth.buffersize_f);
  454. //Part Peak computation (for Part vumeters or fake part vumeters)
  455. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  456. vuoutpeakpart[npart] = 1.0e-12f;
  457. if(part[npart]->Penabled != 0) {
  458. float *outl = part[npart]->partoutl,
  459. *outr = part[npart]->partoutr;
  460. for(int i = 0; i < synth.buffersize; ++i) {
  461. float tmp = fabs(outl[i] + outr[i]);
  462. if(tmp > vuoutpeakpart[npart])
  463. vuoutpeakpart[npart] = tmp;
  464. }
  465. vuoutpeakpart[npart] *= volume;
  466. }
  467. else
  468. if(fakepeakpart[npart] > 1)
  469. fakepeakpart[npart]--;
  470. }
  471. }
  472. /*
  473. * Enable/Disable a part
  474. */
  475. void Master::partonoff(int npart, int what)
  476. {
  477. if(npart >= NUM_MIDI_PARTS)
  478. return;
  479. if(what == 0) { //disable part
  480. fakepeakpart[npart] = 0;
  481. part[npart]->Penabled = 0;
  482. part[npart]->cleanup();
  483. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx) {
  484. if(Pinsparts[nefx] == npart)
  485. insefx[nefx]->cleanup();
  486. }
  487. }
  488. else { //enabled
  489. part[npart]->Penabled = 1;
  490. fakepeakpart[npart] = 0;
  491. }
  492. }
  493. void Master::setMasterChangedCallback(void(*cb)(void*,Master*), void *ptr)
  494. {
  495. mastercb = cb;
  496. mastercb_ptr = ptr;
  497. }
  498. #if 0
  499. template <class T>
  500. struct def_skip
  501. {
  502. static void skip(const char*& argptr) { argptr += sizeof(T); }
  503. };
  504. template <class T>
  505. struct str_skip
  506. {
  507. static void skip(const char*& argptr) { while(argptr++); /*TODO: 4 padding */ }
  508. };
  509. template<class T, class Display = T, template<class TMP> class SkipsizeFunc = def_skip>
  510. void _dump_prim_arg(const char*& argptr, std::ostream& os)
  511. {
  512. os << ' ' << (Display)*(const T*)argptr;
  513. SkipsizeFunc<T>::skip(argptr);
  514. }
  515. void dump_msg(const char* ptr, std::ostream& os = std::cerr)
  516. {
  517. assert(*ptr == '/');
  518. os << ptr;
  519. while(*++ptr) ; // skip address
  520. while(!*++ptr) ; // skip 0s
  521. assert(*ptr == ',');
  522. os << ' ' << (ptr + 1);
  523. const char* argptr = ptr;
  524. while(*++argptr) ; // skip type string
  525. while(!*++argptr) ; // skip 0s
  526. char c;
  527. while((c = *++ptr))
  528. {
  529. switch(c)
  530. {
  531. case 'i':
  532. _dump_prim_arg<int32_t>(argptr, os); break;
  533. case 'c':
  534. _dump_prim_arg<int32_t, char>(argptr, os); break;
  535. // case 's':
  536. // _dump_prim_arg<char, const char*>(argptr, os); break;
  537. default:
  538. exit(1);
  539. }
  540. }
  541. }
  542. #endif
  543. int msg_id=0;
  544. /*
  545. * Master audio out (the final sound)
  546. */
  547. void Master::AudioOut(float *outl, float *outr)
  548. {
  549. //Danger Limits
  550. if(memory->lowMemory(2,1024*1024))
  551. printf("QUITE LOW MEMORY IN THE RT POOL BE PREPARED FOR WEIRD BEHAVIOR!!\n");
  552. //Normal Limits
  553. if(!pendingMemory && memory->lowMemory(4,1024*1024)) {
  554. printf("Requesting more memory\n");
  555. bToU->write("/request-memory", "");
  556. pendingMemory = true;
  557. }
  558. //Handle user events TODO move me to a proper location
  559. char loc_buf[1024];
  560. DataObj d{loc_buf, 1024, this, bToU};
  561. memset(loc_buf, 0, sizeof(loc_buf));
  562. int events = 0;
  563. while(uToB && uToB->hasNext() && events < 100) {
  564. const char *msg = uToB->read();
  565. if(!strcmp(msg, "/load-master")) {
  566. Master *this_master = this;
  567. Master *new_master = *(Master**)rtosc_argument(msg, 0).b.data;
  568. new_master->AudioOut(outl, outr);
  569. Nio::masterSwap(new_master);
  570. if (mastercb)
  571. mastercb(mastercb_ptr, new_master);
  572. bToU->write("/free", "sb", "Master", sizeof(Master*), &this_master);
  573. return;
  574. }
  575. //XXX yes, this is not realtime safe, but it is useful...
  576. if(strcmp(msg, "/get-vu") && false) {
  577. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 5 + 30, 0 + 40);
  578. fprintf(stdout, "backend[%d]: '%s'<%s>\n", msg_id++, msg,
  579. rtosc_argument_string(msg));
  580. fprintf(stdout, "%c[%d;%d;%dm", 0x1B, 0, 7 + 30, 0 + 40);
  581. }
  582. ports.dispatch(msg, d, true);
  583. events++;
  584. if(!d.matches) {// && !ports.apropos(msg)) {
  585. fprintf(stderr, "%c[%d;%d;%dm", 0x1B, 1, 7 + 30, 0 + 40);
  586. fprintf(stderr, "Unknown address<BACKEND> '%s:%s'\n", uToB->peak(), rtosc_argument_string(uToB->peak()));
  587. #if 0
  588. if(strstr(msg, "PFMVelocity"))
  589. dump_msg(msg);
  590. if(ports.apropos(msg))
  591. fprintf(stderr, " -> best match: '%s'\n", ports.apropos(msg)->name);
  592. if(ports.apropos(msg+1))
  593. fprintf(stderr, " -> best match: '%s'\n", ports.apropos(msg+1)->name);
  594. #endif
  595. fprintf(stderr, "%c[%d;%d;%dm", 0x1B, 0, 7 + 30, 0 + 40);
  596. }
  597. }
  598. if(events>1 && false)
  599. fprintf(stderr, "backend: %d events per cycle\n",events);
  600. //Swaps the Left channel with Right Channel
  601. if(swaplr)
  602. swap(outl, outr);
  603. //clean up the output samples (should not be needed?)
  604. memset(outl, 0, synth.bufferbytes);
  605. memset(outr, 0, synth.bufferbytes);
  606. //Compute part samples and store them part[npart]->partoutl,partoutr
  607. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  608. if(part[npart]->Penabled)
  609. part[npart]->ComputePartSmps();
  610. //Insertion effects
  611. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx)
  612. if(Pinsparts[nefx] >= 0) {
  613. int efxpart = Pinsparts[nefx];
  614. if(part[efxpart]->Penabled)
  615. insefx[nefx]->out(part[efxpart]->partoutl,
  616. part[efxpart]->partoutr);
  617. }
  618. //Apply the part volumes and pannings (after insertion effects)
  619. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  620. if(!part[npart]->Penabled)
  621. continue;
  622. Stereo<float> newvol(part[npart]->volume),
  623. oldvol(part[npart]->oldvolumel,
  624. part[npart]->oldvolumer);
  625. float pan = part[npart]->panning;
  626. if(pan < 0.5f)
  627. newvol.l *= pan * 2.0f;
  628. else
  629. newvol.r *= (1.0f - pan) * 2.0f;
  630. //if(npart==0)
  631. //printf("[%d]vol = %f->%f\n", npart, oldvol.l, newvol.l);
  632. //the volume or the panning has changed and needs interpolation
  633. if(ABOVE_AMPLITUDE_THRESHOLD(oldvol.l, newvol.l)
  634. || ABOVE_AMPLITUDE_THRESHOLD(oldvol.r, newvol.r)) {
  635. for(int i = 0; i < synth.buffersize; ++i) {
  636. Stereo<float> vol(INTERPOLATE_AMPLITUDE(oldvol.l, newvol.l,
  637. i, synth.buffersize),
  638. INTERPOLATE_AMPLITUDE(oldvol.r, newvol.r,
  639. i, synth.buffersize));
  640. part[npart]->partoutl[i] *= vol.l;
  641. part[npart]->partoutr[i] *= vol.r;
  642. }
  643. part[npart]->oldvolumel = newvol.l;
  644. part[npart]->oldvolumer = newvol.r;
  645. }
  646. else {
  647. for(int i = 0; i < synth.buffersize; ++i) { //the volume did not changed
  648. part[npart]->partoutl[i] *= newvol.l;
  649. part[npart]->partoutr[i] *= newvol.r;
  650. }
  651. }
  652. }
  653. //System effects
  654. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx) {
  655. if(sysefx[nefx]->geteffect() == 0)
  656. continue; //the effect is disabled
  657. float tmpmixl[synth.buffersize];
  658. float tmpmixr[synth.buffersize];
  659. //Clean up the samples used by the system effects
  660. memset(tmpmixl, 0, synth.bufferbytes);
  661. memset(tmpmixr, 0, synth.bufferbytes);
  662. //Mix the channels according to the part settings about System Effect
  663. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  664. //skip if the part has no output to effect
  665. if(Psysefxvol[nefx][npart] == 0)
  666. continue;
  667. //skip if the part is disabled
  668. if(part[npart]->Penabled == 0)
  669. continue;
  670. //the output volume of each part to system effect
  671. const float vol = sysefxvol[nefx][npart];
  672. for(int i = 0; i < synth.buffersize; ++i) {
  673. tmpmixl[i] += part[npart]->partoutl[i] * vol;
  674. tmpmixr[i] += part[npart]->partoutr[i] * vol;
  675. }
  676. }
  677. // system effect send to next ones
  678. for(int nefxfrom = 0; nefxfrom < nefx; ++nefxfrom)
  679. if(Psysefxsend[nefxfrom][nefx] != 0) {
  680. const float vol = sysefxsend[nefxfrom][nefx];
  681. for(int i = 0; i < synth.buffersize; ++i) {
  682. tmpmixl[i] += sysefx[nefxfrom]->efxoutl[i] * vol;
  683. tmpmixr[i] += sysefx[nefxfrom]->efxoutr[i] * vol;
  684. }
  685. }
  686. sysefx[nefx]->out(tmpmixl, tmpmixr);
  687. //Add the System Effect to sound output
  688. const float outvol = sysefx[nefx]->sysefxgetvolume();
  689. for(int i = 0; i < synth.buffersize; ++i) {
  690. outl[i] += tmpmixl[i] * outvol;
  691. outr[i] += tmpmixr[i] * outvol;
  692. }
  693. }
  694. //Mix all parts
  695. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  696. if(part[npart]->Penabled) //only mix active parts
  697. for(int i = 0; i < synth.buffersize; ++i) { //the volume did not changed
  698. outl[i] += part[npart]->partoutl[i];
  699. outr[i] += part[npart]->partoutr[i];
  700. }
  701. //Insertion effects for Master Out
  702. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx)
  703. if(Pinsparts[nefx] == -2)
  704. insefx[nefx]->out(outl, outr);
  705. //Master Volume
  706. for(int i = 0; i < synth.buffersize; ++i) {
  707. outl[i] *= volume;
  708. outr[i] *= volume;
  709. }
  710. vuUpdate(outl, outr);
  711. //Shutup if it is asked (with fade-out)
  712. if(shutup) {
  713. for(int i = 0; i < synth.buffersize; ++i) {
  714. float tmp = (synth.buffersize_f - i) / synth.buffersize_f;
  715. outl[i] *= tmp;
  716. outr[i] *= tmp;
  717. }
  718. ShutUp();
  719. }
  720. //update the global frame timer
  721. time++;
  722. }
  723. //TODO review the respective code from yoshimi for this
  724. //If memory serves correctly, libsamplerate was used
  725. void Master::GetAudioOutSamples(size_t nsamples,
  726. unsigned samplerate,
  727. float *outl,
  728. float *outr)
  729. {
  730. off_t out_off = 0;
  731. //Fail when resampling rather than doing a poor job
  732. if(synth.samplerate != samplerate) {
  733. printf("darn it: %d vs %d\n", synth.samplerate, samplerate);
  734. return;
  735. }
  736. while(nsamples) {
  737. //use all available samples
  738. if(nsamples >= smps) {
  739. memcpy(outl + out_off, bufl + off, sizeof(float) * smps);
  740. memcpy(outr + out_off, bufr + off, sizeof(float) * smps);
  741. nsamples -= smps;
  742. //generate samples
  743. AudioOut(bufl, bufr);
  744. off = 0;
  745. out_off += smps;
  746. smps = synth.buffersize;
  747. }
  748. else { //use some samples
  749. memcpy(outl + out_off, bufl + off, sizeof(float) * nsamples);
  750. memcpy(outr + out_off, bufr + off, sizeof(float) * nsamples);
  751. smps -= nsamples;
  752. off += nsamples;
  753. nsamples = 0;
  754. }
  755. }
  756. }
  757. Master::~Master()
  758. {
  759. delete []bufl;
  760. delete []bufr;
  761. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  762. delete part[npart];
  763. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx)
  764. delete insefx[nefx];
  765. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx)
  766. delete sysefx[nefx];
  767. delete fft;
  768. delete memory;
  769. }
  770. /*
  771. * Parameter control
  772. */
  773. void Master::setPvolume(char Pvolume_)
  774. {
  775. Pvolume = Pvolume_;
  776. volume = dB2rap((Pvolume - 96.0f) / 96.0f * 40.0f);
  777. }
  778. void Master::setPkeyshift(char Pkeyshift_)
  779. {
  780. Pkeyshift = Pkeyshift_;
  781. keyshift = (int)Pkeyshift - 64;
  782. }
  783. void Master::setPsysefxvol(int Ppart, int Pefx, char Pvol)
  784. {
  785. Psysefxvol[Pefx][Ppart] = Pvol;
  786. sysefxvol[Pefx][Ppart] = powf(0.1f, (1.0f - Pvol / 96.0f) * 2.0f);
  787. }
  788. void Master::setPsysefxsend(int Pefxfrom, int Pefxto, char Pvol)
  789. {
  790. Psysefxsend[Pefxfrom][Pefxto] = Pvol;
  791. sysefxsend[Pefxfrom][Pefxto] = powf(0.1f, (1.0f - Pvol / 96.0f) * 2.0f);
  792. }
  793. /*
  794. * Panic! (Clean up all parts and effects)
  795. */
  796. void Master::ShutUp()
  797. {
  798. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  799. part[npart]->cleanup();
  800. fakepeakpart[npart] = 0;
  801. }
  802. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx)
  803. insefx[nefx]->cleanup();
  804. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx)
  805. sysefx[nefx]->cleanup();
  806. vuresetpeaks();
  807. shutup = 0;
  808. }
  809. /*
  810. * Reset peaks and clear the "cliped" flag (for VU-meter)
  811. */
  812. void Master::vuresetpeaks()
  813. {
  814. vu.outpeakl = 1e-9;
  815. vu.outpeakr = 1e-9;
  816. vu.maxoutpeakl = 1e-9;
  817. vu.maxoutpeakr = 1e-9;
  818. vu.clipped = 0;
  819. }
  820. void Master::applyparameters(void)
  821. {
  822. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart)
  823. part[npart]->applyparameters();
  824. }
  825. void Master::initialize_rt(void)
  826. {
  827. for(int i=0; i<NUM_SYS_EFX; ++i)
  828. sysefx[i]->init();
  829. for(int i=0; i<NUM_INS_EFX; ++i)
  830. insefx[i]->init();
  831. for(int i=0; i<NUM_MIDI_PARTS; ++i)
  832. part[i]->initialize_rt();
  833. }
  834. void Master::add2XML(XMLwrapper *xml)
  835. {
  836. xml->addpar("volume", Pvolume);
  837. xml->addpar("key_shift", Pkeyshift);
  838. xml->addparbool("nrpn_receive", ctl.NRPN.receive);
  839. xml->beginbranch("MICROTONAL");
  840. microtonal.add2XML(xml);
  841. xml->endbranch();
  842. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  843. xml->beginbranch("PART", npart);
  844. part[npart]->add2XML(xml);
  845. xml->endbranch();
  846. }
  847. xml->beginbranch("SYSTEM_EFFECTS");
  848. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx) {
  849. xml->beginbranch("SYSTEM_EFFECT", nefx);
  850. xml->beginbranch("EFFECT");
  851. sysefx[nefx]->add2XML(xml);
  852. xml->endbranch();
  853. for(int pefx = 0; pefx < NUM_MIDI_PARTS; ++pefx) {
  854. xml->beginbranch("VOLUME", pefx);
  855. xml->addpar("vol", Psysefxvol[nefx][pefx]);
  856. xml->endbranch();
  857. }
  858. for(int tonefx = nefx + 1; tonefx < NUM_SYS_EFX; ++tonefx) {
  859. xml->beginbranch("SENDTO", tonefx);
  860. xml->addpar("send_vol", Psysefxsend[nefx][tonefx]);
  861. xml->endbranch();
  862. }
  863. xml->endbranch();
  864. }
  865. xml->endbranch();
  866. xml->beginbranch("INSERTION_EFFECTS");
  867. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx) {
  868. xml->beginbranch("INSERTION_EFFECT", nefx);
  869. xml->addpar("part", Pinsparts[nefx]);
  870. xml->beginbranch("EFFECT");
  871. insefx[nefx]->add2XML(xml);
  872. xml->endbranch();
  873. xml->endbranch();
  874. }
  875. xml->endbranch();
  876. }
  877. int Master::getalldata(char **data)
  878. {
  879. XMLwrapper *xml = new XMLwrapper();
  880. xml->beginbranch("MASTER");
  881. add2XML(xml);
  882. xml->endbranch();
  883. *data = xml->getXMLdata();
  884. delete (xml);
  885. return strlen(*data) + 1;
  886. }
  887. void Master::putalldata(const char *data)
  888. {
  889. XMLwrapper *xml = new XMLwrapper();
  890. if(!xml->putXMLdata(data)) {
  891. delete (xml);
  892. return;
  893. }
  894. if(xml->enterbranch("MASTER") == 0)
  895. return;
  896. getfromXML(xml);
  897. xml->exitbranch();
  898. delete (xml);
  899. }
  900. int Master::saveXML(const char *filename)
  901. {
  902. XMLwrapper *xml = new XMLwrapper();
  903. xml->beginbranch("MASTER");
  904. add2XML(xml);
  905. xml->endbranch();
  906. int result = xml->saveXMLfile(filename, gzip_compression);
  907. delete (xml);
  908. return result;
  909. }
  910. int Master::loadXML(const char *filename)
  911. {
  912. XMLwrapper *xml = new XMLwrapper();
  913. if(xml->loadXMLfile(filename) < 0) {
  914. delete (xml);
  915. return -1;
  916. }
  917. if(xml->enterbranch("MASTER") == 0)
  918. return -10;
  919. getfromXML(xml);
  920. xml->exitbranch();
  921. delete (xml);
  922. initialize_rt();
  923. return 0;
  924. }
  925. void Master::getfromXML(XMLwrapper *xml)
  926. {
  927. setPvolume(xml->getpar127("volume", Pvolume));
  928. setPkeyshift(xml->getpar127("key_shift", Pkeyshift));
  929. ctl.NRPN.receive = xml->getparbool("nrpn_receive", ctl.NRPN.receive);
  930. part[0]->Penabled = 0;
  931. for(int npart = 0; npart < NUM_MIDI_PARTS; ++npart) {
  932. if(xml->enterbranch("PART", npart) == 0)
  933. continue;
  934. part[npart]->getfromXML(xml);
  935. xml->exitbranch();
  936. }
  937. if(xml->enterbranch("MICROTONAL")) {
  938. microtonal.getfromXML(xml);
  939. xml->exitbranch();
  940. }
  941. sysefx[0]->changeeffect(0);
  942. if(xml->enterbranch("SYSTEM_EFFECTS")) {
  943. for(int nefx = 0; nefx < NUM_SYS_EFX; ++nefx) {
  944. if(xml->enterbranch("SYSTEM_EFFECT", nefx) == 0)
  945. continue;
  946. if(xml->enterbranch("EFFECT")) {
  947. sysefx[nefx]->getfromXML(xml);
  948. xml->exitbranch();
  949. }
  950. for(int partefx = 0; partefx < NUM_MIDI_PARTS; ++partefx) {
  951. if(xml->enterbranch("VOLUME", partefx) == 0)
  952. continue;
  953. setPsysefxvol(partefx, nefx,
  954. xml->getpar127("vol", Psysefxvol[partefx][nefx]));
  955. xml->exitbranch();
  956. }
  957. for(int tonefx = nefx + 1; tonefx < NUM_SYS_EFX; ++tonefx) {
  958. if(xml->enterbranch("SENDTO", tonefx) == 0)
  959. continue;
  960. setPsysefxsend(nefx, tonefx,
  961. xml->getpar127("send_vol",
  962. Psysefxsend[nefx][tonefx]));
  963. xml->exitbranch();
  964. }
  965. xml->exitbranch();
  966. }
  967. xml->exitbranch();
  968. }
  969. if(xml->enterbranch("INSERTION_EFFECTS")) {
  970. for(int nefx = 0; nefx < NUM_INS_EFX; ++nefx) {
  971. if(xml->enterbranch("INSERTION_EFFECT", nefx) == 0)
  972. continue;
  973. Pinsparts[nefx] = xml->getpar("part",
  974. Pinsparts[nefx],
  975. -2,
  976. NUM_MIDI_PARTS);
  977. if(xml->enterbranch("EFFECT")) {
  978. insefx[nefx]->getfromXML(xml);
  979. xml->exitbranch();
  980. }
  981. xml->exitbranch();
  982. }
  983. xml->exitbranch();
  984. }
  985. }