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.

1123 lines
35KB

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