TransistorBass.cpp 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807
  1. // FL Studio's Transistor Bass engine (docs/analise/REA_rodada57.md §2). Clean-room: our own code from the behaviour, data
  2. // layouts and formulas described in that document. Section numbers (§) below refer to it.
  3. #include "core/TransistorBass.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <atomic>
  7. #include <cmath>
  8. #include <cstring>
  9. #include <fstream>
  10. #include <iterator>
  11. #include <map>
  12. #include <mutex>
  13. #include "core/Sha256.h"
  14. #include "core/Song.h"
  15. #if defined(__SSE__) || defined(_M_X64) || defined(__x86_64__)
  16. #include <xmmintrin.h>
  17. #define LYNX_TBASS_MXCSR 1
  18. #endif
  19. // the engine's float operations, one rounding each, in its order: no contraction, no reordering
  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. // The render flushes denormals (MXCSR | 0x8040) and keeps round-to-nearest (§2.5).
  30. #ifdef LYNX_TBASS_MXCSR
  31. struct RenderMode
  32. {
  33. unsigned saved;
  34. RenderMode() noexcept : saved (_mm_getcsr()) { _mm_setcsr ((saved | 0x8040u) & ~0x6000u); }
  35. ~RenderMode() { _mm_setcsr (saved); }
  36. };
  37. #else
  38. struct RenderMode
  39. {
  40. };
  41. #endif
  42. double powD (double a, double b) noexcept { return a == 2.0 ? std::exp2 (b) : (double) std::pow ((long double) a, (long double) b); }
  43. float powF (float a, float b) noexcept { return (float) powD ((double) a, (double) b); }
  44. float sinF (float x) noexcept { return (float) std::sin ((double) x); }
  45. float expF (float x) noexcept { return (float) std::exp ((double) x); }
  46. float lnF (float x) noexcept { return (float) std::log ((double) x); }
  47. float bitsF (std::uint32_t u) noexcept
  48. {
  49. float f;
  50. std::memcpy (&f, &u, 4);
  51. return f;
  52. }
  53. // ------------------------------------------------------------------------------------------------ installation data (§2.3)
  54. constexpr const char* engineSha256 = "4cc72470063a0a9f8f126102415cbb1ef2b91abb2995cd9fbdf2c8e676c6907f";
  55. struct Wave
  56. {
  57. std::vector<float> data; // n points + 1 guard (data[n] = data[0])
  58. int length = 0;
  59. };
  60. struct DllData
  61. {
  62. std::vector<Wave> recorded; // engine V1's 57 "303 Pulse" cycles (192 kHz), longest first
  63. std::vector<Wave> recorded2; // engine V2's 55 cycles (44.1 kHz), longest first
  64. };
  65. // 16-bit mono RIFF/WAVE → floats x/32768
  66. bool decodeWav (const std::uint8_t* p, std::size_t n, std::vector<float>& out)
  67. {
  68. if (n < 12 || std::memcmp (p, "RIFF", 4) != 0 || std::memcmp (p + 8, "WAVE", 4) != 0)
  69. return false;
  70. std::size_t at = 12;
  71. int bits = 0, channels = 0;
  72. while (at + 8 <= n)
  73. {
  74. std::uint32_t size = 0;
  75. std::memcpy (&size, p + at + 4, 4);
  76. if (std::memcmp (p + at, "fmt ", 4) == 0 && size >= 16)
  77. {
  78. std::uint16_t c = 0, b = 0;
  79. std::memcpy (&c, p + at + 10, 2);
  80. std::memcpy (&b, p + at + 22, 2);
  81. channels = c, bits = b;
  82. }
  83. else if (std::memcmp (p + at, "data", 4) == 0)
  84. {
  85. if (bits != 16 || channels != 1 || at + 8 + size > n)
  86. return false;
  87. out.resize (size / 2);
  88. for (std::size_t i = 0; i < out.size(); ++i)
  89. {
  90. std::int16_t s = 0;
  91. std::memcpy (&s, p + at + 8 + 2 * i, 2);
  92. out[i] = (float) s / 32768.0f;
  93. }
  94. return true;
  95. }
  96. at += 8 + size + (size & 1);
  97. }
  98. return false;
  99. }
  100. std::shared_ptr<const DllData> loadDll (const std::string& path)
  101. {
  102. static std::mutex lock;
  103. static std::map<std::string, std::weak_ptr<const DllData>> cache;
  104. std::lock_guard<std::mutex> g (lock);
  105. if (auto t = cache[path].lock())
  106. return t;
  107. std::ifstream in (path, std::ios::binary);
  108. if (! in)
  109. {
  110. auto local = path;
  111. std::replace (local.begin(), local.end(), '\\', '/');
  112. in.open (local, std::ios::binary);
  113. }
  114. if (! in)
  115. return nullptr;
  116. const std::vector<std::uint8_t> b ((std::istreambuf_iterator<char> (in)), std::istreambuf_iterator<char>());
  117. if (b.size() < 0x1000 || sha256Hex (b.data(), b.size()) != engineSha256)
  118. return nullptr;
  119. auto rd = [&] (std::size_t off, auto& v) { if (off + sizeof (v) <= b.size()) std::memcpy (&v, b.data() + off, sizeof (v)); };
  120. std::uint32_t pe = 0;
  121. rd (0x3c, pe);
  122. std::uint16_t sections = 0, optSize = 0;
  123. rd (pe + 6, sections);
  124. rd (pe + 20, optSize);
  125. struct Section { std::uint32_t va, vs, ro, rs; };
  126. std::vector<Section> secs;
  127. for (std::uint32_t i = 0, o = pe + 24 + optSize; i < sections; ++i, o += 40)
  128. {
  129. Section s {};
  130. rd (o + 8, s.vs);
  131. rd (o + 12, s.va);
  132. rd (o + 16, s.rs);
  133. rd (o + 20, s.ro);
  134. secs.push_back (s);
  135. }
  136. auto offset = [&] (std::uint32_t rva) -> std::size_t {
  137. for (const auto& s : secs)
  138. if (rva >= s.va && rva < s.va + std::min (s.vs, s.rs))
  139. return (std::size_t) (s.ro + rva - s.va);
  140. return b.size();
  141. };
  142. auto t = std::make_shared<DllData>();
  143. // recorded cycles: count, then [size][RIFF bytes] (§2.3); each: (x − 0.63)·6.3157892, mean removed, guard point
  144. auto readSet = [&] (std::uint32_t rva, int expected, std::vector<Wave>& out) {
  145. auto at = offset (rva);
  146. std::int32_t count = 0;
  147. rd (at, count);
  148. if (count != expected)
  149. return false;
  150. at += 4;
  151. for (int k = 0; k < count; ++k)
  152. {
  153. std::int32_t size = 0;
  154. rd (at, size);
  155. if (size <= 0 || at + 4 + (std::size_t) size > b.size())
  156. return false;
  157. Wave w;
  158. if (! decodeWav (b.data() + at + 4, (std::size_t) size, w.data))
  159. return false;
  160. w.length = (int) w.data.size();
  161. const auto scale = 6.315789222717285f; // float constant
  162. for (auto& x : w.data)
  163. x = (float) ((double) x - 0.63) * scale;
  164. double sum = 0.0; // the mean is taken in double
  165. for (int i = 0; i < w.length; ++i)
  166. sum += (double) w.data[(std::size_t) i];
  167. const auto mean = sum / (double) w.length;
  168. for (int i = 0; i < w.length; ++i)
  169. w.data[(std::size_t) i] = (float) ((double) w.data[(std::size_t) i] - mean);
  170. w.data.push_back (w.data[0]);
  171. out.push_back (std::move (w));
  172. at += 4 + (std::size_t) size;
  173. }
  174. return true;
  175. };
  176. if (! readSet (0xFEAF0, 57, t->recorded) || ! readSet (0x15B2F0, 55, t->recorded2))
  177. return nullptr;
  178. cache[path] = t;
  179. return t;
  180. }
  181. // ----------------------------------------------------------------------------------- band-limited saw tables (§2.4)
  182. // 48 tables: a 1024-point falling ramp resampled by 2^(−1/4) per level with a 64-tap windowed-sinc kernel (16 384
  183. // phases), each then upsampled ×16 with the same kernel; one guard point before, two after.
  184. struct SawTables
  185. {
  186. std::vector<std::vector<float>> data; // per level: [guard, n points, 2 guards]
  187. std::vector<int> length;
  188. };
  189. const SawTables& sawTables()
  190. {
  191. static const SawTables tables = [] {
  192. constexpr int phases = 0x4000, taps = 64;
  193. std::vector<float> kernel ((std::size_t) phases * taps);
  194. const auto q = std::pow (2.0, 0.25);
  195. const auto pi = 3.141592653589793;
  196. for (int p = 0; p < phases; ++p)
  197. {
  198. const auto off = (double) p * 6.103515625e-05;
  199. for (int j = 0; j < taps; ++j)
  200. {
  201. auto u = std::max (0.0, ((double) j - off) * 0.015625);
  202. auto w = 0.5 - std::cos ((u + u) * pi) * 0.5;
  203. w = w * w;
  204. auto t = std::max (-32.0, (double) (j - 32) - off) / q * pi;
  205. const auto s = t == 0.0 ? 1.0 : std::sin (t) / t;
  206. kernel[(std::size_t) p * taps + (std::size_t) j] = (float) (s * w / q);
  207. }
  208. }
  209. auto resample = [&] (const std::vector<float>& src, int n, double x) {
  210. const auto i = (int) x;
  211. const auto ph = (int) ((x - (double) i) * 16384.0);
  212. const auto* k = kernel.data() + (std::size_t) ph * taps;
  213. auto base = i - 30 + n * 100;
  214. double acc = 0.0;
  215. for (int j = 0; j < taps; ++j)
  216. acc += (double) src[(std::size_t) ((base + j - 2) % n)] * (double) k[j];
  217. return (float) acc;
  218. };
  219. SawTables t;
  220. std::vector<std::vector<float>> raw (48);
  221. std::vector<int> len (48);
  222. raw[0].resize (1024);
  223. for (int i = 0; i < 1024; ++i)
  224. raw[0][(std::size_t) i] = (float) -(((double) i * 2.0) * 0.0009765625 - 1.0);
  225. len[0] = 1024;
  226. const auto ratio = std::pow (2.0, 1.0 / 4.0);
  227. auto size = 1024.0;
  228. for (int lv = 1; lv < 48; ++lv)
  229. {
  230. size /= ratio;
  231. auto n = (int) (size + 0.5);
  232. if (n < 2)
  233. n = 2;
  234. raw[(std::size_t) lv].resize ((std::size_t) n);
  235. const auto step = (double) len[(std::size_t) lv - 1] / (double) n;
  236. auto x = 0.0;
  237. for (int k = 0; k < n; ++k, x += step)
  238. raw[(std::size_t) lv][(std::size_t) k] = resample (raw[(std::size_t) lv - 1], len[(std::size_t) lv - 1], x);
  239. len[(std::size_t) lv] = n;
  240. }
  241. t.data.resize (48);
  242. t.length.resize (48);
  243. for (int lv = 0; lv < 48; ++lv)
  244. {
  245. const auto n = len[(std::size_t) lv] * 16;
  246. std::vector<float> up ((std::size_t) n + 3);
  247. auto x = 0.0;
  248. for (int k = 0; k < n; ++k, x += 1.0 / 16.0)
  249. up[(std::size_t) k + 1] = resample (raw[(std::size_t) lv], len[(std::size_t) lv], x);
  250. up[0] = up[(std::size_t) n];
  251. up[(std::size_t) n + 1] = up[1];
  252. up[(std::size_t) n + 2] = up[2];
  253. t.data[(std::size_t) lv] = std::move (up);
  254. t.length[(std::size_t) lv] = n;
  255. }
  256. return t;
  257. }();
  258. return tables;
  259. }
  260. // ------------------------------------------------------------------------------------------------------- one-pole (§2.5)
  261. struct OnePole
  262. {
  263. float y = 0.0f, x1 = 0.0f, b0 = 0.0f, b1 = 0.0f, a1 = 0.0f;
  264. int highPass = 0;
  265. float freq = 100.0f, piOverFs = 7.1237928e-05f;
  266. void coefficients (float t) noexcept
  267. {
  268. if (highPass)
  269. {
  270. const auto num = t - 1.0f, den = t + 1.0f;
  271. b0 = 1.0f / den;
  272. b1 = -b0;
  273. a1 = -num / den;
  274. }
  275. else
  276. {
  277. const auto den = t + 1.0f;
  278. b0 = t / den;
  279. b1 = b0;
  280. a1 = -(t - 1.0f) / den;
  281. }
  282. }
  283. void setRate (double fs) noexcept
  284. {
  285. piOverFs = (float) (1.0 / fs) * 3.1415927410125732f;
  286. coefficients ((float) std::tan ((double) (piOverFs * freq)));
  287. }
  288. void setFreq (float f) noexcept
  289. {
  290. freq = f;
  291. coefficients ((float) std::tan ((double) (freq * piOverFs)));
  292. }
  293. };
  294. // -------------------------------------------------------------------------------------------- diode ladder (§2.5)
  295. struct Ladder
  296. {
  297. float fb = 0.0f, hp1 = 0.0f; // feedback one-pole high-pass: output, previous input
  298. float b0 = 0.0f, b1 = 0.0f, a1 = 0.0f;
  299. double g = 0.0, y1 = 0.0, y2 = 0.0, y3 = 0.0, y4 = 0.0, k = 0.0, outGain = 0.0, maxCut = 0.0, wcScale = 0.0;
  300. void setRate (double fs) noexcept
  301. {
  302. maxCut = fs * 0.4;
  303. wcScale = 1.0 / (fs * 1.4142135623730951);
  304. const auto piOverFs = (float) (1.0 / fs) * 3.1415927410125732f;
  305. const auto t = (float) std::tan ((double) (piOverFs * 160.0f));
  306. const auto num = t - 1.0f, den = t + 1.0f;
  307. b0 = 1.0f / den;
  308. b1 = -b0;
  309. a1 = -num / den;
  310. }
  311. void set (float cutoff, float res, float gainOverride) noexcept
  312. {
  313. auto f = cutoff;
  314. if (11.0f > f)
  315. f = 11.0f;
  316. else if ((double) f > maxCut)
  317. f = (float) maxCut;
  318. const auto wc = (double) f * wcScale;
  319. g = (wc * 6.192218900001 + 0.0004552234600001) / (wc * wc * 4.415634500001 + (wc * 12.35835400001 + 1.000001));
  320. auto p = (((wc + 7198.699700001) * wc - 5837.791700001) * wc - 476.4730800001) * wc;
  321. p = ((p + 614.9561100001) * wc + 213.8712600001) * wc + 16.99879200001;
  322. const auto r = (double) res;
  323. if (0.0f > gainOverride)
  324. outGain = (((p * 0.058823529411764705 - 1.0) * r + 1.0) * (r + 1.0)) * 2.0;
  325. else
  326. outGain = (double) gainOverride;
  327. k = p * r;
  328. }
  329. float tick (float x) noexcept
  330. {
  331. const auto t = (float) (y4 * k);
  332. const auto u = b1 * hp1, v = a1 * fb;
  333. hp1 = t;
  334. auto w = t * b0;
  335. w = w + u;
  336. w = w + v;
  337. fb = w;
  338. auto a = (double) (x - w);
  339. a = ((a - y1) + y2) * g;
  340. y1 = a + a + y1;
  341. y2 = ((y1 - (y2 + y2)) + y3) * g + y2;
  342. y3 = ((y2 - (y3 + y3)) + y4) * g + y3;
  343. y4 = (y3 - (y4 + y4)) * g + y4;
  344. return (float) (y4 * outGain);
  345. }
  346. };
  347. // ------------------------------------------------------------------------------------------ half-band decimator (§2.5)
  348. struct HalfBand
  349. {
  350. struct Allpass { double a, x1 = 0, x2 = 0, y1 = 0, y2 = 0; };
  351. std::array<Allpass, 6> pathA, pathB;
  352. double prevB = 0.0;
  353. HalfBand()
  354. {
  355. constexpr double a[6] = { 0.036681502163648017, 0.2746317593794541, 0.5610989697879195, 0.769741833862266, 0.8922608180038789, 0.962094548378084 };
  356. constexpr double b[6] = { 0.13654762463195771, 0.42313861743656667, 0.6775400499741616, 0.839889624849638, 0.9315419599631839, 0.9878163707328971 };
  357. for (int i = 0; i < 6; ++i)
  358. pathA[(std::size_t) i].a = a[i], pathB[(std::size_t) i].a = b[i];
  359. }
  360. static double run (std::array<Allpass, 6>& path, double x) noexcept
  361. {
  362. for (auto& s : path)
  363. {
  364. const auto x1 = s.x1;
  365. s.x1 = x;
  366. x = (x - s.y2) * s.a + s.x2;
  367. s.x2 = x1;
  368. s.y2 = s.y1;
  369. s.y1 = x;
  370. }
  371. return x;
  372. }
  373. // one input sample; the output is meaningful on every second call
  374. double push (double x) noexcept
  375. {
  376. const auto out = (run (pathA, x) + prevB) * 0.5;
  377. prevB = run (pathB, x);
  378. return out;
  379. }
  380. };
  381. // ------------------------------------------------------------------------------------- Rat-style distortion (§2.7)
  382. // five one-poles (7.2 Hz and 60 Hz high-passes, the "HP" high-pass, the drive low-pass, the "Tone" low-pass), the
  383. // drive gain, a slew limiter with ±4.5 clamp and tanh, the output gain; runs at the oversampled rate
  384. struct Distortion
  385. {
  386. std::array<OnePole, 5> f;
  387. float drive = 0.0f, hpKnob = 0.0f, slew = 0.0f, slewMax = 0.0f, gain = 1.0f, level = 1.0f, out = 1.0f;
  388. Distortion()
  389. {
  390. f[0].highPass = 1, f[0].freq = 7.2f;
  391. f[1].highPass = 1, f[1].freq = 60.0f;
  392. f[2].highPass = 1, f[2].freq = 10.0f;
  393. f[3].highPass = 0, f[3].freq = 16000.0f;
  394. f[4].highPass = 0, f[4].freq = 19475.0f;
  395. }
  396. void setRate (double fs) noexcept
  397. {
  398. for (auto& x : f)
  399. x.setRate (fs);
  400. slewMax = (float) (300000.0 / fs);
  401. }
  402. float outputGain() const noexcept
  403. {
  404. auto e = 1.0f - expF (drive * -11.834190368652344f);
  405. e = e * 0.9819049835205078f;
  406. auto g = 1.0041040182113647f - e;
  407. g = g * level;
  408. return g * (hpKnob + 1.0f);
  409. }
  410. void setHp (float v) noexcept
  411. {
  412. hpKnob = v;
  413. auto fr = v * 3000.0f;
  414. fr = fr * v;
  415. f[2].highPass = 1;
  416. f[2].freq = fr + 10.0f;
  417. f[2].coefficients ((float) std::tan ((double) (f[2].freq * f[2].piOverFs)));
  418. out = outputGain();
  419. }
  420. void setDrive (float d) noexcept
  421. {
  422. static constexpr float taper[7] = { 16000.0f, 5000.0f, 2500.0f, 1500.0f, 900.0f, 600.0f, 8.871999740600586f };
  423. drive = d;
  424. auto x = d * 4.999000072479248f;
  425. const auto i = (int) x;
  426. x = x - (float) i;
  427. auto fr = (1.0f - x) * taper[i];
  428. fr = fr + x * taper[i + 1];
  429. f[3].highPass = 0;
  430. f[3].freq = fr;
  431. f[3].coefficients ((float) std::tan ((double) (fr * f[3].piOverFs)));
  432. auto g = d * d;
  433. g = g * d;
  434. gain = g * 2305.0f + 1.0f;
  435. out = outputGain();
  436. }
  437. void setTone (float v) noexcept
  438. {
  439. f[4].highPass = 0;
  440. auto fr = v * 19000.0f;
  441. fr = fr * v;
  442. f[4].freq = fr + 475.0f;
  443. f[4].coefficients ((float) std::tan ((double) (f[4].freq * f[4].piOverFs)));
  444. }
  445. void setVolume (float v) noexcept
  446. {
  447. auto e = v - 0.5f;
  448. e = e + e;
  449. level = (float) powD (4.0, (double) e);
  450. out = outputGain();
  451. }
  452. static float stage (OnePole& p, float x) noexcept
  453. {
  454. auto y = p.b1 * p.x1;
  455. y = y + x * p.b0;
  456. y = y + p.a1 * p.y;
  457. p.x1 = x;
  458. p.y = y;
  459. return y;
  460. }
  461. float tick (float x) noexcept
  462. {
  463. x = x * gain;
  464. auto y = stage (f[0], x);
  465. y = stage (f[1], y);
  466. y = stage (f[2], y);
  467. y = stage (f[3], y);
  468. auto d = y - slew;
  469. if (-slewMax > d)
  470. d = -slewMax;
  471. else
  472. d = std::min (slewMax, d);
  473. auto s = slew + d;
  474. if (-4.5f > s)
  475. s = -4.5f;
  476. else
  477. s = std::min (4.5f, s);
  478. slew = s;
  479. const auto t = (float) std::tanh ((double) s);
  480. auto& p = f[4];
  481. auto o = t * p.b0;
  482. o = o + p.b1 * p.x1;
  483. o = o + p.a1 * p.y;
  484. p.x1 = t;
  485. p.y = o;
  486. return o * out;
  487. }
  488. };
  489. // ------------------------------------------------------------------------------------------------ stereo delay (§2.8)
  490. // one line (2^18 points) read at a left and a right tap, each a crossfade of two tap times (time changes fade over
  491. // 0.3 s); the feedback runs through a 10 Hz high-pass, the send is added, then a 2×-iterated state-variable low-pass
  492. // ("Tone", 270…22 000 Hz), a soft clipper with level follower and a 65-point line before the write; outputs through 20 Hz
  493. // high-passes and the stereo matrix
  494. struct Delay
  495. {
  496. double fs = 44100.0;
  497. std::vector<float> line = std::vector<float> (0x40000, 0.0f), ap = std::vector<float> (0x8000, 0.0f);
  498. std::uint32_t w = 0, apIdx = 0;
  499. float send = 0.5f, feedback = 0.99f, tone = 0.0f, stereoA = 1.0f, stereoB = 0.0f, dry = 1.0f, wet = 1.0f;
  500. float satIn = 0.1f, satOut = 10.029618263244629f, env = 0.0f, envUp = 0.0f, envDown = 0.0f;
  501. std::array<float, 2> time { 0.1f, 0.1f }, right { 0.5f, 0.5f }, tapL { 0, 0 }, tapR { 0, 0 }, tapX { 0, 0 };
  502. OnePole fbHp, outL, outR;
  503. // state-variable filter
  504. float svSat = 0.0f, mixLp = 0.0f, mixHp = 1.0f, mixBp = 0.0f, svF = 0.0f, svQ = 0.0f, svCut = -1.0f, svRes = -1.0f;
  505. float svHpOut = 0.0f, svLp = 0.0f, svHp = 0.0f, svBp = 0.0f, fsF = 44100.0f;
  506. int svCounter = 0;
  507. Delay()
  508. {
  509. envUp = 1.0f - (float) powD (0.1, 0.0022675736961451248);
  510. envDown = 1.0f - (float) powD (0.1, 0.00022675736961451248);
  511. outL.highPass = outR.highPass = 1;
  512. outL.freq = outR.freq = 20.0f;
  513. setRate (44100.0);
  514. }
  515. void updateTaps (int i) noexcept
  516. {
  517. auto t = (float) fs * time[(std::size_t) i];
  518. t = t + 1.0f;
  519. tapL[(std::size_t) i] = t;
  520. const auto r = right[(std::size_t) i] * 0.5f;
  521. const auto a = 1.0f - r;
  522. t = t - 0.9998999834060669f;
  523. auto x = a * t;
  524. tapR[(std::size_t) i] = x + 1.0f;
  525. x = t * r;
  526. tapX[(std::size_t) i] = x + 1.0f;
  527. }
  528. void setRate (double rate) noexcept
  529. {
  530. fs = rate;
  531. fsF = (float) rate;
  532. svCut = svRes = -1.0f; // (the engine re-derives the filter from the next update)
  533. fbHp.highPass = 0;
  534. fbHp.freq = 100.0f;
  535. fbHp.setRate (44100.0);
  536. fbHp.highPass = 1;
  537. fbHp.setFreq (10.0f);
  538. outL.setRate (rate);
  539. outR.setRate (rate);
  540. updateTaps (0);
  541. updateTaps (1);
  542. clear();
  543. }
  544. void clear() noexcept
  545. {
  546. std::fill (line.begin(), line.end(), 0.0f);
  547. std::fill (ap.begin(), ap.end(), 0.0f);
  548. svHpOut = svLp = svHp = svBp = 0.0f;
  549. fbHp.y = fbHp.x1 = 0.0f;
  550. }
  551. void setSvf (float f, float q) noexcept
  552. {
  553. if (f == svCut && q == svRes)
  554. return;
  555. if (f != svCut)
  556. {
  557. auto x = f / (fsF + fsF);
  558. x = std::min (0.25f, x);
  559. svF = sinF (x * 3.1415927410125732f);
  560. svF = svF + svF;
  561. svCut = f;
  562. }
  563. const auto p = powF (q, 0.25f);
  564. svRes = q;
  565. auto damp = 1.0f - p;
  566. damp = damp + damp;
  567. auto lim = 2.0f / svF;
  568. lim = lim - svF * 0.5f;
  569. lim = std::min (2.0f, lim);
  570. svQ = std::min (damp, lim);
  571. }
  572. void modulation() noexcept
  573. {
  574. if (svCounter == 0)
  575. {
  576. // filter mode 0 (set by the plugin): low-pass on the 270…22 000 Hz table
  577. static constexpr float cut[6] = { 270.0f, 480.0f, 1300.0f, 7000.0f, 22000.0f, 0.0f };
  578. auto t = tone;
  579. t = 0.0f <= t ? std::min (1.0f, t) : 0.0f;
  580. auto x = t * 3.999000072479248f;
  581. const auto i = (int) x;
  582. const auto fr = x - (float) i;
  583. auto a = fr * cut[i + 1];
  584. auto b = (1.0f - fr) * cut[i];
  585. mixLp = 1.0f, mixHp = 0.0f, mixBp = 0.0f;
  586. setSvf (b + a, 0.0f * 0.25f);
  587. }
  588. svCounter = (svCounter + 1) & 3;
  589. }
  590. float svf (float x) noexcept
  591. {
  592. const auto bp = svBp, q = svQ, F = svF;
  593. auto lp1 = F * bp;
  594. lp1 = lp1 + svLp;
  595. auto hp1 = x - q * bp;
  596. hp1 = hp1 - lp1;
  597. auto t3 = svSat * bp;
  598. t3 = t3 * bp;
  599. t3 = t3 * bp;
  600. auto acc = mixLp * lp1;
  601. acc = acc + hp1 * mixHp;
  602. auto bp1 = hp1 * F;
  603. bp1 = bp1 + bp;
  604. bp1 = bp1 - t3;
  605. acc = acc + bp1 * mixBp;
  606. auto lp2 = bp1 * F;
  607. lp2 = lp2 + lp1;
  608. acc = acc * 0.5f;
  609. const auto hx = x - bp1 * q;
  610. svLp = lp2;
  611. svHpOut = hx;
  612. const auto hp2 = hx - lp2;
  613. svHp = hp2;
  614. auto t = bp1 * svSat;
  615. t = t * bp1;
  616. t = t * bp1;
  617. auto bp2 = hp2 * F;
  618. bp2 = bp2 + bp1;
  619. bp2 = bp2 - t;
  620. svBp = bp2;
  621. auto o = lp2 * mixLp;
  622. o = o + hp2 * mixHp;
  623. o = o + bp2 * mixBp;
  624. o = o * 0.5f;
  625. return o + acc;
  626. }
  627. float saturate (float x) noexcept
  628. {
  629. if (satIn != 1.0f)
  630. {
  631. const auto v = satIn * x;
  632. float r;
  633. if (-3.0f > v)
  634. r = -1.0f;
  635. else if (v > 3.0f)
  636. r = 1.0f;
  637. else
  638. {
  639. auto n = v * v;
  640. n = n + 27.0f;
  641. n = n * v;
  642. auto d = v * 9.0f;
  643. d = d * v;
  644. d = d + 27.0f;
  645. r = n / d;
  646. }
  647. x = r * satOut;
  648. }
  649. const auto a = std::fabs (x);
  650. const auto diff = a - env;
  651. env = env + diff * (a >= env ? envUp : envDown);
  652. if (env > 1.0f)
  653. x = x / env;
  654. return x;
  655. }
  656. static float pole (OnePole& p, float x) noexcept
  657. {
  658. auto y = p.b1 * p.x1;
  659. y = y + x * p.b0;
  660. y = y + p.a1 * p.y;
  661. p.x1 = x;
  662. p.y = y;
  663. return y;
  664. }
  665. void tick (float& L, float& R, float xa, float xb) noexcept
  666. {
  667. const auto fbScale = feedback / std::max (1.0f, satOut * satIn);
  668. auto mono = L + R;
  669. mono = mono * 0.5f;
  670. mono = mono * send;
  671. modulation();
  672. const std::uint32_t mask = 0x3FFFF;
  673. auto readFrac = [&] (float pos) {
  674. const auto i = (std::uint32_t) (std::int64_t) pos;
  675. const auto f = pos - (float) (std::int64_t) i;
  676. auto a = (1.0f - f) * line[(w - i) & mask];
  677. a = a + f * line[(w - i - 1) & mask];
  678. return a;
  679. };
  680. auto yl = readFrac (tapL[0]) * xa;
  681. yl = yl + xb * line[(w - (std::uint32_t) (std::int64_t) tapL[1]) & mask];
  682. auto yr = readFrac (tapR[0]) * xa;
  683. yr = yr + xb * line[(w - (std::uint32_t) (std::int64_t) tapR[1]) & mask];
  684. const auto x = yl * fbScale;
  685. auto h = x * fbHp.b0;
  686. h = h + fbHp.b1 * fbHp.x1;
  687. h = h + fbHp.a1 * fbHp.y;
  688. fbHp.x1 = x;
  689. fbHp.y = h;
  690. const auto in = h + mono;
  691. const auto s = saturate (svf (in));
  692. const auto old = ap[(apIdx - 65u) & 0x7FFFu];
  693. const auto c = 0.0f * 0.49900001287460327f;
  694. ap[apIdx] = s - old * c;
  695. apIdx = (apIdx + 1) & 0x7FFF;
  696. auto v = (1.0f - c * c) * old;
  697. line[w] = v + c * s;
  698. w = (w + 1) & mask;
  699. const auto ol = pole (outL, yl), orr = pole (outR, yr);
  700. auto l = orr * stereoB;
  701. l = l + ol * stereoA;
  702. l = l * wet;
  703. L = l + L * dry;
  704. auto r = orr * stereoA;
  705. r = r + ol * stereoB;
  706. r = r * wet;
  707. R = r + R * dry;
  708. }
  709. };
  710. // ------------------------------------------------------------------------------------------------ plate reverb (§2.9)
  711. // FL's plate (Dattorro-style figure-eight tank with the shared plate's line proportions and output taps) with an
  712. // early-reflection line (only its first tap pair is weighted), predelay with feedback, high/low cut, two-band decay and
  713. // damping, room scaling, wet smoothing and stereo width; float throughout, in the engine's order
  714. struct Reverb
  715. {
  716. static constexpr int lineN[12] { 142, 107, 379, 277, 672, 4453, 1800, 3720, 908, 4217, 2656, 3163 };
  717. static constexpr int tapN[14] { 266, 2974, 1913, 2496, 1690, 187, 1566, 353, 3627, 1728, 3173, 1811, 335, 621 };
  718. static constexpr int erLN[8] { 1102, 2904, 3784, 4873, 5878, 7470, 9062, 9263 };
  719. static constexpr int erRN[8] { 837, 1423, 2865, 3938, 5278, 5978, 7532, 9263 };
  720. double fs = 44100.0;
  721. std::vector<float> mem;
  722. std::array<std::size_t, 14> base {}; // 12 lines, predelay, early reflections
  723. std::array<int, 12> L {}, P {};
  724. int preLen = 1, preP = 0, erSize = 1, erP = 0, storedSize = 0;
  725. std::array<int, 14> taps {};
  726. std::array<int, 8> erL {}, erR {};
  727. std::array<float, 8> erGL {}, erGR {};
  728. // integer controls
  729. int inLevel = 0, lowCut = 75, highCut = 40, predelayMs = 0, size = 50, diffusion = 100, bassMul = 10, xover = 500, decay = 15,
  730. damping = 40, dry = 0, er = 0, wet = 0, width = 100;
  731. bool muteIn = false, muteDry = false, muteEr = false, muteWet = false, dirty = true;
  732. float preFeedback = 0.0f;
  733. // coefficients and state
  734. float gIn = 1.0f, cLc = 0.0f, cHc = 1.0f, cD1 = 0.0f, cD2 = 0.0f, cT1 = 0.0f, cT2 = 0.0f, g = 0.0f, cShelf = 0.0f, cXover = 0.0f, cDamp = 1.0f;
  735. float gDry = 0.0f, gEr = 0.0f, gWet = 0.0f, wetNow = -1000.0f;
  736. float sHc = 0.0f, sLcY = 0.0f, sLcX = 0.0f, sAx = 0.0f, sAy = 0.0f, sBx = 0.0f, sBy = 0.0f, sDampA = 0.0f, sDampB = 0.0f;
  737. Reverb()
  738. {
  739. // the constructor's control values (the plugin overwrites all but input level, bass multiplier and crossover)
  740. setParam (0, bitsF (0x3f5b83f4));
  741. setParam (1, bitsF (0x3c99e459));
  742. setParam (2, bitsF (0x3e25ed09));
  743. setParam (3, 0.0f);
  744. setParam (5, bitsF (0x3efd6a05));
  745. setParam (6, 1.0f);
  746. setParam (7, bitsF (0x3e924925));
  747. setParam (8, bitsF (0x3e76474b));
  748. setParam (9, bitsF (0x3d901495));
  749. setParam (10, bitsF (0x3e25ed09));
  750. setParam (11, bitsF (0x3f5b83f4));
  751. setParam (12, bitsF (0x3f463b97));
  752. setParam (13, bitsF (0x3f128bdc));
  753. setParam (14, 0.5f);
  754. setParam (15, 0.0f);
  755. setParam (16, 0.0f);
  756. setParam (17, 0.0f);
  757. setParam (18, 0.0f);
  758. allocate (44100.0);
  759. }
  760. static int law (float v, float a, float b) noexcept
  761. {
  762. auto x = v * a;
  763. x = x + b;
  764. x = x + 0.5f;
  765. return (int) std::floor ((double) x);
  766. }
  767. void setParam (int id, float v) noexcept
  768. {
  769. dirty = true;
  770. switch (id)
  771. {
  772. case 0: { auto x = v * 421.0f; x = x - 361.0f; x = x + 0.5f; inLevel = (int) std::floor ((double) x); break; }
  773. case 1: lowCut = law (v, 2981.0f, 19.0f); break;
  774. case 2: highCut = law (v, 216.0f, 5.0f); break;
  775. case 3: predelayMs = law (v, 250.0f, 0.0f); break;
  776. case 4: preFeedback = v; break;
  777. case 5: size = law (v, 99.0f, 1.0f); break;
  778. case 6: diffusion = law (v, 100.0f, 0.0f); break;
  779. case 7: bassMul = law (v, 28.0f, 2.0f); break;
  780. case 8: xover = law (v, 1975.0f, 25.0f); break;
  781. case 9: decay = law (v, 199.0f, 1.0f); break;
  782. case 10: damping = law (v, 216.0f, 5.0f); break;
  783. case 11: { auto x = v * 421.0f; x = x - 361.0f; x = x + 0.5f; dry = (int) std::floor ((double) x); break; }
  784. case 12: { auto x = v * 421.0f; x = x - 361.0f; x = x + 0.5f; er = (int) std::floor ((double) x); break; }
  785. case 13: { auto x = v * 421.0f; x = x - 361.0f; x = x + 0.5f; wet = (int) std::floor ((double) x); break; }
  786. case 14: width = law (v, 200.0f, 0.0f); break;
  787. case 15: muteIn = (int) std::floor ((double) (v + 0.0f + 0.5f)) != 0; break;
  788. case 16: muteDry = (int) std::floor ((double) (v + 0.0f + 0.5f)) != 0; break;
  789. case 17: muteEr = (int) std::floor ((double) (v + 0.0f + 0.5f)) != 0; break;
  790. case 18: muteWet = (int) std::floor ((double) (v + 0.0f + 0.5f)) != 0; break;
  791. default: break;
  792. }
  793. }
  794. // (re)allocation at a rate: every line at room 100, zeroed, positions 0
  795. void allocate (double rate)
  796. {
  797. fs = rate;
  798. const auto f = (int) rate;
  799. std::size_t total = 0;
  800. for (int k = 0; k < 12; ++k)
  801. {
  802. base[(std::size_t) k] = total;
  803. L[(std::size_t) k] = (f * lineN[k]) / 20000;
  804. total += (std::size_t) L[(std::size_t) k];
  805. P[(std::size_t) k] = 0;
  806. }
  807. base[12] = total;
  808. preLen = (f * 250) / 1000;
  809. total += (std::size_t) preLen;
  810. base[13] = total;
  811. auto u = (unsigned) ((double) f * 13950.0 / 44100.0);
  812. int bits = 0;
  813. if ((int) u > 0)
  814. while (u != 0)
  815. ++bits, u >>= 1;
  816. erSize = 1 << (bits + 1);
  817. total += (std::size_t) erSize;
  818. mem.assign (total, 0.0f);
  819. preP = erP = 0;
  820. }
  821. // FL's reset: every line filled with a tiny constant, filters cleared, the wet level jumps on the next block
  822. void reset() noexcept
  823. {
  824. std::fill (mem.begin(), mem.end(), bitsF (0x0da24260));
  825. sHc = sLcY = sLcX = 0.0f;
  826. sAx = sAy = sBx = sBy = 0.0f;
  827. sDampA = sDampB = 0.0f;
  828. wetNow = -1000.0f;
  829. }
  830. void coefficients() noexcept
  831. {
  832. const auto fsF = (float) fs;
  833. auto level = [] (int v) { return v < -360 ? 0.0f : powF (10.0f, (float) v / 200.0f); };
  834. gIn = level (inLevel);
  835. if (muteIn)
  836. gIn = 0.0f;
  837. if ((float) lowCut > 19.0f)
  838. {
  839. auto x = fsF * 0.5f;
  840. x = std::min (x, (float) lowCut);
  841. x = x * 3.1415927410125732f;
  842. x = x / fsF;
  843. const auto t = (float) std::tan ((double) x);
  844. cLc = (t - 1.0f) / (t + 1.0f);
  845. }
  846. else
  847. cLc = 0.0f;
  848. auto cutLaw = [&] (int v) {
  849. if (221.0f > (float) v)
  850. {
  851. auto x = (float) v * 100.0f;
  852. x = x + x;
  853. x = x * 3.1415927410125732f;
  854. x = x / fsF;
  855. const auto c = (float) std::cos ((double) x);
  856. const auto a = 2.0f - c;
  857. auto r = a * a;
  858. r = r - 1.0f;
  859. const auto sq = std::sqrt (r);
  860. return 1.0f - (a - sq);
  861. }
  862. return 1.0f;
  863. };
  864. cHc = cutLaw (highCut);
  865. const auto fi = (int) fsF;
  866. int len = (fi * predelayMs) / 1000;
  867. if (len < 1)
  868. len = 1;
  869. preLen = len;
  870. preP = preP % len;
  871. const auto R = ((size + 15) * fi) / 115;
  872. for (int k = 0; k < 12; ++k)
  873. {
  874. auto n = (R * lineN[k]) / 20000;
  875. if (n < 1)
  876. n = 1;
  877. L[(std::size_t) k] = n;
  878. P[(std::size_t) k] = P[(std::size_t) k] % n;
  879. }
  880. for (int k = 0; k < 14; ++k)
  881. taps[(std::size_t) k] = (R * tapN[k]) / 20000;
  882. const auto E = (float) (((size + 3) * fi) / 103);
  883. for (int k = 0; k < 8; ++k)
  884. {
  885. auto a = (float) erLN[k];
  886. a = a * 1.5f;
  887. a = a * E;
  888. a = a / 44100.0f;
  889. auto b = (float) erRN[k];
  890. b = b * 1.5f;
  891. b = b * E;
  892. b = b / 44100.0f;
  893. erL[(std::size_t) k] = (int) a;
  894. erR[(std::size_t) k] = (int) b;
  895. float x = 0.0f;
  896. if (k == 0)
  897. x = erL[0] < erR[0] ? (float) erL[0] : (float) erR[0];
  898. auto gl = x * 0.5f;
  899. erGL[(std::size_t) k] = gl / (float) erL[(std::size_t) k];
  900. auto gr = x * 0.36000001430511475f;
  901. erGR[(std::size_t) k] = gr / (float) erR[(std::size_t) k];
  902. }
  903. if (size != storedSize)
  904. {
  905. storedSize = size;
  906. for (int k = 0; k < 12; ++k)
  907. std::fill_n (mem.begin() + (std::ptrdiff_t) base[(std::size_t) k], L[(std::size_t) k], 0.0f);
  908. std::fill_n (mem.begin() + (std::ptrdiff_t) base[13], erSize, 0.0f);
  909. }
  910. const auto diff = (float) diffusion / 100.0f;
  911. const auto logv = lnF (0.0010000000474974513f);
  912. auto half = [&] (int a, int b) {
  913. auto x = (float) (L[(std::size_t) a] + L[(std::size_t) b]);
  914. x = x * 0.5f;
  915. return x / fsF;
  916. };
  917. if (diff == 0.0f)
  918. cD1 = cD2 = cT1 = cT2 = 0.0f;
  919. else
  920. {
  921. auto x = half (0, 1) * logv;
  922. cD1 = expF (x / (diff * 0.07000000029802322f));
  923. x = logv * half (2, 3);
  924. cD2 = expF (x / (diff * 0.10999999940395355f));
  925. x = logv * half (4, 8);
  926. cT1 = expF (x / (diff * 0.3499999940395355f));
  927. x = logv * half (6, 10);
  928. cT2 = expF (x / (diff * 0.5099999904632568f));
  929. }
  930. const auto sum = (float) (L[9] + L[7] + L[5] + L[11]);
  931. const auto d10 = (float) decay / 10.0f;
  932. auto t = sum / fsF;
  933. t = t * logv;
  934. g = powF (expF (t / d10), 0.25f);
  935. auto b = (float) bassMul * d10;
  936. b = b / 10.0f;
  937. const auto ratio = powF (expF (t / b), 0.25f) / g;
  938. const auto m = std::min (1.0f, ratio);
  939. auto sh = ratio - 1.0f;
  940. cShelf = sh * 0.5f;
  941. auto xo = (float) xover * 3.1415927410125732f;
  942. xo = xo / fsF;
  943. const auto tx = (float) std::tan ((double) xo);
  944. cXover = (tx - m) / (m + tx);
  945. cDamp = cutLaw (damping);
  946. gDry = level (dry);
  947. if (muteDry)
  948. gDry = 0.0f;
  949. gEr = level (er) * 0.5f;
  950. if (muteEr)
  951. gEr = 0.0f;
  952. auto w = level (wet) * 0.6000000238418579f;
  953. gWet = w * 0.5f;
  954. if (muteWet)
  955. gWet = 0.0f;
  956. dirty = false;
  957. }
  958. float* line (int k) noexcept { return mem.data() + base[(std::size_t) k]; }
  959. float allpass (int k, float x, float cRead, float cWrite) noexcept
  960. {
  961. auto* b = line (k);
  962. auto& p = P[(std::size_t) k];
  963. auto v = b[p] - cRead * x;
  964. b[p] = cWrite * v + x;
  965. if (--p < 0)
  966. p = L[(std::size_t) k] - 1;
  967. return v;
  968. }
  969. float tap (int k, int at) noexcept
  970. {
  971. const auto n = L[(std::size_t) k];
  972. return line (k)[at < n ? at : at - n];
  973. }
  974. void process (float* left, float* right, int n) noexcept
  975. {
  976. if (dirty)
  977. coefficients();
  978. const auto t1 = 1.0f - g;
  979. auto wA = t1 * 0.6000000238418579f;
  980. wA = wA + g;
  981. auto wB = t1 * 0.25f;
  982. wB = wB + g;
  983. auto wC = t1 * 0.699999988079071f;
  984. wC = wC + g;
  985. auto wD = t1 * 0.20000000298023224f;
  986. wD = wD + g;
  987. auto wE = t1 * 0.5f;
  988. wE = wE + g;
  989. const auto wdt = (float) width * 0.009999999776482582f;
  990. float erLs = 0.0f, erRs = 0.0f;
  991. auto* erb = line (13);
  992. const auto mask = erSize - 1;
  993. for (int i = 0; i < n; ++i)
  994. {
  995. const auto a = gIn * left[i];
  996. const auto b = gIn * right[i];
  997. auto m = b + a;
  998. m = m * 0.5f;
  999. m = m + 1.0000000031710769e-30f;
  1000. m = (m - sHc) * cHc + sHc;
  1001. sHc = m;
  1002. auto lc = (m - sLcY) * cLc + sLcX;
  1003. sLcX = m;
  1004. sLcY = lc;
  1005. if (cLc != 0.0f)
  1006. {
  1007. m = (m - lc) * 0.5f;
  1008. m = m + 1.0000000031710769e-30f;
  1009. }
  1010. if (gEr != 0.0f)
  1011. {
  1012. auto rd = [&] (int t) { return erb[(t + erP) & mask]; };
  1013. auto x = rd (erL[0]) * erGL[0];
  1014. x = x + rd (erL[1]) * erGL[1];
  1015. x = x - rd (erL[2]) * erGL[2];
  1016. erLs = rd (erL[3]) * erGL[3] + x;
  1017. erLs = erLs + rd (erL[4]) * erGL[4];
  1018. erLs = erLs + rd (erL[5]) * erGL[5];
  1019. erLs = erLs + rd (erL[6]) * erGL[6];
  1020. erRs = rd (erR[0]) * erGR[0];
  1021. erRs = erRs - rd (erR[1]) * erGR[1];
  1022. erRs = erRs + rd (erR[2]) * erGR[2];
  1023. erRs = erRs + rd (erR[3]) * erGR[3];
  1024. erRs = erRs - rd (erR[4]) * erGR[4];
  1025. erRs = erRs + rd (erR[5]) * erGR[5];
  1026. erRs = erRs + rd (erR[6]) * erGR[6];
  1027. erRs = erRs - rd (erR[7]) * erGR[7];
  1028. }
  1029. const auto v1 = allpass (0, m, cD1, cD1);
  1030. const auto v2 = allpass (1, v1, cD2, cD1);
  1031. erb[erP] = v1;
  1032. if (--erP < 0)
  1033. erP = erSize - 1;
  1034. const auto v3 = allpass (2, v2, cD1, cD1);
  1035. const auto v4 = allpass (3, v3, cD2, cD1);
  1036. auto* pre = line (12);
  1037. auto x = pre[preP];
  1038. pre[preP] = x * preFeedback + v4;
  1039. if (--preP < 0)
  1040. preP = preLen - 1;
  1041. x = x + 9.999999682655225e-21f;
  1042. // tank half A
  1043. auto s = line (11)[P[11]] * g;
  1044. auto sh = (s - sAy) * cXover + sAx;
  1045. sAx = s;
  1046. sAy = sh;
  1047. auto u = (sh + s) * cShelf + s;
  1048. u = u + x;
  1049. u = (u - sDampA) * cDamp + sDampA;
  1050. sDampA = u;
  1051. const auto a1 = allpass (4, u, cT1, cT1);
  1052. auto& p5 = P[5];
  1053. auto y = line (5)[p5];
  1054. line (5)[p5] = a1;
  1055. if (--p5 < 0)
  1056. p5 = L[5] - 1;
  1057. y = y * g;
  1058. const auto a2 = allpass (6, y, cT2, cT2);
  1059. auto& p7 = P[7];
  1060. line (7)[p7] = a2;
  1061. if (--p7 < 0)
  1062. p7 = L[7] - 1;
  1063. // tank half B
  1064. s = line (7)[p7] * g;
  1065. sh = (s - sBy) * cXover + sBx;
  1066. sBy = sh;
  1067. sBx = s;
  1068. u = (sh + s) * cShelf + s;
  1069. u = u + x;
  1070. u = (u - sDampB) * cDamp + sDampB;
  1071. sDampB = u;
  1072. const auto b1 = allpass (8, u, cT1, cT1);
  1073. auto& p9 = P[9];
  1074. y = line (9)[p9];
  1075. line (9)[p9] = b1;
  1076. if (--p9 < 0)
  1077. p9 = L[9] - 1;
  1078. y = y * g;
  1079. const auto b2 = allpass (10, y, cT2, cT2);
  1080. auto& p11 = P[11];
  1081. line (11)[p11] = b2;
  1082. if (--p11 < 0)
  1083. p11 = L[11] - 1;
  1084. // output taps
  1085. auto oL = tap (9, taps[0] + P[9]);
  1086. oL = oL - wB * tap (9, taps[1] + P[9]);
  1087. oL = oL - wC * tap (10, taps[2] + P[10]);
  1088. oL = oL - wD * tap (11, taps[3] + P[11]);
  1089. oL = oL + wA * tap (5, taps[4] + P[5]);
  1090. oL = oL + tap (6, taps[5] + P[6]);
  1091. oL = oL + wE * tap (7, taps[6] + P[7]);
  1092. auto oR = wB * tap (5, taps[8] + P[5]);
  1093. oR = oR + tap (5, taps[7] + P[5]);
  1094. oR = oR - wC * tap (6, taps[9] + P[6]);
  1095. oR = oR - wD * tap (7, taps[10] + P[7]);
  1096. oR = oR - wA * tap (9, taps[11] + P[9]);
  1097. oR = oR + tap (10, taps[12] + P[10]);
  1098. oR = oR + wE * tap (11, taps[13] + P[11]);
  1099. float w;
  1100. if (-99.0f > wetNow)
  1101. {
  1102. wetNow = gWet;
  1103. w = (gWet - wetNow) * 0.0010000000474974513f + wetNow;
  1104. }
  1105. else
  1106. w = (gWet - wetNow) * 0.0010000000474974513f + wetNow;
  1107. wetNow = w;
  1108. auto wl = w * oL;
  1109. wl = wl + gEr * erLs;
  1110. auto wr = w * oR;
  1111. wr = wr + gEr * erRs;
  1112. const auto sum = wr + wl;
  1113. auto d = wl - wr;
  1114. d = d * wdt;
  1115. const auto r2 = sum - d;
  1116. auto l2 = d + sum;
  1117. l2 = l2 + a * gDry;
  1118. auto rr = b * gDry;
  1119. rr = rr + r2;
  1120. left[i] = l2;
  1121. right[i] = rr;
  1122. }
  1123. }
  1124. };
  1125. // ------------------------------------------------------------------------------------------------ engine "V1" (§2.5)
  1126. class Engine
  1127. {
  1128. public:
  1129. virtual ~Engine() = default;
  1130. virtual void setParam (int i, float v) noexcept = 0;
  1131. virtual float getParam (int i) const noexcept = 0;
  1132. virtual void setRate (double fs) noexcept = 0;
  1133. virtual void noteOn (int key, bool slide, bool accent) noexcept = 0;
  1134. virtual void noteOff() noexcept = 0;
  1135. virtual float tick() noexcept = 0;
  1136. virtual bool silent() const noexcept = 0;
  1137. float transpose = 0.0f, pitchExpr = 0.0f, cutExpr = 0.0f, resExpr = 0.0f;
  1138. double bend = 0.0;
  1139. };
  1140. class Engine1 final : public Engine
  1141. {
  1142. public:
  1143. explicit Engine1 (std::shared_ptr<const DllData> d) : dll (std::move (d))
  1144. {
  1145. for (int i = 0; i < 128; ++i)
  1146. noteTable[(std::size_t) i] = (double) i + 0.0;
  1147. selectRecorded (0x1B4);
  1148. setRate (44100.0);
  1149. }
  1150. // §2.5: one stored raw value per index; laws for the used indices
  1151. void setParam (int i, float v) noexcept override
  1152. {
  1153. if (i >= 0 && i < 256)
  1154. raw[(std::size_t) i] = v;
  1155. switch (i)
  1156. {
  1157. case 2: cutoff = powF (v, 1.5f) * 0.5799999833106995f + 0.10000000149011612f; return;
  1158. case 5:
  1159. {
  1160. const auto sq = powF (v, 2.0f);
  1161. envMod = sq * 0.5400000214576721f + 0.1599999964237213f;
  1162. envModInv = 1.0f - sq * 0.3100000023841858f;
  1163. return;
  1164. }
  1165. case 6: p[6] = v; updateDecay (minDecay); return;
  1166. case 7: accent = v * v; return;
  1167. case 8: volume = v * 0.25f * 3.0f; return;
  1168. case 9:
  1169. p[9] = v;
  1170. hp.highPass = 1;
  1171. hp.freq = v * 390.0f + 10.0f;
  1172. hpFreqParam = hp.freq;
  1173. hp.coefficients ((float) std::tan ((double) (hp.freq * hp.piOverFs)));
  1174. return;
  1175. case 10:
  1176. minDecay = (double) (v * 0.1850000023841858f + 0.1850000023841858f);
  1177. updateDecay (minDecay);
  1178. return;
  1179. case 11: pw = v * 0.44999998807907104f + 0.5f; return;
  1180. case 12:
  1181. p[12] = v;
  1182. lfoInc = (float) ((double) (v * 9.899999618530273f + 0.10000000149011612f) * invFs);
  1183. return;
  1184. case 13: lfoAmount = v * 0.23999999463558197f; return;
  1185. case 0x1B: distOn = v >= 0.5f; return;
  1186. case 0x1C: p[0x1C] = v; dist.setHp (v); return;
  1187. case 0x1D: dist.setDrive (v * v); return;
  1188. case 0x1E: dist.setTone (v); return;
  1189. case 0x1F: dist.setVolume (v); return;
  1190. case 0x28:
  1191. {
  1192. const auto s = (double) (v * v);
  1193. vcaRelease = s * 0.045 + 0.005;
  1194. vcaAttack = s * 0.01 + 0.005;
  1195. vcaAttackCoef = 1.0 - powD (0.1, 1.0 / (vcaAttack * fsOs));
  1196. vcaReleaseCoef = 1.0 - powD (0.1, 1.0 / (vcaRelease * fsOs));
  1197. return;
  1198. }
  1199. case 0x29: pulseMode = (int) ((double) (2 - 1) * (double) v + 0.5); return;
  1200. default:
  1201. if (i >= 0 && i < 256)
  1202. p[(std::size_t) i] = v;
  1203. return;
  1204. }
  1205. }
  1206. float getParam (int i) const noexcept override { return i >= 0 && i < 256 ? raw[(std::size_t) i] : 0.0f; }
  1207. void setRate (double fs) noexcept override
  1208. {
  1209. fsBase = fs;
  1210. invFs = 1.0 / fs;
  1211. fsOs = (double) oversampling * fs;
  1212. invFsOs = 1.0 / fsOs;
  1213. slideCoef[0] = 1.0 - powD (0.1, 1.0 / (fs * glideTime[0]));
  1214. slideCoef[1] = 1.0 - powD (0.1, 1.0 / (fs * glideTime[1]));
  1215. vcaAttackCoef = 1.0 - powD (0.1, 1.0 / (fsOs * vcaAttack));
  1216. vcaReleaseCoef = 1.0 - powD (0.1, 1.0 / (fsOs * vcaRelease));
  1217. hp.piOverFs = (float) (1.0 / fsOs) * 3.1415927410125732f;
  1218. hp.freq = hpFreqParam;
  1219. hp.highPass = 1;
  1220. hp.coefficients ((float) std::tan ((double) (hp.freq * hp.piOverFs)));
  1221. ladder.setRate (fsOs);
  1222. dist.setRate (fsOs);
  1223. // saw-table selection (§2.4)
  1224. const auto& st = sawTables();
  1225. oscInvFs = 1.0 / fsOs;
  1226. const auto x = fsOs * 0.9 / ((double) st.length[0] / 16.0) / 8.17579891564;
  1227. oscIndexOffset = -std::log (x) / std::log (2.0) / 12.0;
  1228. recInvFs = 1.0 / fsOs;
  1229. accentCoef[0] = 1.0 - powD (0.1, 1.0 / (fs * 0.05));
  1230. accentCoef[1] = 1.0 - powD (0.1, 1.0 / (fs * 0.2));
  1231. sustainCoef = powD (0.1, 1.0 / (fsOs * 1.0));
  1232. }
  1233. void noteOn (int key, bool slide, bool acc) noexcept override
  1234. {
  1235. gate = true;
  1236. key = std::clamp (key, 0, 127);
  1237. accentOn = acc;
  1238. if (! slide)
  1239. {
  1240. env = 1.0;
  1241. sustain = 1.0;
  1242. }
  1243. slideIndex = slide ? 1 : 0;
  1244. target = noteTable[(std::size_t) key];
  1245. }
  1246. void noteOff() noexcept override { gate = false; }
  1247. float tick() noexcept override
  1248. {
  1249. const auto s = sinF (lfoPhase * 6.2831854820251465f);
  1250. lfoPhase = lfoPhase + lfoInc;
  1251. const auto t0 = (double) p[0] * 24.0;
  1252. lfoPhase = lfoPhase - (float) (int) lfoPhase;
  1253. pitch = (target - pitch) * slideCoef[(std::size_t) slideIndex] + pitch;
  1254. auto x = pitch + bend;
  1255. x = x - 64.0;
  1256. x = x + 24.0;
  1257. x = x + 4.0;
  1258. x = x + t0;
  1259. x = x + (double) pitchExpr;
  1260. x = x + (double) transpose;
  1261. double xn;
  1262. if (0.0 > x)
  1263. xn = 0.0;
  1264. else
  1265. xn = std::min (144.0, x);
  1266. xn = xn / 144.0;
  1267. const auto ec = powD (0.1, 1.0 / (fsBase * (accentOn ? minDecay : decay)));
  1268. env = ec * env;
  1269. sustain = sustainCoef * sustain;
  1270. const auto r = 1.0f - (1.0f - p[4]) * 0.5f;
  1271. const auto rInv = 1.0f - r;
  1272. double acc = 0.0;
  1273. if (accentOn)
  1274. acc = (double) accent * env * (double) r;
  1275. auto pwNow = s * lfoAmount + pw;
  1276. const auto accF = (float) acc;
  1277. const auto accD = (double) accF;
  1278. auto boost = accF * rInv * 6.0f;
  1279. accentSmooth = (accD - accentSmooth) * accentCoef[accD > accentSmooth ? 0 : 1] + accentSmooth;
  1280. auto boostF = (float) ((double) boost + accentSmooth);
  1281. if (0.0010000000474974513f > pwNow)
  1282. pwNow = bitsF (0x3a83126f);
  1283. else if (pwNow > 0.9990000128746033f)
  1284. pwNow = bitsF (0x3f7fbe77);
  1285. pulseWidth = pwNow;
  1286. if (pulseMode > 0)
  1287. {
  1288. recFreq = (double) powF (2.0f, (float) (xn * 12.0)) * 8.17579891564;
  1289. recInc = recFreq * recInvFs;
  1290. }
  1291. oscSelect (xn);
  1292. // cutoff (§2.5)
  1293. const auto c1 = envModInv * cutoff;
  1294. boostF = boostF * 0.23000000417232513f;
  1295. auto c = (double) c1 + (double) envMod * env + (double) boostF;
  1296. auto cf = (float) c - 0.019999999552965164f;
  1297. auto cd = (double) cf + (double) (p[3] - 0.5f) * xn;
  1298. cf = (float) cd + cutExpr;
  1299. const auto hz = powD (2.0, (double) cf * 128.0 * 0.08333333333333333) * 8.1757989156;
  1300. auto res = resExpr + p[4];
  1301. float rr;
  1302. if (0.0f > res)
  1303. rr = 0.0f;
  1304. else
  1305. rr = std::min (1.0f, res);
  1306. ladder.set ((float) hz, rr, -1.0f);
  1307. std::array<float, 4> buf {};
  1308. for (int n = 0; n < oversampling; ++n)
  1309. {
  1310. float o;
  1311. const auto len = oscLen;
  1312. auto ph = oscPhase;
  1313. const auto pos = len * ph;
  1314. if (pulseMode > 0)
  1315. {
  1316. const auto nextPh = ph + oscInc;
  1317. const auto i = (int) pos;
  1318. const auto f1 = (float) (pos - (double) i);
  1319. const auto wrap = (int) nextPh;
  1320. oscPhase = nextPh - (double) wrap;
  1321. oscCycles += wrap;
  1322. auto saw = (1.0f - f1) * oscTab[(std::size_t) i + 1];
  1323. saw = saw + f1 * oscTab[(std::size_t) i + 2];
  1324. const auto rp = recPhase * recLen;
  1325. recPhase = recPhase + recInc;
  1326. const auto j = (int) rp;
  1327. const auto g = (float) (rp - (double) j);
  1328. auto rec = g * recTab[(std::size_t) j + 1];
  1329. rec = rec + (1.0f - g) * recTab[(std::size_t) j];
  1330. const auto k = (int) recPhase;
  1331. recPhase = recPhase - (double) k;
  1332. if (k != 0)
  1333. selectRecorded ((int) (192000.0 / recFreq));
  1334. o = (1.0f - p[1]) * rec;
  1335. o = o + p[1] * saw;
  1336. }
  1337. else
  1338. {
  1339. auto pos2 = (double) pulseWidth + ph;
  1340. const auto nextPh = ph + oscInc;
  1341. const auto i = (int) pos;
  1342. const auto j = (int) pos2;
  1343. pos2 = (pos2 - (double) j) * len;
  1344. const auto f1 = (float) (pos - (double) i);
  1345. const auto k = (int) pos2;
  1346. const auto f2 = (float) (pos2 - (double) k);
  1347. auto saw1 = (1.0f - f1) * oscTab[(std::size_t) i + 1];
  1348. saw1 = saw1 + f1 * oscTab[(std::size_t) i + 2];
  1349. auto saw2 = (1.0f - f2) * oscTab[(std::size_t) k + 1];
  1350. saw2 = saw2 + f2 * oscTab[(std::size_t) k + 2];
  1351. const auto wrap = (int) nextPh;
  1352. oscCycles += wrap;
  1353. oscPhase = nextPh - (double) wrap;
  1354. o = (saw1 - saw2) * (1.0f - p[1]);
  1355. o = o + saw1 * p[1];
  1356. }
  1357. auto y = ladder.tick (o);
  1358. // VCA (§2.5)
  1359. double v;
  1360. if (gate)
  1361. {
  1362. float tg = 0.0f;
  1363. if (accentOn)
  1364. {
  1365. const auto a = (float) ((accentPeak - accentBase) * (double) accent + accentBase);
  1366. tg = (float) ((double) a * env + accentBase);
  1367. }
  1368. if (sustain > (double) tg)
  1369. tg = (float) sustain;
  1370. v = ((double) tg - vca) * vcaAttackCoef;
  1371. }
  1372. else
  1373. v = (0.0 - vca) * vcaReleaseCoef;
  1374. vca = v + vca;
  1375. const auto z = (float) ((double) y * vca);
  1376. auto h = z * hp.b0;
  1377. h = h + hp.x1 * hp.b1;
  1378. h = h + hp.a1 * hp.y;
  1379. hp.x1 = z;
  1380. hp.y = h;
  1381. auto out = h * volume;
  1382. if (distOn)
  1383. out = distortion (out);
  1384. buf[(std::size_t) n] = out;
  1385. }
  1386. if (oversampling == 1)
  1387. return buf[0];
  1388. if (oversampling == 2)
  1389. {
  1390. dec1.push ((double) buf[0]);
  1391. return (float) dec1.push ((double) buf[1]);
  1392. }
  1393. if (oversampling == 4)
  1394. {
  1395. dec1.push ((double) buf[0]);
  1396. const auto a = (float) dec1.push ((double) buf[1]);
  1397. dec1.push ((double) buf[2]);
  1398. const auto b = (float) dec1.push ((double) buf[3]);
  1399. dec2.push ((double) a);
  1400. return (float) dec2.push ((double) b);
  1401. }
  1402. return 0.0f;
  1403. }
  1404. bool silent() const noexcept override { return ! gate && std::fabs (vca) < 1e-9; }
  1405. private:
  1406. void updateDecay (double minD) noexcept
  1407. {
  1408. decay = (double) powF (p[6], 2.0f) * (decayMax - minD) + minD;
  1409. }
  1410. void oscSelect (double xn) noexcept
  1411. {
  1412. const auto& st = sawTables();
  1413. const auto x0 = (float) xn;
  1414. const auto xd = (double) x0;
  1415. const auto a = (float) (xd * 12.0);
  1416. const auto pw2 = powF (2.0f, a);
  1417. const auto t = (float) ((double) pw2 * 8.17579891564);
  1418. const auto inc = (float) ((double) t * oscInvFs);
  1419. oscInc = (double) inc;
  1420. auto idx = (int) ((xd + oscIndexOffset) * (double) 48);
  1421. idx = idx < 0 ? 0 : std::min (idx, 47);
  1422. oscLen = (double) st.length[(std::size_t) idx];
  1423. oscTab = st.data[(std::size_t) idx].data();
  1424. }
  1425. void selectRecorded (int thr) noexcept
  1426. {
  1427. if (dll == nullptr || dll->recorded.empty())
  1428. return;
  1429. int found = 0;
  1430. for (int i = (int) dll->recorded.size() - 1; i >= 0; --i)
  1431. if (thr < dll->recorded[(std::size_t) i].length)
  1432. {
  1433. found = i;
  1434. break;
  1435. }
  1436. recLen = (double) dll->recorded[(std::size_t) found].length;
  1437. recTab = dll->recorded[(std::size_t) found].data.data();
  1438. }
  1439. float distortion (float x) noexcept { return dist.tick (x); }
  1440. std::shared_ptr<const DllData> dll;
  1441. std::array<float, 256> raw {}, p {};
  1442. std::array<double, 128> noteTable {};
  1443. int oversampling = 4;
  1444. double fsBase = 44100.0, invFs = 1.0 / 44100.0, fsOs = 176400.0, invFsOs = 1.0 / 176400.0;
  1445. // envelope, accent
  1446. double minDecay = 0.185, decayMax = 2.16, decay = 0.185, env = 0.0, sustain = 0.0, sustainCoef = 0.0;
  1447. double accentSmooth = 0.0;
  1448. std::array<double, 2> accentCoef {};
  1449. float accent = 0.0f, envMod = 0.0f, envModInv = 0.0f, cutoff = 0.0f, volume = 0.0f, pw = 0.5f, lfoAmount = 0.0f;
  1450. float lfoPhase = 0.0f, lfoInc = 0.0f;
  1451. bool gate = false, accentOn = false, distOn = false;
  1452. // pitch
  1453. std::array<double, 2> glideTime { 0.0001, 0.05 }, slideCoef {};
  1454. int slideIndex = 0;
  1455. double pitch = 0.0, target = 0.0;
  1456. // oscillators
  1457. int pulseMode = 0, oscCycles = 0;
  1458. float pulseWidth = 0.5f;
  1459. double oscPhase = 0.0, oscInc = 0.0, oscLen = 0.0, oscInvFs = 0.0, oscIndexOffset = 0.0;
  1460. const float* oscTab = nullptr;
  1461. double recPhase = 0.0, recInc = 0.0, recLen = 0.0, recFreq = 440.0, recInvFs = 0.0;
  1462. const float* recTab = nullptr;
  1463. // VCA, filters
  1464. double vca = 0.0, vcaAttack = 0.005, vcaRelease = 0.005, vcaAttackCoef = 1.0, vcaReleaseCoef = 1.0;
  1465. double accentBase = 0.7400000095367432, accentPeak = 2.5999999046325684;
  1466. Ladder ladder;
  1467. OnePole hp;
  1468. float hpFreqParam = 200.0f;
  1469. HalfBand dec1, dec2;
  1470. Distortion dist;
  1471. };
  1472. // ------------------------------------------------------------------------------------------------ engine "V2" (§2.6)
  1473. // the second engine: the same oscillators (its own recorded "303 Pulse" set), ladder, high-pass, distortion and
  1474. // decimators, with a modelled accent circuit (two RC paths) driving the cutoff, three envelopes (VCA, accent, accent
  1475. // release) and table-based cutoff / resonance / envelope-modulation laws ("TB303 range"; "extended" scales them
  1476. // linearly)
  1477. class Engine2 final : public Engine
  1478. {
  1479. public:
  1480. Engine2 (std::shared_ptr<const DllData> d, bool extended) : dll (std::move (d)), ext (extended)
  1481. {
  1482. for (int i = 0; i < 128; ++i)
  1483. noteTable[(std::size_t) i] = (double) i + 0.0;
  1484. selectRecorded (100);
  1485. env2.releaseTime = 0.2, env2.releaseTarget = 0.15, env2.decayTime = 0.007;
  1486. env3.releaseTime = 0.185, env3.releaseTarget = 0.1;
  1487. setRate (44100.0);
  1488. }
  1489. void setParam (int i, float v) noexcept override
  1490. {
  1491. if (i >= 0 && i < 256)
  1492. raw[(std::size_t) i] = v;
  1493. switch (i)
  1494. {
  1495. case 2:
  1496. {
  1497. if (ext)
  1498. cutoff = v * 0.699999988079071f;
  1499. else if (1.0f <= v)
  1500. cutoff = 0.6299999952316284f;
  1501. else
  1502. cutoff = interp4 (cutTable, v);
  1503. return;
  1504. }
  1505. case 4:
  1506. {
  1507. static constexpr float t[6] = { 0.0f, 0.10300000011920929f, 0.38999998569488525f, 0.5910000205039978f, 1.0019999742507935f, 0.0f };
  1508. res = 1.0f <= v ? 1.0019999742507935f : interp4 (t, v);
  1509. return;
  1510. }
  1511. case 5:
  1512. {
  1513. static constexpr float t[6] = { 0.091796875f, 0.12800000607967377f, 0.169097900390625f, 0.2709999978542328f, 0.550000011920929f, 0.0f };
  1514. if (ext)
  1515. {
  1516. auto x = v * 0.699999988079071f;
  1517. envMod = x + 0.091796875f;
  1518. }
  1519. else
  1520. {
  1521. const auto r = raw[5];
  1522. envMod = 1.0f <= r ? 0.550000011920929f : interp4 (t, r);
  1523. }
  1524. return;
  1525. }
  1526. case 6:
  1527. p[6] = v;
  1528. decayCoef = powD (0.1, 1.0 / (decayTime (p[6]) * fsBase));
  1529. return;
  1530. case 8: volume = v * 0.25f * 3.0f; return;
  1531. case 9:
  1532. p[9] = v;
  1533. hp.highPass = 1;
  1534. hp.freq = v * 390.0f + 10.0f;
  1535. hpFreqParam = hp.freq;
  1536. hp.coefficients ((float) std::tan ((double) (hp.freq * hp.piOverFs)));
  1537. return;
  1538. case 10:
  1539. {
  1540. auto x = v - 0.5f;
  1541. x = x * 0.10000000149011612f;
  1542. minDecay = (double) (x + 0.1850000023841858f);
  1543. const auto q = p[6];
  1544. auto f = (float) (minDecay / (double) 0.1850000023841858f);
  1545. f = f * (1.0f - q);
  1546. f = f + q;
  1547. float t;
  1548. if (1.0f <= q)
  1549. t = 2.2249999046325684f;
  1550. else
  1551. {
  1552. auto y = q * 10.0f;
  1553. const auto k = (int) y;
  1554. y = y - (float) k;
  1555. auto a = (1.0f - y) * decayTable[k];
  1556. t = a + y * decayTable[k + 1];
  1557. }
  1558. t = t * f;
  1559. decayCoef = powD (0.1, 1.0 / ((double) t * fsBase));
  1560. accentDecayCoef = powD (0.1, 1.0 / (decayTime (0.0f) * fsBase));
  1561. return;
  1562. }
  1563. case 11: pw = v * 0.44999998807907104f + 0.5f; return;
  1564. case 12:
  1565. p[12] = v;
  1566. lfoInc = (float) ((double) (v * 9.899999618530273f + 0.10000000149011612f) * invFs);
  1567. return;
  1568. case 13: lfoAmount = v * 0.23999999463558197f; return;
  1569. case 0x1B: distOn = v >= 0.5f; return;
  1570. case 0x1C: p[0x1C] = v; dist.setHp (v); return;
  1571. case 0x1D: dist.setDrive (v * v); return;
  1572. case 0x1E: dist.setTone (v); return;
  1573. case 0x1F: dist.setVolume (v); return;
  1574. case 0x28: vcaSmoothCoef = 1.0 - powD (0.09999999999999998, 1.0 / ((smoothLaw() * 0.05 + 0.0001) * fsBase)); return;
  1575. case 0x29: pulse = 0.5f <= v; return;
  1576. default:
  1577. if (i >= 0 && i < 256)
  1578. p[(std::size_t) i] = v;
  1579. return;
  1580. }
  1581. }
  1582. float getParam (int i) const noexcept override { return i >= 0 && i < 256 ? raw[(std::size_t) i] : 0.0f; }
  1583. void setRate (double fs) noexcept override
  1584. {
  1585. fsBase = fs;
  1586. fsOs = (double) oversampling * fs;
  1587. invFs = 1.0 / fs;
  1588. invFsOs = 1.0 / fsOs;
  1589. slideCoef[0] = 1.0 - powD (0.09999999999999998, 1.0 / (fs * glideTime[0]));
  1590. slideCoef[1] = 1.0 - powD (0.09999999999999998, 1.0 / (fs * glideTime[1]));
  1591. for (auto* e : { &env1, &env2, &env3 })
  1592. {
  1593. e->fs = fs;
  1594. e->attackInc = 1.0 / (fs * e->attackTime);
  1595. e->decayInc = 1.0 / (fs * e->decayTime);
  1596. e->releaseCoef = powD (e->releaseTarget, 1.0 / (fs * e->releaseTime));
  1597. }
  1598. vcaSmoothCoef = 1.0 - powD (0.09999999999999998, 1.0 / ((smoothLaw() * 0.05 + 0.0001) * fs));
  1599. hp.piOverFs = (float) (1.0 / fsOs) * 3.1415927410125732f;
  1600. hp.freq = hpFreqParam;
  1601. hp.highPass = 1;
  1602. hp.coefficients ((float) std::tan ((double) (hp.freq * hp.piOverFs)));
  1603. ladder.setRate (fsOs);
  1604. const auto& st = sawTables();
  1605. oscInvFs = 1.0 / fsOs;
  1606. const auto x = fsOs * 0.9 / ((double) st.length[0] / 16.0) / 8.17579891564;
  1607. oscIndexOffset = -std::log (x) / std::log (2.0) / 12.0;
  1608. recInvFs = 1.0 / fsOs;
  1609. circuit.fs = fs;
  1610. circuit.dirty = true;
  1611. decayCoef = accentDecayCoef = powD (0.1, 1.0 / (decayTime (0.0f) * fs));
  1612. vcaUp = 1.0 - powD (0.09999999999999998, 1.0 / (fs * 0.0003));
  1613. vcaDown = 1.0 - powD (0.09999999999999998, 1.0 / (fs * 0.01));
  1614. dist.setRate (fsOs);
  1615. }
  1616. void noteOn (int key, bool slide, bool acc) noexcept override
  1617. {
  1618. accentOn = acc;
  1619. gate = true;
  1620. key = std::clamp (key, 0, 127);
  1621. if (! slide)
  1622. {
  1623. env1.restart();
  1624. env = 1.0;
  1625. if (accentOn)
  1626. {
  1627. env2.restart();
  1628. env3.restart();
  1629. }
  1630. }
  1631. slideIndex = slide ? 1 : 0;
  1632. target = noteTable[(std::size_t) key];
  1633. }
  1634. void noteOff() noexcept override
  1635. {
  1636. gate = false;
  1637. env1.stage = 3;
  1638. env2.stage = 3;
  1639. }
  1640. float tick() noexcept override
  1641. {
  1642. const auto s = sinF (lfoPhase * 6.2831854820251465f);
  1643. lfoPhase = lfoPhase + lfoInc;
  1644. const auto t0 = (double) p[0] * 24.0;
  1645. lfoPhase = lfoPhase - (float) (int) lfoPhase;
  1646. pitch = (target - pitch) * slideCoef[(std::size_t) slideIndex] + pitch;
  1647. auto x = pitch + bend;
  1648. x = x - 64.0;
  1649. x = x + 24.0;
  1650. x = x + 4.0;
  1651. x = x + t0;
  1652. x = x + (double) pitchExpr;
  1653. x = x + (double) transpose;
  1654. double xn;
  1655. if (0.0 > x)
  1656. xn = 0.0;
  1657. else
  1658. xn = std::min (144.0, x);
  1659. xn = xn / 144.0;
  1660. double accIn = 0.0;
  1661. if (accentOn)
  1662. {
  1663. env = accentDecayCoef * env;
  1664. envCopy = env;
  1665. accIn = env * (double) raw[7];
  1666. }
  1667. else
  1668. {
  1669. env = decayCoef * env;
  1670. envCopy = env;
  1671. }
  1672. const auto drive = (float) ((double) (float) accIn * 10.0);
  1673. const auto c = circuit.tick ((double) raw[4], (double) raw[7], drive);
  1674. auto pwNow = s * lfoAmount + pw;
  1675. auto boost = (float) ((((double) c - 3.25) * 0.1) * 1.33);
  1676. if (0.0010000000474974513f > pwNow)
  1677. pwNow = bitsF (0x3a83126f);
  1678. else if (pwNow > 0.9990000128746033f)
  1679. pwNow = bitsF (0x3f7fbe77);
  1680. pulseWidth = pwNow;
  1681. if (pulse)
  1682. {
  1683. recFreq = (double) powF (2.0f, (float) (xn * 12.0)) * 8.17579891564;
  1684. recInc = recFreq * recInvFs;
  1685. }
  1686. oscSelect (xn);
  1687. const auto em = (float) ((double) envMod * (envCopy - 0.32499998807907104));
  1688. boost = boost * 0.75f;
  1689. auto cf = em + boost;
  1690. cf = cf + cutoff;
  1691. cf = cf + 0.10000000149011612f;
  1692. auto cd = (double) cf + (double) (p[3] - 0.5f) * xn;
  1693. cf = (float) cd + cutExpr;
  1694. const auto hz = powD (2.0, (double) cf * 128.0 * 0.08333333333333333) * 8.1757989156;
  1695. ladder.set ((float) hz, res, -1.0f);
  1696. const auto e1 = env1.tick();
  1697. auto e2 = env2.tick();
  1698. e2 = e2 * 3.0f;
  1699. e2 = e2 * raw[7];
  1700. auto e3 = env3.tick();
  1701. e3 = e3 * 1.75f;
  1702. e3 = e3 * raw[7];
  1703. auto g = std::min (1.0f, e3);
  1704. if (gate)
  1705. g = 0.0f;
  1706. const auto m = std::max (e1, e2);
  1707. const auto y = std::max (g, m);
  1708. const auto yd = (double) y;
  1709. const auto d = yd - vca1;
  1710. vca1 = d * (yd > vca1 ? vcaUp : vcaDown) + vca1;
  1711. vca2 = (vca1 - vca2) * vcaSmoothCoef + vca2;
  1712. std::array<float, 4> buf {};
  1713. for (int n = 0; n < oversampling; ++n)
  1714. {
  1715. float o;
  1716. const auto len = oscLen;
  1717. const auto ph = oscPhase;
  1718. const auto pos = len * ph;
  1719. if (pulse)
  1720. {
  1721. const auto nextPh = ph + oscInc;
  1722. const auto i = (int) pos;
  1723. const auto f1 = (float) (pos - (double) i);
  1724. const auto wrap = (int) nextPh;
  1725. oscPhase = nextPh - (double) wrap;
  1726. oscCycles += wrap;
  1727. auto saw = (1.0f - f1) * oscTab[(std::size_t) i + 1];
  1728. saw = saw + f1 * oscTab[(std::size_t) i + 2];
  1729. const auto rp = recPhase * recLen;
  1730. recPhase = recPhase + recInc;
  1731. const auto j = (int) rp;
  1732. const auto gg = (float) (rp - (double) j);
  1733. auto rec = gg * recTab[(std::size_t) j + 1];
  1734. rec = rec + (1.0f - gg) * recTab[(std::size_t) j];
  1735. const auto k = (int) recPhase;
  1736. recPhase = recPhase - (double) k;
  1737. if (k != 0)
  1738. selectRecorded ((int) (44100.0 / recFreq));
  1739. o = (1.0f - p[1]) * rec;
  1740. o = o + p[1] * saw;
  1741. }
  1742. else
  1743. {
  1744. auto pos2 = (double) pulseWidth + ph;
  1745. const auto nextPh = ph + oscInc;
  1746. const auto i = (int) pos;
  1747. const auto j = (int) pos2;
  1748. pos2 = (pos2 - (double) j) * len;
  1749. const auto f1 = (float) (pos - (double) i);
  1750. const auto k = (int) pos2;
  1751. const auto f2 = (float) (pos2 - (double) k);
  1752. auto saw1 = (1.0f - f1) * oscTab[(std::size_t) i + 1];
  1753. saw1 = saw1 + f1 * oscTab[(std::size_t) i + 2];
  1754. auto saw2 = (1.0f - f2) * oscTab[(std::size_t) k + 1];
  1755. saw2 = saw2 + f2 * oscTab[(std::size_t) k + 2];
  1756. const auto wrap = (int) nextPh;
  1757. oscCycles += wrap;
  1758. oscPhase = nextPh - (double) wrap;
  1759. o = (saw1 - saw2) * (1.0f - p[1]);
  1760. o = o + saw1 * p[1];
  1761. }
  1762. const auto f = ladder.tick (-o);
  1763. const auto z = (float) ((double) f * vca2);
  1764. auto h = z * hp.b0;
  1765. h = h + hp.x1 * hp.b1;
  1766. h = h + hp.y * hp.a1;
  1767. hp.x1 = z;
  1768. hp.y = h;
  1769. auto out = h * volume;
  1770. if (distOn)
  1771. out = dist.tick (out);
  1772. buf[(std::size_t) n] = out;
  1773. }
  1774. if (oversampling == 1)
  1775. return buf[0];
  1776. if (oversampling == 2)
  1777. {
  1778. dec1.push ((double) buf[0]);
  1779. return (float) dec1.push ((double) buf[1]);
  1780. }
  1781. if (oversampling == 4)
  1782. {
  1783. dec1.push ((double) buf[0]);
  1784. const auto a = (float) dec1.push ((double) buf[1]);
  1785. dec1.push ((double) buf[2]);
  1786. const auto b = (float) dec1.push ((double) buf[3]);
  1787. dec2.push ((double) a);
  1788. return (float) dec2.push ((double) b);
  1789. }
  1790. return 0.0f;
  1791. }
  1792. bool silent() const noexcept override { return ! gate && std::fabs (vca2) < 1e-9 && std::fabs (vca1) < 1e-9; }
  1793. private:
  1794. static constexpr float decayTable[12] = { 0.1850000023841858f, 0.20399999618530273f, 0.2329999953508377f, 0.3540000021457672f, 0.45500001311302185f, 0.5379999876022339f,
  1795. 0.652999997138977f, 0.9409999847412109f, 1.4299999475479126f, 2.121999979019165f, 2.2249999046325684f, 0.0f };
  1796. static constexpr float cutTable[6] = { 0.3330000042915344f, 0.3709999918937683f, 0.44699999690055847f, 0.5329999923706055f, 0.6299999952316284f, 0.0f };
  1797. static float interp4 (const float* t, float v) noexcept
  1798. {
  1799. auto x = v * 4.0f;
  1800. const auto i = (int) x;
  1801. x = x - (float) i;
  1802. auto a = (1.0f - x) * t[i];
  1803. return a + x * t[i + 1];
  1804. }
  1805. double smoothLaw() const noexcept
  1806. {
  1807. const auto v = raw[0x28];
  1808. auto c = v * v;
  1809. c = c * v;
  1810. return (double) c;
  1811. }
  1812. // decay time law (seconds): the table at 10·x scaled by the minimum-decay ratio
  1813. double decayTime (float q) const noexcept
  1814. {
  1815. auto f = (float) (minDecay / (double) 0.1850000023841858f);
  1816. f = f * (1.0f - q);
  1817. f = f + q;
  1818. if (1.0f <= q)
  1819. return (double) (2.2249999046325684f * f);
  1820. auto y = q * 10.0f;
  1821. const auto k = (int) y;
  1822. y = y - (float) k;
  1823. auto a = (1.0f - y) * decayTable[k];
  1824. a = a + y * decayTable[k + 1];
  1825. return (double) (a * f);
  1826. }
  1827. struct Env
  1828. {
  1829. double attackTime = 0.00077, level = 0.5, attackInc = 0.0, phase = 0.0, decayTime = 0.01, decayPhase = 0.0, decayInc = 0.0;
  1830. double releaseTime = 3.2, releaseTarget = 0.1, out = 0.0, releaseCoef = 0.0, fs = 44100.0;
  1831. int stage = 2;
  1832. void restart() noexcept { phase = 0.0, decayPhase = 0.0, stage = 0; }
  1833. float tick() noexcept
  1834. {
  1835. if (stage == 0)
  1836. {
  1837. auto x = attackInc + phase;
  1838. phase = x;
  1839. if (x > 1.0)
  1840. {
  1841. stage = 1;
  1842. phase = 1.0;
  1843. x = 1.0;
  1844. }
  1845. out = x * x * x * level;
  1846. return (float) out;
  1847. }
  1848. if (stage == 1)
  1849. {
  1850. auto y = decayInc + decayPhase;
  1851. decayPhase = y;
  1852. if (y > 1.0)
  1853. {
  1854. stage = 2;
  1855. decayPhase = 1.0;
  1856. y = 1.0;
  1857. }
  1858. const auto f = (float) (1.0 - y);
  1859. auto c = f * f;
  1860. c = c * f;
  1861. out = (double) (1.0f - c) * (1.0 - level) + level;
  1862. return (float) out;
  1863. }
  1864. if (stage == 2)
  1865. {
  1866. out = releaseCoef * out;
  1867. return (float) out;
  1868. }
  1869. return 0.0f;
  1870. }
  1871. };
  1872. // the accent circuit: two RC paths whose time constants follow resonance and accent (§2.6)
  1873. struct Circuit
  1874. {
  1875. double ratio = 0.0, gUp = 0.0, gOut = 0.0, gDown = 0.0, cachedRes = 0.0, cachedAcc = 0.0, cA = 0.0, cB = 0.0, fs = 44100.0;
  1876. double out = 0.0, s1 = 3.25, s2 = 3.25;
  1877. bool dirty = true;
  1878. float tick (double r, double a, float drive) noexcept
  1879. {
  1880. if (dirty || r != cachedRes || a != cachedAcc)
  1881. {
  1882. dirty = false;
  1883. cachedRes = r;
  1884. cachedAcc = a;
  1885. const auto x1 = a * 50000.0;
  1886. const auto ra = (1.0 - a) * 50000.0;
  1887. const auto rr = (1.0 - r) * 50000.0;
  1888. const auto r5 = r * 50000.0;
  1889. auto par = ra * x1;
  1890. par = par / (ra + x1);
  1891. par = par + 47000.0;
  1892. par = par + r5;
  1893. auto t = 1.0 / par + 1e-05;
  1894. auto rtot = 1.0 / t + rr;
  1895. const auto rb = rr + 100000.0;
  1896. cA = 1.0 - powD (0.37, 1.0 / (rtot * 1e-06 * fs));
  1897. cB = 1.0 - powD (0.37, 1.0 / (rb * 1e-06 * fs));
  1898. par = par + 100000.0;
  1899. gUp = 100000.0 / par;
  1900. gOut = rr / rtot;
  1901. gDown = 100000.0 / rb;
  1902. ratio = gDown;
  1903. }
  1904. auto in = (double) drive * a;
  1905. in = in - 0.43;
  1906. const auto thr = (s2 - s1) * ratio + s1;
  1907. double o;
  1908. if (in > thr)
  1909. {
  1910. auto t = (in - s1) * gUp + s1;
  1911. s2 = (t - s2) * cA + s2;
  1912. o = (t - s2) * gOut + s2;
  1913. }
  1914. else
  1915. {
  1916. s2 = (s1 - s2) * cB + s2;
  1917. o = (s2 - s1) * gDown + s1;
  1918. }
  1919. out = o;
  1920. return (float) o;
  1921. }
  1922. };
  1923. void oscSelect (double xn) noexcept
  1924. {
  1925. const auto& st = sawTables();
  1926. const auto x0 = (float) xn;
  1927. const auto xd = (double) x0;
  1928. const auto a = (float) (xd * 12.0);
  1929. const auto pw2 = powF (2.0f, a);
  1930. const auto t = (float) ((double) pw2 * 8.17579891564);
  1931. const auto inc = (float) ((double) t * oscInvFs);
  1932. oscInc = (double) inc;
  1933. auto idx = (int) ((xd + oscIndexOffset) * (double) 48);
  1934. idx = idx < 0 ? 0 : std::min (idx, 47);
  1935. oscLen = (double) st.length[(std::size_t) idx];
  1936. oscTab = st.data[(std::size_t) idx].data();
  1937. }
  1938. void selectRecorded (int thr) noexcept
  1939. {
  1940. if (dll == nullptr || dll->recorded2.empty())
  1941. return;
  1942. int found = 0;
  1943. for (int i = (int) dll->recorded2.size() - 1; i >= 0; --i)
  1944. if (thr < dll->recorded2[(std::size_t) i].length)
  1945. {
  1946. found = i;
  1947. break;
  1948. }
  1949. recLen = (double) dll->recorded2[(std::size_t) found].length;
  1950. recTab = dll->recorded2[(std::size_t) found].data.data();
  1951. }
  1952. std::shared_ptr<const DllData> dll;
  1953. bool ext = true;
  1954. std::array<float, 256> raw {}, p {};
  1955. std::array<double, 128> noteTable {};
  1956. int oversampling = 4;
  1957. double fsBase = 44100.0, invFs = 1.0 / 44100.0, fsOs = 176400.0, invFsOs = 1.0 / 176400.0;
  1958. double minDecay = 0.185, decayCoef = 0.0, accentDecayCoef = 0.0, env = 0.0, envCopy = 0.0;
  1959. float cutoff = 0.0f, res = 0.0f, envMod = 0.0f, volume = 0.0f, pw = 0.5f, lfoAmount = 0.0f, lfoPhase = 0.0f, lfoInc = 0.0f;
  1960. bool gate = false, accentOn = false, distOn = false, pulse = false;
  1961. std::array<double, 2> glideTime { 0.0001, 0.05 }, slideCoef {};
  1962. int slideIndex = 0, oscCycles = 0;
  1963. double pitch = 0.0, target = 0.0;
  1964. float pulseWidth = 0.5f;
  1965. double oscPhase = 0.0, oscInc = 0.0, oscLen = 0.0, oscInvFs = 0.0, oscIndexOffset = 0.0;
  1966. const float* oscTab = nullptr;
  1967. double recPhase = 0.0, recInc = 0.0, recLen = 0.0, recFreq = 440.0, recInvFs = 0.0;
  1968. const float* recTab = nullptr;
  1969. double vca1 = 0.0, vca2 = 0.0, vcaUp = 0.0, vcaDown = 0.0, vcaSmoothCoef = 0.0;
  1970. Env env1, env2, env3;
  1971. Circuit circuit;
  1972. Ladder ladder;
  1973. OnePole hp;
  1974. float hpFreqParam = 200.0f;
  1975. HalfBand dec1, dec2;
  1976. Distortion dist;
  1977. };
  1978. // ------------------------------------------------------------------------------------------------------ state (§2.2)
  1979. struct Step
  1980. {
  1981. bool slide = false, gate = false, accent = false;
  1982. int note = 60;
  1983. double length = 0.5;
  1984. float velocity = 0.5f;
  1985. };
  1986. struct Sequence
  1987. {
  1988. std::array<Step, 32> steps {};
  1989. int length = 16;
  1990. double bpm = 125.0, shuffle = 0.0, gateLength = 0.66;
  1991. bool internalBpm = false;
  1992. };
  1993. struct Program
  1994. {
  1995. int patch = 0, sequence = 0, transpose = 0;
  1996. };
  1997. struct State
  1998. {
  1999. bool usable = false;
  2000. int version = 0, program = 0, sequencerMode = 0, engine = 0, oversampling = 4;
  2001. float seqTranspose = 0.0f;
  2002. std::array<Program, 128> programs {};
  2003. std::vector<std::array<float, 100>> patches; // the working copies (the second of each stored pair)
  2004. std::vector<Sequence> sequences;
  2005. };
  2006. struct Reader
  2007. {
  2008. const std::vector<std::uint8_t>& b;
  2009. std::size_t at;
  2010. bool ok = true;
  2011. template <typename T> T get()
  2012. {
  2013. T v {};
  2014. if (at + sizeof (T) > b.size())
  2015. {
  2016. ok = false;
  2017. return v;
  2018. }
  2019. std::memcpy (&v, b.data() + at, sizeof (T));
  2020. at += sizeof (T);
  2021. return v;
  2022. }
  2023. void skipString()
  2024. {
  2025. const auto n = get<std::int32_t>();
  2026. if (n < 0 || at + (std::size_t) n > b.size())
  2027. ok = false;
  2028. else
  2029. at += (std::size_t) n;
  2030. }
  2031. };
  2032. State parseState (const std::vector<std::uint8_t>& s)
  2033. {
  2034. State st;
  2035. Reader r { s, 0 };
  2036. const auto wrapperVersion = r.get<std::uint32_t>(); // the presets carry 1, FL 2026 saves 2; the wrapper refuses > 2
  2037. if (wrapperVersion < 1 || wrapperVersion > 2)
  2038. return st;
  2039. std::size_t engineAt = 0, engineEnd = 0;
  2040. while (r.ok && r.at + 12 <= s.size())
  2041. {
  2042. const auto id = r.get<std::uint32_t>();
  2043. const auto n = r.get<std::uint64_t>();
  2044. if (n > s.size() - r.at)
  2045. return st;
  2046. if (id == 2)
  2047. engineAt = r.at, engineEnd = r.at + (std::size_t) n;
  2048. r.at += (std::size_t) n;
  2049. }
  2050. if (engineAt == 0)
  2051. return st;
  2052. Reader e { s, engineAt };
  2053. e.get<std::uint32_t>();
  2054. const auto n = e.get<std::uint64_t>();
  2055. if (! e.ok || e.at + n != engineEnd)
  2056. return st;
  2057. st.version = e.get<std::int16_t>();
  2058. if (st.version < 1 || st.version > 5)
  2059. return st;
  2060. st.program = e.get<std::int32_t>();
  2061. e.get<std::int32_t>();
  2062. e.get<std::uint8_t>();
  2063. for (auto& p : st.programs)
  2064. {
  2065. e.get<std::int16_t>();
  2066. e.skipString();
  2067. p.sequence = e.get<std::int32_t>();
  2068. p.patch = e.get<std::int32_t>();
  2069. p.transpose = e.get<std::int32_t>();
  2070. }
  2071. st.patches.resize (128);
  2072. for (int k = 0; k < 128; ++k)
  2073. for (int c = 0; c < 2; ++c)
  2074. {
  2075. e.skipString();
  2076. std::array<float, 100> v {};
  2077. for (auto& x : v)
  2078. x = e.get<float>();
  2079. if (c == 1)
  2080. st.patches[(std::size_t) k] = v;
  2081. }
  2082. st.sequences.resize (128);
  2083. for (auto& q : st.sequences)
  2084. {
  2085. const auto ver = e.get<std::int16_t>();
  2086. e.skipString();
  2087. e.get<std::int16_t>();
  2088. q.length = e.get<std::int32_t>();
  2089. for (auto& stp : q.steps)
  2090. {
  2091. const auto sv = e.get<std::int16_t>();
  2092. stp.slide = e.get<std::int8_t>() > 0;
  2093. stp.note = e.get<std::int32_t>();
  2094. stp.gate = e.get<std::int8_t>() > 0;
  2095. stp.length = e.get<double>();
  2096. stp.velocity = e.get<float>();
  2097. if (sv == 1)
  2098. stp.accent = e.get<std::int8_t>() > 0;
  2099. }
  2100. q.bpm = e.get<double>();
  2101. q.internalBpm = e.get<std::int8_t>() > 0;
  2102. q.shuffle = e.get<double>();
  2103. q.gateLength = 0.66;
  2104. if (ver > 0)
  2105. q.gateLength = e.get<double>();
  2106. }
  2107. st.sequencerMode = e.get<std::int32_t>() != 0 ? 4 : 0;
  2108. if (st.version >= 2)
  2109. {
  2110. st.seqTranspose = (float) e.get<std::int32_t>();
  2111. e.get<std::int32_t>();
  2112. e.get<std::int32_t>();
  2113. e.get<std::int32_t>();
  2114. }
  2115. if (st.version >= 3)
  2116. st.oversampling = e.get<std::int32_t>();
  2117. st.engine = 0;
  2118. if (st.version >= 5)
  2119. st.engine = e.get<std::int32_t>();
  2120. st.usable = e.ok && e.at == engineEnd && st.program >= 0 && st.program < 128;
  2121. for (const auto& p : st.programs)
  2122. if (p.patch < 0 || p.patch >= 128 || p.sequence < 0 || p.sequence >= 128)
  2123. st.usable = false;
  2124. return st;
  2125. }
  2126. // ------------------------------------------------------------------------------------------- the plugin (§2.10)
  2127. class Plugin
  2128. {
  2129. public:
  2130. Plugin (const State& s, std::shared_ptr<const DllData> d, double fs) : st (s), dll (std::move (d))
  2131. {
  2132. if (st.engine == 0)
  2133. engine = std::make_unique<Engine1> (dll);
  2134. else
  2135. engine = std::make_unique<Engine2> (dll, st.engine == 1);
  2136. reverb.reset();
  2137. program = st.program;
  2138. seqMode = st.sequencerMode;
  2139. seqTranspose = st.seqTranspose;
  2140. applyPatch();
  2141. setRate (fs);
  2142. }
  2143. void setRate (double fs) noexcept
  2144. {
  2145. engine->setRate (fs);
  2146. delay.setRate (fs);
  2147. reverb.allocate (fs);
  2148. xfLength = (int) (fs * 0.3);
  2149. xfStep = 1.0f / (float) xfLength;
  2150. rate = fs;
  2151. invRate = 1.0 / fs;
  2152. }
  2153. void setTempo (double bpm) noexcept { hostTempo = bpm; }
  2154. // MyPlugin note-on (§2.10)
  2155. void noteOn (int channel, int key, int velocity) noexcept
  2156. {
  2157. if (channel == 12)
  2158. {
  2159. seqTranspose = (float) (key - 60);
  2160. return;
  2161. }
  2162. lastKey = key;
  2163. if (seqMode == 0)
  2164. {
  2165. releaseList();
  2166. held.clear();
  2167. arpNoteOn (key, (float) velocity / 127.0f);
  2168. playing = false;
  2169. return;
  2170. }
  2171. const auto oldPatch = st.programs[(std::size_t) program].patch;
  2172. program = std::clamp (key, 0, 127);
  2173. if (st.programs[(std::size_t) program].patch != oldPatch)
  2174. reset();
  2175. if (seqMode != 0)
  2176. arpNoteOn (0, 1.0f);
  2177. applyPatch();
  2178. playing = true;
  2179. }
  2180. void noteOff (int channel, int key) noexcept
  2181. {
  2182. if (channel == 12)
  2183. return;
  2184. if (seqMode != 0)
  2185. {
  2186. if (key != lastKey)
  2187. return;
  2188. key = 0;
  2189. }
  2190. arpNoteOff (key);
  2191. playing = false;
  2192. }
  2193. void setPanExpression (float pan) noexcept
  2194. {
  2195. auto p = (pan + 1.0f) * 0.5f;
  2196. p = 0.0f <= p ? std::min (1.0f, p) : 0.0f;
  2197. gainR = std::sqrt (p);
  2198. gainL = std::sqrt (1.0f - p);
  2199. }
  2200. void setPitchExpression (float semis) noexcept { engine->pitchExpr = semis * 0.009999999776482582f; }
  2201. void setCutExpression (float x) noexcept { engine->cutExpr = x; }
  2202. void setResExpression (float y) noexcept { engine->resExpr = y; }
  2203. void render (float* left, float* right, int n) noexcept
  2204. {
  2205. RenderMode mode;
  2206. for (int i = 0; i < n; ++i)
  2207. {
  2208. const auto& q = st.sequences[(std::size_t) st.programs[(std::size_t) program].sequence];
  2209. const auto tempo = q.internalBpm ? q.bpm : hostTempo;
  2210. if (playing)
  2211. {
  2212. engine->transpose = seqTranspose;
  2213. clockSequencer (tempo);
  2214. }
  2215. else
  2216. engine->transpose = 0.0f;
  2217. const auto s = engine->tick();
  2218. auto l = s * gainL, r = s * gainR;
  2219. if (delayOn)
  2220. {
  2221. if (i == 0)
  2222. delayTimes (tempo);
  2223. delay.tick (l, r, xfA, xfB);
  2224. if (xfading)
  2225. {
  2226. const auto f = (float) xfCount * xfStep;
  2227. if (xfIndex == 0)
  2228. xfA = 1.0f - f, xfB = f;
  2229. else
  2230. xfA = f, xfB = 1.0f - f;
  2231. if (++xfCount == xfLength)
  2232. {
  2233. xfading = false;
  2234. xfA = 0.5f > xfA ? 0.0f : 1.0f;
  2235. xfB = 0.5f > xfB ? 0.0f : 1.0f;
  2236. xfIndex = xfTarget;
  2237. }
  2238. }
  2239. }
  2240. left[i] = l * midiVolume;
  2241. right[i] = r * midiVolume;
  2242. }
  2243. if (0.5f <= params[0x0E])
  2244. reverb.process (left, right, n);
  2245. }
  2246. // delay times at the start of each block: first use sets both taps; later changes crossfade over 0.3 s (§2.8)
  2247. void delayTimes (double tempo) noexcept
  2248. {
  2249. float t;
  2250. if (delaySync)
  2251. {
  2252. const auto beat = tempo / 60.0;
  2253. t = (float) ((double) delaySyncTime * (1.0 / beat));
  2254. }
  2255. else
  2256. t = delayFreeTime;
  2257. if (delayTime == 0.0f)
  2258. {
  2259. delayTime = t;
  2260. delay.time[0] = t;
  2261. delay.updateTaps (0);
  2262. delay.time[1] = delayTime;
  2263. delay.updateTaps (1);
  2264. delay.right[0] = delayRightNow;
  2265. delay.updateTaps (0);
  2266. delay.right[1] = delayRightNow;
  2267. delay.updateTaps (1);
  2268. }
  2269. if (! xfading && (delayTime != t || delayRightNow != delayRight))
  2270. {
  2271. xfading = true;
  2272. xfCount = 0;
  2273. xfTarget = xfIndex ^ 1;
  2274. delayTime = t;
  2275. delayRightNow = delayRight;
  2276. delay.time[(std::size_t) xfTarget] = t;
  2277. delay.right[(std::size_t) xfTarget] = delayRight;
  2278. delay.updateTaps (xfTarget);
  2279. }
  2280. }
  2281. bool silent() const noexcept { return engine->silent(); }
  2282. private:
  2283. void applyPatch() noexcept
  2284. {
  2285. const auto& patch = st.patches[(std::size_t) st.programs[(std::size_t) program].patch];
  2286. for (int i = 0; i < 0x2A; ++i)
  2287. setParam (i, (double) patch[(std::size_t) i]);
  2288. }
  2289. // MyPlugin parameter setter (§2.10)
  2290. void setParam (int i, double value) noexcept
  2291. {
  2292. const auto d = 0.0 <= value ? std::min (1.0, value) : 0.0;
  2293. const auto v = (float) d;
  2294. engine->setParam (i, v);
  2295. params[(std::size_t) i] = v;
  2296. switch (i)
  2297. {
  2298. case 0x0F: reverb.setParam (1, v); break;
  2299. case 0x10: reverb.setParam (2, v); break;
  2300. case 0x11: reverb.setParam (3, v); break;
  2301. case 0x12: reverb.setParam (4, v); break;
  2302. case 0x13: reverb.setParam (5, v); break;
  2303. case 0x14: reverb.setParam (6, v); break;
  2304. case 0x15: reverb.setParam (9, (float) (d * d)); break;
  2305. case 0x16: reverb.setParam (10, v); break;
  2306. case 0x17: reverb.setParam (14, v); break;
  2307. case 0x18: reverb.setParam (11, v); break;
  2308. case 0x19: reverb.setParam (12, v); break;
  2309. case 0x1A: reverb.setParam (13, v); break;
  2310. case 0x20: delayOn = 0.5 <= d; break;
  2311. case 0x21: delaySync = 0.5 <= d; break;
  2312. case 0x22: delay.send = v; break;
  2313. case 0x23:
  2314. {
  2315. static constexpr double sync[18] = { 0.015625, 0.03125, 0.041666666666666664, 0.046875, 0.0625, 0.08333333333333333, 0.09375, 0.3333333333333333, 0.125,
  2316. 0.16666666666666666, 0.1875, 0.25, 0.3333333333333333, 0.375, 0.5, 0.6666666666666666, 0.75, 1.0 };
  2317. const auto x = (double) params[0x23];
  2318. const auto k = (int) ((double) (0x12 - 1) * x + 0.5);
  2319. delaySyncTime = (float) (sync[k] * 4.0);
  2320. delayFreeTime = (float) (x * 0.49 + 0.01);
  2321. break;
  2322. }
  2323. case 0x24: delayRight = v; break;
  2324. case 0x25: delay.feedback = v; break;
  2325. case 0x26: delay.tone = v; break;
  2326. case 0x27:
  2327. {
  2328. auto a = v * 0.5f;
  2329. a = a + 0.5f;
  2330. delay.stereoA = a;
  2331. delay.stereoB = 1.0f - a;
  2332. break;
  2333. }
  2334. default: break;
  2335. }
  2336. }
  2337. void reset() noexcept
  2338. {
  2339. releaseList();
  2340. held.clear();
  2341. engine->noteOff();
  2342. delay.clear();
  2343. reverb.reset();
  2344. reverb.dirty = true;
  2345. playing = false;
  2346. }
  2347. // ---- the arpeggiator / sequencer object (§2.10)
  2348. struct Held { int note; float velocity; };
  2349. void arpNoteOn (int note, float vel) noexcept
  2350. {
  2351. if (seqMode == 0)
  2352. {
  2353. targetNoteOn (note, vel, false);
  2354. return;
  2355. }
  2356. for (const auto& h : held)
  2357. if (h.note == note)
  2358. return;
  2359. if (held.size() >= 20)
  2360. return;
  2361. if (held.empty())
  2362. {
  2363. octave = 0;
  2364. heldIndex = 0;
  2365. position = 0.0;
  2366. stepIndex = -1;
  2367. }
  2368. held.push_back ({ note, vel });
  2369. }
  2370. void arpNoteOff (int note) noexcept
  2371. {
  2372. if (seqMode == 0)
  2373. {
  2374. targetNoteOff();
  2375. return;
  2376. }
  2377. for (std::size_t i = 0; i < held.size(); ++i)
  2378. if (held[i].note == note)
  2379. {
  2380. held.erase (held.begin() + (std::ptrdiff_t) i);
  2381. break;
  2382. }
  2383. if (held.empty())
  2384. releaseList();
  2385. }
  2386. void releaseList() noexcept
  2387. {
  2388. for (std::size_t i = 0; i < sounding.size(); ++i)
  2389. targetNoteOff();
  2390. sounding.clear();
  2391. gateLeft = 0.0;
  2392. }
  2393. void targetNoteOn (int note, float vel, bool accentFlag) noexcept
  2394. {
  2395. const auto acc = accentFlag || 0.8661417365074158f <= vel;
  2396. engine->noteOn (note + st.programs[(std::size_t) program].transpose, targetCount > 0, acc);
  2397. ++targetCount;
  2398. }
  2399. void targetNoteOff() noexcept
  2400. {
  2401. targetCount = std::max (0, targetCount - 1);
  2402. if (targetCount == 0)
  2403. engine->noteOff();
  2404. }
  2405. void stepEvent (const Step& s, const Sequence& q) noexcept
  2406. {
  2407. if (! s.gate)
  2408. return;
  2409. if (gateLeft < 10000.0)
  2410. releaseList();
  2411. if (held.empty() || seqMode != 4)
  2412. return;
  2413. if (heldIndex >= (int) held.size())
  2414. heldIndex = 0;
  2415. const auto& h = held[(std::size_t) heldIndex];
  2416. const auto note = std::clamp (s.note + octave * 12 + h.note, 0, 127);
  2417. auto vel = (1.0f - velocityMix) * s.velocity;
  2418. vel = vel + velocityMix * h.velocity;
  2419. targetNoteOn (note, vel, s.accent);
  2420. releaseList();
  2421. sounding.push_back (note);
  2422. gateLeft = s.slide ? 20000.0 : q.gateLength;
  2423. ++heldIndex;
  2424. }
  2425. void clockSequencer (double tempo) noexcept
  2426. {
  2427. const auto& q = st.sequences[(std::size_t) st.programs[(std::size_t) program].sequence];
  2428. auto inc = tempo * 0.06666666666666667;
  2429. inc = inc * invRate;
  2430. if (seqMode == 0)
  2431. return;
  2432. inc = inc * rateScale;
  2433. const auto shuffle = -q.shuffle;
  2434. const auto sw = shuffle * 0.5 + 1.0;
  2435. auto pos = position;
  2436. auto x = pos - (double) ((int) pos & ~1);
  2437. auto base = pos - x;
  2438. double idx;
  2439. if (1.0 < x)
  2440. {
  2441. const auto a = (2.0 - sw) * (x - 1.0);
  2442. idx = a + (base + sw);
  2443. }
  2444. else
  2445. idx = x * sw + base;
  2446. const auto step = (int) idx;
  2447. if (stepIndex != step)
  2448. {
  2449. stepIndex = step;
  2450. if (step >= 0 && step < 32)
  2451. stepEvent (q.steps[(std::size_t) step], q);
  2452. }
  2453. if (! sounding.empty())
  2454. {
  2455. gateLeft = gateLeft - inc;
  2456. if (0.0 > gateLeft)
  2457. {
  2458. for (std::size_t i = 0; i < sounding.size(); ++i)
  2459. targetNoteOff();
  2460. sounding.clear();
  2461. gateLeft = 0.0;
  2462. }
  2463. }
  2464. pos = inc + position;
  2465. position = pos;
  2466. if ((double) q.length <= pos)
  2467. {
  2468. position = pos - (double) (int) pos;
  2469. stepIndex = -1;
  2470. }
  2471. }
  2472. State st;
  2473. std::shared_ptr<const DllData> dll;
  2474. std::unique_ptr<Engine> engine;
  2475. std::array<float, 0x2A> params {};
  2476. Delay delay;
  2477. Reverb reverb;
  2478. bool delayOn = false, delaySync = false, xfading = false;
  2479. float delaySyncTime = 0.0f, delayFreeTime = 0.0f, delayRight = 0.0f, delayRightNow = 0.0f, delayTime = 0.0f;
  2480. float xfA = 1.0f, xfB = 0.0f, xfStep = 0.0f;
  2481. int xfLength = 13230, xfCount = 0, xfIndex = 0, xfTarget = 0;
  2482. double rate = 44100.0, invRate = 1.0 / 44100.0, hostTempo = 125.0, rateScale = 1.0;
  2483. int program = 0, seqMode = 0, lastKey = -1, targetCount = 0;
  2484. float seqTranspose = 0.0f, gainL = 1.0f, gainR = 1.0f, midiVolume = 1.0f, velocityMix = 0.0f;
  2485. bool playing = false;
  2486. std::vector<Held> held;
  2487. std::vector<int> sounding;
  2488. int octave = 0, heldIndex = 0, stepIndex = -1;
  2489. double position = 0.0, gateLeft = 0.0;
  2490. };
  2491. // MIDI velocity as FL's wrapper derives it from Init.Vol (§2.10)
  2492. int velocityFromInitVol (double initVol) noexcept
  2493. {
  2494. auto v = lnF ((float) initVol * 10.0f + 1.0f) / lnF (21.0f) * 127.0f;
  2495. v = 0.0f > v ? 0.0f : std::min (127.0f, v);
  2496. return (int) v;
  2497. }
  2498. // ------------------------------------------------------------------------------------------------ LYNX instrument
  2499. class TransistorBassInstrument final : public Instrument
  2500. {
  2501. public:
  2502. ~TransistorBassInstrument() override
  2503. {
  2504. delete incoming.exchange (nullptr);
  2505. delete retired.exchange (nullptr);
  2506. }
  2507. void prepare (double sr) noexcept override
  2508. {
  2509. delete retired.exchange (nullptr);
  2510. take();
  2511. if (sr == rate.load() && plugin != nullptr)
  2512. return;
  2513. rate.store (sr);
  2514. delete incoming.exchange (build().release());
  2515. take();
  2516. }
  2517. void configure (const ChannelDef& channel, double bpm) noexcept override
  2518. {
  2519. delete retired.exchange (nullptr);
  2520. tempo.store (bpm > 0.0 ? bpm : 140.0);
  2521. channelCents.store (channel.sampler.pitch * 100.0f);
  2522. if (channel.pluginState == state && channel.samplePath == dllPath)
  2523. return;
  2524. state = channel.pluginState;
  2525. dllPath = channel.samplePath;
  2526. parsed = parseState (state);
  2527. data = loadDll (dllPath);
  2528. delete incoming.exchange (build().release());
  2529. }
  2530. void setNextNoteExpression (float pan, float cents, bool) noexcept override
  2531. {
  2532. nextPan = pan;
  2533. nextCents = cents;
  2534. }
  2535. void noteOn (int key, float velocity) noexcept override
  2536. {
  2537. take();
  2538. if (plugin == nullptr)
  2539. return;
  2540. const auto k = std::clamp (key, 0, 127);
  2541. const auto vel = std::clamp ((double) velocity, 0.0, 1.0);
  2542. const auto initVol = (std::pow (11.0, 1.28 * vel) - 1.0) / 10.0;
  2543. const auto v7 = velocityFromInitVol (initVol);
  2544. if (sounding[(std::size_t) k])
  2545. plugin->noteOff (0, k);
  2546. sounding[(std::size_t) k] = true;
  2547. notePan[(std::size_t) k] = nextPan;
  2548. noteCents[(std::size_t) k] = (float) channelCents.load() + nextCents;
  2549. plugin->noteOn (0, k, v7);
  2550. sent[(std::size_t) k] = false;
  2551. nextPan = 0.0f, nextCents = 0.0f;
  2552. quiet = 0;
  2553. }
  2554. void noteOff (int key) noexcept override
  2555. {
  2556. take();
  2557. const auto k = std::clamp (key, 0, 127);
  2558. if (plugin == nullptr || ! sounding[(std::size_t) k])
  2559. return;
  2560. sounding[(std::size_t) k] = false;
  2561. plugin->noteOff (0, k);
  2562. }
  2563. void allNotesOff() noexcept override
  2564. {
  2565. for (int k = 0; k < 128; ++k)
  2566. noteOff (k);
  2567. }
  2568. // idle once no key is held and the output (synth, delay and reverb tails) stayed below −140 dB for half a second
  2569. bool idle() const noexcept override { return plugin == nullptr || quiet >= (int) (rate.load() * 0.5); }
  2570. void render (float* left, float* right, int n, float gl, float gr) noexcept override
  2571. {
  2572. take();
  2573. if (plugin == nullptr || n <= 0)
  2574. return;
  2575. const auto vol = std::sqrt (((double) gl * gl + (double) gr * gr) * 0.5);
  2576. auto pan = vol > 0.0 ? std::atan2 ((double) gr, (double) gl) * (4.0 / 3.141592653589793) - 1.0 : 0.0;
  2577. if (std::fabs (pan) < 1e-9)
  2578. pan = 0.0;
  2579. for (int k = 0; k < 128; ++k)
  2580. if (sounding[(std::size_t) k] && ! sent[(std::size_t) k])
  2581. {
  2582. plugin->setCutExpression (0.0f);
  2583. plugin->setResExpression (0.0f);
  2584. plugin->setPitchExpression (noteCents[(std::size_t) k]);
  2585. plugin->setPanExpression ((float) std::clamp ((double) notePan[(std::size_t) k] + pan, -1.0, 1.0));
  2586. sent[(std::size_t) k] = true;
  2587. }
  2588. plugin->setTempo (tempo.load());
  2589. float peak = 0.0f;
  2590. for (int done = 0; done < n;)
  2591. {
  2592. const auto m = std::min (n - done, (int) scratchL.size());
  2593. plugin->render (scratchL.data(), scratchR.data(), m);
  2594. const auto g = (float) vol;
  2595. for (int i = 0; i < m; ++i)
  2596. {
  2597. left[done + i] += scratchL[(std::size_t) i] * g;
  2598. right[done + i] += scratchR[(std::size_t) i] * g;
  2599. peak = std::max ({ peak, std::fabs (scratchL[(std::size_t) i]), std::fabs (scratchR[(std::size_t) i]) });
  2600. }
  2601. done += m;
  2602. }
  2603. bool held = false;
  2604. for (const auto k : sounding)
  2605. held = held || k;
  2606. quiet = ! held && peak < 1.0e-7f ? std::min (quiet + n, 1 << 30) : 0;
  2607. }
  2608. private:
  2609. std::unique_ptr<Plugin> build() const
  2610. {
  2611. if (! parsed.usable || data == nullptr)
  2612. return nullptr;
  2613. return std::make_unique<Plugin> (parsed, data, rate.load());
  2614. }
  2615. void take() noexcept
  2616. {
  2617. if (retired.load() != nullptr)
  2618. return;
  2619. if (auto* s = incoming.exchange (nullptr))
  2620. {
  2621. retired.store (plugin.release());
  2622. plugin.reset (s);
  2623. sounding.fill (false);
  2624. quiet = 0;
  2625. }
  2626. }
  2627. std::unique_ptr<Plugin> plugin;
  2628. std::atomic<Plugin*> incoming { nullptr }, retired { nullptr };
  2629. State parsed;
  2630. std::shared_ptr<const DllData> data;
  2631. std::atomic<double> rate { 44100.0 }, tempo { 140.0 };
  2632. std::atomic<float> channelCents { 0.0f };
  2633. std::vector<std::uint8_t> state;
  2634. std::string dllPath;
  2635. int quiet = 0;
  2636. std::array<bool, 128> sounding {}, sent {};
  2637. std::array<float, 128> notePan {}, noteCents {};
  2638. float nextPan = 0.0f, nextCents = 0.0f;
  2639. std::array<float, 512> scratchL {}, scratchR {};
  2640. };
  2641. } // namespace
  2642. bool transistorBassStateUsable (const std::vector<std::uint8_t>& state) { return parseState (state).usable; }
  2643. bool transistorBassDllUsable (const std::string& path) { return loadDll (path) != nullptr; }
  2644. std::unique_ptr<Instrument> makeTransistorBassInstrument() { return std::make_unique<TransistorBassInstrument>(); }
  2645. namespace tbass
  2646. {
  2647. std::vector<float> renderReference (const std::vector<std::uint8_t>& state, const std::string& dll, const std::vector<RefNote>& notes,
  2648. double sampleRate, int length, const RefOptions& options)
  2649. {
  2650. const auto st = parseState (state);
  2651. auto data = loadDll (dll);
  2652. if (! st.usable || data == nullptr || length <= 0)
  2653. return {};
  2654. auto plugin = std::make_unique<Plugin> (st, data, sampleRate);
  2655. plugin->setTempo (options.tempo > 0.0 ? options.tempo : 125.0);
  2656. std::vector<float> out (2 * (std::size_t) length);
  2657. std::vector<float> l ((std::size_t) std::max (1, options.block)), r ((std::size_t) std::max (1, options.block));
  2658. struct Pending { int key; float pan, cents, fcut, fres; };
  2659. std::vector<Pending> pending;
  2660. std::array<bool, 128> sounding {};
  2661. for (int n0 = 0; n0 < length;)
  2662. {
  2663. auto len = std::min (options.block, length - n0);
  2664. for (const auto& nt : notes)
  2665. {
  2666. if (nt.start > n0 && nt.start < n0 + len)
  2667. len = nt.start - n0;
  2668. if (nt.release > n0 && nt.release < n0 + len)
  2669. len = nt.release - n0;
  2670. }
  2671. for (const auto& nt : notes)
  2672. if (nt.release == n0 && sounding[(std::size_t) (nt.key & 127)])
  2673. {
  2674. sounding[(std::size_t) (nt.key & 127)] = false;
  2675. plugin->noteOff (nt.channel, nt.key);
  2676. }
  2677. for (const auto& nt : notes)
  2678. if (nt.start == n0)
  2679. {
  2680. const auto v = velocityFromInitVol (nt.initVol);
  2681. if (sounding[(std::size_t) (nt.key & 127)])
  2682. plugin->noteOff (nt.channel, nt.key);
  2683. sounding[(std::size_t) (nt.key & 127)] = true;
  2684. plugin->noteOn (nt.channel, nt.key, v);
  2685. pending.push_back ({ nt.key, (float) nt.finalPan, (float) nt.pitchCents, (float) nt.fcut, (float) nt.fres });
  2686. }
  2687. for (const auto& p : pending)
  2688. {
  2689. plugin->setCutExpression (p.fcut);
  2690. plugin->setResExpression (p.fres);
  2691. plugin->setPitchExpression (p.cents);
  2692. plugin->setPanExpression (p.pan);
  2693. }
  2694. pending.clear();
  2695. plugin->render (l.data(), r.data(), len);
  2696. for (int i = 0; i < len; ++i)
  2697. {
  2698. out[2 * (std::size_t) (n0 + i)] = l[(std::size_t) i];
  2699. out[2 * (std::size_t) (n0 + i) + 1] = r[(std::size_t) i];
  2700. }
  2701. n0 += len;
  2702. }
  2703. return out;
  2704. }
  2705. } // namespace tbass
  2706. } // namespace lynx