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.

1206 lines
36KB

  1. /*
  2. ZynAddSubFX - a software synthesizer
  3. Part.cpp - Part implementation
  4. Copyright (C) 2002-2005 Nasca Octavian Paul
  5. Author: Nasca Octavian Paul
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of version 2 of the GNU General Public License
  8. as published by the Free Software Foundation.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License (version 2 or later) for more details.
  13. You should have received a copy of the GNU General Public License (version 2)
  14. along with this program; if not, write to the Free Software Foundation,
  15. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  16. */
  17. #include "Part.h"
  18. #include "Microtonal.h"
  19. #include "Util.h"
  20. #include "XMLwrapper.h"
  21. #include "Allocator.h"
  22. #include "../Effects/EffectMgr.h"
  23. #include "../Params/ADnoteParameters.h"
  24. #include "../Params/SUBnoteParameters.h"
  25. #include "../Params/PADnoteParameters.h"
  26. #include "../Synth/Resonance.h"
  27. #include "../Synth/SynthNote.h"
  28. #include "../Synth/ADnote.h"
  29. #include "../Synth/SUBnote.h"
  30. #include "../Synth/PADnote.h"
  31. #include "../DSP/FFTwrapper.h"
  32. #include "../Misc/Util.h"
  33. #include <cstdlib>
  34. #include <cstdio>
  35. #include <cstring>
  36. #include <cassert>
  37. #include <rtosc/ports.h>
  38. #include <rtosc/port-sugar.h>
  39. #include <iostream>
  40. using rtosc::Ports;
  41. using rtosc::RtData;
  42. #define rObject Part
  43. static const Ports partPorts = {
  44. rRecurs(kit, 16, "Kit"),//NUM_KIT_ITEMS
  45. rRecursp(partefx, 3, "Part Effect"),
  46. rRecur(ctl, "Controller"),
  47. rToggle(Penabled, "Part enable"),
  48. #undef rChangeCb
  49. #define rChangeCb obj->setPvolume(obj->Pvolume);
  50. rParamZyn(Pvolume, "Part Volume"),
  51. #undef rChangeCb
  52. #define rChangeCb obj->setPpanning(obj->Ppanning);
  53. rParamZyn(Ppanning, "Set Panning"),
  54. #undef rChangeCb
  55. #define rChangeCb obj->setkeylimit(obj->Pkeylimit);
  56. rParamI(Pkeylimit, rProp(parameter), rMap(min,0), rMap(max, POLYPHONY), "Key limit per part"),
  57. #undef rChangeCb
  58. #define rChangeCb
  59. rParamZyn(Pminkey, "Min Used Key"),
  60. rParamZyn(Pmaxkey, "Max Used Key"),
  61. rParamZyn(Pkeyshift, "Part keyshift"),
  62. rParamZyn(Prcvchn, "Active MIDI channel"),
  63. rParamZyn(Pvelsns, "Velocity sensing"),
  64. rParamZyn(Pveloffs, "Velocity offset"),
  65. rToggle(Pnoteon, "If the channel accepts note on events"),
  66. rOption(Pkitmode, rOptions(Off, Multi-Kit, Single-Kit), "Kit mode/enable\n"
  67. "Off - Only the first kit is ever utilized\n"
  68. "Multi-kit - Every applicable kit is run for a note\n"
  69. "Single-kit - The first applicable kit is run for a given note"),
  70. rToggle(Pdrummode, "Drum mode enable\n"
  71. "When drum mode is enabled all keys are mapped to 12tET and legato is disabled"),
  72. rToggle(Ppolymode, "Polyphony mode"),
  73. rToggle(Plegatomode, "Legato mode"),
  74. rParamZyn(info.Ptype, "Class of Instrument"),
  75. rString(info.Pauthor, MAX_INFO_TEXT_SIZE, "Instrument author"),
  76. rString(info.Pcomments, MAX_INFO_TEXT_SIZE, "Instrument comments"),
  77. rString(Pname, PART_MAX_NAME_LEN, "User specified label"),
  78. rArray(Pefxroute, NUM_PART_EFX, "Effect Routing"),
  79. rArrayT(Pefxbypass, NUM_PART_EFX, "If an effect is bypassed"),
  80. {"captureMin:", rDoc("Capture minimum valid note"), NULL,
  81. [](const char *, RtData &r)
  82. {Part *p = (Part*)r.obj; p->Pminkey = p->lastnote;}},
  83. {"captureMax:", rDoc("Capture maximum valid note"), NULL,
  84. [](const char *, RtData &r)
  85. {Part *p = (Part*)r.obj; p->Pmaxkey = p->lastnote;}},
  86. {"polyType::c:i", rProp(parameter) rOptions(Polyphonic, Monophonic, Legato)
  87. rDoc("Synthesis polyphony type\n"
  88. "Polyphonic - Each note is played independently\n"
  89. "Monophonic - A single note is played at a time with"
  90. " envelopes resetting between notes\n"
  91. "Legato - A single note is played at a time without"
  92. " envelopes resetting between notes\n"
  93. ), NULL,
  94. [](const char *msg, RtData &d)
  95. {
  96. Part *p = (Part*)d.obj;
  97. if(!rtosc_narguments(msg)) {
  98. int res = 0;
  99. if(!p->Ppolymode)
  100. res = p->Plegatomode ? 2 : 1;
  101. d.reply(d.loc, "c", res);
  102. return;
  103. }
  104. int i = rtosc_argument(msg, 0).i;
  105. if(i == 0) {
  106. p->Ppolymode = 1;
  107. p->Plegatomode = 0;
  108. } else if(i==1) {
  109. p->Ppolymode = 0;
  110. p->Plegatomode = 0;
  111. } else {
  112. p->Ppolymode = 0;
  113. p->Plegatomode = 1;
  114. }}},
  115. {"clear:", rProp(internal) rDoc("Reset Part To Defaults"), 0,
  116. [](const char *, RtData &d)
  117. {
  118. //XXX todo forward this event for middleware to handle
  119. //Part *p = (Part*)d.obj;
  120. //p->defaults();
  121. //char part_loc[128];
  122. //strcpy(part_loc, d.loc);
  123. //char *end = strrchr(part_loc, '/');
  124. //if(end)
  125. // end[1] = 0;
  126. //d.broadcast("/damage", "s", part_loc);
  127. }},
  128. //{"kit#16::T:F", "::Enables or disables kit item", 0,
  129. // [](const char *m, RtData &d) {
  130. // auto loc = d.loc;
  131. // Part *p = (Part*)d.obj;
  132. // unsigned kitid = -1;
  133. // //Note that this event will be captured before transmitted, thus
  134. // //reply/broadcast don't matter
  135. // for(int i=0; i<NUM_KIT_ITEMS; ++i) {
  136. // d.reply("/middleware/oscil", "siisb", loc, kitid, i,
  137. // "oscil", sizeof(void*),
  138. // p->kit[kitid]->adpars->voice[i]->OscilSmp);
  139. // d.reply("/middleware/oscil", "siisb", loc, kitid, i, "oscil-mod"
  140. // sizeof(void*),
  141. // p->kit[kitid]->adpars->voice[i]->somethingelse);
  142. // }
  143. // d.reply("/middleware/pad", "sib", loc, kitid,
  144. // sizeof(PADnoteParameters*),
  145. // p->kit[kitid]->padpars)
  146. // }}
  147. };
  148. #undef rObject
  149. #define rObject Part::Kit
  150. static const Ports kitPorts = {
  151. rRecurp(padpars, "Padnote parameters"),
  152. rRecurp(adpars, "Adnote parameters"),
  153. rRecurp(subpars, "Adnote parameters"),
  154. rToggle(Penabled, "Kit item enable"),
  155. rToggle(Pmuted, "Kit item mute"),
  156. rParamZyn(Pminkey, "Kit item min key"),
  157. rParamZyn(Pmaxkey, "Kit item max key"),
  158. rToggle(Padenabled, "ADsynth enable"),
  159. rToggle(Psubenabled, "SUBsynth enable"),
  160. rToggle(Ppadenabled, "PADsynth enable"),
  161. rParamZyn(Psendtoparteffect, "Effect Levels"),
  162. rString(Pname, PART_MAX_NAME_LEN, "Kit User Specified Label"),
  163. {"captureMin:", rDoc("Capture minimum valid note"), NULL,
  164. [](const char *, RtData &r)
  165. {Part::Kit *p = (Part::Kit*)r.obj; p->Pminkey = p->parent->lastnote;}},
  166. {"captureMax:", rDoc("Capture maximum valid note"), NULL, [](const char *, RtData &r)
  167. {Part::Kit *p = (Part::Kit*)r.obj; p->Pmaxkey = p->parent->lastnote;}},
  168. {"padpars-data:b", rProp(internal) rDoc("Set PADsynth data pointer"), 0,
  169. [](const char *msg, RtData &d) {
  170. rObject &o = *(rObject*)d.obj;
  171. assert(o.padpars == NULL);
  172. o.padpars = *(decltype(o.padpars)*)rtosc_argument(msg, 0).b.data;
  173. }},
  174. {"adpars-data:b", rProp(internal) rDoc("Set ADsynth data pointer"), 0,
  175. [](const char *msg, RtData &d) {
  176. rObject &o = *(rObject*)d.obj;
  177. assert(o.adpars == NULL);
  178. o.adpars = *(decltype(o.adpars)*)rtosc_argument(msg, 0).b.data;
  179. }},
  180. {"subpars-data:b", rProp(internal) rDoc("Set SUBsynth data pointer"), 0,
  181. [](const char *msg, RtData &d) {
  182. rObject &o = *(rObject*)d.obj;
  183. assert(o.subpars == NULL);
  184. o.subpars = *(decltype(o.subpars)*)rtosc_argument(msg, 0).b.data;
  185. }},
  186. };
  187. const Ports &Part::Kit::ports = kitPorts;
  188. const Ports &Part::ports = partPorts;
  189. Part::Part(Allocator &alloc, const SYNTH_T &synth_, const AbsTime &time_,
  190. const int &gzip_compression, const int &interpolation,
  191. Microtonal *microtonal_, FFTwrapper *fft_)
  192. :Pdrummode(false),
  193. Ppolymode(true),
  194. Plegatomode(false),
  195. partoutl(new float[synth_.buffersize]),
  196. partoutr(new float[synth_.buffersize]),
  197. ctl(synth_, &time_),
  198. microtonal(microtonal_),
  199. fft(fft_),
  200. memory(alloc),
  201. synth(synth_),
  202. time(time_),
  203. gzip_compression(gzip_compression),
  204. interpolation(interpolation)
  205. {
  206. monomemClear();
  207. for(int n = 0; n < NUM_KIT_ITEMS; ++n) {
  208. kit[n].parent = this;
  209. kit[n].Pname = new char [PART_MAX_NAME_LEN];
  210. kit[n].adpars = nullptr;
  211. kit[n].subpars = nullptr;
  212. kit[n].padpars = nullptr;
  213. }
  214. kit[0].adpars = new ADnoteParameters(synth, fft, &time);
  215. //Part's Insertion Effects init
  216. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx) {
  217. partefx[nefx] = new EffectMgr(memory, synth, 1, &time);
  218. Pefxbypass[nefx] = false;
  219. }
  220. assert(partefx[0]);
  221. for(int n = 0; n < NUM_PART_EFX + 1; ++n) {
  222. partfxinputl[n] = new float [synth.buffersize];
  223. partfxinputr[n] = new float [synth.buffersize];
  224. }
  225. killallnotes = false;
  226. oldfreq = -1.0f;
  227. cleanup();
  228. Pname = new char[PART_MAX_NAME_LEN];
  229. oldvolumel = oldvolumer = 0.5f;
  230. lastnote = -1;
  231. defaults();
  232. assert(partefx[0]);
  233. }
  234. Part::Kit::Kit(void)
  235. :parent(nullptr),
  236. Penabled(false), Pmuted(false),
  237. Pminkey(0), Pmaxkey(127),
  238. Pname(nullptr),
  239. Padenabled(false), Psubenabled(false),
  240. Ppadenabled(false), Psendtoparteffect(0),
  241. adpars(nullptr), subpars(nullptr), padpars(nullptr)
  242. {
  243. }
  244. void Part::cloneTraits(Part &p) const
  245. {
  246. #define CLONE(x) p.x = this->x
  247. CLONE(Penabled);
  248. p.setPvolume(this->Pvolume);
  249. p.setPpanning(this->Ppanning);
  250. CLONE(Pminkey);
  251. CLONE(Pmaxkey);
  252. CLONE(Pkeyshift);
  253. CLONE(Prcvchn);
  254. CLONE(Pvelsns);
  255. CLONE(Pveloffs);
  256. CLONE(Pnoteon);
  257. CLONE(Ppolymode);
  258. CLONE(Plegatomode);
  259. CLONE(Pkeylimit);
  260. CLONE(ctl);
  261. }
  262. void Part::defaults()
  263. {
  264. Penabled = 0;
  265. Pminkey = 0;
  266. Pmaxkey = 127;
  267. Pnoteon = 1;
  268. Ppolymode = 1;
  269. Plegatomode = 0;
  270. setPvolume(96);
  271. Pkeyshift = 64;
  272. Prcvchn = 0;
  273. setPpanning(64);
  274. Pvelsns = 64;
  275. Pveloffs = 64;
  276. Pkeylimit = 15;
  277. defaultsinstrument();
  278. ctl.defaults();
  279. }
  280. void Part::defaultsinstrument()
  281. {
  282. ZERO(Pname, PART_MAX_NAME_LEN);
  283. info.Ptype = 0;
  284. ZERO(info.Pauthor, MAX_INFO_TEXT_SIZE + 1);
  285. ZERO(info.Pcomments, MAX_INFO_TEXT_SIZE + 1);
  286. Pkitmode = 0;
  287. Pdrummode = 0;
  288. for(int n = 0; n < NUM_KIT_ITEMS; ++n) {
  289. //kit[n].Penabled = false;
  290. kit[n].Pmuted = false;
  291. kit[n].Pminkey = 0;
  292. kit[n].Pmaxkey = 127;
  293. kit[n].Padenabled = false;
  294. kit[n].Psubenabled = false;
  295. kit[n].Ppadenabled = false;
  296. ZERO(kit[n].Pname, PART_MAX_NAME_LEN);
  297. kit[n].Psendtoparteffect = 0;
  298. if(n != 0)
  299. setkititemstatus(n, 0);
  300. }
  301. kit[0].Penabled = 1;
  302. kit[0].Padenabled = 1;
  303. kit[0].adpars->defaults();
  304. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx) {
  305. partefx[nefx]->defaults();
  306. Pefxroute[nefx] = 0; //route to next effect
  307. }
  308. }
  309. /*
  310. * Cleanup the part
  311. */
  312. void Part::cleanup(bool final_)
  313. {
  314. notePool.killAllNotes();
  315. for(int i = 0; i < synth.buffersize; ++i) {
  316. partoutl[i] = final_ ? 0.0f : synth.denormalkillbuf[i];
  317. partoutr[i] = final_ ? 0.0f : synth.denormalkillbuf[i];
  318. }
  319. ctl.resetall();
  320. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx)
  321. partefx[nefx]->cleanup();
  322. for(int n = 0; n < NUM_PART_EFX + 1; ++n)
  323. for(int i = 0; i < synth.buffersize; ++i) {
  324. partfxinputl[n][i] = final_ ? 0.0f : synth.denormalkillbuf[i];
  325. partfxinputr[n][i] = final_ ? 0.0f : synth.denormalkillbuf[i];
  326. }
  327. }
  328. Part::~Part()
  329. {
  330. cleanup(true);
  331. for(int n = 0; n < NUM_KIT_ITEMS; ++n) {
  332. delete kit[n].adpars;
  333. delete kit[n].subpars;
  334. delete kit[n].padpars;
  335. delete [] kit[n].Pname;
  336. }
  337. delete [] Pname;
  338. delete [] partoutl;
  339. delete [] partoutr;
  340. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx)
  341. delete partefx[nefx];
  342. for(int n = 0; n < NUM_PART_EFX + 1; ++n) {
  343. delete [] partfxinputl[n];
  344. delete [] partfxinputr[n];
  345. }
  346. }
  347. static void assert_kit_sanity(const Part::Kit *kits)
  348. {
  349. for(int i=0; i<NUM_KIT_ITEMS; ++i) {
  350. //an enabled kit must have a corresponding parameter object
  351. assert(!kits[i].Padenabled || kits[i].adpars);
  352. assert(!kits[i].Ppadenabled || kits[i].padpars);
  353. assert(!kits[i].Psubenabled || kits[i].subpars);
  354. }
  355. }
  356. static int kit_usage(const Part::Kit *kits, int note, int mode)
  357. {
  358. const bool non_kit = mode == 0;
  359. const bool singl_kit = mode == 2;
  360. int synth_usage = 0;
  361. for(uint8_t i = 0; i < NUM_KIT_ITEMS; ++i) {
  362. const auto &item = kits[i];
  363. if(!non_kit && !item.validNote(note))
  364. continue;
  365. synth_usage += item.Padenabled;
  366. synth_usage += item.Psubenabled;
  367. synth_usage += item.Ppadenabled;
  368. //Partial Kit Use
  369. if(non_kit || (singl_kit && item.active()))
  370. break;
  371. }
  372. return synth_usage;
  373. }
  374. /*
  375. * Note On Messages
  376. */
  377. bool Part::NoteOn(unsigned char note,
  378. unsigned char velocity,
  379. int masterkeyshift)
  380. {
  381. //Verify Basic Mode and sanity
  382. const bool isRunningNote = notePool.existsRunningNote();
  383. const bool doingLegato = isRunningNote && isLegatoMode() &&
  384. lastlegatomodevalid;
  385. if(!Pnoteon || !inRange(note, Pminkey, Pmaxkey) || notePool.full() ||
  386. notePool.synthFull(kit_usage(kit, note, Pkitmode)))
  387. return false;
  388. verifyKeyMode();
  389. assert_kit_sanity(kit);
  390. //Preserve Note Stack
  391. if(isMonoMode() || isLegatoMode()) {
  392. monomemPush(note);
  393. monomem[note].velocity = velocity;
  394. monomem[note].mkeyshift = masterkeyshift;
  395. } else if(!monomemEmpty())
  396. monomemClear();
  397. //Mono/Legato Release old notes
  398. if(isMonoMode() || (isLegatoMode() && !doingLegato))
  399. notePool.releasePlayingNotes();
  400. lastlegatomodevalid = isLegatoMode();
  401. //Compute Note Parameters
  402. const float vel = getVelocity(velocity, Pvelsns, Pveloffs);
  403. const int partkeyshift = (int)Pkeyshift - 64;
  404. const int keyshift = masterkeyshift + partkeyshift;
  405. const float notebasefreq = getBaseFreq(note, keyshift);
  406. if(notebasefreq < 0)
  407. return false;
  408. //Portamento
  409. lastnote = note;
  410. if(oldfreq < 1.0f)
  411. oldfreq = notebasefreq;//this is only the first note is played
  412. // For Mono/Legato: Force Portamento Off on first
  413. // notes. That means it is required that the previous note is
  414. // still held down or sustained for the Portamento to activate
  415. // (that's like Legato).
  416. bool portamento = false;
  417. if(Ppolymode || isRunningNote)
  418. portamento = ctl.initportamento(oldfreq, notebasefreq, doingLegato);
  419. oldfreq = notebasefreq;
  420. //Adjust Existing Notes
  421. if(doingLegato) {
  422. LegatoParams pars = {notebasefreq, vel, portamento, note, true};
  423. notePool.applyLegato(pars);
  424. return true;
  425. }
  426. if(Ppolymode)
  427. notePool.makeUnsustainable(note);
  428. //Create New Notes
  429. for(uint8_t i = 0; i < NUM_KIT_ITEMS; ++i) {
  430. auto &item = kit[i];
  431. if(Pkitmode != 0 && !item.validNote(note))
  432. continue;
  433. SynthParams pars{memory, ctl, synth, time, notebasefreq, vel,
  434. portamento, note, false};
  435. const int sendto = Pkitmode ? item.sendto() : 0;
  436. try {
  437. if(item.Padenabled)
  438. notePool.insertNote(note, sendto,
  439. {memory.alloc<ADnote>(kit[i].adpars, pars), 0, i});
  440. if(item.Psubenabled)
  441. notePool.insertNote(note, sendto,
  442. {memory.alloc<SUBnote>(kit[i].subpars, pars), 1, i});
  443. if(item.Ppadenabled)
  444. notePool.insertNote(note, sendto,
  445. {memory.alloc<PADnote>(kit[i].padpars, pars, interpolation), 2, i});
  446. } catch (std::bad_alloc & ba) {
  447. std::cerr << "dropped new note: " << ba.what() << std::endl;
  448. }
  449. //Partial Kit Use
  450. if(isNonKit() || (isSingleKit() && item.active()))
  451. break;
  452. }
  453. if(isLegatoMode())
  454. notePool.upgradeToLegato();
  455. //Enforce the key limit
  456. setkeylimit(Pkeylimit);
  457. return true;
  458. }
  459. /*
  460. * Note Off Messages
  461. */
  462. void Part::NoteOff(unsigned char note) //release the key
  463. {
  464. // This note is released, so we remove it from the list.
  465. if(!monomemEmpty())
  466. monomemPop(note);
  467. for(auto &desc:notePool.activeDesc()) {
  468. if(desc.note != note || !desc.playing())
  469. continue;
  470. if(!ctl.sustain.sustain) { //the sustain pedal is not pushed
  471. if((isMonoMode() || isLegatoMode()) && !monomemEmpty())
  472. MonoMemRenote();//Play most recent still active note
  473. else
  474. notePool.release(desc);
  475. }
  476. else { //the sustain pedal is pushed
  477. if(desc.canSustain())
  478. desc.doSustain();
  479. else
  480. notePool.release(desc);
  481. }
  482. }
  483. }
  484. void Part::PolyphonicAftertouch(unsigned char note,
  485. unsigned char velocity,
  486. int masterkeyshift)
  487. {
  488. (void) masterkeyshift;
  489. if(!Pnoteon || !inRange(note, Pminkey, Pmaxkey) || Pdrummode)
  490. return;
  491. // MonoMem stuff:
  492. if(!Ppolymode) // if Poly is off
  493. monomem[note].velocity = velocity; // Store this note's velocity.
  494. const float vel = getVelocity(velocity, Pvelsns, Pveloffs);
  495. for(auto &d:notePool.activeDesc()) {
  496. if(d.note == note && d.playing())
  497. for(auto &s:notePool.activeNotes(d))
  498. s.note->setVelocity(vel);
  499. }
  500. }
  501. /*
  502. * Controllers
  503. */
  504. void Part::SetController(unsigned int type, int par)
  505. {
  506. switch(type) {
  507. case C_pitchwheel:
  508. ctl.setpitchwheel(par);
  509. break;
  510. case C_expression:
  511. ctl.setexpression(par);
  512. setPvolume(Pvolume); //update the volume
  513. break;
  514. case C_portamento:
  515. ctl.setportamento(par);
  516. break;
  517. case C_panning:
  518. ctl.setpanning(par);
  519. setPpanning(Ppanning); //update the panning
  520. break;
  521. case C_filtercutoff:
  522. ctl.setfiltercutoff(par);
  523. break;
  524. case C_filterq:
  525. ctl.setfilterq(par);
  526. break;
  527. case C_bandwidth:
  528. ctl.setbandwidth(par);
  529. break;
  530. case C_modwheel:
  531. ctl.setmodwheel(par);
  532. break;
  533. case C_fmamp:
  534. ctl.setfmamp(par);
  535. break;
  536. case C_volume:
  537. ctl.setvolume(par);
  538. if(ctl.volume.receive != 0)
  539. volume = ctl.volume.volume;
  540. else
  541. setPvolume(Pvolume);
  542. break;
  543. case C_sustain:
  544. ctl.setsustain(par);
  545. if(ctl.sustain.sustain == 0)
  546. ReleaseSustainedKeys();
  547. break;
  548. case C_allsoundsoff:
  549. AllNotesOff(); //Panic
  550. break;
  551. case C_resetallcontrollers:
  552. ctl.resetall();
  553. ReleaseSustainedKeys();
  554. if(ctl.volume.receive != 0)
  555. volume = ctl.volume.volume;
  556. else
  557. setPvolume(Pvolume);
  558. setPvolume(Pvolume); //update the volume
  559. setPpanning(Ppanning); //update the panning
  560. for(int item = 0; item < NUM_KIT_ITEMS; ++item) {
  561. if(kit[item].adpars == NULL)
  562. continue;
  563. kit[item].adpars->GlobalPar.Reson->
  564. sendcontroller(C_resonance_center, 1.0f);
  565. kit[item].adpars->GlobalPar.Reson->
  566. sendcontroller(C_resonance_bandwidth, 1.0f);
  567. }
  568. //more update to add here if I add controllers
  569. break;
  570. case C_allnotesoff:
  571. ReleaseAllKeys();
  572. break;
  573. case C_resonance_center:
  574. ctl.setresonancecenter(par);
  575. for(int item = 0; item < NUM_KIT_ITEMS; ++item) {
  576. if(kit[item].adpars == NULL)
  577. continue;
  578. kit[item].adpars->GlobalPar.Reson->
  579. sendcontroller(C_resonance_center,
  580. ctl.resonancecenter.relcenter);
  581. }
  582. break;
  583. case C_resonance_bandwidth:
  584. ctl.setresonancebw(par);
  585. kit[0].adpars->GlobalPar.Reson->
  586. sendcontroller(C_resonance_bandwidth, ctl.resonancebandwidth.relbw);
  587. break;
  588. }
  589. }
  590. /*
  591. * Release the sustained keys
  592. */
  593. void Part::ReleaseSustainedKeys()
  594. {
  595. // Let's call MonoMemRenote() on some conditions:
  596. if((isMonoMode() || isLegatoMode()) && !monomemEmpty())
  597. if(monomemBack() != lastnote) // Sustain controller manipulation would cause repeated same note respawn without this check.
  598. MonoMemRenote(); // To play most recent still held note.
  599. for(auto &d:notePool.activeDesc())
  600. if(d.sustained())
  601. for(auto &s:notePool.activeNotes(d))
  602. s.note->releasekey();
  603. }
  604. /*
  605. * Release all keys
  606. */
  607. void Part::ReleaseAllKeys()
  608. {
  609. for(auto &d:notePool.activeDesc())
  610. if(!d.released())
  611. for(auto &s:notePool.activeNotes(d))
  612. s.note->releasekey();
  613. }
  614. // Call NoteOn(...) with the most recent still held key as new note
  615. // (Made for Mono/Legato).
  616. void Part::MonoMemRenote()
  617. {
  618. unsigned char mmrtempnote = monomemBack(); // Last list element.
  619. monomemPop(mmrtempnote); // We remove it, will be added again in NoteOn(...).
  620. NoteOn(mmrtempnote, monomem[mmrtempnote].velocity,
  621. monomem[mmrtempnote].mkeyshift);
  622. }
  623. float Part::getBaseFreq(int note, int keyshift) const
  624. {
  625. if(Pdrummode)
  626. return 440.0f * powf(2.0f, (note - 69.0f) / 12.0f);
  627. else
  628. return microtonal->getnotefreq(note, keyshift);
  629. }
  630. float Part::getVelocity(uint8_t velocity, uint8_t velocity_sense,
  631. uint8_t velocity_offset) const
  632. {
  633. //compute sense function
  634. const float vel = VelF(velocity / 127.0f, velocity_sense);
  635. //compute the velocity offset
  636. return limit(vel + (velocity_offset - 64.0f) / 64.0f, 0.0f, 1.0f);
  637. }
  638. void Part::verifyKeyMode(void)
  639. {
  640. if(Plegatomode && !Pdrummode && Ppolymode) {
  641. fprintf(stderr,
  642. "WARNING: Poly & Legato modes are On, that shouldn't happen\n"
  643. "Disabling Legato mode...\n"
  644. "(Part.cpp::NoteOn(..))\n");
  645. Plegatomode = 0;
  646. }
  647. }
  648. /*
  649. * Set Part's key limit
  650. */
  651. void Part::setkeylimit(unsigned char Pkeylimit_)
  652. {
  653. Pkeylimit = Pkeylimit_;
  654. int keylimit = Pkeylimit;
  655. if(keylimit == 0)
  656. keylimit = POLYPHONY - 5;
  657. if(notePool.getRunningNotes() >= keylimit)
  658. notePool.enforceKeyLimit(keylimit);
  659. }
  660. /*
  661. * Prepare all notes to be turned off
  662. */
  663. void Part::AllNotesOff()
  664. {
  665. killallnotes = true;
  666. }
  667. /*
  668. * Compute Part samples and store them in the partoutl[] and partoutr[]
  669. */
  670. void Part::ComputePartSmps()
  671. {
  672. assert(partefx[0]);
  673. for(unsigned nefx = 0; nefx < NUM_PART_EFX + 1; ++nefx) {
  674. memset(partfxinputl[nefx], 0, synth.bufferbytes);
  675. memset(partfxinputr[nefx], 0, synth.bufferbytes);
  676. }
  677. for(auto &d:notePool.activeDesc()) {
  678. d.age++;
  679. for(auto &s:notePool.activeNotes(d)) {
  680. float tmpoutr[synth.buffersize];
  681. float tmpoutl[synth.buffersize];
  682. auto &note = *s.note;
  683. note.noteout(&tmpoutl[0], &tmpoutr[0]);
  684. for(int i = 0; i < synth.buffersize; ++i) { //add the note to part(mix)
  685. partfxinputl[d.sendto][i] += tmpoutl[i];
  686. partfxinputr[d.sendto][i] += tmpoutr[i];
  687. }
  688. if(note.finished())
  689. notePool.kill(s);
  690. }
  691. }
  692. //Apply part's effects and mix them
  693. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx) {
  694. if(!Pefxbypass[nefx]) {
  695. partefx[nefx]->out(partfxinputl[nefx], partfxinputr[nefx]);
  696. if(Pefxroute[nefx] == 2)
  697. for(int i = 0; i < synth.buffersize; ++i) {
  698. partfxinputl[nefx + 1][i] += partefx[nefx]->efxoutl[i];
  699. partfxinputr[nefx + 1][i] += partefx[nefx]->efxoutr[i];
  700. }
  701. }
  702. int routeto = ((Pefxroute[nefx] == 0) ? nefx + 1 : NUM_PART_EFX);
  703. for(int i = 0; i < synth.buffersize; ++i) {
  704. partfxinputl[routeto][i] += partfxinputl[nefx][i];
  705. partfxinputr[routeto][i] += partfxinputr[nefx][i];
  706. }
  707. }
  708. for(int i = 0; i < synth.buffersize; ++i) {
  709. partoutl[i] = partfxinputl[NUM_PART_EFX][i];
  710. partoutr[i] = partfxinputr[NUM_PART_EFX][i];
  711. }
  712. if(killallnotes) {
  713. for(int i = 0; i < synth.buffersize; ++i) {
  714. float tmp = (synth.buffersize_f - i) / synth.buffersize_f;
  715. partoutl[i] *= tmp;
  716. partoutr[i] *= tmp;
  717. }
  718. notePool.killAllNotes();
  719. monomemClear();
  720. killallnotes = false;
  721. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx)
  722. partefx[nefx]->cleanup();
  723. }
  724. ctl.updateportamento();
  725. }
  726. /*
  727. * Parameter control
  728. */
  729. void Part::setPvolume(char Pvolume_)
  730. {
  731. Pvolume = Pvolume_;
  732. volume =
  733. dB2rap((Pvolume - 96.0f) / 96.0f * 40.0f) * ctl.expression.relvolume;
  734. }
  735. void Part::setPpanning(char Ppanning_)
  736. {
  737. Ppanning = Ppanning_;
  738. panning = limit(Ppanning / 127.0f + ctl.panning.pan, 0.0f, 1.0f);
  739. }
  740. /*
  741. * Enable or disable a kit item
  742. */
  743. void Part::setkititemstatus(unsigned kititem, bool Penabled_)
  744. {
  745. //nonexistent kit item and the first kit item is always enabled
  746. if((kititem == 0) || (kititem >= NUM_KIT_ITEMS))
  747. return;
  748. Kit &kkit = kit[kititem];
  749. //no need to update if
  750. if(kkit.Penabled == Penabled_)
  751. return;
  752. kkit.Penabled = Penabled_;
  753. if(!Penabled_) {
  754. delete kkit.adpars;
  755. delete kkit.subpars;
  756. delete kkit.padpars;
  757. kkit.adpars = nullptr;
  758. kkit.subpars = nullptr;
  759. kkit.padpars = nullptr;
  760. kkit.Pname[0] = '\0';
  761. notePool.killAllNotes();
  762. }
  763. else {
  764. //All parameters must be NULL in this case
  765. assert(!(kkit.adpars || kkit.subpars || kkit.padpars));
  766. kkit.adpars = new ADnoteParameters(synth, fft, &time);
  767. kkit.subpars = new SUBnoteParameters(&time);
  768. kkit.padpars = new PADnoteParameters(synth, fft, &time);
  769. }
  770. }
  771. void Part::add2XMLinstrument(XMLwrapper& xml)
  772. {
  773. xml.beginbranch("INFO");
  774. xml.addparstr("name", (char *)Pname);
  775. xml.addparstr("author", (char *)info.Pauthor);
  776. xml.addparstr("comments", (char *)info.Pcomments);
  777. xml.addpar("type", info.Ptype);
  778. xml.endbranch();
  779. xml.beginbranch("INSTRUMENT_KIT");
  780. xml.addpar("kit_mode", Pkitmode);
  781. xml.addparbool("drum_mode", Pdrummode);
  782. for(int i = 0; i < NUM_KIT_ITEMS; ++i) {
  783. xml.beginbranch("INSTRUMENT_KIT_ITEM", i);
  784. xml.addparbool("enabled", kit[i].Penabled);
  785. if(kit[i].Penabled != 0) {
  786. xml.addparstr("name", (char *)kit[i].Pname);
  787. xml.addparbool("muted", kit[i].Pmuted);
  788. xml.addpar("min_key", kit[i].Pminkey);
  789. xml.addpar("max_key", kit[i].Pmaxkey);
  790. xml.addpar("send_to_instrument_effect", kit[i].Psendtoparteffect);
  791. xml.addparbool("add_enabled", kit[i].Padenabled);
  792. if(kit[i].Padenabled && kit[i].adpars) {
  793. xml.beginbranch("ADD_SYNTH_PARAMETERS");
  794. kit[i].adpars->add2XML(xml);
  795. xml.endbranch();
  796. }
  797. xml.addparbool("sub_enabled", kit[i].Psubenabled);
  798. if(kit[i].Psubenabled && kit[i].subpars) {
  799. xml.beginbranch("SUB_SYNTH_PARAMETERS");
  800. kit[i].subpars->add2XML(xml);
  801. xml.endbranch();
  802. }
  803. xml.addparbool("pad_enabled", kit[i].Ppadenabled);
  804. if(kit[i].Ppadenabled && kit[i].padpars) {
  805. xml.beginbranch("PAD_SYNTH_PARAMETERS");
  806. kit[i].padpars->add2XML(xml);
  807. xml.endbranch();
  808. }
  809. }
  810. xml.endbranch();
  811. }
  812. xml.endbranch();
  813. xml.beginbranch("INSTRUMENT_EFFECTS");
  814. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx) {
  815. xml.beginbranch("INSTRUMENT_EFFECT", nefx);
  816. xml.beginbranch("EFFECT");
  817. partefx[nefx]->add2XML(xml);
  818. xml.endbranch();
  819. xml.addpar("route", Pefxroute[nefx]);
  820. partefx[nefx]->setdryonly(Pefxroute[nefx] == 2);
  821. xml.addparbool("bypass", Pefxbypass[nefx]);
  822. xml.endbranch();
  823. }
  824. xml.endbranch();
  825. }
  826. void Part::add2XML(XMLwrapper& xml)
  827. {
  828. //parameters
  829. xml.addparbool("enabled", Penabled);
  830. if((Penabled == 0) && (xml.minimal))
  831. return;
  832. xml.addpar("volume", Pvolume);
  833. xml.addpar("panning", Ppanning);
  834. xml.addpar("min_key", Pminkey);
  835. xml.addpar("max_key", Pmaxkey);
  836. xml.addpar("key_shift", Pkeyshift);
  837. xml.addpar("rcv_chn", Prcvchn);
  838. xml.addpar("velocity_sensing", Pvelsns);
  839. xml.addpar("velocity_offset", Pveloffs);
  840. xml.addparbool("note_on", Pnoteon);
  841. xml.addparbool("poly_mode", Ppolymode);
  842. xml.addpar("legato_mode", Plegatomode);
  843. xml.addpar("key_limit", Pkeylimit);
  844. xml.beginbranch("INSTRUMENT");
  845. add2XMLinstrument(xml);
  846. xml.endbranch();
  847. xml.beginbranch("CONTROLLER");
  848. ctl.add2XML(xml);
  849. xml.endbranch();
  850. }
  851. int Part::saveXML(const char *filename)
  852. {
  853. XMLwrapper xml;
  854. xml.beginbranch("INSTRUMENT");
  855. add2XMLinstrument(xml);
  856. xml.endbranch();
  857. int result = xml.saveXMLfile(filename, gzip_compression);
  858. return result;
  859. }
  860. int Part::loadXMLinstrument(const char *filename)
  861. {
  862. XMLwrapper xml;
  863. if(xml.loadXMLfile(filename) < 0) {
  864. return -1;
  865. }
  866. if(xml.enterbranch("INSTRUMENT") == 0)
  867. return -10;
  868. getfromXMLinstrument(xml);
  869. xml.exitbranch();
  870. return 0;
  871. }
  872. void Part::applyparameters(void)
  873. {
  874. applyparameters([]{return false;});
  875. }
  876. void Part::applyparameters(std::function<bool()> do_abort)
  877. {
  878. for(int n = 0; n < NUM_KIT_ITEMS; ++n)
  879. if(kit[n].Ppadenabled && kit[n].padpars)
  880. kit[n].padpars->applyparameters(do_abort);
  881. }
  882. void Part::initialize_rt(void)
  883. {
  884. for(int i=0; i<NUM_PART_EFX; ++i)
  885. partefx[i]->init();
  886. }
  887. void Part::kill_rt(void)
  888. {
  889. for(int i=0; i<NUM_PART_EFX; ++i)
  890. partefx[i]->kill();
  891. notePool.killAllNotes();
  892. }
  893. void Part::monomemPush(char note)
  894. {
  895. for(int i=0; i<256; ++i)
  896. if(monomemnotes[i]==note)
  897. return;
  898. for(int i=254;i>=0; --i)
  899. monomemnotes[i+1] = monomemnotes[i];
  900. monomemnotes[0] = note;
  901. }
  902. void Part::monomemPop(char note)
  903. {
  904. int note_pos=-1;
  905. for(int i=0; i<256; ++i)
  906. if(monomemnotes[i]==note)
  907. note_pos = i;
  908. if(note_pos != -1) {
  909. for(int i=note_pos; i<256; ++i)
  910. monomemnotes[i] = monomemnotes[i+1];
  911. monomemnotes[255] = -1;
  912. }
  913. }
  914. char Part::monomemBack(void) const
  915. {
  916. return monomemnotes[0];
  917. }
  918. bool Part::monomemEmpty(void) const
  919. {
  920. return monomemnotes[0] == -1;
  921. }
  922. void Part::monomemClear(void)
  923. {
  924. for(int i=0; i<256; ++i)
  925. monomemnotes[i] = -1;
  926. }
  927. void Part::getfromXMLinstrument(XMLwrapper& xml)
  928. {
  929. if(xml.enterbranch("INFO")) {
  930. xml.getparstr("name", (char *)Pname, PART_MAX_NAME_LEN);
  931. xml.getparstr("author", (char *)info.Pauthor, MAX_INFO_TEXT_SIZE);
  932. xml.getparstr("comments", (char *)info.Pcomments, MAX_INFO_TEXT_SIZE);
  933. info.Ptype = xml.getpar("type", info.Ptype, 0, 16);
  934. xml.exitbranch();
  935. }
  936. if(xml.enterbranch("INSTRUMENT_KIT")) {
  937. Pkitmode = xml.getpar127("kit_mode", Pkitmode);
  938. Pdrummode = xml.getparbool("drum_mode", Pdrummode);
  939. setkititemstatus(0, 0);
  940. for(int i = 0; i < NUM_KIT_ITEMS; ++i) {
  941. if(xml.enterbranch("INSTRUMENT_KIT_ITEM", i) == 0)
  942. continue;
  943. setkititemstatus(i, xml.getparbool("enabled", kit[i].Penabled));
  944. if(kit[i].Penabled == 0) {
  945. xml.exitbranch();
  946. continue;
  947. }
  948. xml.getparstr("name", (char *)kit[i].Pname, PART_MAX_NAME_LEN);
  949. kit[i].Pmuted = xml.getparbool("muted", kit[i].Pmuted);
  950. kit[i].Pminkey = xml.getpar127("min_key", kit[i].Pminkey);
  951. kit[i].Pmaxkey = xml.getpar127("max_key", kit[i].Pmaxkey);
  952. kit[i].Psendtoparteffect = xml.getpar127(
  953. "send_to_instrument_effect",
  954. kit[i].Psendtoparteffect);
  955. kit[i].Padenabled = xml.getparbool("add_enabled",
  956. kit[i].Padenabled);
  957. if(xml.enterbranch("ADD_SYNTH_PARAMETERS")) {
  958. if(!kit[i].adpars)
  959. kit[i].adpars = new ADnoteParameters(synth, fft, &time);
  960. kit[i].adpars->getfromXML(xml);
  961. xml.exitbranch();
  962. }
  963. kit[i].Psubenabled = xml.getparbool("sub_enabled",
  964. kit[i].Psubenabled);
  965. if(xml.enterbranch("SUB_SYNTH_PARAMETERS")) {
  966. if(!kit[i].subpars)
  967. kit[i].subpars = new SUBnoteParameters(&time);
  968. kit[i].subpars->getfromXML(xml);
  969. xml.exitbranch();
  970. }
  971. kit[i].Ppadenabled = xml.getparbool("pad_enabled",
  972. kit[i].Ppadenabled);
  973. if(xml.enterbranch("PAD_SYNTH_PARAMETERS")) {
  974. if(!kit[i].padpars)
  975. kit[i].padpars = new PADnoteParameters(synth, fft, &time);
  976. kit[i].padpars->getfromXML(xml);
  977. xml.exitbranch();
  978. }
  979. xml.exitbranch();
  980. }
  981. xml.exitbranch();
  982. }
  983. if(xml.enterbranch("INSTRUMENT_EFFECTS")) {
  984. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx) {
  985. if(xml.enterbranch("INSTRUMENT_EFFECT", nefx) == 0)
  986. continue;
  987. if(xml.enterbranch("EFFECT")) {
  988. partefx[nefx]->getfromXML(xml);
  989. xml.exitbranch();
  990. }
  991. Pefxroute[nefx] = xml.getpar("route",
  992. Pefxroute[nefx],
  993. 0,
  994. NUM_PART_EFX);
  995. partefx[nefx]->setdryonly(Pefxroute[nefx] == 2);
  996. Pefxbypass[nefx] = xml.getparbool("bypass", Pefxbypass[nefx]);
  997. xml.exitbranch();
  998. }
  999. xml.exitbranch();
  1000. }
  1001. }
  1002. void Part::getfromXML(XMLwrapper& xml)
  1003. {
  1004. Penabled = xml.getparbool("enabled", Penabled);
  1005. setPvolume(xml.getpar127("volume", Pvolume));
  1006. setPpanning(xml.getpar127("panning", Ppanning));
  1007. Pminkey = xml.getpar127("min_key", Pminkey);
  1008. Pmaxkey = xml.getpar127("max_key", Pmaxkey);
  1009. Pkeyshift = xml.getpar127("key_shift", Pkeyshift);
  1010. Prcvchn = xml.getpar127("rcv_chn", Prcvchn);
  1011. Pvelsns = xml.getpar127("velocity_sensing", Pvelsns);
  1012. Pveloffs = xml.getpar127("velocity_offset", Pveloffs);
  1013. Pnoteon = xml.getparbool("note_on", Pnoteon);
  1014. Ppolymode = xml.getparbool("poly_mode", Ppolymode);
  1015. Plegatomode = xml.getparbool("legato_mode", Plegatomode); //older versions
  1016. if(!Plegatomode)
  1017. Plegatomode = xml.getpar127("legato_mode", Plegatomode);
  1018. Pkeylimit = xml.getpar127("key_limit", Pkeylimit);
  1019. if(xml.enterbranch("INSTRUMENT")) {
  1020. getfromXMLinstrument(xml);
  1021. xml.exitbranch();
  1022. }
  1023. if(xml.enterbranch("CONTROLLER")) {
  1024. ctl.getfromXML(xml);
  1025. xml.exitbranch();
  1026. }
  1027. }
  1028. bool Part::Kit::active(void) const
  1029. {
  1030. return Padenabled || Psubenabled || Ppadenabled;
  1031. }
  1032. uint8_t Part::Kit::sendto(void) const
  1033. {
  1034. return limit((int)Psendtoparteffect, 0, NUM_PART_EFX);
  1035. }
  1036. bool Part::Kit::validNote(char note) const
  1037. {
  1038. return !Pmuted && inRange((uint8_t)note, Pminkey, Pmaxkey);
  1039. }