GrossBeat.cpp 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  1. // FL Studio's Gross Beat (REA_rodada53): state reader, envelope player, time-travel buffer reader and volume stage.
  2. // Behaviour rebuilt from the plugin DLL of the user's installation; written from scratch in LYNX's own words. The order of
  3. // the floating-point operations follows the plugin wherever it changes the result (float vs double vs x87 extended,
  4. // IPP-style vector steps), which is what makes the output sample-identical.
  5. #include "core/GrossBeat.h"
  6. #include <algorithm>
  7. #include <cmath>
  8. #include <cstring>
  9. #include <limits>
  10. #if defined(__SSE__) || defined(_M_X64) || defined(__x86_64__) // x86 only: rcpps cannot be reproduced through NEON; ARM64 takes the plain path
  11. #include "core/Simd.h"
  12. #define LYNX_GB_SSE 1
  13. #endif
  14. namespace lynx::grossbeat
  15. {
  16. namespace
  17. {
  18. using ext = long double; // the plugin's x87 steps (64-bit mantissa where the platform has it)
  19. constexpr double pi = 3.141592653589793;
  20. constexpr float twoPiF = 6.28318548f;
  21. constexpr int intMax = std::numeric_limits<std::int32_t>::max();
  22. constexpr int holdNow = std::numeric_limits<std::int32_t>::min() + 1;
  23. // Delphi's Round (and cvtsd2si): to nearest, ties to even
  24. inline std::int64_t roundEven (double x) noexcept { return (std::int64_t) std::nearbyint (x); }
  25. // The plugin's vector exp for the volume tension (IPP's 11-bit "A11" exp as dispatched on FMA-capable x86-64; its outputs
  26. // were matched sample for sample over |x| ≤ 7.5, the range the tension uses): x = n·ln2 + r with n the nearest integer to
  27. // x·log2(e) (float), a float cubic in r evaluated with fused multiply-adds, scaled by 2^n.
  28. inline float exp11 (float x) noexcept
  29. {
  30. const float n = std::nearbyint (x * 1.44269502f);
  31. const float nl = n * 0.693147182f;
  32. const float r = x - nl;
  33. const float p = std::fma (std::fma (std::fma (0.165419281f, r, 0.503705382f), r, 1.00011802f), r, 1.0f);
  34. return std::ldexp (p, (int) n);
  35. }
  36. inline std::uint32_t floatBits (float f) noexcept
  37. {
  38. std::uint32_t u;
  39. std::memcpy (&u, &f, 4);
  40. return u;
  41. }
  42. inline bool atLeastOne (double phase) noexcept // the player's loop test: high word of the double above 0x3fefffff
  43. {
  44. std::uint64_t u;
  45. std::memcpy (&u, &phase, 8);
  46. return (std::uint32_t) (u >> 32) > 0x3fefffffu;
  47. }
  48. std::int32_t i32 (const std::uint8_t* p) noexcept
  49. {
  50. std::int32_t v;
  51. std::memcpy (&v, p, 4);
  52. return v;
  53. }
  54. // ---------------------------------------------------------------------------------------------------------------
  55. // envelope points: normalisation to one 4-beat bar and per-point coefficients (done by the plugin when a slot loads)
  56. constexpr double barLength = 4.0;
  57. void insertPoint (std::vector<Point>& pts, double x, float y)
  58. {
  59. x = std::clamp (x, 0.0, barLength);
  60. const auto n = (int) pts.size();
  61. int idx = n;
  62. double before = 0.0;
  63. if (n >= 1)
  64. {
  65. double cum = pts[0].dx;
  66. before = cum;
  67. for (int i = 1; i < n; ++i)
  68. {
  69. const auto next = cum + pts[(std::size_t) i].dx;
  70. if (x < next)
  71. {
  72. idx = i;
  73. before = cum;
  74. break;
  75. }
  76. cum = next;
  77. before = cum;
  78. }
  79. }
  80. Point p;
  81. const auto gap = (float) (x - before);
  82. p.dx = (double) (0.0f < gap ? gap : 0.0f);
  83. p.y = y;
  84. pts.insert (pts.begin() + idx, p);
  85. if (idx < n)
  86. pts[(std::size_t) idx + 1].dx -= pts[(std::size_t) idx].dx;
  87. }
  88. int waveCount (const Point& p) noexcept
  89. {
  90. if (p.type < 3 || p.type > 6)
  91. return -1;
  92. const auto v = 1.0 - std::fabs ((double) p.tension) * 0.6;
  93. const auto e = std::exp ((double) (float) v * std::log (1000001.0));
  94. auto n = (int) roundEven ((double) (float) (e - 1.0) * 0.001);
  95. if (p.type == 3 && 0.0f <= p.tension)
  96. ++n;
  97. return n;
  98. }
  99. void tensionCurve (float k, float& kOut, float& inv, float& lnK) noexcept
  100. {
  101. kOut = k;
  102. if (k != 0.0f)
  103. {
  104. inv = (float) (1.0 / std::fabs ((double) k));
  105. lnK = (float) std::log (std::fabs ((double) k) + 1.0);
  106. }
  107. }
  108. void precompute (std::vector<Point>& pts) noexcept
  109. {
  110. for (std::size_t i = 0; i < pts.size(); ++i)
  111. {
  112. auto& p = pts[i];
  113. if (p.dx < 0.0)
  114. p.dx = 0.0;
  115. if (i == 0)
  116. continue;
  117. const auto bits = floatBits (p.tension);
  118. p.dir = (std::int8_t) ((bits & 0x7fffffffu) == 0 ? 0 : ((bits >> 31) != 0 ? -1 : 1));
  119. const auto n = waveCount (p);
  120. const float sign = p.tension < 0.0f ? -1.0f : 1.0f;
  121. switch (p.type)
  122. {
  123. case 0:
  124. case 1:
  125. {
  126. const auto mag = (double) (float) std::fabs ((double) p.tension);
  127. auto k = (float) (std::exp (mag * std::log (1000001.0)) - 1.0);
  128. const int s = (bits << 1) == 0 ? 0 : 1 - 2 * (int) (bits >> 31);
  129. k *= (float) s;
  130. tensionCurve (k, p.k14, p.k18, p.k1c);
  131. break;
  132. }
  133. case 3:
  134. p.k1c = sign * 0.5f;
  135. p.k14 = (float) (n + 1);
  136. p.k18 = 1.0f / (p.k14 - sign);
  137. break;
  138. case 4:
  139. p.k14 = (float) (n + 1);
  140. p.k18 = 1.0f / p.k14;
  141. break;
  142. case 5:
  143. p.k1c = sign * 0.5f;
  144. p.k14 = (float) ((n + 1) * 2);
  145. p.k18 = twoPiF;
  146. break;
  147. case 6:
  148. p.k14 = (float) ((double) n + 0.5);
  149. p.k18 = twoPiF;
  150. if (n == 0 && p.dir > 0)
  151. p.dir = 2;
  152. break;
  153. case 7:
  154. case 8:
  155. p.k14 = p.tension;
  156. break;
  157. case 9:
  158. p.k14 = (float) std::fabs ((double) p.tension);
  159. break;
  160. case 11:
  161. case 12:
  162. {
  163. auto k = std::fabs ((double) p.tension) * 0.9;
  164. if (k <= 1.52587890625e-05)
  165. k = 1.52587890625e-05;
  166. const auto a = 1.0 - k;
  167. p.k14 = (float) (1.0 - a * a * a);
  168. p.k18 = (1.0f - p.k14) / p.k14;
  169. p.k1c = p.k18;
  170. if (p.dir > 0)
  171. {
  172. p.k18 = -p.k18;
  173. p.k1c = p.k18 - 1.0f;
  174. }
  175. if (p.type == 12)
  176. {
  177. p.k18 = (float) ((double) p.k18 * 0.5);
  178. p.k1c = (float) ((double) p.k1c * 0.5);
  179. }
  180. break;
  181. }
  182. default: // 2 hold; 10 (spline, not decoded: evaluated as a straight line)
  183. if (p.type == 10)
  184. p.dir = 2;
  185. break;
  186. }
  187. // types 0, 1, 7, 8, 9, 11, 12 with no tension: straight line
  188. if (p.type < 16 && ((0x1b83u >> p.type) & 1u) != 0 && p.tension == 0.0f)
  189. p.dir = 2;
  190. }
  191. }
  192. void normalise (std::vector<Point>& pts)
  193. {
  194. if (pts.empty())
  195. insertPoint (pts, 0.0, 1.0f);
  196. else if (0.0 < pts[0].dx)
  197. insertPoint (pts, 0.0, pts[0].y);
  198. double total = 0.0;
  199. for (const auto& p : pts)
  200. total += p.dx;
  201. if (0.0 < total)
  202. {
  203. const auto f = barLength / total;
  204. if (f != 1.0)
  205. for (auto& p : pts)
  206. p.dx *= f;
  207. }
  208. else
  209. insertPoint (pts, barLength, pts.back().y);
  210. }
  211. // curve of the segment that arrives at `p`, at phase `ph` (0…1)
  212. double shape (const Point& p, double ph) noexcept
  213. {
  214. if (p.dir == 2)
  215. return ph;
  216. std::uint64_t u;
  217. std::memcpy (&u, &ph, 8);
  218. const auto firstHalf = (std::uint32_t) (u >> 32) < 0x3fe00000u;
  219. const auto k14 = (double) p.k14, k18 = (double) p.k18, k1c = (double) p.k1c;
  220. const auto kBits = floatBits (p.k14);
  221. switch (p.type)
  222. {
  223. case 0:
  224. if (kBits == 0)
  225. return ph;
  226. if ((kBits & 0x80000000u) == 0)
  227. return 1.0 - (std::exp ((1.0 - ph) * k1c) - 1.0) * k18;
  228. return (std::exp (ph * k1c) - 1.0) * k18;
  229. case 1:
  230. {
  231. double v;
  232. if (firstHalf)
  233. {
  234. if (kBits == 0)
  235. v = ph * 2.0;
  236. else if ((kBits & 0x80000000u) == 0)
  237. v = 1.0 - (std::exp ((1.0 - ph * 2.0) * k1c) - 1.0) * k18;
  238. else
  239. v = (std::exp (ph * 2.0 * k1c) - 1.0) * k18;
  240. return v * 0.5;
  241. }
  242. if (kBits == 0)
  243. v = (1.0 - ph) * 2.0;
  244. else if ((kBits & 0x80000000u) == 0)
  245. v = 1.0 - (std::exp ((1.0 - (1.0 - ph) * 2.0) * k1c) - 1.0) * k18;
  246. else
  247. v = (std::exp ((1.0 - ph) * 2.0 * k1c) - 1.0) * k18;
  248. return 1.0 - v * 0.5;
  249. }
  250. case 3:
  251. return (double) ((float) roundEven (ph * k14 - k1c) * p.k18);
  252. case 4:
  253. {
  254. auto v = ph * k14 - 0.5;
  255. const auto i = roundEven (v - 0.5);
  256. v = (v - (double) i) * 2.0 - 1.0;
  257. if (p.dir < 0)
  258. {
  259. const auto a = 1.0 - std::fabs (v);
  260. v = (1.0 - a * a * a) * (std::signbit (v) ? -1.0 : 1.0);
  261. }
  262. else
  263. v = v * v * v;
  264. return ((double) i + v * 0.5 + 1.0) * k18;
  265. }
  266. case 5:
  267. return (double) (roundEven (ph * k14 - k1c) & 1);
  268. case 6:
  269. if (p.dir < 0)
  270. return (std::sin ((ph * k14 + 0.75) * k18) + 1.0) * 0.5;
  271. else
  272. {
  273. const auto v = ph * k14 - 0.5;
  274. const auto i = roundEven (v - 0.5);
  275. return std::fabs ((v - (double) i) * 2.0 - 1.0);
  276. }
  277. case 7:
  278. {
  279. const auto c = p.dir > 0 ? 1.0 - ph : ph;
  280. const auto c3 = c * c * c;
  281. return ph - (c3 * c3 - c) * k14;
  282. }
  283. case 8:
  284. if (firstHalf)
  285. {
  286. const auto h = ph * 2.0;
  287. const auto c = p.dir > 0 ? 1.0 - h : h;
  288. const auto c3 = c * c * c;
  289. return (h - (c3 * c3 - c) * k14) * 0.5;
  290. }
  291. else
  292. {
  293. const auto h = (1.0 - ph) * 2.0;
  294. const auto c = p.dir > 0 ? 1.0 - h : h;
  295. const auto c3 = c * c * c;
  296. return 1.0 - (h - (c3 * c3 - c) * k14) * 0.5;
  297. }
  298. case 9:
  299. {
  300. const auto q = ph * (double) 1.57079637f;
  301. const auto c = p.dir < 1 ? 1.0 - std::cos (q) : std::sin (q);
  302. return ph - (ph - c) * k14;
  303. }
  304. case 11:
  305. if (p.dir < 1)
  306. return k18 / (1.0 - k14 * ph) - k1c;
  307. return k18 / (1.0 - k14 * (1.0 - ph)) - k1c;
  308. case 12:
  309. if (firstHalf)
  310. {
  311. if (p.dir < 1)
  312. return k18 / (1.0 - k14 * ph * 2.0) - k1c;
  313. return k18 / (1.0 - k14 * (1.0 - ph * 2.0)) - k1c;
  314. }
  315. else
  316. {
  317. const auto h = (1.0 - ph) * 2.0;
  318. if (p.dir < 1)
  319. return (1.0 - k18 / (1.0 - k14 * h)) + k1c;
  320. return (1.0 - k18 / (1.0 - k14 * (1.0 - h))) + k1c;
  321. }
  322. default:
  323. return 0.0; // 2 = hold (and the undecoded ones)
  324. }
  325. }
  326. // The plugin's envelope player (one per slot kind): loops over the bar, `adv` beats per step
  327. struct Player
  328. {
  329. int idx = 0;
  330. double phase = 0.0, rate = 1.0, start = 0.0, delta = 0.0;
  331. void reset (const std::vector<Point>& p) noexcept
  332. {
  333. idx = 0;
  334. if (p[0].dx == 0.0)
  335. rate = 1.0, phase = 1.0;
  336. else
  337. rate = 1.0 / p[0].dx, phase = 0.0;
  338. start = (double) p[0].y;
  339. delta = 0.0;
  340. }
  341. double step (const std::vector<Point>& p, double& inc, double adv) noexcept
  342. {
  343. phase += inc;
  344. while (atLeastOne (phase))
  345. {
  346. if (rate == 0.0)
  347. phase = adv;
  348. else
  349. phase = (phase - 1.0) / rate;
  350. start = (double) p[(std::size_t) idx].y;
  351. idx = idx < (int) p.size() - 1 ? idx + 1 : 0;
  352. delta = (double) p[(std::size_t) idx].y - start;
  353. const auto d = p[(std::size_t) idx].dx;
  354. if (d <= 0.0)
  355. {
  356. rate = 1.0;
  357. phase += 1.0;
  358. }
  359. else
  360. {
  361. rate = 1.0 / d;
  362. phase *= rate;
  363. }
  364. inc = adv * rate;
  365. }
  366. return start + shape (p[(std::size_t) idx], phase) * delta;
  367. }
  368. template <typename T>
  369. void render (const std::vector<Point>& p, T* out, int n, double adv) noexcept
  370. {
  371. auto inc = adv * rate;
  372. for (int i = 0; i < n; ++i)
  373. out[i] = (T) step (p, inc, adv);
  374. }
  375. void advance (const std::vector<Point>& p, double adv) noexcept
  376. {
  377. auto inc = adv * rate;
  378. step (p, inc, adv);
  379. }
  380. };
  381. // one-pole follower with separate rise/fall coefficients (the plugin's attack/release smoother): x87 arithmetic, the
  382. // running value stays in extended precision within a block and is kept as a double between blocks
  383. struct Follower
  384. {
  385. double up = 0.0, down = 0.0, state = 0.0;
  386. void set (double riseSamples, double fallSamples) noexcept
  387. {
  388. auto coef = [] (double t) { return t > 0.0 ? std::exp (std::log (0.01) / std::max (t, 1.0)) : 0.0; };
  389. up = coef (riseSamples);
  390. down = coef (fallSamples);
  391. }
  392. void run (float* x, int n) noexcept
  393. {
  394. const auto u = (ext) up, d = (ext) down;
  395. auto y = (ext) state;
  396. for (int i = 0; i < n; ++i)
  397. {
  398. const auto v = (ext) x[i];
  399. const auto c = v >= y ? u : d;
  400. y = (y - v) * c + v;
  401. x[i] = (float) y;
  402. }
  403. state = (double) (std::fabs (y) > (ext) 5.96046448e-08f ? y : 0.0L);
  404. }
  405. };
  406. // The x87 part of the plugin's sinc reader (phases of the window cosines and band-limited sines, their recurrence seeds
  407. // and the tap distances). The plugin runs this part with the x87 unit at 64-bit precision rounding toward −∞; on
  408. // x86 with an 80-bit long double LYNX does the same, elsewhere it rounds to nearest (a last-bit difference).
  409. #if (defined(__GNUC__) || defined(__clang__)) && (defined(__x86_64__) || defined(__i386__)) && __LDBL_MANT_DIG__ == 64
  410. #define LYNX_GB_X87 1
  411. #endif
  412. #if LYNX_GB_X87
  413. __attribute__ ((noinline))
  414. #endif
  415. void readerSetup (double fr, double c80, double cutoff, double cw, double cc, float* A, float* B, float* X) noexcept
  416. {
  417. #if LYNX_GB_X87
  418. unsigned short saved = 0, down = 0;
  419. __asm__ volatile ("fnstcw %0" : "=m"(saved));
  420. down = (unsigned short) ((saved & 0xf0ffu) | 0x0700u);
  421. __asm__ volatile ("fldcw %0" : : "m"(down) : "memory");
  422. __asm__ volatile ("" : "+m"(fr), "+m"(c80), "+m"(cutoff), "+m"(cw), "+m"(cc));
  423. const ext pie = 0xC.90FDAA22168C234p-2L; // the x87 π rounded toward −∞
  424. #else
  425. const ext pie = 3.14159265358979323846264338327950288L;
  426. #endif
  427. const ext e0 = (ext) fr * (ext) (-c80) + (ext) 1.5707963267948966;
  428. const ext e1 = e0 + (ext) (-c80);
  429. const ext e2 = (ext) fr * (ext) cutoff;
  430. const ext e3 = e2 + (ext) cutoff;
  431. volatile double d0 = (double) e0, d1 = (double) e1, d2 = (double) e2, d3 = (double) e3;
  432. // FL takes these four sines from IPP's 50-bit vector sine; LYNX uses the C library's, which agrees after the float
  433. // rounding below except at whole-sample positions, where IPP gives 1 − 2⁻⁵³ for the first one (EXEC)
  434. const double s0 = d0 == 1.5707963267948963 ? 0.99999999999999989 : std::sin (d0);
  435. const double s1 = std::sin (d1), s2 = std::sin (d2), s3 = std::sin (d3);
  436. const ext v = (ext) s0 * (ext) cw - (ext) s1;
  437. const ext v2 = v * (ext) cw - (ext) s0;
  438. const ext w = (ext) s2 * (ext) cc - (ext) s3;
  439. const ext w2 = w * (ext) cc - (ext) s2;
  440. const ext x = (ext) fr * pie;
  441. const ext xm = x - pie;
  442. // the sines reach the float lanes through the x87 unit too (rounded with its mode, not SSE's)
  443. volatile ext t0 = s0, t1 = s1, t2 = s2, t3 = s3;
  444. A[0] = (float) w, A[1] = (float) t2, A[2] = (float) v, A[3] = (float) t0;
  445. B[0] = (float) w2, B[1] = (float) t3, B[2] = (float) v2, B[3] = (float) t1;
  446. X[0] = (float) xm, X[1] = (float) x, X[2] = (float) (xm - pie), X[3] = (float) (x + pie);
  447. #if LYNX_GB_X87
  448. __asm__ volatile ("fldcw %0" : : "m"(saved) : "memory");
  449. #endif
  450. }
  451. } // namespace
  452. // ---------------------------------------------------------------------------------------------------------------
  453. // state
  454. std::optional<State> parseState (const std::uint8_t* d, std::size_t size)
  455. {
  456. if (d == nullptr || size < 8)
  457. return std::nullopt;
  458. auto v = (std::int32_t) i32 (d);
  459. if (v >= 0x90004)
  460. return std::nullopt;
  461. if (v > 0xffff)
  462. v = (std::int32_t) ((std::uint32_t) v >> 16);
  463. State s;
  464. s.version = v;
  465. s.params = { 0, 0, 256, 256, 1765, 5000, 0, 0, 0x10000 };
  466. s.options = { 0, 0, 0, 0, 0, 0, 0, 1, 1 };
  467. std::size_t pos = 4;
  468. const auto paramBytes = (std::size_t) (v < 2 ? 0x20 : 0x24);
  469. if (pos + paramBytes > size)
  470. return std::nullopt;
  471. for (std::size_t i = 0; i < paramBytes / 4; ++i)
  472. s.params[i] = i32 (d + pos + 4 * i);
  473. pos += paramBytes;
  474. auto nopt = v < 3 ? 8 : 9;
  475. if (v < 5)
  476. --nopt;
  477. if (pos + (std::size_t) nopt > size)
  478. return std::nullopt;
  479. for (int i = 0; i < nopt; ++i)
  480. s.options[(std::size_t) i] = d[pos + (std::size_t) i];
  481. pos += (std::size_t) nopt;
  482. for (int k = 0; k < 2 * slotsPerKind; ++k)
  483. {
  484. auto& slot = s.slots[(std::size_t) k];
  485. if (pos >= size)
  486. return std::nullopt;
  487. std::size_t len = d[pos++];
  488. if (len == 0xff)
  489. {
  490. if (pos + 4 > size)
  491. return std::nullopt;
  492. len = (std::size_t) (std::uint32_t) i32 (d + pos);
  493. pos += 4;
  494. }
  495. if (pos + len + 15 + 12 > size)
  496. return std::nullopt;
  497. slot.name.assign ((const char*) d + pos, len);
  498. pos += len;
  499. if (v < 4 && slot.name == "Slot " + std::to_string (k % slotsPerKind + 1))
  500. slot.name.clear();
  501. slot.triggerSync = i32 (d + pos);
  502. slot.positionSync = i32 (d + pos + 4);
  503. slot.hold = i32 (d + pos + 8);
  504. slot.link = d[pos + 12] != 0;
  505. slot.keyHeld = d[pos + 13] != 0;
  506. slot.oneShot = d[pos + 14] != 0;
  507. pos += 15;
  508. // envelope stream: kind (3 = map), version, point count, points, five integers
  509. const auto kind = i32 (d + pos);
  510. if (kind != 3)
  511. return std::nullopt;
  512. const auto ev = i32 (d + pos + 4);
  513. pos += 8;
  514. if (ev >= 4)
  515. return std::nullopt; // the plugin skips such a stream entirely (never written by FL)
  516. const auto n = i32 (d + pos);
  517. pos += 4;
  518. const auto pointBytes = (std::size_t) (ev < 2 ? 8 : 16) + (std::size_t) (ev < 1 ? 4 : 8);
  519. if (n < 0 || n > 100000 || pos + (std::size_t) n * pointBytes + 20 > size)
  520. return std::nullopt;
  521. slot.points.resize ((std::size_t) n);
  522. for (auto& p : slot.points)
  523. {
  524. if (ev < 2)
  525. {
  526. float x, y;
  527. std::memcpy (&x, d + pos, 4);
  528. std::memcpy (&y, d + pos + 4, 4);
  529. p.dx = x, p.y = y;
  530. pos += 8;
  531. }
  532. else
  533. {
  534. double x, y;
  535. std::memcpy (&x, d + pos, 8);
  536. std::memcpy (&y, d + pos + 8, 8);
  537. p.dx = x, p.y = (float) y;
  538. pos += 16;
  539. }
  540. std::memcpy (&p.tension, d + pos, 4);
  541. if (ev >= 1)
  542. p.type = d[pos + 4];
  543. pos += ev < 1 ? 4 : 8;
  544. if (! std::isfinite (p.dx))
  545. p.dx = 0.0;
  546. if (std::isnan (p.y))
  547. p.y = 1.0f;
  548. }
  549. pos += 20;
  550. normalise (slot.points);
  551. precompute (slot.points);
  552. slot.flat = true;
  553. for (const auto& p : slot.points)
  554. if (floatBits (p.y) != floatBits (slot.points[0].y))
  555. slot.flat = false;
  556. if ((double) slot.points[0].y != 1.0)
  557. slot.flat = false;
  558. }
  559. return s;
  560. }
  561. std::vector<std::uint8_t> pack (const std::vector<std::uint8_t>& flState, int ppq)
  562. {
  563. std::vector<std::uint8_t> out { 'L', 'X', 'G', 'B', 1, 0, 0, 0, 0, 0, 0, 0 };
  564. std::memcpy (out.data() + 8, &ppq, 4);
  565. out.insert (out.end(), flState.begin(), flState.end());
  566. return out;
  567. }
  568. bool unpack (const std::vector<std::uint8_t>& c, std::vector<std::uint8_t>& flState, int& ppq)
  569. {
  570. if (c.size() < 12 || std::memcmp (c.data(), "LXGB", 4) != 0 || c[4] != 1)
  571. return false;
  572. ppq = i32 (c.data() + 8);
  573. if (ppq <= 0)
  574. ppq = 96;
  575. flState.assign (c.begin() + 12, c.end());
  576. return true;
  577. }
  578. void setPpq (std::vector<std::uint8_t>& c, int ppq)
  579. {
  580. if (c.size() >= 12 && std::memcmp (c.data(), "LXGB", 4) == 0 && ppq > 0)
  581. std::memcpy (c.data() + 8, &ppq, 4);
  582. }
  583. namespace
  584. {
  585. constexpr std::array<int, paramCount> rawMin { 0, 0, 0, 0, 0, 0, -256, 0 };
  586. constexpr std::array<int, paramCount> rawMax { 35, 35, 256, 256, 10000, 10000, 256, 1 };
  587. } // namespace
  588. float paramFromRaw (int index, int raw) noexcept
  589. {
  590. if (index < 0 || index >= paramCount)
  591. return 0.0f;
  592. const auto lo = rawMin[(std::size_t) index], hi = rawMax[(std::size_t) index];
  593. return (float) (std::clamp (raw, lo, hi) - lo) / (float) (hi - lo);
  594. }
  595. int rawFromParam (int index, float value) noexcept
  596. {
  597. if (index < 0 || index >= paramCount)
  598. return 0;
  599. const auto lo = rawMin[(std::size_t) index], hi = rawMax[(std::size_t) index];
  600. const auto v = std::clamp ((double) value, 0.0, 1.0);
  601. return lo + (int) std::lround (v * (double) (hi - lo));
  602. }
  603. // ---------------------------------------------------------------------------------------------------------------
  604. // engine
  605. struct Engine::Impl
  606. {
  607. State st;
  608. bool loaded = false;
  609. int ppq = 96, fs = 44100, maxBlock = 512;
  610. float tempo = 120.0f;
  611. std::array<int, 6> syncTicks {};
  612. // timing (beats per bar of samples etc.)
  613. double spb = 0.0, span = 0.0, step = 0.0;
  614. // slots: 0 time, 1 volume
  615. struct Kind
  616. {
  617. int current = -1, requested = 0, pendingIndex = 0, pendingTime = intMax;
  618. Player player;
  619. double attackComp = 0.0;
  620. };
  621. std::array<Kind, 2> kinds;
  622. // parameters / derived
  623. std::array<int, 9> P {};
  624. float tensionK = 0.0f, tensionInv = 0.0f, tensionLn = 0.0f;
  625. std::array<Follower, 2> volFollow;
  626. double attackSamples = 0.0;
  627. // play state
  628. bool enabled = false, resetPending = false;
  629. double hostTicks = 0.0;
  630. float lastL = 0.0f, lastR = 0.0f;
  631. // buffer (ring of stereo frames with 16 guard frames on each side) and the reader
  632. static constexpr int guard = 16;
  633. std::vector<float> ring; // 2 * (L + 2 guard)
  634. std::uint32_t L = 0, write = 0, dirty = 0; // dirty: frames written since the buffer was last cleared
  635. struct Reader
  636. {
  637. std::uint32_t base = 0;
  638. int taps = 8;
  639. double c80 = 0.0, cw = 0.0; // π/taps, 2cos(π/taps)
  640. double cutoff = pi, cc = -2.0; // per-call cutoff and 2cos(cutoff)
  641. Follower speed; // speed smoothing (high quality)
  642. void setTaps (int n) noexcept
  643. {
  644. if (taps == n)
  645. return;
  646. taps = n;
  647. c80 = pi / (double) n;
  648. cw = std::cos (c80) * 2.0;
  649. }
  650. void setCutoff (double speedRatio) noexcept
  651. {
  652. const auto a = std::fabs (speedRatio);
  653. if (a <= 1.0)
  654. cutoff = pi, cc = -2.0;
  655. else
  656. cutoff = pi / a, cc = std::cos (cutoff) * 2.0;
  657. }
  658. } reader, fadeReader;
  659. // 15-frame dry delay
  660. std::array<float, 30> delayBuf {};
  661. int delayPos = 0;
  662. // time path state
  663. double prevPos = 0.0;
  664. float clickOffL = 0.0f, clickOffR = 0.0f, prevOutL = 0.0f, prevOutR = 0.0f;
  665. float jumpLevel = 0.0f, clickDecay = 0.0f;
  666. int fadeLen = 44, fadeLeft = 0;
  667. double fadeSpan = 0.0;
  668. int quality = 8;
  669. // hold ("repeat") state
  670. int holdMask = 0, holdTime = intMax, holdSync = 5, holdBase = 0, savedBase = 0;
  671. bool frozen = false;
  672. // DC blocker (option byte 4)
  673. ext dcS[2] {}, dcV[2] {};
  674. float dcC2 = 0.0f, dcC1 = 0.96f;
  675. // scratch
  676. std::vector<double> pos, frac, posCopy, wide, sines;
  677. std::vector<std::int64_t> ipos;
  678. std::vector<float> gain, spd, timeL, timeR, oldL, oldR, dryL, dryR;
  679. std::vector<double> cutoffs, ccs;
  680. const Slot& slotOf (int kind, int index) const noexcept
  681. {
  682. return st.slots[(std::size_t) (kind * slotsPerKind + std::clamp (index, 0, slotsPerKind - 1))];
  683. }
  684. const Slot& currentSlot (int kind) const noexcept { return slotOf (kind, std::max (0, kinds[(std::size_t) kind].current)); }
  685. int hostPos() const noexcept { return (int) roundEven (hostTicks); }
  686. // ---- set-up ------------------------------------------------------------------------------------------------
  687. void timing()
  688. {
  689. spb = (double) ((float) (fs * 240) / tempo);
  690. const auto oldSpan = span;
  691. span = spb * 2.0;
  692. step = 4.0 / spb;
  693. // read base relative to the write head: two bars back plus the 15-frame latency
  694. auto d = (std::int64_t) roundEven (span + 0.5) + 15;
  695. if (d < 16)
  696. d = 15;
  697. if (d > (std::int64_t) L - 15)
  698. d = (std::int64_t) L - 15;
  699. const auto newBase = (std::uint32_t) ((std::int64_t) L + (((std::int64_t) write - d) + 2 * (std::int64_t) L) % (std::int64_t) L);
  700. if (enabled && oldSpan > 0.0 && std::fabs (span - oldSpan) > 8.0)
  701. {
  702. fadeReader.base = reader.base % L + L;
  703. fadeSpan = oldSpan;
  704. fadeLeft = fadeLen;
  705. }
  706. reader.base = newBase;
  707. savedBase = (int) newBase;
  708. }
  709. void setFollowers()
  710. {
  711. const auto ms = [] (int raw) { return (double) (float) (std::exp ((double) ((float) raw * 9.99999975e-05f) * std::log (501.0)) - 1.0); };
  712. const auto inv = 1.0 / std::sqrt (2.0);
  713. attackSamples = ms (P[4]) * 0.001 * (double) fs;
  714. const auto comp = attackSamples * (double) (std::int8_t) st.options[5];
  715. kinds[0].attackComp = kinds[1].attackComp = comp;
  716. const auto rel = ms (P[5]) * 0.001 * (double) fs * 2.0;
  717. for (auto& f : volFollow)
  718. f.set (attackSamples * inv, rel * inv);
  719. }
  720. void setTension()
  721. {
  722. const auto mag = (double) (float) std::fabs ((double) ((float) P[6] * 0.00390625f));
  723. auto k = (float) (std::exp (mag * std::log (1001.0)) - 1.0);
  724. k *= (float) (P[6] == 0 ? 0 : (P[6] < 0 ? -1 : 1));
  725. tensionK = 0.0f;
  726. tensionCurve (k, tensionK, tensionInv, tensionLn);
  727. }
  728. void prepare (int sampleRate, int block)
  729. {
  730. fs = sampleRate;
  731. maxBlock = std::max (block, 16);
  732. // ring: three bars at 10 BPM plus margins (FL's size, independent of the block)
  733. const auto d = (double) ((float) (fs * 240) / 10.0f);
  734. const auto size = (std::int64_t) roundEven (d * 2.0 + d) + 16;
  735. L = (std::uint32_t) (size + 32 + 8192);
  736. if (ring.size() != (std::size_t) (L + 2 * guard) * 2)
  737. ring.assign ((std::size_t) (L + 2 * guard) * 2, 0.0f);
  738. else
  739. std::fill (ring.begin(), ring.end(), 0.0f);
  740. write = (std::uint32_t) (size + 16);
  741. dirty = 0;
  742. const auto cap = (std::size_t) maxBlock + 8;
  743. for (auto* v : { &pos, &frac, &posCopy, &cutoffs, &ccs })
  744. v->assign (cap, 0.0);
  745. wide.assign (cap * 4, 0.0);
  746. sines.assign (cap * 4, 0.0);
  747. ipos.assign (cap, 0);
  748. for (auto* v : { &gain, &spd, &timeL, &timeR, &oldL, &oldR, &dryL, &dryR })
  749. v->assign (cap, 0.0f);
  750. reader.taps = 0;
  751. reader.setTaps (8);
  752. fadeReader.taps = 0;
  753. fadeReader.setTaps (16);
  754. reader.setCutoff (1.0);
  755. fadeReader.setCutoff (1.0);
  756. fadeLen = (int) std::max<std::int64_t> (roundEven ((double) fs * 0.001), 1);
  757. jumpLevel = (float) ((double) fs * 0.002);
  758. const auto opt = std::min<int> (st.options[8], 2);
  759. static constexpr float clickMs[3] { 25.0f, 25.0f, 35.0f };
  760. static constexpr float speedMs[3] { 1.0f, 1.0f, 5.0f };
  761. clickDecay = (float) std::exp (std::log (0.01) / ((double) clickMs[opt] * 0.001 * (double) fs));
  762. const auto sm = (double) speedMs[opt] * 0.001 * (double) fs;
  763. reader.speed.set (sm, sm);
  764. dcC2 = (float) (44100.0 / (double) fs * 2.2834999999999997e-05);
  765. span = 0.0;
  766. timing();
  767. setFollowers();
  768. quality = st.options[6] != 0 ? 16 : 8;
  769. }
  770. void load (const State& s, int q)
  771. {
  772. st = s;
  773. ppq = q > 0 ? q : 96;
  774. syncTicks = { 0, ppq / 4, ppq / 2, ppq, ppq * 2, ppq * 4 };
  775. P = s.params;
  776. for (int k = 0; k < 2; ++k)
  777. kinds[(std::size_t) k].requested = std::clamp (P[(std::size_t) k], 0, slotsPerKind - 1);
  778. holdMask = 0; // FL writes the stored value before ProcessParam, so a stored hold does not engage by itself
  779. setTension();
  780. loaded = true;
  781. }
  782. // ---- slots -------------------------------------------------------------------------------------------------
  783. int syncTime (int combo) const noexcept
  784. {
  785. if (combo <= 0 || combo > 5)
  786. return intMax;
  787. const auto period = syncTicks[(std::size_t) combo];
  788. return ((hostPos() + period - 1) / period) * period;
  789. }
  790. void switchSlot (int kind, int index, bool cascade)
  791. {
  792. auto& K = kinds[(std::size_t) kind];
  793. const auto oldLink = K.current >= 0 && currentSlot (kind).link;
  794. if (kind == 1 && kinds[0].current >= 0 && currentSlot (0).link)
  795. {
  796. index = kinds[0].current;
  797. K.pendingTime = intMax;
  798. }
  799. K.current = std::clamp (index, 0, slotsPerKind - 1);
  800. const auto& slot = currentSlot (kind);
  801. K.player.reset (slot.points);
  802. const auto bit = 2 << kind;
  803. if (slot.hold < 1)
  804. {
  805. const auto before = holdMask;
  806. holdMask &= ~bit;
  807. if (before > 0 && holdMask == 0)
  808. holdTime = holdNow;
  809. }
  810. else
  811. {
  812. holdMask |= bit;
  813. if (holdTime == intMax)
  814. holdTime = slot.hold == 1 ? holdNow : hostPos() + syncTicks[(std::size_t) holdSync];
  815. }
  816. double phase = 0.0;
  817. if (slot.positionSync > 0 && slot.positionSync <= 5)
  818. {
  819. const auto period = syncTicks[(std::size_t) slot.positionSync];
  820. const auto p = (double) hostPos();
  821. auto t = p;
  822. if (holdMask > 0 && holdTime != intMax)
  823. {
  824. t = 0.0;
  825. if (holdTime != holdNow)
  826. t = (p + (double) (ppq << 8)) - (double) holdTime;
  827. }
  828. if (0.0 < t)
  829. {
  830. const auto whole = (std::int64_t) (t / (double) period);
  831. phase = (t - (double) (whole * period)) / (double) ppq;
  832. }
  833. }
  834. K.player.advance (slot.points, phase + K.attackComp * step);
  835. if (slot.oneShot)
  836. {
  837. K.pendingIndex = 0;
  838. K.pendingTime = hostPos() + syncTicks[5];
  839. }
  840. if (cascade && (slot.link || oldLink))
  841. switchSlot (1, kinds[1].requested, false);
  842. }
  843. void requestSlot (int kind, int index)
  844. {
  845. auto& K = kinds[(std::size_t) kind];
  846. index = std::clamp (index, 0, slotsPerKind - 1);
  847. if (K.requested == index)
  848. return;
  849. K.requested = index;
  850. if (! enabled)
  851. return;
  852. if (kind == 1 && kinds[0].current >= 0 && currentSlot (0).link)
  853. return;
  854. const auto t = syncTime (slotOf (kind, index).triggerSync);
  855. K.pendingTime = t;
  856. if (t == intMax)
  857. switchSlot (kind, index, true);
  858. else
  859. K.pendingIndex = K.requested;
  860. }
  861. void resync()
  862. {
  863. if (frozen)
  864. reader.base = (std::uint32_t) savedBase;
  865. frozen = false;
  866. holdTime = intMax;
  867. if (holdMask > 0)
  868. holdTime = hostPos() + syncTicks[(std::size_t) holdSync];
  869. kinds[0].pendingTime = kinds[1].pendingTime = intMax;
  870. switchSlot (0, kinds[0].requested, true);
  871. switchSlot (1, kinds[1].requested, true);
  872. }
  873. void start (double ticks)
  874. {
  875. hostTicks = ticks;
  876. if (enabled)
  877. return;
  878. enabled = true;
  879. dcS[0] = dcS[1] = dcV[0] = dcV[1] = 0.0L;
  880. clearRing();
  881. delayBuf.fill (0.0f);
  882. resetPending = true;
  883. prevPos = 0.0;
  884. reader.speed.state = 1.0;
  885. clickOffL = clickOffR = prevOutL = prevOutR = 0.0f;
  886. lastL = lastR = 0.0f;
  887. fadeLeft = 0;
  888. resync();
  889. }
  890. void stop()
  891. {
  892. if (! enabled)
  893. return;
  894. enabled = false;
  895. clearRing();
  896. fadeLeft = 0;
  897. holdMask &= 1;
  898. holdTime = intMax;
  899. for (auto& K : kinds)
  900. K.current = -1, K.pendingTime = intMax;
  901. }
  902. void setParam (int index, int raw)
  903. {
  904. if (index < 0 || index > 8)
  905. return;
  906. const auto old = P[(std::size_t) index];
  907. P[(std::size_t) index] = raw;
  908. if (index < 2)
  909. requestSlot (index, raw);
  910. else if (index == 4 || index == 5)
  911. setFollowers();
  912. else if (index == 6)
  913. setTension();
  914. else if (index == 7)
  915. {
  916. if ((0 < old) != (0 < raw))
  917. {
  918. holdMask = (holdMask & ~1) | (raw > 0 ? 1 : 0);
  919. if (holdTime == intMax)
  920. holdTime = syncTime (holdSync);
  921. }
  922. }
  923. }
  924. // ---- buffer --------------------------------------------------------------------------------------------------
  925. float* frame (std::uint32_t i) noexcept { return ring.data() + 2 * ((std::size_t) i + guard); }
  926. // the plugin zeroes the whole buffer; only the part written since the last clear can be non-zero
  927. void clearRing() noexcept
  928. {
  929. if (ring.empty())
  930. return;
  931. if (dirty >= L)
  932. std::fill (ring.begin(), ring.end(), 0.0f);
  933. else if (dirty > 0)
  934. {
  935. const auto first = (write + L - dirty) % L;
  936. const auto tail = std::min (dirty, L - first);
  937. std::fill (frame (first), frame (first) + 2 * (std::size_t) tail, 0.0f);
  938. std::fill (frame (0), frame (0) + 2 * (std::size_t) (dirty - tail), 0.0f);
  939. std::fill (ring.begin(), ring.begin() + 2 * guard, 0.0f);
  940. std::fill (ring.end() - 2 * guard, ring.end(), 0.0f);
  941. }
  942. dirty = 0;
  943. }
  944. void writeRing (const float* l, const float* r, int n) noexcept
  945. {
  946. for (int i = 0; i < n; ++i)
  947. {
  948. auto* f = frame (write);
  949. f[0] = l[i], f[1] = r[i];
  950. if (++write >= L)
  951. write = 0;
  952. }
  953. dirty = std::min (L, dirty + (std::uint32_t) n);
  954. // guard frames: the first frames repeated after the end, the last ones before the start
  955. std::memcpy (frame (L), frame (0), sizeof (float) * 2 * guard);
  956. std::memcpy (ring.data(), frame (L - guard), sizeof (float) * 2 * guard);
  957. }
  958. // windowed-sinc read of one frame at ring index `idx` + `fr` (0 ≤ fr < 1) with the reader's taps and cutoff
  959. void kernel (const Reader& R, const float* at, double fr, float& outL, float& outR) noexcept
  960. {
  961. fr = fr < 1e-25 ? 1e-25 : fr;
  962. float A[4], B[4], X[4];
  963. readerSetup (fr, R.c80, R.cutoff, R.cw, R.cc, A, B, X);
  964. const float C[4] { (float) R.cc, (float) R.cc, (float) R.cw, (float) R.cw };
  965. #if LYNX_GB_SSE
  966. __m128 a = _mm_loadu_ps (A), b = _mm_loadu_ps (B), xx = _mm_loadu_ps (X), c = _mm_loadu_ps (C);
  967. const __m128 w1 = _mm_setr_ps (0.36f, 0.36f, 0.0f, 0.0f), wq = _mm_setr_ps (0.64f, 0.64f, 1.0f, 1.0f);
  968. const __m128 s = _mm_setr_ps (-twoPiF, twoPiF, -twoPiF, twoPiF);
  969. __m128 acc = _mm_setzero_ps(), h = _mm_setzero_ps();
  970. const float* fwd = at + 2;
  971. const float* bwd = at - 2;
  972. for (int k = 0; k < R.taps / 2; ++k)
  973. {
  974. auto r = _mm_rcp_ps (xx);
  975. const auto t = _mm_mul_ps (_mm_mul_ps (xx, r), r);
  976. auto a0 = a;
  977. a = b;
  978. b = _mm_sub_ps (_mm_mul_ps (b, c), a0);
  979. r = _mm_sub_ps (_mm_add_ps (r, r), t);
  980. h = _mm_movehl_ps (h, a0);
  981. auto win = _mm_add_ps (_mm_add_ps (_mm_mul_ps (_mm_mul_ps (wq, h), h), h), w1);
  982. xx = _mm_add_ps (xx, s);
  983. auto q = _mm_mul_ps (_mm_mul_ps (a0, r), win);
  984. const auto rhi = _mm_movehl_ps (r, r);
  985. const auto f14 = _mm_loadu_ps (fwd), f15 = _mm_loadu_ps (bwd);
  986. q = _mm_shuffle_ps (q, q, 0x50);
  987. const auto F1 = _mm_shuffle_ps (f14, f15, 0xe4), F2 = _mm_shuffle_ps (f14, f15, 0x4e);
  988. acc = _mm_add_ps (acc, _mm_mul_ps (q, F1));
  989. h = _mm_movehl_ps (h, a);
  990. a0 = a;
  991. a = b;
  992. b = _mm_sub_ps (_mm_mul_ps (b, c), a0);
  993. win = _mm_add_ps (_mm_add_ps (_mm_mul_ps (_mm_mul_ps (wq, h), h), h), w1);
  994. q = _mm_mul_ps (_mm_mul_ps (a0, rhi), win);
  995. q = _mm_shuffle_ps (q, q, 0x50);
  996. acc = _mm_add_ps (acc, _mm_mul_ps (q, F2));
  997. fwd += 4;
  998. bwd -= 4;
  999. }
  1000. const auto sum = _mm_mul_ps (_mm_add_ps (_mm_movehl_ps (acc, acc), acc), _mm_setr_ps (0.5f, 0.5f, 1.0f, 1.0f));
  1001. float o[4];
  1002. _mm_storeu_ps (o, sum);
  1003. outL = o[0], outR = o[1];
  1004. #else
  1005. float a[4], b[4], xx[4], acc[4] {}, h0 = 0.0f, h1 = 0.0f;
  1006. std::memcpy (a, A, 16), std::memcpy (b, B, 16), std::memcpy (xx, X, 16);
  1007. const float s[4] { -twoPiF, twoPiF, -twoPiF, twoPiF };
  1008. const float* fwd = at + 2;
  1009. const float* bwd = at - 2;
  1010. for (int k = 0; k < R.taps / 2; ++k)
  1011. {
  1012. float r[4], a0[4];
  1013. for (int j = 0; j < 4; ++j)
  1014. {
  1015. const auto rr = 1.0f / xx[j];
  1016. r[j] = (rr + rr) - (xx[j] * rr) * rr;
  1017. a0[j] = a[j];
  1018. a[j] = b[j];
  1019. b[j] = b[j] * C[j] - a0[j];
  1020. xx[j] += s[j];
  1021. }
  1022. h0 = a0[2], h1 = a0[3];
  1023. auto q0 = (a0[0] * r[0]) * (((0.64f * h0) * h0 + h0) + 0.36f);
  1024. auto q1 = (a0[1] * r[1]) * (((0.64f * h1) * h1 + h1) + 0.36f);
  1025. acc[0] += q0 * fwd[0], acc[1] += q0 * fwd[1], acc[2] += q1 * bwd[2], acc[3] += q1 * bwd[3];
  1026. float a1[4];
  1027. for (int j = 0; j < 4; ++j)
  1028. {
  1029. a1[j] = a[j];
  1030. a[j] = b[j];
  1031. b[j] = b[j] * C[j] - a1[j];
  1032. }
  1033. h0 = a1[2], h1 = a1[3];
  1034. q0 = (a1[0] * r[2]) * (((0.64f * h0) * h0 + h0) + 0.36f);
  1035. q1 = (a1[1] * r[3]) * (((0.64f * h1) * h1 + h1) + 0.36f);
  1036. acc[0] += q0 * fwd[2], acc[1] += q0 * fwd[3], acc[2] += q1 * bwd[0], acc[3] += q1 * bwd[1];
  1037. fwd += 4;
  1038. bwd -= 4;
  1039. }
  1040. outL = (acc[2] + acc[0]) * 0.5f;
  1041. outR = (acc[3] + acc[1]) * 0.5f;
  1042. #endif
  1043. }
  1044. // positions (samples, relative to the reader's moving base) → output frames
  1045. void read (Reader& R, const double* p, float* outL, float* outR, int n, bool perSampleCutoff) noexcept
  1046. {
  1047. for (int i = 0; i < n; ++i)
  1048. {
  1049. const auto ip = (std::int64_t) p[i];
  1050. const auto fr = p[i] - (double) ip;
  1051. const auto idx = (std::uint32_t) (((std::uint64_t) R.base + (std::uint64_t) ip) % (std::uint64_t) L);
  1052. ++R.base;
  1053. if (perSampleCutoff)
  1054. R.cutoff = cutoffs[(std::size_t) i], R.cc = ccs[(std::size_t) i];
  1055. kernel (R, frame (idx), fr, outL[i], outR[i]);
  1056. }
  1057. }
  1058. // ---- block ---------------------------------------------------------------------------------------------------
  1059. void process (float* l, float* r, int n, double ticks) noexcept
  1060. {
  1061. hostTicks = ticks;
  1062. if (! enabled)
  1063. {
  1064. if (lastL != 0.0f || lastR != 0.0f)
  1065. {
  1066. const auto last = (double) std::max (n - 1, 1);
  1067. for (int i = 0; i < n; ++i)
  1068. {
  1069. const auto w = (float) ((std::cos ((double) i * pi / last) + 1.0) * 0.5);
  1070. l[i] = (float) ((double) l[i] * (1.0 - (double) w) + (double) (lastL * w));
  1071. r[i] = (float) ((double) r[i] * (1.0 - (double) w) + (double) (lastR * w));
  1072. }
  1073. lastL = lastR = 0.0f;
  1074. }
  1075. return;
  1076. }
  1077. while (n > maxBlock)
  1078. {
  1079. block (l, r, maxBlock);
  1080. l += maxBlock, r += maxBlock, n -= maxBlock;
  1081. hostTicks += (double) maxBlock * (double) tempo / 60.0 * (double) ppq / (double) fs;
  1082. }
  1083. block (l, r, n);
  1084. }
  1085. void block (float* l, float* r, int n) noexcept
  1086. {
  1087. if (n <= 0)
  1088. return;
  1089. const auto now = (double) hostPos();
  1090. for (int k = 0; k < 2; ++k)
  1091. if ((double) kinds[(std::size_t) k].pendingTime <= now)
  1092. {
  1093. kinds[(std::size_t) k].pendingTime = intMax;
  1094. switchSlot (k, kinds[(std::size_t) k].pendingIndex, true);
  1095. }
  1096. // hold / repeat
  1097. bool holdStart = false;
  1098. const auto declick = st.options[8] != 0;
  1099. if ((double) holdTime <= now)
  1100. {
  1101. if (holdMask < 1)
  1102. {
  1103. if (frozen)
  1104. {
  1105. frozen = false;
  1106. reader.base = (std::uint32_t) savedBase;
  1107. holdTime = intMax;
  1108. holdStart = declick;
  1109. }
  1110. }
  1111. else
  1112. {
  1113. if (! frozen)
  1114. {
  1115. savedBase = (int) reader.base;
  1116. const auto len = (int) roundEven (spb * (double) syncTicks[(std::size_t) holdSync] / (double) (ppq << 2));
  1117. holdBase = (int) (reader.base + L) - len;
  1118. frozen = true;
  1119. }
  1120. reader.base = (std::uint32_t) holdBase;
  1121. holdTime = (int) roundEven (now) + syncTicks[(std::size_t) holdSync];
  1122. holdStart = declick;
  1123. }
  1124. }
  1125. // the dry path is delayed by 15 frames; the input also feeds the buffer
  1126. if (! frozen)
  1127. writeRing (l, r, n);
  1128. for (int i = 0; i < n; ++i)
  1129. {
  1130. auto* d = delayBuf.data() + 2 * delayPos;
  1131. dryL[(std::size_t) i] = d[0], dryR[(std::size_t) i] = d[1];
  1132. d[0] = l[i], d[1] = r[i];
  1133. if (++delayPos >= 15)
  1134. delayPos = 0;
  1135. }
  1136. reader.base = reader.base % L + L;
  1137. const auto& tslot = currentSlot (0);
  1138. const bool timeOn = (! tslot.flat && P[2] != 0) || frozen || clickOffL != 0.0f || clickOffR != 0.0f || holdStart;
  1139. float* outL = dryL.data();
  1140. float* outR = dryR.data();
  1141. if (timeOn)
  1142. {
  1143. auto& K = kinds[0];
  1144. K.player.render (tslot.points, pos.data(), n, step);
  1145. const auto fading = fadeLeft > 0;
  1146. if (fading)
  1147. std::copy (pos.begin(), pos.begin() + n, posCopy.begin());
  1148. for (int i = 0; i < n; ++i)
  1149. pos[(std::size_t) i] *= span;
  1150. if (resetPending)
  1151. prevPos = pos[0];
  1152. bool perSample = false;
  1153. int taps = 8;
  1154. float* dspeed = spd.data();
  1155. if (quality < 9)
  1156. {
  1157. if (declick)
  1158. {
  1159. for (int i = 0; i < n; ++i)
  1160. {
  1161. const auto pv = pos[(std::size_t) i];
  1162. dspeed[i] = (float) (pv - prevPos);
  1163. prevPos = pv;
  1164. }
  1165. for (int i = 0; i < n; ++i)
  1166. dspeed[i] = std::fabs (dspeed[i] + 1.0f);
  1167. }
  1168. prevPos = pos[(std::size_t) n - 1];
  1169. reader.setCutoff (1.0);
  1170. }
  1171. else
  1172. {
  1173. for (int i = 0; i < n; ++i)
  1174. {
  1175. const auto pv = pos[(std::size_t) i];
  1176. gain[(std::size_t) i] = (float) (pv - prevPos);
  1177. prevPos = pv;
  1178. }
  1179. for (int i = 0; i < n; ++i)
  1180. gain[(std::size_t) i] = std::fabs (gain[(std::size_t) i] + 1.0f);
  1181. if (declick)
  1182. std::copy (gain.begin(), gain.begin() + n, spd.begin());
  1183. reader.speed.run (gain.data(), n);
  1184. auto mn = gain[0], mx = gain[0];
  1185. for (int i = 1; i < n; ++i)
  1186. mn = std::min (mn, gain[(std::size_t) i]), mx = std::max (mx, gain[(std::size_t) i]);
  1187. const auto eps = 5.96046448e-08f;
  1188. perSample = eps + 1.0f < mx;
  1189. if (! perSample)
  1190. {
  1191. reader.setCutoff (1.0);
  1192. taps = 1.0f - eps <= mn ? 8 : 16;
  1193. }
  1194. else
  1195. {
  1196. taps = 16;
  1197. for (int i = 0; i < n; ++i)
  1198. {
  1199. const auto sp = (double) std::max (gain[(std::size_t) i], 1.0f);
  1200. cutoffs[(std::size_t) i] = pi / sp;
  1201. ccs[(std::size_t) i] = std::cos (cutoffs[(std::size_t) i]) * 2.0;
  1202. }
  1203. }
  1204. }
  1205. reader.setTaps (taps);
  1206. read (reader, pos.data(), timeL.data(), timeR.data(), n, perSample);
  1207. if (fading)
  1208. {
  1209. for (int i = 0; i < n; ++i)
  1210. posCopy[(std::size_t) i] *= fadeSpan;
  1211. read (fadeReader, posCopy.data(), oldL.data(), oldR.data(), n, perSample);
  1212. const auto len = std::min (fadeLen, n);
  1213. for (int i = 0; i < n; ++i)
  1214. {
  1215. auto w = (double) i / (double) len;
  1216. w = w < 0.0 ? 0.0 : (w > 1.0 ? 1.0 : w);
  1217. const auto o = 1.0 - w;
  1218. timeL[(std::size_t) i] = (float) ((double) timeL[(std::size_t) i] * w + (double) oldL[(std::size_t) i] * o);
  1219. timeR[(std::size_t) i] = (float) ((double) timeR[(std::size_t) i] * w + (double) oldR[(std::size_t) i] * o);
  1220. }
  1221. fadeLeft = 0;
  1222. }
  1223. if (declick)
  1224. {
  1225. if (holdStart)
  1226. dspeed[0] = jumpLevel * 2.0f;
  1227. const auto lim = (std::int32_t) floatBits (jumpLevel);
  1228. for (int i = 0; i < n; ++i)
  1229. {
  1230. if (lim < (std::int32_t) floatBits (dspeed[i]))
  1231. {
  1232. clickOffL = (clickOffL + prevOutL) - timeL[(std::size_t) i];
  1233. clickOffR = (clickOffR + prevOutR) - timeR[(std::size_t) i];
  1234. }
  1235. prevOutL = timeL[(std::size_t) i];
  1236. prevOutR = timeR[(std::size_t) i];
  1237. timeL[(std::size_t) i] += clickOffL;
  1238. timeR[(std::size_t) i] += clickOffR;
  1239. clickOffL *= clickDecay;
  1240. clickOffR *= clickDecay;
  1241. }
  1242. const auto flush = [] (float& v) { if (floatBits (v) * 2u < floatBits (5.96046448e-08f) * 2u) v = 0.0f; };
  1243. flush (clickOffL);
  1244. flush (clickOffR);
  1245. }
  1246. if (P[2] != 256)
  1247. {
  1248. const auto m = (float) P[2] * 0.00390625f;
  1249. for (int i = 0; i < n; ++i)
  1250. {
  1251. timeL[(std::size_t) i] = timeL[(std::size_t) i] * m + dryL[(std::size_t) i] * (1.0f - m);
  1252. timeR[(std::size_t) i] = timeR[(std::size_t) i] * m + dryR[(std::size_t) i] * (1.0f - m);
  1253. }
  1254. }
  1255. outL = timeL.data();
  1256. outR = timeR.data();
  1257. }
  1258. else
  1259. {
  1260. kinds[0].player.advance (tslot.points, (double) n * step);
  1261. prevPos = span;
  1262. reader.base += (std::uint32_t) n;
  1263. fadeLeft = 0;
  1264. }
  1265. // volume
  1266. const auto& vslot = currentSlot (1);
  1267. auto* g = gain.data();
  1268. if (! vslot.flat && P[3] != 0)
  1269. {
  1270. kinds[1].player.render (vslot.points, g, n, step);
  1271. if (tensionK != 0.0f)
  1272. {
  1273. const auto rising = (floatBits (tensionK) & 0x80000000u) == 0;
  1274. for (int i = 0; i < n; ++i)
  1275. {
  1276. auto x = g[i];
  1277. if (rising)
  1278. x = 1.0f - x;
  1279. x *= tensionLn;
  1280. x = exp11 (x) + -1.0f;
  1281. x *= tensionInv;
  1282. if (rising)
  1283. x = 1.0f - x;
  1284. g[i] = x;
  1285. }
  1286. }
  1287. if (P[3] != 256)
  1288. {
  1289. const auto m = (float) P[3] * 0.00390625f;
  1290. for (int i = 0; i < n; ++i)
  1291. g[i] = g[i] * m + (1.0f - m);
  1292. }
  1293. }
  1294. else
  1295. {
  1296. kinds[1].player.advance (vslot.points, (double) n * step);
  1297. std::fill (g, g + n, 1.0f);
  1298. }
  1299. if (resetPending)
  1300. for (auto& f : volFollow)
  1301. f.state = (double) g[0];
  1302. for (auto& f : volFollow)
  1303. f.run (g, n);
  1304. for (int i = 0; i < n; ++i)
  1305. {
  1306. l[i] = g[i] * outL[i];
  1307. r[i] = g[i] * outR[i];
  1308. }
  1309. if (st.options[4] != 0)
  1310. for (int i = 0; i < n; ++i)
  1311. {
  1312. ext x = (ext) l[i];
  1313. dcV[0] = dcV[0] + (x - dcS[0]) * (ext) dcC2;
  1314. dcS[0] = dcS[0] + dcV[0];
  1315. dcV[0] = dcV[0] * (ext) dcC1;
  1316. l[i] = (float) (x - dcS[0]);
  1317. x = (ext) r[i];
  1318. dcV[1] = dcV[1] + (x - dcS[1]) * (ext) dcC2;
  1319. dcS[1] = dcS[1] + dcV[1];
  1320. dcV[1] = dcV[1] * (ext) dcC1;
  1321. r[i] = (float) (x - dcS[1]);
  1322. }
  1323. if (st.options[4] != 0) // states kept as doubles between blocks, tiny ones flushed to zero
  1324. {
  1325. const auto keep = [] (ext v) { return (ext) (double) (std::fabs (v) <= (ext) 5.96046448e-08f ? 0.0L : v); };
  1326. for (int c = 0; c < 2; ++c)
  1327. dcV[c] = keep (dcV[c]), dcS[c] = keep (dcS[c]);
  1328. }
  1329. lastL = l[n - 1];
  1330. lastR = r[n - 1];
  1331. resetPending = false;
  1332. }
  1333. };
  1334. Engine::Engine() : impl (std::make_unique<Impl>()) {}
  1335. Engine::~Engine() = default;
  1336. bool Engine::load (const State& state, int ppq)
  1337. {
  1338. impl->load (state, ppq);
  1339. return true;
  1340. }
  1341. void Engine::prepare (int sampleRate, int maxBlock) { impl->prepare (sampleRate, maxBlock); }
  1342. void Engine::setTempo (float bpm)
  1343. {
  1344. if (bpm <= 0.0f || bpm == impl->tempo)
  1345. return;
  1346. impl->tempo = bpm;
  1347. impl->timing();
  1348. }
  1349. void Engine::setParam (int index, int raw) { impl->setParam (index, raw); }
  1350. void Engine::start (double ticks) { impl->start (ticks); }
  1351. void Engine::stop() { impl->stop(); }
  1352. bool Engine::playing() const noexcept { return impl->enabled; }
  1353. void Engine::jump (double ticks)
  1354. {
  1355. impl->hostTicks = ticks;
  1356. if (impl->enabled)
  1357. impl->resync();
  1358. }
  1359. void Engine::process (float* left, float* right, int n, double ticks) noexcept { impl->process (left, right, n, ticks); }
  1360. // ---------------------------------------------------------------------------------------------------------------
  1361. // LYNX effect wrapper
  1362. std::optional<EffectSlot> slotFromFl (const std::vector<std::uint8_t>& flState, int ppq)
  1363. {
  1364. const auto s = parseState (flState.data(), flState.size());
  1365. if (! s)
  1366. return std::nullopt;
  1367. EffectSlot slot;
  1368. slot.kind = EffectKind::grossBeat;
  1369. for (int i = 0; i < paramCount; ++i)
  1370. slot.params[(std::size_t) i] = paramFromRaw (i, s->params[(std::size_t) i]);
  1371. slot.state = pack (flState, ppq);
  1372. return slot;
  1373. }
  1374. std::vector<std::string> slotNames (const std::vector<std::uint8_t>& container, bool volume)
  1375. {
  1376. std::vector<std::uint8_t> fl;
  1377. int ppq = 96;
  1378. std::vector<std::string> names;
  1379. if (! unpack (container, fl, ppq))
  1380. return names;
  1381. const auto s = parseState (fl.data(), fl.size());
  1382. if (! s)
  1383. return names;
  1384. for (int i = 0; i < slotsPerKind; ++i)
  1385. names.push_back (s->slots[(std::size_t) ((volume ? slotsPerKind : 0) + i)].name);
  1386. return names;
  1387. }
  1388. namespace
  1389. {
  1390. class GrossBeatEffect final : public Effect
  1391. {
  1392. public:
  1393. explicit GrossBeatEffect (const std::vector<std::uint8_t>& container)
  1394. {
  1395. std::vector<std::uint8_t> fl;
  1396. int ppq = 96;
  1397. if (unpack (container, fl, ppq))
  1398. if (auto s = parseState (fl.data(), fl.size()))
  1399. {
  1400. state = *s;
  1401. flPpq = ppq;
  1402. ok = true;
  1403. engine.load (state, flPpq);
  1404. raw = state.params;
  1405. }
  1406. }
  1407. void prepare (double sr) noexcept override
  1408. {
  1409. sampleRate = (int) std::lround (sr);
  1410. if (ok)
  1411. engine.prepare (sampleRate, 4096);
  1412. lastTicks = -1.0;
  1413. }
  1414. void reset() noexcept override
  1415. {
  1416. if (ok)
  1417. engine.stop();
  1418. lastTicks = -1.0;
  1419. }
  1420. void setSongPosition (double ticks) noexcept override { songTicks = ticks; }
  1421. void process (float* l, float* r, int n, const EffectParams& p, double bpm) noexcept override
  1422. {
  1423. if (! ok)
  1424. return;
  1425. for (int i = 0; i < paramCount; ++i)
  1426. {
  1427. const auto v = rawFromParam (i, p[(std::size_t) i]);
  1428. if (v != raw[(std::size_t) i])
  1429. {
  1430. raw[(std::size_t) i] = v;
  1431. engine.setParam (i, v);
  1432. }
  1433. }
  1434. engine.setTempo ((float) bpm);
  1435. const auto flTicks = songTicks / (double) ppq * (double) flPpq;
  1436. // LYNX's transport: a moving song position is FL's "playing"; a position that does not follow the previous
  1437. // block is a jump (FL re-syncs the slots)
  1438. const auto moving = lastTicks < 0.0 || songTicks != lastTicks;
  1439. if (! moving)
  1440. engine.stop();
  1441. else if (! engine.playing())
  1442. engine.start (flTicks);
  1443. else if (std::fabs (songTicks - expected) > 1.0)
  1444. engine.jump (flTicks);
  1445. lastTicks = songTicks;
  1446. expected = songTicks + (double) n * bpm / 60.0 * (double) ppq / (double) sampleRate;
  1447. engine.process (l, r, n, flTicks);
  1448. }
  1449. private:
  1450. State state;
  1451. Engine engine;
  1452. bool ok = false;
  1453. int flPpq = 96, sampleRate = 44100;
  1454. std::array<int, 9> raw {};
  1455. double songTicks = 0.0, lastTicks = -1.0, expected = 0.0;
  1456. };
  1457. } // namespace
  1458. std::unique_ptr<Effect> make (const std::vector<std::uint8_t>& container) { return std::make_unique<GrossBeatEffect> (container); }
  1459. } // namespace lynx::grossbeat