Plucked.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. // FL Studio's Plucked! (REA_rodada65 §1). See Plucked.h.
  2. #include "core/Plucked.h"
  3. #include <algorithm>
  4. #include <array>
  5. #include <atomic>
  6. #include <cmath>
  7. #include <cstring>
  8. #include "core/FlVoiceProcessor.h" // (FL's x87 host pan law, round-half-even)
  9. #if defined(__clang__)
  10. #pragma clang fp contract(off)
  11. #elif defined(__GNUC__)
  12. #pragma GCC optimize ("fp-contract=off")
  13. #endif
  14. namespace lynx
  15. {
  16. namespace
  17. {
  18. using flvp::roundEven;
  19. struct Params
  20. {
  21. int decay = 128, colour = 64, normalize = 1, gate = 0, widen = 1;
  22. };
  23. bool parse (const std::vector<std::uint8_t>& s, Params& p)
  24. {
  25. if (s.size() < 20)
  26. return false;
  27. std::int32_t v[5];
  28. std::memcpy (v, s.data(), 20);
  29. p.decay = v[0], p.colour = v[1], p.normalize = v[2], p.gate = v[3], p.widen = v[4];
  30. return true;
  31. }
  32. // Delphi's Random: RandSeed = RandSeed·0x08088405 + 1, value = RandSeed·2^-32 (§1.4)
  33. struct DelphiRandom
  34. {
  35. std::uint32_t seed = 0;
  36. double next() noexcept
  37. {
  38. seed = seed * 0x08088405u + 1u;
  39. return (double) seed * 2.3283064365386963e-10;
  40. }
  41. };
  42. // Delphi's Power(Single, Single) as the plugin calls it (§1.3): integral exponents through IntPower
  43. float delphiPower (float base, float e) noexcept
  44. {
  45. if (e == 0.0f)
  46. return 1.0f;
  47. if (base == 0.0f && e > 0.0f)
  48. return 0.0f;
  49. if ((float) std::trunc ((double) e + 0.5) == e)
  50. {
  51. const auto n = (int) e;
  52. double r = 1.0;
  53. for (int i = 0; i < std::abs (n); ++i)
  54. r *= (double) base;
  55. return (float) (n < 0 ? 1.0 / r : r);
  56. }
  57. return (float) std::exp ((double) e * std::log ((double) base));
  58. }
  59. // the pitch ratio (relative to 523.2511306 Hz) of a note's Final.Pitch in cents (§1.3)
  60. float pitchRatio (float pitchCents) noexcept
  61. {
  62. auto c = roundEven ((double) pitchCents);
  63. if (c < -3600)
  64. c = (c + 100) % 1200 - 2500;
  65. else if (c >= 3600)
  66. c = c % 1200 + 2400;
  67. const auto e = (float) (c - 2400) * 0.0008333333535119891f + 1.0f;
  68. return delphiPower (2.0f, e);
  69. }
  70. // the per-sample feedback gain (§1.5): decay knob + Mod X, the log law, ×0.5 (the two-point average)
  71. float feedbackGain (const Params& P, float modX, bool normalize, float invRatio) noexcept
  72. {
  73. const auto lv = std::clamp ((std::int64_t) P.decay + roundEven ((double) (modX * 256.0f)), (std::int64_t) 0, (std::int64_t) 256);
  74. const auto d = std::log ((double) ((float) lv + 1.0f)) / std::log (257.0);
  75. auto g = (float) ((double) ((float) d * 0.04989999905228615f) + 0.95);
  76. if (normalize)
  77. g = delphiPower (g, invRatio);
  78. return g * 0.5f;
  79. }
  80. constexpr int maxVoices = 64;
  81. struct Voice
  82. {
  83. bool active = false, released = false, wide = false, normalize = false;
  84. int key = 0, N = 0, pos = 0, counter = -1;
  85. float g = 0.0f, invRatio = 0.0f, modX = 0.0f, prevL = 0.0f, prevR = 0.0f;
  86. float peak = 0.0f, lastPeak = 1.0f;
  87. float fvol = 1.0f, fpan = 0.0f, gainL = 0.0f, gainR = 0.0f;
  88. std::uint64_t order = 0;
  89. float* line = nullptr; // N (mono) or 2N (widen: left line, then right line) samples
  90. };
  91. class Engine
  92. {
  93. public:
  94. Params P;
  95. DelphiRandom random;
  96. bool panLawA = true, ramp = true;
  97. int maxPoly = 0;
  98. std::array<Voice, maxVoices> voices {};
  99. void prepare (double sampleRate)
  100. {
  101. rate = sampleRate;
  102. // the longest line: c = −3600 → ratio 2^-4 (32.7 Hz)
  103. capacity = (int) std::ceil (sampleRate / (523.251130601197 / 16.0)) + 8;
  104. storage.assign ((std::size_t) maxVoices * (std::size_t) capacity * 2, 0.0f);
  105. for (int i = 0; i < maxVoices; ++i)
  106. voices[(std::size_t) i] = Voice {}, voices[(std::size_t) i].line = storage.data() + (std::size_t) i * (std::size_t) capacity * 2;
  107. scratch.assign (1024, 0.0f);
  108. }
  109. bool idle() const noexcept
  110. {
  111. return std::none_of (voices.begin(), voices.end(), [] (const Voice& v) { return v.active; });
  112. }
  113. void releaseAll() noexcept
  114. {
  115. for (auto& v : voices)
  116. if (v.active)
  117. release (v);
  118. }
  119. void release (Voice& v) noexcept
  120. {
  121. if (P.gate > 0)
  122. v.released = true;
  123. }
  124. // TriggerVoice (§1.2–§1.4)
  125. Voice& trigger (int key, float finalPitch, float fvol, float fpan, float modX, float modY) noexcept
  126. {
  127. // max polyphony: the quietest sounding voice (smallest last peak) is released
  128. if (maxPoly > 0)
  129. {
  130. int sounding = 0;
  131. Voice* quietest = nullptr;
  132. float least = 2.0f;
  133. for (auto* v : ordered())
  134. if (! v->released)
  135. {
  136. ++sounding;
  137. if (v->lastPeak < least)
  138. least = v->lastPeak, quietest = v;
  139. }
  140. if (sounding >= maxPoly && quietest != nullptr)
  141. quietest->released = true;
  142. }
  143. Voice* slot = nullptr;
  144. for (auto& v : voices)
  145. if (! v.active)
  146. {
  147. slot = &v;
  148. break;
  149. }
  150. if (slot == nullptr) // (pool full: the oldest voice makes room)
  151. slot = ordered().front();
  152. auto& v = *slot;
  153. auto* line = v.line;
  154. v = Voice {};
  155. v.line = line;
  156. v.active = true, v.key = key, v.order = ++serial;
  157. v.fvol = fvol, v.fpan = fpan, v.modX = modX;
  158. const auto ratio = pitchRatio (finalPitch);
  159. v.N = std::clamp ((int) roundEven (rate / ((double) ratio * 523.251130601197)), 1, capacity);
  160. v.normalize = P.normalize > 0;
  161. if (v.normalize)
  162. v.invRatio = 1.0f / ratio;
  163. v.wide = P.widen > 0;
  164. const auto lv = std::clamp ((std::int64_t) P.colour + roundEven ((double) (modY * 128.0f)), (std::int64_t) 0, (std::int64_t) 128);
  165. const auto c = (float) lv * 0.0078125f;
  166. const auto a = (1.0f - c) * 0.5f;
  167. const auto half = v.N >> 1;
  168. for (int i = 0; i < v.N; ++i)
  169. line[i] = i < half ? a : -a;
  170. if (v.wide)
  171. for (int i = 0; i < v.N; ++i)
  172. line[v.N + i] = (float) ((double) line[i] + (random.next() * 2.0 - 1.0) * (double) c);
  173. for (int i = 0; i < v.N; ++i)
  174. line[i] = (float) ((double) line[i] + (random.next() * 2.0 - 1.0) * (double) c);
  175. v.g = feedbackGain (P, modX, v.normalize, v.invRatio);
  176. return v;
  177. }
  178. // one host block of every voice, added into left/right (§1.5, §1.6)
  179. void render (float* left, float* right, int n) noexcept
  180. {
  181. if ((int) scratch.size() < 2 * n)
  182. n = (int) scratch.size() / 2; // (callers keep blocks ≤ 512)
  183. for (auto& v : voices)
  184. {
  185. if (! v.active)
  186. continue;
  187. if (decayDirty)
  188. v.g = feedbackGain (P, v.modX, v.normalize, v.invRatio);
  189. float tl = 0.0f, tr = 0.0f;
  190. if (! v.released)
  191. gains (v.fpan, v.fvol, tl, tr);
  192. if (v.counter < 0)
  193. v.gainL = tl, v.gainR = tr, v.counter = 0;
  194. const auto g = v.g;
  195. auto* L = v.line;
  196. auto* R = v.line + v.N;
  197. float pL = v.prevL, pR = v.prevR;
  198. int p = v.pos;
  199. float peakL = 0.0f, peakR = 0.0f;
  200. for (int i = 0; i < n; ++i)
  201. {
  202. const auto y = L[p];
  203. L[p] = g * (y + pL);
  204. pL = y;
  205. scratch[(std::size_t) (2 * i)] = y;
  206. peakL = std::max (peakL, std::fabs (y));
  207. if (v.wide)
  208. {
  209. const auto yr = R[p];
  210. R[p] = g * (yr + pR);
  211. pR = yr;
  212. scratch[(std::size_t) (2 * i + 1)] = yr;
  213. peakR = std::max (peakR, std::fabs (yr));
  214. }
  215. else
  216. scratch[(std::size_t) (2 * i + 1)] = y;
  217. if (++p >= v.N)
  218. p = 0;
  219. }
  220. v.prevL = pL, v.prevR = pR, v.pos = p;
  221. // the host adds the voice with its L/R gains, ramping from the previous block's
  222. const auto sl = v.gainL, sr = v.gainR;
  223. const bool moving = ramp && (sl != tl || sr != tr);
  224. for (int i = 0; i < n; ++i)
  225. {
  226. const auto t = moving ? (float) (i + 1) / (float) n : 1.0f;
  227. const auto gl = moving ? sl + (tl - sl) * t : tl;
  228. const auto gr = moving ? sr + (tr - sr) * t : tr;
  229. left[i] += scratch[(std::size_t) (2 * i)] * gl;
  230. right[i] += scratch[(std::size_t) (2 * i + 1)] * gr;
  231. }
  232. v.gainL = tl, v.gainR = tr;
  233. if (! v.released)
  234. {
  235. // level watch: every stretch of more than 256 samples, a peak below 0.004 ends the voice
  236. v.peak = std::max (v.peak, std::max (peakL, peakR));
  237. v.counter += n;
  238. if (v.counter > 256)
  239. {
  240. v.counter = 0;
  241. v.lastPeak = v.peak;
  242. if (v.peak >= 0.004f)
  243. v.peak = 0.0f;
  244. else
  245. v.active = false;
  246. }
  247. }
  248. else if (tl == 0.0f && tr == 0.0f)
  249. v.active = false;
  250. }
  251. decayDirty = false;
  252. }
  253. void setFinal (Voice& v, float fvol, float fpan) noexcept { v.fvol = fvol, v.fpan = fpan; }
  254. void markDecayDirty() noexcept { decayDirty = true; }
  255. private:
  256. void gains (float pan, float vol, float& l, float& r) const noexcept
  257. {
  258. if (panLawA)
  259. flvp::panLaw (pan, vol, l, r);
  260. else
  261. l = r = vol;
  262. }
  263. // the active voices, oldest first (FL keeps them in trigger order); no allocation
  264. struct Ordered
  265. {
  266. std::array<Voice*, maxVoices> v {};
  267. int count = 0;
  268. Voice** begin() noexcept { return v.data(); }
  269. Voice** end() noexcept { return v.data() + count; }
  270. Voice* front() const noexcept { return v[0]; }
  271. };
  272. Ordered ordered() noexcept
  273. {
  274. Ordered out;
  275. for (auto& v : voices)
  276. if (v.active)
  277. out.v[(std::size_t) out.count++] = &v;
  278. std::sort (out.begin(), out.end(), [] (const Voice* a, const Voice* b) { return a->order < b->order; });
  279. return out;
  280. }
  281. double rate = 44100.0;
  282. int capacity = 0;
  283. std::uint64_t serial = 0;
  284. bool decayDirty = false;
  285. std::vector<float> storage, scratch;
  286. };
  287. // ------------------------------------------------------------------------------------------------------- LYNX front-end
  288. //
  289. // Levels as the other FL voice generators (REA_rodada47 §2.1): Final.Vol = channel volume × Init.Vol (Init.Vol =
  290. // (11^(1.28·vel) − 1)/10 from LYNX's velocity), Final.Pan = note pan + channel pan, Final.Pitch = 100·(key − 60) +
  291. // channel pitch + note cents; LYNX's channel gains gl = √2·V·cos((1 + p)π/4), gr = √2·V·sin(…) give V and p back.
  292. class PluckedInstrument final : public Instrument
  293. {
  294. public:
  295. PluckedInstrument() { engine.prepare (44100.0); }
  296. void prepare (double sr) noexcept override
  297. {
  298. engine.prepare (sr);
  299. engine.P = loadParams();
  300. }
  301. void configure (const ChannelDef& channel, double) noexcept override
  302. {
  303. pitchCents.store (channel.sampler.pitch * 100.0f);
  304. maxPoly.store (channel.synth.mono ? 1 : 0);
  305. Params p;
  306. if (parse (channel.pluginState, p))
  307. {
  308. knobs[0].store (p.decay), knobs[1].store (p.colour), knobs[2].store (p.normalize);
  309. knobs[3].store (p.gate), knobs[4].store (p.widen);
  310. }
  311. }
  312. void setNextNoteExpression (float pan, float cents, bool) noexcept override
  313. {
  314. nextPan = pan;
  315. nextCents = cents;
  316. }
  317. void noteOn (int key, float velocity) noexcept override
  318. {
  319. sync();
  320. const auto vel = std::clamp ((double) velocity, 0.0, 1.0);
  321. const auto initVol = (std::pow (11.0, 1.28 * vel) - 1.0) / 10.0;
  322. const auto k = std::clamp (key, 0, 127);
  323. const auto finalPitch = (float) (100.0 * (k - 60) + (double) pitchCents.load() + (double) nextCents);
  324. auto& v = engine.trigger (k, finalPitch, (float) (channelVol * initVol),
  325. (float) std::clamp ((double) nextPan + channelPan, -1.0, 1.0), 0.0f, 0.0f);
  326. const auto slot = (std::size_t) (&v - engine.voices.data());
  327. volFactor[slot] = (float) initVol;
  328. notePan[slot] = nextPan;
  329. nextPan = 0.0f;
  330. nextCents = 0.0f;
  331. }
  332. void noteOff (int key) noexcept override
  333. {
  334. for (auto& v : engine.voices)
  335. if (v.active && v.key == key && ! v.released)
  336. engine.release (v);
  337. }
  338. void allNotesOff() noexcept override { engine.releaseAll(); }
  339. bool idle() const noexcept override { return engine.idle(); }
  340. void render (float* left, float* right, int n, float gl, float gr) noexcept override
  341. {
  342. sync();
  343. const auto vol = std::sqrt (((double) gl * gl + (double) gr * gr) * 0.5);
  344. auto pan = vol > 0.0 ? std::atan2 ((double) gr, (double) gl) * (4.0 / 3.141592653589793) - 1.0 : 0.0;
  345. if (std::fabs (pan) < 1e-9)
  346. pan = 0.0;
  347. if (vol != channelVol || pan != channelPan)
  348. {
  349. channelVol = vol, channelPan = pan;
  350. for (std::size_t i = 0; i < engine.voices.size(); ++i)
  351. if (engine.voices[i].active)
  352. engine.setFinal (engine.voices[i], (float) (vol * (double) volFactor[i]),
  353. (float) std::clamp ((double) notePan[i] + pan, -1.0, 1.0));
  354. }
  355. for (int done = 0; done < n;)
  356. {
  357. const auto len = std::min (512, n - done);
  358. engine.render (left + done, right + done, len);
  359. done += len;
  360. }
  361. }
  362. private:
  363. void sync() noexcept
  364. {
  365. engine.maxPoly = maxPoly.load();
  366. const auto p = loadParams();
  367. if (p.decay != engine.P.decay)
  368. engine.markDecayDirty(); // (parameter 0 makes every voice recompute its feedback gain)
  369. engine.P = p;
  370. }
  371. Params loadParams() const noexcept
  372. {
  373. Params p;
  374. p.decay = knobs[0].load(), p.colour = knobs[1].load(), p.normalize = knobs[2].load();
  375. p.gate = knobs[3].load(), p.widen = knobs[4].load();
  376. return p;
  377. }
  378. Engine engine;
  379. std::array<std::atomic<int>, 5> knobs { 128, 64, 1, 0, 1 };
  380. std::atomic<float> pitchCents { 0.0f };
  381. std::atomic<int> maxPoly { 0 };
  382. std::array<float, maxVoices> volFactor {}, notePan {};
  383. double channelVol = 1.0, channelPan = 0.0;
  384. float nextPan = 0.0f, nextCents = 0.0f;
  385. };
  386. } // namespace
  387. bool pluckedStateUsable (const std::vector<std::uint8_t>& state)
  388. {
  389. Params p;
  390. return parse (state, p);
  391. }
  392. std::optional<std::vector<int>> pluckedParams (const std::vector<std::uint8_t>& state)
  393. {
  394. Params p;
  395. if (! parse (state, p))
  396. return std::nullopt;
  397. return std::vector<int> { p.decay, p.colour, p.normalize, p.gate, p.widen };
  398. }
  399. std::unique_ptr<Instrument> makePluckedInstrument() { return std::make_unique<PluckedInstrument>(); }
  400. namespace plucked
  401. {
  402. std::vector<float> renderReference (const std::vector<std::uint8_t>& state, const std::vector<RefNote>& notes, double sampleRate,
  403. int length, int block, std::uint32_t seed, bool panLawA, int maxPoly)
  404. {
  405. Params P;
  406. if (! parse (state, P) || length <= 0)
  407. return {};
  408. auto engine = std::make_unique<Engine>();
  409. engine->prepare (sampleRate);
  410. engine->P = P, engine->random.seed = seed, engine->panLawA = panLawA, engine->ramp = false, engine->maxPoly = maxPoly;
  411. std::vector<float> out ((std::size_t) length * 2, 0.0f), L ((std::size_t) block), R ((std::size_t) block);
  412. std::vector<Voice*> handle (notes.size(), nullptr);
  413. block = std::clamp (block, 1, 512);
  414. for (int n0 = 0; n0 < length;)
  415. {
  416. auto len = std::min (block, length - n0);
  417. for (const auto& e : notes)
  418. {
  419. if (e.start > n0 && e.start < n0 + len)
  420. len = e.start - n0;
  421. if (e.release > n0 && e.release < n0 + len)
  422. len = e.release - n0;
  423. }
  424. for (std::size_t i = 0; i < notes.size(); ++i)
  425. {
  426. const auto& e = notes[i];
  427. if (e.start == n0)
  428. handle[i] = &engine->trigger (e.key, (float) (100.0 * (e.key - 60) + e.pitchOffset), (float) e.finalVol,
  429. (float) e.finalPan, (float) e.modX, (float) e.modY);
  430. if (e.release == n0 && handle[i] != nullptr && handle[i]->active)
  431. engine->release (*handle[i]);
  432. }
  433. std::fill (L.begin(), L.end(), 0.0f);
  434. std::fill (R.begin(), R.end(), 0.0f);
  435. engine->render (L.data(), R.data(), len);
  436. for (int i = 0; i < len; ++i)
  437. out[(std::size_t) (2 * (n0 + i))] = L[(std::size_t) i], out[(std::size_t) (2 * (n0 + i) + 1)] = R[(std::size_t) i];
  438. n0 += len;
  439. }
  440. return out;
  441. }
  442. } // namespace plucked
  443. } // namespace lynx