MiniSynth.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  1. #include "core/MiniSynth.h"
  2. #include <algorithm>
  3. #include <array>
  4. #include <atomic>
  5. #include <cmath>
  6. #include <cstdint>
  7. #include <cstring>
  8. #include <fstream>
  9. #include <iterator>
  10. #include <limits>
  11. #include <map>
  12. #include <mutex>
  13. #include <optional>
  14. #include <vector>
  15. // 1:1 port of our round-41 reference model (r41/py/msmodel.py). The model emulates the DLL's float32 arithmetic by
  16. // rounding every single-precision result and uses Python floats (doubles) where the DLL computes in double. This file
  17. // keeps those types — `float` where the model holds float32, `double` + an explicit (float) where it rounds a double —
  18. // and the operation order of every expression, so fusing a·b + c into one FMA would change the results: contraction
  19. // stays off.
  20. #if defined(__clang__)
  21. #pragma clang fp contract(off)
  22. #elif defined(__GNUC__)
  23. #pragma GCC optimize ("fp-contract=off")
  24. #endif
  25. namespace lynx
  26. {
  27. namespace
  28. {
  29. constexpr int maxChunk = 512; // engine buffer of 512 samples per call (§2.2)
  30. constexpr int blockLen = 32; // control block (§2.3)
  31. constexpr int voiceCount = 99; // §3.1
  32. constexpr int paramCount = 43;
  33. constexpr int tableCount = 1024, tableLen = 2048;
  34. // cvttss2si / cvttsd2si: truncation toward zero; out of range or NaN → INT_MIN
  35. int i32 (double x) noexcept
  36. {
  37. if (! (x == x) || x >= 2147483648.0 || x < -2147483648.0)
  38. return std::numeric_limits<int>::min();
  39. return (int) x;
  40. }
  41. // (int)(long long)x: truncation to 64 bits, low 32 bits kept
  42. std::int32_t i32via64 (double x) noexcept
  43. {
  44. if (! (x == x) || x >= 9.2e18 || x <= -9.2e18)
  45. return 0;
  46. return (std::int32_t) (std::uint32_t) (std::uint64_t) (long long) x;
  47. }
  48. std::int32_t add32 (std::int32_t a, std::int32_t b) noexcept { return (std::int32_t) ((std::uint32_t) a + (std::uint32_t) b); }
  49. // the C runtime's powf as the model computes it: the exact power, rounded to float
  50. float powf32 (double x, double y) noexcept { return (float) std::pow (x, y); }
  51. // ------------------------------------------------------------------------------------------------------- state
  52. constexpr float defaults[paramCount] = { 0.375f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
  53. 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.0f, 0.0f, 0.25f, 0.5f, 0.0f,
  54. 1.0f, 1.0f, 0.07f, 0.0f, 0.0f, 0.0f, 0.0f, 0.7f, 0.5f, 1.0f, 0.5f,
  55. 0.0f, 0.25f, 0.5f, 0.5f, 0.0f, 0.11222222f, 0.4f, 0.1f, 1.0f, 0.5f };
  56. std::uint32_t rd32 (const std::uint8_t* p) noexcept { return (std::uint32_t) p[0] | (std::uint32_t) p[1] << 8 | (std::uint32_t) p[2] << 16 | (std::uint32_t) p[3] << 24; }
  57. // "SSLF" + u32 size, then the .flms body: signature (99 46 4C 53 0D 0A 1A 0A; one factory preset has "\x99FLM"),
  58. // "HEAD" + size (u16 1, u16 1, u16 L, L UTF-16 characters of the preset name), "DATA" + size, "0rev" + floats. Like the
  59. // plugin, only the name length and the DATA size are read (an optional 60-byte "CcnK…FPCh" header is skipped); parameter
  60. // i is set while the DATA size minus 4·(i + 1) is still above 3 (§1.1); a value is clamped to 0…1 (NaN is read as 0
  61. // here).
  62. std::optional<std::array<float, paramCount>> parseState (const std::vector<std::uint8_t>& d, std::size_t* floatsAt = nullptr)
  63. {
  64. if (d.size() < 8 || std::memcmp (d.data(), "SSLF", 4) != 0)
  65. return std::nullopt;
  66. std::size_t body = 8;
  67. if (d.size() > body + 60 && std::memcmp (d.data() + body, "CcnK", 4) == 0 && std::memcmp (d.data() + body + 8, "FPCh", 4) == 0)
  68. body += 60;
  69. if (d.size() < body + 0x16)
  70. return std::nullopt;
  71. const std::size_t nameLen = (std::size_t) (d[body + 0x14] | d[body + 0x15] << 8);
  72. const std::size_t at = body + 0x16 + 2 * nameLen; // "DATA"
  73. if (at + 12 > d.size())
  74. return std::nullopt;
  75. if (floatsAt != nullptr)
  76. *floatsAt = at + 12;
  77. auto size = (long long) (std::int32_t) rd32 (d.data() + at + 4);
  78. if (size < 4)
  79. return std::nullopt;
  80. std::array<float, paramCount> P {};
  81. std::copy (std::begin (defaults), std::end (defaults), P.begin());
  82. for (int i = 0; i < paramCount; ++i)
  83. {
  84. size -= 4;
  85. if (size <= 3)
  86. continue;
  87. const auto off = at + 12 + 4 * (std::size_t) i;
  88. if (off + 4 > d.size())
  89. break;
  90. float v;
  91. const auto bits = rd32 (d.data() + off);
  92. std::memcpy (&v, &bits, 4);
  93. P[(std::size_t) i] = v == v ? std::min (std::max (v, 0.0f), 1.0f) : 0.0f;
  94. }
  95. return P;
  96. }
  97. std::vector<std::uint8_t> readFileBytes (const std::string& path)
  98. {
  99. std::ifstream in (path, std::ios::binary);
  100. if (! in)
  101. {
  102. auto local = path;
  103. std::replace (local.begin(), local.end(), '\\', '/');
  104. in.open (local, std::ios::binary);
  105. }
  106. return std::vector<std::uint8_t> ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  107. }
  108. // ------------------------------------------------------------------------------------------------------- tables
  109. // §3.3: oscdata.dat = 1024 amplitudes + 1024 phases (float). Table 1023 − h holds harmonics 1…h + 1: harmonic h + 1 adds
  110. // amp[h]·cos(j·(h + 1)·2π/2048 + phase[h]) to the running float sum.
  111. using Tables = std::vector<float>;
  112. std::shared_ptr<const Tables> zeroTables()
  113. {
  114. static const auto z = std::make_shared<const Tables> ((std::size_t) tableCount * tableLen, 0.0f);
  115. return z;
  116. }
  117. std::shared_ptr<const Tables> buildTables (const std::vector<std::uint8_t>& bytes)
  118. {
  119. if (bytes.size() < 8192)
  120. return zeroTables();
  121. auto T = std::make_shared<Tables> ((std::size_t) tableCount * tableLen);
  122. std::vector<float> acc (tableLen, 0.0f);
  123. for (int h = 0; h < tableCount; ++h)
  124. {
  125. float amp, ph;
  126. const auto a = rd32 (bytes.data() + 4 * h), p = rd32 (bytes.data() + 4096 + 4 * h);
  127. std::memcpy (&amp, &a, 4);
  128. std::memcpy (&ph, &p, 4);
  129. const auto w = (double) ((float) h + 1.0f) * 0.0030679615757712823;
  130. for (int j = 0; j < tableLen; ++j)
  131. acc[(std::size_t) j] = (float) (std::cos ((double) (float) j * w + (double) ph) * (double) amp + (double) acc[(std::size_t) j]);
  132. std::copy (acc.begin(), acc.end(), T->begin() + (std::ptrdiff_t) (tableCount - 1 - h) * tableLen);
  133. }
  134. return T;
  135. }
  136. std::shared_ptr<const Tables> tablesFor (const std::string& path)
  137. {
  138. static std::mutex mutex;
  139. static std::map<std::string, std::shared_ptr<const Tables>> cache;
  140. if (path.empty())
  141. return zeroTables();
  142. {
  143. const std::lock_guard<std::mutex> lock (mutex);
  144. if (const auto it = cache.find (path); it != cache.end())
  145. return it->second;
  146. }
  147. auto T = buildTables (readFileBytes (path));
  148. const std::lock_guard<std::mutex> lock (mutex);
  149. return cache.emplace (path, T).first->second;
  150. }
  151. // ------------------------------------------------------------------------------------------------------- engine
  152. // §3.6: the generator; per-sample/per-block draws use one rule, the voice reset another (128 steps per value)
  153. struct Lcg
  154. {
  155. std::uint32_t s = 0;
  156. std::uint32_t step() noexcept
  157. {
  158. const auto old = s;
  159. s = s * 0xbb38435u + 0x3619636bu;
  160. return old;
  161. }
  162. std::uint32_t resetValue() noexcept
  163. {
  164. for (int i = 0; i < 128; ++i)
  165. s = s * 0xB464B2F9u + 0x9D6F2492u;
  166. return s;
  167. }
  168. };
  169. // §4.4: per-sample envelope coefficient
  170. float envRate (double p, bool attack) noexcept
  171. {
  172. if (p >= 0.0010000000474974513)
  173. {
  174. const auto k = p * 0.95 + 0.05;
  175. const auto d = k * k * k * k * (attack ? 500.0 : 50.0);
  176. if (d >= 0.001)
  177. return (float) (0.0002 / d);
  178. }
  179. return 1.0f;
  180. }
  181. constexpr double lfoBeats[12] = { 0.25, 0.375, 0.5, 0.75, 1.0, 2.0, 4.0, 8.0, 16.0, 64.0, 128.0, 256.0 };
  182. class Engine;
  183. struct Voice
  184. {
  185. Engine* e = nullptr;
  186. double rate = 44100.0;
  187. std::int32_t ph[8] {}, inc[8] {};
  188. float gain[8] {};
  189. int n = 0;
  190. const float* table = nullptr;
  191. int key = -1;
  192. float vel = 0.0f;
  193. std::uint32_t age = 0;
  194. float glide = 0.0f;
  195. double y[4] {};
  196. double A[4][5] {};
  197. float fe = 0.0f, feT = 0.0f, feR = 0.0f, ae = 0.0f, aeT = 0.0f, aeR = 0.0f;
  198. float dc = 0.0f, drift = 0.0f;
  199. double note = 0.0, freq = 0.0;
  200. float tL = 0.0f, tR = 0.0f, gL = -1.0f, gR = -1.0f;
  201. bool released = true;
  202. bool active() const noexcept { return key >= 0; }
  203. void reset (double r) noexcept;
  204. void start (int k, float v, bool legato) noexcept;
  205. void release() noexcept;
  206. bool control() noexcept;
  207. void oscSetup() noexcept;
  208. void filterSetup() noexcept;
  209. void render (float* outL, float* outR, int m) noexcept;
  210. };
  211. class Engine
  212. {
  213. public:
  214. Lcg lcg;
  215. std::shared_ptr<const Tables> tabs = zeroTables();
  216. double rate = 0.0, bpm = 120.0, songpos = 0.0;
  217. bool playing = false;
  218. float P[paramCount] {};
  219. float keyvel[128] {};
  220. int last = 0;
  221. std::uint32_t counter = 1;
  222. float keyL[128] {}, keyR[128] {}, keyPitch[128] {}, keyFcut[128] {}, keyFres[128] {};
  223. float bend = 0.0f, mw = 0.0f;
  224. bool sustainPedal = false;
  225. float lfo = 0.0f;
  226. double lfoPhase = 0.0;
  227. std::uint32_t silence = 0;
  228. int polyMax = voiceCount, polyLimit = 0;
  229. std::array<Voice, voiceCount> voices;
  230. // derived parameters (§1.2)
  231. bool poly = true, lead = false;
  232. float transpose = 0.0f, slide = 0.0f, mwAmt = 0.0f, oscmod = 0.0f, noise = 0.0f, fltFreq = 1.0f, peak = 0.0f, fltKbd = 0.0f,
  233. fltVel = 0.0f;
  234. int mwDest = 0, kind = 0, lfoShape = 0, lfoDest = 0;
  235. float feAtk = 1.0f, feDec = 1.0f, feSus = 1.0f, feRel = 1.0f, egfAmt = 0.0f, lfoAmt = 0.0f;
  236. float aeAtk = 1.0f, aeDec = 1.0f, aeSus = 1.0f, aeRel = 1.0f;
  237. double lfoBeat = 1.0, dlyTime = 0.25;
  238. float phaSpeed = 0.25f;
  239. bool dlyOn = false, choOn = false, phaOn = false, dlyReset = true, choReset = true, phaReset = true;
  240. // effect state (§6)
  241. std::int32_t holdCnt = 0;
  242. float holdL = 0.0f, holdR = 0.0f;
  243. std::vector<float> dlyBuf, choBuf;
  244. int dlyN = 0, choN = 0, dlyPos = 0, choPos = 0;
  245. float dlyLp = 0.0f, choP1 = 0.62f, choP2 = 0.1f;
  246. float phaS[14] {}, phaF = -1.0f, phaPhase = 0.0f;
  247. void init() noexcept
  248. {
  249. lcg = {};
  250. rate = 0.0;
  251. bpm = 120.0;
  252. songpos = 0.0;
  253. playing = false;
  254. std::fill (std::begin (keyvel), std::end (keyvel), 0.0f);
  255. last = 0;
  256. counter = 1;
  257. std::fill (std::begin (keyL), std::end (keyL), 1.0f);
  258. std::fill (std::begin (keyR), std::end (keyR), 1.0f);
  259. std::fill (std::begin (keyPitch), std::end (keyPitch), 0.0f);
  260. std::fill (std::begin (keyFcut), std::end (keyFcut), 0.0f);
  261. std::fill (std::begin (keyFres), std::end (keyFres), 0.0f);
  262. bend = mw = 0.0f;
  263. lfo = 0.0f;
  264. lfoPhase = 0.0;
  265. silence = 0;
  266. polyLimit = 0;
  267. dlyOn = choOn = phaOn = false;
  268. // the 99 voices are constructed (one reset each), then the defaults are applied (§3.6)
  269. for (auto& v : voices)
  270. {
  271. v = Voice {};
  272. v.e = this;
  273. v.reset (0.0);
  274. }
  275. for (int i = 0; i < paramCount; ++i)
  276. setParam (i, defaults[i]);
  277. holdCnt = 0;
  278. holdL = holdR = 0.0f;
  279. dlyReset = choReset = phaReset = true;
  280. dlyPos = choPos = 0;
  281. dlyLp = 0.0f;
  282. choP1 = 0.62f, choP2 = 0.1f;
  283. std::fill (std::begin (phaS), std::end (phaS), 0.0f);
  284. phaF = -1.0f, phaPhase = 0.0f;
  285. }
  286. void setParam (int i, float v) noexcept
  287. {
  288. if (i < 0 || i >= paramCount)
  289. return;
  290. v = std::min (std::max (v, 0.0f), 1.0f);
  291. P[i] = v;
  292. switch (i)
  293. {
  294. case 0:
  295. {
  296. const auto mode = (int) (v + v);
  297. if (mode == 0)
  298. poly = true, lead = false;
  299. else if (mode == 1)
  300. poly = false, lead = false;
  301. else if (mode == 2)
  302. poly = false, lead = true;
  303. break;
  304. }
  305. case 1: transpose = (float) i32 ((v - 0.5f) * 24.0f); break;
  306. case 2:
  307. {
  308. const auto t = (1.0f - v) * (1.0f - v);
  309. slide = (float) ((double) (t * t) * 0.9 + 0.01);
  310. break;
  311. }
  312. case 3: mwDest = (int) v; break;
  313. case 4: mwAmt = v; break;
  314. case 5: kind = (int) (v * 9.0f); break;
  315. case 6: oscmod = v; break;
  316. case 7: noise = v * v; break;
  317. case 8: fltFreq = v; break;
  318. case 9: peak = v * 0.99f; break;
  319. case 10: fltKbd = v; break;
  320. case 11: fltVel = v; break;
  321. case 12: feAtk = envRate (v, true); break;
  322. case 13: feDec = envRate (v, false); break;
  323. case 14: feSus = v; break;
  324. case 15: feRel = envRate (v, false); break;
  325. case 16: egfAmt = (v + v) - 1.0f; break;
  326. case 17: lfoShape = (int) (v + v); break;
  327. case 18: lfoDest = (int) (v + v); break;
  328. case 19:
  329. if (const auto j = (int) (v * 11.0f); j >= 0 && j <= 11)
  330. lfoBeat = lfoBeats[j];
  331. break;
  332. case 20: lfoAmt = (v + v) - 1.0f; break;
  333. case 21: aeAtk = envRate (v, true); break;
  334. case 22: aeDec = envRate (v, false); break;
  335. case 23: aeSus = v; break;
  336. case 24: aeRel = envRate ((double) v * 0.95 + 0.05, false) * 10.0f; break;
  337. case 28:
  338. if (dlyOn != (v != 0.0f))
  339. dlyReset = true;
  340. dlyOn = v != 0.0f;
  341. break;
  342. case 29: dlyTime = ((double) i32 (v * 3.0f) + 1.0) * 0.25; break;
  343. case 33:
  344. if (choOn != (v != 0.0f))
  345. choReset = true;
  346. choOn = v != 0.0f;
  347. break;
  348. case 37:
  349. if (phaOn != (v != 0.0f))
  350. phaReset = true;
  351. phaOn = v != 0.0f;
  352. break;
  353. case 38:
  354. if (const auto j = (int) (v * 11.0f); j >= 0 && j <= 11)
  355. phaSpeed = (float) lfoBeats[j];
  356. break;
  357. default: break;
  358. }
  359. }
  360. // §2.4: the sample-rate set; the buffers are (re)allocated off the audio thread (prepare)
  361. void setRate (double r)
  362. {
  363. if (r != 0.0 && r != rate)
  364. {
  365. rate = r;
  366. dlyN = (int) (rate * 1.5);
  367. choN = (int) (rate * 0.01);
  368. dlyBuf.assign ((std::size_t) std::max (dlyN, 1), 0.0f);
  369. choBuf.assign ((std::size_t) std::max (choN, 1), 0.0f);
  370. }
  371. std::fill (std::begin (keyvel), std::end (keyvel), 0.0f);
  372. lfoPhase = 0.0;
  373. for (auto& v : voices)
  374. v.reset (rate);
  375. holdCnt = 0;
  376. holdL = holdR = 0.0f;
  377. silence = 0xffffffffu;
  378. dlyReset = choReset = phaReset = true;
  379. }
  380. void setMaxPoly (int n) noexcept { polyLimit = n == 0 ? polyMax : n; }
  381. // §3.2: note on (vel > 0) / off (vel = 0), vel = MIDI velocity / 127
  382. void note (int key, float vel) noexcept
  383. {
  384. if (key < 0 || key > 127)
  385. return;
  386. vel = std::min (std::max (vel, 0.0f), 1.0f);
  387. keyvel[key] = vel;
  388. if (vel == 0.0f)
  389. {
  390. if (sustainPedal)
  391. return;
  392. for (auto& v : voices)
  393. {
  394. if (v.key != key)
  395. continue;
  396. if (! poly && lead)
  397. {
  398. int below = -1, above = -1;
  399. float vb = 0.0f, va = 0.0f;
  400. for (int k = 0; k < key; ++k)
  401. if (keyvel[k] != 0.0f)
  402. below = k, vb = keyvel[k];
  403. for (int k = 127; k > key; --k)
  404. if (keyvel[k] != 0.0f)
  405. above = k, va = keyvel[k];
  406. if (vb != 0.0f)
  407. {
  408. v.key = below, v.vel = vb, last = below;
  409. continue;
  410. }
  411. if (va != 0.0f)
  412. {
  413. v.key = above, v.vel = va, last = above;
  414. continue;
  415. }
  416. }
  417. v.release();
  418. }
  419. return;
  420. }
  421. Voice* v = nullptr;
  422. if (poly)
  423. {
  424. const auto n = std::min (polyMax, polyLimit);
  425. for (int i = 0; i < n; ++i)
  426. if (! voices[(std::size_t) i].active())
  427. v = &voices[(std::size_t) i];
  428. if (v == nullptr)
  429. {
  430. std::uint32_t best = 0xffffffffu;
  431. for (int i = 0; i < n; ++i)
  432. {
  433. const auto a = voices[(std::size_t) i].age;
  434. if (a <= best)
  435. v = &voices[(std::size_t) i];
  436. if (a < best)
  437. best = a;
  438. }
  439. }
  440. if (v == nullptr)
  441. return;
  442. }
  443. else
  444. v = &voices[0];
  445. counter = counter + 1;
  446. v->age = counter;
  447. v->glide = (float) last;
  448. if (lead)
  449. {
  450. bool alone = true;
  451. for (int k = 0; k < 128; ++k)
  452. alone = alone && (keyvel[k] == 0.0f || k == key);
  453. if (alone)
  454. v->glide = (float) key;
  455. }
  456. v->start (key, vel, lead);
  457. last = key;
  458. }
  459. void lfoStep (int m, double pos) noexcept // §5
  460. {
  461. float w = lfo;
  462. if (lfoShape == 0)
  463. w = (float) std::sin (lfoPhase * 6.283185307179586);
  464. else if (lfoShape == 1)
  465. w = (float) (((1.0 - lfoPhase) + (1.0 - lfoPhase)) - 1.0);
  466. else if (lfoShape == 2)
  467. {
  468. const auto b = 0.5 > lfoPhase ? 1.0f : 0.0f;
  469. w = (b + b) - 1.0f;
  470. }
  471. const auto a = lfoAmt;
  472. auto a2 = a;
  473. if (mwDest == 1)
  474. a2 = a + mwAmt * mw;
  475. if (a > 1.0f)
  476. lfo = w;
  477. else if (a < -1.0f)
  478. lfo = -w;
  479. else
  480. {
  481. w = (a2 * a2) * w;
  482. lfo = a >= 0.0f ? w : -w;
  483. }
  484. double x;
  485. if (playing)
  486. x = pos / lfoBeat;
  487. else
  488. x = (((0.016666666666666666 / lfoBeat) * bpm) / rate) * (double) m + lfoPhase;
  489. lfoPhase = x - (double) i32 (x);
  490. }
  491. // one engine call of n ≤ 512 samples, summed into L/R (§2.3)
  492. void process (float* L, float* R, int n) noexcept
  493. {
  494. auto pos = songpos;
  495. const auto limit = (std::uint32_t) i32 (rate * 0.5);
  496. bool any = false;
  497. while (n > 0)
  498. {
  499. const auto m = std::min (n, blockLen);
  500. n -= m;
  501. lfoStep (m, pos);
  502. pos = pos + (((double) m / rate) * bpm) * 0.016666666666666666;
  503. for (auto& v : voices)
  504. if (v.active())
  505. {
  506. v.render (L, R, m);
  507. any = true;
  508. }
  509. std::uint32_t cnt;
  510. if (any)
  511. silence = 0, cnt = 0;
  512. else
  513. {
  514. if (silence != 0xffffffffu)
  515. silence += (std::uint32_t) m;
  516. cnt = silence;
  517. }
  518. if (cnt < limit)
  519. {
  520. fxDist (L, R, m);
  521. fxDelay (L, R, m);
  522. fxPhaser (L, R, m, pos);
  523. fxChorus (L, R, m);
  524. any = true;
  525. }
  526. L += m;
  527. R += m;
  528. }
  529. }
  530. bool anyActive() const noexcept
  531. {
  532. return std::any_of (voices.begin(), voices.end(), [] (const Voice& v) { return v.active(); });
  533. }
  534. private:
  535. void fxDist (float* L, float* R, int m) noexcept // §6.1
  536. {
  537. if (P[25] == 0.0f)
  538. return;
  539. const auto D = (P[26] * P[26]) * 20.0f;
  540. auto t = 1.0f - D * 0.0625f;
  541. t = t * t, t = t * t, t = t * t;
  542. const auto g = (float) ((double) t * 0.7 + 0.3);
  543. auto h = P[27] * P[27];
  544. h = std::min (std::max (h, 0.0f), 1.0f);
  545. const auto H = i32 (h * 64.0f);
  546. auto shape = [&] (float x) {
  547. float y;
  548. if (x >= 0.0f)
  549. y = 1.0f - powf32 (10.0, (double) -(x * D)) * (1.0f - x);
  550. else
  551. y = powf32 (10.0, (double) (x * D)) * (x + 1.0f) - 1.0f;
  552. return g * y;
  553. };
  554. for (int i = 0; i < m; ++i)
  555. {
  556. auto yl = shape (L[i]), yr = shape (R[i]);
  557. if (H != 0)
  558. {
  559. auto c = holdCnt;
  560. if ((float) c > 0.0f)
  561. yl = holdL, yr = holdR;
  562. else
  563. {
  564. holdL = yl, holdR = yr;
  565. c = add32 (c, H);
  566. }
  567. holdCnt = i32 ((float) c - 1.0f);
  568. }
  569. L[i] = yl;
  570. R[i] = yr;
  571. }
  572. }
  573. void fxDelay (float* L, float* R, int m) noexcept // §6.2
  574. {
  575. if (! dlyOn || dlyBuf.empty() || dlyN <= 0)
  576. return;
  577. if (dlyReset)
  578. {
  579. dlyReset = false;
  580. std::fill (dlyBuf.begin(), dlyBuf.end(), 0.0f);
  581. dlyPos = 0;
  582. dlyLp = 0.0f;
  583. }
  584. const auto c = std::min (std::max (P[31], 0.0f), 1.0f) * 0.99f + 0.01f;
  585. const auto fb = P[30], mix = P[32] * P[32];
  586. auto q = (dlyTime * 40.0) / bpm;
  587. while (q > 1.0)
  588. q = q * 0.5;
  589. const auto ln = std::min (std::max (i32 ((double) (dlyN - 1) * q), 1), dlyN);
  590. for (int i = 0; i < m; ++i)
  591. {
  592. if (dlyPos >= ln)
  593. dlyPos = 0;
  594. auto& b = dlyBuf[(std::size_t) dlyPos];
  595. const auto s = (float) ((((double) (fb * b) + 1e-30) - (double) dlyLp) * (double) c + (double) dlyLp);
  596. dlyLp = s;
  597. b = (R[i] + L[i]) + s;
  598. const auto wet = s * mix;
  599. if (std::fabs ((double) wet) > 1e-05)
  600. silence = 0;
  601. L[i] = wet + L[i];
  602. R[i] = wet + R[i];
  603. ++dlyPos;
  604. }
  605. }
  606. void fxPhaser (float* L, float* R, int m, double pos) noexcept // §6.3
  607. {
  608. if (! phaOn)
  609. return;
  610. if (phaReset)
  611. {
  612. phaReset = false;
  613. std::fill (std::begin (phaS), std::end (phaS), 0.0f);
  614. phaF = -1.0f;
  615. phaPhase = 0.0f;
  616. }
  617. const auto hi = (float) ((0.5 / rate) * 40000.0), lo = (float) ((0.5 / rate) * 100.0);
  618. const auto w = powf32 ((double) P[39], 3.0) * 0.5f;
  619. const auto fb = (float) ((double) powf32 ((double) P[40], (double) 0.33333334f) * 0.98);
  620. const auto T = std::max (P[42] * P[42], 1e-5f);
  621. const auto mo = std::max (P[41], 1e-5f);
  622. if (phaF < 0.0f)
  623. phaF = T;
  624. double x;
  625. if (playing)
  626. x = pos / (double) phaSpeed;
  627. else
  628. x = (bpm / ((double) (phaSpeed * 60.0f) * rate)) * (double) m + (double) phaPhase;
  629. const auto xf = (float) x;
  630. phaPhase = xf - (float) i32 (xf);
  631. const auto s = std::cos ((double) phaPhase * 6.283185307179586);
  632. const auto cA = (float) ((s + 1.0) * (double) w), cB = (float) ((1.0 - s) * (double) w);
  633. const auto span = hi - lo;
  634. for (int i = 0; i < m; ++i)
  635. {
  636. const auto F = phaF;
  637. const auto xl = (float) ((double) L[i] + 1e-30), xr = (float) ((double) R[i] + 1e-30);
  638. const auto gA = std::max (std::min ((F + cA) * span + lo, 0.499f), 1e-5f);
  639. const auto gB = std::max (std::min ((F + cB) * span + lo, 0.499f), 1e-5f);
  640. phaF = (float) ((double) (T - F) * 0.001 + (double) F);
  641. const auto aA = (1.0f - gA) / (gA + 1.0f), aB = (1.0f - gB) / (gB + 1.0f);
  642. auto chain = [&] (float a, int base, int fbi, float in, float& out) {
  643. auto prev = in + fb * phaS[fbi];
  644. for (int k = 0; k < 6; ++k)
  645. {
  646. const auto v = phaS[base + k] - a * prev;
  647. phaS[base + k] = v * a + prev;
  648. prev = v;
  649. }
  650. phaS[fbi] = prev;
  651. out = prev * mo + out;
  652. };
  653. chain (aA, 0, 6, xl, L[i]);
  654. chain (aB, 7, 13, xr, R[i]);
  655. }
  656. }
  657. void fxChorus (float* L, float* R, int m) noexcept // §6.4
  658. {
  659. if (! choOn || choBuf.empty() || choN <= 0)
  660. return;
  661. const auto N = choN;
  662. if (choReset)
  663. {
  664. choReset = false;
  665. std::fill (choBuf.begin(), choBuf.end(), 0.0f);
  666. choPos = 0;
  667. choP1 = 0.62f, choP2 = 0.1f;
  668. }
  669. const auto D = (P[35] * 0.9f) * 0.4f + 0.04f;
  670. const auto M = P[36] * P[36];
  671. const auto r = (P[34] * P[34]) * 4.0f + 0.2f;
  672. const auto inv = 1.0 / rate;
  673. const auto i1 = (float) ((double) r * inv), i2 = (float) ((double) (r + 0.05f) * inv);
  674. const auto ND = (float) N * D;
  675. auto tap = [&] (int p, float posf) {
  676. const auto ip = i32 (posf);
  677. const auto fr = posf - (float) ip;
  678. auto a = p + ip;
  679. if (a >= N)
  680. a -= N;
  681. auto b = a + 1;
  682. if (b >= N)
  683. b -= N;
  684. return (1.0f - fr) * choBuf[(std::size_t) a] + fr * choBuf[(std::size_t) b];
  685. };
  686. for (int i = 0; i < m; ++i)
  687. {
  688. if (choPos >= N)
  689. choPos = 0;
  690. const auto p = choPos;
  691. choBuf[(std::size_t) p] = L[i] + R[i];
  692. const auto v = (float) (std::sin ((double) choP1 * 6.283185307179586) * (double) D + 0.5);
  693. const auto tapL = tap (p, ND * (v * v));
  694. const auto tapR = tap (p, (float) (std::sin ((double) choP2 * 6.283185307179586) * (double) D + 0.5));
  695. const auto p2 = choP2 + i2, p1 = choP1 + i1;
  696. choP1 = p1 - (float) i32 (p1);
  697. choP2 = p2 - (float) i32 (p2);
  698. L[i] = tapL * M + L[i];
  699. R[i] = tapR * M + R[i];
  700. ++choPos;
  701. }
  702. }
  703. };
  704. void Voice::reset (double r) noexcept
  705. {
  706. if (r != 0.0)
  707. rate = (double) (float) r;
  708. for (auto& p : ph)
  709. p = (std::int32_t) e->lcg.resetValue();
  710. key = -1;
  711. vel = 0.0f;
  712. y[0] = y[1] = y[2] = y[3] = 0.0;
  713. fe = 0.0f;
  714. ae = 0.0f;
  715. released = true;
  716. gL = gR = -1.0f;
  717. }
  718. void Voice::start (int k, float v, bool legato) noexcept
  719. {
  720. vel = v;
  721. key = k;
  722. if (legato && ! released)
  723. return;
  724. fe = 0.0f, feT = 4.0f, feR = e->feAtk;
  725. aeT = 4.0f, aeR = e->aeAtk;
  726. released = false;
  727. }
  728. void Voice::release() noexcept
  729. {
  730. released = true;
  731. feT = 0.0f, feR = e->feRel;
  732. aeT = 0.0f, aeR = e->aeRel;
  733. }
  734. // §4.1: once per 32-sample block; false when the voice ended (reset) instead
  735. bool Voice::control() noexcept
  736. {
  737. auto v = vel;
  738. if (ae < 1e-5f && aeT == 0.0f)
  739. v = 0.0f;
  740. tL = v * e->keyL[key];
  741. tR = v * e->keyR[key];
  742. if (! (gL >= 0.0f))
  743. gL = tL;
  744. if (! (gR >= 0.0f))
  745. gR = tR;
  746. if (released && v == 0.0f && gL < 1e-5f && gR < 1e-5f)
  747. {
  748. reset (0.0);
  749. return false;
  750. }
  751. const auto r = e->lcg.step();
  752. const auto rnd = (float) ((double) r * 4.656612874161595e-10 - 1.0);
  753. drift = (rnd - drift) * 0.01f + drift;
  754. const auto ds = drift * 0.08f;
  755. glide = ((float) key - glide) * e->slide + glide;
  756. auto nt = (double) ((glide + e->transpose) + ds);
  757. nt = (double) e->bend + nt;
  758. if (e->lfoDest == 1)
  759. nt = (double) (e->lfo * 12.0f) + nt;
  760. nt = (double) e->keyPitch[key] + nt;
  761. note = nt;
  762. freq = std::pow (2.0, (nt - 57.0) * 0.08333333333333333) * 220.0;
  763. oscSetup();
  764. filterSetup();
  765. return true;
  766. }
  767. // §3.4: oscillator set-up per kind (all oscillators read the table chosen for the first one)
  768. void Voice::oscSetup() noexcept
  769. {
  770. const auto f = freq;
  771. auto m = e->oscmod;
  772. if (e->lfoDest == 2)
  773. m = m + e->lfo * 12.0f;
  774. const auto expo = (float) i32 (m * 24.0f - 12.0f) * 0.0833333358168602f + 0.006250000558793545f;
  775. const auto r = (double) powf32 (2.0, (double) expo);
  776. const auto am = std::fabs (m);
  777. float g[8] = { 1.0f, -1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.5f };
  778. double fr[8] = { f, f, f, f, f, f, f, f };
  779. auto offset = [] (float x) { return i32via64 ((double) x * 4294967295.0); };
  780. switch (e->kind)
  781. {
  782. case 0:
  783. {
  784. n = 3;
  785. const auto off = offset (1.0f - am);
  786. ph[2] = ph[0];
  787. ph[1] = add32 (ph[0], off);
  788. if (off == 0)
  789. n = 1;
  790. break;
  791. }
  792. case 1:
  793. n = 2, fr[1] = f * r, g[1] = 1.0f;
  794. break;
  795. case 2:
  796. n = 2;
  797. ph[1] = add32 (offset (1.0f - am), ph[0]);
  798. break;
  799. case 3:
  800. n = 3, fr[2] = f * r;
  801. ph[1] = add32 (ph[0], 0x7fffffff);
  802. break;
  803. case 4:
  804. n = 4, fr[2] = fr[3] = f * r, g[3] = -1.0f;
  805. ph[1] = add32 (ph[0], -0x70000001);
  806. ph[3] = add32 (ph[2], -0x70000001);
  807. break;
  808. case 5:
  809. n = 8;
  810. for (int k = 0; k < 8; ++k)
  811. g[k] = 0.5f, fr[k] = (((double) k * 0.0125 - 0.05) * (double) m + 1.0) * f;
  812. break;
  813. case 6:
  814. {
  815. n = 6;
  816. for (auto& x : g)
  817. x = 0.5f;
  818. const auto d = offset (std::fabs (m * 0.5f));
  819. const auto p0 = ph[0];
  820. std::int32_t acc = 0;
  821. for (int k = 0; k < 6; ++k)
  822. ph[k] = add32 (p0, acc), acc = add32 (acc, d);
  823. break;
  824. }
  825. case 7:
  826. n = 2, g[1] = 1.0f;
  827. ph[1] = add32 (offset (1.0f - am), ph[0]);
  828. break;
  829. case 8:
  830. case 9:
  831. {
  832. n = 3, g[1] = 1.0f, g[2] = 1.0f;
  833. const auto q = (double) m * 0.01;
  834. fr[0] = (1.0 - q) * f * (e->kind == 8 ? 0.5 : 1.5);
  835. fr[2] = (f + f) * (q + 1.0);
  836. break;
  837. }
  838. default: n = 0; break;
  839. }
  840. const auto ratef = (float) rate;
  841. for (int k = 0; k < n; ++k)
  842. {
  843. gain[k] = g[k];
  844. inc[k] = i32via64 ((fr[k] / rate) * 4294967295.0);
  845. if (k == 0)
  846. {
  847. const auto frf = (float) fr[k];
  848. int lvl = 0;
  849. if (ratef * 0.00048828125f < frf)
  850. lvl = std::min (std::max (0x3ff - i32 ((0.5f / frf) * ratef), 0), 0x3ff);
  851. table = e->tabs->data() + (std::size_t) lvl * tableLen;
  852. }
  853. }
  854. }
  855. // §4.2: cutoff/resonance and the per-sample transition matrix (4096 Euler sub-steps by 12 squarings)
  856. void Voice::filterSetup() noexcept
  857. {
  858. auto a = (((double) vel - 0.5) * (double) e->fltVel) * 14.0;
  859. const auto b = ((note - 48.0) * (double) e->fltKbd) * 0.08333333333333333;
  860. const auto c = (double) e->fltFreq * 10.3;
  861. a = a + b;
  862. a = a + 4.0;
  863. a = a + ((double) drift * 0.10300000000000001 + c);
  864. if (e->lfoDest == 0)
  865. a = a + (double) e->lfo * 4.0;
  866. if (e->mwDest == 0)
  867. a = a + (double) (e->mwAmt * e->mw) * 4.0;
  868. const auto fc = std::pow (2.0, (double) e->keyFcut[key] + a);
  869. const auto g0 = 6.25 / (4096.0 * rate);
  870. const auto ex = std::pow (2.0, (double) e->egfAmt * 10.0);
  871. const auto fc2 = std::min ((ex * fc - fc) * (double) fe + fc, 20000.0);
  872. const auto g = std::min (std::max (g0 * fc2, 0.0), 1.0);
  873. const auto k = std::min (std::max ((double) e->keyFres[key] + (double) e->peak, 0.0), 1.0) * -4.050000190734863;
  874. const auto om = 1.0 - g;
  875. const auto g2 = g * g, ag = om * g, kg = k * g;
  876. const auto ag2 = ag * g, g3 = g2 * g, kg2 = kg * g, kg3 = kg2 * g;
  877. const auto ag3 = ag2 * g, g4 = g3 * g, kg4a = kg3 * g + om;
  878. double M[4][5] = { { om, 0.0, 0.0, kg, g }, { ag, om, 0.0, kg2, g2 }, { ag2, ag, om, kg3, g3 }, { ag3, ag2, ag, kg4a, g4 } };
  879. for (int it = 0; it < 12; ++it)
  880. {
  881. const auto A00 = M[0][0], A01 = M[0][1], A02 = M[0][2], A03 = M[0][3], A04 = M[0][4];
  882. const auto A10 = M[1][0], A11 = M[1][1], A12 = M[1][2], A13 = M[1][3], A14 = M[1][4];
  883. const auto A20 = M[2][0], A21 = M[2][1], A22 = M[2][2], A23 = M[2][3], A24 = M[2][4];
  884. const auto A30 = M[3][0], A31 = M[3][1], A32 = M[3][2], A33 = M[3][3], A34 = M[3][4];
  885. M[0][0] = ((A10 * A01) + (A00 * A00)) + ((A20 * A02) + (A30 * A03));
  886. M[0][1] = (((A11 + A00) * A01) + (A21 * A02)) + (A31 * A03);
  887. M[0][2] = (((A00 + A22) * A02) + (A12 * A01)) + (A32 * A03);
  888. M[0][3] = (((A33 + A00) * A03) + (A13 * A01)) + (A23 * A02);
  889. M[0][4] = (((A34 * A03) + A04) + (A24 * A02)) + ((A14 * A01) + (A04 * A00));
  890. M[1][0] = ((A00 * A10) + (A10 * A11)) + ((A20 * A12) + (A30 * A13));
  891. M[1][1] = ((A01 * A10) + (A11 * A11)) + ((A21 * A12) + (A13 * A31));
  892. M[1][2] = ((A11 * A12) + (A10 * A02)) + ((A12 * A22) + (A13 * A32));
  893. M[1][3] = ((A33 * A13) + (A23 * A12)) + ((A13 * A11) + (A03 * A10));
  894. M[1][4] = (((A34 * A13) + A14) + (A24 * A12)) + ((A04 * A10) + (A14 * A11));
  895. M[2][0] = ((A30 * A23) + (A20 * A22)) + ((A00 * A20) + (A10 * A21));
  896. M[2][1] = ((A01 * A20) + (A11 * A21)) + ((A23 * A31) + (A21 * A22));
  897. M[2][2] = ((A22 * A22) + (A23 * A32)) + ((A21 * A12) + (A20 * A02));
  898. M[2][3] = ((A03 * A20) + (A13 * A21)) + ((A33 * A23) + (A23 * A22));
  899. M[2][4] = (((A34 * A23) + A24) + (A24 * A22)) + ((A04 * A20) + (A14 * A21));
  900. M[3][0] = ((A33 * A30) + (A32 * A20)) + ((A00 * A30) + (A10 * A31));
  901. M[3][1] = ((A33 * A31) + (A32 * A21)) + ((A30 * A01) + (A11 * A31));
  902. M[3][2] = ((A31 * A12) + (A30 * A02)) + ((A32 * A22) + (A33 * A32));
  903. M[3][3] = ((A33 * A33) + (A23 * A32)) + ((A03 * A30) + (A13 * A31));
  904. M[3][4] = (((A34 * A33) + A34) + (A24 * A32)) + ((A04 * A30) + (A14 * A31));
  905. }
  906. std::memcpy (A, M, sizeof (A));
  907. }
  908. // §4.3: the per-sample loop
  909. void Voice::render (float* outL, float* outR, int m) noexcept
  910. {
  911. if (! control())
  912. return;
  913. auto& lcg = e->lcg;
  914. const auto noise = e->noise;
  915. const auto A00 = A[0][0], A01 = A[0][1], A02 = A[0][2], A03 = A[0][3], A04 = A[0][4];
  916. const auto A10 = A[1][0], A11 = A[1][1], A12 = A[1][2], A13 = A[1][3], A14 = A[1][4];
  917. const auto A20 = A[2][0], A21 = A[2][1], A22 = A[2][2], A23 = A[2][3], A24 = A[2][4];
  918. const auto A30 = A[3][0], A31 = A[3][1], A32 = A[3][2], A33 = A[3][3], A34 = A[3][4];
  919. auto y1 = y[0], y2 = y[1], y3 = y[2], y4 = y[3];
  920. const auto* T = table;
  921. for (int i = 0; i < m; ++i)
  922. {
  923. const auto r = lcg.s;
  924. lcg.s = r * 0xbb38435u + 0x3619636bu;
  925. const auto d = lcg.s & 0x3fffffu;
  926. double s = 0.0;
  927. for (int k = 0; k < n; ++k)
  928. {
  929. const auto p = (std::uint32_t) ph[k];
  930. s += (double) (T[(p + d) >> 21] * gain[k]);
  931. ph[k] = add32 (ph[k], inc[k]);
  932. }
  933. const auto nz = (float) (((double) r * 2.3283064370807974e-10) * 2.0 - 1.0) * noise;
  934. const auto x = (((double) nz + s) * 0.20000000298023224 + 0.06999999985098837) * (double) ae;
  935. const auto n4 = (((x * A34) + (y4 * A33)) + (y3 * A32)) + ((y1 * A30) + (y2 * A31));
  936. const auto n1 = (((y4 * A03) + (x * A04)) + (y3 * A02)) + ((y1 * A00) + (y2 * A01));
  937. const auto n2 = (((y4 * A13) + (x * A14)) + (y3 * A12)) + ((y1 * A10) + (y2 * A11));
  938. const auto n3 = (((y4 * A23) + (x * A24)) + (y3 * A22)) + ((y1 * A20) + (y2 * A21));
  939. y4 = n4, y2 = n2, y3 = n3;
  940. y1 = n1 / (n1 * n1 + 1.0);
  941. auto out = n4 * 4.999999925494195;
  942. dc = (float) ((out - (double) dc) * 0.004999999888241291 + (double) dc);
  943. out = out + (double) -dc;
  944. fe = (feT - fe) * feR + fe;
  945. ae = (aeT - ae) * aeR + ae;
  946. gL = (tL - gL) * 0.005f + gL;
  947. gR = (tR - gR) * 0.005f + gR;
  948. if (fe > 1.0f)
  949. fe = 1.0f, feT = e->feSus, feR = e->feDec;
  950. if (ae > 1.0f)
  951. ae = 1.0f, aeT = e->aeSus, aeR = e->aeDec;
  952. outL[i] = (float) ((double) gL * out + (double) outL[i]);
  953. outR[i] = (float) ((double) gR * out + (double) outR[i]);
  954. }
  955. y[0] = y1, y[1] = y2, y[2] = y3, y[3] = y4;
  956. }
  957. // ------------------------------------------------------------------------------------------------------- wrapper
  958. void lawA (double pan, double vol, float& l, float& r) noexcept
  959. {
  960. const auto t = (1.0 + std::clamp (pan, -1.0, 1.0)) * 0.78539816339744831;
  961. l = (float) (vol * std::cos (t));
  962. r = (float) (vol * std::sin (t));
  963. }
  964. int velFromInitVol (double iv) noexcept // §2.1
  965. {
  966. const auto x = (float) iv * 10.0f + 1.0f;
  967. const auto v = ((float) std::log ((double) x) * 0.3284587264060974f) * 127.0f;
  968. return std::clamp (i32 ((double) v), 0, 127);
  969. }
  970. // The FL wrapper (CFLWrapper): held notes with their FinalLevels, per-note tables, Gen_Render chunking (§2)
  971. class Plugin
  972. {
  973. public:
  974. struct Held
  975. {
  976. bool on = false;
  977. double fvol = 1.0, fpan = 0.0, pitchCents = 0.0; // Final.Vol, Final.Pan, Final.Pitch − 100·(key − 60)
  978. };
  979. Engine eng;
  980. Held held[128];
  981. bool panLawA = true;
  982. bool playing = false, changed = false;
  983. // a freshly created plugin (its own 44.1 kHz set-up), then the host's sample rate when it differs (§2.4)
  984. void init (double fs, const float* params)
  985. {
  986. eng.init();
  987. if (params != nullptr)
  988. for (int i = 0; i < paramCount; ++i)
  989. eng.setParam (i, params[i]);
  990. eng.setRate (44100.0);
  991. if (fs != 44100.0)
  992. eng.setRate (fs);
  993. eng.setMaxPoly (0);
  994. for (auto& h : held)
  995. h = Held {};
  996. playing = changed = false;
  997. }
  998. void noteOn (int key, double initVol, double fvol, double fpan, double pitchCents) noexcept
  999. {
  1000. key = std::clamp (key, 0, 127);
  1001. if (held[key].on)
  1002. eng.note (key, 0.0f);
  1003. held[key] = { true, fvol, fpan, pitchCents };
  1004. eng.note (key, (float) velFromInitVol (initVol) * 0.007874016f);
  1005. }
  1006. void noteOff (int key) noexcept
  1007. {
  1008. if (key >= 0 && key < 128)
  1009. eng.note (key, 0.0f);
  1010. }
  1011. void setLevels (int key, double fvol, double fpan) noexcept
  1012. {
  1013. if (key >= 0 && key < 128 && held[key].on)
  1014. held[key].fvol = fvol, held[key].fpan = fpan;
  1015. }
  1016. void setPlaying (bool on) noexcept
  1017. {
  1018. if (on != playing)
  1019. playing = on, changed = true;
  1020. }
  1021. void tables() noexcept
  1022. {
  1023. float cl = 0.0f, cr = 0.0f, cp = 0.0f;
  1024. bool first = true;
  1025. for (int i = 0; i < 128; ++i)
  1026. {
  1027. if (held[i].on)
  1028. {
  1029. const auto& h = held[i];
  1030. if (panLawA)
  1031. lawA (h.fpan, h.fvol, cl, cr);
  1032. else
  1033. cl = cr = (float) h.fvol;
  1034. const auto fp = (float) (float) ((float) (100.0 * i - 6000.0) + (float) h.pitchCents);
  1035. cp = (float) ((double) fp * 0.01 - (double) i + 60.0);
  1036. if (first)
  1037. {
  1038. for (int j = 0; j < i; ++j)
  1039. eng.keyL[j] = cl, eng.keyR[j] = cr, eng.keyPitch[j] = cp, eng.keyFcut[j] = 0.0f, eng.keyFres[j] = 0.0f;
  1040. first = false;
  1041. }
  1042. }
  1043. eng.keyL[i] = cl, eng.keyR[i] = cr, eng.keyPitch[i] = cp, eng.keyFcut[i] = 0.0f, eng.keyFres[i] = 0.0f;
  1044. }
  1045. }
  1046. bool idle() const noexcept
  1047. {
  1048. if (eng.anyActive())
  1049. return false;
  1050. return std::none_of (std::begin (held), std::end (held), [] (const Held& h) { return h.on; });
  1051. }
  1052. // one Gen_Render of n samples summed into outL/outR; songBeats = the host's song position (used while playing)
  1053. void render (float* outL, float* outR, int n, double songBeats) noexcept
  1054. {
  1055. tables();
  1056. auto sp = playing ? songBeats : 0.0;
  1057. for (int c0 = 0; c0 < n; c0 += maxChunk)
  1058. {
  1059. const auto cn = std::min (maxChunk, n - c0);
  1060. eng.songpos = sp;
  1061. if (changed)
  1062. eng.playing = playing, changed = false;
  1063. eng.process (outL + c0, outR + c0, cn);
  1064. if (playing)
  1065. sp = sp + ((eng.bpm * 0.016666666666666666) * (double) cn) * (1.0 / eng.rate);
  1066. }
  1067. // host voices whose key is released and has no engine voice any more are killed
  1068. for (int key = 0; key < 128; ++key)
  1069. if (held[key].on && eng.keyvel[key] == 0.0f
  1070. && std::none_of (eng.voices.begin(), eng.voices.end(), [key] (const Voice& v) { return v.active() && v.key == key; }))
  1071. held[key].on = false;
  1072. }
  1073. };
  1074. // ------------------------------------------------------------------------------------------------------- LYNX front-end
  1075. //
  1076. // Levels (§2.1, REA_rodada28 §4.1, as GMS in REA_rodada39 §3.1): Final.Vol = channel volume, Final.Pan = note pan +
  1077. // channel pan, Final.Pitch = 100·(key − 60) + channel pitch + note cents; the wrapper turns them into the per-note
  1078. // tables with the host's law A. LYNX's channel gains gl = √2·V·cos((1 + p)π/4), gr = √2·V·sin(…) give V and p back, so
  1079. // the channel volume/pan are not applied twice. Velocity: Init.Vol = (11^(1.28·vel) − 1)/10 from LYNX's velocity, then
  1080. // the wrapper's MIDI velocity. The tempo is the song tempo; the max-polyphony event is taken as value 0 (99 voices).
  1081. // While the transport plays, the song position locks the LFO and the phaser LFO (§5, §6.3).
  1082. struct Setup
  1083. {
  1084. std::array<float, paramCount> P {};
  1085. std::shared_ptr<const Tables> tabs;
  1086. };
  1087. class MiniSynthInstrument final : public Instrument
  1088. {
  1089. public:
  1090. MiniSynthInstrument()
  1091. {
  1092. setup = new Setup();
  1093. std::copy (std::begin (defaults), std::end (defaults), setup->P.begin());
  1094. setup->tabs = zeroTables();
  1095. applySetup (44100.0);
  1096. }
  1097. ~MiniSynthInstrument() override
  1098. {
  1099. delete incoming.exchange (nullptr);
  1100. delete retired.exchange (nullptr);
  1101. delete setup;
  1102. }
  1103. void prepare (double sr) noexcept override
  1104. {
  1105. take();
  1106. idleKnown = false;
  1107. rate = sr;
  1108. applySetup (sr);
  1109. lastTicks = -1.0;
  1110. }
  1111. void configure (const ChannelDef& channel, double bpm) noexcept override
  1112. {
  1113. delete retired.exchange (nullptr);
  1114. pitchCents.store (channel.sampler.pitch * 100.0f);
  1115. tempo.store (bpm > 0.0 ? bpm : 120.0);
  1116. if (channel.pluginState == state && channel.samplePath == oscdata)
  1117. return;
  1118. state = channel.pluginState;
  1119. oscdata = channel.samplePath;
  1120. auto s = std::make_unique<Setup>();
  1121. if (auto p = parseState (state))
  1122. s->P = *p;
  1123. else
  1124. std::copy (std::begin (defaults), std::end (defaults), s->P.begin());
  1125. s->tabs = tablesFor (oscdata);
  1126. delete incoming.exchange (s.release());
  1127. }
  1128. void setNextNoteExpression (float pan, float cents, bool) noexcept override
  1129. {
  1130. nextPan = pan;
  1131. nextCents = cents;
  1132. }
  1133. void noteOn (int key, float velocity) noexcept override
  1134. {
  1135. take();
  1136. idleKnown = false;
  1137. const auto vel = std::clamp ((double) velocity, 0.0, 1.0);
  1138. const auto initVol = (std::pow (11.0, 1.28 * vel) - 1.0) / 10.0;
  1139. const auto k = std::clamp (key, 0, 127);
  1140. notePan[k] = nextPan;
  1141. plugin.noteOn (k, initVol, channelVol, std::clamp ((double) nextPan + channelPan, -1.0, 1.0),
  1142. (double) pitchCents.load() + (double) nextCents);
  1143. nextPan = 0.0f;
  1144. nextCents = 0.0f;
  1145. }
  1146. void noteOff (int key) noexcept override
  1147. {
  1148. take();
  1149. idleKnown = false;
  1150. plugin.noteOff (key);
  1151. }
  1152. void allNotesOff() noexcept override
  1153. {
  1154. idleKnown = false;
  1155. for (int k = 0; k < 128; ++k)
  1156. if (plugin.held[k].on)
  1157. plugin.noteOff (k);
  1158. }
  1159. bool idle() const noexcept override
  1160. {
  1161. // the cheap test first; the plugin's scan of its 99 voices and 128 keys can only change through the calls
  1162. // that touch the plugin (they clear idleKnown), so its answer is kept until then
  1163. if (quiet < (int) rate)
  1164. return false;
  1165. if (! idleKnown)
  1166. idleCached = plugin.idle(), idleKnown = true;
  1167. return idleCached;
  1168. }
  1169. void setSongPosition (double ticks) noexcept override
  1170. {
  1171. // the transport plays when the position moves between blocks
  1172. playing = lastTicks >= 0.0 && ticks != lastTicks;
  1173. lastTicks = ticks;
  1174. songBeats = ticks / (double) ppq;
  1175. }
  1176. void render (float* left, float* right, int n, float gl, float gr) noexcept override
  1177. {
  1178. take();
  1179. idleKnown = false;
  1180. plugin.eng.bpm = tempo.load();
  1181. const auto vol = std::sqrt (((double) gl * gl + (double) gr * gr) * 0.5);
  1182. auto pan = vol > 0.0 ? std::atan2 ((double) gr, (double) gl) * (4.0 / 3.141592653589793) - 1.0 : 0.0;
  1183. if (std::fabs (pan) < 1e-9)
  1184. pan = 0.0;
  1185. if (vol != channelVol || pan != channelPan)
  1186. {
  1187. channelVol = vol, channelPan = pan;
  1188. for (int k = 0; k < 128; ++k)
  1189. plugin.setLevels (k, vol, std::clamp ((double) notePan[k] + pan, -1.0, 1.0));
  1190. }
  1191. if (n <= 0)
  1192. return;
  1193. plugin.setPlaying (playing);
  1194. // render into the scratch buffers (the engine sums) and keep track of how long the output has been silent
  1195. for (int c0 = 0; c0 < n; c0 += maxChunk)
  1196. {
  1197. const auto cn = std::min (maxChunk, n - c0);
  1198. std::fill (bufL, bufL + cn, 0.0f);
  1199. std::fill (bufR, bufR + cn, 0.0f);
  1200. plugin.render (bufL, bufR, cn, songBeats + (double) c0 * plugin.eng.bpm / (60.0 * rate));
  1201. bool loud = false;
  1202. for (int i = 0; i < cn; ++i)
  1203. {
  1204. left[c0 + i] += bufL[i];
  1205. right[c0 + i] += bufR[i];
  1206. loud = loud || std::fabs (bufL[i]) > 1e-7f || std::fabs (bufR[i]) > 1e-7f;
  1207. }
  1208. quiet = loud ? 0 : std::min (quiet + cn, 1 << 30);
  1209. }
  1210. }
  1211. private:
  1212. void applySetup (double sr) noexcept
  1213. {
  1214. plugin.eng.tabs = setup->tabs;
  1215. plugin.init (sr, setup->P.data());
  1216. plugin.eng.bpm = tempo.load();
  1217. quiet = 0;
  1218. }
  1219. void take() noexcept
  1220. {
  1221. if (retired.load() != nullptr)
  1222. return;
  1223. if (auto* s = incoming.exchange (nullptr))
  1224. {
  1225. retired.store (setup);
  1226. setup = s;
  1227. // a new patch: the plugin restores the state (its parameters) without resetting its voices
  1228. plugin.eng.tabs = setup->tabs;
  1229. for (int i = 0; i < paramCount; ++i)
  1230. plugin.eng.setParam (i, setup->P[(std::size_t) i]);
  1231. }
  1232. }
  1233. Plugin plugin;
  1234. Setup* setup = nullptr;
  1235. std::atomic<Setup*> incoming { nullptr }, retired { nullptr };
  1236. std::atomic<float> pitchCents { 0.0f };
  1237. std::atomic<double> tempo { 120.0 };
  1238. std::vector<std::uint8_t> state;
  1239. std::string oscdata;
  1240. double rate = 44100.0, channelVol = 1.0, channelPan = 0.0, lastTicks = -1.0, songBeats = 0.0;
  1241. bool playing = false;
  1242. int quiet = 0;
  1243. mutable bool idleKnown = false, idleCached = false;
  1244. float notePan[128] {};
  1245. float nextPan = 0.0f, nextCents = 0.0f;
  1246. float bufL[maxChunk] {}, bufR[maxChunk] {};
  1247. };
  1248. } // namespace
  1249. bool miniSynthStateUsable (const std::vector<std::uint8_t>& state) { return parseState (state).has_value(); }
  1250. std::vector<float> miniSynthParams (const std::vector<std::uint8_t>& state)
  1251. {
  1252. const auto p = parseState (state);
  1253. if (! p)
  1254. return {};
  1255. return std::vector<float> (p->begin(), p->end());
  1256. }
  1257. int miniSynthParamOffset (const std::vector<std::uint8_t>& state, int index)
  1258. {
  1259. std::size_t at = 0;
  1260. if (index < 0 || index >= paramCount || ! parseState (state, &at) || at + 4 * (std::size_t) index + 4 > state.size())
  1261. return -1;
  1262. return (int) (at + 4 * (std::size_t) index);
  1263. }
  1264. std::unique_ptr<Instrument> makeMiniSynthInstrument() { return std::make_unique<MiniSynthInstrument>(); }
  1265. namespace minisynth
  1266. {
  1267. std::vector<float> renderReference (const std::vector<std::uint8_t>& state, const std::vector<RefNote>& notes, double sampleRate,
  1268. int length, const std::string& oscdataPath, int block, double bpm, int maxPoly, double songPos,
  1269. bool panLawA)
  1270. {
  1271. const auto p = parseState (state);
  1272. if (! p || length <= 0)
  1273. return {};
  1274. auto plugin = std::make_unique<Plugin>();
  1275. plugin->eng.tabs = tablesFor (oscdataPath);
  1276. plugin->init (sampleRate, p->data());
  1277. plugin->eng.setMaxPoly (maxPoly);
  1278. plugin->eng.bpm = (double) (float) bpm;
  1279. plugin->panLawA = panLawA;
  1280. if (songPos >= 0.0)
  1281. plugin->setPlaying (true);
  1282. std::vector<int> evs;
  1283. for (const auto& nt : notes)
  1284. {
  1285. evs.push_back (nt.start);
  1286. if (nt.release >= 0)
  1287. evs.push_back (nt.release);
  1288. }
  1289. std::vector<float> out (2 * (std::size_t) length, 0.0f), l ((std::size_t) std::max (block, 1)), r (l.size());
  1290. block = std::max (1, block);
  1291. int n0 = 0;
  1292. while (n0 < length)
  1293. {
  1294. for (std::size_t i = 0; i < notes.size(); ++i)
  1295. {
  1296. if (notes[i].start == n0)
  1297. plugin->noteOn (notes[i].key, notes[i].initVol, notes[i].finalVol, notes[i].finalPan, notes[i].pitchCents);
  1298. if (notes[i].release == n0)
  1299. plugin->noteOff (std::clamp (notes[i].key, 0, 127));
  1300. }
  1301. auto ln = std::min (block, length - n0);
  1302. for (auto e : evs)
  1303. if (n0 < e && e < n0 + ln)
  1304. ln = e - n0;
  1305. std::fill (l.begin(), l.begin() + ln, 0.0f);
  1306. std::fill (r.begin(), r.begin() + ln, 0.0f);
  1307. plugin->render (l.data(), r.data(), ln, songPos >= 0.0 ? songPos + (double) n0 * bpm / (60.0 * sampleRate) : 0.0);
  1308. for (int j = 0; j < ln; ++j)
  1309. {
  1310. out[2 * (std::size_t) (n0 + j)] = l[(std::size_t) j];
  1311. out[2 * (std::size_t) (n0 + j) + 1] = r[(std::size_t) j];
  1312. }
  1313. n0 += ln;
  1314. }
  1315. return out;
  1316. }
  1317. } // namespace minisynth
  1318. } // namespace lynx