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.

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