Dx10.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. #include "core/Dx10.h"
  2. #include "core/FlVoiceProcessor.h"
  3. #include <algorithm>
  4. #include <array>
  5. #include <atomic>
  6. #include <cmath>
  7. #include <cstdint>
  8. #include <cstring>
  9. #include <optional>
  10. #include <vector>
  11. // 1:1 port of our round-42 reference model (r42/py/dxmodel.py + dxproc.py). The model emulates the DLL's float32 arithmetic with
  12. // numpy float32 scalars and uses Python floats (doubles) where the DLL computes in double; this file keeps those types
  13. // and the operation order of every expression, so fusing a·b + c into one FMA would change the results: contraction
  14. // stays off.
  15. #if defined(__clang__)
  16. #pragma clang fp contract(off)
  17. #elif defined(__GNUC__)
  18. #pragma GCC optimize ("fp-contract=off")
  19. #endif
  20. namespace lynx
  21. {
  22. namespace
  23. {
  24. using namespace flvp;
  25. constexpr int paramCount = 22;
  26. constexpr int maxVoices = 256; // voice records per instance (FL: unlimited; the oldest is cut beyond this)
  27. constexpr int stateWithSnapshot = 4 + 0x5c + snapshotSize; // the plugin applies a snapshot when ≥ 364 bytes follow the 92
  28. std::int32_t i32At (const std::vector<std::uint8_t>& d, std::size_t at) noexcept
  29. {
  30. std::uint32_t v = 0;
  31. std::memcpy (&v, d.data() + at, 4);
  32. return (std::int32_t) v;
  33. }
  34. struct Params
  35. {
  36. std::array<std::int32_t, paramCount> raw {};
  37. float p (int i) const noexcept
  38. {
  39. const int lo = i == 21 ? -3 : 0, hi = i == 21 ? 3 : 65536;
  40. return (float) (raw[(std::size_t) i] - lo) / (float) (hi - lo);
  41. }
  42. };
  43. std::optional<Params> parseState (const std::vector<std::uint8_t>& d)
  44. {
  45. if (d.size() < 4 + 4 * (std::size_t) paramCount)
  46. return std::nullopt;
  47. const auto version = i32At (d, 0); // FUN_00734940: any version below 3 (signed) except 0x7fffffff
  48. if (version == 0x7fffffff || version >= 3)
  49. return std::nullopt;
  50. Params P;
  51. for (int i = 0; i < paramCount; ++i)
  52. P.raw[(std::size_t) i] = i32At (d, 4 + 4 * (std::size_t) i);
  53. return P;
  54. }
  55. // ------------------------------------------------------------------------------------------------------- engine
  56. struct Voice
  57. {
  58. float fpitch = 0, fpitchBase = 0, fvol = 1, fpan = 0, curPitch = 0;
  59. float phi = 0, D = 0, vibofs = 0;
  60. float L1 = 0, T1 = 0, c1 = 0, k1 = 1, L2 = 0, T2 = 0, c2 = 0, k2 = 1;
  61. std::uint32_t ph1 = 0, inc1 = 0, ph2 = 0, inc2 = 0;
  62. float target = 0, g = 0, a = 0, env = 0, d = 0;
  63. int cnt = 0, key = 60;
  64. bool ended = false, released = false;
  65. std::uint64_t serial = 0;
  66. Proc proc;
  67. };
  68. class Engine
  69. {
  70. public:
  71. void init (const Params& params, double sampleRate, const std::uint8_t* snapshot, int ppq, double tempo)
  72. {
  73. P = params;
  74. fs = (int) std::lround (sampleRate);
  75. std::memcpy (snap.data(), snapshot, snap.size());
  76. timing (ppq, tempo);
  77. update();
  78. // end-fade table (FUN_0071e060, mode 3, 10 ms): 0.5·(1 + cos((i + 1)·π/(L + 1))), built by the constructor while
  79. // the plugin's rate object still holds 44 100 Hz, so L = 441 at every rate (EXEC); FL computes the cosine with
  80. // IPP's ippsCos_32f_A11, which LYNX restates (REA_rodada74 §1)
  81. const auto L = roundEven (10.0 * 0.001 * 44100.0);
  82. endTable.resize ((std::size_t) L);
  83. ippcos::endFadeTable (endTable.data(), (long) L);
  84. }
  85. // ProcessEvent 0 (tempo) / SetTimeSig (PPQ): the articulators' tick counts (FUN_00722d80)
  86. void timing (int ppq, double tempo) noexcept
  87. {
  88. const auto keep = S.hasGlobal;
  89. std::array<std::uint32_t, 5> phases {};
  90. for (int k = 0; k < 5; ++k)
  91. phases[(std::size_t) k] = S.recs[(std::size_t) k].globalPhase;
  92. S.build (snap.data(), ppq, tempo);
  93. if (keep)
  94. for (int k = 0; k < 5; ++k)
  95. S.recs[(std::size_t) k].globalPhase = phases[(std::size_t) k];
  96. }
  97. // FUN_00735760
  98. void update() noexcept
  99. {
  100. const auto inv = (float) (1.0 / fs), r44 = (float) (44100.0 / fs);
  101. auto p = [&] (int i) { return (double) P.p (i); };
  102. const auto oct = std::floor (p (21) * 6.9);
  103. D0 = (float) ((double) inv * 8.175798915644 * std::pow (2.0, oct - 2.0));
  104. auto coarse = [&] (int i) { return (float) std::floor (p (i) * 40.1 * p (i)); };
  105. auto fine = [&] (int i) {
  106. if (p (i) >= 0.5)
  107. {
  108. switch (roundEven (p (i) * 8.9))
  109. {
  110. case 4: return 0.25f;
  111. case 5: return 0.333333343f;
  112. case 6: return 0.5f;
  113. case 7: return 0.666666687f;
  114. default: return 0.75f;
  115. }
  116. }
  117. return (float) (p (i) * 0.2 * p (i));
  118. };
  119. ratio1 = (coarse (3) + fine (4)) * 1073741824.0f;
  120. init1 = (float) ((double) r44 * 0.0002 * p (5) * p (5));
  121. sus1 = (float) ((double) r44 * 0.0002 * p (7) * p (7));
  122. vel1 = P.p (9);
  123. ratio2 = (coarse (14) + fine (15)) * 1073741824.0f;
  124. init2 = (float) ((double) r44 * 0.0002 * p (16) * p (16));
  125. sus2 = (float) ((double) r44 * 0.0002 * p (18) * p (18));
  126. vel2 = P.p (20);
  127. vib = (float) (p (10) * 0.001 * p (10));
  128. const auto ninv = (double) -inv;
  129. att = (float) (1.0 - std::exp (ninv * std::exp (8.0 - p (0) * 8.0)));
  130. dec = p (1) > 0.98 ? 1.0f : (float) std::exp (ninv * std::exp (5.0 - p (1) * 8.0));
  131. rel = (float) std::exp (ninv * std::exp (5.0 - p (2) * 5.0));
  132. time1 = (float) (1.0 - std::exp (ninv * std::exp (6.0 - p (6) * 7.0)));
  133. mrel1 = (float) (1.0 - std::exp (ninv * std::exp (5.0 - p (8) * 8.0)));
  134. time2 = (float) (1.0 - std::exp (ninv * std::exp (6.0 - p (17) * 7.0)));
  135. mrel2 = (float) (1.0 - std::exp (ninv * std::exp (5.0 - p (19) * 8.0)));
  136. rich = (float) (0.5 - p (11) * 3.0 * p (11));
  137. thru = (float) (p (12) * 0.25 * p (12));
  138. lfoRate = (float) ((double) inv * 15707.499999999998 * p (13) * p (13));
  139. waveform = P.p (11);
  140. }
  141. // FUN_00735d90: past the max polyphony, the quietest unfinished voice (lowest envelope target) is finished
  142. void steal() noexcept
  143. {
  144. if (maxPoly <= 0 || maxPoly > count)
  145. return;
  146. int unfinished = 0;
  147. Voice* best = nullptr;
  148. float lowest = 2.0f;
  149. for (int i = 0; i < count; ++i)
  150. {
  151. auto& v = voices[(std::size_t) order[(std::size_t) i]];
  152. if (! v.ended)
  153. {
  154. ++unfinished;
  155. if (v.target < lowest)
  156. lowest = v.target, best = &v;
  157. }
  158. }
  159. if (unfinished >= maxPoly && best != nullptr)
  160. best->ended = true, best->target = 0.0f;
  161. }
  162. // FUN_00735e30 (TriggerVoice); returns the voice record index
  163. int trigger (int key, float initVol, float finalPitch, float finalVol, float finalPan) noexcept
  164. {
  165. steal();
  166. if (count >= maxVoices)
  167. removeAt (oldest());
  168. int slot = 0;
  169. while (used[(std::size_t) slot])
  170. ++slot;
  171. used[(std::size_t) slot] = true;
  172. auto& v = voices[(std::size_t) slot];
  173. v = Voice {};
  174. v.key = key;
  175. v.serial = ++serials;
  176. v.fpitch = v.fpitchBase = v.curPitch = finalPitch;
  177. v.fvol = finalVol;
  178. v.fpan = finalPan;
  179. const auto k = roundEven ((double) finalPitch);
  180. const auto q = k / 100; // C division
  181. const auto frac = (float) (k - 100 * q) * 0.01f;
  182. auto note = (int) ((finalPitch * 0.01f - frac) + 60.0f);
  183. note = std::min (std::max (note, 0), 127);
  184. auto x = initVol * 10.0f;
  185. const auto lim = 20.5511818f;
  186. if (x > lim)
  187. x = lim;
  188. const auto a = std::log ((double) (x + 1.0f)), b = std::log ((double) (lim + 1.0f));
  189. auto V = roundEven ((double) ((float) (a / b) * 127.0f));
  190. V = std::min<std::int64_t> (std::max<std::int64_t> (V, 0), 1270);
  191. const auto Vf = (float) V;
  192. auto ratio = (float) std::exp ((double) ((float) note + frac) * 0.05776226505);
  193. v.D = D0 * bend * ratio;
  194. if ((double) ratio > 50.0)
  195. ratio = 50.0f;
  196. const auto l1 = (float) ((double) ratio * ((double) (vel1 * (Vf - 64.0f)) + 64.0));
  197. v.L1 = init1 * l1, v.T1 = sus1 * l1, v.c1 = time1;
  198. v.inc1 = (std::uint32_t) roundEven ((double) (ratio1 * v.D));
  199. const auto l2 = (float) ((double) ratio * ((double) (vel2 * (Vf - 64.0f)) + 64.0));
  200. v.L2 = init2 * l2, v.T2 = sus2 * l2, v.c2 = time2;
  201. v.inc2 = (std::uint32_t) roundEven ((double) (ratio2 * v.D));
  202. v.target = (float) ((1.5 - (double) waveform) * 0.0035000001080334187 * (double) (Vf + 10.0f));
  203. v.g = (float) (1.2 / (double) v.target);
  204. v.a = att, v.env = 0.0f, v.d = dec;
  205. v.proc.init (S);
  206. order[(std::size_t) count++] = slot;
  207. return slot;
  208. }
  209. // FUN_00736320 (Voice_Release; the processor's articulators are not released)
  210. void release (int slot) noexcept
  211. {
  212. auto& v = voices[(std::size_t) slot];
  213. v.released = true;
  214. v.d = rel, v.target = v.env, v.a = 1.0f;
  215. v.T1 = 0.0f, v.c1 = mrel1, v.T2 = 0.0f, v.c2 = mrel2;
  216. }
  217. // FUN_00736800: Final.Pitch changed
  218. void repitch (Voice& v) noexcept
  219. {
  220. const auto k = roundEven ((double) v.curPitch);
  221. const auto q = k / 100;
  222. const auto note = (int) std::min<std::int64_t> (std::max<std::int64_t> (q + 60, 0), 127);
  223. const auto frac = (float) ((double) (k - 100 * q) / 100.0);
  224. const auto r = (float) std::exp ((double) ((float) note + frac) * 0.05776226505);
  225. v.D = D0 * bend * r;
  226. v.inc1 = (std::uint32_t) roundEven ((double) (ratio1 * v.D));
  227. v.inc2 = (std::uint32_t) roundEven ((double) (ratio2 * v.D));
  228. }
  229. // FUN_007364a0 (Voice_Render): mono output into x
  230. void voiceRender (Voice& v, float* x, int n) noexcept
  231. {
  232. if (v.fpitch != v.curPitch)
  233. {
  234. v.curPitch = v.fpitch;
  235. repitch (v);
  236. }
  237. const auto& sine = sineTable();
  238. auto phi = v.phi;
  239. auto d = v.D + v.vibofs;
  240. for (int i = 0; i < n; ++i)
  241. {
  242. if (v.cnt == 0)
  243. {
  244. lfoS = lfoS + lfoRate * lfoC;
  245. lfoC = lfoC - lfoRate * lfoS;
  246. v.vibofs = lfoC * (modWheel + vib);
  247. d = v.D + v.vibofs;
  248. v.cnt = 100;
  249. }
  250. else
  251. --v.cnt;
  252. v.env = v.env + v.a * (v.target - v.env);
  253. v.target = v.target * v.d;
  254. const auto m1 = v.k1 * sine[v.ph1 >> 18];
  255. phi = ((phi + d) + v.L1 * m1) + (v.L2 * v.k2) * sine[v.ph2 >> 18];
  256. v.L1 = v.L1 + v.c1 * (v.T1 - v.L1);
  257. v.L2 = v.L2 + v.c2 * (v.T2 - v.L2);
  258. v.ph1 += v.inc1;
  259. v.ph2 += v.inc2;
  260. if (std::fabs (phi) > 1.0f)
  261. {
  262. if (phi < 0.0f)
  263. while (std::fabs (phi) > 1.0f)
  264. phi = phi + 2.0f;
  265. else
  266. while (std::fabs (phi) > 1.0f)
  267. phi = phi - 2.0f;
  268. }
  269. const auto pp = phi * phi;
  270. const auto shaped = phi + (pp * phi) * ((rich * (pp - 1.0f)) - 1.0f);
  271. x[i] = (v.g * v.env) * (thru * m1 + shaped);
  272. }
  273. v.phi = phi;
  274. if (bitsOf (v.target) < 961656599) // envelope target below 0.0002 (bit compare)
  275. v.d = 1.0f, v.ended = true;
  276. if (bitsOf (v.L1) < 864026624)
  277. v.L1 = 0.0f, v.T1 = 0.0f;
  278. if (bitsOf (v.L2) < 864026624)
  279. v.L2 = 0.0f, v.T2 = 0.0f;
  280. }
  281. // NewTick (FUN_00736b00 → FUN_00721f60): flags the next render's articulator step; global LFOs advance once the
  282. // plugin has listed them (at the first render with voices after a load, FUN_00721d10/FUN_00721c80)
  283. void newTick() noexcept
  284. {
  285. tickPending = true;
  286. if (listed)
  287. for (auto& r : S.recs)
  288. if ((r.flags & 0x20) != 0)
  289. r.globalPhase += r.lfoInc;
  290. }
  291. // Gen_Render (FUN_00736a10): voices through the processor, mixed into l/r (overwrites)
  292. void render (float* l, float* r, int n) noexcept
  293. {
  294. std::fill (l, l + n, 0.0f);
  295. std::fill (r, r + n, 0.0f);
  296. if (count > 0)
  297. listed = true;
  298. const auto tick = tickPending;
  299. tickPending = false;
  300. if ((int) mono.size() < n)
  301. return; // (prepared for at most `prepareBlock`)
  302. for (int i = 0; i < count; ++i)
  303. {
  304. auto& v = voices[(std::size_t) order[(std::size_t) i]];
  305. auto& pr = v.proc;
  306. if (tick || pr.first > 0)
  307. {
  308. pr.control (S);
  309. v.fpitch = v.fpitchBase + pr.pitch; // FL's host restores Final.Pitch every tick (inference)
  310. }
  311. voiceRender (v, mono.data(), n);
  312. for (int j = 0; j < n; ++j)
  313. bufA[2 * (std::size_t) j] = bufA[2 * (std::size_t) j + 1] = mono[(std::size_t) j];
  314. float tL, tR;
  315. panLaw (v.fpan + pr.pan, v.fvol * pr.vol, tL, tR);
  316. if (! pr.gainsSet)
  317. pr.gL = pr.gR = 0.0f, pr.gainsSet = true;
  318. if (pr.first > 1)
  319. pr.gL = tL, pr.gR = tR; // the first block starts at the target
  320. const float* x = bufA.data();
  321. if (flvp::filter (S, pr, bufA.data(), bufB.data(), n, tL, tR))
  322. x = bufB.data();
  323. if (pr.endPos >= 0) // end fade (FUN_0071e8b0, mode 3): the table, then silence
  324. {
  325. auto* w = const_cast<float*> (x);
  326. const auto L = (int) endTable.size();
  327. const auto k = std::min (std::max (L - pr.endPos, 0), n);
  328. for (int j = 0; j < k; ++j)
  329. {
  330. const auto t = endTable[(std::size_t) (pr.endPos + j)];
  331. w[2 * j] = w[2 * j] * t;
  332. w[2 * j + 1] = w[2 * j + 1] * t;
  333. }
  334. std::fill (w + 2 * k, w + 2 * n, 0.0f);
  335. pr.endPos += n;
  336. if (pr.endPos >= L)
  337. v.ended = true;
  338. }
  339. const auto sL = rampStep (tL, pr.gL, n), sR = rampStep (tR, pr.gR, n);
  340. if (sL == 0.0f && sR == 0.0f)
  341. {
  342. for (int j = 0; j < n; ++j)
  343. {
  344. l[j] = x[2 * j] * tL + l[j];
  345. r[j] = x[2 * j + 1] * tR + r[j];
  346. }
  347. }
  348. else
  349. mixRamp (x, l, r, n, pr.gL, pr.gR, sL, sR);
  350. pr.gL = tL, pr.gR = tR;
  351. pr.first = 0;
  352. }
  353. // the plugin asks the host to kill finished voices, last to first; the host's kill removes them at once
  354. for (int i = count - 1; i >= 0; --i)
  355. if (voices[(std::size_t) order[(std::size_t) i]].ended)
  356. removeAt (i);
  357. }
  358. // FUN_005f9760 (SSE path): lanes [L0, R0, L1, R1] start at g and g + s, +2s per pair of frames, single frames +s
  359. static void mixRamp (const float* x, float* l, float* r, int n, float gL, float gR, float sL, float sR) noexcept
  360. {
  361. float a0 = gL + 0.0f, a1 = gR + 0.0f, a2 = gL + sL, a3 = gR + sR;
  362. const float s2L = sL + sL, s2R = sR + sR;
  363. const int full = (n >> 3) << 3;
  364. for (int i = 0; i < full; i += 2)
  365. {
  366. l[i] = x[2 * i] * a0 + l[i];
  367. r[i] = x[2 * i + 1] * a1 + r[i];
  368. l[i + 1] = x[2 * i + 2] * a2 + l[i + 1];
  369. r[i + 1] = x[2 * i + 3] * a3 + r[i + 1];
  370. a0 = a0 + s2L, a1 = a1 + s2R, a2 = a2 + s2L, a3 = a3 + s2R;
  371. }
  372. for (int i = full; i < n; ++i)
  373. {
  374. l[i] = x[2 * i] * a0 + l[i];
  375. r[i] = x[2 * i + 1] * a1 + r[i];
  376. a0 = a0 + sL, a1 = a1 + sR;
  377. }
  378. }
  379. // unordered list: the last voice takes the removed one's place (FUN_005ea710)
  380. void removeAt (int i) noexcept
  381. {
  382. if (i < 0 || i >= count)
  383. return;
  384. used[(std::size_t) order[(std::size_t) i]] = false;
  385. order[(std::size_t) i] = order[(std::size_t) (count - 1)];
  386. --count;
  387. }
  388. int oldest() const noexcept
  389. {
  390. int best = 0;
  391. for (int i = 1; i < count; ++i)
  392. if (voices[(std::size_t) order[(std::size_t) i]].serial < voices[(std::size_t) order[(std::size_t) best]].serial)
  393. best = i;
  394. return best;
  395. }
  396. void reset() noexcept
  397. {
  398. count = 0;
  399. used.fill (false);
  400. lfoS = 0.0f, lfoC = 1.0f;
  401. listed = false, tickPending = false;
  402. for (auto& r : S.recs)
  403. r.globalPhase = 0;
  404. }
  405. void prepareBlock (int maxBlock)
  406. {
  407. const auto m = (std::size_t) std::max (maxBlock, 1);
  408. mono.assign (m, 0.0f);
  409. bufA.assign (2 * m, 0.0f);
  410. bufB.assign (2 * m, 0.0f);
  411. }
  412. Params P;
  413. Settings S;
  414. std::array<std::uint8_t, snapshotSize> snap = defaultSnapshot();
  415. int fs = 44100, maxPoly = 0;
  416. float D0 = 0, ratio1 = 0, init1 = 0, sus1 = 0, vel1 = 0, ratio2 = 0, init2 = 0, sus2 = 0, vel2 = 0, vib = 0;
  417. float att = 0, dec = 1, rel = 1, time1 = 0, mrel1 = 0, time2 = 0, mrel2 = 0, rich = 0, thru = 0, lfoRate = 0, waveform = 0;
  418. float lfoS = 0.0f, lfoC = 1.0f, modWheel = 0.0f, bend = 1.0f; // plugin globals after the constructor
  419. bool listed = false, tickPending = false;
  420. std::array<Voice, maxVoices> voices {};
  421. std::array<bool, maxVoices> used {};
  422. std::array<int, maxVoices> order {};
  423. int count = 0;
  424. std::uint64_t serials = 0;
  425. std::vector<float> mono, bufA, bufB, endTable;
  426. };
  427. const std::uint8_t* snapshotOf (const std::vector<std::uint8_t>& state, const std::array<std::uint8_t, snapshotSize>& fallback) noexcept
  428. {
  429. return state.size() >= (std::size_t) stateWithSnapshot ? state.data() + 96 : fallback.data();
  430. }
  431. } // namespace
  432. bool dx10StateUsable (const std::vector<std::uint8_t>& state) { return parseState (state).has_value(); }
  433. std::vector<std::uint8_t> dx10StateWithSnapshot (const std::vector<std::uint8_t>& state, const std::vector<std::uint8_t>& snapshot, bool replace)
  434. {
  435. if (! parseState (state) || snapshot.size() < (std::size_t) snapshotSize)
  436. return {};
  437. if (state.size() >= (std::size_t) stateWithSnapshot && ! replace)
  438. return state;
  439. std::vector<std::uint8_t> out (state.begin(), state.begin() + 4 + 4 * paramCount);
  440. const std::int32_t version = 2;
  441. std::memcpy (out.data(), &version, 4);
  442. out.resize (96, 0);
  443. out.insert (out.end(), snapshot.begin(), snapshot.begin() + snapshotSize);
  444. return out;
  445. }
  446. bool dx10ProcessorNeutral (const std::vector<std::uint8_t>& state)
  447. {
  448. if (! dx10StateUsable (state))
  449. return false;
  450. static const auto defaults = defaultSnapshot();
  451. const auto* s = snapshotOf (state, defaults);
  452. auto at = [&] (int k, int i) {
  453. std::int32_t v;
  454. std::memcpy (&v, s + 0x44 * k + 4 * i, 4);
  455. return v;
  456. };
  457. for (int k = 0; k < 5; ++k)
  458. {
  459. if (at (k, 11) != 0) // LFO amount
  460. return false;
  461. if (k == 1 ? ! (at (k, 1) == 0 && (at (k, 0) & 4) != 0) : (k != 0 && at (k, 1) != 0 && at (k, 8) != 0))
  462. return false;
  463. }
  464. std::int32_t modX, modY, type;
  465. std::memcpy (&modX, s + 0x15c, 4);
  466. std::memcpy (&modY, s + 0x160, 4);
  467. std::memcpy (&type, s + 0x168, 4);
  468. return type == 0 && modX >= 256 && modY <= 0;
  469. }
  470. std::optional<int> dx10Param (const std::vector<std::uint8_t>& state, int index)
  471. {
  472. const auto P = parseState (state);
  473. if (! P || index < 0 || index >= paramCount)
  474. return std::nullopt;
  475. return P->raw[(std::size_t) index];
  476. }
  477. bool dx10SetParam (std::vector<std::uint8_t>& state, int index, int value)
  478. {
  479. if (! parseState (state) || index < 0 || index >= paramCount)
  480. return false;
  481. value = index == 21 ? std::clamp (value, -3, 3) : std::clamp (value, 0, 65536);
  482. const auto v = (std::uint32_t) value;
  483. std::memcpy (state.data() + 4 + 4 * (std::size_t) index, &v, 4);
  484. return true;
  485. }
  486. namespace
  487. {
  488. // ------------------------------------------------------------------------------------------------------- instrument
  489. struct Setup
  490. {
  491. Params P;
  492. std::array<std::uint8_t, snapshotSize> snap = defaultSnapshot();
  493. int ppq = 96;
  494. double tempo = 140.0;
  495. };
  496. class Dx10Instrument final : public Instrument
  497. {
  498. public:
  499. Dx10Instrument()
  500. {
  501. engine.prepareBlock (blockSize);
  502. engine.init (Params {}, 44100.0, defaultSnapshot().data(), 96, 140.0);
  503. }
  504. ~Dx10Instrument() override
  505. {
  506. delete incoming.exchange (nullptr);
  507. delete retired.exchange (nullptr);
  508. }
  509. void prepare (double sr) noexcept override
  510. {
  511. rate = sr;
  512. take();
  513. engine.init (current.P, sr, current.snap.data(), current.ppq, current.tempo);
  514. engine.reset();
  515. tickPhase = 0.0;
  516. playing = false;
  517. lastTicks = -1.0;
  518. }
  519. // UI thread: the parsed state goes through a mailbox (the audio thread takes it, this thread frees it)
  520. void configure (const ChannelDef& channel, double bpm) noexcept override
  521. {
  522. delete retired.exchange (nullptr);
  523. pitchCents.store (channel.sampler.pitch * 100.0f);
  524. maxPoly.store (channel.synth.mono ? 1 : 0);
  525. const auto ppq = channel.modelParams.empty() ? 96 : std::clamp ((int) channel.modelParams[0], 1, 1 << 16);
  526. const auto tempo = bpm > 0.0 ? bpm : 140.0;
  527. if (channel.pluginState == state && ppq == lastPpq && tempo == lastTempo)
  528. return;
  529. state = channel.pluginState, lastPpq = ppq, lastTempo = tempo;
  530. if (auto p = parseState (state))
  531. {
  532. auto s = std::make_unique<Setup>();
  533. s->P = *p;
  534. static const auto defaults = defaultSnapshot();
  535. std::memcpy (s->snap.data(), snapshotOf (state, defaults), snapshotSize);
  536. s->ppq = ppq, s->tempo = tempo;
  537. delete incoming.exchange (s.release());
  538. }
  539. }
  540. void setNextNoteExpression (float pan, float cents, bool) noexcept override
  541. {
  542. nextPan = pan;
  543. nextCents = cents;
  544. }
  545. void noteOn (int key, float velocity) noexcept override
  546. {
  547. take();
  548. const auto vel = std::clamp ((double) velocity, 0.0, 1.0);
  549. const auto initVol = (float) ((std::pow (11.0, 1.28 * vel) - 1.0) / 10.0);
  550. const auto k = std::clamp (key, 0, 127);
  551. const auto finalPitch = (float) (100.0 * (k - 60) + (double) pitchCents.load() + (double) nextCents);
  552. const auto slot = engine.trigger (k, initVol, finalPitch, (float) (channelVol * (double) initVol),
  553. (float) std::clamp ((double) nextPan + channelPan, -1.0, 1.0));
  554. volFactor[(std::size_t) slot] = initVol;
  555. notePan[(std::size_t) slot] = nextPan;
  556. nextPan = 0.0f;
  557. nextCents = 0.0f;
  558. }
  559. void noteOff (int key) noexcept override
  560. {
  561. for (int i = 0; i < engine.count; ++i)
  562. {
  563. const auto slot = engine.order[(std::size_t) i];
  564. const auto& v = engine.voices[(std::size_t) slot];
  565. if (v.key == key && ! v.released)
  566. engine.release (slot);
  567. }
  568. }
  569. void allNotesOff() noexcept override
  570. {
  571. for (int i = 0; i < engine.count; ++i)
  572. {
  573. const auto slot = engine.order[(std::size_t) i];
  574. if (! engine.voices[(std::size_t) slot].released)
  575. engine.release (slot);
  576. }
  577. }
  578. bool idle() const noexcept override { return engine.count == 0; }
  579. // while the transport moves, FL's sequencer ticks fall on the song's PPQ grid
  580. void setSongPosition (double ticks) noexcept override
  581. {
  582. playing = lastTicks >= 0.0 && ticks != lastTicks;
  583. lastTicks = ticks;
  584. if (playing)
  585. tickPhase = ticks / (double) ppq * (double) current.ppq;
  586. }
  587. void render (float* left, float* right, int n, float gl, float gr) noexcept override
  588. {
  589. take();
  590. engine.maxPoly = maxPoly.load();
  591. // FL's channel volume/pan from LYNX's gains (gl = √2·V·cos((1 + p)π/4), gr = √2·V·sin(…)); FL recomputes the
  592. // voices' FinalLevels when the channel level changes
  593. const auto vol = std::sqrt (((double) gl * gl + (double) gr * gr) * 0.5);
  594. auto pan = vol > 0.0 ? std::atan2 ((double) gr, (double) gl) * (4.0 / 3.141592653589793) - 1.0 : 0.0;
  595. if (std::fabs (pan) < 1e-9)
  596. pan = 0.0;
  597. if (vol != channelVol || pan != channelPan)
  598. {
  599. channelVol = vol, channelPan = pan;
  600. for (int i = 0; i < engine.count; ++i)
  601. {
  602. const auto slot = engine.order[(std::size_t) i];
  603. auto& v = engine.voices[(std::size_t) slot];
  604. v.fvol = (float) (vol * (double) volFactor[(std::size_t) slot]);
  605. v.fpan = (float) std::clamp ((double) notePan[(std::size_t) slot] + pan, -1.0, 1.0);
  606. }
  607. }
  608. // FL's sequencer ticks (PPQ per beat): a tick boundary starts a new host block, NewTick first
  609. const auto perSample = current.tempo * (double) current.ppq / (60.0 * rate);
  610. for (int done = 0; done < n;)
  611. {
  612. if (std::fabs (tickPhase - std::round (tickPhase)) < 1e-9)
  613. {
  614. tickPhase = std::round (tickPhase);
  615. engine.newTick();
  616. }
  617. const auto next = std::floor (tickPhase) + 1.0;
  618. const auto toNext = std::max (1, (int) std::ceil ((next - tickPhase) / perSample - 1e-9));
  619. const auto len = std::min ({ blockSize, n - done, toNext });
  620. engine.render (bufL.data(), bufR.data(), len);
  621. for (int j = 0; j < len; ++j)
  622. {
  623. left[done + j] += bufL[(std::size_t) j];
  624. right[done + j] += bufR[(std::size_t) j];
  625. }
  626. tickPhase = len == toNext ? next : tickPhase + (double) len * perSample;
  627. done += len;
  628. }
  629. }
  630. private:
  631. void take() noexcept
  632. {
  633. if (retired.load() != nullptr)
  634. return;
  635. if (auto* s = incoming.exchange (nullptr))
  636. {
  637. current = *s;
  638. engine.P = current.P;
  639. std::memcpy (engine.snap.data(), current.snap.data(), snapshotSize);
  640. engine.timing (current.ppq, current.tempo); // (FL: parameters and tempo reach the plugin while voices play)
  641. engine.update();
  642. retired.store (s);
  643. }
  644. }
  645. static constexpr int blockSize = 512;
  646. Engine engine;
  647. Setup current;
  648. std::atomic<Setup*> incoming { nullptr }, retired { nullptr };
  649. std::atomic<float> pitchCents { 0.0f };
  650. std::atomic<int> maxPoly { 0 };
  651. std::vector<std::uint8_t> state;
  652. int lastPpq = -1;
  653. double lastTempo = -1.0;
  654. std::array<float, blockSize> bufL {}, bufR {};
  655. std::array<float, maxVoices> volFactor {}, notePan {};
  656. double rate = 44100.0, channelVol = 1.0, channelPan = 0.0, tickPhase = 0.0, lastTicks = -1.0;
  657. bool playing = false;
  658. float nextPan = 0.0f, nextCents = 0.0f;
  659. };
  660. } // namespace
  661. std::unique_ptr<Instrument> makeDx10Instrument() { return std::make_unique<Dx10Instrument>(); }
  662. namespace dx10
  663. {
  664. std::vector<float> renderReference (const std::vector<std::uint8_t>& state, const std::vector<RefNote>& notes, double sampleRate,
  665. int length, const RefOptions& opt)
  666. {
  667. const auto P = parseState (state);
  668. if (! P || length <= 0)
  669. return {};
  670. static const auto defaults = defaultSnapshot();
  671. auto engine = std::make_unique<Engine>();
  672. engine->init (*P, sampleRate, snapshotOf (state, defaults), opt.ppq, opt.tempo);
  673. engine->maxPoly = opt.maxPoly;
  674. const auto block = std::max (1, opt.block);
  675. engine->prepareBlock (block);
  676. std::vector<int> slot (notes.size(), -1);
  677. std::vector<std::uint64_t> serial (notes.size(), 0);
  678. std::vector<float> out (2 * (std::size_t) length, 0.0f), l ((std::size_t) block), r ((std::size_t) block);
  679. // events at a sample in the model's order: sorted by sample, then in list order (stable)
  680. std::vector<std::pair<int, int>> order; // (sample, 2·note + isOff)
  681. for (std::size_t i = 0; i < notes.size(); ++i)
  682. {
  683. order.push_back ({ notes[i].start, 2 * (int) i });
  684. if (notes[i].release >= 0)
  685. order.push_back ({ notes[i].release, 2 * (int) i + 1 });
  686. }
  687. std::stable_sort (order.begin(), order.end(), [] (const auto& a, const auto& b) { return a.first < b.first; });
  688. int n0 = 0;
  689. std::size_t next = 0;
  690. while (n0 < length)
  691. {
  692. auto ln = std::min (block, length - n0);
  693. for (const auto& e : order)
  694. if (n0 < e.first && e.first < n0 + ln)
  695. ln = e.first - n0;
  696. if (opt.tick > 0)
  697. {
  698. const auto nt = (n0 / opt.tick + 1) * opt.tick;
  699. if (nt < n0 + ln)
  700. ln = nt - n0;
  701. if (n0 % opt.tick == 0)
  702. engine->newTick();
  703. }
  704. while (next < order.size() && order[next].first < n0)
  705. ++next;
  706. while (next < order.size() && order[next].first == n0)
  707. {
  708. const auto i = (std::size_t) (order[next].second / 2);
  709. const auto& nt = notes[i];
  710. if (order[next].second % 2 == 0)
  711. {
  712. slot[i] = engine->trigger (nt.key, (float) nt.initVol, (float) (100.0 * nt.key - 6000.0 + nt.pitchOffset), (float) nt.finalVol,
  713. (float) nt.finalPan);
  714. serial[i] = engine->voices[(std::size_t) slot[i]].serial;
  715. }
  716. else if (slot[i] >= 0 && engine->used[(std::size_t) slot[i]] && engine->voices[(std::size_t) slot[i]].serial == serial[i])
  717. engine->release (slot[i]);
  718. ++next;
  719. }
  720. engine->render (l.data(), r.data(), ln);
  721. for (int j = 0; j < ln; ++j)
  722. {
  723. out[2 * (std::size_t) (n0 + j)] = l[(std::size_t) j];
  724. out[2 * (std::size_t) (n0 + j) + 1] = r[(std::size_t) j];
  725. }
  726. n0 += ln;
  727. }
  728. return out;
  729. }
  730. } // namespace dx10
  731. } // namespace lynx