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.

1158 lines
36KB

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