FlGenerators.cpp 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481
  1. // GMS, Ogun/Autogun, Sakura and Fruity DrumSynth Live approximated by the built-in synth (or by a
  2. // drum sample). Formats and formulas in docs/analise/REA_rodada12.md (clean-room).
  3. #include "core/FlSynths.h"
  4. #include "core/Inflate.h"
  5. #include <algorithm>
  6. #include <array>
  7. #include <cctype>
  8. #include <cmath>
  9. #include <cstring>
  10. #include <string>
  11. #include <vector>
  12. namespace lynx
  13. {
  14. namespace
  15. {
  16. constexpr double pi = 3.141592653589793;
  17. std::uint32_t u32At (const std::uint8_t* d, std::size_t offset)
  18. {
  19. std::uint32_t v = 0;
  20. std::memcpy (&v, d + offset, 4);
  21. return v;
  22. }
  23. void setPitch (SynthOscillator& osc, double semitones)
  24. {
  25. if (! std::isfinite (semitones))
  26. semitones = 0.0;
  27. while (semitones < -47.0)
  28. semitones += 12.0;
  29. while (semitones > 47.0)
  30. semitones -= 12.0;
  31. const auto whole = (int) std::lround (semitones);
  32. osc.octave = std::clamp (whole / 12, -3, 3);
  33. osc.semitones = std::clamp (whole - osc.octave * 12, -11, 11);
  34. osc.detune = (float) std::clamp ((semitones - whole) * 100.0 + osc.detune, -100.0, 100.0);
  35. }
  36. std::string lower (std::string s)
  37. {
  38. for (auto& ch : s)
  39. ch = (char) std::tolower ((unsigned char) ch);
  40. return s;
  41. }
  42. // ---- GMS ----
  43. // LYNX waveform from the GMS .wav name (§1.4); `octaveUp` for waves with a dominant 2nd harmonic
  44. Waveform gmsWave (const std::string& path, bool& octaveUp)
  45. {
  46. auto name = path.substr (path.find_last_of ("\\/") == std::string::npos ? 0 : path.find_last_of ("\\/") + 1);
  47. if (const auto dot = name.find_last_of ('.'); dot != std::string::npos)
  48. name.resize (dot);
  49. name = lower (name);
  50. octaveUp = name == "digital" || name == "double spike" || name == "devils horn" || name == "liquid";
  51. if (name.empty() || name == "sine" || name == "keys")
  52. return Waveform::sine;
  53. if (name == "triangle" || name == "smooth sub" || name == "rhodes" || name == "string")
  54. return Waveform::triangle;
  55. if (name.rfind ("square", 0) == 0 || name == "digital")
  56. return Waveform::square;
  57. return Waveform::saw;
  58. }
  59. // GMS ladder cutoff in Hz for u = 0..1 (table 2^(9.77u), pole at 4× 44.1 kHz)
  60. double gmsCutoffHz (double u)
  61. {
  62. const auto g = 0.0005 * std::pow (2.0, 9.7734 * std::clamp (u, 0.0, 0.999));
  63. return std::clamp (-std::log (1.0 - g) * 4.0 * 44100.0 / (2.0 * pi), 20.0, 20000.0);
  64. }
  65. int truncf32 (float x) { return (int) x; }
  66. // ---- Ogun's timbre engine (REA_rodada24 §1) ----
  67. // IPP-style uniform generator (§1.3): subtract-with-borrow + congruential sequence, our own implementation
  68. std::vector<float> ogunUniform (int count, float lo, float hi, std::int32_t seed)
  69. {
  70. constexpr std::uint32_t a = 69069u, c = 0x3c6ef373u;
  71. const auto s = (std::uint32_t) seed;
  72. std::uint32_t e3 = (s * a + c) * a + c, e2 = s * a + c, e1 = s; // e[k−3], e[k−2], e[k−1]
  73. std::uint32_t l = 0x436cbae9u;
  74. std::int32_t borrow = -1;
  75. const auto scale = (double) (hi - lo) * std::ldexp (1.0, -32);
  76. const auto offset = (double) (lo + hi) * 0.5;
  77. std::vector<float> out ((std::size_t) std::max (0, count));
  78. for (auto& o : out)
  79. {
  80. auto v = (std::int32_t) (e2 - e3 + (std::uint32_t) borrow);
  81. borrow = v < 0 ? -1 : 0;
  82. if (v < 0)
  83. v = (std::int32_t) ((std::uint32_t) v - 18u);
  84. e3 = e2;
  85. e2 = e1;
  86. e1 = (std::uint32_t) v;
  87. l = l * a + c;
  88. o = (float) ((double) (std::int32_t) ((std::uint32_t) v + l) * scale + offset);
  89. }
  90. return out;
  91. }
  92. // 32-bit integer mix used for the seeds (§1.4)
  93. std::int32_t ogunMix (std::int32_t value, std::uint32_t k1)
  94. {
  95. const auto a = (std::uint32_t) value;
  96. std::uint32_t u6 = (0u - a - k1) ^ (a << 8);
  97. std::uint32_t u7 = (0x1eefu - a - u6) ^ (u6 >> 13);
  98. std::uint32_t u5 = (a - u6 - u7) ^ (u7 >> 12);
  99. u6 = (u6 - u7 - u5) ^ (u5 << 16);
  100. u7 = (u7 - u5 - u6) ^ (u6 >> 5);
  101. u5 = (u5 - u6 - u7) ^ (u7 >> 3);
  102. u6 = (u6 - u7 - u5) ^ (u5 << 10);
  103. u6 = (u7 - u5 - u6) ^ (u6 >> 15);
  104. const auto r = (std::int32_t) u6;
  105. return r == INT32_MIN ? INT32_MAX : std::abs (r);
  106. }
  107. struct OgunPoint
  108. {
  109. double dx = 0.0, y = 0.0;
  110. float tension = 0.0f;
  111. int mode = 0;
  112. };
  113. using OgunEnvelope = std::vector<OgunPoint>;
  114. // The state's envelopes (`i32 type, i32 version 3, i32 n`, n × 24 B points, 20 B trailer), in order
  115. std::vector<OgunEnvelope> ogunEnvelopes (const std::vector<std::uint8_t>& body)
  116. {
  117. std::vector<OgunEnvelope> out;
  118. auto i32 = [&] (std::size_t at) { std::int32_t v; std::memcpy (&v, body.data() + at, 4); return v; };
  119. std::size_t i = 0x110;
  120. while (i + 12 <= body.size())
  121. {
  122. const auto kind = i32 (i), version = i32 (i + 4), n = i32 (i + 8);
  123. if (kind >= 0 && kind < 64 && version == 3 && n >= 1 && n <= 70000 && i + 12 + (std::size_t) n * 24 + 20 <= body.size())
  124. {
  125. OgunEnvelope env;
  126. auto ok = true;
  127. auto j = i + 12;
  128. for (int k = 0; k < n && ok; ++k, j += 24)
  129. {
  130. OgunPoint p;
  131. std::memcpy (&p.dx, body.data() + j, 8);
  132. std::memcpy (&p.y, body.data() + j + 8, 8);
  133. std::memcpy (&p.tension, body.data() + j + 16, 4);
  134. p.mode = body[j + 20];
  135. ok = std::isfinite (p.dx) && std::isfinite (p.y) && p.dx >= -1e-9 && p.dx <= 1e6 && std::abs (p.y) < 1e6 && std::abs (p.tension) <= 1.0001f;
  136. env.push_back (p);
  137. }
  138. if (ok)
  139. {
  140. out.push_back (std::move (env));
  141. i = j + 20;
  142. continue;
  143. }
  144. }
  145. ++i;
  146. }
  147. return out;
  148. }
  149. // Segment shape t → 0..1 of FL's envelope library (REA_rodada23 §1.2). Modes 1 and 10 (not transcribed) are linear.
  150. double ogunSegment (double t, int mode, double tension)
  151. {
  152. const auto sign = tension > 0.0 ? 1 : tension < 0.0 ? -1 : 0;
  153. auto count = [&] { return std::round ((std::pow (1000001.0, 1.0 - 0.6 * std::abs (tension)) - 1.0) * 0.001); };
  154. switch (mode)
  155. {
  156. case 0:
  157. {
  158. if (tension == 0.0)
  159. return t;
  160. const auto k = std::pow (1000001.0, std::abs (tension)) - 1.0;
  161. const auto l = std::log (k + 1.0);
  162. return tension > 0.0 ? 1.0 - (std::exp ((1.0 - t) * l) - 1.0) / k : (std::exp (t * l) - 1.0) / k;
  163. }
  164. case 2: return 0.0;
  165. case 5:
  166. {
  167. const auto c10 = 2.0 * (count() + 1.0);
  168. return (double) ((long long) std::round (t * c10 - (tension < 0.0 ? -0.5 : 0.5)) & 1);
  169. }
  170. case 6:
  171. {
  172. const auto c10 = count() + 0.5;
  173. if (sign > 0 && count() == 0.0)
  174. return t;
  175. if (sign < 0)
  176. return (std::sin ((t * c10 + 0.75) * 2.0 * pi) + 1.0) * 0.5;
  177. const auto v = t * c10 - 0.5;
  178. const auto r = std::round (v - 0.5);
  179. return std::abs ((v - r) * 2.0 - 1.0);
  180. }
  181. case 7:
  182. {
  183. const auto u = sign > 0 ? 1.0 - t : t;
  184. return t - (std::pow (u, 6.0) - u) * tension;
  185. }
  186. default: return t;
  187. }
  188. }
  189. double ogunEnvelopeAt (const OgunEnvelope& env, double x)
  190. {
  191. if (env.empty())
  192. return 0.0;
  193. double total = 0.0;
  194. for (std::size_t j = 1; j < env.size(); ++j)
  195. total += env[j].dx;
  196. if (total <= 0.0)
  197. total = 1.0;
  198. if (x <= 0.0)
  199. return env[0].y;
  200. double start = 0.0;
  201. for (std::size_t j = 1; j < env.size(); ++j)
  202. {
  203. const auto end = start + env[j].dx / total;
  204. if (x < end || j + 1 == env.size())
  205. {
  206. if (x >= end)
  207. return env[j].y;
  208. const auto t = end > start ? (x - start) / (end - start) : 0.0;
  209. return env[j - 1].y + ogunSegment (t, env[j].mode, env[j].tension) * (env[j].y - env[j - 1].y);
  210. }
  211. start = end;
  212. }
  213. return env.back().y;
  214. }
  215. // Ogun's initial spectrum (§1.5–§1.7) in the "spectral" oscillator. Partial h of an Ogun note of frequency f sounds
  216. // at h·f·2^(7 − P52); the oscillator runs at f·2^o, o = max(−2, 7 − P52), so partial h lands on index h/stride,
  217. // stride = 2^(P52 − 7 + o). With P52 ≤ 9 every partial is an exact index; above, partials are binned (energy) to the
  218. // nearest index. Returns false if the maps cannot be read. `decaySeconds`/`releaseSeconds` = time for the whole
  219. // spectrum to fall 40 dB with the per-partial times (< 0 = no decay).
  220. struct OgunSpectrum
  221. {
  222. std::array<float, SynthSettings::spectrumSize> amplitude {}, phase {};
  223. std::array<float, SynthSettings::spectrumSize> decay {}; // per index, seconds to −60 dB (0 = holds)
  224. std::array<float, SynthSettings::spectrumSize> target {}; // ALT DECAY: level each index settles on
  225. int octave = 0;
  226. double decaySeconds = -1.0, releaseSeconds = -1.0;
  227. };
  228. bool ogunSpectrum (const std::int32_t* p, const std::vector<std::uint8_t>& body, OgunSpectrum& out)
  229. {
  230. const auto envelopes = ogunEnvelopes (body);
  231. if (envelopes.size() != 82 || body.size() < 0xFC)
  232. return false;
  233. const auto& forced = envelopes[78];
  234. const auto& impulseMap = envelopes[79];
  235. const auto& decayMap = envelopes[80];
  236. const auto& releaseMap = envelopes[81];
  237. const bool perNoteSeed = body[0xE0] != 0, logAxis = body[0xE7] != 0, altDecay = body[0xF8] != 0,
  238. normalise = body[0xF9] != 0, invSqrt = body[0xFA] != 0;
  239. std::int32_t pattern[4];
  240. std::memcpy (pattern, body.data() + 0xE8, sizeof (pattern));
  241. const auto richness = std::clamp (p[52], 6, 16);
  242. const auto m = (1 << (richness - 1)) - 1; // partials 1…M
  243. const auto mapLength = std::min (m * 3 / 2, 0x8000);
  244. // map sampling (§1.6): x = i/32767 or log2(i + 1)/15; EQs use (3^(2y) − 1)/2
  245. auto sample = [&] (const OgunEnvelope& env, int length, bool eq, bool sqrtScaled, int patternValue)
  246. {
  247. std::vector<double> v ((std::size_t) length);
  248. for (int i = 0; i < length; ++i)
  249. {
  250. const auto x = (logAxis ? std::log2 (i + 1.0) / 15.0 : i / 32767.0) + 5.96e-8;
  251. auto y = std::clamp (ogunEnvelopeAt (env, x), 0.0, 1.0);
  252. if (eq)
  253. y = y * 2.0 == 1.0 ? 1.0 : (std::pow (3.0, 2.0 * y) - 1.0) / 2.0;
  254. if (sqrtScaled)
  255. y /= std::sqrt (i + 1.0);
  256. if (patternValue > 0 && ((patternValue < 5 && i % (patternValue + 1) == patternValue) || (patternValue >= 5 && i % (patternValue - 2) != 0)))
  257. y = 0.0;
  258. v[(std::size_t) i] = y;
  259. }
  260. return v;
  261. };
  262. const auto forcedOn = std::any_of (forced.begin(), forced.end(), [] (const OgunPoint& pt) { return pt.y != 0.0; });
  263. const auto forcedValues = forcedOn ? sample (forced, m, false, invSqrt, pattern[0]) : std::vector<double> {};
  264. const auto impulse = sample (impulseMap, mapLength, true, invSqrt, pattern[1]);
  265. const auto decayEq = sample (decayMap, mapLength, true, invSqrt && altDecay, pattern[2]);
  266. const auto releaseEq = sample (releaseMap, mapLength, true, false, pattern[3]);
  267. auto mapAt = [] (const std::vector<double>& v, int i) { return v.empty() ? 1.0 : v[(std::size_t) std::min (i, (int) v.size() - 1)]; };
  268. // articulators at their neutral values (§1.8): art6 = art7 = art10 = 1, art9 = art11 = art12 = 0
  269. const auto fullness = std::clamp (p[8] / 1000.0, -1.0, 1.0);
  270. const auto shape = (std::pow (10000001.0, std::abs (fullness)) - 1.0) * 0.01 * (fullness > 0.0 ? -1.0 : fullness < 0.0 ? 1.0 : 0.0);
  271. const auto morph = p[9] / 1000.0;
  272. const auto preDecay = std::max (0.001, p[5] / 1000.0);
  273. auto seedOf = [] (std::int32_t v) { return v - 1 < 0 ? -1 : ogunMix (v - 0x20cf, 0x1cfc); };
  274. // Seed 1 per key: key 60 (C5) is used; Seed 2 = "Random" draws a new seed on every note in FL — LYNX keeps one
  275. // fixed draw (counter 0)
  276. const auto seed1 = perNoteSeed ? ogunMix (p[10] + 60 - 0x1f88, 0x1e42) : seedOf (p[10]);
  277. const auto seed2 = p[11] - 1 < 0 ? ogunMix (0 - 0x200e, 0x1dbc) : seedOf (p[11]);
  278. auto weights = [&] (std::int32_t seed)
  279. {
  280. auto u = ogunUniform (m, 0.0f, 1.0f, seed);
  281. std::vector<double> g ((std::size_t) m);
  282. for (int i = 0; i < m; ++i)
  283. {
  284. const double x = u[(std::size_t) i];
  285. if (shape == 0.0)
  286. g[(std::size_t) i] = x;
  287. else if (shape > 0.0)
  288. g[(std::size_t) i] = (std::pow (1.0 + shape, x) - 1.0) / shape;
  289. else
  290. g[(std::size_t) i] = ((1.0 - shape) - std::pow (1.0 - shape, 1.0 - x)) / -shape;
  291. }
  292. return g;
  293. };
  294. std::vector<double> b ((std::size_t) m, 0.0);
  295. if (morph != 0.0)
  296. {
  297. const auto g = weights (seed2);
  298. for (int i = 0; i < m; ++i)
  299. b[(std::size_t) i] += morph * g[(std::size_t) i];
  300. }
  301. if (morph < 1.0)
  302. {
  303. const auto g = seed1 < 0 ? std::vector<double> ((std::size_t) m, 1.0) : weights (seed1);
  304. for (int i = 0; i < m; ++i)
  305. b[(std::size_t) i] += (1.0 - morph) * g[(std::size_t) i];
  306. }
  307. for (int i = 0; i < m; ++i)
  308. {
  309. auto& w = b[(std::size_t) i];
  310. w = std::max (0.0, w);
  311. if (forcedOn)
  312. w = 1.0 - forcedValues[(std::size_t) i] * (1.0 - w);
  313. }
  314. // pre-decayed amplitudes and RMS normalisation (§1.7)
  315. std::vector<double> d ((std::size_t) m);
  316. double sumD = 0.0;
  317. for (int i = 0; i < m; ++i)
  318. {
  319. d[(std::size_t) i] = std::pow (0.01, 1.0 / (b[(std::size_t) i] / preDecay + 0.001));
  320. sumD += d[(std::size_t) i] * d[(std::size_t) i];
  321. }
  322. const auto rms = std::sqrt (sumD / m);
  323. if (rms <= 0.0)
  324. return false;
  325. auto gain = 1.0;
  326. if (normalise)
  327. {
  328. auto mapRms = [&] (const std::vector<double>& v) { double s = 0.0; for (int i = 0; i < m; ++i) s += v[(std::size_t) i] * v[(std::size_t) i]; return std::sqrt (s / m); };
  329. auto r = mapRms (impulse);
  330. if (altDecay)
  331. r = std::max (r, mapRms (decayEq));
  332. if (r > 5.96e-8)
  333. gain = 0.5 / r;
  334. }
  335. int first = m, last = -1;
  336. for (int i = 0; i < (int) impulse.size(); ++i)
  337. if (impulse[(std::size_t) i] > 5.96e-8)
  338. first = std::min (first, i), last = i;
  339. const auto theta = ogunUniform (m, 0.0f, 6.2831855f, 3); // fixed phase table (§1.2)
  340. const auto decayKnob = p[6] >= 10000 ? -1.0 : ((std::pow (21.0, std::clamp (p[6], 0, 10000) / 10000.0) - 1.0) * 997.5 + 50.0) / 1000.0;
  341. const auto releaseKnob = p[7] >= 10000 ? 20.0 : ((std::pow (21.0, std::clamp (p[7], 0, 10000) / 10000.0) - 1.0) * 997.5 + 50.0) / 1000.0;
  342. out.octave = std::max (-2, 7 - richness);
  343. const auto stride = 1 << (richness - 7 + out.octave);
  344. std::array<double, SynthSettings::spectrumSize> energy {}, strongest {}, weightedTau {}, targetEnergy {};
  345. std::vector<double> amp ((std::size_t) m, 0.0);
  346. for (int i = 0; i < m; ++i)
  347. {
  348. // ALT DECAY (REA_rodada26 §1.3): every partial moves from its impulse level towards Y = the same law with the
  349. // Decay EQ, X_k = Y + (A₀ − Y)·(1 − c)^k; it settles on Y instead of fading out
  350. if (altDecay && decayKnob >= 0.0)
  351. if (const auto index = (int) std::lround ((i + 1.0) / stride); index >= 1 && index <= SynthSettings::spectrumSize)
  352. {
  353. const auto y = 2.0 / std::sqrt ((double) m) * d[(std::size_t) i] * gain / rms * mapAt (decayEq, i);
  354. targetEnergy[(std::size_t) index - 1] += y * y;
  355. if (y > strongest[(std::size_t) index - 1] && (i < first || i > last))
  356. out.phase[(std::size_t) index - 1] = (float) std::fmod (theta[(std::size_t) i] / (2.0 * pi) + 0.25, 1.0);
  357. }
  358. if (i < first || i > last)
  359. continue;
  360. const auto a = 2.0 / std::sqrt ((double) m) * d[(std::size_t) i] * gain / rms * mapAt (impulse, i);
  361. amp[(std::size_t) i] = a;
  362. const auto index = (int) std::lround ((i + 1.0) / stride);
  363. if (index < 1 || index > SynthSettings::spectrumSize)
  364. continue;
  365. const auto k = (std::size_t) index - 1;
  366. energy[k] += a * a;
  367. if (decayKnob >= 0.0) // τ_h = (t − 0.025)·B·E_dec + 0.025 to −40 dB (§1.7)
  368. weightedTau[k] += a * a * std::max (0.001, (decayKnob - 0.025) * b[(std::size_t) i] * mapAt (decayEq, i) + 0.025);
  369. if (a > strongest[k])
  370. {
  371. strongest[k] = a;
  372. out.phase[k] = (float) std::fmod (theta[(std::size_t) i] / (2.0 * pi) + 0.25, 1.0);
  373. }
  374. }
  375. for (std::size_t k = 0; k < energy.size(); ++k)
  376. {
  377. out.amplitude[k] = (float) (std::sqrt (energy[k]) * pi / 2.0); // physical level (round 23 convention)
  378. if (altDecay && decayKnob >= 0.0)
  379. {
  380. // the gap to Y falls 40 dB in max(0, t_dec − 0.025) s for every partial (per-frame c = 1 − 0.01^(1/T))
  381. out.target[k] = (float) (std::sqrt (targetEnergy[k]) * pi / 2.0);
  382. if (energy[k] > 0.0 || targetEnergy[k] > 0.0)
  383. out.decay[k] = (float) std::min (60.0, 1.5 * std::max (0.001, decayKnob - 0.025));
  384. }
  385. else if (energy[k] > 0.0 && decayKnob >= 0.0)
  386. out.decay[k] = (float) std::min (60.0, 1.5 * weightedTau[k] / energy[k]); // −40 dB → −60 dB
  387. }
  388. // time for the summed energy to fall 40 dB when partial h falls 40 dB in τ_h = (t − 0.025)·B·E + 0.025
  389. auto overall = [&] (double knob, const std::vector<double>& eq)
  390. {
  391. std::vector<std::pair<double, double>> parts;
  392. double total = 0.0;
  393. for (int i = 0; i < m; ++i)
  394. if (amp[(std::size_t) i] > 0.0)
  395. {
  396. const auto tau = std::max (0.001, (knob - 0.025) * b[(std::size_t) i] * mapAt (eq, i) + 0.025);
  397. parts.emplace_back (amp[(std::size_t) i] * amp[(std::size_t) i], tau);
  398. total += parts.back().first;
  399. }
  400. if (total <= 0.0)
  401. return knob;
  402. double lo = 0.0, hi = 60.0;
  403. for (int it = 0; it < 50; ++it)
  404. {
  405. const auto t = (lo + hi) / 2.0;
  406. double e = 0.0;
  407. for (const auto& [a2, tau] : parts)
  408. e += a2 * std::pow (10.0, -4.0 * t / tau);
  409. (e > total * 1e-4 ? lo : hi) = t;
  410. }
  411. return hi;
  412. };
  413. out.decaySeconds = decayKnob < 0.0 ? -1.0 : overall (decayKnob, decayEq);
  414. out.releaseSeconds = overall (releaseKnob, releaseEq);
  415. return true;
  416. }
  417. } // namespace
  418. bool synthFromGms (const std::vector<std::uint8_t>& state, double bpm, SynthSettings& synth, float& gain)
  419. {
  420. // "SSLF" + size + the .gmsynth preset
  421. if (state.size() < 8 || std::memcmp (state.data(), "SSLF", 4) != 0)
  422. return false;
  423. const auto size = (std::size_t) u32At (state.data(), 4);
  424. if (size + 8 > state.size() || size < 4)
  425. return false;
  426. const auto* d = state.data() + 8;
  427. const auto tag = u32At (d, 0);
  428. const bool syn4 = tag == 0x53796E34, syn3 = tag == 0x53796E33;
  429. if (! syn4 && ! syn3)
  430. return false;
  431. const std::size_t paramsAt = syn4 ? 0xE10 : 0xE04;
  432. if (paramsAt + 212 * 4 > size)
  433. return false;
  434. float x[212];
  435. std::memcpy (x, d + paramsAt, sizeof (x));
  436. const auto velocityToCutoff = x[199] == 1.0f; // destination stored as an integer (1 = cutoff)
  437. for (int i = 0; i < 212; ++i)
  438. if (! std::isfinite (x[i]) || x[i] < 0.0f || x[i] > 1.0f)
  439. x[i] = i < 197 ? std::clamp (std::isfinite (x[i]) ? x[i] : 0.0f, 0.0f, 1.0f) : 0.0f;
  440. std::string waves[3];
  441. for (int k = 0; k < 3; ++k)
  442. {
  443. const auto* slot = reinterpret_cast<const char*> (d + 4 + 512 * (std::size_t) k);
  444. waves[k].assign (slot, strnlen (slot, 512));
  445. }
  446. SynthSettings s;
  447. // tuning: global octave, channel Δ and semitones/cents of each oscillator (in float32, truncating)
  448. const auto octave = std::clamp (truncf32 (4.0f * x[44]) - 2, -2, 2);
  449. const auto channel = -truncf32 (24.0f - 48.0f * x[2]);
  450. double semis[3] {};
  451. for (int k = 0; k < 3; ++k)
  452. {
  453. bool up = false;
  454. s.osc[(std::size_t) k].wave = gmsWave (waves[k], up);
  455. semis[k] = 12.0 * octave + channel + truncf32 (72.0f * x[55 + 2 * k] - 36.0f) + truncf32 (100.0f * x[56 + 2 * k] - 50.0f) / 100.0 + (up ? 12.0 : 0.0);
  456. }
  457. // cascaded mix (§1.3)
  458. const double a = (double) x[48] * x[48], b = (double) x[49] * x[49], n = (double) x[45] * x[45];
  459. double level[3] = { (1 - a) * (1 - b) * (1 - n), a * (1 - b) * (1 - n), b * (1 - n) };
  460. for (int k = 0; k < 3; ++k)
  461. {
  462. auto& o = s.osc[(std::size_t) k];
  463. o.detune = 0.0f;
  464. setPitch (o, semis[k]);
  465. o.level = (float) std::clamp (level[k], 0.0, 1.0);
  466. o.pan = 0.0f;
  467. }
  468. // modulation osc2 -> osc1
  469. const auto modKind = std::clamp (truncf32 (2.0f * x[51]), 0, 2);
  470. const auto m = (double) x[50] * x[50];
  471. if (m > 0.0 && modKind == 2) // AM: GMS osc 2 becomes the modulator (LYNX osc 3)
  472. {
  473. auto osc3 = s.osc[2];
  474. auto modulator = s.osc[1];
  475. modulator.level = (float) std::min (1.0, 3.0 * m);
  476. s.am = true;
  477. s.osc[1] = osc3; // GMS osc 3 (if audible) takes the free slot
  478. s.osc[2] = modulator;
  479. }
  480. else if (m > 0.0 && modKind == 1 && level[2] < 0.05) // FM/PM: GMS osc 2 becomes the modulator (LYNX osc 3)
  481. {
  482. auto modulator = s.osc[1];
  483. modulator.level = 1.0f;
  484. modulator.pan = 0.0f;
  485. s.fm = (float) std::min (8.0, 3.75 * m); // osc 1 phase receives osc2·15·m quarter cycles
  486. s.osc[2] = modulator;
  487. if (level[1] < 0.05) // GMS osc 2 was only modulating
  488. s.osc[1].level = 0.0f;
  489. }
  490. else if (m > 0.0 && modKind == 0) // hard sync: a higher, richer osc1
  491. {
  492. s.osc[0].wave = Waveform::saw;
  493. setPitch (s.osc[0], semis[0] + 12.0 * std::log2 (1.0 + 3.0 * m));
  494. }
  495. // noise in an empty slot
  496. if (n > 0.05)
  497. for (auto& o : s.osc)
  498. if (o.level < 0.05f && ! ((s.am || s.fm > 0.0f) && &o == &s.osc[2]))
  499. {
  500. o = { Waveform::noise, 0, 0.0f, (float) std::min (1.0, n) };
  501. break;
  502. }
  503. // unison: copies of osc 1 in the empty slots
  504. const auto voices = 1 + truncf32 (15.0f * x[41]);
  505. if (voices >= 2)
  506. {
  507. const auto spread = std::max (3.0, 600.0 * std::pow (0.4 * x[42], 2.0));
  508. const auto compensation = 1.0 / (1.0 + 0.15 * (voices - 1));
  509. int sign = 1;
  510. for (std::size_t k = 1; k < 3; ++k)
  511. if (s.osc[k].level < 0.05f && ! ((s.am || s.fm > 0.0f) && k == 2))
  512. {
  513. s.osc[k] = s.osc[0];
  514. s.osc[k].detune = (float) std::clamp (s.osc[0].detune + sign * spread, -100.0, 100.0);
  515. s.osc[k].pan = (float) (sign * x[43]);
  516. sign = -sign;
  517. }
  518. for (std::size_t k = 0; k < 3; ++k)
  519. if (! ((s.am || s.fm > 0.0f) && k == 2))
  520. s.osc[k].level = (float) std::clamp (s.osc[k].level * compensation * 1.5, 0.0, 1.0);
  521. }
  522. // amplitude: the output is e², times are to −40 dB
  523. s.attack = (float) std::min (5.0, 1.265 * std::pow ((double) x[4], 3.0));
  524. const auto td = 50.0 * std::pow ((double) x[5], 4.0) + 0.001;
  525. const auto tr = 25.0 * std::pow (0.55 * x[7] + 0.1, 3.0) + 0.001;
  526. s.sustain = x[6] * x[6];
  527. s.decay = s.sustain >= 0.999f ? 0.0f : (float) std::min (20.0, 2.3 * td / 8.82);
  528. s.release = (float) std::clamp (2.3 * tr / 8.82, 0.003, 10.0);
  529. // ladder filter -> LYNX SVF
  530. auto u = (double) x[12];
  531. if (velocityToCutoff) // velocity -> cutoff (with a typical velocity of 0.8)
  532. u += (2.0 * x[198] - 1.0) * 0.8;
  533. u = std::clamp (u, 0.0, 0.999);
  534. const auto filterType = std::clamp (truncf32 (2.0f * x[15]), 0, 2);
  535. s.filterType = filterType == 0 ? 0 : filterType == 1 ? 1 : 2;
  536. s.cutoff = (float) gmsCutoffHz (u);
  537. s.resonance = std::min (0.95f, x[13]);
  538. auto octavesFrom = [&] (double du) { return std::log2 (gmsCutoffHz (u + du) / gmsCutoffHz (u)); };
  539. // AD modulation envelopes
  540. for (int k = 0; k < 2; ++k)
  541. {
  542. auto amount = (double) x[16 + k] * x[16 + k];
  543. if (x[18 + k] >= 0.5f)
  544. amount = -amount;
  545. if (std::abs (amount) < 1e-4)
  546. continue;
  547. const auto attack = std::min (10.0, 7.59 * std::pow ((double) x[20 + k], 5.0));
  548. const auto decay = std::min (20.0, 4.6 * (70.0 * std::pow (0.8 * x[22 + k] + 0.2, 5.0) + 0.001) / 8.82);
  549. const auto dest = std::clamp (truncf32 (3.0f * x[24 + k]), 0, 3);
  550. if (dest == 0 && s.filterEnv.amount == 0.0f)
  551. {
  552. if (amount < 0.0) // closing: the cutoff starts low and "opens" back up
  553. s.filterEnv = { (float) std::clamp (octavesFrom (amount), -10.0, 0.0), (float) attack, 0.0f, (float) decay, 0.0f, s.release };
  554. else
  555. s.filterEnv = { (float) std::clamp (octavesFrom (amount), 0.0, 10.0), (float) attack, 0.0f, (float) decay, 0.0f, s.release };
  556. }
  557. else if (dest == 2 && s.pitchEnv.amount == 0.0f)
  558. s.pitchEnv = { (float) (24.0 * amount), (float) attack, 0.0f, (float) decay, 0.0f, s.release };
  559. }
  560. // LFOs
  561. for (int k = 0; k < 2; ++k)
  562. {
  563. auto amount = (double) x[28 + k] * x[28 + k];
  564. if (x[30 + k] >= 0.5f)
  565. amount = -amount;
  566. if (std::abs (amount) < 1e-4)
  567. continue;
  568. ChannelLfo lfo;
  569. const auto shape = std::clamp (truncf32 (3.0f * x[32 + k]), 0, 3);
  570. lfo.shape = shape == 0 ? 0 : shape == 3 ? 2 : 1;
  571. const auto sync = std::clamp (truncf32 (2.0f * x[36 + k]), 0, 2);
  572. if (sync == 0)
  573. lfo.period = (float) (1.0 / (25.0 * std::pow (1.0 - x[34 + k], 2.0) + 0.01));
  574. else
  575. {
  576. static constexpr double beats[] = { 0.125, 0.25, 0.375, 0.5, 0.75, 1.0, 2.0, 4.0, 8.0 };
  577. lfo.period = (float) (beats[std::clamp (truncf32 (9.0f * x[34 + k]), 0, 8)] * (sync == 2 ? 4.0 : 1.0));
  578. lfo.sync = true;
  579. }
  580. lfo.global = x[26 + k] < 0.5f; // without retrig the phase runs free
  581. // an envelope targeting "LFO" becomes this LFO's fade-in
  582. if (std::clamp (truncf32 (3.0f * x[24 + k]), 0, 3) == 3 && x[16 + k] > 0.0f)
  583. lfo.attack = (float) std::min (10.0, 7.59 * std::pow ((double) x[20 + k], 5.0));
  584. if (lfo.sync && lfo.attack > 0.0f)
  585. lfo.attack = (float) (lfo.attack * std::max (1.0, bpm) / 60.0);
  586. switch (std::clamp (truncf32 (3.0f * x[38 + k]), 0, 3))
  587. {
  588. case 0: lfo.amount = (float) std::clamp (octavesFrom (std::abs (amount)) * (amount < 0 ? -1 : 1), -10.0, 10.0); s.lfo[lfoCutoff] = lfo; break;
  589. case 2: lfo.amount = (float) (12.0 * amount); s.lfo[lfoPitch] = lfo; break;
  590. case 3: lfo.amount = (float) std::abs (amount); s.lfo[lfoVolume] = lfo; break;
  591. default: break; // "modulation": no equivalent
  592. }
  593. }
  594. s.mono = x[40] > 0.0f;
  595. s.porta = x[11] > 0.0f;
  596. if (s.porta)
  597. s.portaBeats = (float) std::clamp (0.52 * (2.0 * std::pow ((double) x[10], 3.0)) * std::max (1.0, bpm) / 60.0, 0.01, 8.0);
  598. if (const auto pan = 2.0f * x[1] - 1.0f; std::abs (pan) > 0.01f)
  599. for (auto& o : s.osc)
  600. o.pan = std::clamp (o.pan + pan, -1.0f, 1.0f);
  601. gain = (float) std::clamp (std::pow (10.0, (80.0 * x[0] - 60.0) / 20.0) * std::pow (10.0, (50.0 * x[8] - 25.0) / 20.0), 0.0, 8.0);
  602. synth = s;
  603. return true;
  604. }
  605. // ---- Ogun / Autogun ----
  606. // LYNX synth resonance 0..1 for a Q (the SVF uses k = 1/Q = 2 − 1.9·res; Q < 0.5 becomes 0)
  607. float synthResonanceForQ (double q)
  608. {
  609. return (float) std::clamp ((2.0 - 1.0 / std::max (q, 1e-3)) / 1.9, 0.0, 1.0);
  610. }
  611. bool synthFromOgun (const std::vector<std::uint8_t>& state, SynthSettings& synth, float& gain)
  612. {
  613. if (state.size() < 8)
  614. return false;
  615. auto version = u32At (state.data(), 0);
  616. if (version > 0xffff)
  617. version >>= 16;
  618. if (version < 14 || version > 19)
  619. return false; // old versions store a reduced block (not used in the current demos)
  620. const auto body = inflateZlib (state.data() + 4, state.size() - 4, false, 8u << 20);
  621. if (! body || body->size() < 64 * 4)
  622. return false;
  623. std::int32_t p[64];
  624. std::memcpy (p, body->data(), sizeof (p));
  625. // timbre knob time: 10000 = infinite
  626. auto seconds = [] (int v) { return v >= 10000 ? -1.0 : ((std::pow (21.0, std::clamp (v, 0, 10000) / 10000.0) - 1.0) * 997.5 + 50.0) / 1000.0; };
  627. SynthSettings s;
  628. const auto fullness = std::clamp (p[8], -1000, 1000);
  629. const auto richness = std::clamp (p[52] - 5, 1, 11);
  630. const auto wave = fullness <= -800 && richness <= 3 ? Waveform::sine : fullness < -300 ? Waveform::triangle : Waveform::saw;
  631. const auto transpose = std::clamp (p[1], -24, 24) + std::clamp (p[2], -50, 50) / 100.0;
  632. // REA_rodada24 §1: Ogun is an inverse-FFT spectral synth; its initial spectrum goes into the "spectral"
  633. // oscillator, with each harmonic's own decay (spectrumDecay, 8 frames per note). Approximations: binned
  634. // partials share an energy-weighted decay, the release is one overall envelope, ALT DECAY's morph towards the
  635. // Decay EQ uses a target per harmonic (REA_rodada26 §1.3), articulators at their neutral values, Seed 2 "Random" = one fixed draw,
  636. // partials of dense spectra (richness > 9) binned onto the nearest harmonic of f/4.
  637. // Without readable maps the old waveform approximation is used.
  638. OgunSpectrum spectrum;
  639. const auto spectral = ogunSpectrum (p, *body, spectrum);
  640. if (spectral)
  641. {
  642. s.spectrum = spectrum.amplitude;
  643. s.spectrumPhase = spectrum.phase;
  644. s.spectrumDecay = spectrum.decay; // each harmonic decays at its own rate (the envelope then holds)
  645. s.spectrumTarget = spectrum.target;
  646. s.osc = { SynthOscillator { Waveform::spectral, 0, 0.0f, 1.0f }, SynthOscillator {}, SynthOscillator {} };
  647. setPitch (s.osc[0], transpose);
  648. s.osc[0].octave = std::clamp (s.osc[0].octave + spectrum.octave, -3, 3);
  649. }
  650. else
  651. {
  652. s.osc = { SynthOscillator { wave, 0, 0.0f, 0.8f }, SynthOscillator {}, SynthOscillator {} };
  653. setPitch (s.osc[0], transpose);
  654. if (fullness > 300) // "metallic" timbre: a partial one octave up
  655. {
  656. s.osc[1] = { Waveform::sine, 0, 0.0f, 0.3f };
  657. setPitch (s.osc[1], transpose + 12.0);
  658. }
  659. }
  660. // spectral: the 40 dB fall of the whole spectrum → LYNX's 60 dB times (×1.5)
  661. // (with the per-harmonic decay in the spectrum, the volume envelope holds)
  662. const auto decay = spectral ? -1.0 : seconds (p[6]);
  663. const auto release = spectral ? 1.5 * spectrum.releaseSeconds : seconds (p[7]);
  664. s.attack = 0.0f;
  665. if (decay < 0.0)
  666. {
  667. s.decay = 0.0f;
  668. s.sustain = 1.0f;
  669. }
  670. else
  671. {
  672. s.decay = (float) std::min (30.0, decay);
  673. s.sustain = 0.0f;
  674. }
  675. s.release = (float) std::clamp (release < 0.0 ? 20.0 : release, 0.005, 30.0); // P7 = 10000 → 20 s (REA_rodada21 §2.2)
  676. if (const auto voices = std::clamp (p[12], 1, 9); voices >= 2)
  677. {
  678. const auto pan = std::clamp (p[13], 0, 128) / 128.0f;
  679. for (std::size_t k = 1; k < 3; ++k)
  680. if (s.osc[k].level == 0.0f)
  681. {
  682. s.osc[k] = s.osc[0];
  683. // detune ±5·(11^(P15/256) − 1) cents (REA_rodada21 §2.4)
  684. const auto spread = (float) (5.0 * (std::pow (11.0, std::clamp (p[15], 0, 256) / 256.0) - 1.0));
  685. s.osc[k].detune = std::clamp (s.osc[0].detune + (k == 1 ? spread : -spread), -100.0f, 100.0f);
  686. s.osc[k].pan = k == 1 ? pan : -pan;
  687. }
  688. for (auto& o : s.osc)
  689. o.level *= 0.6f;
  690. }
  691. // filter: only exists with order > 0
  692. s.cutoff = 20000.0f;
  693. if (const auto order = std::clamp (p[50], 0, 3); order > 0)
  694. {
  695. const auto type = std::clamp (p[49], 0, 3);
  696. const auto u = std::clamp (p[17], 0, 256) / 256.0;
  697. // REA_rodada21 §2.5: fc = 44100·(c + c₀) Hz (ω limited to 2.8495 rad); order = identical cascaded biquads
  698. // (LYNX has only one: approximate slope); LP/HP with Q^(1/order) per stage, BP/BS with width in octaves
  699. double c = 0.0, c0 = 0.0;
  700. if (type == 0)
  701. c = 0.0006646667 * (std::pow (1501.0, u) - 1.0), c0 = 0.003;
  702. else
  703. c = std::min (type == 3 ? 0.6001 : 1.0001, 0.00039993 * (std::pow (1501.0, u) - 1.0)), c0 = 0.0001;
  704. s.filterType = type == 0 ? 0 : type == 1 ? 1 : type == 2 ? 3 : 2;
  705. s.cutoff = (float) std::clamp (44100.0 * (c + c0), 20.0, std::min (20000.0, 2.8495 / (2.0 * 3.141592653589793) * 44100.0));
  706. auto r = std::clamp (p[18], 0, 256) / 256.0;
  707. if (p[51] != 0) // FLAT
  708. r *= (u + 1.0) / 2.0;
  709. double q = 0.707;
  710. if (type == 0 || type == 3)
  711. q = std::pow (r <= 0.0 ? 0.1 : r >= 1.0 ? 50.0 : 0.02495 * (std::pow (2001.0, r) - 1.0) + 0.1, 1.0 / order);
  712. else
  713. {
  714. const auto bw = r <= 0.0 ? 0.01 : r >= 1.0 ? 12.0 : 0.1199 * (std::pow (101.0, r) - 1.0) + 0.01;
  715. q = 1.0 / (2.0 * std::sinh (std::log (2.0) / 2.0 * bw));
  716. }
  717. s.resonance = synthResonanceForQ (q);
  718. }
  719. gain = (float) std::clamp ((std::pow (3.0, std::clamp (p[0], 0, 256) / 128.0) - 1.0) / 2.0, 0.0, 4.0); // (3^(P0/128) − 1)/2
  720. synth = s;
  721. return true;
  722. }
  723. // ---- Sakura ----
  724. std::optional<std::vector<float>> sakuraParams (const std::vector<std::uint8_t>& state)
  725. {
  726. // "SSLF" + size + "Skr1" + 146 floats, raw (index 111 is an integer mode; REA_rodada28 §1.1)
  727. if (state.size() < 12 + 146 * 4 || std::memcmp (state.data(), "SSLF", 4) != 0 || u32At (state.data(), 8) != 0x536B7231)
  728. return std::nullopt;
  729. std::vector<float> p (146);
  730. std::memcpy (p.data(), state.data() + 12, sizeof (float) * 146);
  731. for (std::size_t k = 0; k < 114; ++k) // floats 114…145 are not parameters
  732. if (! std::isfinite (p[k]))
  733. return std::nullopt;
  734. return p;
  735. }
  736. bool synthFromSakura (const std::vector<std::uint8_t>& state, SynthSettings& synth)
  737. {
  738. if (state.size() < 12 + 146 * 4 || std::memcmp (state.data(), "SSLF", 4) != 0 || u32At (state.data(), 8) != 0x536B7231)
  739. return false;
  740. float t[146];
  741. std::memcpy (t, state.data() + 12, sizeof (t));
  742. for (auto& v : t)
  743. v = std::isfinite (v) ? std::clamp (v, 0.0f, 1.0f) : 0.0f;
  744. // Sakura's strings are physical (exciter + waveguide): here they become a saw (string 1) + triangle
  745. // (string 2) — the model swap is an approximation. Confirmed (REA_rodada18 §10): Amp A = 35x⁵ + 0.001 s,
  746. // D = 50x⁵ + 0.001 s and R = 10x⁵ + 0.1 s with poles of time constant T/8.82 (LYNX measures time down to −60 dB:
  747. // ×6.908/8.82), sustain x², Tune trunc(198x − 99)·0.01 semitone, linear String Mix (string 1 ∝ 1 − mix).
  748. // The string decay (feedback d^0.05 per period → T60 ≈ 60/(f·(−log10 d)) s) depends on the
  749. // note: the T60 of key 60 is used (approximation). Hi-Cut (REA_rodada19 §5): 4 first-order poles with
  750. // c = Cutoff² (no envelope); each pole cuts at −fs·ln(1 − c)/2π and the cascade at ≈ 0.435 of that, with
  751. // fs = 48 kHz (the engine's coefficient rate; not confirmed as the render rate). In FL it filters the
  752. // exciter; here, the synth output (2 poles).
  753. SynthSettings s;
  754. const auto mix = t[17];
  755. s.osc = { SynthOscillator { Waveform::saw, 0, 0.0f, 1.0f - mix }, SynthOscillator { Waveform::triangle, 0, 0.0f, mix }, SynthOscillator {} };
  756. const auto tune = std::clamp ((int) (198.0f * t[1] - 99.0f), -99, 99) * 0.01;
  757. setPitch (s.osc[0], tune);
  758. setPitch (s.osc[1], tune);
  759. auto p5 = [] (float x) { return std::pow ((double) x, 5.0); };
  760. constexpr double toLynx = 6.907755 / 8.82;
  761. s.attack = (float) (35.0 * p5 (t[2]) + 0.001);
  762. s.decay = (float) ((50.0 * p5 (t[3]) + 0.001) * toLynx);
  763. s.sustain = t[4] * t[4];
  764. s.release = (float) ((10.0 * p5 (t[5]) + 0.1) * toLynx);
  765. const auto d = std::clamp ((double) t[6], 0.0, 0.999999);
  766. const auto stringT60 = d <= 0.0 ? 0.01 : 60.0 / (261.63 * -std::log10 (d));
  767. if (stringT60 < 30.0 && (s.sustain > 0.0f || stringT60 < s.decay))
  768. {
  769. s.sustain = 0.0f;
  770. s.decay = (float) std::max (0.01, stringT60);
  771. }
  772. s.cutoff = 20000.0f;
  773. if (const auto c = (double) t[29] * t[29]; c < 0.999)
  774. s.cutoff = (float) std::clamp (0.435 * -48000.0 * std::log (1.0 - c) / (2.0 * 3.141592653589793), 20.0, 20000.0);
  775. synth = s;
  776. return true;
  777. }
  778. // ---- Fruity DrumSynth Live ----
  779. std::optional<std::string> drumSynthLiveSound (const std::vector<std::uint8_t>& state)
  780. {
  781. if (state.size() < 9)
  782. return std::nullopt;
  783. const auto version = u32At (state.data(), 0), index = u32At (state.data(), 4);
  784. if (version < 3 || version > 8 || index >= 120)
  785. return std::nullopt;
  786. std::size_t pos = 8;
  787. std::string name;
  788. for (std::uint32_t i = 0; i <= index; ++i)
  789. {
  790. if (pos >= state.size())
  791. return std::nullopt;
  792. const auto len = (std::size_t) state[pos];
  793. if (pos + 1 + len > state.size())
  794. return std::nullopt;
  795. name.assign (reinterpret_cast<const char*> (state.data() + pos + 1), len);
  796. pos += 1 + len;
  797. }
  798. return name.empty() ? std::nullopt : std::optional<std::string> (name);
  799. }
  800. std::vector<std::string> drumSampleCandidates (const std::string& soundName)
  801. {
  802. const auto name = lower (soundName);
  803. const bool is909 = name.find ("909") != std::string::npos;
  804. const std::string first = is909 ? "909" : "808", second = is909 ? "808" : "909";
  805. const std::string root = "%FLStudioData%\\Patches\\Packs\\Drums\\";
  806. auto has = [&] (const char* w) { return name.find (w) != std::string::npos; };
  807. std::vector<std::string> out;
  808. auto both = [&] (const std::string& folder, const std::string& rest909, const std::string& rest808) {
  809. for (const auto& kit : { first, second })
  810. out.push_back (root + folder + "\\" + kit + " " + (kit == "909" ? rest909 : rest808) + ".wav");
  811. };
  812. if (has ("kick"))
  813. both ("Kicks", "Kick", "Kick");
  814. else if (has ("snare"))
  815. both ("Snares", "Snare", "Snare");
  816. else if (has ("rim"))
  817. both ("Snares", "Rim", "Rim");
  818. else if (has ("clap"))
  819. {
  820. out.push_back (root + "Percussion\\909 Clap.wav");
  821. out.push_back ("%FLStudioData%\\Patches\\Packs\\Legacy\\Drums\\Dance\\Basic 808 Clap.wav");
  822. }
  823. else if (has ("hat o"))
  824. both ("Hats", "OH", "OH");
  825. else if (has ("hat"))
  826. both ("Hats", "CH 1", "CH");
  827. else if (has ("ride"))
  828. out.push_back (root + "Cymbals\\909 Ride.wav");
  829. else if (has ("crash"))
  830. both ("Cymbals", "Crash", "Crash");
  831. else if (has ("tom"))
  832. both ("Toms", "Tom", "Tom");
  833. else if (has ("cowbell"))
  834. out.push_back (root + "Percussion\\808 Cowbell.wav");
  835. else if (has ("clave"))
  836. both ("Percussion", "Clav", "Clav");
  837. else if (has ("bongo") || has ("conga"))
  838. out.push_back (root + "Percussion\\808 Conga.wav");
  839. else if (has ("maracas"))
  840. out.push_back (root + "Hats\\808 CH.wav");
  841. return out;
  842. }
  843. // ---- Kepler (REA_rodada13 §2) ----
  844. bool synthFromKepler (const std::vector<std::uint8_t>& state, SynthSettings& synth, float& gain)
  845. {
  846. // u32 0, u32 size, u32 0, u32 9 + "Kepler-1\0", u32 version, u32 n, n floats
  847. if (state.size() < 0x21 + 34 * 4 || u32At (state.data(), 12) != 9 || std::memcmp (state.data() + 16, "Kepler-1", 8) != 0)
  848. return false;
  849. const auto count = (int) u32At (state.data(), 0x1D);
  850. if (count < 34 || count > 64 || 0x21 + (std::size_t) count * 4 > state.size())
  851. return false;
  852. float k[64] {};
  853. std::memcpy (k, state.data() + 0x21, (std::size_t) count * 4);
  854. for (auto& v : k)
  855. v = std::isfinite (v) ? std::clamp (v, 0.0f, 1.0f) : 0.0f;
  856. // engine 11-point tables, interpolated at x·10 (REA_rodada17 §6)
  857. auto table = [] (const double (&t)[11], float x) {
  858. const auto pos = std::clamp ((double) x, 0.0, 1.0) * 10.0;
  859. const auto i = std::min (9, (int) pos);
  860. return t[i] + (t[i + 1] - t[i]) * (pos - i);
  861. };
  862. static constexpr double attackTable[11] = { 0.003, 0.004, 0.013, 0.05, 0.128, 0.243, 0.401, 0.7, 1.3, 2.403, 3.049 };
  863. static constexpr double decayTable[11] = { 0.0015, 0.0027, 0.043, 0.141, 0.328, 0.651, 1.144, 2.053, 3.956, 8.466, 10.124 };
  864. static constexpr double releaseTable[11] = { 0.001, 0.002, 0.02, 0.112, 0.321, 0.572, 1.063, 1.964, 3.38, 6.91, 10.967 };
  865. static constexpr double cutoffTable[11] = { 2.0, 2.4594, 3.3219, 4.3219, 5.6837, 6.9542, 8.543, 10.4717, 12.388, 15.1635, 15.6096 };
  866. static constexpr double envAmountTable[11] = { 0.0, 0.389, 1.681, 2.888, 4.017, 5.039, 6.069, 7.288, 8.475, 8.957, 8.972 };
  867. SynthSettings s;
  868. const auto octave = std::clamp ((int) std::lround (2.0 * k[32]) - 1, -1, 1); // −1, 0, +1
  869. const auto saw = k[14] >= 0.5f, pulse = k[13] >= 0.5f, sub = k[15] >= 0.5f;
  870. s.osc = { SynthOscillator { Waveform::saw, octave, 0.0f, saw ? 1.0f : 0.0f },
  871. SynthOscillator { Waveform::square, octave, 0.0f, pulse ? 1.0f : 0.0f },
  872. SynthOscillator {} };
  873. if (! saw && ! pulse)
  874. s.osc[0].level = 1.0f;
  875. if (k[17] > k[16] * (sub ? 1.0f : 0.0f) && k[17] > 0.05f) // noise louder than the sub
  876. s.osc[2] = { Waveform::noise, 0, 0.0f, k[17] };
  877. else if (sub)
  878. s.osc[2] = { Waveform::square, std::max (-3, octave - 1), 0.0f, std::max (0.05f, k[16]) };
  879. // Env1: attack reaches 1 at T_A (linear in LYNX); Kepler's decay/release are to −20 dB, LYNX's
  880. // to −60 dB (exponential): × 3
  881. s.attack = (float) table (attackTable, k[26]);
  882. s.decay = (float) (3.0 * table (decayTable, k[27]));
  883. s.sustain = k[28];
  884. s.release = (float) std::max (0.003, 3.0 * table (releaseTable, k[29]));
  885. if (k[25] >= 0.5f) // gate-driven VCA
  886. {
  887. s.attack = 0.002f;
  888. s.decay = 0.0f;
  889. s.sustain = 1.0f;
  890. s.release = 0.01f;
  891. }
  892. s.cutoff = (float) std::clamp (std::pow (2.0, table (cutoffTable, k[19])), 20.0, 20000.0);
  893. s.resonance = std::min (0.95f, k[20]);
  894. if (const auto octaves = table (envAmountTable, k[22]); octaves > 0.01)
  895. {
  896. const auto sign = k[21] >= 0.5f ? -1.0f : 1.0f; // polarity
  897. s.filterEnv = { sign * (float) octaves, s.attack, 0.0f, s.decay, s.sustain, s.release };
  898. }
  899. // LFO1 (REA_rodada17 §6, rodada18 §7, rodada19 §3): a single, nearly sinusoidal global LFO, value ±1;
  900. // rate 21.739·2^(−T(x)) Hz; vibrato ±A(k10) octaves and cutoff ±A_c(k23) octaves (peaks); delay = linear
  901. // ramp of D(k7) s. The ×10 "Range" only exists on the Kepler Exo panel (left off here); BPM Sync
  902. // (k6) was not read. Chorus (panel 30): mode trunc(3x + 0.5) = Off / I / II / I+II, FL's chain (REA_rodada26 §3).
  903. static constexpr double lfoRateTable[11] = { 7.4422, 5.8074, 4.3499, 3.6563, 3.1131, 2.6712, 2.0463, 1.3093, 0.8515, 0.2838, 0.0 };
  904. static constexpr double vibratoTable[11] = { 0, 0.00116, 0.00813, 0.01506, 0.02196, 0.02882, 0.05259, 0.07819, 0.12057, 0.17728, 0.21388 };
  905. static constexpr double lfoCutoffTable[11] = { 0, 0.0914, 0.38038, 0.662, 0.96846, 1.23732, 1.48249, 1.85735, 2.27554, 2.66441, 2.82 };
  906. static constexpr double lfoDelayTable[11] = { 0, 0.229, 0.447, 0.547, 0.833, 1.0, 2.074, 4.775, 5.612, 6.774, 6.706 };
  907. ChannelLfo lfo;
  908. s.chorus = std::clamp ((int) (3.0f * k[30] + 0.5f), 0, 3);
  909. lfo.period = (float) (1.0 / (21.739 * std::exp2 (-table (lfoRateTable, k[5]))));
  910. lfo.attack = (float) table (lfoDelayTable, k[7]);
  911. lfo.global = true;
  912. if (const auto oct = table (vibratoTable, k[10]); oct > 1e-4)
  913. {
  914. s.lfo[lfoPitch] = lfo;
  915. s.lfo[lfoPitch].amount = (float) (12.0 * oct);
  916. }
  917. if (const auto oct = table (lfoCutoffTable, k[23]); oct > 1e-3)
  918. {
  919. s.lfo[lfoCutoff] = lfo;
  920. s.lfo[lfoCutoff].amount = (float) oct;
  921. }
  922. // Main Volume: m(v) = 0.34968v − 0.32754v² + 1.39229v³ (v = 1 -> 0 dB)
  923. const auto v = (double) k[33];
  924. gain = (float) std::clamp (0.34968 * v - 0.32754 * v * v + 1.39229 * v * v * v, 0.0, 2.0);
  925. synth = s;
  926. return true;
  927. }
  928. // ---- Wave Traveller (§4): the sample and root note ----
  929. std::optional<std::pair<std::string, int>> waveTravellerSample (const std::vector<std::uint8_t>& state)
  930. {
  931. if (state.size() < 24 || u32At (state.data(), 0) != 1000)
  932. return std::nullopt;
  933. const auto root = (int) u32At (state.data(), 12);
  934. const auto length = (std::size_t) u32At (state.data(), 16);
  935. if (length == 0 || length > 4096 || 20 + length > state.size())
  936. return std::nullopt;
  937. std::string path (reinterpret_cast<const char*> (state.data() + 20), length);
  938. path.resize (strnlen (path.c_str(), path.size()));
  939. if (path.empty())
  940. return std::nullopt;
  941. return std::make_pair (path, std::clamp (root, 0, 127));
  942. }
  943. // ---- FLEX (§1.1): only the plugin state (the packs are protected and are not opened) ----
  944. std::optional<std::pair<std::string, std::string>> flexPresetName (const std::vector<std::uint8_t>& state)
  945. {
  946. if (state.size() < 0x411 + 1024 || u32At (state.data(), 0) != 1)
  947. return std::nullopt;
  948. auto text = [&] (std::size_t offset) {
  949. const auto* p = reinterpret_cast<const char*> (state.data() + offset);
  950. return std::string (p, strnlen (p, 1024));
  951. };
  952. auto pack = text (0x10), preset = text (0x411);
  953. if (preset.empty() && pack.empty())
  954. return std::nullopt;
  955. return std::make_pair (pack, preset);
  956. }
  957. // ---- BooBass (REA_rodada10 §5): bass with Bass/Mid/Treble ----
  958. bool synthFromBooBass (const std::vector<std::uint8_t>& state, SynthSettings& synth)
  959. {
  960. if (state.size() < 16 || u32At (state.data(), 0) != 1)
  961. return false;
  962. auto knob = [&] (std::size_t i) { return std::clamp ((int) u32At (state.data(), 4 + 4 * i), 0, 65535) / 65535.0; };
  963. const auto bass = knob (0), mid = knob (1), treble = knob (2);
  964. // REA_rodada18 §11: BooBass's sound is a sample (attack + loop) that is not in the project data;
  965. // here the source is a saw one octave down with a decay (approximation). The three knobs are the confirmed
  966. // 3-band EQ: below 0.1 the band is muted; Bass 10^((12x − 12)/20), Mid 10^((10x − 10)/20),
  967. // Treble 10^((12x − 9)/20). The 2nd stage (low-end saturation, ×3, limiter) is left out.
  968. auto band = [] (double x, double range, double top) { return x < 0.1 ? 0.0f : (float) std::pow (10.0, (range * x - range + top) / 20.0); };
  969. SynthSettings s;
  970. s.osc = { SynthOscillator { Waveform::saw, -1, 0.0f, 1.0f }, SynthOscillator {}, SynthOscillator {} };
  971. s.cutoff = 20000.0f;
  972. s.bandGain = { band (bass, 12.0, 0.0), band (mid, 10.0, 0.0), band (treble, 12.0, 3.0) };
  973. s.attack = 0.002f;
  974. s.decay = 0.6f;
  975. s.sustain = 0.5f;
  976. s.release = 0.08f;
  977. synth = s;
  978. return true;
  979. }
  980. // ---- Drumpad (§6): only the patch name; the physical model is not reproduced ----
  981. std::optional<std::string> drumpadPatchName (const std::vector<std::uint8_t>& state)
  982. {
  983. if (state.size() < 0x40 || std::memcmp (state.data(), "SSLF", 4) != 0 || std::memcmp (state.data() + 8, "3PMD", 4) != 0)
  984. return std::nullopt;
  985. const auto* p = reinterpret_cast<const char*> (state.data() + 12);
  986. std::string name (p, strnlen (p, 0x30));
  987. if (name.empty())
  988. return std::nullopt;
  989. return name;
  990. }
  991. std::optional<std::array<float, 38>> drumpadParams (const std::vector<std::uint8_t>& state)
  992. {
  993. // "SSLF" + size + "3PMD" + 128 B name + 38 floats (parameters 0…37 in order), REA_rodada18 §12
  994. if (state.size() < 140 + 38 * 4 || std::memcmp (state.data(), "SSLF", 4) != 0 || std::memcmp (state.data() + 8, "3PMD", 4) != 0)
  995. return std::nullopt;
  996. std::array<float, 38> p {};
  997. std::memcpy (p.data(), state.data() + 140, sizeof (float) * 38);
  998. for (auto& v : p)
  999. if (! std::isfinite (v))
  1000. return std::nullopt;
  1001. return p;
  1002. }
  1003. SynthSettings drumToneForName (const std::string& patchName)
  1004. {
  1005. const auto name = lower (patchName);
  1006. auto has = [&] (const char* w) { return name.find (w) != std::string::npos; };
  1007. // "generic" drum: sine with a pitch drop + a little noise for the attack
  1008. SynthSettings s;
  1009. s.osc = { SynthOscillator { Waveform::sine, 0, 0.0f, 1.0f }, SynthOscillator { Waveform::noise, 0, 0.0f, 0.12f }, SynthOscillator {} };
  1010. s.attack = 0.0f;
  1011. s.decay = 0.3f;
  1012. s.sustain = 0.0f;
  1013. s.release = 0.1f;
  1014. s.cutoff = 6000.0f;
  1015. s.pitchEnv = { 5.0f, 0.0f, 0.0f, 0.06f, 0.0f, 0.05f };
  1016. if (has ("war") || has ("taiko") || has ("lo") || has ("floor"))
  1017. {
  1018. s.osc[0].octave = -1;
  1019. s.decay = 0.6f;
  1020. }
  1021. if (has ("bongo") || has ("hi "))
  1022. {
  1023. s.osc[0].octave = 1;
  1024. s.decay = 0.15f;
  1025. }
  1026. if (has ("conga"))
  1027. s.decay = 0.25f;
  1028. if (has ("wood") || has ("block") || has ("clave") || has ("rim"))
  1029. {
  1030. s.osc[0] = { Waveform::triangle, 1, 0.0f, 1.0f };
  1031. s.osc[1].level = 0.05f;
  1032. s.decay = 0.06f;
  1033. s.pitchEnv.amount = 2.0f;
  1034. }
  1035. return s;
  1036. }
  1037. // ---- PoiZone, BassDrum, Toxic Biohazard (REA_rodada15 §12) ----
  1038. namespace
  1039. {
  1040. bool sslfFloats (const std::vector<std::uint8_t>& state, const char* tag, std::size_t offset, float* out, int count)
  1041. {
  1042. if (state.size() < offset + (std::size_t) count * 4 || std::memcmp (state.data(), "SSLF", 4) != 0 || std::memcmp (state.data() + 8, tag, 4) != 0)
  1043. return false;
  1044. std::memcpy (out, state.data() + offset, (std::size_t) count * 4);
  1045. for (int i = 0; i < count; ++i)
  1046. out[i] = std::isfinite (out[i]) ? std::clamp (out[i], 0.0f, 1.0f) : 0.0f;
  1047. return true;
  1048. }
  1049. double ms4 (double lo, double span, float x) { return (lo + span * std::pow ((double) x, 4.0)) / 1000.0; }
  1050. } // namespace
  1051. bool synthFromPoiZone (const std::vector<std::uint8_t>& state, SynthSettings& synth, float& gain)
  1052. {
  1053. float p[74];
  1054. if (! sslfFloats (state, "4reV", 12, p, 74))
  1055. return false;
  1056. SynthSettings s;
  1057. const auto transpose = std::floor (48.0f * p[17]) - 24.0 + (200.0 * p[16] - 100.0) / 100.0;
  1058. const auto waveA = p[0] > 0.0f ? Waveform::square : Waveform::saw;
  1059. const auto waveB = p[4] > 0.0f ? Waveform::square : Waveform::saw;
  1060. s.osc[0] = { waveA, 0, 0.0f, std::clamp (1.0f - p[8], 0.0f, 1.0f) };
  1061. s.osc[1] = { waveB, 0, (float) (50.0 * p[7]), std::clamp (p[8], 0.0f, 1.0f) };
  1062. s.osc[2] = { Waveform::noise, 0, 0.0f, p[9] * 0.5f };
  1063. setPitch (s.osc[0], transpose);
  1064. setPitch (s.osc[1], transpose + std::floor (48.0f * p[6]) - 24.0);
  1065. s.osc[1].detune = (float) std::clamp (s.osc[1].detune + 50.0 * p[7], -100.0, 100.0);
  1066. s.attack = (float) ms4 (1.0, 4999.0, p[22]);
  1067. s.decay = (float) ms4 (1.0, 19999.0, p[23]);
  1068. s.sustain = p[24];
  1069. s.release = (float) ms4 (15.0, 9985.0, p[25]);
  1070. // cutoff (REA_rodada17 §8): 2^(10·v + 6) Hz with v = 1.1·x clipped at 0.91 (64 Hz … 35 kHz)
  1071. s.cutoff = (float) std::clamp (std::pow (2.0, 10.0 * std::min (0.91, 1.1 * (double) p[18]) + 6.0), 20.0, 20000.0);
  1072. s.resonance = std::min (0.95f, p[19]);
  1073. s.filterType = std::clamp ((int) (2.0f * p[66]), 0, 2) == 0 ? 0 : (int) (2.0f * p[66]) == 1 ? 1 : 2;
  1074. // filter envelope on the cutoff: ±10·a² octaves, a = 2x − 1 (REA_rodada17 §8)
  1075. if (const auto a = 2.0f * p[10] - 1.0f; (int) (4.0f * p[65]) == 0 && std::abs (a) > 0.01f)
  1076. s.filterEnv = { (a < 0.0f ? -10.0f : 10.0f) * a * a, (float) ms4 (5.0, 49995.0, p[11]), 0.0f, (float) ms4 (5.0, 49995.0, p[12]), p[13],
  1077. (float) ms4 (5.0, 49995.0, p[14]) };
  1078. if (std::abs (p[26] - 0.5f) > 0.01f && p[28] > 0.0f)
  1079. {
  1080. ChannelLfo lfo;
  1081. lfo.period = (float) (1.0 / std::max (0.02, 30.0 * std::pow ((double) p[28], 5.0)));
  1082. const auto shape = std::clamp ((int) (4.0f * p[68]), 0, 4);
  1083. lfo.shape = shape == 1 ? 2 : shape == 2 ? 1 : 0;
  1084. const auto amount = 2.0f * p[26] - 1.0f;
  1085. switch (std::clamp ((int) (5.0f * p[67]), 0, 5))
  1086. {
  1087. case 0: lfo.amount = (amount < 0.0f ? -10.0f : 10.0f) * amount * amount; s.lfo[lfoCutoff] = lfo; break; // ±10·l² oct
  1088. case 1: case 2: lfo.amount = std::floor (24.0f * amount); s.lfo[lfoPitch] = lfo; break; // up to ±24 st
  1089. default: break; // PW and pan: scales not confirmed
  1090. }
  1091. }
  1092. s.mono = p[44] >= 0.5f;
  1093. s.porta = p[46] > 0.0f;
  1094. gain = (float) std::pow (10.0, (30.0 * p[15] - 20.0) / 20.0);
  1095. synth = s;
  1096. return true;
  1097. }
  1098. bool synthFromBassDrum (const std::vector<std::uint8_t>& state, SynthSettings& synth, float& gain)
  1099. {
  1100. float p[23];
  1101. if (! sslfFloats (state, "1kiK", 0x50C, p, 23) && ! sslfFloats (state, "2kiK", 0x50C, p, 23))
  1102. return false;
  1103. // sine at the "Base" frequency (2^(4x + 4) Hz). Confirmed (REA_rodada17 §7 + rodada18 §9): duration = linear
  1104. // ramp of (x³ + 0.001) s, no release; Peak f = base·(1 + 100·peak³·s⁴), with s falling by
  1105. // (1 − 0.0002/T_s) every sample (at 44.1 kHz), T_s = 20·slide³ + 0.001. The click and the sample layer
  1106. // are left out (the oscillator table is nearly sinusoidal).
  1107. const auto baseHz = std::pow (2.0, 4.0 * p[6] + 4.0);
  1108. SynthSettings s;
  1109. s.osc = { SynthOscillator { Waveform::sine, 0, 0.0f, 1.0f }, SynthOscillator {}, SynthOscillator {} };
  1110. setPitch (s.osc[0], 12.0 * std::log2 (baseHz / 261.63));
  1111. const auto duration = (float) (std::pow ((double) p[2], 3.0) + 0.001);
  1112. s.attack = 0.0005f;
  1113. s.decay = duration; // LYNX's decay reaches −60 dB in the given time (the BassDrum ramp reaches zero)
  1114. s.sustain = 0.0f;
  1115. s.release = duration; // no release: releasing the note does not cut it
  1116. s.cutoff = 20000.0f;
  1117. s.sweep = (float) (100.0 * std::pow ((double) p[7], 3.0));
  1118. const auto slide = 20.0 * std::pow ((double) p[8], 3.0) + 0.001;
  1119. s.sweepTime = (float) (-1.0 / (44100.0 * std::log (1.0 - 0.0002 / slide))); // time constant of s
  1120. gain = (float) std::pow (10.0, 40.0 * (p[0] - 0.5) / 20.0);
  1121. synth = s;
  1122. return true;
  1123. }
  1124. bool synthFromToxic (const std::vector<std::uint8_t>& state, SynthSettings& synth, float& gain)
  1125. {
  1126. float p[301];
  1127. if (! sslfFloats (state, "2iBT", 0x204C, p, 294))
  1128. return false;
  1129. // p300 (filter mode) is raw, outside the 0..1 range: read separately (REA_rodada19 §4.1)
  1130. std::fill (&p[294], &p[301], 0.0f);
  1131. if (state.size() >= 0x204C + 301 * 4)
  1132. std::memcpy (&p[294], state.data() + 0x204C + 294 * 4, sizeof (float) * 7);
  1133. const auto filterMode = std::isfinite (p[300]) ? std::clamp ((int) p[300], 0, 3) : 0;
  1134. // carrier = enabled operator with the highest "Mix" (REA_rodada17 §9) + the enabled modulator with the largest
  1135. // matrix cell into it (REA_rodada18 §8: target operator t receives from source j the cell 109 + 6j + t,
  1136. // phase deviation = 2·cell·output cycles). Filter (REA_rodada19 §4): mode p300 (0 off, 1 LP, 2 BP,
  1137. // 3 HP), cutoff 2^(9u + 5) Hz at note 60, key-track 0.09·KT octave per semitone, envelope ±9·EGAmt octaves
  1138. // with EGAmt = sign(2x − 1)(2x − 1)². The filter is FL's 4-pole ladder (REA_rodada26 §2: table, resonance
  1139. // scale R(u), input saturation), with the resonance p16 as is.
  1140. int carrier = -1;
  1141. for (int i = 0; i < 6; ++i)
  1142. if (p[25 + i] >= 0.5f && (carrier < 0 || p[103 + i] > p[103 + carrier]))
  1143. carrier = i;
  1144. if (carrier < 0)
  1145. carrier = 0;
  1146. auto steps = [] (float x) { return (double) std::clamp ((int) (198.0f * x - 99.0f), -99, 99); }; // trunc(198x − 99)
  1147. const auto semis = steps (p[31 + carrier]) + steps (p[37 + carrier]) * 0.01 + (double) (int) (48.0f * p[2] - 24.0f);
  1148. auto seconds = [] (float x) { return (float) std::max (50.0 * std::pow ((double) x, 4.0), 0.00101); };
  1149. SynthSettings s;
  1150. s.osc = { SynthOscillator { Waveform::sine, 0, 0.0f, 1.0f }, SynthOscillator {}, SynthOscillator {} };
  1151. setPitch (s.osc[0], semis);
  1152. int modulator = -1;
  1153. for (int j = 0; j < 6; ++j)
  1154. if (j != carrier && p[25 + j] >= 0.5f && p[109 + 6 * j + carrier] > 0.005f
  1155. && (modulator < 0 || p[109 + 6 * j + carrier] > p[109 + 6 * modulator + carrier]))
  1156. modulator = j;
  1157. if (modulator >= 0)
  1158. {
  1159. const auto cell = std::floor (100.0f * p[109 + 6 * modulator + carrier]) * 0.01f;
  1160. s.osc[2] = SynthOscillator { Waveform::sine, 0, 0.0f, 1.0f };
  1161. setPitch (s.osc[2], steps (p[31 + modulator]) + steps (p[37 + modulator]) * 0.01 + (double) (int) (48.0f * p[2] - 24.0f));
  1162. s.fm = 2.0f * cell * cell;
  1163. // the modulator's envelope scales its output: decay down to sustain (the attack is left out)
  1164. s.fmDecay = seconds (p[79 + modulator]);
  1165. s.fmSustain = p[85 + modulator] * p[85 + modulator];
  1166. }
  1167. s.attack = seconds (p[3]);
  1168. s.decay = seconds (p[4]);
  1169. s.sustain = p[5] * p[5];
  1170. s.release = 0.35f * seconds (p[6]) + 0.02f;
  1171. s.cutoff = 20000.0f;
  1172. if (filterMode != 0)
  1173. {
  1174. const auto u = (double) p[15], kt = 0.09 * 12.0 * p[17]; // octaves per octave
  1175. s.filterType = filterMode == 1 ? 0 : filterMode == 2 ? 1 : 2;
  1176. s.keyTrack = (float) kt;
  1177. s.cutoff = (float) std::clamp (std::exp2 (9.0 * u + 5.0 - kt), 20.0, 20000.0); // LYNX measures at key 48
  1178. s.ladder = true; // FL's 4-pole filter with its resonance scale (REA_rodada26 §2)
  1179. s.resonance = std::clamp (p[16], 0.0f, 1.0f);
  1180. const auto eg = 2.0 * p[23] - 1.0;
  1181. const auto egAmount = 9.0 * (eg < 0.0 ? -eg * eg : eg * eg);
  1182. if (std::abs (egAmount) > 0.01)
  1183. // FL's exponential pole gets close to the target in ~half the time T; LYNX's envelope is linear
  1184. s.filterEnv = { (float) egAmount, seconds (p[19]), 0.0f, 0.5f * seconds (p[20]), p[21] * p[21], 0.5f * seconds (p[22]) };
  1185. }
  1186. gain = 1.0f;
  1187. synth = s;
  1188. return true;
  1189. }
  1190. // ---- Morphine (REA_rodada16 §3): additive with up to 4 generators; each becomes an oscillator from the shape of
  1191. // the average spectrum (frames weighted by duration × gain). Envelope, level and tuning: the master block ----
  1192. namespace
  1193. {
  1194. std::uint32_t tagAt (const std::uint8_t* d, std::size_t o) { return u32At (d, o); }
  1195. constexpr std::uint32_t morTag (const char (&t)[5]) { return (std::uint32_t) t[3] << 24 | (std::uint32_t) t[2] << 16 | (std::uint32_t) t[1] << 8 | (std::uint32_t) t[0]; }
  1196. struct MorphineGenerator
  1197. {
  1198. std::array<double, 128> energy {}; // average energy of each harmonic
  1199. double weight = 0.0;
  1200. float mix = 0.0f;
  1201. };
  1202. // MBP0: 3 vectors of 128 values in 16 groups of 8 (mask + one f32 per set bit); the 1st is the amplitude
  1203. bool readPartials (const std::vector<std::uint8_t>& d, std::size_t& o, std::size_t end, std::array<float, 128>& amplitude)
  1204. {
  1205. if (o + 4 > end || tagAt (d.data(), o) != morTag ("0PBM"))
  1206. return false;
  1207. o += 4;
  1208. for (int a = 0; a < 3; ++a)
  1209. for (int g = 0; g < 16; ++g)
  1210. {
  1211. if (o >= end)
  1212. return false;
  1213. const auto mask = d[o++];
  1214. for (int b = 0; b < 8; ++b)
  1215. if ((mask >> b) & 1)
  1216. {
  1217. if (o + 4 > end)
  1218. return false;
  1219. float v = 0.0f;
  1220. std::memcpy (&v, d.data() + o, 4);
  1221. o += 4;
  1222. if (a == 0)
  1223. amplitude[(std::size_t) (g * 8 + b)] = std::isfinite (v) ? v : 0.0f;
  1224. }
  1225. }
  1226. return true;
  1227. }
  1228. bool readGenerator (const std::vector<std::uint8_t>& d, std::size_t o, std::size_t end, MorphineGenerator& gen)
  1229. {
  1230. // MVC0 · i32 · MZH0 · i32 zones · { i32, f32 level, i32 n, MSP0 } · i32 n · 6 × i32 (the 1st is Mix, f32)
  1231. if (o + 8 > end || tagAt (d.data(), o) != morTag ("0CVM"))
  1232. return false;
  1233. o += 8;
  1234. if (o + 8 > end || tagAt (d.data(), o) != morTag ("0HZM"))
  1235. return false;
  1236. const auto zones = (int) u32At (d.data(), o + 4);
  1237. o += 8;
  1238. for (int z = 0; z < zones; ++z)
  1239. {
  1240. if (o + 12 > end)
  1241. return false;
  1242. const auto zoneEnd = o + 12 + (std::size_t) u32At (d.data(), o + 8); // includes the size field itself [DATA]
  1243. o += 12;
  1244. if (o + 8 > end || tagAt (d.data(), o) != morTag ("0PSM"))
  1245. return false;
  1246. const auto frames = (int) u32At (d.data(), o + 4);
  1247. o += 8;
  1248. for (int f = 0; f < frames; ++f)
  1249. {
  1250. if (o + 12 > end)
  1251. return false;
  1252. const auto duration = (double) (std::int32_t) u32At (d.data(), o);
  1253. float frameGain = 0.0f;
  1254. std::memcpy (&frameGain, d.data() + o + 4, 4);
  1255. const auto next = o + 12 + (std::size_t) u32At (d.data(), o + 8);
  1256. o += 12;
  1257. std::array<float, 128> amplitude {};
  1258. if (! readPartials (d, o, end, amplitude) || o != next)
  1259. return false;
  1260. const auto w = std::max (0.0, duration) * std::abs ((double) frameGain);
  1261. for (std::size_t n = 0; n < 128; ++n)
  1262. gen.energy[n] += w * (double) amplitude[n] * amplitude[n];
  1263. gen.weight += w;
  1264. }
  1265. o = zoneEnd > o ? zoneEnd : o;
  1266. if (o > end)
  1267. return false;
  1268. }
  1269. if (o + 8 > end)
  1270. return false;
  1271. std::memcpy (&gen.mix, d.data() + o + 4, 4);
  1272. gen.mix = std::isfinite (gen.mix) ? std::clamp (gen.mix, 0.0f, 1.0f) : 0.0f;
  1273. return true;
  1274. }
  1275. // waveform from the spectrum: dominant fundamental -> sine; odd harmonics only -> square (slow falloff) or
  1276. // triangle (fast falloff, ~1/n²); everything else -> saw
  1277. [[maybe_unused]] Waveform waveFromSpectrum (const std::array<double, 128>& e)
  1278. {
  1279. double total = 0.0, odd = 0.0, peak = 0.0;
  1280. for (std::size_t n = 0; n < e.size(); ++n)
  1281. {
  1282. total += e[n];
  1283. if (n % 2 == 0)
  1284. odd += e[n];
  1285. peak = std::max (peak, e[n]);
  1286. }
  1287. if (total <= 0.0)
  1288. return Waveform::sine;
  1289. int strong = 0;
  1290. for (auto v : e)
  1291. strong += std::sqrt (v / peak) > 0.05 ? 1 : 0;
  1292. if (e[0] / total >= 0.7 && strong <= 6)
  1293. return Waveform::sine;
  1294. if (odd / total >= 0.8)
  1295. {
  1296. // log-log slope of the amplitudes of the odd harmonics present
  1297. double sx = 0.0, sy = 0.0, sxx = 0.0, sxy = 0.0;
  1298. int count = 0;
  1299. for (std::size_t n = 0; n < e.size(); n += 2)
  1300. if (e[n] > peak * 1e-6)
  1301. {
  1302. const auto x = std::log ((double) n + 1.0), y = 0.5 * std::log (e[n]);
  1303. sx += x, sy += y, sxx += x * x, sxy += x * y, ++count;
  1304. }
  1305. const auto slope = count >= 2 ? (count * sxy - sx * sy) / std::max (1e-12, count * sxx - sx * sx) : -1.0;
  1306. return slope >= -1.4 ? Waveform::square : Waveform::triangle;
  1307. }
  1308. return Waveform::saw;
  1309. }
  1310. } // namespace
  1311. bool synthFromMorphine (const std::vector<std::uint8_t>& d, SynthSettings& synth, float& gain)
  1312. {
  1313. if (d.size() < 32 || std::memcmp (d.data(), "SSLF", 4) != 0 || tagAt (d.data(), 8) != morTag ("0roM") || tagAt (d.data(), 12) != morTag ("0RPM"))
  1314. return false;
  1315. std::size_t o = 16;
  1316. std::array<MorphineGenerator, 4> gens {};
  1317. for (auto& g : gens)
  1318. {
  1319. if (o + 4 > d.size())
  1320. return false;
  1321. const auto n = (std::size_t) u32At (d.data(), o);
  1322. if (n > d.size() - o - 4 || ! readGenerator (d, o + 4, o + 4 + n, g))
  1323. return false;
  1324. o += 4 + n;
  1325. }
  1326. for (int block = 0; block < 2; ++block) // MML0 (morph line) and MMD0 (modulation envelopes)
  1327. {
  1328. if (o + 8 > d.size())
  1329. return false;
  1330. o += 4 + (std::size_t) u32At (d.data(), o);
  1331. }
  1332. if (o + 4 + 40 * 4 > d.size() || u32At (d.data(), o) != 0x5C4)
  1333. return false;
  1334. float a[40];
  1335. std::memcpy (a, d.data() + o + 4, sizeof (a));
  1336. for (auto& v : a)
  1337. v = std::isfinite (v) ? std::clamp (v, 0.0f, 1.0f) : 0.0f;
  1338. // the generators that make sound, by Mix
  1339. std::vector<int> active;
  1340. for (int g = 0; g < 4; ++g)
  1341. if (gens[(std::size_t) g].weight > 0.0 && std::any_of (gens[(std::size_t) g].energy.begin(), gens[(std::size_t) g].energy.end(), [] (double v) { return v > 0.0; }))
  1342. active.push_back (g);
  1343. std::stable_sort (active.begin(), active.end(), [&] (int x, int y) { return gens[(std::size_t) x].mix > gens[(std::size_t) y].mix; });
  1344. SynthSettings s;
  1345. s.osc = { SynthOscillator { Waveform::sine, 0, 0.0f, 1.0f }, SynthOscillator {}, SynthOscillator {} };
  1346. const auto transpose = (double) (int) ((a[5] - 0.5f) * 48.0f) + (double) (int) ((a[6] - 0.5f) * 200.0f) / 100.0;
  1347. // average spectrum of the active generators (energy per harmonic × Mix²) in the "Harmonics" oscillator; phases
  1348. // are not read (0). Scale: the strongest harmonic is 1 (Morphine's absolute level was not measured)
  1349. std::array<double, 128> energy {};
  1350. for (const auto g : active)
  1351. for (std::size_t n = 0; n < energy.size(); ++n)
  1352. energy[n] += gens[(std::size_t) g].energy[n] / std::max (1e-12, gens[(std::size_t) g].weight)
  1353. * (double) gens[(std::size_t) g].mix * gens[(std::size_t) g].mix;
  1354. const auto strongest = *std::max_element (energy.begin(), energy.end());
  1355. if (strongest > 0.0)
  1356. {
  1357. for (std::size_t n = 0; n < energy.size(); ++n)
  1358. s.spectrum[n] = (float) std::sqrt (energy[n] / strongest);
  1359. s.osc[0] = { Waveform::spectral, 0, 0.0f, 1.0f };
  1360. }
  1361. setPitch (s.osc[0], transpose);
  1362. // master envelope (s): A 15·v^3.5, D 30·v³, S v², R 10·v³ (min. 3 ms)
  1363. s.attack = (float) (15.0 * std::pow ((double) a[9], 3.5));
  1364. s.decay = (float) (30.0 * std::pow ((double) a[10], 3.0));
  1365. s.sustain = a[11] * a[11];
  1366. s.release = (float) std::max (0.003, 10.0 * std::pow ((double) a[12], 3.0));
  1367. s.cutoff = 20000.0f;
  1368. gain = (float) std::pow (10.0, (48.0 * a[0] - 24.0) / 20.0);
  1369. synth = s;
  1370. return true;
  1371. }
  1372. } // namespace lynx