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.

1185 lines
35KB

  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. //Create New Notes
  417. for(uint8_t i = 0; i < NUM_KIT_ITEMS; ++i) {
  418. auto &item = kit[i];
  419. if(Pkitmode != 0 && !item.validNote(note))
  420. continue;
  421. SynthParams pars{memory, ctl, synth, time, notebasefreq, vel,
  422. portamento, note, false};
  423. const int sendto = Pkitmode ? item.sendto() : 0;
  424. try {
  425. if(item.Padenabled)
  426. notePool.insertNote(note, sendto,
  427. {memory.alloc<ADnote>(kit[i].adpars, pars), 0, i});
  428. if(item.Psubenabled)
  429. notePool.insertNote(note, sendto,
  430. {memory.alloc<SUBnote>(kit[i].subpars, pars), 1, i});
  431. if(item.Ppadenabled)
  432. notePool.insertNote(note, sendto,
  433. {memory.alloc<PADnote>(kit[i].padpars, pars, interpolation), 2, i});
  434. } catch (std::bad_alloc & ba) {
  435. std::cerr << "dropped new note: " << ba.what() << std::endl;
  436. }
  437. //Partial Kit Use
  438. if(isNonKit() || (isSingleKit() && item.active()))
  439. break;
  440. }
  441. if(isLegatoMode())
  442. notePool.upgradeToLegato();
  443. //Enforce the key limit
  444. setkeylimit(Pkeylimit);
  445. return true;
  446. }
  447. /*
  448. * Note Off Messages
  449. */
  450. void Part::NoteOff(unsigned char note) //release the key
  451. {
  452. // This note is released, so we remove it from the list.
  453. if(!monomemEmpty())
  454. monomemPop(note);
  455. for(auto &desc:notePool.activeDesc()) {
  456. if(desc.note != note || desc.status != KEY_PLAYING)
  457. continue;
  458. if(!ctl.sustain.sustain) { //the sustain pedal is not pushed
  459. if((isMonoMode() || isLegatoMode()) && !monomemEmpty())
  460. MonoMemRenote();//Play most recent still active note
  461. else
  462. notePool.release(desc);
  463. }
  464. else //the sustain pedal is pushed
  465. desc.status = KEY_RELEASED_AND_SUSTAINED;
  466. }
  467. }
  468. void Part::PolyphonicAftertouch(unsigned char note,
  469. unsigned char velocity,
  470. int masterkeyshift)
  471. {
  472. (void) masterkeyshift;
  473. if(!Pnoteon || !inRange(note, Pminkey, Pmaxkey) || Pdrummode)
  474. return;
  475. // MonoMem stuff:
  476. if(!Ppolymode) // if Poly is off
  477. monomem[note].velocity = velocity; // Store this note's velocity.
  478. const float vel = getVelocity(velocity, Pvelsns, Pveloffs);
  479. for(auto &d:notePool.activeDesc()) {
  480. if(d.note == note && d.status == KEY_PLAYING)
  481. for(auto &s:notePool.activeNotes(d))
  482. s.note->setVelocity(vel);
  483. }
  484. }
  485. /*
  486. * Controllers
  487. */
  488. void Part::SetController(unsigned int type, int par)
  489. {
  490. switch(type) {
  491. case C_pitchwheel:
  492. ctl.setpitchwheel(par);
  493. break;
  494. case C_expression:
  495. ctl.setexpression(par);
  496. setPvolume(Pvolume); //update the volume
  497. break;
  498. case C_portamento:
  499. ctl.setportamento(par);
  500. break;
  501. case C_panning:
  502. ctl.setpanning(par);
  503. setPpanning(Ppanning); //update the panning
  504. break;
  505. case C_filtercutoff:
  506. ctl.setfiltercutoff(par);
  507. break;
  508. case C_filterq:
  509. ctl.setfilterq(par);
  510. break;
  511. case C_bandwidth:
  512. ctl.setbandwidth(par);
  513. break;
  514. case C_modwheel:
  515. ctl.setmodwheel(par);
  516. break;
  517. case C_fmamp:
  518. ctl.setfmamp(par);
  519. break;
  520. case C_volume:
  521. ctl.setvolume(par);
  522. if(ctl.volume.receive != 0)
  523. volume = ctl.volume.volume;
  524. else
  525. setPvolume(Pvolume);
  526. break;
  527. case C_sustain:
  528. ctl.setsustain(par);
  529. if(ctl.sustain.sustain == 0)
  530. ReleaseSustainedKeys();
  531. break;
  532. case C_allsoundsoff:
  533. AllNotesOff(); //Panic
  534. break;
  535. case C_resetallcontrollers:
  536. ctl.resetall();
  537. ReleaseSustainedKeys();
  538. if(ctl.volume.receive != 0)
  539. volume = ctl.volume.volume;
  540. else
  541. setPvolume(Pvolume);
  542. setPvolume(Pvolume); //update the volume
  543. setPpanning(Ppanning); //update the panning
  544. for(int item = 0; item < NUM_KIT_ITEMS; ++item) {
  545. if(kit[item].adpars == NULL)
  546. continue;
  547. kit[item].adpars->GlobalPar.Reson->
  548. sendcontroller(C_resonance_center, 1.0f);
  549. kit[item].adpars->GlobalPar.Reson->
  550. sendcontroller(C_resonance_bandwidth, 1.0f);
  551. }
  552. //more update to add here if I add controllers
  553. break;
  554. case C_allnotesoff:
  555. ReleaseAllKeys();
  556. break;
  557. case C_resonance_center:
  558. ctl.setresonancecenter(par);
  559. for(int item = 0; item < NUM_KIT_ITEMS; ++item) {
  560. if(kit[item].adpars == NULL)
  561. continue;
  562. kit[item].adpars->GlobalPar.Reson->
  563. sendcontroller(C_resonance_center,
  564. ctl.resonancecenter.relcenter);
  565. }
  566. break;
  567. case C_resonance_bandwidth:
  568. ctl.setresonancebw(par);
  569. kit[0].adpars->GlobalPar.Reson->
  570. sendcontroller(C_resonance_bandwidth, ctl.resonancebandwidth.relbw);
  571. break;
  572. }
  573. }
  574. /*
  575. * Release the sustained keys
  576. */
  577. void Part::ReleaseSustainedKeys()
  578. {
  579. // Let's call MonoMemRenote() on some conditions:
  580. if((isMonoMode() || isLegatoMode()) && !monomemEmpty())
  581. if(monomemBack() != lastnote) // Sustain controller manipulation would cause repeated same note respawn without this check.
  582. MonoMemRenote(); // To play most recent still held note.
  583. for(auto &d:notePool.activeDesc())
  584. if(d.status == KEY_RELEASED_AND_SUSTAINED)
  585. for(auto &s:notePool.activeNotes(d))
  586. s.note->releasekey();
  587. }
  588. /*
  589. * Release all keys
  590. */
  591. void Part::ReleaseAllKeys()
  592. {
  593. for(auto &d:notePool.activeDesc())
  594. if(d.status != KEY_RELEASED)
  595. for(auto &s:notePool.activeNotes(d))
  596. s.note->releasekey();
  597. }
  598. // Call NoteOn(...) with the most recent still held key as new note
  599. // (Made for Mono/Legato).
  600. void Part::MonoMemRenote()
  601. {
  602. unsigned char mmrtempnote = monomemBack(); // Last list element.
  603. monomemPop(mmrtempnote); // We remove it, will be added again in NoteOn(...).
  604. NoteOn(mmrtempnote, monomem[mmrtempnote].velocity,
  605. monomem[mmrtempnote].mkeyshift);
  606. }
  607. float Part::getBaseFreq(int note, int keyshift) const
  608. {
  609. if(Pdrummode)
  610. return 440.0f * powf(2.0f, (note - 69.0f) / 12.0f);
  611. else
  612. return microtonal->getnotefreq(note, keyshift);
  613. }
  614. float Part::getVelocity(uint8_t velocity, uint8_t velocity_sense,
  615. uint8_t velocity_offset) const
  616. {
  617. //compute sense function
  618. const float vel = VelF(velocity / 127.0f, velocity_sense);
  619. //compute the velocity offset
  620. return limit(vel + (velocity_offset - 64.0f) / 64.0f, 0.0f, 1.0f);
  621. }
  622. void Part::verifyKeyMode(void)
  623. {
  624. if(Plegatomode && !Pdrummode && Ppolymode) {
  625. fprintf(stderr,
  626. "WARNING: Poly & Legato modes are On, that shouldn't happen\n"
  627. "Disabling Legato mode...\n"
  628. "(Part.cpp::NoteOn(..))\n");
  629. Plegatomode = 0;
  630. }
  631. }
  632. /*
  633. * Set Part's key limit
  634. */
  635. void Part::setkeylimit(unsigned char Pkeylimit_)
  636. {
  637. Pkeylimit = Pkeylimit_;
  638. int keylimit = Pkeylimit;
  639. if(keylimit == 0)
  640. keylimit = POLYPHONY - 5;
  641. if(notePool.getRunningNotes() > keylimit)
  642. notePool.enforceKeyLimit(keylimit);
  643. }
  644. /*
  645. * Prepare all notes to be turned off
  646. */
  647. void Part::AllNotesOff()
  648. {
  649. killallnotes = true;
  650. }
  651. /*
  652. * Compute Part samples and store them in the partoutl[] and partoutr[]
  653. */
  654. void Part::ComputePartSmps()
  655. {
  656. assert(partefx[0]);
  657. for(unsigned nefx = 0; nefx < NUM_PART_EFX + 1; ++nefx) {
  658. memset(partfxinputl[nefx], 0, synth.bufferbytes);
  659. memset(partfxinputr[nefx], 0, synth.bufferbytes);
  660. }
  661. for(auto &d:notePool.activeDesc()) {
  662. d.age++;
  663. for(auto &s:notePool.activeNotes(d)) {
  664. float tmpoutr[synth.buffersize];
  665. float tmpoutl[synth.buffersize];
  666. auto &note = *s.note;
  667. note.noteout(&tmpoutl[0], &tmpoutr[0]);
  668. for(int i = 0; i < synth.buffersize; ++i) { //add the note to part(mix)
  669. partfxinputl[d.sendto][i] += tmpoutl[i];
  670. partfxinputr[d.sendto][i] += tmpoutr[i];
  671. }
  672. if(note.finished())
  673. notePool.kill(s);
  674. }
  675. }
  676. //Apply part's effects and mix them
  677. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx) {
  678. if(!Pefxbypass[nefx]) {
  679. partefx[nefx]->out(partfxinputl[nefx], partfxinputr[nefx]);
  680. if(Pefxroute[nefx] == 2)
  681. for(int i = 0; i < synth.buffersize; ++i) {
  682. partfxinputl[nefx + 1][i] += partefx[nefx]->efxoutl[i];
  683. partfxinputr[nefx + 1][i] += partefx[nefx]->efxoutr[i];
  684. }
  685. }
  686. int routeto = ((Pefxroute[nefx] == 0) ? nefx + 1 : NUM_PART_EFX);
  687. for(int i = 0; i < synth.buffersize; ++i) {
  688. partfxinputl[routeto][i] += partfxinputl[nefx][i];
  689. partfxinputr[routeto][i] += partfxinputr[nefx][i];
  690. }
  691. }
  692. for(int i = 0; i < synth.buffersize; ++i) {
  693. partoutl[i] = partfxinputl[NUM_PART_EFX][i];
  694. partoutr[i] = partfxinputr[NUM_PART_EFX][i];
  695. }
  696. if(killallnotes) {
  697. for(int i = 0; i < synth.buffersize; ++i) {
  698. float tmp = (synth.buffersize_f - i) / synth.buffersize_f;
  699. partoutl[i] *= tmp;
  700. partoutr[i] *= tmp;
  701. }
  702. notePool.killAllNotes();
  703. monomemClear();
  704. killallnotes = false;
  705. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx)
  706. partefx[nefx]->cleanup();
  707. }
  708. ctl.updateportamento();
  709. }
  710. /*
  711. * Parameter control
  712. */
  713. void Part::setPvolume(char Pvolume_)
  714. {
  715. Pvolume = Pvolume_;
  716. volume =
  717. dB2rap((Pvolume - 96.0f) / 96.0f * 40.0f) * ctl.expression.relvolume;
  718. }
  719. void Part::setPpanning(char Ppanning_)
  720. {
  721. Ppanning = Ppanning_;
  722. panning = limit(Ppanning / 127.0f + ctl.panning.pan, 0.0f, 1.0f);
  723. }
  724. /*
  725. * Enable or disable a kit item
  726. */
  727. void Part::setkititemstatus(unsigned kititem, bool Penabled_)
  728. {
  729. //nonexistent kit item and the first kit item is always enabled
  730. if((kititem == 0) || (kititem >= NUM_KIT_ITEMS))
  731. return;
  732. Kit &kkit = kit[kititem];
  733. //no need to update if
  734. if(kkit.Penabled == Penabled_)
  735. return;
  736. kkit.Penabled = Penabled_;
  737. if(!Penabled_) {
  738. delete kkit.adpars;
  739. delete kkit.subpars;
  740. delete kkit.padpars;
  741. kkit.Pname[0] = '\0';
  742. notePool.killAllNotes();
  743. }
  744. else {
  745. //All parameters must be NULL in this case
  746. assert(!(kkit.adpars || kkit.subpars || kkit.padpars));
  747. kkit.adpars = new ADnoteParameters(synth, fft, &time);
  748. kkit.subpars = new SUBnoteParameters(&time);
  749. kkit.padpars = new PADnoteParameters(synth, fft, &time);
  750. }
  751. }
  752. void Part::add2XMLinstrument(XMLwrapper& xml)
  753. {
  754. xml.beginbranch("INFO");
  755. xml.addparstr("name", (char *)Pname);
  756. xml.addparstr("author", (char *)info.Pauthor);
  757. xml.addparstr("comments", (char *)info.Pcomments);
  758. xml.addpar("type", info.Ptype);
  759. xml.endbranch();
  760. xml.beginbranch("INSTRUMENT_KIT");
  761. xml.addpar("kit_mode", Pkitmode);
  762. xml.addparbool("drum_mode", Pdrummode);
  763. for(int i = 0; i < NUM_KIT_ITEMS; ++i) {
  764. xml.beginbranch("INSTRUMENT_KIT_ITEM", i);
  765. xml.addparbool("enabled", kit[i].Penabled);
  766. if(kit[i].Penabled != 0) {
  767. xml.addparstr("name", (char *)kit[i].Pname);
  768. xml.addparbool("muted", kit[i].Pmuted);
  769. xml.addpar("min_key", kit[i].Pminkey);
  770. xml.addpar("max_key", kit[i].Pmaxkey);
  771. xml.addpar("send_to_instrument_effect", kit[i].Psendtoparteffect);
  772. xml.addparbool("add_enabled", kit[i].Padenabled);
  773. if(kit[i].Padenabled && kit[i].adpars) {
  774. xml.beginbranch("ADD_SYNTH_PARAMETERS");
  775. kit[i].adpars->add2XML(xml);
  776. xml.endbranch();
  777. }
  778. xml.addparbool("sub_enabled", kit[i].Psubenabled);
  779. if(kit[i].Psubenabled && kit[i].subpars) {
  780. xml.beginbranch("SUB_SYNTH_PARAMETERS");
  781. kit[i].subpars->add2XML(xml);
  782. xml.endbranch();
  783. }
  784. xml.addparbool("pad_enabled", kit[i].Ppadenabled);
  785. if(kit[i].Ppadenabled && kit[i].padpars) {
  786. xml.beginbranch("PAD_SYNTH_PARAMETERS");
  787. kit[i].padpars->add2XML(xml);
  788. xml.endbranch();
  789. }
  790. }
  791. xml.endbranch();
  792. }
  793. xml.endbranch();
  794. xml.beginbranch("INSTRUMENT_EFFECTS");
  795. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx) {
  796. xml.beginbranch("INSTRUMENT_EFFECT", nefx);
  797. xml.beginbranch("EFFECT");
  798. partefx[nefx]->add2XML(xml);
  799. xml.endbranch();
  800. xml.addpar("route", Pefxroute[nefx]);
  801. partefx[nefx]->setdryonly(Pefxroute[nefx] == 2);
  802. xml.addparbool("bypass", Pefxbypass[nefx]);
  803. xml.endbranch();
  804. }
  805. xml.endbranch();
  806. }
  807. void Part::add2XML(XMLwrapper& xml)
  808. {
  809. //parameters
  810. xml.addparbool("enabled", Penabled);
  811. if((Penabled == 0) && (xml.minimal))
  812. return;
  813. xml.addpar("volume", Pvolume);
  814. xml.addpar("panning", Ppanning);
  815. xml.addpar("min_key", Pminkey);
  816. xml.addpar("max_key", Pmaxkey);
  817. xml.addpar("key_shift", Pkeyshift);
  818. xml.addpar("rcv_chn", Prcvchn);
  819. xml.addpar("velocity_sensing", Pvelsns);
  820. xml.addpar("velocity_offset", Pveloffs);
  821. xml.addparbool("note_on", Pnoteon);
  822. xml.addparbool("poly_mode", Ppolymode);
  823. xml.addpar("legato_mode", Plegatomode);
  824. xml.addpar("key_limit", Pkeylimit);
  825. xml.beginbranch("INSTRUMENT");
  826. add2XMLinstrument(xml);
  827. xml.endbranch();
  828. xml.beginbranch("CONTROLLER");
  829. ctl.add2XML(xml);
  830. xml.endbranch();
  831. }
  832. int Part::saveXML(const char *filename)
  833. {
  834. XMLwrapper xml;
  835. xml.beginbranch("INSTRUMENT");
  836. add2XMLinstrument(xml);
  837. xml.endbranch();
  838. int result = xml.saveXMLfile(filename, gzip_compression);
  839. return result;
  840. }
  841. int Part::loadXMLinstrument(const char *filename)
  842. {
  843. XMLwrapper xml;
  844. if(xml.loadXMLfile(filename) < 0) {
  845. return -1;
  846. }
  847. if(xml.enterbranch("INSTRUMENT") == 0)
  848. return -10;
  849. getfromXMLinstrument(xml);
  850. xml.exitbranch();
  851. return 0;
  852. }
  853. void Part::applyparameters(void)
  854. {
  855. applyparameters([]{return false;});
  856. }
  857. void Part::applyparameters(std::function<bool()> do_abort)
  858. {
  859. for(int n = 0; n < NUM_KIT_ITEMS; ++n)
  860. if(kit[n].Ppadenabled && kit[n].padpars)
  861. kit[n].padpars->applyparameters(do_abort);
  862. }
  863. void Part::initialize_rt(void)
  864. {
  865. for(int i=0; i<NUM_PART_EFX; ++i)
  866. partefx[i]->init();
  867. }
  868. void Part::kill_rt(void)
  869. {
  870. for(int i=0; i<NUM_PART_EFX; ++i)
  871. partefx[i]->kill();
  872. notePool.killAllNotes();
  873. }
  874. void Part::monomemPush(char note)
  875. {
  876. for(int i=0; i<256; ++i)
  877. if(monomemnotes[i]==note)
  878. return;
  879. for(int i=254;i>=0; --i)
  880. monomemnotes[i+1] = monomemnotes[i];
  881. monomemnotes[0] = note;
  882. }
  883. void Part::monomemPop(char note)
  884. {
  885. int note_pos=-1;
  886. for(int i=0; i<256; ++i)
  887. if(monomemnotes[i]==note)
  888. note_pos = i;
  889. if(note_pos != -1) {
  890. for(int i=note_pos; i<256; ++i)
  891. monomemnotes[i] = monomemnotes[i+1];
  892. monomemnotes[255] = -1;
  893. }
  894. }
  895. char Part::monomemBack(void) const
  896. {
  897. return monomemnotes[0];
  898. }
  899. bool Part::monomemEmpty(void) const
  900. {
  901. return monomemnotes[0] == -1;
  902. }
  903. void Part::monomemClear(void)
  904. {
  905. for(int i=0; i<256; ++i)
  906. monomemnotes[i] = -1;
  907. }
  908. void Part::getfromXMLinstrument(XMLwrapper& xml)
  909. {
  910. if(xml.enterbranch("INFO")) {
  911. xml.getparstr("name", (char *)Pname, PART_MAX_NAME_LEN);
  912. xml.getparstr("author", (char *)info.Pauthor, MAX_INFO_TEXT_SIZE);
  913. xml.getparstr("comments", (char *)info.Pcomments, MAX_INFO_TEXT_SIZE);
  914. info.Ptype = xml.getpar("type", info.Ptype, 0, 16);
  915. xml.exitbranch();
  916. }
  917. if(xml.enterbranch("INSTRUMENT_KIT")) {
  918. Pkitmode = xml.getpar127("kit_mode", Pkitmode);
  919. Pdrummode = xml.getparbool("drum_mode", Pdrummode);
  920. setkititemstatus(0, 0);
  921. for(int i = 0; i < NUM_KIT_ITEMS; ++i) {
  922. if(xml.enterbranch("INSTRUMENT_KIT_ITEM", i) == 0)
  923. continue;
  924. setkititemstatus(i, xml.getparbool("enabled", kit[i].Penabled));
  925. if(kit[i].Penabled == 0) {
  926. xml.exitbranch();
  927. continue;
  928. }
  929. xml.getparstr("name", (char *)kit[i].Pname, PART_MAX_NAME_LEN);
  930. kit[i].Pmuted = xml.getparbool("muted", kit[i].Pmuted);
  931. kit[i].Pminkey = xml.getpar127("min_key", kit[i].Pminkey);
  932. kit[i].Pmaxkey = xml.getpar127("max_key", kit[i].Pmaxkey);
  933. kit[i].Psendtoparteffect = xml.getpar127(
  934. "send_to_instrument_effect",
  935. kit[i].Psendtoparteffect);
  936. kit[i].Padenabled = xml.getparbool("add_enabled",
  937. kit[i].Padenabled);
  938. if(xml.enterbranch("ADD_SYNTH_PARAMETERS")) {
  939. if(!kit[i].adpars)
  940. kit[i].adpars = new ADnoteParameters(synth, fft, &time);
  941. kit[i].adpars->getfromXML(xml);
  942. xml.exitbranch();
  943. }
  944. kit[i].Psubenabled = xml.getparbool("sub_enabled",
  945. kit[i].Psubenabled);
  946. if(xml.enterbranch("SUB_SYNTH_PARAMETERS")) {
  947. if(!kit[i].subpars)
  948. kit[i].subpars = new SUBnoteParameters(&time);
  949. kit[i].subpars->getfromXML(xml);
  950. xml.exitbranch();
  951. }
  952. kit[i].Ppadenabled = xml.getparbool("pad_enabled",
  953. kit[i].Ppadenabled);
  954. if(xml.enterbranch("PAD_SYNTH_PARAMETERS")) {
  955. if(!kit[i].padpars)
  956. kit[i].padpars = new PADnoteParameters(synth, fft, &time);
  957. kit[i].padpars->getfromXML(xml);
  958. xml.exitbranch();
  959. }
  960. xml.exitbranch();
  961. }
  962. xml.exitbranch();
  963. }
  964. if(xml.enterbranch("INSTRUMENT_EFFECTS")) {
  965. for(int nefx = 0; nefx < NUM_PART_EFX; ++nefx) {
  966. if(xml.enterbranch("INSTRUMENT_EFFECT", nefx) == 0)
  967. continue;
  968. if(xml.enterbranch("EFFECT")) {
  969. partefx[nefx]->getfromXML(xml);
  970. xml.exitbranch();
  971. }
  972. Pefxroute[nefx] = xml.getpar("route",
  973. Pefxroute[nefx],
  974. 0,
  975. NUM_PART_EFX);
  976. partefx[nefx]->setdryonly(Pefxroute[nefx] == 2);
  977. Pefxbypass[nefx] = xml.getparbool("bypass", Pefxbypass[nefx]);
  978. xml.exitbranch();
  979. }
  980. xml.exitbranch();
  981. }
  982. }
  983. void Part::getfromXML(XMLwrapper& xml)
  984. {
  985. Penabled = xml.getparbool("enabled", Penabled);
  986. setPvolume(xml.getpar127("volume", Pvolume));
  987. setPpanning(xml.getpar127("panning", Ppanning));
  988. Pminkey = xml.getpar127("min_key", Pminkey);
  989. Pmaxkey = xml.getpar127("max_key", Pmaxkey);
  990. Pkeyshift = xml.getpar127("key_shift", Pkeyshift);
  991. Prcvchn = xml.getpar127("rcv_chn", Prcvchn);
  992. Pvelsns = xml.getpar127("velocity_sensing", Pvelsns);
  993. Pveloffs = xml.getpar127("velocity_offset", Pveloffs);
  994. Pnoteon = xml.getparbool("note_on", Pnoteon);
  995. Ppolymode = xml.getparbool("poly_mode", Ppolymode);
  996. Plegatomode = xml.getparbool("legato_mode", Plegatomode); //older versions
  997. if(!Plegatomode)
  998. Plegatomode = xml.getpar127("legato_mode", Plegatomode);
  999. Pkeylimit = xml.getpar127("key_limit", Pkeylimit);
  1000. if(xml.enterbranch("INSTRUMENT")) {
  1001. getfromXMLinstrument(xml);
  1002. xml.exitbranch();
  1003. }
  1004. if(xml.enterbranch("CONTROLLER")) {
  1005. ctl.getfromXML(xml);
  1006. xml.exitbranch();
  1007. }
  1008. }
  1009. bool Part::Kit::active(void) const
  1010. {
  1011. return Padenabled || Psubenabled || Ppadenabled;
  1012. }
  1013. uint8_t Part::Kit::sendto(void) const
  1014. {
  1015. return limit((int)Psendtoparteffect, 0, NUM_PART_EFX);
  1016. }
  1017. bool Part::Kit::validNote(char note) const
  1018. {
  1019. return !Pmuted && inRange((uint8_t)note, Pminkey, Pmaxkey);
  1020. }