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.

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