Instruments.cpp 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574
  1. #include "core/Instruments.h"
  2. #include "core/DirectWave.h"
  3. #include "core/FlSynths.h"
  4. #include "core/FlResampler.h"
  5. #include "core/FlVoiceProcessor.h"
  6. #include "core/DrumSynthLive.h"
  7. #include "core/Gms.h"
  8. #include "core/Harmless.h"
  9. #include "core/Morphine.h"
  10. #include "core/SytrusEngine.h"
  11. #include "core/Harmor.h"
  12. #include "core/MiniSynth.h"
  13. #include "core/SimSynth.h"
  14. #include "core/Wasp.h"
  15. #include "core/Plucked.h"
  16. #include "core/BeepMap.h"
  17. #include "core/Sawer.h"
  18. #include "core/Drumaxx.h"
  19. #include "core/Granulizer.h"
  20. #include "core/Slayer.h"
  21. #include "core/Ogun.h"
  22. #include "core/TransistorBass.h"
  23. #include "core/Dx10.h"
  24. #include "core/Kepler.h"
  25. #include "core/PoiZone.h"
  26. #include "core/BassDrum.h"
  27. #include "core/FruitKick.h"
  28. #include "core/Toxic.h"
  29. #include "core/ThreeOsc.h"
  30. #include "core/PhysicalModels.h"
  31. #include <algorithm>
  32. #include <atomic>
  33. #include <cmath>
  34. #include <complex>
  35. namespace lynx
  36. {
  37. namespace
  38. {
  39. // 1 / channelGain at FL's default channel volume (10000 of 12800)
  40. float audioClipUnity() noexcept
  41. {
  42. static const float unity = 1.0f / channelGain (10000.0f / 12800.0f);
  43. return unity;
  44. }
  45. } // namespace
  46. namespace
  47. {
  48. constexpr double twoPi = 6.283185307179586;
  49. // Per-sample factor for an exponential decay that drops 60 dB in `seconds`.
  50. float decayCoefficient (double seconds, double sampleRate) noexcept
  51. {
  52. return (float) std::exp (std::log (0.001) / (seconds * sampleRate));
  53. }
  54. // In-place complex radix-2 FFT (wavetables for the spectral oscillator)
  55. void fftInPlace (std::vector<std::complex<double>>& a, bool inverse)
  56. {
  57. const auto n = a.size();
  58. for (std::size_t i = 1, j = 0; i < n; ++i)
  59. {
  60. auto bit = n >> 1;
  61. for (; j & bit; bit >>= 1)
  62. j ^= bit;
  63. j ^= bit;
  64. if (i < j)
  65. std::swap (a[i], a[j]);
  66. }
  67. for (std::size_t len = 2; len <= n; len <<= 1)
  68. {
  69. const auto w = std::polar (1.0, (inverse ? 2.0 : -2.0) * twoPi / 2.0 / (double) len);
  70. for (std::size_t i = 0; i < n; i += len)
  71. {
  72. std::complex<double> wn (1.0, 0.0);
  73. for (std::size_t k = 0; k < len / 2; ++k)
  74. {
  75. const auto u = a[i + k], v = a[i + k + len / 2] * wn;
  76. a[i + k] = u + v;
  77. a[i + k + len / 2] = u - v;
  78. wn *= w;
  79. }
  80. }
  81. }
  82. }
  83. double midiToHz (int key) noexcept
  84. {
  85. return 440.0 * std::pow (2.0, (key - 69) / 12.0);
  86. }
  87. // ---------------------------------------------------------------------------
  88. // Drums: each hit takes a voice; a few voices allow short overlaps.
  89. struct DrumVoice
  90. {
  91. bool active = false;
  92. float level = 0.0f; // amplitude envelope
  93. float velocity = 0.0f;
  94. double phase = 0.0;
  95. double pitchEnv = 0.0; // kick/snare: pitch envelope
  96. float filterState = 0.0f;
  97. float lastNoise = 0.0f;
  98. float lastHighPass = 0.0f;
  99. int age = 0; // samples since the hit
  100. };
  101. class DrumInstrument final : public Instrument
  102. {
  103. public:
  104. explicit DrumInstrument (InstrumentKind k) : kind (k) {}
  105. void prepare (double sr) noexcept override
  106. {
  107. sampleRate = sr;
  108. const double decaySeconds = kind == InstrumentKind::kick ? 0.45
  109. : kind == InstrumentKind::snare ? 0.22
  110. : kind == InstrumentKind::clap ? 0.30
  111. : 0.06; // hat
  112. decay = decayCoefficient (decaySeconds, sr);
  113. pitchDecay = decayCoefficient (kind == InstrumentKind::kick ? 0.08 : 0.03, sr);
  114. allNotesOff();
  115. }
  116. void noteOn (int, float velocity) noexcept override
  117. {
  118. // Steals the oldest voice if all are busy.
  119. DrumVoice* target = &voices[0];
  120. for (auto& v : voices)
  121. {
  122. if (! v.active)
  123. {
  124. target = &v;
  125. break;
  126. }
  127. if (v.age > target->age)
  128. target = &v;
  129. }
  130. *target = {};
  131. target->active = true;
  132. target->level = 1.0f;
  133. target->velocity = velocity;
  134. target->pitchEnv = 1.0;
  135. }
  136. void noteOff (int) noexcept override {} // drums play until the end of the decay
  137. void allNotesOff() noexcept override
  138. {
  139. for (auto& v : voices)
  140. v.active = false;
  141. }
  142. void render (float* left, float* right, int n, float gl, float gr) noexcept override
  143. {
  144. for (auto& v : voices)
  145. {
  146. if (! v.active)
  147. continue;
  148. for (int i = 0; i < n; ++i)
  149. {
  150. const auto s = nextSample (v) * v.velocity;
  151. left[i] += s * gl;
  152. right[i] += s * gr;
  153. }
  154. if (v.level < 0.0005f)
  155. v.active = false;
  156. }
  157. }
  158. bool idle() const noexcept override
  159. {
  160. return std::none_of (voices.begin(), voices.end(), [] (const auto& v) { return v.active; });
  161. }
  162. private:
  163. float nextSample (DrumVoice& v) noexcept
  164. {
  165. float out = 0.0f;
  166. switch (kind)
  167. {
  168. case InstrumentKind::kick:
  169. {
  170. const auto hz = 45.0 + 110.0 * v.pitchEnv; // sweep 155 → 45 Hz
  171. v.phase += twoPi * hz / sampleRate;
  172. out = (float) std::sin (v.phase) * v.level;
  173. break;
  174. }
  175. case InstrumentKind::snare:
  176. {
  177. const auto hz = 180.0 + 60.0 * v.pitchEnv;
  178. v.phase += twoPi * hz / sampleRate;
  179. const auto tone = (float) std::sin (v.phase) * (float) v.pitchEnv;
  180. const auto noise = highPass (v, noiseGen.next());
  181. out = (0.5f * tone + 0.7f * noise) * v.level;
  182. break;
  183. }
  184. case InstrumentKind::hat:
  185. out = 0.8f * highPass (v, noiseGen.next()) * v.level;
  186. break;
  187. case InstrumentKind::clap:
  188. {
  189. // Three short snaps followed by a tail: mimics several hands.
  190. const auto ms = v.age * 1000.0 / sampleRate;
  191. const auto burst = ms < 30.0 ? (float) std::exp (-std::fmod (ms, 10.0) / 2.0) : 1.0f;
  192. out = 0.8f * bandPass (v, noiseGen.next()) * v.level * burst;
  193. break;
  194. }
  195. case InstrumentKind::synth:
  196. case InstrumentKind::sampler:
  197. case InstrumentKind::audioClip:
  198. case InstrumentKind::plugin:
  199. case InstrumentKind::controller:
  200. case InstrumentKind::sakura:
  201. case InstrumentKind::drumpad:
  202. case InstrumentKind::boobass:
  203. case InstrumentKind::drumsynth:
  204. case InstrumentKind::harmless:
  205. case InstrumentKind::sytrus:
  206. case InstrumentKind::harmor:
  207. case InstrumentKind::gms:
  208. case InstrumentKind::morphine:
  209. case InstrumentKind::ogun:
  210. case InstrumentKind::minisynth:
  211. case InstrumentKind::dx10:
  212. case InstrumentKind::kepler:
  213. case InstrumentKind::poizone:
  214. case InstrumentKind::fruitkick:
  215. case InstrumentKind::bassdrum:
  216. case InstrumentKind::toxic:
  217. case InstrumentKind::threeosc:
  218. case InstrumentKind::autogun:
  219. case InstrumentKind::transistorbass:
  220. case InstrumentKind::simsynth:
  221. case InstrumentKind::wasp:
  222. case InstrumentKind::plucked:
  223. case InstrumentKind::beepmap:
  224. case InstrumentKind::sawer:
  225. case InstrumentKind::flkeys:
  226. case InstrumentKind::granulizer:
  227. case InstrumentKind::drumaxx:
  228. case InstrumentKind::slayer:
  229. case InstrumentKind::fruitydance:
  230. case InstrumentKind::directwave:
  231. break;
  232. }
  233. v.level *= decay;
  234. v.pitchEnv *= pitchDecay;
  235. ++v.age;
  236. return out;
  237. }
  238. // Simple 1st-order high-pass (difference), good enough for cymbal noise.
  239. static float highPass (DrumVoice& v, float x) noexcept
  240. {
  241. const auto y = 0.85f * (v.filterState + x - v.lastNoise);
  242. v.lastNoise = x;
  243. v.filterState = y;
  244. return y;
  245. }
  246. // Cheap band-pass: high-pass followed by a two-point average.
  247. static float bandPass (DrumVoice& v, float x) noexcept
  248. {
  249. const auto hp = highPass (v, x);
  250. const auto y = 0.5f * (hp + v.lastHighPass);
  251. v.lastHighPass = hp;
  252. return y;
  253. }
  254. InstrumentKind kind;
  255. double sampleRate = 44100.0;
  256. float decay = 0.999f;
  257. double pitchDecay = 0.999;
  258. std::array<DrumVoice, 4> voices {};
  259. Noise noiseGen;
  260. };
  261. // Per-voice pan gains (constant power, 1 at center).
  262. inline void voicePan (float pan, float& left, float& right) noexcept
  263. {
  264. const auto angle = (std::clamp (pan, -1.0f, 1.0f) + 1.0f) * 0.25f * 3.14159265f;
  265. left = std::cos (angle) * 1.41421356f;
  266. right = std::sin (angle) * 1.41421356f;
  267. }
  268. // ---------------------------------------------------------------------------
  269. // Simple polyphonic synth: sawtooth with low-pass and AR envelope.
  270. // ---------------------------------------------------------------------------
  271. // Modulation envelopes (cutoff and pitch), per voice: 0 attack, 1 hold, 2 decay,
  272. // 3 sustain, 4 release. Straight segments (tension 0, the FL default; REA_rodada3 §1.5).
  273. struct ModState
  274. {
  275. float level = 0.0f;
  276. float releaseStep = 0.0f; // fixed on note release: from the current level down to 0
  277. int stage = 0, held = 0;
  278. // Toxic shape: samples left in the current 128-sample block, elapsed time and the block's target/coefficient
  279. int blockLeft = 0;
  280. double elapsed = 0.0;
  281. float target = 0.0f, coefficient = 0.0f;
  282. };
  283. struct ModCoefficients
  284. {
  285. bool active = false, toxic = false;
  286. float amount = 0.0f, attackStep = 1.0f, decayStep = 1.0f, releasePerLevel = 1.0f, sustain = 0.0f;
  287. float toxicAttack = 0.0f, toxicDecay = 0.0f, toxicRelease = 0.0f; // per-sample coefficients
  288. int holdSamples = 0;
  289. static ModCoefficients make (const ModEnvelope& e, double sampleRate) noexcept
  290. {
  291. ModCoefficients c;
  292. c.active = e.amount != 0.0f;
  293. c.amount = e.amount;
  294. if (e.shape == 1)
  295. {
  296. // REA_rodada33 §2.1–2.2: times in seconds (floor 0.001), sustain level as is
  297. auto seconds = [] (float t) { return std::max (t, 0.001f); };
  298. c.toxic = true;
  299. c.attackStep = seconds (e.attack); // the attack stage lasts while elapsed < A
  300. c.sustain = e.sustain;
  301. c.toxicAttack = (float) (8.82 / ((double) seconds (e.attack) * 39.441975 * sampleRate));
  302. c.toxicDecay = (float) (8.82 / ((double) seconds (e.decay) * sampleRate));
  303. c.toxicRelease = (float) (8.82 / ((double) seconds (e.release) * sampleRate));
  304. return c;
  305. }
  306. c.attackStep = (float) (1.0 / (std::max (0.0005, (double) e.attack) * sampleRate));
  307. c.holdSamples = (int) (std::max (0.0f, e.hold) * sampleRate);
  308. c.sustain = std::clamp (e.sustain, 0.0f, 1.0f);
  309. c.decayStep = (float) ((1.0 - c.sustain) / (std::max (0.0005, (double) e.decay) * sampleRate)); // from 1 to sustain
  310. c.releasePerLevel = (float) (1.0 / (std::max (0.002, (double) e.release) * sampleRate));
  311. return c;
  312. }
  313. void advance (ModState& m) const noexcept
  314. {
  315. if (toxic)
  316. {
  317. // stage chosen at each block start (released → 0, attack → 5 while elapsed < A, else decay → S + 1e-7);
  318. // one-pole step every sample, clipped at 1
  319. if (--m.blockLeft < 0)
  320. {
  321. m.blockLeft = 127;
  322. if (m.stage == 4)
  323. m.target = 0.0f, m.coefficient = toxicRelease;
  324. else if ((double) attackStep <= m.elapsed)
  325. m.target = sustain + 1.0e-7f, m.coefficient = toxicDecay;
  326. else
  327. m.target = 5.0f, m.coefficient = toxicAttack;
  328. m.elapsed += 128.0 / 44100.0;
  329. }
  330. m.level = std::min (1.0f, (m.target - m.level) * m.coefficient + m.level);
  331. return;
  332. }
  333. switch (m.stage)
  334. {
  335. case 0:
  336. m.level += attackStep;
  337. if (m.level >= 1.0f) { m.level = 1.0f; m.stage = 1; }
  338. break;
  339. case 1:
  340. if (++m.held >= holdSamples) m.stage = 2;
  341. break;
  342. case 2:
  343. m.level -= decayStep;
  344. if (m.level <= sustain) { m.level = sustain; m.stage = 3; }
  345. break;
  346. case 3: break;
  347. default: m.level = std::max (0.0f, m.level - m.releaseStep); break;
  348. }
  349. }
  350. void release (ModState& m) const noexcept
  351. {
  352. m.stage = 4;
  353. m.releaseStep = m.level * releasePerLevel;
  354. }
  355. };
  356. // Channel LFO, advanced on the control tick.
  357. struct LfoState
  358. {
  359. double phase = 0.0;
  360. float fade = 0.0f;
  361. double delayLeft = 0.0; // samples
  362. };
  363. struct LfoCoefficients
  364. {
  365. bool active = false;
  366. float amount = 0.0f;
  367. double increment = 0.0; // cycles per sample
  368. double delaySamples = 0.0;
  369. float fadeStep = 1.0f; // per sample
  370. int shape = 0;
  371. bool global = false;
  372. double cyclesPerTick = 0.0; // global: phase = song position (ticks) × this
  373. static LfoCoefficients make (const ChannelLfo& l, double sampleRate, double bpm) noexcept
  374. {
  375. LfoCoefficients c;
  376. c.active = l.amount != 0.0f;
  377. c.amount = l.amount;
  378. const auto unit = l.sync ? 60.0 / std::max (1.0, bpm) : 1.0; // beats -> seconds
  379. c.increment = 1.0 / (std::max (0.005, (double) l.period * unit) * sampleRate);
  380. const auto timeUnit = l.secondsTiming ? 1.0 : unit;
  381. c.delaySamples = std::max (0.0, (double) l.delay * timeUnit * sampleRate);
  382. c.fadeStep = l.attack > 0.0f ? (float) (1.0 / ((double) l.attack * timeUnit * sampleRate)) : 1.0f;
  383. c.shape = std::clamp (l.shape, 0, 2);
  384. c.global = l.global;
  385. // period in beats (synced) or in seconds converted via BPM
  386. const auto periodBeats = l.sync ? std::max (0.005, (double) l.period) : std::max (0.005, (double) l.period) * std::max (1.0, bpm) / 60.0;
  387. c.cyclesPerTick = 1.0 / (periodBeats * ppq);
  388. return c;
  389. }
  390. // `songTicks`: song position (a global LFO starts at its phase; delay and fade-in stay per note)
  391. void start (LfoState& s, double songTicks = 0.0) const noexcept
  392. {
  393. s = { 0.0, fadeStep >= 1.0f ? 1.0f : 0.0f, delaySamples };
  394. if (global)
  395. {
  396. s.phase = songTicks * cyclesPerTick;
  397. s.phase -= std::floor (s.phase);
  398. }
  399. }
  400. // advances `n` samples and returns the output (±1, fade-in already applied)
  401. float tick (LfoState& s, int n) const noexcept
  402. {
  403. if (s.delayLeft > 0.0)
  404. {
  405. s.delayLeft -= n;
  406. return 0.0f;
  407. }
  408. s.phase += increment * n;
  409. s.phase -= std::floor (s.phase);
  410. s.fade = std::min (1.0f, s.fade + fadeStep * (float) n);
  411. const auto p = s.phase;
  412. float value = 0.0f;
  413. switch (shape)
  414. {
  415. case 1: value = (float) (p < 0.25 ? 4.0 * p : p < 0.75 ? 2.0 - 4.0 * p : 4.0 * p - 4.0); break;
  416. case 2: value = p < 0.5 ? 1.0f : -1.0f; break;
  417. default: value = (float) std::sin (6.283185307179586 * p); break;
  418. }
  419. return value * s.fade;
  420. }
  421. };
  422. // "TPT" SVF low-pass coefficients (stable at any cutoff), shared by the synth and the sampler.
  423. // The same filter gives all four responses (mode: 0 low-pass, 1 band-pass, 2 high-pass,
  424. // 3 band-stop), like the LP/BP/HP/BS types of FL's channel filter.
  425. struct SvfCoefficients
  426. {
  427. float a1 = 1.0f, a2 = 0.0f, a3 = 0.0f, k = 2.0f;
  428. int mode = 0;
  429. // 4-pole ladder (Toxic Biohazard, REA_rodada26 §2): f = 2fc/fs, k = 3.6f − 1.6f² − 1, p = (k + 1)/2, feedback
  430. // res·R(u) with u = (log2 fc − 5)/9; stages s = (x + x_prev)·p − k·s_prev; input saturated by
  431. // v·(1 − 3a + 4a² − 2a³), a = min(|v|/15, 1). (FL builds its table for 44.1 kHz; LYNX keeps fc in Hz at any rate.)
  432. bool ladder = false;
  433. float lp = 0.0f, lk = 0.0f, feedback = 0.0f;
  434. void setLadder (double cutoffHz, float resonance, double sampleRate, int filterMode) noexcept
  435. {
  436. ladder = true;
  437. mode = std::clamp (filterMode, 0, 2);
  438. const auto fc = std::clamp (cutoffHz, 32.0, 16384.0 * sampleRate / 44100.0);
  439. const auto f = 2.0 * fc / sampleRate;
  440. const auto kk = 3.6 * f - 1.6 * f * f - 1.0, p = (kk + 1.0) / 2.0;
  441. const auto u = std::clamp ((std::log2 (fc) - 5.0) / 9.0, 0.0, 1.0);
  442. const auto r = 1.96 * std::pow (1.0 - u, 1.5)
  443. + 0.98 * (0.95 * std::exp ((1.0 - p) * 1.386249) + (u > 0.7 ? 8.0 / 9.0 * (u - 0.7) * (u - 0.7) : 0.0));
  444. lp = (float) p;
  445. lk = (float) kk;
  446. feedback = (float) (std::clamp (resonance, 0.0f, 1.0f) * r);
  447. }
  448. // state: s1…s4 and the previous input of each stage
  449. float processLadder (float in, std::array<float, 8>& st) const noexcept
  450. {
  451. auto v = in - feedback * st[3];
  452. const auto a = std::min (std::abs (v) / 15.0f, 1.0f);
  453. v *= 1.0f - 3.0f * a + 4.0f * a * a - 2.0f * a * a * a;
  454. auto x = v;
  455. for (int i = 0; i < 4; ++i)
  456. {
  457. const auto s = (x + st[(std::size_t) i + 4]) * lp - lk * st[(std::size_t) i];
  458. st[(std::size_t) i + 4] = x;
  459. st[(std::size_t) i] = s;
  460. x = s;
  461. }
  462. switch (mode)
  463. {
  464. case 1: return st[2] - st[3];
  465. case 2: return v - st[3];
  466. default: return st[3];
  467. }
  468. }
  469. void set (double cutoffHz, float resonance, double sampleRate, int filterMode = 0, bool useLadder = false) noexcept
  470. {
  471. if (useLadder)
  472. {
  473. setLadder (cutoffHz, resonance, sampleRate, filterMode);
  474. return;
  475. }
  476. ladder = false;
  477. const auto fc = std::clamp (cutoffHz, 20.0, sampleRate * 0.45);
  478. const auto g = (float) std::tan (3.14159265358979 * fc / sampleRate);
  479. k = 2.0f - 1.9f * std::clamp (resonance, 0.0f, 1.0f); // 2 = no resonance
  480. a1 = 1.0f / (1.0f + g * (g + k));
  481. a2 = g * a1;
  482. a3 = g * a2;
  483. mode = std::clamp (filterMode, 0, 3);
  484. }
  485. float process (float in, float& low, float& band) const noexcept
  486. {
  487. const auto v3 = in - low;
  488. const auto v1 = a1 * band + a2 * v3;
  489. const auto v2 = low + a2 * band + a3 * v3;
  490. band = 2.0f * v1 - band;
  491. low = 2.0f * v2 - low;
  492. switch (mode)
  493. {
  494. case 1: return v1;
  495. case 2: return in - k * v1 - v2;
  496. case 3: return in - k * v1;
  497. default: return v2;
  498. }
  499. }
  500. };
  501. // Kepler's chorus (REA_rodada26 §3): mono input → high-pass (0.5 Hz) → two RBJ low-passes (7 kHz, Q 0.707) →
  502. // one delay line read by two taps (L and R LFO phases) with Catmull-Rom interpolation → 1-pole low-pass 7 kHz →
  503. // equal-power mix (m → 0.5). Delay = base + depth·w(LFO), smoothed by s = 1 − 0.1^(20/fs). Noise/gate not modelled.
  504. class KeplerChorus
  505. {
  506. public:
  507. void prepare (double sr) noexcept
  508. {
  509. sampleRate = sr;
  510. smooth = 1.0 - std::pow (0.1, 20.0 / sr);
  511. const auto th = std::tan (3.141592653589793 * 0.5 / sr);
  512. hpB = 1.0 / (1.0 + th);
  513. hpA = (1.0 - th) / (1.0 + th);
  514. const auto tl = std::tan (3.141592653589793 * 7000.0 / sr);
  515. lpB = tl / (1.0 + tl);
  516. lpA = (1.0 - tl) / (1.0 + tl);
  517. const auto w0 = 2.0 * 3.141592653589793 * 7000.0 / sr, alpha = std::sin (w0) / (2.0 * 0.707), a0 = 1.0 + alpha;
  518. bq = { (1.0 - std::cos (w0)) / 2.0 / a0, (1.0 - std::cos (w0)) / a0, (1.0 - std::cos (w0)) / 2.0 / a0,
  519. -2.0 * std::cos (w0) / a0, (1.0 - alpha) / a0 };
  520. reset();
  521. }
  522. void reset() noexcept
  523. {
  524. line.fill (0.0f);
  525. write = 0;
  526. phase = 0.0f;
  527. delay = { 0.01, 0.01 };
  528. mix = 0.0;
  529. outputGain = 0.0;
  530. hpX = hpY = 0.0;
  531. biquad = {};
  532. post = {};
  533. }
  534. // in place on a mono-summed signal; left/right receive the stereo result
  535. void process (float* left, float* right, int n, int mode) noexcept
  536. {
  537. const auto rate = mode == 3 ? 8.0 : mode == 2 ? 0.6 : 0.4;
  538. const auto offset = mode == 3 ? 0.0286111f : 0.5f;
  539. const auto base = mode == 3 ? 0.00285 : 0.00108, depth = mode == 3 ? 0.00052 : 0.00415;
  540. const auto increment = (float) (rate / sampleRate);
  541. for (int i = 0; i < n; ++i)
  542. {
  543. const double dry = 0.5 * ((double) left[i] + right[i]);
  544. // pre-filter (high-pass, then two low-pass biquads) into the delay line
  545. const auto hp = hpB * (dry - hpX) + hpA * hpY;
  546. hpX = dry;
  547. hpY = hp;
  548. auto x = hp;
  549. for (auto& st : biquad)
  550. {
  551. const auto y = bq[0] * x + st[0];
  552. st[0] = bq[1] * x - bq[3] * y + st[1];
  553. st[1] = bq[2] * x - bq[4] * y;
  554. x = y;
  555. }
  556. line[(std::size_t) write] = (float) x;
  557. mix += (0.5 - mix) * smooth;
  558. outputGain += (1.0 - outputGain) * smooth; // the unit fades in after it starts (§3.3 step 10)
  559. const auto wetGain = std::sqrt (mix), dryGain = std::sqrt (1.0 - mix);
  560. for (int c = 0; c < 2; ++c)
  561. {
  562. auto ph = phase + (c == 1 ? offset : 0.0f);
  563. ph -= std::floor (ph);
  564. const double w = mode == 3 ? (std::sin (2.0 * 3.141592653589793 * ph) + 1.0) / 2.0
  565. : ph < 0.25f ? 2.0 * ph + 0.5 : ph < 0.75f ? 1.5 - 2.0 * ph : 2.0 * ph - 1.5;
  566. auto& d = delay[(std::size_t) c];
  567. d += (base + depth * w - d) * smooth;
  568. const auto samples = d * sampleRate;
  569. const auto whole = (int) samples;
  570. const auto t = samples - whole;
  571. auto tap = [&] (int back) { return (double) line[(std::size_t) ((write - back) & mask)]; };
  572. const auto y0 = tap (whole - 1), y1 = tap (whole), y2 = tap (whole + 1), y3 = tap (whole + 2);
  573. const auto wet = y1 + 0.5 * t * (y2 - y0 + t * (2.0 * y0 - 5.0 * y1 + 4.0 * y2 - y3 + t * (3.0 * (y1 - y2) + y3 - y0)));
  574. auto& p = post[(std::size_t) c];
  575. const auto filtered = lpB * (wet + p[0]) + lpA * p[1];
  576. p[0] = wet;
  577. p[1] = filtered;
  578. (c == 0 ? left : right)[i] = (float) ((filtered * wetGain + dry * dryGain) * outputGain);
  579. }
  580. phase += increment;
  581. if (phase >= 1.0f)
  582. phase -= 1.0f;
  583. write = (write + 1) & mask;
  584. }
  585. }
  586. private:
  587. static constexpr int size = 32768, mask = size - 1;
  588. double sampleRate = 44100.0, smooth = 0.001;
  589. double hpB = 1.0, hpA = 0.0, lpB = 0.5, lpA = 0.0;
  590. std::array<double, 5> bq {};
  591. std::array<std::array<double, 2>, 2> biquad {}, post {};
  592. double hpX = 0.0, hpY = 0.0, mix = 0.0, outputGain = 0.0;
  593. std::array<double, 2> delay { 0.01, 0.01 };
  594. std::array<float, size> line {};
  595. int write = 0;
  596. float phase = 0.0f; // float32 LFO phase, as in FL (§3.5)
  597. };
  598. struct SynthVoice
  599. {
  600. float panL = 1.0f, panR = 1.0f;
  601. double glideRatio = 1.0; // multiplies the frequency every sample during a slide
  602. int glideLeft = 0;
  603. bool active = false;
  604. bool releasing = false;
  605. int key = 0;
  606. float velocity = 0.0f;
  607. float level = 0.0f; // envelope
  608. int stage = 0; // 0 attack, 1 decay, 2 sustain, 3 release
  609. double phaseDelta = 0.0; // of the fundamental (each oscillator multiplies it)
  610. std::array<double, 3> phase {};
  611. float low = 0.0f, band = 0.0f; // filter states
  612. float lowR = 0.0f, bandR = 0.0f; // right-side filter (only with per-oscillator pan)
  613. std::array<std::array<float, 8>, 2> ladder {}; // ladder filter states (left, right)
  614. std::array<ModState, 2> mod {}; // filter, pitch
  615. std::array<LfoState, lfoTargets> lfo {};
  616. float lfoGain = 1.0f, lfoGainStep = 0.0f; // volume LFO, ramped between ticks
  617. float basePan = 0.0f; // note pan (the pan LFO adds to it)
  618. SvfCoefficients filter; // this voice's (only with a cutoff envelope)
  619. double pitchMul = 1.0;
  620. float fmLevel = 1.0f; // FM index envelope (1 -> fmSustain)
  621. double sweep = 1.0; // s of the pitch sweep (1 -> 0)
  622. float tone[2][2] {}; // states of the two low-passes of the 3-band tone control (per side)
  623. int controlCountdown = 0;
  624. int age = 0;
  625. };
  626. // Settings exchange without blocking the audio thread: the UI writes under a short flag and audio
  627. // only copies when it can grab the flag (if it can't, it uses the old settings for this block).
  628. template <typename T>
  629. class SettingsMailbox
  630. {
  631. public:
  632. void write (const T& value) noexcept
  633. {
  634. while (busy.test_and_set (std::memory_order_acquire)) {}
  635. pending = value;
  636. dirty = true;
  637. busy.clear (std::memory_order_release);
  638. }
  639. bool read (T& out) noexcept
  640. {
  641. if (busy.test_and_set (std::memory_order_acquire))
  642. return false;
  643. const auto changed = dirty;
  644. if (changed)
  645. {
  646. out = pending;
  647. dirty = false;
  648. }
  649. busy.clear (std::memory_order_release);
  650. return changed;
  651. }
  652. private:
  653. std::atomic_flag busy = ATOMIC_FLAG_INIT;
  654. T pending {};
  655. bool dirty = false;
  656. };
  657. class SynthInstrument final : public Instrument
  658. {
  659. public:
  660. void prepare (double sr) noexcept override
  661. {
  662. sampleRate = sr;
  663. lastPhaseDelta = 0.0;
  664. chorusUnit.prepare (sr);
  665. updateCoefficients();
  666. allNotesOff();
  667. }
  668. void configure (const ChannelDef& channel, double songBpm) noexcept override
  669. {
  670. bpm.store (std::max (1.0, songBpm)); // first: the synced LFO uses it when reading the settings
  671. updateFrames (channel.synth);
  672. mailbox.write (channel.synth);
  673. }
  674. ~SynthInstrument() override
  675. {
  676. delete incomingFrames.exchange (nullptr);
  677. delete retiredFrames.exchange (nullptr);
  678. delete activeFrames;
  679. }
  680. void startModulation (SynthVoice& v, float pan) noexcept
  681. {
  682. v.basePan = pan;
  683. v.lfoGain = 1.0f;
  684. v.lfoGainStep = 0.0f;
  685. v.sweep = 1.0;
  686. std::fill (&v.tone[0][0], &v.tone[0][0] + 4, 0.0f);
  687. v.controlCountdown = 0;
  688. for (std::size_t i = 0; i < lfoTargets; ++i)
  689. if (lfos[i].active)
  690. lfos[i].start (v.lfo[i], songTicks);
  691. }
  692. void setSongPosition (double ticks) noexcept override { songTicks = ticks; }
  693. // portamento: the voice starts at `from` and glides to `to` over the porta time (channel porta,
  694. // inverted by the note)
  695. void glide (SynthVoice& v, double from, double to) noexcept
  696. {
  697. const auto steps = (int) (settings.portaBeats * 60.0 / bpm.load() * sampleRate);
  698. const auto on = settings.porta != nextPorta;
  699. if (! on || settings.portaBeats <= 0.0f || from <= 0.0 || steps < 1)
  700. {
  701. v.phaseDelta = to;
  702. v.glideLeft = 0;
  703. return;
  704. }
  705. v.phaseDelta = from;
  706. v.glideRatio = std::pow (to / from, 1.0 / steps); // linear in semitones, like FL
  707. v.glideLeft = steps;
  708. }
  709. void noteOn (int key, float velocity) noexcept override
  710. {
  711. if (mailbox.read (settings))
  712. updateCoefficients();
  713. if (settings.mono)
  714. {
  715. // mono channel (polyphony 1 in FL): the sounding voice changes note without resetting phase or filter;
  716. // the envelopes restart from the current level
  717. SynthVoice* sounding = nullptr;
  718. for (auto& v : voices)
  719. if (v.active && (sounding == nullptr || v.age < sounding->age))
  720. sounding = &v;
  721. if (sounding != nullptr)
  722. {
  723. for (auto& v : voices)
  724. if (&v != sounding)
  725. v.active = false;
  726. auto& v = *sounding;
  727. v.key = key;
  728. v.velocity = velocity;
  729. v.releasing = false;
  730. v.stage = 0;
  731. v.age = 0;
  732. const auto target = midiToHz (key) / sampleRate * std::pow (2.0, nextCents / 1200.0);
  733. glide (v, v.phaseDelta, target);
  734. lastPhaseDelta = target;
  735. for (auto& m : v.mod)
  736. m = { m.level, 0.0f, 0, 0 };
  737. v.fmLevel = 1.0f;
  738. voicePan (nextPan, v.panL, v.panR);
  739. startModulation (v, nextPan);
  740. nextPan = nextCents = 0.0f;
  741. nextPorta = false;
  742. return;
  743. }
  744. }
  745. SynthVoice* target = &voices[0];
  746. for (auto& v : voices)
  747. {
  748. if (! v.active)
  749. {
  750. target = &v;
  751. break;
  752. }
  753. if (v.age > target->age)
  754. target = &v;
  755. }
  756. *target = {};
  757. target->active = true;
  758. target->key = key;
  759. target->velocity = velocity;
  760. const auto delta = midiToHz (key) / sampleRate * std::pow (2.0, nextCents / 1200.0);
  761. glide (*target, lastPhaseDelta, delta); // with porta, starts from the previous note's pitch
  762. lastPhaseDelta = delta;
  763. voicePan (nextPan, target->panL, target->panR);
  764. startModulation (*target, nextPan);
  765. nextPan = nextCents = 0.0f;
  766. nextPorta = false;
  767. }
  768. void setNextNoteExpression (float pan, float cents, bool porta) noexcept override
  769. {
  770. nextPan = pan;
  771. nextCents = cents;
  772. nextPorta = porta;
  773. }
  774. void slideTo (int key, float cents, float samples) noexcept override
  775. {
  776. const auto target = midiToHz (key) / sampleRate * std::pow (2.0, cents / 1200.0);
  777. const auto steps = std::max (1, (int) samples);
  778. for (auto& v : voices)
  779. if (v.active && ! v.releasing && v.phaseDelta > 0.0)
  780. {
  781. v.glideRatio = std::pow (target / v.phaseDelta, 1.0 / steps);
  782. v.glideLeft = steps; // the voice keeps its original key: its "off" is what ends the note
  783. }
  784. }
  785. void noteOff (int key) noexcept override
  786. {
  787. for (auto& v : voices)
  788. if (v.active && ! v.releasing && v.key == key)
  789. {
  790. v.releasing = true;
  791. v.stage = 3;
  792. for (std::size_t e = 0; e < 2; ++e)
  793. modEnv[e].release (v.mod[e]);
  794. }
  795. }
  796. void allNotesOff() noexcept override
  797. {
  798. for (auto& v : voices)
  799. v.active = false;
  800. }
  801. void render (float* left, float* right, int n, float gl, float gr) noexcept override
  802. {
  803. if (mailbox.read (settings))
  804. updateCoefficients();
  805. // new spectrum frames (built in configure): the old set goes back for the other thread to free
  806. if (retiredFrames.load() == nullptr)
  807. if (auto* frames = incomingFrames.exchange (nullptr))
  808. {
  809. retiredFrames.store (activeFrames); // a set with count 0 stays active as "static spectrum"
  810. activeFrames = frames;
  811. evolving = frames->count > 1;
  812. }
  813. // Kepler chorus: voices without the channel's volume/pan → chorus (mono in, stereo out) → volume/pan
  814. if (settings.chorus > 0)
  815. {
  816. const auto anyActive = std::any_of (voices.begin(), voices.end(), [] (const SynthVoice& v) { return v.active; });
  817. if (anyActive)
  818. chorusTail = (int) (0.05 * sampleRate); // the delay (≤ 5.2 ms) and filters ring a little after the last voice
  819. for (int done = 0; done < n; done += scratchSize)
  820. {
  821. const auto m = std::min (scratchSize, n - done);
  822. std::fill (scratchL.begin(), scratchL.begin() + m, 0.0f);
  823. std::fill (scratchR.begin(), scratchR.begin() + m, 0.0f);
  824. renderVoices (scratchL.data(), scratchR.data(), m, 1.0f, 1.0f);
  825. chorusUnit.process (scratchL.data(), scratchR.data(), m, settings.chorus);
  826. for (int i = 0; i < m; ++i)
  827. {
  828. left[done + i] += scratchL[(std::size_t) i] * gl;
  829. right[done + i] += scratchR[(std::size_t) i] * gr;
  830. }
  831. }
  832. if (! anyActive)
  833. chorusTail = std::max (0, chorusTail - n);
  834. return;
  835. }
  836. renderVoices (left, right, n, gl, gr);
  837. }
  838. void renderVoices (float* left, float* right, int n, float gl, float gr) noexcept
  839. {
  840. for (auto& v : voices)
  841. {
  842. if (! v.active)
  843. continue;
  844. for (int i = 0; i < n; ++i)
  845. {
  846. if (evolving) // evolving spectrum: the two frames around the note's age
  847. {
  848. const auto t = v.age / sampleRate;
  849. const auto x = std::min ((double) (activeFrames->count - 1), (activeFrames->count - 1) * std::sqrt (t / activeFrames->span));
  850. const auto k = std::min ((int) x, activeFrames->count - 2);
  851. frameA = &activeFrames->tables[(std::size_t) k];
  852. frameB = &activeFrames->tables[(std::size_t) k + 1];
  853. frameMix = (float) (x - k);
  854. }
  855. // ADSR envelope
  856. switch (v.stage)
  857. {
  858. case 0:
  859. v.level += attackStep;
  860. if (v.level >= 1.0f) { v.level = 1.0f; v.stage = 1; }
  861. break;
  862. case 1:
  863. v.level = settings.sustain + (v.level - settings.sustain) * decayCoeff;
  864. if (v.level - settings.sustain < 0.001f) { v.level = settings.sustain; v.stage = 2; }
  865. break;
  866. case 2: break;
  867. default: v.level *= releaseCoeff; break;
  868. }
  869. if (v.glideLeft > 0)
  870. {
  871. v.phaseDelta *= v.glideRatio;
  872. --v.glideLeft;
  873. }
  874. if (modulated)
  875. {
  876. for (std::size_t e = 0; e < 2; ++e)
  877. if (modEnv[e].active)
  878. modEnv[e].advance (v.mod[e]);
  879. // every 16 samples (the control "tick"): pitch, filter, volume and pan
  880. if (--v.controlCountdown <= 0)
  881. {
  882. v.controlCountdown = 16;
  883. auto semitones = modEnv[1].active ? modEnv[1].amount * v.mod[1].level : 0.0f;
  884. auto octaves = modEnv[0].active ? modEnv[0].amount * v.mod[0].level : 0.0f;
  885. octaves += settings.keyTrack * (float) (v.key - 48) / 12.0f;
  886. if (lfos[lfoPitch].active)
  887. semitones += lfos[lfoPitch].amount * lfos[lfoPitch].tick (v.lfo[lfoPitch], 16);
  888. if (settings.vibratoCents > 0.0f) // 6 Hz global phase, depth × r², r = 3·age/fs ≤ 1
  889. {
  890. const auto r = std::min (1.0, 3.0 * (v.age + 1) / sampleRate);
  891. const auto phase = vibratoPhase + 6.0 * i / sampleRate;
  892. semitones += (float) (settings.vibratoCents / 100.0 * r * r * std::sin (2.0 * 3.141592653589793 * phase));
  893. }
  894. if (lfos[lfoCutoff].active)
  895. octaves += lfos[lfoCutoff].amount * lfos[lfoCutoff].tick (v.lfo[lfoCutoff], 16);
  896. if (lfos[lfoVolume].active)
  897. {
  898. const auto target = std::max (0.0f, 1.0f + lfos[lfoVolume].amount * lfos[lfoVolume].tick (v.lfo[lfoVolume], 16));
  899. v.lfoGainStep = (target - v.lfoGain) / 16.0f;
  900. }
  901. if (lfos[lfoPan].active)
  902. voicePan (v.basePan + lfos[lfoPan].amount * lfos[lfoPan].tick (v.lfo[lfoPan], 16), v.panL, v.panR);
  903. v.pitchMul = semitones != 0.0f ? std::exp2 (semitones / 12.0) : 1.0;
  904. if (settings.sweep > 0.0f)
  905. {
  906. const auto s2 = v.sweep * v.sweep;
  907. v.pitchMul *= 1.0 + settings.sweep * s2 * s2;
  908. v.sweep *= sweepCoeff;
  909. }
  910. if (filterModulated)
  911. v.filter.set (settings.cutoff * std::exp2 (octaves), settings.resonance, sampleRate, settings.filterType, settings.ladder);
  912. }
  913. v.lfoGain += v.lfoGainStep;
  914. }
  915. float sum = 0.0f, sumR = 0.0f, modulator = 0.0f;
  916. double fmShift = 0.0;
  917. // AM/FM: osc 3 is not summed, it modulates (first, so FM shifts the phase of osc 1 + 2)
  918. if (osc3Modulates)
  919. {
  920. const auto& osc = settings.osc[2];
  921. if (osc.level > 0.0f)
  922. {
  923. const auto delta = std::min (0.49, v.phaseDelta * ratios[2] * v.pitchMul);
  924. modulator = osc.level * oscillator (osc.wave, v.phase[2], delta);
  925. v.phase[2] += delta;
  926. if (v.phase[2] >= 1.0)
  927. v.phase[2] -= 1.0;
  928. }
  929. if (settings.fm > 0.0f)
  930. {
  931. v.fmLevel = settings.fmSustain + (v.fmLevel - settings.fmSustain) * fmDecayCoeff;
  932. fmShift = (double) (settings.fm * v.fmLevel * modulator);
  933. }
  934. }
  935. for (std::size_t o = 0; o < (osc3Modulates ? 2u : 3u); ++o)
  936. {
  937. const auto& osc = settings.osc[o];
  938. if (osc.level <= 0.0f)
  939. continue;
  940. const auto delta = std::min (0.49, v.phaseDelta * ratios[o] * v.pitchMul);
  941. auto phase = v.phase[o];
  942. if (fmShift != 0.0)
  943. {
  944. phase += fmShift;
  945. phase -= std::floor (phase);
  946. }
  947. const auto value = osc.level * oscillator (osc.wave, phase, delta);
  948. sum += value * oscPanL[o];
  949. sumR += value * oscPanR[o];
  950. v.phase[o] += delta;
  951. if (v.phase[o] >= 1.0) // delta < 0.5: at most one wrap (no floor, which is a function call on CPUs without SSE4)
  952. v.phase[o] -= 1.0;
  953. }
  954. if (settings.am) // (o1·g1 + o2·g2)·(1 − g3·o3), REA_rodada6 §3; ring (Sytrus): 1 − g3 + g3·o3, rodada18 §2
  955. {
  956. const auto factor = settings.ring ? 1.0f - settings.osc[2].level + modulator : 1.0f - modulator;
  957. sum *= factor;
  958. sumR *= factor;
  959. }
  960. // resonant low-pass filter (state variable "TPT": stable at any cutoff)
  961. const auto& f = filterModulated ? v.filter : sharedFilter;
  962. auto outL = f.ladder ? f.processLadder (sum, v.ladder[0]) : f.process (sum, v.low, v.band);
  963. auto outR = ! stereoOscillators ? outL : f.ladder ? f.processLadder (sumR, v.ladder[1]) : f.process (sumR, v.lowR, v.bandR);
  964. if (useBands)
  965. {
  966. auto bands = [&] (float x, float* st) {
  967. st[0] += toneCoeff[0] * (x - st[0]);
  968. st[1] += toneCoeff[1] * (x - st[1]);
  969. return st[0] * settings.bandGain[0] + (st[1] - st[0]) * settings.bandGain[1] + (x - st[1]) * settings.bandGain[2];
  970. };
  971. outL = bands (outL, v.tone[0]);
  972. outR = stereoOscillators ? bands (outR, v.tone[1]) : outL;
  973. }
  974. const auto s = 0.3f * v.level * v.velocity * v.lfoGain;
  975. auto tl = 1.0f, tr = 1.0f;
  976. if (settings.stereoTremolo > 0.0f) // rectified 2.5 Hz, L/R a quarter period apart; 0.1 s fade-in per voice
  977. {
  978. const auto theta = 2.0 * 3.141592653589793 * (tremoloPhase + 2.5 * i / sampleRate);
  979. const auto d = (double) settings.stereoTremolo;
  980. const auto r = std::min (1.0, v.age / std::max (1.0, std::round (0.1 * sampleRate)));
  981. tl = (float) (1.0 + r * d * (std::abs (1.25 * std::cos (theta)) - 1.0));
  982. tr = (float) (1.0 + r * d * (std::abs (1.25 * std::sin (theta)) - 1.0));
  983. }
  984. left[i] += outL * s * gl * v.panL * tl;
  985. right[i] += outR * s * gr * v.panR * tr;
  986. ++v.age;
  987. }
  988. if (v.stage == 3 && v.level < 0.0005f)
  989. v.active = false;
  990. }
  991. // global free-running phases (Harmless tremolo and vibrato)
  992. tremoloPhase += 2.5 * n / sampleRate;
  993. tremoloPhase -= std::floor (tremoloPhase);
  994. vibratoPhase += 6.0 * n / sampleRate;
  995. vibratoPhase -= std::floor (vibratoPhase);
  996. }
  997. bool idle() const noexcept override
  998. {
  999. return chorusTail <= 0 && std::none_of (voices.begin(), voices.end(), [] (const auto& v) { return v.active; });
  1000. }
  1001. private:
  1002. static constexpr int scratchSize = 1024;
  1003. std::array<float, scratchSize> scratchL {}, scratchR {};
  1004. KeplerChorus chorusUnit;
  1005. int chorusTail = 0;
  1006. double tremoloPhase = 0.0, vibratoPhase = 0.0;
  1007. // sine of a 0..1 phase via a refined parabola (error < 0.1%), much cheaper than std::sin
  1008. static float fastSine (double phase) noexcept
  1009. {
  1010. auto x = (float) (phase < 0.5 ? phase : phase - 1.0) * 2.0f; // -1..1 (half cycle = 1)
  1011. const auto y = 4.0f * x * (1.0f - std::abs (x)); // parabola
  1012. return 0.225f * (y * std::abs (y) - y) + y; // refinement
  1013. }
  1014. // aliasing correction at discontinuities (polyBLEP)
  1015. static float polyBlep (double t, double dt) noexcept
  1016. {
  1017. if (t < dt)
  1018. {
  1019. t /= dt;
  1020. return (float) (t + t - t * t - 1.0);
  1021. }
  1022. if (t > 1.0 - dt)
  1023. {
  1024. t = (t - 1.0) / dt;
  1025. return (float) (t * t + t + t + 1.0);
  1026. }
  1027. return 0.0f;
  1028. }
  1029. float oscillator (Waveform w, double phase, double dt) noexcept
  1030. {
  1031. switch (w)
  1032. {
  1033. case Waveform::sine: return fastSine (phase);
  1034. case Waveform::triangle: return (float) (phase < 0.5 ? 4.0 * phase - 1.0 : 3.0 - 4.0 * phase);
  1035. case Waveform::saw: return (float) (2.0 * phase - 1.0) - polyBlep (phase, dt);
  1036. case Waveform::square:
  1037. {
  1038. auto s = phase < 0.5 ? 1.0f : -1.0f;
  1039. s += polyBlep (phase, dt);
  1040. s -= polyBlep (phase < 0.5 ? phase + 0.5 : phase - 0.5, dt);
  1041. return s;
  1042. }
  1043. case Waveform::noise: return noise.next();
  1044. case Waveform::spectral:
  1045. {
  1046. // the table with harmonics up to 1024 >> j stays below Nyquist: j = lowest level that fits
  1047. int level = 0;
  1048. while (level < wavetableLevels - 1 && (double) (1024 >> level) * dt > 0.5)
  1049. ++level;
  1050. const auto pos = phase * wavetableSize;
  1051. const auto i = std::min ((int) pos, wavetableSize - 1);
  1052. const auto f = (float) (pos - i);
  1053. auto read = [&] (const Tables& tables) {
  1054. const auto& t = tables[(std::size_t) level];
  1055. return t[(std::size_t) i] + f * (t[(std::size_t) i + 1] - t[(std::size_t) i]);
  1056. };
  1057. if (evolving)
  1058. {
  1059. const auto a = read (*frameA);
  1060. return a + frameMix * (read (*frameB) - a);
  1061. }
  1062. return read (wavetables);
  1063. }
  1064. }
  1065. return 0.0f;
  1066. }
  1067. // band-limited wavetables of the spectrum (IFFT per level; level j holds harmonics ≤ 1024 >> j)
  1068. static constexpr int wavetableSize = 2048, wavetableLevels = 10;
  1069. using Tables = std::array<std::array<float, wavetableSize + 1>, wavetableLevels>;
  1070. Tables wavetables {};
  1071. // evolving spectrum: `count` snapshots at t_f = span·(f/(count − 1))², harmonic h scaled by 10^(−3t/decay_h)
  1072. struct Frames
  1073. {
  1074. int count = 0;
  1075. double span = 1.0;
  1076. std::vector<Tables> tables;
  1077. };
  1078. static constexpr int frameCount = 8;
  1079. std::atomic<Frames*> incomingFrames { nullptr }, retiredFrames { nullptr };
  1080. Frames* activeFrames = nullptr; // audio thread only
  1081. bool evolving = false;
  1082. const Tables* frameA = nullptr;
  1083. const Tables* frameB = nullptr;
  1084. float frameMix = 0.0f;
  1085. // configure() side: what the last frames were built from
  1086. std::array<float, SynthSettings::spectrumSize> framedSpectrum {}, framedPhase {}, framedDecay {}, framedTarget {};
  1087. static void fillTables (Tables& tables, const std::array<float, SynthSettings::spectrumSize>& amplitude,
  1088. const std::array<float, SynthSettings::spectrumSize>& phase, std::vector<std::complex<double>>& bins)
  1089. {
  1090. for (int level = 0; level < wavetableLevels; ++level)
  1091. {
  1092. std::fill (bins.begin(), bins.end(), std::complex<double> {});
  1093. const auto top = std::min (SynthSettings::spectrumSize, 1024 >> level);
  1094. for (int h = 1; h <= top; ++h)
  1095. {
  1096. // a·sin(2π(h·t + φ)) = Im: coefficient −i·a/2·e^(i2πφ) at +h and its conjugate at −h
  1097. const auto a = (double) amplitude[(std::size_t) h - 1] * (2.0 / 3.141592653589793); // 1/n saw = LYNX's ±1 saw
  1098. const auto c = std::polar (a / 2.0, twoPi * phase[(std::size_t) h - 1] - twoPi / 4.0);
  1099. bins[(std::size_t) h] = c;
  1100. bins[(std::size_t) (wavetableSize - h)] = std::conj (c);
  1101. }
  1102. fftInPlace (bins, true);
  1103. auto& t = tables[(std::size_t) level];
  1104. for (int i = 0; i < wavetableSize; ++i)
  1105. t[(std::size_t) i] = (float) bins[(std::size_t) i].real();
  1106. t[(std::size_t) wavetableSize] = t[0];
  1107. }
  1108. }
  1109. // called from configure() (off the audio thread): builds the frames when the evolving spectrum changes
  1110. void updateFrames (const SynthSettings& s)
  1111. {
  1112. delete retiredFrames.exchange (nullptr);
  1113. const auto spectral = std::any_of (s.osc.begin(), s.osc.end(), [] (const SynthOscillator& o) { return o.wave == Waveform::spectral; });
  1114. const auto evolving = spectral && std::any_of (s.spectrumDecay.begin(), s.spectrumDecay.end(), [] (float t) { return t > 0.0f; });
  1115. const auto wasEvolving = std::any_of (framedDecay.begin(), framedDecay.end(), [] (float t) { return t > 0.0f; });
  1116. if (! evolving && ! wasEvolving)
  1117. return;
  1118. if (evolving && framedSpectrum == s.spectrum && framedPhase == s.spectrumPhase && framedDecay == s.spectrumDecay
  1119. && framedTarget == s.spectrumTarget)
  1120. return;
  1121. framedTarget = s.spectrumTarget;
  1122. framedSpectrum = s.spectrum;
  1123. framedPhase = s.spectrumPhase;
  1124. framedDecay = evolving ? s.spectrumDecay : std::array<float, SynthSettings::spectrumSize> {};
  1125. auto* frames = new Frames; // count 0 = back to the static spectrum
  1126. if (evolving)
  1127. {
  1128. frames->count = frameCount;
  1129. frames->span = std::min (60.0, (double) *std::max_element (s.spectrumDecay.begin(), s.spectrumDecay.end()));
  1130. frames->tables.resize ((std::size_t) frameCount);
  1131. std::vector<std::complex<double>> bins ((std::size_t) wavetableSize);
  1132. for (int f = 0; f < frameCount; ++f)
  1133. {
  1134. const auto t = frames->span * std::pow ((double) f / (frameCount - 1), 2.0);
  1135. auto amplitude = s.spectrum;
  1136. for (std::size_t h = 0; h < amplitude.size(); ++h)
  1137. if (s.spectrumDecay[h] > 0.0f)
  1138. amplitude[h] = s.spectrumTarget[h]
  1139. + (amplitude[h] - s.spectrumTarget[h]) * (float) std::pow (10.0, -3.0 * t / s.spectrumDecay[h]);
  1140. fillTables (frames->tables[(std::size_t) f], amplitude, s.spectrumPhase, bins);
  1141. }
  1142. }
  1143. delete incomingFrames.exchange (frames);
  1144. }
  1145. std::array<float, SynthSettings::spectrumSize> builtSpectrum {}, builtPhase {};
  1146. bool wavetablesBuilt = false;
  1147. std::vector<std::complex<double>> fftBins = std::vector<std::complex<double>> ((std::size_t) wavetableSize);
  1148. void buildWavetables()
  1149. {
  1150. if (wavetablesBuilt && builtSpectrum == settings.spectrum && builtPhase == settings.spectrumPhase)
  1151. return;
  1152. builtSpectrum = settings.spectrum;
  1153. builtPhase = settings.spectrumPhase;
  1154. wavetablesBuilt = true;
  1155. fillTables (wavetables, settings.spectrum, settings.spectrumPhase, fftBins); // bins allocated with the instrument
  1156. }
  1157. void updateCoefficients() noexcept
  1158. {
  1159. if (std::any_of (settings.osc.begin(), settings.osc.end(), [] (const SynthOscillator& o) { return o.wave == Waveform::spectral; }))
  1160. buildWavetables(); // only when the spectrum changes
  1161. attackStep = (float) (1.0 / (std::max (0.0005, (double) settings.attack) * sampleRate));
  1162. decayCoeff = decayCoefficient (std::max (0.001, (double) settings.decay), sampleRate);
  1163. releaseCoeff = decayCoefficient (std::max (0.005, (double) settings.release), sampleRate);
  1164. for (std::size_t o = 0; o < 3; ++o)
  1165. {
  1166. const auto& osc = settings.osc[o];
  1167. ratios[o] = std::pow (2.0, osc.octave + (osc.semitones * 100.0 + osc.detune) / 1200.0);
  1168. const auto p = std::clamp (osc.pan, -1.0f, 1.0f);
  1169. oscPanL[o] = p > 0.0f ? 1.0f - p : 1.0f;
  1170. oscPanR[o] = p < 0.0f ? 1.0f + p : 1.0f;
  1171. }
  1172. stereoOscillators = std::any_of (settings.osc.begin(), settings.osc.end(), [] (const SynthOscillator& o) { return o.pan != 0.0f; });
  1173. osc3Modulates = settings.am || settings.fm > 0.0f;
  1174. fmDecayCoeff = settings.fmDecay > 0.0f ? decayCoefficient (std::max (0.001, (double) settings.fmDecay), sampleRate) : 1.0f;
  1175. sharedFilter.set (settings.cutoff, settings.resonance, sampleRate, settings.filterType, settings.ladder);
  1176. modEnv[0] = ModCoefficients::make (settings.filterEnv, sampleRate);
  1177. modEnv[1] = ModCoefficients::make (settings.pitchEnv, sampleRate);
  1178. auto anyLfo = false;
  1179. for (std::size_t i = 0; i < lfoTargets; ++i)
  1180. {
  1181. lfos[i] = LfoCoefficients::make (settings.lfo[i], sampleRate, bpm.load());
  1182. anyLfo = anyLfo || lfos[i].active;
  1183. }
  1184. filterModulated = modEnv[0].active || lfos[lfoCutoff].active || settings.keyTrack != 0.0f;
  1185. modulated = modEnv[0].active || modEnv[1].active || anyLfo || settings.keyTrack != 0.0f || settings.sweep > 0.0f
  1186. || settings.vibratoCents > 0.0f;
  1187. sweepCoeff = std::exp (-16.0 / (std::max (0.0005, (double) settings.sweepTime) * sampleRate)); // per 16-sample tick
  1188. useBands = settings.bandGain != std::array<float, 3> { 1.0f, 1.0f, 1.0f };
  1189. toneCoeff[0] = (float) std::min (1.0, 0.025 * 44100.0 / sampleRate); // ≈ 178 Hz (REA_rodada18 §11)
  1190. toneCoeff[1] = (float) std::min (1.0, 0.155 * 44100.0 / sampleRate); // ≈ 1.18 kHz
  1191. }
  1192. double sampleRate = 44100.0;
  1193. SettingsMailbox<SynthSettings> mailbox;
  1194. SynthSettings settings;
  1195. float attackStep = 0.01f;
  1196. float decayCoeff = 0.999f;
  1197. float releaseCoeff = 0.999f;
  1198. SvfCoefficients sharedFilter; // without a cutoff envelope, all voices use this one
  1199. std::array<ModCoefficients, 2> modEnv {};
  1200. std::array<LfoCoefficients, lfoTargets> lfos {};
  1201. bool modulated = false, filterModulated = false;
  1202. std::array<double, 3> ratios { 1.0, 1.0, 1.0 };
  1203. std::atomic<double> bpm { 120.0 };
  1204. double lastPhaseDelta = 0.0; // pitch of the last note (where porta starts from)
  1205. double songTicks = 0.0; // song position in the block (global LFO)
  1206. std::array<float, 3> oscPanL { 1.0f, 1.0f, 1.0f }, oscPanR { 1.0f, 1.0f, 1.0f };
  1207. bool stereoOscillators = false;
  1208. bool osc3Modulates = false; // AM or FM: osc 3 is not summed
  1209. float fmDecayCoeff = 1.0f;
  1210. double sweepCoeff = 1.0;
  1211. bool useBands = false;
  1212. float toneCoeff[2] { 0.025f, 0.155f };
  1213. float nextPan = 0.0f, nextCents = 0.0f;
  1214. bool nextPorta = false;
  1215. Noise noise;
  1216. std::array<SynthVoice, 16> voices {};
  1217. };
  1218. // ---------------------------------------------------------------------------
  1219. // Sampler: plays the whole sample on each note (one-shot, like an FL step),
  1220. // transposed by the key (60 = original pitch), with FL's sampler interpolation (core/FlResampler.h: 24-point sinc while
  1221. // playing, 32-point when exporting, FL's defaults; REA_rodada69 §1).
  1222. struct SamplerVoice
  1223. {
  1224. bool active = false;
  1225. double position = 0.0; // read position in region order (reversed voices read the region backwards)
  1226. double rate = 1.0; // frames per output sample (> 0)
  1227. bool reversed = false;
  1228. int loops = 0; // times the zone loop has wrapped (FL lets taps before the loop start wrap only then)
  1229. flrs::Kernel kernel;
  1230. bool flEnvelope = false; // FL's volume articulator drives the level (the ADSR stays at 1)
  1231. flvp::Art volumeArt;
  1232. double tickLeft = 0.0; // samples until the next sequencer tick
  1233. float flLevel = 0.0f, flStep = 0.0f; // the level ramps linearly to each tick's value over the tick (FL)
  1234. float velocity = 0.0f;
  1235. float fade = 1.0f; // < 1 when the voice was stolen (declick)
  1236. bool stolen = false;
  1237. int age = 0;
  1238. int key = 60;
  1239. float env = 1.0f; // envelope
  1240. float envStep = 0.0f; // attack step (> 0) or release step (< 0)
  1241. int stage = 1; // 0 attack, 1 decay, 2 sustain, 3 release
  1242. double first = 0.0, last = 0.0; // played region: first and last frame (inclusive)
  1243. float clipElapsed = 0.0f, clipRemaining = 0.0f, fadeIn = 0.0f, fadeOut = 0.0f; // clip fades
  1244. float panL = 1.0f, panR = 1.0f;
  1245. double glideRatio = 1.0;
  1246. int glideLeft = 0;
  1247. float lowL = 0.0f, bandL = 0.0f, lowR = 0.0f, bandR = 0.0f; // channel filter
  1248. std::array<ModState, 2> mod {}; // cutoff and pitch envelopes
  1249. std::array<LfoState, lfoTargets> lfo {};
  1250. float lfoGain = 1.0f, lfoGainStep = 0.0f;
  1251. float basePan = 0.0f;
  1252. const SampleData* data = nullptr; // this voice's sample (the chosen zone, in multi-sample)
  1253. float zoneGain = 1.0f;
  1254. double loopStart = 0.0, loopEnd = 0.0; // loopEnd > loopStart: the voice jumps back to the loop start
  1255. bool loopWhileHeld = false;
  1256. SvfCoefficients filter; // this voice's (only with a cutoff envelope)
  1257. double pitchMul = 1.0;
  1258. int controlCountdown = 0;
  1259. // FL's native sampler voice (REA_rodada76): the channel's articulators and filter (flvp), the note's initial
  1260. // volume and pan, the stereo gains ramping between ticks, the fast LP's running coefficient, the song tick index
  1261. bool flVoice = false;
  1262. flvp::Proc flProc;
  1263. float initVol = 1.0f, notePan = 0.0f;
  1264. float gL = 0.0f, gR = 0.0f, sL = 0.0f, sR = 0.0f;
  1265. float fcRun = 0.0f, fcSlope = 0.0f;
  1266. std::int64_t tickIndex = 0;
  1267. double nextGap = 0.0; // samples from this tick to the next one on the song's grid
  1268. int endFade = -1; // ≥ 0: past the sample's end, the last frame fading out (FL's 10 ms end fade)
  1269. int offFade = -1; // ≥ 0: a looping voice fading out after its note-off (the same table)
  1270. float holdL = 0.0f, holdR = 0.0f; // the last frame read
  1271. };
  1272. // FL's note velocity → initial volume (FLEngine FUN_00d29aa0, REA_rodada76 §1): x = byte·0.01; 1 at x = 1, else
  1273. // (exp(x·ln 11) − 1)·0.1 — velocity 100 is unity, 128 ≈ 2.05
  1274. inline float flInitVolume (float velocity) noexcept
  1275. {
  1276. static const float ln11 = (float) std::log (11.0);
  1277. const auto x = (float) std::nearbyint (std::clamp (velocity, 0.0f, 1.0f) * 128.0f) * 0.01f;
  1278. if (x == 1.0f)
  1279. return 1.0f;
  1280. return (float) ((std::exp ((double) (x * ln11)) - 1.0) * (double) 0.1f);
  1281. }
  1282. class SamplerInstrument final : public Instrument
  1283. {
  1284. public:
  1285. // clipMode: Playlist audio clip (no transposition, stops on noteOff; it follows Reverse and the stretch)
  1286. SamplerInstrument (std::shared_ptr<const SampleData> s, bool clip) : sample (std::move (s)), clipMode (clip) {}
  1287. // multi-sample: called before the instrument goes to the audio thread
  1288. void setZones (std::vector<LoadedZone> z)
  1289. {
  1290. zones = std::move (z);
  1291. zones.erase (std::remove_if (zones.begin(), zones.end(), [] (const LoadedZone& lz) { return lz.sample == nullptr || lz.sample->frames() < 2; }),
  1292. zones.end());
  1293. if (sample == nullptr && ! zones.empty())
  1294. sample = zones.front().sample;
  1295. }
  1296. // the zone for the key/velocity; several covering the same note take turns like FPC's "cycle" layers (REA_rodada69
  1297. // §4: among the zones covering the note, in order, the one after the last chosen, wrapping); if none covers it, the
  1298. // one with the nearest root key. The velocity index is FL's round(velocity · 128), at most 127.
  1299. const LoadedZone* zoneFor (int key, float velocity) noexcept
  1300. {
  1301. if (zones.empty())
  1302. return nullptr;
  1303. const auto vel = std::min (127, (int) std::nearbyint (std::clamp (velocity, 0.0f, 1.0f) * 128.0f));
  1304. const LoadedZone* nearest = nullptr;
  1305. int matches[16] {};
  1306. int matchCount = 0, lastAt = -1;
  1307. for (int i = 0; i < (int) zones.size(); ++i)
  1308. {
  1309. const auto& z = zones[(std::size_t) i];
  1310. if (key >= z.zone.lowKey && key <= z.zone.highKey && vel >= z.zone.lowVelocity && vel <= z.zone.highVelocity && matchCount < 16)
  1311. {
  1312. if (i == lastZone)
  1313. lastAt = matchCount;
  1314. matches[matchCount++] = i;
  1315. }
  1316. if (nearest == nullptr || std::abs (z.zone.rootKey - key) < std::abs (nearest->zone.rootKey - key))
  1317. nearest = &z;
  1318. }
  1319. if (matchCount == 0)
  1320. return nearest;
  1321. const auto pick = matchCount == 1 || lastAt + 1 >= matchCount ? 0 : lastAt + 1;
  1322. lastZone = matches[pick];
  1323. return &zones[(std::size_t) lastZone];
  1324. }
  1325. void prepare (double sr) noexcept override
  1326. {
  1327. sampleRate = sr;
  1328. quality = offlineRendering() ? flrs::renderQuality : flrs::liveQuality;
  1329. fadeStep = (float) (1.0 / (0.003 * sr)); // 3 ms
  1330. updateModulation();
  1331. allNotesOff();
  1332. }
  1333. void configure (const ChannelDef& channel, double songBpm) noexcept override
  1334. {
  1335. const auto& s = channel.sampler;
  1336. pitch.store (std::clamp (s.pitch, -24.0f, 24.0f));
  1337. attack.store (std::clamp (s.attack, 0.0f, 2.0f));
  1338. decay.store (std::clamp (s.decay, 0.0f, 10.0f));
  1339. sustain.store (std::clamp (s.sustain, 0.0f, 1.0f));
  1340. release.store (std::clamp (s.release, 0.0f, 4.0f));
  1341. reverse.store (s.reverse);
  1342. cut.store (s.cut);
  1343. // with "keep pitch" the sample arrives already stretched (RackState): play at normal speed
  1344. stretchBeats.store (s.keepPitch ? 0.0f : std::max (0.0f, s.stretchBeats));
  1345. regionStart.store (std::clamp (s.regionStart, 0.0f, 1.0f));
  1346. regionEnd.store (std::clamp (s.regionEnd, 0.0f, 1.0f));
  1347. porta.store (s.porta);
  1348. portaBeats.store (std::max (0.0f, s.portaBeats));
  1349. cutoff.store (std::clamp (s.cutoff, 20.0f, 20000.0f));
  1350. resonance.store (std::clamp (s.resonance, 0.0f, 1.0f));
  1351. filterType.store (std::clamp (s.filterType, 0, 3));
  1352. bpm.store (std::max (1.0, songBpm)); // before the mailbox: the synced LFO reads it when updating
  1353. {
  1354. Modulation m { { s.filterEnv, s.pitchEnv }, s.lfo };
  1355. if (s.flChannel.size() == 89 || s.flChannel.size() == 90)
  1356. {
  1357. // FL's channel articulators and filter in the plugins' 364-byte snapshot layout (REA_rodada76 §4)
  1358. std::array<std::uint8_t, flvp::snapshotSize> snap {};
  1359. std::memcpy (snap.data(), s.flChannel.data(), 85 * 4);
  1360. std::memcpy (snap.data() + 0x15c, &s.flChannel[85], 4);
  1361. std::memcpy (snap.data() + 0x160, &s.flChannel[86], 4);
  1362. std::memcpy (snap.data() + 0x168, &s.flChannel[87], 4);
  1363. const auto ppq = std::clamp ((int) s.flChannel[88], 24, 3840);
  1364. m.flNative = true;
  1365. m.flTriangular = s.flChannel.size() == 90 && s.flChannel[89] == 2;
  1366. m.fl.build (snap.data(), ppq, std::max (1.0, songBpm));
  1367. m.ticksPerSecond = (double) ppq * std::max (1.0, songBpm) / 60.0;
  1368. }
  1369. else if (s.flVolumeEnvelope.size() == 18)
  1370. {
  1371. const auto ppq = std::clamp ((int) s.flVolumeEnvelope[17], 24, 3840);
  1372. m.flVolume = true;
  1373. m.volume.build (s.flVolumeEnvelope.data(), ppq, std::max (1.0, songBpm));
  1374. m.ticksPerSecond = (double) ppq * std::max (1.0, songBpm) / 60.0;
  1375. }
  1376. envelopeMailbox.write (m);
  1377. }
  1378. SliceTable table;
  1379. table.count = (int) std::min<std::size_t> (s.slices.size(), table.starts.size());
  1380. for (int i = 0; i < table.count; ++i)
  1381. table.starts[(std::size_t) i] = std::clamp (s.slices[(std::size_t) i], 0.0f, 1.0f);
  1382. sliceMailbox.write (table);
  1383. bpm.store (std::max (1.0, songBpm));
  1384. }
  1385. // Sample frames read per output sample (before note tuning). With
  1386. // stretch, the whole sample lasts `stretchBeats` at the current tempo (resampling, like FL's
  1387. // "resample" mode: the pitch follows).
  1388. double baseRate (const SampleData& data) const noexcept
  1389. {
  1390. const auto beats = stretchBeats.load();
  1391. if (beats > 0.0f)
  1392. return (double) data.frames() / ((double) beats * 60.0 / bpm.load() * sampleRate);
  1393. return data.sampleRate * (1.0 / sampleRate);
  1394. }
  1395. void noteOn (int key, float velocity) noexcept override { noteOnAt (key, velocity, 0.0); }
  1396. void noteOnAt (int key, float velocity, double startSeconds) noexcept override
  1397. {
  1398. const auto* zone = clipMode ? nullptr : zoneFor (key, velocity);
  1399. const auto* data = zone != nullptr ? zone->sample.get() : sample.get();
  1400. if (envelopeMailbox.read (modulation))
  1401. updateModulation();
  1402. if (data == nullptr || data->frames() < 2)
  1403. return;
  1404. sliceMailbox.read (slices);
  1405. const auto backwards = reverse.load(); // audio clips too (the clip menu's Reverse)
  1406. const auto total = (double) (data->frames() - 1);
  1407. // sample region (the start acts as "start offset"); audio clips use the whole file. `last` is the region's
  1408. // last frame: FL plays until the read position passes it, interpolating with that frame repeated.
  1409. auto first = clipMode ? 0.0 : std::floor (total * std::min (regionStart.load(), regionEnd.load()));
  1410. auto last = clipMode ? total : std::max (first + 1.0, std::floor (total * regionEnd.load()));
  1411. auto sliced = false;
  1412. // sliced sample: each key from C5 up plays one slice, at the original pitch
  1413. if (! clipMode && slices.count > 0)
  1414. {
  1415. const auto index = key - 60;
  1416. if (index < 0 || index >= slices.count)
  1417. return;
  1418. first = std::floor (total * slices.starts[(std::size_t) index]);
  1419. last = index + 1 < slices.count ? std::max (first, std::floor (total * slices.starts[(std::size_t) index + 1]) - 1.0) : total;
  1420. sliced = true;
  1421. }
  1422. const auto stretched = stretchBeats.load() > 0.0f;
  1423. const auto base = baseRate (*data);
  1424. auto startFrame = first + std::max (0.0, startSeconds * sampleRate * base);
  1425. if (startFrame >= last + 1.0)
  1426. return;
  1427. if (! clipMode && cut.load())
  1428. for (auto& v : voices)
  1429. if (v.active)
  1430. v.stolen = true; // "cut itself": the previous note fades out quickly
  1431. SamplerVoice* target = nullptr;
  1432. for (auto& v : voices)
  1433. if (! v.active)
  1434. {
  1435. target = &v;
  1436. break;
  1437. }
  1438. if (target == nullptr)
  1439. {
  1440. // No free voice: steal the oldest.
  1441. target = &voices[0];
  1442. for (auto& v : voices)
  1443. if (v.age > target->age)
  1444. target = &v;
  1445. }
  1446. // with stretch (FL's "resample") the note pitch does not change the speed
  1447. const auto root = zone != nullptr ? zone->zone.rootKey : 60;
  1448. const auto tune = zone != nullptr ? (double) zone->zone.tune : 0.0;
  1449. const auto semitones = clipMode || stretched ? 0.0 : (sliced ? 0 : key - root) + tune + (double) pitch.load() + nextCents / 100.0;
  1450. const auto attackSeconds = clipMode ? 0.0f : attack.load();
  1451. *target = {};
  1452. target->active = true;
  1453. target->key = key;
  1454. // FL plays a Playlist audio clip at unity gain at the channel's default volume (78%): the channel volume
  1455. // curve is relative to that point for clips (REA_rodada89 §4.2 [EXEC]: +5.2 dB at every volume and pan)
  1456. target->velocity = clipMode ? velocity * audioClipUnity() : velocity;
  1457. target->data = data;
  1458. target->zoneGain = zone != nullptr ? zone->zone.gain : 1.0f;
  1459. // zone loop (DirectWave): only when playing forward and with the loop inside the region
  1460. if (zone != nullptr && zone->zone.loopMode != 0 && ! backwards && zone->zone.loopEnd > zone->zone.loopStart + 16
  1461. && (double) zone->zone.loopEnd <= last && (double) zone->zone.loopStart >= first)
  1462. {
  1463. target->loopStart = (double) zone->zone.loopStart;
  1464. target->loopEnd = (double) zone->zone.loopEnd;
  1465. target->loopWhileHeld = zone->zone.loopMode == 2;
  1466. }
  1467. target->position = startFrame;
  1468. target->first = first;
  1469. target->last = last;
  1470. target->clipElapsed = nextClip[0];
  1471. target->clipRemaining = nextClip[1];
  1472. target->fadeIn = nextClip[2];
  1473. target->fadeOut = nextClip[3];
  1474. nextClip = {};
  1475. // FL's read speed: the rate ratio at the original pitch, else exp(cents·ln2/1200)·ratio
  1476. target->rate = stretched ? base : flrs::speedFor ((float) (semitones * 100.0), base);
  1477. target->reversed = backwards;
  1478. target->kernel.setQuality (quality);
  1479. // portamento (channel porta, inverted by the note): starts from the previous note's pitch
  1480. if (! clipMode && (porta.load() != nextPorta) && lastRate != 0.0 && ! stretched)
  1481. {
  1482. const auto steps = (int) (portaBeats.load() * 60.0 / bpm.load() * sampleRate);
  1483. const auto from = std::abs (lastRate);
  1484. if (steps >= 1 && from != 0.0)
  1485. {
  1486. target->glideRatio = std::pow (target->rate / from, 1.0 / steps);
  1487. target->glideLeft = steps;
  1488. target->rate = from;
  1489. }
  1490. }
  1491. if (! clipMode)
  1492. lastRate = target->glideLeft > 0 ? target->rate * std::pow (target->glideRatio, target->glideLeft) : target->rate;
  1493. target->env = attackSeconds > 0.0f ? 0.0f : 1.0f;
  1494. target->envStep = attackSeconds > 0.0f ? (float) (1.0 / (attackSeconds * sampleRate)) : 0.0f;
  1495. target->stage = attackSeconds > 0.0f ? 0 : 1;
  1496. // FL's volume articulator: starts at its initial level and is stepped on the voice's first block (FLEngine
  1497. // FUN_00d24ae0 steps a new voice at once, then once per sequencer tick)
  1498. target->flEnvelope = ! clipMode && modulation.flVolume && modulation.ticksPerSecond > 0.0;
  1499. if (target->flEnvelope)
  1500. {
  1501. target->env = 1.0f;
  1502. target->envStep = 0.0f;
  1503. target->stage = 1;
  1504. target->volumeArt.init (modulation.volume);
  1505. target->flLevel = target->volumeArt.val;
  1506. target->flStep = 0.0f;
  1507. target->tickLeft = 0.0;
  1508. }
  1509. // FL's native sampler voice (REA_rodada76): the articulators start, the first render block steps them at once,
  1510. // the following steps fall on the song's tick grid (the tick this note starts on, then round(k · spt))
  1511. target->flVoice = ! clipMode && modulation.flNative && modulation.ticksPerSecond > 0.0;
  1512. if (target->flVoice)
  1513. {
  1514. target->flEnvelope = false;
  1515. target->env = 1.0f;
  1516. target->envStep = 0.0f;
  1517. target->stage = 1;
  1518. target->flProc.init (modulation.fl);
  1519. target->initVol = flInitVolume (velocity);
  1520. target->notePan = nextPan;
  1521. const auto spt = sampleRate / modulation.ticksPerSecond;
  1522. target->tickIndex = (std::int64_t) std::nearbyint (songSample / spt);
  1523. target->tickLeft = 0.0;
  1524. target->nextGap = std::max (1.0, (double) flvp::roundEven ((double) (target->tickIndex + 1) * spt) - songSample);
  1525. // the file's own loop (WAV smpl): FL plays it while the note lasts (REA_rodada76 §8)
  1526. if (zone == nullptr && ! backwards && data->loopStart >= 0 && data->loopEnd > data->loopStart + 1
  1527. && (double) data->loopStart >= first && (double) data->loopEnd <= last + 1.0)
  1528. {
  1529. target->loopStart = (double) data->loopStart;
  1530. target->loopEnd = (double) data->loopEnd;
  1531. target->loopWhileHeld = false;
  1532. }
  1533. }
  1534. voicePan (clipMode ? 0.0f : nextPan, target->panL, target->panR);
  1535. target->basePan = clipMode ? 0.0f : nextPan;
  1536. for (std::size_t i = 0; i < lfoTargets; ++i)
  1537. if (lfos[i].active && ! clipMode)
  1538. lfos[i].start (target->lfo[i], songTicks);
  1539. nextPan = nextCents = 0.0f;
  1540. nextPorta = false;
  1541. }
  1542. void setNextNoteExpression (float pan, float cents, bool porta) noexcept override
  1543. {
  1544. nextPan = pan;
  1545. nextCents = cents;
  1546. nextPorta = porta;
  1547. }
  1548. void setNextClipFades (float elapsed, float remaining, float in, float out) noexcept override
  1549. {
  1550. nextClip = { elapsed, remaining, in, out };
  1551. }
  1552. void slideTo (int key, float cents, float samples) noexcept override
  1553. {
  1554. if (clipMode)
  1555. return;
  1556. const auto semitones = (key - 60) + (double) pitch.load() + cents / 100.0;
  1557. const auto steps = std::max (1, (int) samples);
  1558. for (auto& v : voices)
  1559. if (v.active && ! v.stolen && v.rate != 0.0 && v.data != nullptr)
  1560. {
  1561. const auto target = flrs::speedFor ((float) (semitones * 100.0), v.data->sampleRate * (1.0 / sampleRate));
  1562. v.glideRatio = std::pow (target / v.rate, 1.0 / steps);
  1563. v.glideLeft = steps;
  1564. }
  1565. }
  1566. void noteOff (int key) noexcept override
  1567. {
  1568. if (clipMode)
  1569. {
  1570. allNotesOff(); // the clip ended: fade out quickly
  1571. return;
  1572. }
  1573. // the cutoff/pitch envelopes always release
  1574. for (auto& v : voices)
  1575. if (v.active && v.key == key && v.stage < 3)
  1576. for (std::size_t e = 0; e < 2; ++e)
  1577. modEnv[e].release (v.mod[e]);
  1578. // FL's voice: the volume, cutoff, resonance and pitch articulators release (FLEngine FUN_00d241e0); without a
  1579. // volume envelope the note-off changes nothing — the sample plays on and the other envelopes hold (EXEC: FL's
  1580. // renders, REA_rodada76 §6)
  1581. for (auto& v : voices)
  1582. if (v.active && v.key == key && v.flVoice && v.stage < 3)
  1583. {
  1584. if (modulation.fl.recs[1].enabled != 0)
  1585. for (int k = 1; k < 5; ++k)
  1586. v.flProc.arts[(std::size_t) k].release (modulation.fl.recs[(std::size_t) k]);
  1587. else if (v.loopEnd > v.loopStart && v.offFade < 0)
  1588. v.offFade = 0; // a looping sample without volume envelope fades out in 10 ms (EXEC, §8)
  1589. v.stage = 3;
  1590. }
  1591. // FL's volume articulator enters its release stage from the current level
  1592. for (auto& v : voices)
  1593. if (v.active && v.key == key && v.flEnvelope && v.stage < 3)
  1594. {
  1595. v.volumeArt.release (modulation.volume);
  1596. v.stage = 3; // released (stops "while held" loops); the ADSR level stays at 1
  1597. }
  1598. // with release, the released note decays; without release the sample plays in full (one-shot)
  1599. const auto seconds = release.load();
  1600. if (seconds <= 0.0f)
  1601. return;
  1602. // linear release from the current level (like FL)
  1603. for (auto& v : voices)
  1604. if (v.active && v.key == key && v.stage < 3 && ! v.flEnvelope && ! v.flVoice)
  1605. {
  1606. v.stage = 3;
  1607. v.envStep = -(float) (std::max (v.env, 0.001f) / (seconds * sampleRate));
  1608. }
  1609. }
  1610. void allNotesOff() noexcept override
  1611. {
  1612. for (auto& v : voices)
  1613. if (v.active)
  1614. v.stolen = true; // fade out instead of a hard cut
  1615. }
  1616. void render (float* left, float* right, int n, float gl, float gr) noexcept override
  1617. {
  1618. const struct Advance
  1619. {
  1620. double& at;
  1621. int n;
  1622. ~Advance() { at += n; }
  1623. } advance { songSample, n };
  1624. if (sample == nullptr && zones.empty())
  1625. return;
  1626. if (envelopeMailbox.read (modulation))
  1627. updateModulation();
  1628. // FL's native sampler voices: the channel's volume and pan act inside each voice (REA_rodada76 §3), so they are
  1629. // recovered from the rack's gains (panGains: gain·√2·cos/sin of (1 + pan)·π/4)
  1630. if (modulation.flNative)
  1631. {
  1632. const auto chanVol = (float) std::sqrt (((double) gl * gl + (double) gr * gr) * 0.5);
  1633. auto chanPan = chanVol > 0.0f ? (float) (std::atan2 ((double) gr, (double) gl) * (4.0 / 3.141592653589793) - 1.0) : 0.0f;
  1634. if (std::fabs (chanPan) < 1.0e-6f)
  1635. chanPan = 0.0f;
  1636. const flvp::X87Extended precision;
  1637. for (auto& v : voices)
  1638. if (v.active && v.data != nullptr && v.flVoice)
  1639. renderFl (v, left, right, n, chanVol, chanPan);
  1640. }
  1641. // channel filter (TPT SVF, same as the synth); off when open, without resonance and without modulation
  1642. const auto fc = cutoff.load(), res = resonance.load();
  1643. const auto type = filterType.load();
  1644. const auto filterModulated = modEnv[0].active || lfos[lfoCutoff].active;
  1645. const auto filtered = fc < 19500.0f || res > 0.0f || type != 0 || filterModulated;
  1646. const auto modulated = modEnv[0].active || modEnv[1].active || anyLfo;
  1647. if (filtered && (fc != filterCutoff || res != filterResonance || type != sharedFilter.mode))
  1648. {
  1649. filterCutoff = fc;
  1650. filterResonance = res;
  1651. sharedFilter.set (fc, res, sampleRate, type);
  1652. }
  1653. const flvp::X87Extended precision; // FL's interpolators run the x87 unit at 64-bit precision
  1654. for (auto& v : voices)
  1655. {
  1656. if (! v.active || v.data == nullptr || v.flVoice)
  1657. continue;
  1658. const auto* l = v.data->leftData();
  1659. const auto* r = v.data->rightData();
  1660. const auto lastFrame = std::min ((double) (v.data->frames() - 1), v.last);
  1661. for (int i = 0; i < n; ++i)
  1662. {
  1663. // loop: jump back to its start (the "while held" mode stops looping on release)
  1664. const auto looping = v.loopEnd > v.loopStart && (! v.loopWhileHeld || v.stage < 3);
  1665. if (looping && v.position >= v.loopEnd)
  1666. {
  1667. while (v.position >= v.loopEnd)
  1668. v.position = (v.position - v.loopEnd) + v.loopStart;
  1669. ++v.loops;
  1670. }
  1671. if ((double) flrs::wholeFrames (v.position) > lastFrame || v.position < v.first || (v.stolen && v.fade <= 0.0f) || (v.env <= 0.0f && v.stage >= 1))
  1672. {
  1673. v.active = false;
  1674. break;
  1675. }
  1676. if (v.flEnvelope)
  1677. {
  1678. if (v.tickLeft <= 0.0)
  1679. {
  1680. // a sequencer tick: step the articulator; the level ramps to its value over round(tick) samples
  1681. v.volumeArt.step (modulation.volume);
  1682. const auto perTick = sampleRate / modulation.ticksPerSecond;
  1683. v.flStep = (v.volumeArt.val - v.flLevel) / (float) std::max (1.0, std::nearbyint (perTick));
  1684. v.tickLeft += perTick;
  1685. }
  1686. if (v.volumeArt.state == 9 && v.flLevel <= 0.0f && v.flStep <= 0.0f)
  1687. {
  1688. v.active = false;
  1689. break;
  1690. }
  1691. }
  1692. float sl, sr;
  1693. readFrame (v, l, r, lastFrame, looping, sl, sr);
  1694. if (modulated)
  1695. {
  1696. for (std::size_t e = 0; e < 2; ++e)
  1697. if (modEnv[e].active)
  1698. modEnv[e].advance (v.mod[e]);
  1699. if (--v.controlCountdown <= 0) // 16-sample control tick, as in the synth
  1700. {
  1701. v.controlCountdown = 16;
  1702. auto semitones = modEnv[1].active ? modEnv[1].amount * v.mod[1].level : 0.0f;
  1703. auto octaves = modEnv[0].active ? modEnv[0].amount * v.mod[0].level : 0.0f;
  1704. if (lfos[lfoPitch].active)
  1705. semitones += lfos[lfoPitch].amount * lfos[lfoPitch].tick (v.lfo[lfoPitch], 16);
  1706. if (lfos[lfoCutoff].active)
  1707. octaves += lfos[lfoCutoff].amount * lfos[lfoCutoff].tick (v.lfo[lfoCutoff], 16);
  1708. if (lfos[lfoVolume].active)
  1709. {
  1710. const auto target = std::max (0.0f, 1.0f + lfos[lfoVolume].amount * lfos[lfoVolume].tick (v.lfo[lfoVolume], 16));
  1711. v.lfoGainStep = (target - v.lfoGain) / 16.0f;
  1712. }
  1713. if (lfos[lfoPan].active)
  1714. voicePan (v.basePan + lfos[lfoPan].amount * lfos[lfoPan].tick (v.lfo[lfoPan], 16), v.panL, v.panR);
  1715. v.pitchMul = semitones != 0.0f ? std::exp2 (semitones / 12.0) : 1.0;
  1716. if (filterModulated)
  1717. v.filter.set (fc * std::exp2 (octaves), res, sampleRate, type);
  1718. }
  1719. v.lfoGain += v.lfoGainStep;
  1720. }
  1721. if (filtered)
  1722. {
  1723. const auto& f = filterModulated ? v.filter : sharedFilter;
  1724. sl = f.process (sl, v.lowL, v.bandL);
  1725. sr = f.process (sr, v.lowR, v.bandR);
  1726. }
  1727. auto gain = v.velocity * v.fade * v.env * v.lfoGain * v.zoneGain;
  1728. if (v.flEnvelope)
  1729. {
  1730. gain *= std::max (0.0f, v.flLevel);
  1731. const auto next = v.flLevel + v.flStep;
  1732. // the ramp stops at the tick's value
  1733. v.flLevel = (v.flStep > 0.0f && next > v.volumeArt.val) || (v.flStep < 0.0f && next < v.volumeArt.val) ? v.volumeArt.val : next;
  1734. v.tickLeft -= 1.0;
  1735. }
  1736. if (v.fadeIn > 0.0f || v.fadeOut > 0.0f)
  1737. {
  1738. if (v.fadeIn > 0.0f && v.clipElapsed < v.fadeIn)
  1739. gain *= v.clipElapsed / v.fadeIn;
  1740. if (v.fadeOut > 0.0f && v.clipRemaining < v.fadeOut)
  1741. gain *= std::max (0.0f, v.clipRemaining) / v.fadeOut;
  1742. v.clipElapsed += 1.0f;
  1743. v.clipRemaining -= 1.0f;
  1744. }
  1745. left[i] += sl * gain * gl * v.panL;
  1746. right[i] += sr * gain * gr * v.panR;
  1747. v.position += v.rate * v.pitchMul;
  1748. ++v.age;
  1749. if (v.glideLeft > 0)
  1750. {
  1751. v.rate *= v.glideRatio;
  1752. --v.glideLeft;
  1753. }
  1754. // envelope: 0 attack, 1 decay, 2 sustain, 3 release
  1755. if (v.stage == 0)
  1756. {
  1757. v.env += v.envStep;
  1758. if (v.env >= 1.0f)
  1759. {
  1760. v.env = 1.0f;
  1761. v.stage = 1;
  1762. }
  1763. }
  1764. else if (v.stage == 1)
  1765. {
  1766. const auto s = sustain.load (std::memory_order_relaxed);
  1767. const auto d = decay.load (std::memory_order_relaxed);
  1768. if (s >= 1.0f)
  1769. v.stage = 2;
  1770. else if (d <= 0.0f)
  1771. {
  1772. v.env = s;
  1773. v.stage = 2;
  1774. }
  1775. else
  1776. {
  1777. // the ramp goes from 1 to 0 over `decay` and stops at sustain (like FL)
  1778. v.env -= (float) (1.0 / (d * sampleRate));
  1779. if (v.env <= s)
  1780. {
  1781. v.env = s;
  1782. v.stage = 2;
  1783. }
  1784. }
  1785. }
  1786. else if (v.stage == 3)
  1787. v.env += v.envStep;
  1788. if (v.stolen)
  1789. v.fade -= fadeStep;
  1790. }
  1791. }
  1792. }
  1793. // One sequencer tick of FL's sampler voice (FLEngine FUN_00d24ae0 / FUN_00d24500 / FUN_00d24650, REA_rodada76
  1794. // §3–§4): the articulators step; the target gains are the pan law of (note pan + channel pan + pan articulator,
  1795. // initial volume · channel volume · volume articulator); the filter coefficients follow Final.FCut/FRes plus the
  1796. // cutoff/resonance articulators; gains and the fast LP's coefficient ramp towards their targets over round(spt)
  1797. // samples, at most 0.001·44100/fs per sample.
  1798. void flTick (SamplerVoice& v, float chanVol, float chanPan, int perTick) noexcept
  1799. {
  1800. const auto& S = modulation.fl;
  1801. auto& pr = v.flProc;
  1802. // global LFOs (flag 0x20): one phase for the whole channel, advanced on every song tick — at tick k it is
  1803. // (k + 1)·increment (EXEC: FL's render of a global volume LFO, REA_rodada76 §10)
  1804. if (S.hasGlobal)
  1805. for (auto& r : modulation.fl.recs)
  1806. if ((r.flags & 0x20) != 0)
  1807. r.globalPhase = (std::uint32_t) ((std::uint64_t) (v.tickIndex + 1) * (std::uint64_t) r.lfoInc);
  1808. pr.control (S);
  1809. const auto finalVol = v.initVol * chanVol, finalPan = v.notePan + chanPan;
  1810. float tL, tR;
  1811. if (modulation.flTriangular)
  1812. {
  1813. // FL's pan-law mode 1 (FLEngine FUN_006a39c0, x87): vol·sin(π/4) on the louder side, (1 ∓ pan)·that on the
  1814. // other (EXEC: FL's render with the project's pan law 2, REA_rodada76 §9)
  1815. const auto pan = std::min (std::max (finalPan + pr.pan, -1.0f), 1.0f);
  1816. const auto vol = finalVol * pr.vol * 0.70710677f;
  1817. using ld = long double;
  1818. if (std::signbit (pan))
  1819. tL = vol, tR = (float) (((ld) 1 + (ld) pan) * (ld) vol);
  1820. else
  1821. tR = vol, tL = (float) (((ld) 1 - (ld) pan) * (ld) vol);
  1822. }
  1823. else
  1824. flvp::panLaw (finalPan + pr.pan, finalVol * pr.vol, tL, tR);
  1825. v.pitchMul = pr.pitch != 0.0f ? std::exp2 ((double) pr.pitch / 1200.0) : 1.0;
  1826. const auto first = pr.first;
  1827. const auto cx = ((float) S.modX * 0.00390625f + 0.0f) + pr.cut;
  1828. const auto cy = ((float) S.modY * 0.00390625f + 0.0f) + pr.res;
  1829. if (pr.kind == 0)
  1830. {
  1831. flvp::coefFast (cx, cy, pr.fc, pr.fq, S.rateRatio);
  1832. if (flvp::bitsOf (pr.fc) != 0x3f800000 || flvp::bitsOf (pr.fq) != 0)
  1833. pr.active = true;
  1834. if (! pr.active || first > 0)
  1835. v.fcRun = pr.fc, v.fcSlope = 0.0f;
  1836. else
  1837. v.fcSlope = flvp::rampStep (pr.fc, v.fcRun, perTick, S.rampLimit);
  1838. }
  1839. else if (pr.kind >= 1 && pr.kind <= 4)
  1840. flvp::coefBiquad (pr.kind, cx, cy, pr.fc, pr.fq, pr.b, S.rateRatio);
  1841. else if (pr.kind == 6)
  1842. flvp::coefSvf (cx, cy, pr.fc, pr.fq, S.rateRatio);
  1843. // the first block: with the volume articulator past its attack the gains start at their (unscaled) target,
  1844. // else they ramp up from 0
  1845. auto prevL = v.gL, prevR = v.gR;
  1846. if (first > 1)
  1847. prevL = tL, prevR = tR;
  1848. pr.first = 0;
  1849. if (pr.active && pr.kind >= 1 && pr.kind <= 4 && pr.stage2 != 0)
  1850. {
  1851. const auto g = (float) (1.0 - (double) pr.fq * (3.2 - (double) pr.fc) * 0.046875);
  1852. tL = tL * g, tR = tR * g;
  1853. }
  1854. v.sL = flvp::rampStep (tL, prevL, perTick, S.rampLimit);
  1855. v.sR = flvp::rampStep (tR, prevR, perTick, S.rampLimit);
  1856. v.gL = prevL, v.gR = prevR;
  1857. // the volume envelope has ended and the level is down: the voice is done
  1858. if (pr.arts[1].state == 9 && tL == 0.0f && tR == 0.0f && std::fabs (prevL) < 1.0e-7f && std::fabs (prevR) < 1.0e-7f)
  1859. v.active = false;
  1860. }
  1861. // FL's sampler voice over n samples: split at the song's ticks, the sample read through FL's interpolators, the
  1862. // channel filter on the stereo block, the gains ramped per sample (the channel's volume and pan are inside)
  1863. void renderFl (SamplerVoice& v, float* left, float* right, int n, float chanVol, float chanPan) noexcept
  1864. {
  1865. const auto spt = sampleRate / modulation.ticksPerSecond;
  1866. const auto perTick = (int) std::max<std::int64_t> (1, flvp::roundEven (spt));
  1867. const auto* l = v.data->leftData();
  1868. const auto* r = v.data->rightData();
  1869. const auto lastFrame = std::min ((double) (v.data->frames() - 1), v.last);
  1870. auto& pr = v.flProc;
  1871. for (int pos = 0; pos < n && v.active;)
  1872. {
  1873. if (v.tickLeft <= 0.0)
  1874. {
  1875. flTick (v, chanVol, chanPan, perTick);
  1876. v.tickLeft += v.nextGap;
  1877. ++v.tickIndex;
  1878. v.nextGap = (double) (flvp::roundEven ((double) (v.tickIndex + 1) * spt) - flvp::roundEven ((double) v.tickIndex * spt));
  1879. if (! v.active)
  1880. break;
  1881. }
  1882. auto seg = std::min ({ n - pos, (int) std::ceil (v.tickLeft), flBlock });
  1883. // read the segment (loop wrap, region end, declick of stolen voices, clip fades)
  1884. auto ended = false;
  1885. int m = 0;
  1886. for (; m < seg; ++m)
  1887. {
  1888. const auto looping = v.loopEnd > v.loopStart && (! v.loopWhileHeld || v.stage < 3);
  1889. if (looping && v.position >= v.loopEnd)
  1890. {
  1891. while (v.position >= v.loopEnd)
  1892. v.position = (v.position - v.loopEnd) + v.loopStart;
  1893. ++v.loops;
  1894. }
  1895. if (v.stolen && v.fade <= 0.0f)
  1896. {
  1897. ended = true;
  1898. break;
  1899. }
  1900. // past the region's end FL holds the last frame and fades it out with the 441-entry end table (EXEC:
  1901. // FL's render, REA_rodada76 §6)
  1902. if (v.endFade < 0 && ((double) flrs::wholeFrames (v.position) > lastFrame || v.position < v.first))
  1903. v.endFade = 0;
  1904. float sl, sr, endGain = 1.0f;
  1905. if (v.endFade >= 0)
  1906. {
  1907. const auto& table = flvp::endTable();
  1908. if (v.endFade >= (int) table.size())
  1909. {
  1910. ended = true;
  1911. break;
  1912. }
  1913. endGain = table[(std::size_t) v.endFade++];
  1914. sl = v.holdL, sr = v.holdR;
  1915. }
  1916. else
  1917. {
  1918. readFrame (v, l, r, lastFrame, looping, sl, sr);
  1919. v.holdL = sl, v.holdR = sr;
  1920. }
  1921. auto gain = v.fade * v.zoneGain;
  1922. if (v.fadeIn > 0.0f || v.fadeOut > 0.0f)
  1923. {
  1924. if (v.fadeIn > 0.0f && v.clipElapsed < v.fadeIn)
  1925. gain *= v.clipElapsed / v.fadeIn;
  1926. if (v.fadeOut > 0.0f && v.clipRemaining < v.fadeOut)
  1927. gain *= std::max (0.0f, v.clipRemaining) / v.fadeOut;
  1928. v.clipElapsed += 1.0f;
  1929. v.clipRemaining -= 1.0f;
  1930. }
  1931. flX[(std::size_t) (2 * m)] = sl;
  1932. flX[(std::size_t) (2 * m + 1)] = sr;
  1933. if (v.offFade >= 0)
  1934. {
  1935. const auto& table = flvp::endTable();
  1936. if (v.offFade >= (int) table.size())
  1937. {
  1938. ended = true;
  1939. break;
  1940. }
  1941. endGain *= table[(std::size_t) v.offFade++];
  1942. }
  1943. flG[(std::size_t) m] = gain * endGain;
  1944. v.position += v.rate * v.pitchMul;
  1945. ++v.age;
  1946. if (v.glideLeft > 0)
  1947. {
  1948. v.rate *= v.glideRatio;
  1949. --v.glideLeft;
  1950. }
  1951. if (v.stolen)
  1952. v.fade -= fadeStep;
  1953. }
  1954. seg = m;
  1955. // the channel filter (FLEngine FUN_00d247a0)
  1956. const float* y = flX.data();
  1957. if (pr.active && seg > 0)
  1958. {
  1959. if (pr.kind == 0)
  1960. {
  1961. flvp::renderFast (pr.fst, pr.fq, flX.data(), flY.data(), seg, v.fcRun, v.fcSlope);
  1962. v.fcRun = v.fcRun + (float) seg * v.fcSlope;
  1963. y = flY.data();
  1964. }
  1965. else if (pr.kind >= 1 && pr.kind <= 4)
  1966. {
  1967. flvp::renderBiquad (pr.st1, pr.b, flX.data(), flY.data(), seg);
  1968. if (pr.stage2 != 0)
  1969. flvp::renderBiquad (pr.st2, pr.b, flY.data(), flY.data(), seg);
  1970. y = flY.data();
  1971. }
  1972. else if (pr.kind == 6)
  1973. {
  1974. flvp::renderSvf (pr.st1, pr.fc, pr.fq, flX.data(), flY.data(), seg);
  1975. if (pr.stage2 != 0)
  1976. flvp::renderSvf (pr.st2, pr.fc, pr.fq + (1.0f - pr.fq) * 0.25f, flY.data(), flY.data(), seg);
  1977. y = flY.data();
  1978. }
  1979. }
  1980. for (int i = 0; i < seg; ++i)
  1981. {
  1982. const auto g = flG[(std::size_t) i];
  1983. left[pos + i] += y[2 * i] * ((v.gL + (float) i * v.sL) * g);
  1984. right[pos + i] += y[2 * i + 1] * ((v.gR + (float) i * v.sR) * g);
  1985. }
  1986. v.gL = v.gL + v.sL * (float) seg;
  1987. v.gR = v.gR + v.sR * (float) seg;
  1988. v.tickLeft -= seg;
  1989. pos += seg;
  1990. if (ended)
  1991. v.active = false;
  1992. }
  1993. }
  1994. // FL's sampler read (REA_rodada69 §1): the kernel's taps around the read position, frames outside the region
  1995. // repeating its first/last frame, taps past the loop end wrapping to the loop start (and, once the voice has
  1996. // looped, taps before the loop start wrapping to its end), a reversed voice reading the region backwards
  1997. void readFrame (SamplerVoice& v, const float* l, const float* r, double lastFrame, bool looping, float& outL, float& outR) noexcept
  1998. {
  1999. v.kernel.setSpeed (v.rate * v.pitchMul);
  2000. const auto half = v.kernel.halfWidth;
  2001. const auto whole = flrs::wholeFrames (v.position);
  2002. const auto frac = v.position - (double) whole;
  2003. const auto first = (std::int64_t) v.first, last = (std::int64_t) lastFrame;
  2004. const auto lo = whole - half + 1, hi = whole + half;
  2005. const auto loopStart = (std::int64_t) v.loopStart, loopEnd = (std::int64_t) v.loopEnd;
  2006. // at the original rate on a whole frame FL copies the sample instead of interpolating
  2007. if (v.rate * v.pitchMul == 1.0 && frac == 0.0)
  2008. {
  2009. const auto q = v.reversed ? first + last - whole : whole;
  2010. outL = l[q];
  2011. outR = r[q];
  2012. return;
  2013. }
  2014. if (! v.reversed && lo >= first && hi <= last && ! (looping && hi >= loopEnd))
  2015. {
  2016. flrs::interpolate (v.kernel, l + lo, r + lo, frac, outL, outR);
  2017. return;
  2018. }
  2019. for (std::int64_t t = 0; t < 2 * half; ++t)
  2020. {
  2021. auto q = lo + t;
  2022. if (looping && loopEnd > loopStart)
  2023. {
  2024. while (q >= loopEnd)
  2025. q -= loopEnd - loopStart;
  2026. if (v.loops > 0 && q < loopStart)
  2027. q += loopEnd - loopStart;
  2028. }
  2029. q = std::clamp (q, first, last);
  2030. if (v.reversed)
  2031. q = first + last - q;
  2032. tapL[(std::size_t) t] = l[q];
  2033. tapR[(std::size_t) t] = r[q];
  2034. }
  2035. flrs::interpolate (v.kernel, tapL.data(), tapR.data(), frac, outL, outR);
  2036. }
  2037. bool idle() const noexcept override
  2038. {
  2039. return std::none_of (voices.begin(), voices.end(), [] (const auto& v) { return v.active; });
  2040. }
  2041. private:
  2042. std::shared_ptr<const SampleData> sample;
  2043. bool clipMode = false;
  2044. double sampleRate = 44100.0;
  2045. float fadeStep = 0.01f;
  2046. std::array<SamplerVoice, 16> voices {};
  2047. int quality = flrs::liveQuality; // FL's interpolation index (prepare)
  2048. std::array<float, 1024> tapL {}, tapR {}; // kernel taps gathered near the region edges and loops
  2049. static constexpr int flBlock = 512; // FL voices: longest segment rendered at once
  2050. std::array<float, 2 * flBlock> flX {}, flY {};
  2051. std::array<float, flBlock> flG {};
  2052. std::atomic<float> pitch { 0.0f }, attack { 0.0f }, decay { 0.0f }, sustain { 1.0f }, release { 0.0f }, stretchBeats { 0.0f };
  2053. std::atomic<double> bpm { 120.0 };
  2054. std::atomic<float> regionStart { 0.0f }, regionEnd { 1.0f };
  2055. std::atomic<float> cutoff { 20000.0f }, resonance { 0.0f };
  2056. std::atomic<bool> porta { false };
  2057. std::atomic<float> portaBeats { 0.125f };
  2058. std::vector<LoadedZone> zones; // multi-sample (fixed after creation)
  2059. double songTicks = 0.0; // song position in the block (global LFO)
  2060. public:
  2061. void setSongPosition (double ticks) noexcept override
  2062. {
  2063. songTicks = ticks;
  2064. // the song's sample position (FL's ticks fall at round(k · samples per tick) from the song start)
  2065. const auto tps = (double) ppq * bpm.load() / (60.0 * sampleRate);
  2066. songSample = tps > 0.0 ? std::nearbyint (ticks / tps) : 0.0;
  2067. }
  2068. private:
  2069. double songSample = 0.0; // sample position of the next render call in the song
  2070. int lastZone = -1; // the zone the last note chose (overlapping layers cycle from it)
  2071. double lastRate = 0.0; // read speed of the last note (where porta starts from)
  2072. std::atomic<int> filterType { 0 };
  2073. float filterCutoff = -1.0f, filterResonance = -1.0f; // values the coefficients were computed with
  2074. SvfCoefficients sharedFilter;
  2075. struct Modulation
  2076. {
  2077. std::array<ModEnvelope, 2> envelopes {};
  2078. std::array<ChannelLfo, lfoTargets> lfo {};
  2079. bool flVolume = false; // FL's volume articulator replaces the ADSR
  2080. flvp::Rec volume {}; // its settings (FLEngine FUN_009ce9e0 = the plugins' FUN_0071ff00, REA_rodada69 §3)
  2081. double ticksPerSecond = 0; // FL steps it once per sequencer tick
  2082. bool flNative = false; // FL's whole sampler voice (SamplerSettings::flChannel)
  2083. bool flTriangular = false; // the project's triangular pan law
  2084. flvp::Settings fl {};
  2085. };
  2086. SettingsMailbox<Modulation> envelopeMailbox;
  2087. Modulation modulation;
  2088. std::array<LfoCoefficients, lfoTargets> lfos {};
  2089. bool anyLfo = false;
  2090. void updateModulation() noexcept
  2091. {
  2092. anyLfo = false;
  2093. if (modulation.flNative)
  2094. modulation.fl.setRate (sampleRate); // FLEngine FUN_006a0230: ratio 44100/fs, ramp limit ratio·0.001
  2095. for (std::size_t e = 0; e < 2; ++e)
  2096. modEnv[e] = ModCoefficients::make (modulation.envelopes[e], sampleRate);
  2097. for (std::size_t i = 0; i < lfoTargets; ++i)
  2098. {
  2099. lfos[i] = LfoCoefficients::make (modulation.lfo[i], sampleRate, bpm.load());
  2100. anyLfo = anyLfo || lfos[i].active;
  2101. }
  2102. }
  2103. std::array<ModCoefficients, 2> modEnv {};
  2104. std::array<float, 4> nextClip {}; // fades for the next noteOn (only the audio thread touches it)
  2105. struct SliceTable
  2106. {
  2107. std::array<float, 128> starts {};
  2108. int count = 0;
  2109. };
  2110. SettingsMailbox<SliceTable> sliceMailbox;
  2111. SliceTable slices; // audio thread's copy
  2112. float nextPan = 0.0f, nextCents = 0.0f;
  2113. bool nextPorta = false;
  2114. std::atomic<bool> reverse { false }, cut { false };
  2115. };
  2116. } // namespace
  2117. std::unique_ptr<Instrument> makeZonedSampler (std::vector<LoadedZone> zones)
  2118. {
  2119. auto sampler = std::make_unique<SamplerInstrument> (nullptr, false);
  2120. sampler->setZones (std::move (zones));
  2121. return sampler;
  2122. }
  2123. namespace
  2124. {
  2125. // FL's Envelope Controller: no audio; each articulator follows the last note in its key range and
  2126. // the output holds the last value when there is no note.
  2127. class ControllerInstrument final : public Instrument
  2128. {
  2129. public:
  2130. void prepare (double sr) noexcept override { sampleRate = sr; }
  2131. void configure (const ChannelDef& channel, double bpm) noexcept override
  2132. {
  2133. Data data {};
  2134. if (auto keyboard = parseKeyboardController (channel.controllerState))
  2135. {
  2136. data.keyboard = true;
  2137. data.keys = *keyboard;
  2138. }
  2139. else if (auto parsed = parseEnvelopeController (channel.controllerState))
  2140. {
  2141. data.articulators = *parsed;
  2142. const auto beat = 60.0 / std::max (1.0, bpm);
  2143. for (auto& a : data.articulators)
  2144. if (a.tempo)
  2145. {
  2146. for (int i = 0; i < a.count; ++i)
  2147. a.time[(std::size_t) i] = (float) (a.time[(std::size_t) i] * beat);
  2148. a.tempo = false;
  2149. }
  2150. }
  2151. mailbox.write (data);
  2152. }
  2153. void noteOn (int key, float) noexcept override
  2154. {
  2155. mailbox.read (data);
  2156. if (data.keyboard) // Keyboard Controller: output 0 is the key's value
  2157. {
  2158. heldKey = key;
  2159. if (key >= 0 && key < (int) data.keys.keys.size())
  2160. values[0] = data.keys.keys[(std::size_t) key];
  2161. return;
  2162. }
  2163. for (std::size_t k = 0; k < voices.size(); ++k)
  2164. {
  2165. const auto& a = data.articulators[k];
  2166. if (key >= a.lowKey && key <= a.highKey)
  2167. voices[k] = { true, key, 0.0, -1.0 };
  2168. }
  2169. }
  2170. void noteOff (int key) noexcept override
  2171. {
  2172. if (data.keyboard)
  2173. {
  2174. if (key == heldKey && data.keys.autoRelease)
  2175. values[0] = data.keys.noteOffValue;
  2176. return;
  2177. }
  2178. for (auto& v : voices)
  2179. if (v.active && v.key == key && v.sinceRelease < 0.0)
  2180. v.sinceRelease = 0.0;
  2181. }
  2182. void allNotesOff() noexcept override
  2183. {
  2184. for (auto& v : voices)
  2185. if (v.active && v.sinceRelease < 0.0)
  2186. v.sinceRelease = 0.0;
  2187. }
  2188. void render (float*, float*, int n, float, float) noexcept override
  2189. {
  2190. if (mailbox.read (data) && ! data.keyboard)
  2191. for (std::size_t k = 0; k < values.size(); ++k)
  2192. if (! voices[k].active)
  2193. values[k] = data.articulators[k].base;
  2194. if (data.keyboard)
  2195. return;
  2196. const auto seconds = n / sampleRate;
  2197. for (std::size_t k = 0; k < voices.size(); ++k)
  2198. {
  2199. auto& v = voices[k];
  2200. if (! v.active)
  2201. continue;
  2202. v.sinceOn += seconds;
  2203. if (v.sinceRelease >= 0.0)
  2204. v.sinceRelease += seconds;
  2205. values[k] = controllerValue (data.articulators[k], v.sinceOn, v.sinceRelease);
  2206. }
  2207. }
  2208. float controlOutput (int output) const noexcept override
  2209. {
  2210. return output >= 0 && output < (int) values.size() ? values[(std::size_t) output] : 0.0f;
  2211. }
  2212. private:
  2213. struct Data
  2214. {
  2215. EnvelopeControllerData articulators {};
  2216. bool keyboard = false;
  2217. KeyboardControllerData keys {};
  2218. };
  2219. int heldKey = -1;
  2220. struct Voice
  2221. {
  2222. bool active = false;
  2223. int key = 0;
  2224. double sinceOn = 0.0, sinceRelease = -1.0;
  2225. };
  2226. SettingsMailbox<Data> mailbox;
  2227. Data data {};
  2228. std::array<Voice, 8> voices {};
  2229. std::array<float, 8> values { 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f };
  2230. double sampleRate = 44100.0;
  2231. };
  2232. } // namespace
  2233. namespace
  2234. {
  2235. std::atomic<bool> offlineRenderingFlag { false };
  2236. }
  2237. void setOfflineRendering (bool on) noexcept { offlineRenderingFlag.store (on); }
  2238. bool offlineRendering() noexcept { return offlineRenderingFlag.load(); }
  2239. HostTimeline& hostTimeline() noexcept
  2240. {
  2241. static HostTimeline timeline;
  2242. return timeline;
  2243. }
  2244. std::unique_ptr<Instrument> makeInstrument (InstrumentKind kind, std::shared_ptr<const SampleData> sample)
  2245. {
  2246. if (kind == InstrumentKind::controller)
  2247. return std::make_unique<ControllerInstrument>();
  2248. if (kind == InstrumentKind::sampler || kind == InstrumentKind::audioClip)
  2249. return std::make_unique<SamplerInstrument> (std::move (sample), kind == InstrumentKind::audioClip);
  2250. if (kind == InstrumentKind::synth)
  2251. return std::make_unique<SynthInstrument>();
  2252. if (kind == InstrumentKind::sakura)
  2253. return makeSakuraInstrument();
  2254. if (kind == InstrumentKind::drumpad)
  2255. return makeDrumpadInstrument();
  2256. if (kind == InstrumentKind::boobass)
  2257. return makeBooBassInstrument();
  2258. if (kind == InstrumentKind::drumsynth)
  2259. return makeDrumSynthInstrument();
  2260. if (kind == InstrumentKind::harmless)
  2261. return makeHarmlessInstrument();
  2262. if (kind == InstrumentKind::sytrus)
  2263. return makeSytrusInstrument();
  2264. if (kind == InstrumentKind::harmor)
  2265. return makeHarmorInstrument();
  2266. if (kind == InstrumentKind::gms)
  2267. return makeGmsInstrument();
  2268. if (kind == InstrumentKind::morphine)
  2269. return makeMorphineInstrument();
  2270. if (kind == InstrumentKind::ogun)
  2271. return makeOgunInstrument();
  2272. if (kind == InstrumentKind::minisynth)
  2273. return makeMiniSynthInstrument();
  2274. if (kind == InstrumentKind::dx10)
  2275. return makeDx10Instrument();
  2276. if (kind == InstrumentKind::kepler)
  2277. return makeKeplerInstrument();
  2278. if (kind == InstrumentKind::poizone)
  2279. return makePoiZoneInstrument();
  2280. if (kind == InstrumentKind::fruitkick)
  2281. return makeFruitKickInstrument();
  2282. if (kind == InstrumentKind::bassdrum)
  2283. return makeBassDrumInstrument();
  2284. if (kind == InstrumentKind::toxic)
  2285. return makeToxicInstrument();
  2286. if (kind == InstrumentKind::threeosc)
  2287. return makeThreeOscInstrument();
  2288. if (kind == InstrumentKind::autogun)
  2289. return makeAutogunInstrument();
  2290. if (kind == InstrumentKind::transistorbass)
  2291. return makeTransistorBassInstrument();
  2292. if (kind == InstrumentKind::simsynth)
  2293. return makeSimSynthInstrument();
  2294. if (kind == InstrumentKind::wasp || kind == InstrumentKind::fruitydance)
  2295. return makeWaspInstrument(); // both make no sound and keep their state
  2296. if (kind == InstrumentKind::plucked)
  2297. return makePluckedInstrument();
  2298. if (kind == InstrumentKind::beepmap)
  2299. return makeBeepMapInstrument();
  2300. if (kind == InstrumentKind::sawer)
  2301. return makeSawerInstrument();
  2302. if (kind == InstrumentKind::granulizer)
  2303. return makeGranulizerInstrument (std::move (sample));
  2304. if (kind == InstrumentKind::drumaxx)
  2305. return makeDrumaxxInstrument();
  2306. if (kind == InstrumentKind::slayer)
  2307. return makeSlayerInstrument();
  2308. if (kind == InstrumentKind::directwave)
  2309. return dw::makeDirectWaveInstrument ({}); // samples come from RackRenderer
  2310. return std::make_unique<DrumInstrument> (kind);
  2311. }
  2312. } // namespace lynx