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.

1195 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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. void Part::cloneTraits(Part &p) const
  235. {
  236. #define CLONE(x) p.x = this->x
  237. CLONE(Penabled);
  238. p.setPvolume(this->Pvolume);
  239. p.setPpanning(this->Ppanning);
  240. CLONE(Pminkey);
  241. CLONE(Pmaxkey);
  242. CLONE(Pkeyshift);
  243. CLONE(Prcvchn);
  244. CLONE(Pvelsns);
  245. CLONE(Pveloffs);
  246. CLONE(Pnoteon);
  247. CLONE(Ppolymode);
  248. CLONE(Plegatomode);
  249. CLONE(Pkeylimit);
  250. CLONE(ctl);
  251. }
  252. void Part::defaults()
  253. {
  254. Penabled = 0;
  255. Pminkey = 0;
  256. Pmaxkey = 127;
  257. Pnoteon = 1;
  258. Ppolymode = 1;
  259. Plegatomode = 0;
  260. setPvolume(96);
  261. Pkeyshift = 64;
  262. Prcvchn = 0;
  263. setPpanning(64);
  264. Pvelsns = 64;
  265. Pveloffs = 64;
  266. Pkeylimit = 15;
  267. defaultsinstrument();
  268. ctl.defaults();
  269. }
  270. void Part::defaultsinstrument()
  271. {
  272. ZERO(Pname, PART_MAX_NAME_LEN);
  273. info.Ptype = 0;
  274. ZERO(info.Pauthor, MAX_INFO_TEXT_SIZE + 1);
  275. ZERO(info.Pcomments, MAX_INFO_TEXT_SIZE + 1);
  276. Pkitmode = 0;
  277. Pdrummode = 0;
  278. for(int n = 0; n < NUM_KIT_ITEMS; ++n) {
  279. //kit[n].Penabled = false;
  280. kit[n].Pmuted = false;
  281. kit[n].Pminkey = 0;
  282. kit[n].Pmaxkey = 127;
  283. kit[n].Padenabled = false;
  284. kit[n].Psubenabled = false;
  285. kit[n].Ppadenabled = false;
  286. ZERO(kit[n].Pname, PART_MAX_NAME_LEN);
  287. kit[n].Psendtoparteffect = 0;
  288. if(n != 0)
  289. setkititemstatus(n, 0);
  290. }
  291. kit[0].Penabled = 1;
  292. kit[0].Padenabled = 1;
  293. kit[0].adpars->defaults();
  294. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx) {
  295. partefx[nefx]->defaults();
  296. Pefxroute[nefx] = 0; //route to next effect
  297. }
  298. }
  299. /*
  300. * Cleanup the part
  301. */
  302. void Part::cleanup(bool final_)
  303. {
  304. notePool.killAllNotes();
  305. for(int i = 0; i < synth.buffersize; ++i) {
  306. partoutl[i] = final_ ? 0.0f : synth.denormalkillbuf[i];
  307. partoutr[i] = final_ ? 0.0f : synth.denormalkillbuf[i];
  308. }
  309. ctl.resetall();
  310. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx)
  311. partefx[nefx]->cleanup();
  312. for(int n = 0; n < NUM_PART_EFX + 1; ++n)
  313. for(int i = 0; i < synth.buffersize; ++i) {
  314. partfxinputl[n][i] = final_ ? 0.0f : synth.denormalkillbuf[i];
  315. partfxinputr[n][i] = final_ ? 0.0f : synth.denormalkillbuf[i];
  316. }
  317. }
  318. Part::~Part()
  319. {
  320. cleanup(true);
  321. for(int n = 0; n < NUM_KIT_ITEMS; ++n) {
  322. delete kit[n].adpars;
  323. delete kit[n].subpars;
  324. delete kit[n].padpars;
  325. delete [] kit[n].Pname;
  326. }
  327. delete [] Pname;
  328. delete [] partoutl;
  329. delete [] partoutr;
  330. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx)
  331. delete partefx[nefx];
  332. for(int n = 0; n < NUM_PART_EFX + 1; ++n) {
  333. delete [] partfxinputl[n];
  334. delete [] partfxinputr[n];
  335. }
  336. }
  337. static void assert_kit_sanity(const Part::Kit *kits)
  338. {
  339. for(int i=0; i<NUM_KIT_ITEMS; ++i) {
  340. //an enabled kit must have a corresponding parameter object
  341. assert(!kits[i].Padenabled || kits[i].adpars);
  342. assert(!kits[i].Ppadenabled || kits[i].padpars);
  343. assert(!kits[i].Psubenabled || kits[i].subpars);
  344. }
  345. }
  346. static int kit_usage(const Part::Kit *kits, int note, int mode)
  347. {
  348. const bool non_kit = mode == 0;
  349. const bool singl_kit = mode == 2;
  350. int synth_usage = 0;
  351. for(uint8_t i = 0; i < NUM_KIT_ITEMS; ++i) {
  352. const auto &item = kits[i];
  353. if(!non_kit && !item.validNote(note))
  354. continue;
  355. synth_usage += item.Padenabled;
  356. synth_usage += item.Psubenabled;
  357. synth_usage += item.Ppadenabled;
  358. //Partial Kit Use
  359. if(non_kit || (singl_kit && item.active()))
  360. break;
  361. }
  362. return synth_usage;
  363. }
  364. /*
  365. * Note On Messages
  366. */
  367. bool Part::NoteOn(unsigned char note,
  368. unsigned char velocity,
  369. int masterkeyshift)
  370. {
  371. //Verify Basic Mode and sanity
  372. const bool isRunningNote = notePool.existsRunningNote();
  373. const bool doingLegato = isRunningNote && isLegatoMode() &&
  374. lastlegatomodevalid;
  375. if(!Pnoteon || !inRange(note, Pminkey, Pmaxkey) || notePool.full() ||
  376. notePool.synthFull(kit_usage(kit, note, Pkitmode)))
  377. return false;
  378. verifyKeyMode();
  379. assert_kit_sanity(kit);
  380. //Preserve Note Stack
  381. if(isMonoMode() || isLegatoMode()) {
  382. monomemPush(note);
  383. monomem[note].velocity = velocity;
  384. monomem[note].mkeyshift = masterkeyshift;
  385. } else if(!monomemEmpty())
  386. monomemClear();
  387. //Mono/Legato Release old notes
  388. if(isMonoMode() || (isLegatoMode() && !doingLegato))
  389. notePool.releasePlayingNotes();
  390. lastlegatomodevalid = isLegatoMode();
  391. //Compute Note Parameters
  392. const float vel = getVelocity(velocity, Pvelsns, Pveloffs);
  393. const int partkeyshift = (int)Pkeyshift - 64;
  394. const int keyshift = masterkeyshift + partkeyshift;
  395. const float notebasefreq = getBaseFreq(note, keyshift);
  396. if(notebasefreq < 0)
  397. return false;
  398. //Portamento
  399. lastnote = note;
  400. if(oldfreq < 1.0f)
  401. oldfreq = notebasefreq;//this is only the first note is played
  402. // For Mono/Legato: Force Portamento Off on first
  403. // notes. That means it is required that the previous note is
  404. // still held down or sustained for the Portamento to activate
  405. // (that's like Legato).
  406. bool portamento = false;
  407. if(Ppolymode || isRunningNote)
  408. portamento = ctl.initportamento(oldfreq, notebasefreq, doingLegato);
  409. oldfreq = notebasefreq;
  410. //Adjust Existing Notes
  411. if(doingLegato) {
  412. LegatoParams pars = {notebasefreq, vel, portamento, note, true};
  413. notePool.applyLegato(pars);
  414. return true;
  415. }
  416. if(Ppolymode)
  417. notePool.makeUnsustainable(note);
  418. //Create New Notes
  419. for(uint8_t i = 0; i < NUM_KIT_ITEMS; ++i) {
  420. auto &item = kit[i];
  421. if(Pkitmode != 0 && !item.validNote(note))
  422. continue;
  423. SynthParams pars{memory, ctl, synth, time, notebasefreq, vel,
  424. portamento, note, false};
  425. const int sendto = Pkitmode ? item.sendto() : 0;
  426. try {
  427. if(item.Padenabled)
  428. notePool.insertNote(note, sendto,
  429. {memory.alloc<ADnote>(kit[i].adpars, pars), 0, i});
  430. if(item.Psubenabled)
  431. notePool.insertNote(note, sendto,
  432. {memory.alloc<SUBnote>(kit[i].subpars, pars), 1, i});
  433. if(item.Ppadenabled)
  434. notePool.insertNote(note, sendto,
  435. {memory.alloc<PADnote>(kit[i].padpars, pars, interpolation), 2, i});
  436. } catch (std::bad_alloc & ba) {
  437. std::cerr << "dropped new note: " << ba.what() << std::endl;
  438. }
  439. //Partial Kit Use
  440. if(isNonKit() || (isSingleKit() && item.active()))
  441. break;
  442. }
  443. if(isLegatoMode())
  444. notePool.upgradeToLegato();
  445. //Enforce the key limit
  446. setkeylimit(Pkeylimit);
  447. return true;
  448. }
  449. /*
  450. * Note Off Messages
  451. */
  452. void Part::NoteOff(unsigned char note) //release the key
  453. {
  454. // This note is released, so we remove it from the list.
  455. if(!monomemEmpty())
  456. monomemPop(note);
  457. for(auto &desc:notePool.activeDesc()) {
  458. if(desc.note != note || !desc.playing())
  459. continue;
  460. if(!ctl.sustain.sustain) { //the sustain pedal is not pushed
  461. if((isMonoMode() || isLegatoMode()) && !monomemEmpty())
  462. MonoMemRenote();//Play most recent still active note
  463. else
  464. notePool.release(desc);
  465. }
  466. else { //the sustain pedal is pushed
  467. if(desc.canSustain())
  468. desc.doSustain();
  469. else
  470. notePool.release(desc);
  471. }
  472. }
  473. }
  474. void Part::PolyphonicAftertouch(unsigned char note,
  475. unsigned char velocity,
  476. int masterkeyshift)
  477. {
  478. (void) masterkeyshift;
  479. if(!Pnoteon || !inRange(note, Pminkey, Pmaxkey) || Pdrummode)
  480. return;
  481. // MonoMem stuff:
  482. if(!Ppolymode) // if Poly is off
  483. monomem[note].velocity = velocity; // Store this note's velocity.
  484. const float vel = getVelocity(velocity, Pvelsns, Pveloffs);
  485. for(auto &d:notePool.activeDesc()) {
  486. if(d.note == note && d.playing())
  487. for(auto &s:notePool.activeNotes(d))
  488. s.note->setVelocity(vel);
  489. }
  490. }
  491. /*
  492. * Controllers
  493. */
  494. void Part::SetController(unsigned int type, int par)
  495. {
  496. switch(type) {
  497. case C_pitchwheel:
  498. ctl.setpitchwheel(par);
  499. break;
  500. case C_expression:
  501. ctl.setexpression(par);
  502. setPvolume(Pvolume); //update the volume
  503. break;
  504. case C_portamento:
  505. ctl.setportamento(par);
  506. break;
  507. case C_panning:
  508. ctl.setpanning(par);
  509. setPpanning(Ppanning); //update the panning
  510. break;
  511. case C_filtercutoff:
  512. ctl.setfiltercutoff(par);
  513. break;
  514. case C_filterq:
  515. ctl.setfilterq(par);
  516. break;
  517. case C_bandwidth:
  518. ctl.setbandwidth(par);
  519. break;
  520. case C_modwheel:
  521. ctl.setmodwheel(par);
  522. break;
  523. case C_fmamp:
  524. ctl.setfmamp(par);
  525. break;
  526. case C_volume:
  527. ctl.setvolume(par);
  528. if(ctl.volume.receive != 0)
  529. volume = ctl.volume.volume;
  530. else
  531. setPvolume(Pvolume);
  532. break;
  533. case C_sustain:
  534. ctl.setsustain(par);
  535. if(ctl.sustain.sustain == 0)
  536. ReleaseSustainedKeys();
  537. break;
  538. case C_allsoundsoff:
  539. AllNotesOff(); //Panic
  540. break;
  541. case C_resetallcontrollers:
  542. ctl.resetall();
  543. ReleaseSustainedKeys();
  544. if(ctl.volume.receive != 0)
  545. volume = ctl.volume.volume;
  546. else
  547. setPvolume(Pvolume);
  548. setPvolume(Pvolume); //update the volume
  549. setPpanning(Ppanning); //update the panning
  550. for(int item = 0; item < NUM_KIT_ITEMS; ++item) {
  551. if(kit[item].adpars == NULL)
  552. continue;
  553. kit[item].adpars->GlobalPar.Reson->
  554. sendcontroller(C_resonance_center, 1.0f);
  555. kit[item].adpars->GlobalPar.Reson->
  556. sendcontroller(C_resonance_bandwidth, 1.0f);
  557. }
  558. //more update to add here if I add controllers
  559. break;
  560. case C_allnotesoff:
  561. ReleaseAllKeys();
  562. break;
  563. case C_resonance_center:
  564. ctl.setresonancecenter(par);
  565. for(int item = 0; item < NUM_KIT_ITEMS; ++item) {
  566. if(kit[item].adpars == NULL)
  567. continue;
  568. kit[item].adpars->GlobalPar.Reson->
  569. sendcontroller(C_resonance_center,
  570. ctl.resonancecenter.relcenter);
  571. }
  572. break;
  573. case C_resonance_bandwidth:
  574. ctl.setresonancebw(par);
  575. kit[0].adpars->GlobalPar.Reson->
  576. sendcontroller(C_resonance_bandwidth, ctl.resonancebandwidth.relbw);
  577. break;
  578. }
  579. }
  580. /*
  581. * Release the sustained keys
  582. */
  583. void Part::ReleaseSustainedKeys()
  584. {
  585. // Let's call MonoMemRenote() on some conditions:
  586. if((isMonoMode() || isLegatoMode()) && !monomemEmpty())
  587. if(monomemBack() != lastnote) // Sustain controller manipulation would cause repeated same note respawn without this check.
  588. MonoMemRenote(); // To play most recent still held note.
  589. for(auto &d:notePool.activeDesc())
  590. if(d.sustained())
  591. for(auto &s:notePool.activeNotes(d))
  592. s.note->releasekey();
  593. }
  594. /*
  595. * Release all keys
  596. */
  597. void Part::ReleaseAllKeys()
  598. {
  599. for(auto &d:notePool.activeDesc())
  600. if(!d.released())
  601. for(auto &s:notePool.activeNotes(d))
  602. s.note->releasekey();
  603. }
  604. // Call NoteOn(...) with the most recent still held key as new note
  605. // (Made for Mono/Legato).
  606. void Part::MonoMemRenote()
  607. {
  608. unsigned char mmrtempnote = monomemBack(); // Last list element.
  609. monomemPop(mmrtempnote); // We remove it, will be added again in NoteOn(...).
  610. NoteOn(mmrtempnote, monomem[mmrtempnote].velocity,
  611. monomem[mmrtempnote].mkeyshift);
  612. }
  613. float Part::getBaseFreq(int note, int keyshift) const
  614. {
  615. if(Pdrummode)
  616. return 440.0f * powf(2.0f, (note - 69.0f) / 12.0f);
  617. else
  618. return microtonal->getnotefreq(note, keyshift);
  619. }
  620. float Part::getVelocity(uint8_t velocity, uint8_t velocity_sense,
  621. uint8_t velocity_offset) const
  622. {
  623. //compute sense function
  624. const float vel = VelF(velocity / 127.0f, velocity_sense);
  625. //compute the velocity offset
  626. return limit(vel + (velocity_offset - 64.0f) / 64.0f, 0.0f, 1.0f);
  627. }
  628. void Part::verifyKeyMode(void)
  629. {
  630. if(Plegatomode && !Pdrummode && Ppolymode) {
  631. fprintf(stderr,
  632. "WARNING: Poly & Legato modes are On, that shouldn't happen\n"
  633. "Disabling Legato mode...\n"
  634. "(Part.cpp::NoteOn(..))\n");
  635. Plegatomode = 0;
  636. }
  637. }
  638. /*
  639. * Set Part's key limit
  640. */
  641. void Part::setkeylimit(unsigned char Pkeylimit_)
  642. {
  643. Pkeylimit = Pkeylimit_;
  644. int keylimit = Pkeylimit;
  645. if(keylimit == 0)
  646. keylimit = POLYPHONY - 5;
  647. if(notePool.getRunningNotes() >= keylimit)
  648. notePool.enforceKeyLimit(keylimit);
  649. }
  650. /*
  651. * Prepare all notes to be turned off
  652. */
  653. void Part::AllNotesOff()
  654. {
  655. killallnotes = true;
  656. }
  657. /*
  658. * Compute Part samples and store them in the partoutl[] and partoutr[]
  659. */
  660. void Part::ComputePartSmps()
  661. {
  662. assert(partefx[0]);
  663. for(unsigned nefx = 0; nefx < NUM_PART_EFX + 1; ++nefx) {
  664. memset(partfxinputl[nefx], 0, synth.bufferbytes);
  665. memset(partfxinputr[nefx], 0, synth.bufferbytes);
  666. }
  667. for(auto &d:notePool.activeDesc()) {
  668. d.age++;
  669. for(auto &s:notePool.activeNotes(d)) {
  670. float tmpoutr[synth.buffersize];
  671. float tmpoutl[synth.buffersize];
  672. auto &note = *s.note;
  673. note.noteout(&tmpoutl[0], &tmpoutr[0]);
  674. for(int i = 0; i < synth.buffersize; ++i) { //add the note to part(mix)
  675. partfxinputl[d.sendto][i] += tmpoutl[i];
  676. partfxinputr[d.sendto][i] += tmpoutr[i];
  677. }
  678. if(note.finished())
  679. notePool.kill(s);
  680. }
  681. }
  682. //Apply part's effects and mix them
  683. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx) {
  684. if(!Pefxbypass[nefx]) {
  685. partefx[nefx]->out(partfxinputl[nefx], partfxinputr[nefx]);
  686. if(Pefxroute[nefx] == 2)
  687. for(int i = 0; i < synth.buffersize; ++i) {
  688. partfxinputl[nefx + 1][i] += partefx[nefx]->efxoutl[i];
  689. partfxinputr[nefx + 1][i] += partefx[nefx]->efxoutr[i];
  690. }
  691. }
  692. int routeto = ((Pefxroute[nefx] == 0) ? nefx + 1 : NUM_PART_EFX);
  693. for(int i = 0; i < synth.buffersize; ++i) {
  694. partfxinputl[routeto][i] += partfxinputl[nefx][i];
  695. partfxinputr[routeto][i] += partfxinputr[nefx][i];
  696. }
  697. }
  698. for(int i = 0; i < synth.buffersize; ++i) {
  699. partoutl[i] = partfxinputl[NUM_PART_EFX][i];
  700. partoutr[i] = partfxinputr[NUM_PART_EFX][i];
  701. }
  702. if(killallnotes) {
  703. for(int i = 0; i < synth.buffersize; ++i) {
  704. float tmp = (synth.buffersize_f - i) / synth.buffersize_f;
  705. partoutl[i] *= tmp;
  706. partoutr[i] *= tmp;
  707. }
  708. notePool.killAllNotes();
  709. monomemClear();
  710. killallnotes = false;
  711. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx)
  712. partefx[nefx]->cleanup();
  713. }
  714. ctl.updateportamento();
  715. }
  716. /*
  717. * Parameter control
  718. */
  719. void Part::setPvolume(char Pvolume_)
  720. {
  721. Pvolume = Pvolume_;
  722. volume =
  723. dB2rap((Pvolume - 96.0f) / 96.0f * 40.0f) * ctl.expression.relvolume;
  724. }
  725. void Part::setPpanning(char Ppanning_)
  726. {
  727. Ppanning = Ppanning_;
  728. panning = limit(Ppanning / 127.0f + ctl.panning.pan, 0.0f, 1.0f);
  729. }
  730. /*
  731. * Enable or disable a kit item
  732. */
  733. void Part::setkititemstatus(unsigned kititem, bool Penabled_)
  734. {
  735. //nonexistent kit item and the first kit item is always enabled
  736. if((kititem == 0) || (kititem >= NUM_KIT_ITEMS))
  737. return;
  738. Kit &kkit = kit[kititem];
  739. //no need to update if
  740. if(kkit.Penabled == Penabled_)
  741. return;
  742. kkit.Penabled = Penabled_;
  743. if(!Penabled_) {
  744. delete kkit.adpars;
  745. delete kkit.subpars;
  746. delete kkit.padpars;
  747. kkit.adpars = nullptr;
  748. kkit.subpars = nullptr;
  749. kkit.padpars = nullptr;
  750. kkit.Pname[0] = '\0';
  751. notePool.killAllNotes();
  752. }
  753. else {
  754. //All parameters must be NULL in this case
  755. assert(!(kkit.adpars || kkit.subpars || kkit.padpars));
  756. kkit.adpars = new ADnoteParameters(synth, fft, &time);
  757. kkit.subpars = new SUBnoteParameters(&time);
  758. kkit.padpars = new PADnoteParameters(synth, fft, &time);
  759. }
  760. }
  761. void Part::add2XMLinstrument(XMLwrapper& xml)
  762. {
  763. xml.beginbranch("INFO");
  764. xml.addparstr("name", (char *)Pname);
  765. xml.addparstr("author", (char *)info.Pauthor);
  766. xml.addparstr("comments", (char *)info.Pcomments);
  767. xml.addpar("type", info.Ptype);
  768. xml.endbranch();
  769. xml.beginbranch("INSTRUMENT_KIT");
  770. xml.addpar("kit_mode", Pkitmode);
  771. xml.addparbool("drum_mode", Pdrummode);
  772. for(int i = 0; i < NUM_KIT_ITEMS; ++i) {
  773. xml.beginbranch("INSTRUMENT_KIT_ITEM", i);
  774. xml.addparbool("enabled", kit[i].Penabled);
  775. if(kit[i].Penabled != 0) {
  776. xml.addparstr("name", (char *)kit[i].Pname);
  777. xml.addparbool("muted", kit[i].Pmuted);
  778. xml.addpar("min_key", kit[i].Pminkey);
  779. xml.addpar("max_key", kit[i].Pmaxkey);
  780. xml.addpar("send_to_instrument_effect", kit[i].Psendtoparteffect);
  781. xml.addparbool("add_enabled", kit[i].Padenabled);
  782. if(kit[i].Padenabled && kit[i].adpars) {
  783. xml.beginbranch("ADD_SYNTH_PARAMETERS");
  784. kit[i].adpars->add2XML(xml);
  785. xml.endbranch();
  786. }
  787. xml.addparbool("sub_enabled", kit[i].Psubenabled);
  788. if(kit[i].Psubenabled && kit[i].subpars) {
  789. xml.beginbranch("SUB_SYNTH_PARAMETERS");
  790. kit[i].subpars->add2XML(xml);
  791. xml.endbranch();
  792. }
  793. xml.addparbool("pad_enabled", kit[i].Ppadenabled);
  794. if(kit[i].Ppadenabled && kit[i].padpars) {
  795. xml.beginbranch("PAD_SYNTH_PARAMETERS");
  796. kit[i].padpars->add2XML(xml);
  797. xml.endbranch();
  798. }
  799. }
  800. xml.endbranch();
  801. }
  802. xml.endbranch();
  803. xml.beginbranch("INSTRUMENT_EFFECTS");
  804. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx) {
  805. xml.beginbranch("INSTRUMENT_EFFECT", nefx);
  806. xml.beginbranch("EFFECT");
  807. partefx[nefx]->add2XML(xml);
  808. xml.endbranch();
  809. xml.addpar("route", Pefxroute[nefx]);
  810. partefx[nefx]->setdryonly(Pefxroute[nefx] == 2);
  811. xml.addparbool("bypass", Pefxbypass[nefx]);
  812. xml.endbranch();
  813. }
  814. xml.endbranch();
  815. }
  816. void Part::add2XML(XMLwrapper& xml)
  817. {
  818. //parameters
  819. xml.addparbool("enabled", Penabled);
  820. if((Penabled == 0) && (xml.minimal))
  821. return;
  822. xml.addpar("volume", Pvolume);
  823. xml.addpar("panning", Ppanning);
  824. xml.addpar("min_key", Pminkey);
  825. xml.addpar("max_key", Pmaxkey);
  826. xml.addpar("key_shift", Pkeyshift);
  827. xml.addpar("rcv_chn", Prcvchn);
  828. xml.addpar("velocity_sensing", Pvelsns);
  829. xml.addpar("velocity_offset", Pveloffs);
  830. xml.addparbool("note_on", Pnoteon);
  831. xml.addparbool("poly_mode", Ppolymode);
  832. xml.addpar("legato_mode", Plegatomode);
  833. xml.addpar("key_limit", Pkeylimit);
  834. xml.beginbranch("INSTRUMENT");
  835. add2XMLinstrument(xml);
  836. xml.endbranch();
  837. xml.beginbranch("CONTROLLER");
  838. ctl.add2XML(xml);
  839. xml.endbranch();
  840. }
  841. int Part::saveXML(const char *filename)
  842. {
  843. XMLwrapper xml;
  844. xml.beginbranch("INSTRUMENT");
  845. add2XMLinstrument(xml);
  846. xml.endbranch();
  847. int result = xml.saveXMLfile(filename, gzip_compression);
  848. return result;
  849. }
  850. int Part::loadXMLinstrument(const char *filename)
  851. {
  852. XMLwrapper xml;
  853. if(xml.loadXMLfile(filename) < 0) {
  854. return -1;
  855. }
  856. if(xml.enterbranch("INSTRUMENT") == 0)
  857. return -10;
  858. getfromXMLinstrument(xml);
  859. xml.exitbranch();
  860. return 0;
  861. }
  862. void Part::applyparameters(void)
  863. {
  864. applyparameters([]{return false;});
  865. }
  866. void Part::applyparameters(std::function<bool()> do_abort)
  867. {
  868. for(int n = 0; n < NUM_KIT_ITEMS; ++n)
  869. if(kit[n].Ppadenabled && kit[n].padpars)
  870. kit[n].padpars->applyparameters(do_abort);
  871. }
  872. void Part::initialize_rt(void)
  873. {
  874. for(int i=0; i<NUM_PART_EFX; ++i)
  875. partefx[i]->init();
  876. }
  877. void Part::kill_rt(void)
  878. {
  879. for(int i=0; i<NUM_PART_EFX; ++i)
  880. partefx[i]->kill();
  881. notePool.killAllNotes();
  882. }
  883. void Part::monomemPush(char note)
  884. {
  885. for(int i=0; i<256; ++i)
  886. if(monomemnotes[i]==note)
  887. return;
  888. for(int i=254;i>=0; --i)
  889. monomemnotes[i+1] = monomemnotes[i];
  890. monomemnotes[0] = note;
  891. }
  892. void Part::monomemPop(char note)
  893. {
  894. int note_pos=-1;
  895. for(int i=0; i<256; ++i)
  896. if(monomemnotes[i]==note)
  897. note_pos = i;
  898. if(note_pos != -1) {
  899. for(int i=note_pos; i<256; ++i)
  900. monomemnotes[i] = monomemnotes[i+1];
  901. monomemnotes[255] = -1;
  902. }
  903. }
  904. char Part::monomemBack(void) const
  905. {
  906. return monomemnotes[0];
  907. }
  908. bool Part::monomemEmpty(void) const
  909. {
  910. return monomemnotes[0] == -1;
  911. }
  912. void Part::monomemClear(void)
  913. {
  914. for(int i=0; i<256; ++i)
  915. monomemnotes[i] = -1;
  916. }
  917. void Part::getfromXMLinstrument(XMLwrapper& xml)
  918. {
  919. if(xml.enterbranch("INFO")) {
  920. xml.getparstr("name", (char *)Pname, PART_MAX_NAME_LEN);
  921. xml.getparstr("author", (char *)info.Pauthor, MAX_INFO_TEXT_SIZE);
  922. xml.getparstr("comments", (char *)info.Pcomments, MAX_INFO_TEXT_SIZE);
  923. info.Ptype = xml.getpar("type", info.Ptype, 0, 16);
  924. xml.exitbranch();
  925. }
  926. if(xml.enterbranch("INSTRUMENT_KIT")) {
  927. Pkitmode = xml.getpar127("kit_mode", Pkitmode);
  928. Pdrummode = xml.getparbool("drum_mode", Pdrummode);
  929. setkititemstatus(0, 0);
  930. for(int i = 0; i < NUM_KIT_ITEMS; ++i) {
  931. if(xml.enterbranch("INSTRUMENT_KIT_ITEM", i) == 0)
  932. continue;
  933. setkititemstatus(i, xml.getparbool("enabled", kit[i].Penabled));
  934. if(kit[i].Penabled == 0) {
  935. xml.exitbranch();
  936. continue;
  937. }
  938. xml.getparstr("name", (char *)kit[i].Pname, PART_MAX_NAME_LEN);
  939. kit[i].Pmuted = xml.getparbool("muted", kit[i].Pmuted);
  940. kit[i].Pminkey = xml.getpar127("min_key", kit[i].Pminkey);
  941. kit[i].Pmaxkey = xml.getpar127("max_key", kit[i].Pmaxkey);
  942. kit[i].Psendtoparteffect = xml.getpar127(
  943. "send_to_instrument_effect",
  944. kit[i].Psendtoparteffect);
  945. kit[i].Padenabled = xml.getparbool("add_enabled",
  946. kit[i].Padenabled);
  947. if(xml.enterbranch("ADD_SYNTH_PARAMETERS")) {
  948. if(!kit[i].adpars)
  949. kit[i].adpars = new ADnoteParameters(synth, fft, &time);
  950. kit[i].adpars->getfromXML(xml);
  951. xml.exitbranch();
  952. }
  953. kit[i].Psubenabled = xml.getparbool("sub_enabled",
  954. kit[i].Psubenabled);
  955. if(xml.enterbranch("SUB_SYNTH_PARAMETERS")) {
  956. if(!kit[i].subpars)
  957. kit[i].subpars = new SUBnoteParameters(&time);
  958. kit[i].subpars->getfromXML(xml);
  959. xml.exitbranch();
  960. }
  961. kit[i].Ppadenabled = xml.getparbool("pad_enabled",
  962. kit[i].Ppadenabled);
  963. if(xml.enterbranch("PAD_SYNTH_PARAMETERS")) {
  964. if(!kit[i].padpars)
  965. kit[i].padpars = new PADnoteParameters(synth, fft, &time);
  966. kit[i].padpars->getfromXML(xml);
  967. xml.exitbranch();
  968. }
  969. xml.exitbranch();
  970. }
  971. xml.exitbranch();
  972. }
  973. if(xml.enterbranch("INSTRUMENT_EFFECTS")) {
  974. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx) {
  975. if(xml.enterbranch("INSTRUMENT_EFFECT", nefx) == 0)
  976. continue;
  977. if(xml.enterbranch("EFFECT")) {
  978. partefx[nefx]->getfromXML(xml);
  979. xml.exitbranch();
  980. }
  981. Pefxroute[nefx] = xml.getpar("route",
  982. Pefxroute[nefx],
  983. 0,
  984. NUM_PART_EFX);
  985. partefx[nefx]->setdryonly(Pefxroute[nefx] == 2);
  986. Pefxbypass[nefx] = xml.getparbool("bypass", Pefxbypass[nefx]);
  987. xml.exitbranch();
  988. }
  989. xml.exitbranch();
  990. }
  991. }
  992. void Part::getfromXML(XMLwrapper& xml)
  993. {
  994. Penabled = xml.getparbool("enabled", Penabled);
  995. setPvolume(xml.getpar127("volume", Pvolume));
  996. setPpanning(xml.getpar127("panning", Ppanning));
  997. Pminkey = xml.getpar127("min_key", Pminkey);
  998. Pmaxkey = xml.getpar127("max_key", Pmaxkey);
  999. Pkeyshift = xml.getpar127("key_shift", Pkeyshift);
  1000. Prcvchn = xml.getpar127("rcv_chn", Prcvchn);
  1001. Pvelsns = xml.getpar127("velocity_sensing", Pvelsns);
  1002. Pveloffs = xml.getpar127("velocity_offset", Pveloffs);
  1003. Pnoteon = xml.getparbool("note_on", Pnoteon);
  1004. Ppolymode = xml.getparbool("poly_mode", Ppolymode);
  1005. Plegatomode = xml.getparbool("legato_mode", Plegatomode); //older versions
  1006. if(!Plegatomode)
  1007. Plegatomode = xml.getpar127("legato_mode", Plegatomode);
  1008. Pkeylimit = xml.getpar127("key_limit", Pkeylimit);
  1009. if(xml.enterbranch("INSTRUMENT")) {
  1010. getfromXMLinstrument(xml);
  1011. xml.exitbranch();
  1012. }
  1013. if(xml.enterbranch("CONTROLLER")) {
  1014. ctl.getfromXML(xml);
  1015. xml.exitbranch();
  1016. }
  1017. }
  1018. bool Part::Kit::active(void) const
  1019. {
  1020. return Padenabled || Psubenabled || Ppadenabled;
  1021. }
  1022. uint8_t Part::Kit::sendto(void) const
  1023. {
  1024. return limit((int)Psendtoparteffect, 0, NUM_PART_EFX);
  1025. }
  1026. bool Part::Kit::validNote(char note) const
  1027. {
  1028. return !Pmuted && inRange((uint8_t)note, Pminkey, Pmaxkey);
  1029. }