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.

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