Instruments.cpp 86 KB

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