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.

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