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.

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