4
0

DynamicsSuite.cpp 125 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771
  1. #include "core/DynamicsSuite.h"
  2. #include <algorithm>
  3. #include <array>
  4. #include <atomic>
  5. #include <cmath>
  6. #include <complex>
  7. #include <cstdio>
  8. #include "core/Biquad.h"
  9. #include "core/Effects.h"
  10. #include "core/FacetEq.h"
  11. #include "core/LrCrossover.h"
  12. #include "core/MinPhaseBand.h"
  13. #include "core/MixSuite.h"
  14. #include "core/ParametricEqLinear.h"
  15. // REA_rodada108. Published material the designs rest on:
  16. // - feed-forward compressor with a log-domain level detector (branching attack / release), soft-knee gain computer:
  17. // D. Giannoulis, M. Massberg, J. D. Reiss, "Digital Dynamic Range Compressor Design — A Tutorial and Analysis",
  18. // JAES 60(6), 2012 (§2.2 gain computer, §3 detectors, §4 auto make-up gain);
  19. // - look-ahead by delaying the audio against the side chain: U. Zölzer (ed.), "DAFX", 2nd ed., ch. 4.2;
  20. // - upward compression / expansion as mirrored gain curves of the same computer: ibid. ch. 4.2.2;
  21. // - Linkwitz-Riley crossovers (two cascaded Butterworth sections per side): S. Linkwitz, "Active Crossover
  22. // Networks for Non-coincident Drivers", JAES 24(1), 1976;
  23. // - waveshaping families (smooth odd polynomial, asymmetric clipping, even-order rectifier terms) and their
  24. // harmonic signatures: DAFX ch. 4.3, J. Pakarinen / D. T. Yeh, CMJ 33(2), 2009.
  25. // Every constant that shapes a "style" was fitted by us to the black-box measurements (MEASURE_fabfilter.md); the
  26. // fitted values and their residuals are in REA_rodada108.md.
  27. namespace lynx::dyn
  28. {
  29. namespace
  30. {
  31. constexpr double pi = 3.141592653589793;
  32. inline double dbToGain (double db) noexcept { return std::pow (10.0, db / 20.0); }
  33. inline double gainToDb (double g) noexcept { return 20.0 * std::log10 (std::max (g, 1e-6)); }
  34. inline double logMap (float v, double lo, double hi) noexcept { return lo * std::pow (hi / lo, (double) std::clamp (v, 0.0f, 1.0f)); }
  35. inline float logValue (double x, double lo, double hi) noexcept { return (float) std::clamp (std::log (x / lo) / std::log (hi / lo), 0.0, 1.0); }
  36. inline double lin (float v, double lo, double hi) noexcept { return lo + (hi - lo) * (double) std::clamp (v, 0.0f, 1.0f); }
  37. inline bool on (float v) noexcept { return v >= 0.5f; }
  38. inline double coef (double ms, double sr) noexcept { return ms <= 0.0 ? 0.0 : std::exp (-1.0 / (ms * 0.001 * sr)); }
  39. inline int pick (float v, int n) noexcept { return std::clamp ((int) std::lround (std::clamp (v, 0.0f, 1.0f) * (float) (n - 1)), 0, n - 1); }
  40. // the shared ratio law: 1 .. 100 : 1, 0.5 ≈ 2.7 : 1, 0.6 ≈ 4.5 : 1, 0.75 ≈ 11 : 1
  41. double ratioLaw (float v) noexcept { return std::exp (std::log (100.0) * std::pow ((double) std::clamp (v, 0.0f, 1.0f), 2.2)); }
  42. float ratioLawValue (double r) noexcept { return (float) std::clamp (std::pow (std::log (std::max (1.0, r)) / std::log (100.0), 1.0 / 2.2), 0.0, 1.0); }
  43. // Giannoulis et al. eq. (4): reduction (dB, ≥ 0) for an overshoot `o` (dB above the threshold), slope s = 1 − 1/R
  44. double kneeCurve (double o, double s, double knee) noexcept
  45. {
  46. if (2.0 * o <= -knee)
  47. return 0.0;
  48. if (knee > 0.0 && 2.0 * std::abs (o) < knee)
  49. return s * (o + knee * 0.5) * (o + knee * 0.5) / (2.0 * knee);
  50. return s * o;
  51. }
  52. float blockPeak (const float* l, const float* r, int n) noexcept
  53. {
  54. float p = 0.0f;
  55. for (int i = 0; i < n; ++i)
  56. p = std::max (p, std::max (std::abs (l[i]), std::abs (r[i])));
  57. return std::min (p, 1.0f);
  58. }
  59. // Stereo delay line, fixed capacity (no allocation after construction).
  60. struct StereoDelay
  61. {
  62. static constexpr int capacity = 8192; // 20 ms look-ahead at 192 kHz + the oversampler, with room
  63. std::array<float, capacity> l {}, r {};
  64. int pos = 0, len = 0;
  65. void setLength (int n) noexcept
  66. {
  67. n = std::clamp (n, 0, capacity - 1);
  68. if (n != len)
  69. {
  70. len = n;
  71. reset();
  72. }
  73. }
  74. void reset() noexcept { l.fill (0.0f); r.fill (0.0f); pos = 0; }
  75. void process (float& a, float& b) noexcept
  76. {
  77. if (len == 0)
  78. return;
  79. l[(std::size_t) pos] = a;
  80. r[(std::size_t) pos] = b;
  81. auto rd = pos - len;
  82. if (rd < 0)
  83. rd += capacity;
  84. a = l[(std::size_t) rd];
  85. b = r[(std::size_t) rd];
  86. if (++pos == capacity)
  87. pos = 0;
  88. }
  89. };
  90. // mono float delay (the side chain's gain against the look-ahead)
  91. struct MonoDelay
  92. {
  93. static constexpr int capacity = 8192;
  94. std::array<float, capacity> d {};
  95. int pos = 0, len = 0;
  96. void setLength (int n) noexcept { len = std::clamp (n, 0, capacity - 1); }
  97. void reset() noexcept { d.fill (0.0f); pos = 0; }
  98. float process (float x) noexcept
  99. {
  100. if (len == 0)
  101. return x;
  102. d[(std::size_t) pos] = x;
  103. auto rd = pos - len;
  104. if (rd < 0)
  105. rd += capacity;
  106. const auto y = d[(std::size_t) rd];
  107. if (++pos == capacity)
  108. pos = 0;
  109. return y;
  110. }
  111. };
  112. // first-order DC blocker (stereo)
  113. struct DcBlock
  114. {
  115. double a = 0.9995, x1[2] {}, y1[2] {};
  116. void set (double sr) noexcept { a = std::exp (-2.0 * pi * 5.0 / sr); }
  117. void reset() noexcept { x1[0] = x1[1] = y1[0] = y1[1] = 0.0; }
  118. float process (float x, int c) noexcept
  119. {
  120. const auto y = (double) x - x1[c] + a * y1[c];
  121. x1[c] = x;
  122. y1[c] = y;
  123. return (float) y;
  124. }
  125. };
  126. struct LiveMeters
  127. {
  128. std::array<std::atomic<float>, 8> v {};
  129. float read (int k) const noexcept { return k >= 0 && k < 8 ? v[(std::size_t) k].load (std::memory_order_relaxed) : 0.0f; }
  130. void set (int k, float x) noexcept { v[(std::size_t) k].store (x, std::memory_order_relaxed); }
  131. };
  132. std::string fmt (const char* f, double v)
  133. {
  134. char t[48];
  135. std::snprintf (t, sizeof (t), f, v);
  136. return t;
  137. }
  138. std::string hzText (double f)
  139. {
  140. return f >= 1000.0 ? fmt ("%.2f kHz", f / 1000.0) : fmt ("%.0f Hz", f);
  141. }
  142. std::string msText (double ms)
  143. {
  144. if (ms >= 1000.0)
  145. return fmt ("%.2f s", ms / 1000.0);
  146. if (ms >= 100.0)
  147. return fmt ("%.0f ms", ms);
  148. if (ms >= 10.0)
  149. return fmt ("%.1f ms", ms);
  150. return fmt ("%.2f ms", ms);
  151. }
  152. std::string ratioText (double r) { return r >= 99.5 ? "100 : 1" : fmt (r < 10.0 ? "%.2f : 1" : "%.1f : 1", r); }
  153. } // namespace
  154. // ================================================================== Crest Compressor
  155. namespace crest
  156. {
  157. Style styleOf (float v) noexcept { return (Style) pick (v, styles); }
  158. float styleValue (Style s) noexcept { return (float) (int) s / (float) (styles - 1); }
  159. double thresholdDb (float v) noexcept { return lin (v, -60.0, 0.0); }
  160. double ratioOf (float v) noexcept { return ratioLaw (v); }
  161. float ratioValue (double r) noexcept { return ratioLawValue (r); }
  162. double kneeDb (float v) noexcept { return lin (v, 0.0, 72.0); }
  163. double rangeDb (float v) noexcept { return lin (v, 0.0, 60.0); }
  164. double attackMs (float v) noexcept { return logMap (v, 0.005, 250.0); }
  165. float attackValue (double ms) noexcept { return logValue (std::clamp (ms, 0.005, 250.0), 0.005, 250.0); }
  166. double releaseMs (float v) noexcept { return logMap (v, 10.0, 2500.0); }
  167. float releaseValue (double ms) noexcept { return logValue (std::clamp (ms, 10.0, 2500.0), 10.0, 2500.0); }
  168. double holdMs (float v) noexcept { return 500.0 * (double) v * (double) v; }
  169. float holdValue (double ms) noexcept { return (float) std::sqrt (std::clamp (ms / 500.0, 0.0, 1.0)); }
  170. double lookaheadMs (float v) noexcept { return lin (v, 0.0, 20.0); }
  171. double maxLookaheadMs (float v) noexcept
  172. {
  173. static constexpr double ms[] { 0.0, 1.0, 2.0, 5.0, 10.0, 20.0 };
  174. return ms[pick (v, 6)];
  175. }
  176. Character characterOf (float v) noexcept { return (Character) pick (v, 4); }
  177. double driveDb (float v) noexcept { return lin (v, -24.0, 24.0); }
  178. double scLevelDb (float v) noexcept { return lin (v, -36.0, 36.0); }
  179. int oversamplingOf (float v) noexcept { return 1 << pick (v, 4); }
  180. double panOf (float v) noexcept { return std::clamp ((double) v * 2.0 - 1.0, -1.0, 1.0); }
  181. double trimDb (float v) noexcept { return lin (v, -36.0, 36.0); }
  182. LinkMode linkModeOf (float v) noexcept { return (LinkMode) pick (v, linkModes); }
  183. Trigger triggerOf (float v) noexcept { return (Trigger) pick (v, 3); }
  184. double triggerBeats (float v) noexcept { return 4.0 / (double) (1 << pick (v, 5)); }
  185. double triggerRateOf (float v) noexcept { return std::pow (2.0, 2.0 * (double) std::clamp (v, 0.0f, 1.0f) - 1.0); }
  186. double triggerLengthOf (float v) noexcept { return (double) std::clamp (v, 0.0f, 1.0f); }
  187. int triggerChannelOf (float v) noexcept
  188. {
  189. const auto k = (int) std::lround (std::clamp (v, 0.0f, 1.0f) * 128.0f);
  190. return k <= 0 ? -1 : k - 1;
  191. }
  192. // [EXEC] Pro-C 3 hosted at 120 BPM, a steady sine under the threshold: with Host Sync the gain reduction starts on
  193. // every note × rate (1/4 at 100 % = every 500 ms, 50 % = 250 ms, 200 % = 1 s; 1/8 at 100 % = 250 ms) and holds for
  194. // Length of that period (10 % = 50 ms, 50 % = 250 ms); its depth follows a 0 dBFS key (threshold −18 / −40 / 0 dB,
  195. // ratio 4:1, knee 18 dB: 14 / 32 / 2 dB of reduction)
  196. float hostTrigger (const EffectParams& p, double beats) noexcept
  197. {
  198. const auto period = triggerBeats (p[triggerSync]) * triggerRateOf (p[triggerRate]);
  199. if (period <= 0.0 || beats < 0.0)
  200. return 0.0f;
  201. const auto phase = beats / period - std::floor (beats / period);
  202. return phase < triggerLengthOf (p[triggerLength]) ? 1.0f : 0.0f;
  203. }
  204. float linkModeValue (LinkMode m) noexcept { return (float) (int) m / (float) (linkModes - 1); }
  205. double dryDb (float v) noexcept
  206. {
  207. if (v <= 0.0f)
  208. return -120.0;
  209. if (v >= 0.25f)
  210. return 72.0 * (double) v - 36.0;
  211. return -18.0 + 40.0 * std::log10 ((double) v / 0.25); // amplitude ∝ v² below −18 dB
  212. }
  213. float dryValue (double db) noexcept
  214. {
  215. if (db <= -119.0)
  216. return 0.0f;
  217. if (db >= -18.0)
  218. return (float) std::clamp ((db + 36.0) / 72.0, 0.25, 1.0);
  219. return (float) (0.25 * std::pow (10.0, (db + 18.0) / 40.0));
  220. }
  221. double meterRangeDb (float v) noexcept
  222. {
  223. static constexpr double r[] { 9.0, 18.0, 36.0, 72.0, 90.0 };
  224. return r[pick (v, 5)];
  225. }
  226. double autoThresholdDb (double knobDb, double programRmsDb) noexcept
  227. {
  228. return std::clamp (programRmsDb + knobDb + 18.0, -60.0, 0.0);
  229. }
  230. namespace
  231. {
  232. // The style families (fitted to MEASURE_fabfilter §2, see REA_rodada108 §3): time-constant scales of the level
  233. // detector (τ = scale × knob), the knee every curve gets on top of the knob, and the curve family.
  234. enum class Curve { downward, upward, twoWay, vocal, variMu };
  235. struct StyleDef
  236. {
  237. double attackScale; // detector attack τ = scale × knob
  238. double releaseScale; // detector release τ = scale × 200 ms × (knob / 200 ms)^releaseExp
  239. double releaseExp; // how much the release follows its knob (1 = proportional, 0 = fixed)
  240. double kneeAdd, kneeScale; // knee = add + scale × knob
  241. Curve curve;
  242. double windowMs; // > 0: the level is the peak over this window (a ripple-free detector for fast releases)
  243. };
  244. constexpr StyleDef styleDefs[styles] {
  245. { 0.265, 1.27, 0.77, 6.0, 0.50, Curve::downward, 0.0 }, // clean
  246. { 0.56, 0.94, 0.15, 6.0, 1.00, Curve::downward, 0.0 }, // allround
  247. { 0.31, 1.10, 0.65, 4.0, 0.80, Curve::downward, 0.0 }, // punch
  248. { 0.31, 2.50, 1.00, 0.0, 1.00, Curve::upward, 0.0 }, // upward
  249. { 0.235, 0.01, 0.00, 0.0, 1.00, Curve::twoWay, 1.3 }, // two-way (recovers within about a millisecond)
  250. { 0.335, 0.65, 0.98, 0.0, 1.00, Curve::variMu, 0.0 }, // vari-mu
  251. { 0.30, 1.57, 0.53, 4.0, 0.17, Curve::downward, 0.0 }, // classic
  252. { 0.32, 1.52, 0.88, 4.0, 0.65, Curve::downward, 0.0 }, // opto
  253. { 1.08, 1.70, 0.04, 0.0, 1.00, Curve::vocal, 0.0 }, // vocal
  254. { 0.24, 3.57, 0.19, 0.0, 1.00, Curve::downward, 0.0 }, // bus
  255. { 0.08, 2.36, 1.00, 0.0, 1.00, Curve::downward, 0.0 }, // pumping
  256. };
  257. double releaseTau (const StyleDef& d, double knobMs) noexcept
  258. {
  259. return d.releaseScale * 200.0 * std::pow (knobMs / 200.0, d.releaseExp);
  260. }
  261. // vari-mu: the share of the full ratio reached at an overshoot o (dB), by slope s = 1 − 1/R — measured (§2.1 data,
  262. // slopes 1/3 … 0.99, overshoots 0 … 18 dB) and divided by our detector's own shortfall (0.96)
  263. double variMuShare (double s, double o) noexcept
  264. {
  265. static constexpr double slopes[6] { 0.3333, 0.5, 0.75, 0.875, 0.95, 0.99 };
  266. static constexpr double table[6][10] {
  267. { 0, 0.071, 0.118, 0.189, 0.28, 0.383, 0.491, 0.599, 0.701, 0.797 },
  268. { 0, 0.102, 0.2, 0.311, 0.422, 0.524, 0.615, 0.695, 0.764, 0.824 },
  269. { 0, 0.263, 0.442, 0.561, 0.645, 0.708, 0.758, 0.797, 0.829, 0.856 },
  270. { 0, 0.478, 0.637, 0.723, 0.776, 0.813, 0.841, 0.863, 0.881, 0.896 },
  271. { 0, 0.545, 0.677, 0.742, 0.783, 0.812, 0.833, 0.85, 0.863, 0.875 },
  272. { 0, 0.665, 0.767, 0.811, 0.839, 0.857, 0.871, 0.882, 0.892, 0.9 } };
  273. if (o <= 0.0)
  274. return 0.0;
  275. const auto row = [&] (int k) {
  276. if (o >= 18.0)
  277. return 1.0 - (1.0 - table[k][9]) * 18.0 / o;
  278. const auto x = o / 2.0;
  279. const int i = std::min (8, (int) x);
  280. return table[k][i] + (table[k][i + 1] - table[k][i]) * (x - i);
  281. };
  282. double f;
  283. if (s <= slopes[0])
  284. f = row (0) * s / slopes[0];
  285. else if (s >= slopes[5])
  286. f = row (5);
  287. else
  288. {
  289. int k = 0;
  290. while (s > slopes[k + 1])
  291. ++k;
  292. const auto t = (s - slopes[k]) / (slopes[k + 1] - slopes[k]);
  293. f = row (k) + (row (k + 1) - row (k)) * t;
  294. }
  295. return std::min (1.0, f / 0.96);
  296. }
  297. // target gain change (dB; negative = reduction) for a detector level `x` (dB)
  298. double curveGain (Style st, double x, double thr, double r, double knee, double range) noexcept
  299. {
  300. const auto& d = styleDefs[(int) st];
  301. const auto s = 1.0 - 1.0 / r;
  302. switch (d.curve)
  303. {
  304. case Curve::upward:
  305. {
  306. // upward: quiet parts are lifted toward a point 10.5 dB under the threshold; above it the gain holds
  307. const auto g = s * (thr - 10.5 - std::min (x, thr));
  308. return std::clamp (g, -range, range);
  309. }
  310. case Curve::twoWay:
  311. {
  312. // two-way: a fixed offset, upward compression below (threshold − 6 dB), downward above (threshold + 4 dB)
  313. const auto g = -5.75 * s + 0.473 * s * std::max (0.0, thr - 6.0 - x) - 0.808 * kneeCurve (x - thr - 4.0, s, knee);
  314. return std::clamp (g, -range, range);
  315. }
  316. case Curve::vocal:
  317. {
  318. // a long smooth curve that already reduces far below the threshold (softplus in dB), steeper on top
  319. const auto k = 8.0 + knee * 0.5;
  320. const auto sv = std::min (1.0, 1.1667 * s);
  321. const auto z = (x - (thr - 2.1)) / k;
  322. const auto soft = z > 30.0 ? z : std::log1p (std::exp (z));
  323. return -std::min (range, sv * k * soft);
  324. }
  325. case Curve::variMu:
  326. {
  327. // the ratio grows with the reduction (variable-mu tube behaviour), as measured
  328. const auto o = std::max (0.0, x - thr);
  329. const auto soft = knee > 0.0 ? kneeCurve (x - thr, 1.0, knee) : o;
  330. return -std::min (range, s * soft * variMuShare (s, o + knee * 0.25));
  331. }
  332. case Curve::downward:
  333. default:
  334. return -std::min (range, kneeCurve (x - thr, s, d.kneeAdd + d.kneeScale * knee));
  335. }
  336. }
  337. void scEqParams (const EffectParams& p, EffectParams& out) noexcept
  338. {
  339. out.fill (0.0f);
  340. for (int b = 0; b < scBands; ++b)
  341. for (int f = 0; f < 5; ++f)
  342. out[(std::size_t) facet::param (b, f)] = p[(std::size_t) scParam (b, f)];
  343. out[(std::size_t) facet::outputParam] = 0.5f;
  344. out[(std::size_t) facet::scaleParam] = 0.5f;
  345. }
  346. } // namespace
  347. double staticGainDb (const EffectParams& p, double inputDb)
  348. {
  349. return curveGain (styleOf (p[style]), inputDb, thresholdDb (p[threshold]), ratioOf (p[ratio]), kneeDb (p[knee]),
  350. std::max (0.01, rangeDb (p[range])));
  351. }
  352. float characterCurve (Character c, float x) noexcept
  353. {
  354. switch (c)
  355. {
  356. case Character::warm:
  357. {
  358. // clean up to about +9 dBFS, then an asymmetric soft limit (the negative side gives first): even + odd
  359. constexpr float tp = 6.5f, tn = 3.0f, sp = 2.0f, sn = 1.5f;
  360. if (x > tp)
  361. return tp + sp * std::tanh ((x - tp) / sp);
  362. if (x < -tn)
  363. return -tn - sn * std::tanh ((-x - tn) / sn);
  364. return x;
  365. }
  366. case Character::crisp:
  367. {
  368. // a slightly expanding cubic (odd harmonics growing with the square of the level), then an asymmetric
  369. // limit far above full scale
  370. const auto u = x + 0.0083f * x * x * x;
  371. return u >= 0.0f ? 16.0f * std::tanh (u / 16.0f) : 12.0f * std::tanh (u / 12.0f);
  372. }
  373. case Character::bright:
  374. {
  375. // an even, rectifier-like term (second harmonic from low levels) and a gentle, slightly asymmetric limit
  376. constexpr float s = 0.1f;
  377. const auto u = x + 0.007f * s * (std::sqrt (1.0f + (x / s) * (x / s)) - 1.0f);
  378. const auto limit = u >= 0.0f ? 7.75f : 5.5f;
  379. const auto a = std::abs (u / limit);
  380. const auto d = 1.0f + a * std::sqrt (a);
  381. return u / std::cbrt (d * d); // u / (1 + |u/L|^1.5)^(1/1.5)
  382. }
  383. case Character::off:
  384. default: return x;
  385. }
  386. }
  387. namespace
  388. {
  389. class Compressor final : public Effect
  390. {
  391. public:
  392. explicit Compressor (const EffectParams* initial)
  393. {
  394. for (auto& d : gainDelay)
  395. d.assign ((std::size_t) gainCapacity, 1.0f);
  396. if (initial != nullptr)
  397. configure (*initial);
  398. }
  399. void prepare (double rate) noexcept override
  400. {
  401. sr = rate;
  402. dc.set (sr);
  403. latencyMs = -1.0; // re-apply the delays
  404. configure (lastParams);
  405. reset();
  406. }
  407. void reset() noexcept override
  408. {
  409. audioDelay.reset();
  410. dryLa.reset();
  411. dryDelay.reset();
  412. for (auto& d : gainDelay)
  413. std::fill (d.begin(), d.end(), 1.0f);
  414. gainPos = 0;
  415. for (auto& o : os)
  416. o.reset();
  417. for (auto& o : osSide)
  418. o.reset();
  419. for (auto& b : scEq)
  420. for (auto& s : b)
  421. s.reset();
  422. for (auto& d : det)
  423. d = {};
  424. for (auto& pk : peaks)
  425. pk.fill (0.0f);
  426. dc.reset();
  427. }
  428. int latencySamples() const noexcept override { return latency.load (std::memory_order_relaxed); }
  429. float controlOutput (int k) const noexcept override { return meters.read (k); }
  430. void setSidechain (const float* l, const float* r) noexcept override
  431. {
  432. scL = l;
  433. scR = r;
  434. }
  435. // round 137: the trigger's clock and notes
  436. void setSongPosition (double ticks) noexcept override { songBeats = ticks / (double) ppq; }
  437. void setPlaying (bool playing) noexcept override { transportPlaying = playing; }
  438. void setHeldNotes (const NoteMask* channels, int count) noexcept override
  439. {
  440. held = channels;
  441. heldCount = count;
  442. }
  443. void process (float* l, float* r, int n, const EffectParams& p, double bpm) noexcept override
  444. {
  445. lastParams = p;
  446. configure (p);
  447. designScEq (p);
  448. blockBpm = bpm > 1.0 ? bpm : 120.0;
  449. for (int off = 0; off < n; off += maxBlock)
  450. chunk (l + off, r + off, std::min (maxBlock, n - off), p, off);
  451. scL = scR = nullptr;
  452. }
  453. private:
  454. static constexpr int maxBlock = 1024, maxFactor = 8;
  455. static constexpr int gainCapacity = 1 << 17; // the side chain's lead at up to 8x the rate (20 ms at 768 kHz)
  456. static constexpr int peakWindow = 4096;
  457. // the detector of one channel
  458. struct Detector
  459. {
  460. double env = -120.0, sustain = 0.0;
  461. int holdLeft = 0, peakPos = 0;
  462. };
  463. // per-chunk settings at the rate the detector runs at
  464. struct Ctx
  465. {
  466. Style st;
  467. double thr, rat, kn, rng, aA, relMs, rate, slowCoef;
  468. int holdSamples, window;
  469. bool autoRel;
  470. };
  471. // latency = the chosen maximum look-ahead (+ the oversampler when on), as the reference does (§2: 960 samples
  472. // for "maximum 20 ms" whatever the look-ahead knob says)
  473. void configure (const EffectParams& p) noexcept
  474. {
  475. const auto la = maxLookaheadMs (p[maxLookahead]);
  476. const auto factor = oversamplingOf (p[oversampling]);
  477. if (la == latencyMs && factor == osFactor)
  478. return;
  479. latencyMs = la;
  480. osFactor = factor;
  481. laSamples = (int) std::lround (la * 0.001 * sr);
  482. const auto osLat = osFactor > 1 ? mixsuite::Oversampler::latency() : 0;
  483. audioDelay.setLength (laSamples);
  484. dryLa.setLength (laSamples);
  485. dryDelay.setLength (osLat);
  486. for (auto* set : { &os, &osSide })
  487. for (auto& o : *set)
  488. o.setFactor (std::max (2, osFactor));
  489. latency.store (laSamples + osLat, std::memory_order_relaxed);
  490. }
  491. void designScEq (const EffectParams& p) noexcept
  492. {
  493. EffectParams fp;
  494. scEqParams (p, fp);
  495. bool any = false;
  496. for (int b = 0; b < scBands; ++b)
  497. {
  498. std::array<facet::Section, facet::maxSections> sec;
  499. const auto count = facet::design (fp, b, sr, sec);
  500. scCount[(std::size_t) b] = count;
  501. for (int k = 0; k < count; ++k)
  502. {
  503. auto& q = scEq[(std::size_t) b][(std::size_t) k];
  504. q.b0 = sec[(std::size_t) k].b0; q.b1 = sec[(std::size_t) k].b1; q.b2 = sec[(std::size_t) k].b2;
  505. q.a1 = sec[(std::size_t) k].a1; q.a2 = sec[(std::size_t) k].a2;
  506. }
  507. any = any || count > 0;
  508. }
  509. scEqOn = any;
  510. }
  511. Ctx context (const EffectParams& p, double rate) const noexcept
  512. {
  513. Ctx c;
  514. c.st = styleOf (p[style]);
  515. const auto& sd = styleDefs[(int) c.st];
  516. c.thr = on (p[autoThreshold]) ? autoThresholdDb (thresholdDb (p[threshold]), programDb) : thresholdDb (p[threshold]);
  517. c.rat = ratioOf (p[ratio]);
  518. c.kn = kneeDb (p[knee]);
  519. c.rng = std::max (0.01, rangeDb (p[range]));
  520. c.aA = coef (std::max (0.002, attackMs (p[attack]) * sd.attackScale), rate);
  521. c.relMs = std::max (0.5, releaseTau (sd, releaseMs (p[release])));
  522. c.autoRel = on (p[autoRelease]) && sd.curve != Curve::twoWay;
  523. c.rate = rate;
  524. c.slowCoef = coef (1000.0, rate);
  525. c.holdSamples = (int) (holdMs (p[hold]) * 0.001 * rate);
  526. c.window = sd.windowMs > 0.0 ? std::clamp ((int) (sd.windowMs * 0.001 * rate), 1, peakWindow) : 0;
  527. return c;
  528. }
  529. // one detector step: the level → the gain (dB) the compressor applies now
  530. double detect (int c, double level, const Ctx& x) noexcept
  531. {
  532. auto& d = det[(std::size_t) c];
  533. if (x.window > 0) // the peak of the last `window` samples
  534. {
  535. auto& ring = peaks[(std::size_t) c];
  536. ring[(std::size_t) (d.peakPos % x.window)] = (float) level;
  537. d.peakPos = (d.peakPos + 1) % x.window;
  538. for (int k = 0; k < x.window; ++k)
  539. level = std::max (level, (double) ring[(std::size_t) k]);
  540. }
  541. const auto in = std::max (-120.0, 20.0 * std::log10 (level + 1e-12));
  542. if (in > d.env)
  543. {
  544. d.env = x.aA * d.env + (1.0 - x.aA) * in;
  545. d.holdLeft = x.holdSamples;
  546. }
  547. else if (d.holdLeft > 0)
  548. --d.holdLeft;
  549. else
  550. {
  551. auto ms = x.relMs;
  552. if (x.autoRel) // program-dependent: short peaks recover faster than sustained reduction
  553. {
  554. const auto now = -curveGain (x.st, d.env, x.thr, x.rat, x.kn, x.rng);
  555. const auto fraction = now > 0.1 ? std::clamp (d.sustain / now, 0.0, 1.0) : 1.0;
  556. ms *= 0.35 + 0.65 * fraction;
  557. }
  558. const auto aR = coef (ms, x.rate);
  559. d.env = aR * d.env + (1.0 - aR) * in;
  560. }
  561. const auto g = curveGain (x.st, d.env, x.thr, x.rat, x.kn, x.rng);
  562. d.sustain = x.slowCoef * d.sustain + (1.0 - x.slowCoef) * std::max (0.0, -g);
  563. return g;
  564. }
  565. // the gains of a run of side-chain samples (per channel, or linked), through the look-ahead's gain delay
  566. double gains (const float* a, const float* b, int count, double link, int lag, const Ctx& x, float* outL, float* outR) noexcept
  567. {
  568. double maxGr = 0.0;
  569. const bool both = link >= 0.999;
  570. for (int i = 0; i < count; ++i)
  571. {
  572. const auto la = std::abs (a[i]), lb = std::abs (b[i]);
  573. const auto m = (double) std::max (la, lb);
  574. float g[2];
  575. const auto g0 = detect (0, link * m + (1.0 - link) * la, x);
  576. g[0] = (float) dbToGain (g0);
  577. maxGr = std::max (maxGr, -g0);
  578. if (both)
  579. g[1] = g[0];
  580. else
  581. {
  582. const auto g1 = detect (1, link * m + (1.0 - link) * lb, x);
  583. g[1] = (float) dbToGain (g1);
  584. maxGr = std::max (maxGr, -g1);
  585. }
  586. for (int c = 0; c < 2; ++c)
  587. {
  588. auto& line = gainDelay[(std::size_t) c];
  589. line[(std::size_t) gainPos] = g[c];
  590. const auto rd = (gainPos - lag + gainCapacity) % gainCapacity;
  591. (c == 0 ? outL : outR)[i] = line[(std::size_t) rd];
  592. }
  593. gainPos = (gainPos + 1) % gainCapacity;
  594. }
  595. return maxGr;
  596. }
  597. void chunk (float* l, float* r, int n, const EffectParams& p, int offset) noexcept
  598. {
  599. const auto inPeak = blockPeak (l, r, n);
  600. const auto ch = characterOf (p[character]);
  601. const bool pre = on (p[characterPre]);
  602. const auto drv = (float) dbToGain (driveDb (p[drive]));
  603. const auto scGain = (float) dbToGain (scLevelDb (p[scLevel]));
  604. const bool external = on (p[scExternal]) && scL != nullptr && scR != nullptr;
  605. // round 137: the trigger replaces the detector's signal (a 0 dBFS key × the side-chain level)
  606. const auto trig = triggerOf (p[trigger]);
  607. float midiKey = 0.0f;
  608. if (trig == Trigger::midi)
  609. if (const auto c = triggerChannelOf (p[triggerChannel]); c >= 0 && held != nullptr && c < heldCount)
  610. midiKey = (held[c][0] | held[c][1]) != 0 ? 1.0f : 0.0f;
  611. const auto beat0 = songBeats + (double) offset * blockBpm / 60.0 / sr, beatStep = blockBpm / 60.0 / sr;
  612. const auto link = (double) std::clamp (p[stereoLink], 0.0f, 1.0f);
  613. const auto inGain = (float) dbToGain (trimDb (p[input]));
  614. const auto outGain = (float) dbToGain (trimDb (p[output]));
  615. const auto mx = std::clamp (p[mix], 0.0f, 1.0f);
  616. const auto st = styleOf (p[style]);
  617. float makeup = 1.0f;
  618. if (on (p[autoGain]) && styleDefs[(int) st].curve != Curve::upward)
  619. {
  620. const auto rng = std::max (0.01, rangeDb (p[range]));
  621. makeup = (float) dbToGain (std::min (rng, -0.5 * curveGain (st, 0.0, thresholdDb (p[threshold]), ratioOf (p[ratio]), kneeDb (p[knee]), rng)));
  622. }
  623. const auto mode = linkModeOf (p[linkMode]);
  624. const bool ms = mode != LinkMode::stereo;
  625. const auto dryG = (float) (p[dryGain] > 0.0f ? dbToGain (dryDb (p[dryGain])) : 0.0);
  626. const bool autoThr = on (p[autoThreshold]);
  627. const auto la = std::min (lookaheadMs (p[lookahead]), latencyMs);
  628. const auto factor = osFactor > 1 ? osFactor : 1;
  629. const auto lag = std::clamp ((int) std::lround ((latencyMs - la) * 0.001 * sr * factor), 0, gainCapacity - 1);
  630. // the side chain (base rate) and the audio through the look-ahead delay
  631. for (int i = 0; i < n; ++i)
  632. {
  633. float a = l[i] * inGain, b = r[i] * inGain;
  634. float sa, sb;
  635. if (external)
  636. {
  637. sa = scL[offset + i] * inGain;
  638. sb = scR[offset + i] * inGain;
  639. }
  640. else if (pre && ch != Character::off)
  641. {
  642. sa = characterCurve (ch, a * drv) / drv;
  643. sb = characterCurve (ch, b * drv) / drv;
  644. }
  645. else
  646. {
  647. sa = a;
  648. sb = b;
  649. }
  650. sa *= scGain;
  651. sb *= scGain;
  652. if (ms)
  653. {
  654. const auto m = 0.5f * (sa + sb), d = 0.5f * (sa - sb);
  655. sa = m;
  656. sb = d;
  657. }
  658. if (scEqOn)
  659. for (int q = 0; q < scBands; ++q)
  660. for (int k = 0; k < scCount[(std::size_t) q]; ++k)
  661. {
  662. auto& f = scEq[(std::size_t) q][(std::size_t) k];
  663. sa = f.process (sa, 0);
  664. sb = f.process (sb, 1);
  665. }
  666. if (trig != Trigger::off)
  667. sa = sb = scGain * (trig == Trigger::midi ? midiKey : (transportPlaying ? hostTrigger (p, beat0 + beatStep * (double) i) : 0.0f));
  668. sideL[(std::size_t) i] = sa;
  669. sideR[(std::size_t) i] = sb;
  670. if (autoThr)
  671. programSum += 0.5 * ((double) sa * sa + (double) sb * sb);
  672. dl[(std::size_t) i] = a;
  673. dr[(std::size_t) i] = b;
  674. if (ms)
  675. {
  676. const auto m = 0.5f * (a + b), d = 0.5f * (a - b);
  677. a = m;
  678. b = d;
  679. }
  680. audioDelay.process (a, b);
  681. wl[(std::size_t) i] = a;
  682. wr[(std::size_t) i] = b;
  683. }
  684. if (on (p[scListen])) // the detector's signal
  685. {
  686. for (int i = 0; i < n; ++i)
  687. l[i] = r[i] = 0.5f * (sideL[(std::size_t) i] + sideR[(std::size_t) i]);
  688. meters.set (0, 0.0f);
  689. meters.set (2, inPeak);
  690. meters.set (3, blockPeak (l, r, n));
  691. return;
  692. }
  693. if (autoThr) // the programme's slow RMS level (3 s), block by block
  694. {
  695. const auto ms2 = programSum / std::max (1, n);
  696. programSum = 0.0;
  697. const auto k = std::exp (-(double) n / (3.0 * sr));
  698. programMs = k * programMs + (1.0 - k) * ms2;
  699. programDb = std::max (-120.0, 10.0 * std::log10 (programMs + 1e-15));
  700. }
  701. const auto detLink = ms ? 0.0 : link; // mid / side: each detector on its own channel
  702. double maxGr = 0.0;
  703. if (factor == 1)
  704. {
  705. maxGr = gains (sideL.data(), sideR.data(), n, detLink, lag, context (p, sr), gl.data(), gr.data());
  706. if (ms)
  707. routeMs (mode, gl.data(), gr.data(), n);
  708. for (int i = 0; i < n; ++i)
  709. {
  710. wl[(std::size_t) i] = stage (wl[(std::size_t) i], gl[(std::size_t) i] * makeup, ch, pre, drv);
  711. wr[(std::size_t) i] = stage (wr[(std::size_t) i], gr[(std::size_t) i] * makeup, ch, pre, drv);
  712. }
  713. }
  714. else
  715. {
  716. // oversampled: the side chain is upsampled (the same path as the audio, so both stay aligned), the
  717. // detector and the gain run at the high rate, and the gain multiplies the upsampled audio
  718. const auto m = n * factor;
  719. for (int c = 0; c < 2; ++c)
  720. {
  721. auto* src = c == 0 ? sideL.data() : sideR.data();
  722. auto* dst = c == 0 ? upL.data() : upR.data();
  723. int k = 0;
  724. osSide[(std::size_t) c].process (src, n, [&] (float v) noexcept {
  725. dst[std::min (k++, m - 1)] = v;
  726. return 0.0f;
  727. });
  728. }
  729. maxGr = gains (upL.data(), upR.data(), m, detLink, lag, context (p, sr * factor), upGl.data(), upGr.data());
  730. if (ms)
  731. routeMs (mode, upGl.data(), upGr.data(), m);
  732. for (int c = 0; c < 2; ++c)
  733. {
  734. const auto* g = c == 0 ? upGl.data() : upGr.data();
  735. int k = 0;
  736. os[(std::size_t) c].process (c == 0 ? wl.data() : wr.data(), n, [&] (float v) noexcept {
  737. return stage (v, g[std::min (k++, m - 1)] * makeup, ch, pre, drv);
  738. });
  739. }
  740. }
  741. float wetA = 1.0f, wetB = 1.0f, dryA = 1.0f, dryB = 1.0f;
  742. {
  743. const auto balance = [] (double pan, float& a, float& b) {
  744. if (pan > 0.0) a = (float) (1.0 - pan);
  745. else if (pan < 0.0) b = (float) (1.0 + pan);
  746. };
  747. balance (panOf (p[wetPan]), wetA, wetB);
  748. balance (panOf (p[dryPan]), dryA, dryB);
  749. }
  750. const bool panned = wetA != 1.0f || wetB != 1.0f || dryA != 1.0f || dryB != 1.0f;
  751. for (int i = 0; i < n; ++i)
  752. {
  753. float a = wl[(std::size_t) i], b = wr[(std::size_t) i];
  754. if (ms)
  755. {
  756. const auto m = a, d = b;
  757. a = m + d;
  758. b = m - d;
  759. }
  760. if (ch != Character::off)
  761. {
  762. a = dc.process (a, 0);
  763. b = dc.process (b, 1);
  764. }
  765. float da = dl[(std::size_t) i], db = dr[(std::size_t) i];
  766. dryLa.process (da, db);
  767. dryDelay.process (da, db);
  768. if (panned) // round 135: the wet and dry paths balanced on their own
  769. {
  770. l[i] = (a * mx * wetA + da * ((1.0f - mx) + dryG) * dryA) * outGain;
  771. r[i] = (b * mx * wetB + db * ((1.0f - mx) + dryG) * dryB) * outGain;
  772. }
  773. else if (dryG > 0.0f) // round 128: the dry level added on top (parallel compression)
  774. {
  775. l[i] = (da + (a - da) * mx + da * dryG) * outGain;
  776. r[i] = (db + (b - db) * mx + db * dryG) * outGain;
  777. }
  778. else
  779. {
  780. l[i] = (da + (a - da) * mx) * outGain;
  781. r[i] = (db + (b - db) * mx) * outGain;
  782. }
  783. }
  784. meters.set (0, (float) std::clamp (maxGr / 30.0, 0.0, 1.0));
  785. meters.set (2, inPeak);
  786. meters.set (3, blockPeak (l, r, n));
  787. }
  788. // mid / side link modes: the gains computed per channel (0 = mid, 1 = side) → where they apply
  789. static void routeMs (LinkMode mode, float* gm, float* gs, int count) noexcept
  790. {
  791. for (int i = 0; i < count; ++i)
  792. switch (mode)
  793. {
  794. case LinkMode::mid: gs[i] = 1.0f; break;
  795. case LinkMode::side: gm[i] = 1.0f; break;
  796. case LinkMode::midToSide: gs[i] = gm[i]; gm[i] = 1.0f; break;
  797. case LinkMode::sideToMid: gm[i] = gs[i]; gs[i] = 1.0f; break;
  798. case LinkMode::stereo: break;
  799. }
  800. }
  801. static float stage (float x, float g, Character ch, bool pre, float drv) noexcept
  802. {
  803. if (ch == Character::off)
  804. return x * g;
  805. if (pre)
  806. return characterCurve (ch, x * drv) / drv * g;
  807. return characterCurve (ch, x * g * drv) / drv;
  808. }
  809. double sr = 48000.0, latencyMs = -1.0;
  810. double programSum = 0.0, programMs = 1e-4, programDb = -40.0; // auto threshold: the programme's slow RMS
  811. int osFactor = 0, laSamples = 0;
  812. std::atomic<int> latency { 0 };
  813. EffectParams lastParams = [] {
  814. EffectParams p {};
  815. const auto& info = crestInfo();
  816. for (std::size_t i = 0; i < info.params.size(); ++i)
  817. p[i] = info.params[i].defaultValue;
  818. return p;
  819. }();
  820. StereoDelay audioDelay, dryLa, dryDelay;
  821. std::array<std::vector<float>, 2> gainDelay;
  822. int gainPos = 0;
  823. std::array<mixsuite::Oversampler, 2> os, osSide;
  824. std::array<std::array<Biquad, facet::maxSections>, scBands> scEq;
  825. std::array<int, scBands> scCount {};
  826. bool scEqOn = false;
  827. std::array<Detector, 2> det {};
  828. std::array<std::array<float, peakWindow>, 2> peaks {};
  829. DcBlock dc;
  830. const float* scL = nullptr;
  831. const float* scR = nullptr;
  832. // round 137: the trigger's clock (quarter notes at the block start) and the held notes
  833. double songBeats = 0.0, blockBpm = 120.0;
  834. bool transportPlaying = false;
  835. const NoteMask* held = nullptr;
  836. int heldCount = 0;
  837. std::array<float, maxBlock> wl {}, wr {}, gl {}, gr {}, dl {}, dr {}, sideL {}, sideR {};
  838. std::array<float, maxBlock * maxFactor> upL {}, upR {}, upGl {}, upGr {};
  839. LiveMeters meters;
  840. };
  841. } // namespace
  842. } // namespace crest
  843. // ================================================================== Prism Multiband
  844. namespace prism
  845. {
  846. double thresholdDb (float v) noexcept { return -90.0 * (1.0 - std::sqrt ((double) std::clamp (v, 0.0f, 1.0f))); }
  847. float thresholdValue (double db) noexcept
  848. {
  849. const auto u = 1.0 - std::clamp (-db / 90.0, 0.0, 1.0);
  850. return (float) (u * u);
  851. }
  852. double ratioOf (float v) noexcept { return ratioLaw (v); }
  853. double rangeDb (float v) noexcept { return lin (v, -30.0, 30.0); }
  854. double kneeDb (float v) noexcept { return lin (v, 0.0, 48.0); }
  855. double attackMs (float v) noexcept { return 0.11 + 89.0 * std::pow ((double) std::clamp (v, 0.0f, 1.0f), 3.9); }
  856. double releaseMs (float v) noexcept { return 130.0 + 3500.0 * std::pow ((double) std::clamp (v, 0.0f, 1.0f), 3.0); }
  857. double levelDb (float v) noexcept { return lin (v, -30.0, 30.0); }
  858. double crossoverHz (float v) noexcept { return logMap (v, 30.0, 18000.0); }
  859. float crossoverValue (double hz) noexcept { return logValue (std::clamp (hz, 30.0, 18000.0), 30.0, 18000.0); }
  860. int slopeDbOct (float v) noexcept
  861. {
  862. static constexpr int s[] { 12, 24, 48 };
  863. return s[pick (v, 3)];
  864. }
  865. double lookaheadMs (float v) noexcept { return lin (v, 0.0, 20.0); }
  866. double trimDb (float v) noexcept { return lin (v, -36.0, 36.0); }
  867. Phase phaseOf (float v) noexcept
  868. {
  869. const auto k = pick (v, 3);
  870. return k == 0 ? Phase::linear : (k == 1 ? Phase::dynamic : Phase::minimum);
  871. }
  872. bool measuredDynamic (const EffectParams& p) noexcept { return on (p[dynamicEngine]); }
  873. double linkAmount (float v) noexcept { return std::clamp (2.0 * (double) v, 0.0, 1.0); }
  874. double linkOnly (float v) noexcept { return std::clamp (2.0 * (double) v - 1.0, 0.0, 1.0); }
  875. double scFilterHz (float v) noexcept { return 30.0 * std::pow (1000.0, (double) std::clamp (v, 0.0f, 1.0f)); }
  876. int crossoverSlopeDbOct (const EffectParams& p, int k) noexcept
  877. {
  878. static constexpr int own[4] { 0, 12, 24, 48 };
  879. const auto s = own[pick (p[(std::size_t) (xoverSlope0 + std::clamp (k, 0, bands - 2))], 4)];
  880. return s > 0 ? s : slopeDbOct (p[Global::slope]);
  881. }
  882. float crossoverSlopeValue (int dbOct) noexcept { return dbOct <= 0 ? 0.0f : (dbOct <= 12 ? 1.0f / 3.0f : (dbOct <= 24 ? 2.0f / 3.0f : 1.0f)); }
  883. float scFilterValue (double hz) noexcept { return (float) std::clamp (std::log (std::max (hz, 1.0) / 30.0) / std::log (1000.0), 0.0, 1.0); }
  884. int oversamplingOf (float v) noexcept { return 1 << pick (v, 3); }
  885. int linearFftSize (double sampleRate) noexcept
  886. {
  887. int n = 4096;
  888. for (double r = 50000.0; sampleRate > r && n < 16384; r *= 2.0)
  889. n *= 2;
  890. return n;
  891. }
  892. int linearLatency (double sampleRate) noexcept { return 3 * linearFftSize (sampleRate) / 4; }
  893. // round 150 (REA_rodada150 §1–3): the free layout, Pro-MB's edge / slope laws, the detector law
  894. bool freeLayout (const EffectParams& p) noexcept { return on (p[bandLayout]); }
  895. double edgeHz (float v) noexcept { return 30.0 * std::pow (1000.0, (double) std::clamp (v, 0.0f, 1.0f)); }
  896. float edgeValue (double hz) noexcept { return (float) std::clamp (std::log (std::max (hz, 1.0) / 30.0) / std::log (1000.0), 0.0, 1.0); }
  897. double slopeOfValue (float v) noexcept
  898. {
  899. const auto x = (double) std::clamp (v, 0.0f, 1.0f);
  900. return x < 0.25 ? 6.0 + 24.0 * x : 48.0 * x;
  901. }
  902. float slopeValue (double dbOct) noexcept
  903. {
  904. const auto d = std::clamp (dbOct, 6.0, 48.0);
  905. return (float) (d < 12.0 ? (d - 6.0) / 24.0 : d / 48.0);
  906. }
  907. int iirSlope (double dbOct) noexcept
  908. {
  909. static constexpr int s[5] { 6, 12, 24, 36, 48 };
  910. const auto code = minphase::dynamicSideCode (dbOct);
  911. return s[code == 1 ? 0 : code / 2];
  912. }
  913. bool measuredDetector (const EffectParams& p) noexcept { return on (p[detectorLaw]); }
  914. Layout layoutOf (const EffectParams& p) noexcept
  915. {
  916. Layout L;
  917. L.segmentOf.fill (-1);
  918. const auto nb = bandCount (p);
  919. if (! freeLayout (p))
  920. {
  921. // the split layout: band b between crossovers b − 1 and b (the old engine)
  922. const auto f = crossovers (p);
  923. L.segments = nb;
  924. for (int k = 0; k < nb - 1; ++k)
  925. {
  926. L.xoverHz[(std::size_t) k] = f[(std::size_t) k];
  927. L.xoverSlope[(std::size_t) k] = crossoverSlopeDbOct (p, k);
  928. }
  929. for (int b = 0; b < nb; ++b)
  930. {
  931. L.bandOf[(std::size_t) b] = b;
  932. L.segmentOf[(std::size_t) b] = b;
  933. L.loHz[(std::size_t) b] = b > 0 ? f[(std::size_t) (b - 1)] : 0.0;
  934. L.hiHz[(std::size_t) b] = b < nb - 1 ? f[(std::size_t) b] : 0.0;
  935. L.loSlope[(std::size_t) b] = b > 0 ? L.xoverSlope[(std::size_t) (b - 1)] : 24.0;
  936. L.hiSlope[(std::size_t) b] = b < nb - 1 ? L.xoverSlope[(std::size_t) b] : 24.0;
  937. }
  938. return L;
  939. }
  940. // the free layout: the bands in order of their low edge, no overlap (a band starts at least where the one below
  941. // ends), the room between them passes untouched; an edge at 30 Hz (30 kHz) or beyond is no edge
  942. std::array<int, bands> order {};
  943. for (int b = 0; b < nb; ++b)
  944. order[(std::size_t) b] = b;
  945. std::stable_sort (order.begin(), order.begin() + nb, [&] (int a, int c) {
  946. return edgeHz (p[(std::size_t) (bandLo0 + a)]) < edgeHz (p[(std::size_t) (bandLo0 + c)]);
  947. });
  948. int seg = 0, nx = 0;
  949. double cursor = 0.0; // the upper edge of what is laid out (0 = nothing yet)
  950. bool open = false; // a band reached 30 kHz: nothing fits above it
  951. for (int k = 0; k < nb && ! open; ++k)
  952. {
  953. const auto b = order[(std::size_t) k];
  954. auto lo = edgeHz (p[(std::size_t) (bandLo0 + b)]);
  955. auto hi = edgeHz (p[(std::size_t) (bandHi0 + b)]);
  956. const auto ls = slopeOfValue (p[(std::size_t) (bandLoSlope0 + b)]), hs = slopeOfValue (p[(std::size_t) (bandHiSlope0 + b)]);
  957. lo = lo <= 30.5 ? 0.0 : lo;
  958. if (cursor > 0.0)
  959. lo = std::max (lo, cursor);
  960. const bool hasHi = hi < 29500.0;
  961. if (hasHi && lo > 0.0)
  962. hi = std::max (hi, lo * 1.05);
  963. if (lo > 0.0 && (seg == 0 || lo > cursor * 1.0001))
  964. {
  965. L.bandOf[(std::size_t) seg++] = -1; // the gap below the band
  966. L.xoverHz[(std::size_t) nx] = lo;
  967. L.xoverSlope[(std::size_t) nx++] = ls;
  968. }
  969. L.segmentOf[(std::size_t) b] = seg;
  970. L.bandOf[(std::size_t) seg++] = b;
  971. L.loHz[(std::size_t) b] = lo;
  972. L.loSlope[(std::size_t) b] = ls;
  973. L.hiSlope[(std::size_t) b] = hs;
  974. if (hasHi)
  975. {
  976. L.hiHz[(std::size_t) b] = hi;
  977. L.xoverHz[(std::size_t) nx] = hi;
  978. L.xoverSlope[(std::size_t) nx++] = hs;
  979. cursor = hi;
  980. }
  981. else
  982. open = true;
  983. }
  984. if (! open)
  985. L.bandOf[(std::size_t) seg++] = -1; // the room above the last band
  986. L.segments = std::max (1, seg);
  987. return L;
  988. }
  989. namespace
  990. {
  991. // round 150 [EXEC] Pro-MB's range has a soft knee of 12 dB around it (a 9 dB change under a 12 dB range gives 8.61 dB,
  992. // 9 under 6 gives 5.62): x − (x − R + W/2)² / (2W) inside R ± W/2 (W = 12, at most 2R)
  993. double softRange (double x, double range) noexcept
  994. {
  995. const auto w = std::min (12.0, 2.0 * range);
  996. if (w <= 0.0)
  997. return 0.0;
  998. if (x <= range - 0.5 * w)
  999. return x;
  1000. if (x >= range + 0.5 * w)
  1001. return range;
  1002. const auto d = x - range + 0.5 * w;
  1003. return x - d * d / (2.0 * w);
  1004. }
  1005. // gain change (dB) of a band for a detector level x (dB); round 150: `soft` = the measured detector's range knee
  1006. double bandCurve (const EffectParams& p, int b, double x, bool soft = false) noexcept
  1007. {
  1008. const auto at = [&] (int f) { return p[(std::size_t) param (b, f)]; };
  1009. const auto thr = thresholdDb (at (fThreshold));
  1010. const auto r = ratioOf (at (fRatio));
  1011. const auto rng = rangeDb (at (fRange));
  1012. const auto kn = kneeDb (at (fKnee));
  1013. if (std::abs (rng) < 0.01)
  1014. return 0.0;
  1015. const bool expand = on (at (fMode));
  1016. const auto limit = [&] (double v) { return soft ? softRange (v, std::abs (rng)) : std::min (std::abs (rng), v); };
  1017. if (! expand)
  1018. {
  1019. if (rng < 0.0) // downward compression above the threshold
  1020. return -limit (kneeCurve (x - thr, 1.0 - 1.0 / r, kn));
  1021. return limit (kneeCurve (thr - x, 1.0 - 1.0 / r, kn)); // upward compression below it
  1022. }
  1023. if (rng < 0.0) // downward expansion below the threshold
  1024. return -limit (kneeCurve (thr - x, r - 1.0, kn));
  1025. return limit (kneeCurve (x - thr, 1.0 - 1.0 / r, kn)); // upward expansion above it
  1026. }
  1027. // round 150 [EXEC] the measured detector's time constants (fitted to Pro-MB's gain on 1 kHz steps −30 → −6 → −30 →
  1028. // −18 → −30 dBFS, threshold −30, REA_rodada150 §3): the level follower's attack and release (dB domain) and the gain's
  1029. // own release after the curve (so a range-limited band recovers at once); table over 0 / 10 / 20 / 35 / 50 / 75 / 100 %
  1030. double measuredLaw (const double* table, float v) noexcept
  1031. {
  1032. static constexpr double at[7] { 0.0, 0.1, 0.2, 0.35, 0.5, 0.75, 1.0 };
  1033. const auto x = (double) std::clamp (v, 0.0f, 1.0f);
  1034. int k = 0;
  1035. while (k < 5 && x > at[k + 1])
  1036. ++k;
  1037. const auto t = (x - at[k]) / (at[k + 1] - at[k]);
  1038. return std::exp (std::log (table[k]) + (std::log (table[k + 1]) - std::log (table[k])) * t);
  1039. }
  1040. constexpr double measuredAttack[7] { 0.065, 0.081, 0.166, 1.22, 8.35, 35.2, 99.4 };
  1041. constexpr double measuredRelease1[7] { 8.5, 9.2, 56.0, 123.0, 172.0, 298.0, 905.0 };
  1042. constexpr double measuredRelease2[7] { 103.0, 104.0, 125.0, 176.0, 243.0, 681.0, 2449.0 };
  1043. // round 150 [EXEC] Pro-MB's linear-phase band shape for any slope: |high pass| = x^ml / (1 + x^ml) at the low edge,
  1044. // |low pass| = 1 / (1 + x^mh) at the high edge, m = slope / 6 (continuous; every slope 6 … 48 matched within 0.01 dB);
  1045. // x on LYNX's prewarped axis (the reference's analog axis differs by ≤ 0.35 dB at a 3 kHz crossover)
  1046. double linearShare (double wl, double wh, double ml, double mh, double w) noexcept
  1047. {
  1048. double a = 1.0;
  1049. if (wh > 0.0)
  1050. a /= 1.0 + std::pow (w / wh, mh);
  1051. if (wl > 0.0)
  1052. {
  1053. const auto x = std::pow (w / wl, ml);
  1054. a *= x / (1.0 + x);
  1055. }
  1056. return a;
  1057. }
  1058. using Split = LrSplit;
  1059. } // namespace
  1060. int bandCount (const EffectParams& p) noexcept { return 1 + pick (p[bandCountParam], bands); }
  1061. float bandCountValue (int n) noexcept { return (float) (std::clamp (n, 1, bands) - 1) / (float) (bands - 1); }
  1062. double panOf (float v) noexcept { return std::clamp ((double) v * 2.0 - 1.0, -1.0, 1.0); }
  1063. std::array<double, bands - 1> crossovers (const EffectParams& p) noexcept
  1064. {
  1065. std::array<double, bands - 1> f {};
  1066. for (int k = 0; k < bands - 1; ++k)
  1067. {
  1068. f[(std::size_t) k] = crossoverHz (p[(std::size_t) crossoverParam (k)]);
  1069. if (k > 0)
  1070. f[(std::size_t) k] = std::max (f[(std::size_t) k], f[(std::size_t) (k - 1)] * 1.05);
  1071. }
  1072. return f;
  1073. }
  1074. double bandStaticDb (const EffectParams& p, int b, double inputDb)
  1075. {
  1076. if (! on (p[(std::size_t) param (b, fEnabled)]))
  1077. return 0.0;
  1078. return bandCurve (p, b, inputDb, measuredDetector (p)) + levelDb (p[(std::size_t) param (b, fLevel)]);
  1079. }
  1080. double responseDb (const EffectParams& p, const double* bandGainDb, double sampleRate, double hz)
  1081. {
  1082. // round 150: the bands' segments (the split layout: band b = segment b; the free layout: gaps between)
  1083. const auto L = layoutOf (p);
  1084. const auto ns = L.segments;
  1085. const auto w = 2.0 * pi * hz / sampleRate;
  1086. const auto segGain = [&] (int k) { return L.bandOf[(std::size_t) k] >= 0 ? bandGainDb[L.bandOf[(std::size_t) k]] : 0.0; };
  1087. // segments of the tree: S0 = L1, S1 = H1·L2, S2 = H1·H2·L3, …, the last = H1·…·H(n−1); out = x + Σ (g − 1)·Sk
  1088. std::array<std::complex<double>, maxSegments> band {};
  1089. std::complex<double> rest { 1.0, 0.0 };
  1090. for (int k = 0; k < ns - 1; ++k)
  1091. {
  1092. Split s;
  1093. s.design (sampleRate, L.xoverHz[(std::size_t) k], iirSlope (L.xoverSlope[(std::size_t) k]));
  1094. band[(std::size_t) k] = rest * s.response (false, w);
  1095. rest *= s.response (true, w);
  1096. }
  1097. band[(std::size_t) (ns - 1)] = rest;
  1098. // round 144: the processing mode — linear phase: the same magnitudes, no phase; minimum phase: the lower bands
  1099. // pass the all-passes of the crossovers above them, the output is the sum of the bands
  1100. const auto mode = phaseOf (p[processingMode]);
  1101. const auto nb = bandCount (p);
  1102. bool solo = false;
  1103. for (int b = 0; b < nb; ++b)
  1104. solo = solo || on (p[(std::size_t) param (b, fSolo)]);
  1105. const auto om = minphase::warp (hz, sampleRate);
  1106. const auto wOf = [&] (double edge) { return edge > 0.0 ? minphase::warp (std::min (edge, sampleRate * 0.45), sampleRate) : 0.0; };
  1107. if (mode == Phase::linear && freeLayout (p))
  1108. {
  1109. // round 150: each band's own linear-phase shape (Pro-MB's 1 / (1 + x^m), m = slope / 6, continuous)
  1110. std::complex<double> y = solo ? std::complex<double> {} : std::complex<double> { 1.0, 0.0 };
  1111. for (int b = 0; b < nb; ++b)
  1112. {
  1113. if (L.segmentOf[(std::size_t) b] < 0)
  1114. continue;
  1115. const auto a = linearShare (wOf (L.loHz[(std::size_t) b]), wOf (L.hiHz[(std::size_t) b]), L.loSlope[(std::size_t) b] / 6.0, L.hiSlope[(std::size_t) b] / 6.0, om);
  1116. const auto g = dbToGain (bandGainDb[b]);
  1117. if (solo)
  1118. {
  1119. if (on (p[(std::size_t) param (b, fSolo)]))
  1120. y += g * a;
  1121. }
  1122. else
  1123. y += (g - 1.0) * a;
  1124. }
  1125. return gainToDb (std::abs (y)) + trimDb (p[output]);
  1126. }
  1127. if (mode == Phase::linear)
  1128. for (auto& b : band)
  1129. b = std::abs (b);
  1130. else if (mode == Phase::minimum)
  1131. for (int k = 0; k < ns - 2; ++k)
  1132. for (int j = k + 1; j < ns - 1; ++j)
  1133. {
  1134. Split s;
  1135. s.design (sampleRate, L.xoverHz[(std::size_t) j], iirSlope (L.xoverSlope[(std::size_t) j]));
  1136. band[(std::size_t) k] *= s.response (false, w) + s.response (true, w);
  1137. }
  1138. if (mode == Phase::dynamic && measuredDynamic (p) && ! solo)
  1139. {
  1140. // round 147: the measured engine — the product of each band's 1 + (g − 1)·A (its own crossovers' magnitudes);
  1141. // round 150: any slope (the 6 dB/oct models), each band's own edges
  1142. double m = 1.0;
  1143. for (int b = 0; b < nb; ++b)
  1144. {
  1145. if (L.segmentOf[(std::size_t) b] < 0)
  1146. continue;
  1147. m *= minphase::bandMagnitudeM (wOf (L.loHz[(std::size_t) b]), wOf (L.hiHz[(std::size_t) b]),
  1148. minphase::dynamicSideCode (L.loSlope[(std::size_t) b]), minphase::dynamicSideCode (L.hiSlope[(std::size_t) b]),
  1149. dbToGain (bandGainDb[b]), om);
  1150. }
  1151. return gainToDb (std::abs (m)) + trimDb (p[output]);
  1152. }
  1153. std::complex<double> y = solo || mode == Phase::minimum ? std::complex<double> {} : std::complex<double> { 1.0, 0.0 };
  1154. for (int k = 0; k < ns; ++k)
  1155. {
  1156. const auto bi = L.bandOf[(std::size_t) k];
  1157. const auto g = dbToGain (segGain (k));
  1158. if (solo)
  1159. {
  1160. if (bi >= 0 && on (p[(std::size_t) param (bi, fSolo)]))
  1161. y += g * band[(std::size_t) k];
  1162. }
  1163. else if (mode == Phase::minimum)
  1164. y += g * band[(std::size_t) k];
  1165. else
  1166. y += (g - 1.0) * band[(std::size_t) k];
  1167. }
  1168. return gainToDb (std::abs (y)) + trimDb (p[output]);
  1169. }
  1170. namespace
  1171. {
  1172. // a delay line sized in prepare() (the linear-phase path's dry signal: up to 12 288 samples at 192 kHz)
  1173. struct LongDelay
  1174. {
  1175. std::vector<float> l, r;
  1176. int pos = 0, len = 0;
  1177. void allocate (int n) { l.assign ((std::size_t) n + 1, 0.0f); r.assign ((std::size_t) n + 1, 0.0f); len = n; pos = 0; }
  1178. void reset() noexcept { std::fill (l.begin(), l.end(), 0.0f); std::fill (r.begin(), r.end(), 0.0f); pos = 0; }
  1179. void process (float& a, float& b) noexcept
  1180. {
  1181. if (len == 0 || l.empty())
  1182. return;
  1183. const auto size = (int) l.size();
  1184. l[(std::size_t) pos] = a;
  1185. r[(std::size_t) pos] = b;
  1186. auto rd = pos - len;
  1187. if (rd < 0)
  1188. rd += size;
  1189. a = l[(std::size_t) rd];
  1190. b = r[(std::size_t) rd];
  1191. if (++pos == size)
  1192. pos = 0;
  1193. }
  1194. };
  1195. // round 147: Pro-MB's free side-chain filter, measured black-box (REA_rodada147 §2): a 4th-order high pass at the low
  1196. // frequency and low pass at the high one (−24 dB one octave out), their sections' Q 1.25 × Butterworth (the fit to the
  1197. // reference's band shapes of one octave and wider; narrower bands boost more in the reference)
  1198. struct ScFilter
  1199. {
  1200. std::array<Biquad, 4> s;
  1201. Biquad bell;
  1202. double lo = -1.0, hi = -1.0, rate = 0.0;
  1203. bool useHp = false, useLp = false, useBell = false, law = false;
  1204. // round 150 (REA_rodada150 §4, the round-147 sweeps refitted): with the measured detector the free filter is the
  1205. // 4th-order Butterworth high / low pass (section Q × a) times a bell at the band's centre whose gain grows as the
  1206. // band narrows (the reference's +13.7 dB for 2 – 2.5 kHz): fitted per width (0.32 / 0.58 / 1 / 1.58 octaves, rms
  1207. // 0.09 / 0.10 / 0.21 / 0.28 dB), interpolated, none from 3 octaves up
  1208. static void narrowLaw (double octaves, double& a, double& gainDb, double& q) noexcept
  1209. {
  1210. static constexpr double w[5] { 0.32, 0.58, 1.0, 1.58, 3.0 };
  1211. static constexpr double av[5] { 0.993, 0.992, 1.058, 0.984, 1.0 };
  1212. static constexpr double gv[5] { 16.94, 12.63, 4.85, 1.36, 0.0 };
  1213. static constexpr double qv[5] { 4.811, 2.567, 0.762, 0.195, 0.195 };
  1214. const auto x = std::clamp (octaves, w[0], w[4]);
  1215. int k = 0;
  1216. while (k < 3 && x > w[k + 1])
  1217. ++k;
  1218. const auto t = (x - w[k]) / (w[k + 1] - w[k]);
  1219. a = av[k] + (av[k + 1] - av[k]) * t;
  1220. gainDb = gv[k] + (gv[k + 1] - gv[k]) * t;
  1221. q = std::exp (std::log (qv[k]) + (std::log (qv[k + 1]) - std::log (qv[k])) * t);
  1222. }
  1223. void design (double sampleRate, double loHz, double hiHz, bool measured = false) noexcept
  1224. {
  1225. if (loHz == lo && hiHz == hi && sampleRate == rate && measured == law)
  1226. return;
  1227. lo = loHz;
  1228. hi = hiHz;
  1229. rate = sampleRate;
  1230. law = measured;
  1231. static constexpr double bw[2] { 0.54119610, 1.30656296 };
  1232. useHp = loHz > 30.5;
  1233. useLp = hiHz < sampleRate * 0.45;
  1234. useBell = false;
  1235. double scale = 1.25; // round 147: Q 1.25 × Butterworth (the fit to bands of one octave and wider)
  1236. if (measured)
  1237. {
  1238. double g = 0.0, bq = 1.0;
  1239. narrowLaw (useHp && useLp ? std::log2 (std::max (hiHz, loHz * 1.001) / loHz) : 3.0, scale, g, bq);
  1240. if (useHp && useLp && g > 0.01)
  1241. {
  1242. useBell = true;
  1243. bell.peaking (sampleRate, std::min (std::sqrt (loHz * hiHz), sampleRate * 0.45), bq, g);
  1244. }
  1245. }
  1246. for (int k = 0; k < 2; ++k)
  1247. {
  1248. s[(std::size_t) k].filter (sampleRate, 1, loHz, bw[k] * scale);
  1249. s[(std::size_t) (2 + k)].filter (sampleRate, 0, hiHz, bw[k] * scale);
  1250. }
  1251. }
  1252. void reset() noexcept
  1253. {
  1254. for (auto& b : s)
  1255. b.reset();
  1256. bell.reset();
  1257. }
  1258. void run (float& l, float& r) noexcept
  1259. {
  1260. for (int k = 0; k < 4; ++k)
  1261. if (k < 2 ? useHp : useLp)
  1262. {
  1263. l = s[(std::size_t) k].process (l, 0);
  1264. r = s[(std::size_t) k].process (r, 1);
  1265. }
  1266. if (useBell)
  1267. {
  1268. l = bell.process (l, 0);
  1269. r = bell.process (r, 1);
  1270. }
  1271. }
  1272. };
  1273. class Multiband final : public Effect
  1274. {
  1275. public:
  1276. explicit Multiband (const EffectParams* initial)
  1277. {
  1278. if (initial != nullptr)
  1279. configure (*initial);
  1280. }
  1281. void prepare (double rate) noexcept override
  1282. {
  1283. sr = rate;
  1284. laMs = -1.0;
  1285. // round 144: the linear-phase crossovers (one stereo FFT convolver per band below the top one) and the dry
  1286. // delay that matches them, allocated here (process() never allocates)
  1287. const auto size = linearFftSize (rate);
  1288. if (size != linSize)
  1289. {
  1290. linSize = size;
  1291. for (auto& c : lin)
  1292. c.init (size);
  1293. for (auto& t : linTable)
  1294. t.assign ((std::size_t) (size / 2 + 1), 0.0f);
  1295. linDry.allocate (linearLatency (rate));
  1296. linSc.allocate (linearLatency (rate));
  1297. }
  1298. mode = -1;
  1299. osFactor = 0;
  1300. configure (lastParams);
  1301. designed = false;
  1302. reset();
  1303. }
  1304. void reset() noexcept override
  1305. {
  1306. for (auto& s : split)
  1307. s.reset();
  1308. for (auto& s : scSplit)
  1309. s.reset();
  1310. for (auto& row : comp)
  1311. for (auto& s : row)
  1312. s.reset();
  1313. delay.reset();
  1314. for (auto& d : bandDelay)
  1315. d.reset();
  1316. for (auto& d : gainDelay)
  1317. d.reset();
  1318. for (auto& d : gainDelayB)
  1319. d.reset();
  1320. for (auto& f2 : scFilter)
  1321. f2.reset();
  1322. for (auto& c : lin)
  1323. if (c.n > 0)
  1324. c.clear();
  1325. linDry.reset();
  1326. linSc.reset();
  1327. resetOversamplers();
  1328. for (auto& row : dynBand)
  1329. for (auto& fl : row)
  1330. fl.reset();
  1331. dynWorks.fill (false);
  1332. env.fill (-120.0);
  1333. env2.fill (-120.0);
  1334. held.fill (0.0);
  1335. held2.fill (0.0);
  1336. gains.fill (1.0f);
  1337. }
  1338. int latencySamples() const noexcept override { return latency.load (std::memory_order_relaxed); }
  1339. float controlOutput (int k) const noexcept override { return meters.read (k); }
  1340. void setSidechain (const float* l, const float* r) noexcept override
  1341. {
  1342. scL = l;
  1343. scR = r;
  1344. }
  1345. void process (float* l, float* r, int n, const EffectParams& p, double) noexcept override
  1346. {
  1347. lastParams = p;
  1348. configure (p);
  1349. const auto inPeak = blockPeak (l, r, n);
  1350. extreme.fill (0.0);
  1351. const auto* sl = scL;
  1352. const auto* sr2 = scR;
  1353. for (int i = 0; i < n; i += chunk)
  1354. {
  1355. const auto m = std::min (chunk, n - i);
  1356. const bool sc = sl != nullptr && sr2 != nullptr;
  1357. processChunk (l + i, r + i, sc ? sl + i : nullptr, sc ? sr2 + i : nullptr, m, p);
  1358. }
  1359. const auto nb = bandCount (p);
  1360. for (int b = 0; b < bands; ++b)
  1361. meters.set (bandMeter (b), b < nb ? (float) std::clamp (extreme[(std::size_t) b] / 30.0, -1.0, 1.0) : 0.0f);
  1362. meters.set (4, inPeak);
  1363. meters.set (5, blockPeak (l, r, n));
  1364. scL = scR = nullptr;
  1365. }
  1366. private:
  1367. static constexpr int chunk = 256, maxFactor = 4;
  1368. void processChunk (float* l, float* r, const float* scl, const float* scr, int n, const EffectParams& p) noexcept
  1369. {
  1370. // round 150: the layout's segments (the split layout: band b = segment b, the old engine; the free layout: the
  1371. // gaps between the bands are segments that pass untouched)
  1372. const auto L = layoutOf (p);
  1373. const auto ns = L.segments;
  1374. std::array<int, maxSegments - 1> slope {};
  1375. for (int k = 0; k < ns - 1; ++k)
  1376. slope[(std::size_t) k] = iirSlope (L.xoverSlope[(std::size_t) k]);
  1377. const auto nb = bandCount (p);
  1378. const auto md = (Phase) mode;
  1379. const bool linear = md == Phase::linear, minimum = md == Phase::minimum;
  1380. const bool freeLin = linear && freeLayout (p); // round 150: each band its own linear-phase FIR
  1381. if (! designed || L.xoverHz != lastF || slope != lastSlope || ns != lastNs)
  1382. {
  1383. for (int k = 0; k < ns - 1; ++k)
  1384. {
  1385. split[(std::size_t) k].design (sr, L.xoverHz[(std::size_t) k], slope[(std::size_t) k]);
  1386. scSplit[(std::size_t) k].design (sr, L.xoverHz[(std::size_t) k], slope[(std::size_t) k]);
  1387. for (int j = 0; j < ns - 1; ++j)
  1388. comp[(std::size_t) j][(std::size_t) k].design (sr, L.xoverHz[(std::size_t) k], slope[(std::size_t) k]);
  1389. }
  1390. lastF = L.xoverHz;
  1391. lastSlope = slope;
  1392. lastNs = ns;
  1393. designed = true;
  1394. kernelsDirty = true;
  1395. }
  1396. const auto key = kernelKey (L, freeLin, nb);
  1397. if (key != lastKernelKey)
  1398. {
  1399. lastKernelKey = key;
  1400. kernelsDirty = true;
  1401. for (auto& c : lin)
  1402. if (c.n > 0)
  1403. c.clear();
  1404. }
  1405. if (linear && kernelsDirty)
  1406. {
  1407. if (freeLin)
  1408. designFreeKernels (L, nb);
  1409. else
  1410. designKernels (ns);
  1411. }
  1412. // the units the output sums: the segments, or (free linear phase) the bands' own FIR outputs
  1413. const int nu = freeLin ? nb : ns;
  1414. std::array<int, maxSegments> unitBand {};
  1415. for (int u = 0; u < nu; ++u)
  1416. unitBand[(std::size_t) u] = freeLin ? (L.segmentOf[(std::size_t) u] >= 0 ? u : -1) : L.bandOf[(std::size_t) u];
  1417. // round 135: the detectors hear the slot's side chain, split by the same crossovers; round 150: each band chooses
  1418. // the plug-in input or the side chain (or follows the global switch)
  1419. const bool haveSc = scl != nullptr && scr != nullptr;
  1420. const bool globalExt = on (p[scExternal]) && haveSc;
  1421. std::array<bool, bands> bandExt {};
  1422. bool external = false;
  1423. for (int b = 0; b < nb; ++b)
  1424. {
  1425. const auto v = p[(std::size_t) (bandScInput0 + b)];
  1426. bandExt[(std::size_t) b] = v < 0.25f ? globalExt : (v >= 0.75f && haveSc);
  1427. external = external || bandExt[(std::size_t) b];
  1428. }
  1429. const auto inGain = (float) dbToGain (trimDb (p[input]));
  1430. const auto outGain = (float) dbToGain (trimDb (p[output]));
  1431. const auto mx = std::clamp (p[mix], 0.0f, 1.0f);
  1432. const bool msPan = on (p[panMode]);
  1433. const bool measuredDet = measuredDetector (p);
  1434. std::array<double, bands> aA {}, aR {}, aR2 {}, level {};
  1435. std::array<bool, bands> enabled {}, soloed {}, growsWithLevel {};
  1436. std::array<float, bands> panL {}, panR {};
  1437. bool anySolo = false;
  1438. for (int b = 0; b < nb; ++b)
  1439. {
  1440. const auto pan = (float) panOf (p[(std::size_t) bandPanParam (b)]);
  1441. panL[(std::size_t) b] = pan > 0.0f ? 1.0f - pan : 1.0f;
  1442. panR[(std::size_t) b] = pan < 0.0f ? 1.0f + pan : 1.0f;
  1443. if (measuredDet) // round 150: the measured detector's three time constants
  1444. {
  1445. aA[(std::size_t) b] = coef (measuredLaw (measuredAttack, p[(std::size_t) param (b, fAttack)]), sr);
  1446. aR[(std::size_t) b] = coef (measuredLaw (measuredRelease1, p[(std::size_t) param (b, fRelease)]), sr);
  1447. aR2[(std::size_t) b] = coef (measuredLaw (measuredRelease2, p[(std::size_t) param (b, fRelease)]), sr);
  1448. }
  1449. else
  1450. {
  1451. aA[(std::size_t) b] = coef (attackMs (p[(std::size_t) param (b, fAttack)]), sr);
  1452. aR[(std::size_t) b] = coef (releaseMs (p[(std::size_t) param (b, fRelease)]), sr);
  1453. }
  1454. level[(std::size_t) b] = levelDb (p[(std::size_t) param (b, fLevel)]);
  1455. // the change grows with the level (downward compression, upward expansion) or shrinks (the other two)
  1456. growsWithLevel[(std::size_t) b] = on (p[(std::size_t) param (b, fMode)]) == (rangeDb (p[(std::size_t) param (b, fRange)]) > 0.0);
  1457. enabled[(std::size_t) b] = on (p[(std::size_t) param (b, fEnabled)]) && L.segmentOf[(std::size_t) b] >= 0;
  1458. soloed[(std::size_t) b] = on (p[(std::size_t) param (b, fSolo)]) && L.segmentOf[(std::size_t) b] >= 0;
  1459. anySolo = anySolo || soloed[(std::size_t) b];
  1460. // round 128: a band's own look-ahead (≤ the global one): its gain waits for the difference
  1461. const auto bandLa = std::min (laMs, lookaheadMs (p[(std::size_t) bandLookaheadParam (b)]));
  1462. gainDelay[(std::size_t) b].setLength (std::max (0, laSamples - (int) std::lround (bandLa * 0.001 * sr)));
  1463. gainDelayB[(std::size_t) b].setLength (gainDelay[(std::size_t) b].len);
  1464. // round 147: the stereo link and the free side-chain filter (the expert panel)
  1465. const auto lv = p[(std::size_t) (bandLink0 + b)];
  1466. linkA[(std::size_t) b] = linkAmount (lv);
  1467. linkM[(std::size_t) b] = linkOnly (lv);
  1468. linkSide[(std::size_t) b] = on (p[(std::size_t) (bandLinkMode0 + b)]);
  1469. fullLink[(std::size_t) b] = linkA[(std::size_t) b] >= 1.0 && linkM[(std::size_t) b] <= 0.0;
  1470. // the band's gains act on left / right, or on mid / side (the pan mode; a mid- / side-only link)
  1471. bandMs[(std::size_t) b] = linkM[(std::size_t) b] > 0.0 ? true : (linkA[(std::size_t) b] < 1.0 ? false : msPan);
  1472. if (bandMs[(std::size_t) b] == msPan)
  1473. {
  1474. panA[(std::size_t) b] = panL[(std::size_t) b];
  1475. panB[(std::size_t) b] = panR[(std::size_t) b];
  1476. }
  1477. else // the pan's two gains belong to the other pair: their mean (a rare combination)
  1478. panA[(std::size_t) b] = panB[(std::size_t) b] = 0.5f * (panL[(std::size_t) b] + panR[(std::size_t) b]);
  1479. scFree[(std::size_t) b] = on (p[(std::size_t) (bandScFree0 + b)]);
  1480. if (scFree[(std::size_t) b])
  1481. scFilter[(std::size_t) b].design (sr, scFilterHz (p[(std::size_t) (bandScLow0 + b)]), scFilterHz (p[(std::size_t) (bandScHigh0 + b)]), measuredDet);
  1482. }
  1483. // 1. the split, the detectors and the gains at the base rate; the dry signal, the units and the gains are kept
  1484. for (int i = 0; i < n; ++i)
  1485. {
  1486. const float xl = l[i] * inGain, xr = r[i] * inGain;
  1487. float bl[maxSegments], br[maxSegments], sl0[maxSegments], sr0[maxSegments];
  1488. float dl = xl, dr = xr;
  1489. if (freeLin)
  1490. {
  1491. // round 150: each band's FIR (its own edges and slopes), the gaps pass with the dry signal
  1492. linDry.process (dl, dr);
  1493. for (int b = 0; b < nb; ++b)
  1494. {
  1495. if (L.segmentOf[(std::size_t) b] < 0)
  1496. {
  1497. bl[b] = br[b] = 0.0f;
  1498. continue;
  1499. }
  1500. float a = xl, c = xr;
  1501. lin[(std::size_t) b].step (a, c);
  1502. bl[b] = a;
  1503. br[b] = c;
  1504. }
  1505. }
  1506. else if (linear)
  1507. {
  1508. // round 144: FIR bands (zero phase, delayed by the convolvers' latency); the top band is the rest, so
  1509. // the bands always add up to the delayed input
  1510. linDry.process (dl, dr);
  1511. float restL = dl, restR = dr;
  1512. for (int k = 0; k < ns - 1; ++k)
  1513. {
  1514. float a = xl, c = xr;
  1515. lin[(std::size_t) k].step (a, c);
  1516. bl[k] = a;
  1517. br[k] = c;
  1518. restL -= a;
  1519. restR -= c;
  1520. }
  1521. bl[ns - 1] = restL;
  1522. br[ns - 1] = restR;
  1523. }
  1524. else
  1525. {
  1526. // the crossover tree: each split takes the high part of the one before
  1527. float hl = xl, hr = xr;
  1528. for (int k = 0; k < ns - 1; ++k)
  1529. {
  1530. float nl, nr;
  1531. split[(std::size_t) k].run (hl, 0, bl[k], nl);
  1532. split[(std::size_t) k].run (hr, 1, br[k], nr);
  1533. hl = nl;
  1534. hr = nr;
  1535. }
  1536. bl[ns - 1] = hl;
  1537. br[ns - 1] = hr;
  1538. }
  1539. // round 147: what a free side-chain filter hears — the input (in time with the bands) or the side chain
  1540. float srcL = linear ? dl : xl, srcR = linear ? dr : xr, extL = srcL, extR = srcR;
  1541. if (external)
  1542. {
  1543. float el = scl[i] * inGain, er = scr[i] * inGain;
  1544. if (linear)
  1545. linSc.process (el, er); // the detectors stay in time with the delayed bands
  1546. extL = el;
  1547. extR = er;
  1548. for (int k = 0; k < ns - 1; ++k)
  1549. {
  1550. float nl, nr;
  1551. scSplit[(std::size_t) k].run (el, 0, sl0[k], nl);
  1552. scSplit[(std::size_t) k].run (er, 1, sr0[k], nr);
  1553. el = nl;
  1554. er = nr;
  1555. }
  1556. sl0[ns - 1] = el;
  1557. sr0[ns - 1] = er;
  1558. }
  1559. delay.process (dl, dr); // the look-ahead: the audio waits, the detectors don't
  1560. dry[0][(std::size_t) i] = dl;
  1561. dry[1][(std::size_t) i] = dr;
  1562. for (int b = 0; b < nb; ++b)
  1563. {
  1564. float g = 1.0f, g2 = 1.0f;
  1565. if (enabled[(std::size_t) b])
  1566. {
  1567. const auto unit = freeLin ? b : L.segmentOf[(std::size_t) b];
  1568. const auto seg = L.segmentOf[(std::size_t) b];
  1569. const bool ext = bandExt[(std::size_t) b];
  1570. // the detector's two channels: the band (split), or the free side-chain filter (round 147)
  1571. float cl, cr;
  1572. if (scFree[(std::size_t) b])
  1573. {
  1574. cl = ext ? extL : srcL;
  1575. cr = ext ? extR : srcR;
  1576. scFilter[(std::size_t) b].run (cl, cr);
  1577. }
  1578. else
  1579. {
  1580. cl = ext ? sl0[seg] : bl[unit];
  1581. cr = ext ? sr0[seg] : br[unit];
  1582. }
  1583. const auto follow = [&] (double& e, double& hold, double m) noexcept {
  1584. const auto x = std::max (-120.0, 20.0 * std::log10 (m + 1e-12));
  1585. e = x > e ? aA[(std::size_t) b] * e + (1.0 - aA[(std::size_t) b]) * x
  1586. : aR[(std::size_t) b] * e + (1.0 - aR[(std::size_t) b]) * x;
  1587. auto gdb = bandCurve (p, b, e, measuredDet);
  1588. if (measuredDet)
  1589. {
  1590. // round 150: the gain's own release after the curve and the range (the reference's
  1591. // immediate recovery); what a rising level does goes through at once (a compressor's
  1592. // growing reduction, an expander's opening)
  1593. if (growsWithLevel[(std::size_t) b] ? std::abs (gdb) >= std::abs (hold) : std::abs (gdb) <= std::abs (hold))
  1594. hold = gdb;
  1595. else
  1596. hold = aR2[(std::size_t) b] * hold + (1.0 - aR2[(std::size_t) b]) * gdb;
  1597. gdb = hold;
  1598. }
  1599. if (std::abs (gdb) > std::abs (extreme[(std::size_t) b]))
  1600. extreme[(std::size_t) b] = gdb;
  1601. return gdb;
  1602. };
  1603. const auto peak = (double) std::max (std::abs (cl), std::abs (cr));
  1604. const auto lev = level[(std::size_t) b];
  1605. if (fullLink[(std::size_t) b]) // 100 % linked: one detector on the louder channel (the old engine)
  1606. g = g2 = (float) dbToGain (follow (env[(std::size_t) b], held[(std::size_t) b], peak) + lev);
  1607. else if (linkM[(std::size_t) b] <= 0.0)
  1608. {
  1609. // [EXEC] partly linked: each channel's detector hears its own level moved towards the louder one
  1610. const auto k = linkA[(std::size_t) b];
  1611. g = (float) dbToGain (follow (env[(std::size_t) b], held[(std::size_t) b], (1.0 - k) * std::abs (cl) + k * peak) + lev);
  1612. g2 = (float) dbToGain (follow (env2[(std::size_t) b], held2[(std::size_t) b], (1.0 - k) * std::abs (cr) + k * peak) + lev);
  1613. }
  1614. else
  1615. {
  1616. // [EXEC] 100 % + mid- (side-) only: the mid's (side's) detector moves from the louder channel to the mid
  1617. // (side) itself, the other part's gain from the linked one to unity
  1618. const auto u = linkM[(std::size_t) b];
  1619. const auto one = std::abs (0.5 * ((double) cl + (linkSide[(std::size_t) b] ? -(double) cr : (double) cr)));
  1620. const auto gOne = dbToGain (follow (env2[(std::size_t) b], held2[(std::size_t) b], (1.0 - u) * peak + u * one));
  1621. const auto gLinked = dbToGain (follow (env[(std::size_t) b], held[(std::size_t) b], peak));
  1622. const auto gOther = (1.0 - u) * gLinked + u;
  1623. const auto lg = dbToGain (lev);
  1624. g = (float) ((linkSide[(std::size_t) b] ? gOther : gOne) * lg); // mid
  1625. g2 = (float) ((linkSide[(std::size_t) b] ? gOne : gOther) * lg); // side
  1626. }
  1627. }
  1628. gain[(std::size_t) b][(std::size_t) i] = gainDelay[(std::size_t) b].process (g);
  1629. gainB[(std::size_t) b][(std::size_t) i] = gainDelayB[(std::size_t) b].process (g2);
  1630. }
  1631. for (int u = 0; u < nu; ++u)
  1632. {
  1633. float sl = bl[u], sr2 = br[u];
  1634. if (minimum) // round 144: the segment passes the all-passes of the crossovers above it
  1635. for (int j = u + 1; j < ns - 1; ++j)
  1636. {
  1637. sl = comp[(std::size_t) u][(std::size_t) j].allpass (sl, 0);
  1638. sr2 = comp[(std::size_t) u][(std::size_t) j].allpass (sr2, 1);
  1639. }
  1640. bandDelay[(std::size_t) u].process (sl, sr2);
  1641. band[(std::size_t) u][0][(std::size_t) i] = sl;
  1642. band[(std::size_t) u][1][(std::size_t) i] = sr2;
  1643. }
  1644. }
  1645. // round 147: Dynamic phase's measured engine — the (look-ahead delayed) input through each working band's
  1646. // minimum-phase filter in cascade (core/MinPhaseBand.h); soloed bands are still listened to through the split
  1647. if (md == Phase::dynamic && measuredDynamic (p) && ! anySolo)
  1648. {
  1649. if (L.loHz != dynLo || L.hiHz != dynHi || L.loSlope != dynLoS || L.hiSlope != dynHiS || nb != dynNb || osFactor != dynOs || bandMs != dynMs)
  1650. {
  1651. // a new layout: every filter is designed again (their states are kept: no click)
  1652. dynLo = L.loHz;
  1653. dynHi = L.hiHz;
  1654. dynLoS = L.loSlope;
  1655. dynHiS = L.hiSlope;
  1656. dynNb = nb;
  1657. dynOs = osFactor;
  1658. dynMs = bandMs;
  1659. for (auto& g2 : dynGain)
  1660. g2.fill (-1.0);
  1661. }
  1662. std::array<bool, bands> works {};
  1663. for (int b = 0; b < nb; ++b)
  1664. {
  1665. const auto i0 = (std::size_t) param (b, 0);
  1666. const bool w = enabled[(std::size_t) b]
  1667. && (std::abs (rangeDb (p[i0 + fRange])) >= 0.01 || level[(std::size_t) b] != 0.0
  1668. || panL[(std::size_t) b] != 1.0f || panR[(std::size_t) b] != 1.0f);
  1669. if (w && ! dynWorks[(std::size_t) b])
  1670. {
  1671. for (auto& fl : dynBand[(std::size_t) b])
  1672. fl.reset();
  1673. dynGain[(std::size_t) b].fill (-1.0);
  1674. }
  1675. works[(std::size_t) b] = dynWorks[(std::size_t) b] = w;
  1676. }
  1677. for (int b = nb; b < bands; ++b)
  1678. dynWorks[(std::size_t) b] = false;
  1679. std::array<int, bands> codeL {}, codeH {};
  1680. for (int b = 0; b < nb; ++b)
  1681. {
  1682. codeL[(std::size_t) b] = minphase::dynamicSideCode (L.loSlope[(std::size_t) b]);
  1683. codeH[(std::size_t) b] = minphase::dynamicSideCode (L.hiSlope[(std::size_t) b]);
  1684. }
  1685. const auto run = [&] (int len, double rate, int every, const float* d0, const float* d1, auto&& gainAt, float* o0, float* o1) noexcept {
  1686. std::array<double, bands> wl {}, wh {};
  1687. for (int b = 0; b < nb; ++b)
  1688. {
  1689. const auto lo = L.loHz[(std::size_t) b], hi = L.hiHz[(std::size_t) b];
  1690. wl[(std::size_t) b] = lo > 0.0 ? minphase::warp (std::min (lo, sr * 0.45), rate) : 0.0;
  1691. wh[(std::size_t) b] = hi > 0.0 ? minphase::warp (std::min (hi, sr * 0.45), rate) : 0.0;
  1692. }
  1693. for (int i = 0; i < len; ++i)
  1694. {
  1695. if (i % every == 0)
  1696. for (int b = 0; b < nb; ++b)
  1697. {
  1698. if (! works[(std::size_t) b])
  1699. continue;
  1700. const auto [ga, gb] = gainAt (b, i);
  1701. const double gc[2] { (double) ga * panA[(std::size_t) b], (double) gb * panB[(std::size_t) b] };
  1702. for (int c = 0; c < 2; ++c)
  1703. if (std::abs (gc[c] - dynGain[(std::size_t) b][(std::size_t) c]) > 1e-7)
  1704. {
  1705. dynGain[(std::size_t) b][(std::size_t) c] = gc[c];
  1706. dynBand[(std::size_t) b][(std::size_t) c].designM (wl[(std::size_t) b], wh[(std::size_t) b],
  1707. codeL[(std::size_t) b], codeH[(std::size_t) b], std::max (gc[c], 1e-6));
  1708. }
  1709. }
  1710. const double xl = d0[i], xr = d1[i];
  1711. // each band's two gains act on left / right, or on mid / side (the pan mode, a mid- / side-only link)
  1712. double yl = xl, yr = xr;
  1713. for (int b = 0; b < nb; ++b)
  1714. if (works[(std::size_t) b])
  1715. {
  1716. if (bandMs[(std::size_t) b])
  1717. {
  1718. const auto a = dynBand[(std::size_t) b][0].process (0.5 * (yl + yr));
  1719. const auto c = dynBand[(std::size_t) b][1].process (0.5 * (yl - yr));
  1720. yl = a + c;
  1721. yr = a - c;
  1722. }
  1723. else
  1724. {
  1725. yl = dynBand[(std::size_t) b][0].process (yl);
  1726. yr = dynBand[(std::size_t) b][1].process (yr);
  1727. }
  1728. }
  1729. o0[i] = (float) ((xl + (yl - xl) * mx) * outGain);
  1730. o1[i] = (float) ((xr + (yr - xr) * mx) * outGain);
  1731. }
  1732. };
  1733. if (osFactor <= 1)
  1734. {
  1735. run (n, sr, 8, dry[0].data(), dry[1].data(),
  1736. [&] (int b, int i) { return std::pair<float, float> { gain[(std::size_t) b][(std::size_t) i], gainB[(std::size_t) b][(std::size_t) i] }; }, l, r);
  1737. return;
  1738. }
  1739. // oversampled: the input and the gains interpolated (the same half-band filters), the filters designed at
  1740. // the high rate, the result decimated back
  1741. const int hi = n * osFactor;
  1742. const auto upsample = [&] (mixsuite::Oversampler& os, const float* src, float* dst) noexcept {
  1743. std::array<float, chunk> tmp {};
  1744. std::copy (src, src + n, tmp.begin());
  1745. int k = 0;
  1746. os.process (tmp.data(), n, [&] (float v) { dst[k++] = v; return 0.0f; });
  1747. };
  1748. for (int c = 0; c < 2; ++c)
  1749. upsample (upDry[(std::size_t) c], dry[(std::size_t) c].data(), hiDry[(std::size_t) c].data());
  1750. for (int b = 0; b < nb; ++b)
  1751. {
  1752. upsample (upGain[(std::size_t) b], gain[(std::size_t) b].data(), hiGain[(std::size_t) b].data());
  1753. upsample (upGainB[(std::size_t) b], gainB[(std::size_t) b].data(), hiGainB[(std::size_t) b].data());
  1754. }
  1755. run (hi, sr * osFactor, 8 * osFactor, hiDry[0].data(), hiDry[1].data(),
  1756. [&] (int b, int k) { return std::pair<float, float> { hiGain[(std::size_t) b][(std::size_t) k], hiGainB[(std::size_t) b][(std::size_t) k] }; },
  1757. hiDry[0].data(), hiDry[1].data());
  1758. for (int c = 0; c < 2; ++c)
  1759. {
  1760. auto* out = c == 0 ? l : r;
  1761. const auto* src = hiDry[(std::size_t) c].data();
  1762. std::fill (out, out + n, 0.0f);
  1763. int k = 0;
  1764. down[(std::size_t) c].process (out, n, [&] (float) { return src[k++]; });
  1765. }
  1766. return;
  1767. }
  1768. // 2. the units' gains applied and summed (at the oversampled rate when oversampling is on)
  1769. const auto combine = [&] (float dl, float dr, auto&& unitAt, auto&& gainAt, float& outL, float& outR) noexcept {
  1770. float yl = anySolo || minimum ? 0.0f : dl, yr = anySolo || minimum ? 0.0f : dr;
  1771. for (int u = 0; u < nu; ++u)
  1772. {
  1773. const auto b = unitBand[(std::size_t) u];
  1774. float sl, sr2;
  1775. unitAt (u, sl, sr2);
  1776. if (b < 0) // a gap (round 150): unity — only the minimum-phase sum needs it
  1777. {
  1778. if (minimum && ! anySolo)
  1779. {
  1780. yl += sl;
  1781. yr += sr2;
  1782. }
  1783. continue;
  1784. }
  1785. const auto [ga, gb] = gainAt (b);
  1786. const auto gl = ga * panA[(std::size_t) b], gr = gb * panB[(std::size_t) b];
  1787. if (bandMs[(std::size_t) b]) // round 144: the pan's two gains on the band's mid and side (round 147: or the link's)
  1788. {
  1789. const auto mid = 0.5f * (sl + sr2), side = 0.5f * (sl - sr2);
  1790. if (anySolo && ! soloed[(std::size_t) b])
  1791. continue;
  1792. if (anySolo || minimum)
  1793. {
  1794. yl += gl * mid + gr * side;
  1795. yr += gl * mid - gr * side;
  1796. }
  1797. else if (gl != 1.0f || gr != 1.0f)
  1798. {
  1799. yl += (gl - 1.0f) * mid + (gr - 1.0f) * side;
  1800. yr += (gl - 1.0f) * mid - (gr - 1.0f) * side;
  1801. }
  1802. continue;
  1803. }
  1804. if (anySolo)
  1805. {
  1806. if (soloed[(std::size_t) b])
  1807. {
  1808. yl += gl * sl;
  1809. yr += gr * sr2;
  1810. }
  1811. }
  1812. else if (minimum)
  1813. {
  1814. yl += gl * sl;
  1815. yr += gr * sr2;
  1816. }
  1817. else if (gl != 1.0f || gr != 1.0f)
  1818. {
  1819. yl += (gl - 1.0f) * sl;
  1820. yr += (gr - 1.0f) * sr2;
  1821. }
  1822. }
  1823. outL = (dl + (yl - dl) * mx) * outGain;
  1824. outR = (dr + (yr - dr) * mx) * outGain;
  1825. };
  1826. if (osFactor <= 1)
  1827. {
  1828. for (int i = 0; i < n; ++i)
  1829. combine (dry[0][(std::size_t) i], dry[1][(std::size_t) i],
  1830. [&] (int u, float& a, float& c) { a = band[(std::size_t) u][0][(std::size_t) i]; c = band[(std::size_t) u][1][(std::size_t) i]; },
  1831. [&] (int b) { return std::pair<float, float> { gain[(std::size_t) b][(std::size_t) i], gainB[(std::size_t) b][(std::size_t) i] }; }, l[i], r[i]);
  1832. return;
  1833. }
  1834. // round 144: oversampling — every stream is interpolated by the same half-band filters (mixsuite::Oversampler:
  1835. // only its upsampling half is used here), the gains are applied at the high rate (no aliasing from fast gain
  1836. // changes), and one more Oversampler's decimating half brings the sum back
  1837. const int hi = n * osFactor;
  1838. const auto upsample = [&] (mixsuite::Oversampler& os, const float* src, float* dst) noexcept {
  1839. std::array<float, chunk> tmp {};
  1840. std::copy (src, src + n, tmp.begin());
  1841. int k = 0;
  1842. os.process (tmp.data(), n, [&] (float s) { dst[k++] = s; return 0.0f; });
  1843. };
  1844. for (int c = 0; c < 2; ++c)
  1845. upsample (upDry[(std::size_t) c], dry[(std::size_t) c].data(), hiDry[(std::size_t) c].data());
  1846. for (int u = 0; u < nu; ++u)
  1847. for (int c = 0; c < 2; ++c)
  1848. upsample (upBand[(std::size_t) u][(std::size_t) c], band[(std::size_t) u][(std::size_t) c].data(), hiBand[(std::size_t) u][(std::size_t) c].data());
  1849. for (int b = 0; b < nb; ++b)
  1850. {
  1851. upsample (upGain[(std::size_t) b], gain[(std::size_t) b].data(), hiGain[(std::size_t) b].data());
  1852. upsample (upGainB[(std::size_t) b], gainB[(std::size_t) b].data(), hiGainB[(std::size_t) b].data());
  1853. }
  1854. for (int k = 0; k < hi; ++k)
  1855. combine (hiDry[0][(std::size_t) k], hiDry[1][(std::size_t) k],
  1856. [&] (int u, float& a, float& c) { a = hiBand[(std::size_t) u][0][(std::size_t) k]; c = hiBand[(std::size_t) u][1][(std::size_t) k]; },
  1857. [&] (int b) { return std::pair<float, float> { hiGain[(std::size_t) b][(std::size_t) k], hiGainB[(std::size_t) b][(std::size_t) k] }; },
  1858. hiDry[0][(std::size_t) k], hiDry[1][(std::size_t) k]);
  1859. for (int c = 0; c < 2; ++c)
  1860. {
  1861. auto* out = c == 0 ? l : r;
  1862. const auto* src = hiDry[(std::size_t) c].data();
  1863. std::fill (out, out + n, 0.0f);
  1864. int k = 0;
  1865. down[(std::size_t) c].process (out, n, [&] (float) { return src[k++]; });
  1866. }
  1867. }
  1868. // what the linear-phase kernels depend on (the layout, and in the free layout the bands' own edges and slopes)
  1869. std::array<double, 4 * bands + 2> kernelKey (const Layout& L, bool freeLin, int nb) const noexcept
  1870. {
  1871. std::array<double, 4 * bands + 2> k {};
  1872. k[0] = freeLin ? 1.0 : 0.0;
  1873. k[1] = freeLin ? (double) nb : (double) L.segments;
  1874. if (freeLin)
  1875. for (int b = 0; b < bands; ++b)
  1876. {
  1877. const bool use = b < nb && L.segmentOf[(std::size_t) b] >= 0;
  1878. k[(std::size_t) (2 + 4 * b)] = use ? L.loHz[(std::size_t) b] : -1.0;
  1879. k[(std::size_t) (3 + 4 * b)] = use ? L.hiHz[(std::size_t) b] : -1.0;
  1880. k[(std::size_t) (4 + 4 * b)] = use ? L.loSlope[(std::size_t) b] : -1.0;
  1881. k[(std::size_t) (5 + 4 * b)] = use ? L.hiSlope[(std::size_t) b] : -1.0;
  1882. }
  1883. return k;
  1884. }
  1885. // the FIR of each segment below the top one: the magnitude of the segment in the IIR tree (the same crossovers),
  1886. // zero phase
  1887. void designKernels (int nb) noexcept
  1888. {
  1889. kernelsDirty = false;
  1890. if (linSize <= 0)
  1891. return;
  1892. const auto bins = linSize / 2 + 1;
  1893. for (int k = 0; k < nb - 1; ++k)
  1894. {
  1895. auto& t = linTable[(std::size_t) k];
  1896. for (int i = 0; i < bins; ++i)
  1897. {
  1898. const auto w = pi * (double) i / (double) (bins - 1);
  1899. double m = 1.0;
  1900. for (int j = 0; j < k; ++j)
  1901. m *= std::abs (split[(std::size_t) j].response (true, w));
  1902. m *= std::abs (split[(std::size_t) k].response (false, w));
  1903. t[(std::size_t) i] = (float) m;
  1904. }
  1905. lin[(std::size_t) k].setKernel (t);
  1906. }
  1907. }
  1908. // round 150: the free layout's FIRs — each band's own shape (Pro-MB's 1 / (1 + x^m), continuous slopes)
  1909. void designFreeKernels (const Layout& L, int nb) noexcept
  1910. {
  1911. kernelsDirty = false;
  1912. if (linSize <= 0)
  1913. return;
  1914. const auto bins = linSize / 2 + 1;
  1915. for (int b = 0; b < nb; ++b)
  1916. {
  1917. if (L.segmentOf[(std::size_t) b] < 0)
  1918. continue;
  1919. const auto wl = L.loHz[(std::size_t) b] > 0.0 ? minphase::warp (L.loHz[(std::size_t) b], sr) : 0.0;
  1920. const auto wh = L.hiHz[(std::size_t) b] > 0.0 ? minphase::warp (L.hiHz[(std::size_t) b], sr) : 0.0;
  1921. auto& t = linTable[(std::size_t) b];
  1922. for (int i = 0; i < bins; ++i)
  1923. {
  1924. const auto w = std::tan (0.5 * pi * std::min ((double) i / (double) (bins - 1), 0.9999));
  1925. t[(std::size_t) i] = (float) linearShare (wl, wh, L.loSlope[(std::size_t) b] / 6.0, L.hiSlope[(std::size_t) b] / 6.0, w);
  1926. }
  1927. lin[(std::size_t) b].setKernel (t);
  1928. }
  1929. }
  1930. void resetOversamplers() noexcept
  1931. {
  1932. for (auto& o : upDry) o.reset();
  1933. for (auto& row : upBand)
  1934. for (auto& o : row) o.reset();
  1935. for (auto& o : upGain) o.reset();
  1936. for (auto& o : upGainB) o.reset();
  1937. for (auto& o : down) o.reset();
  1938. }
  1939. void configure (const EffectParams& p) noexcept
  1940. {
  1941. // round 144: the processing mode and the oversampling (at most 4x, and only up to 400 kHz)
  1942. const int m = linSize > 0 ? (int) phaseOf (p[processingMode]) : (int) Phase::dynamic;
  1943. int factor = oversamplingOf (p[oversampling]);
  1944. while (factor > 1 && sr * factor > 400000.0)
  1945. factor /= 2;
  1946. const auto la = lookaheadMs (p[lookahead]);
  1947. if (la == laMs && m == mode && factor == osFactor)
  1948. return;
  1949. if (m != mode)
  1950. {
  1951. mode = m;
  1952. kernelsDirty = true;
  1953. for (auto& c : lin)
  1954. if (c.n > 0)
  1955. c.clear();
  1956. linDry.reset();
  1957. linSc.reset();
  1958. }
  1959. if (factor != osFactor)
  1960. {
  1961. osFactor = factor;
  1962. const auto set = [&] (mixsuite::Oversampler& o) { o.setFactor (std::max (2, factor)); o.reset(); };
  1963. for (auto& o : upDry) set (o);
  1964. for (auto& row : upBand)
  1965. for (auto& o : row) set (o);
  1966. for (auto& o : upGain) set (o);
  1967. for (auto& o : upGainB) set (o);
  1968. for (auto& o : down) set (o);
  1969. }
  1970. if (la != laMs)
  1971. {
  1972. laMs = la;
  1973. const auto s = (int) std::lround (la * 0.001 * sr);
  1974. laSamples = s;
  1975. delay.setLength (s);
  1976. for (auto& d : bandDelay)
  1977. d.setLength (s);
  1978. }
  1979. latency.store (laSamples + ((Phase) mode == Phase::linear ? linearLatency (sr) : 0)
  1980. + (osFactor > 1 ? mixsuite::Oversampler::latency() : 0),
  1981. std::memory_order_relaxed);
  1982. }
  1983. double sr = 48000.0, laMs = -1.0;
  1984. std::atomic<int> latency { 0 };
  1985. EffectParams lastParams = [] {
  1986. EffectParams p {};
  1987. const auto& info = prismInfo();
  1988. for (std::size_t i = 0; i < info.params.size(); ++i)
  1989. p[i] = info.params[i].defaultValue;
  1990. return p;
  1991. }();
  1992. // round 150: up to 2·bands + 1 segments (the free layout's gaps), 2·bands crossovers
  1993. std::array<Split, maxSegments - 1> split, scSplit;
  1994. std::array<std::array<Split, maxSegments - 1>, maxSegments - 1> comp; // minimum phase: segment k's copy of split j's all-pass
  1995. std::array<double, maxSegments - 1> lastF {};
  1996. const float* scL = nullptr;
  1997. const float* scR = nullptr;
  1998. std::array<int, maxSegments - 1> lastSlope {};
  1999. std::array<double, 4 * bands + 2> lastKernelKey {};
  2000. bool designed = false, kernelsDirty = true;
  2001. int mode = -1, osFactor = 0, linSize = 0, lastNs = 0;
  2002. std::array<peqfl::FftConvolver, bands> lin; // the split layout: one per segment below the top; free: one per band
  2003. std::array<std::vector<float>, bands> linTable;
  2004. LongDelay linDry, linSc;
  2005. StereoDelay delay;
  2006. std::array<StereoDelay, maxSegments> bandDelay;
  2007. std::array<MonoDelay, bands> gainDelay, gainDelayB;
  2008. // round 147: the stereo link (linked part, mid- / side-only part, side mode), the free side-chain filters
  2009. std::array<double, bands> linkA {}, linkM {};
  2010. std::array<bool, bands> linkSide {}, fullLink {}, bandMs {}, scFree {};
  2011. std::array<float, bands> panA {}, panB {};
  2012. std::array<ScFilter, bands> scFilter {};
  2013. int laSamples = 0;
  2014. std::array<double, bands> env {}, env2 {}, extreme {};
  2015. std::array<double, bands> held {}, held2 {}; // round 150: the measured detector's gain after its own release
  2016. std::array<float, bands> gains {};
  2017. // one chunk of the base-rate streams, and the same at the oversampled rate
  2018. std::array<std::array<float, chunk>, 2> dry {};
  2019. std::array<std::array<std::array<float, chunk>, 2>, maxSegments> band {};
  2020. std::array<std::array<float, chunk>, bands> gain {}, gainB {}; // each band's two gains (left / right or mid / side)
  2021. std::array<std::array<float, chunk * maxFactor>, 2> hiDry {};
  2022. std::array<std::array<std::array<float, chunk * maxFactor>, 2>, maxSegments> hiBand {};
  2023. std::array<std::array<float, chunk * maxFactor>, bands> hiGain {}, hiGainB {};
  2024. std::array<mixsuite::Oversampler, 2> upDry, down;
  2025. std::array<std::array<mixsuite::Oversampler, 2>, maxSegments> upBand;
  2026. std::array<mixsuite::Oversampler, bands> upGain, upGainB;
  2027. // round 147: the measured Dynamic phase — each band's two filters (left / right or mid / side), their last gains
  2028. std::array<std::array<minphase::Band, 2>, bands> dynBand {};
  2029. std::array<std::array<double, 2>, bands> dynGain {};
  2030. std::array<bool, bands> dynWorks {};
  2031. std::array<double, bands> dynLo {}, dynHi {}, dynLoS {}, dynHiS {};
  2032. int dynNb = 0, dynOs = 0;
  2033. std::array<bool, bands> dynMs {};
  2034. LiveMeters meters;
  2035. };
  2036. } // namespace
  2037. } // namespace prism
  2038. // ================================================================== Sentry Gate
  2039. namespace sentry
  2040. {
  2041. Style styleOf (float v) noexcept { return (Style) pick (v, styles); }
  2042. float styleValue (Style s) noexcept { return (float) (int) s / (float) (styles - 1); }
  2043. double thresholdDb (float v) noexcept { return lin (v, -60.0, 0.0); }
  2044. double ratioOf (float v) noexcept { return ratioLaw (v); }
  2045. double rangeDb (float v) noexcept { return lin (v, 0.0, 100.0); }
  2046. double attackMs (float v) noexcept { return 1000.0 * std::pow ((double) std::clamp (v, 0.0f, 1.0f), 4.0); }
  2047. double releaseMs (float v) noexcept { return 5000.0 * std::pow ((double) std::clamp (v, 0.0f, 1.0f), 3.0); }
  2048. double holdMs (float v) noexcept { return 250.0 * (double) v * (double) v; }
  2049. double kneeDb (float v) noexcept { return lin (v, 0.0, 30.0); }
  2050. double lookaheadMs (float v) noexcept { return lin (v, 0.0, 10.0); }
  2051. double filterHz (float v) noexcept { return logMap (v, 5.0, 30000.0); }
  2052. float filterValue (double hz) noexcept { return logValue (std::clamp (hz, 5.0, 30000.0), 5.0, 30000.0); }
  2053. double upThresholdDb (float v) noexcept { return lin (v, -30.0, 0.0); }
  2054. double upRatioOf (float v) noexcept { return lin (v, 1.0, 3.0); }
  2055. double scGainDb (float v) noexcept { return lin (v, -36.0, 36.0); }
  2056. double mixOf (float v) noexcept { return lin (v, -1.0, 1.0); }
  2057. double panOf (float v) noexcept { return lin (v, -1.0, 1.0); }
  2058. namespace
  2059. {
  2060. // style families (fitted to MEASURE_fabfilter §7): where an expander starts under the threshold (divided by
  2061. // ratio − 1, so a gate of high ratio opens right at the threshold), the fastest opening, release = base + scale ×
  2062. // knob, the share of the hold knob that delays the release
  2063. struct StyleDef
  2064. {
  2065. double offsetDb, attackMinMs, attackScale, releaseBaseMs, releaseScale, holdScale;
  2066. };
  2067. constexpr StyleDef styleDefs[styles] {
  2068. { 7.9, 0.0, 0.49, 45.0, 0.10, 0.50 }, // classic
  2069. { 4.3, 0.15, 0.49, 120.0, 0.25, 0.50 }, // clean
  2070. { 0.2, 17.0, 0.49, 100.0, 0.20, 0.50 }, // vocal
  2071. { 0.0, 0.7, 0.49, 20.0, 0.05, 0.60 }, // guitar (its release waits ~110 ms, then falls fast)
  2072. { 0.0, 0.0, 0.49, 45.0, 0.10, 0.50 }, // upward
  2073. };
  2074. constexpr double guitarWaitMs = 110.0;
  2075. // target gain (dB) for a detector level x
  2076. double gateCurve (const EffectParams& p, double x) noexcept
  2077. {
  2078. const auto st = styleOf (p[style]);
  2079. if (st == Style::upward)
  2080. {
  2081. const auto ut = upThresholdDb (p[upThreshold]);
  2082. return kneeCurve (x - ut, 1.0 - 1.0 / upRatioOf (p[upRatio]), kneeDb (p[knee]));
  2083. }
  2084. const auto r = ratioOf (p[ratio]);
  2085. if (r <= 1.0001)
  2086. return 0.0;
  2087. const auto start = thresholdDb (p[threshold]) - styleDefs[(int) st].offsetDb / std::max (1.0, r - 1.0);
  2088. return -std::min (rangeDb (p[range]), kneeCurve (start - x, r - 1.0, kneeDb (p[knee])));
  2089. }
  2090. } // namespace
  2091. double hysteresisDb (Style s) noexcept { return styleDefs[(int) s].offsetDb; }
  2092. double staticGainDb (const EffectParams& p, double inputDb, bool)
  2093. {
  2094. const auto g = gateCurve (p, inputDb);
  2095. if (on (p[ducking]) && styleOf (p[style]) != Style::upward) // ducking: the gate turned upside down
  2096. return -rangeDb (p[range]) - g;
  2097. return g;
  2098. }
  2099. namespace
  2100. {
  2101. class Gate final : public Effect
  2102. {
  2103. public:
  2104. explicit Gate (const EffectParams* initial)
  2105. {
  2106. if (initial != nullptr)
  2107. configure (*initial);
  2108. }
  2109. void prepare (double rate) noexcept override
  2110. {
  2111. sr = rate;
  2112. laOn = -1;
  2113. osFactor = 0;
  2114. configure (lastParams);
  2115. reset();
  2116. }
  2117. void reset() noexcept override
  2118. {
  2119. delay.reset();
  2120. gainDelay.reset();
  2121. hp.reset();
  2122. lp.reset();
  2123. for (auto& o : os) o.reset();
  2124. osGain.reset();
  2125. level = 0.0;
  2126. gain = 0.0;
  2127. holdLeft = 0;
  2128. }
  2129. int latencySamples() const noexcept override { return latency.load (std::memory_order_relaxed); }
  2130. float controlOutput (int k) const noexcept override { return meters.read (k); }
  2131. void setSidechain (const float* l, const float* r) noexcept override
  2132. {
  2133. scL = l;
  2134. scR = r;
  2135. }
  2136. void process (float* l, float* r, int n, const EffectParams& p, double bpm) noexcept override
  2137. {
  2138. if (n > maxBlock) // the oversampled path works on blocks of at most maxBlock samples
  2139. {
  2140. const auto* sl = scL;
  2141. const auto* sr2 = scR;
  2142. for (int i = 0; i < n; i += maxBlock)
  2143. {
  2144. if (sl != nullptr && sr2 != nullptr) { scL = sl + i; scR = sr2 + i; }
  2145. processBlock (l + i, r + i, std::min (maxBlock, n - i), p, bpm);
  2146. }
  2147. scL = scR = nullptr;
  2148. return;
  2149. }
  2150. processBlock (l, r, n, p, bpm);
  2151. }
  2152. private:
  2153. void processBlock (float* l, float* r, int n, const EffectParams& p, double) noexcept
  2154. {
  2155. lastParams = p;
  2156. configure (p);
  2157. const auto inPeak = blockPeak (l, r, n);
  2158. const auto st = styleOf (p[style]);
  2159. const auto& sd = styleDefs[(int) st];
  2160. const auto hpHz = filterHz (p[highPass]), lpHz = filterHz (p[lowPass]);
  2161. const bool hpOn = hpHz > 6.0, lpOn = lpHz < std::min (29000.0, sr * 0.45);
  2162. if (hpOn)
  2163. hp.filter (sr, 1, std::min (hpHz, sr * 0.45), 0.70710678);
  2164. if (lpOn)
  2165. lp.filter (sr, 0, std::min (lpHz, sr * 0.45), 0.70710678);
  2166. const bool external = on (p[scExternal]) && scL != nullptr && scR != nullptr;
  2167. const bool listen = on (p[scListen]);
  2168. // round 128: input level, the expert side-chain gain / mix per detector channel (mid / side in M/S mode),
  2169. // ducking, wet / dry pan
  2170. const auto inG = (float) dbToGain (lin (p[input], -24.0, 24.0));
  2171. const bool msMode = on (p[channelMode]);
  2172. const auto gL = (float) dbToGain (scGainDb (p[scGainL])), gR = (float) dbToGain (scGainDb (p[scGainR]));
  2173. const auto mL = (float) mixOf (p[scMixL]), mR = (float) mixOf (p[scMixR]);
  2174. const bool expertSc = msMode || gL != 1.0f || gR != 1.0f || mL != 0.0f || mR != 0.0f;
  2175. const bool duck = on (p[ducking]) && st != Style::upward;
  2176. const auto duckFloor = dbToGain (-rangeDb (p[range]));
  2177. const auto balance = [] (float pan, float& a, float& b) {
  2178. if (pan > 0.0f) a = 1.0f - pan;
  2179. else if (pan < 0.0f) b = 1.0f + pan;
  2180. };
  2181. float wetA = 1.0f, wetB = 1.0f, dryA = 1.0f, dryB = 1.0f;
  2182. balance ((float) panOf (p[wetPan]), wetA, wetB);
  2183. balance ((float) panOf (p[dryPan]), dryA, dryB);
  2184. const bool panned = wetA != 1.0f || wetB != 1.0f || dryA != 1.0f || dryB != 1.0f;
  2185. if (inG != 1.0f)
  2186. for (int i = 0; i < n; ++i)
  2187. {
  2188. l[i] *= inG;
  2189. r[i] *= inG;
  2190. }
  2191. const auto attMs = std::max (sd.attackMinMs, attackMs (p[attack]) * sd.attackScale);
  2192. const auto aA = coef (attMs, sr);
  2193. const auto aR = coef (sd.releaseBaseMs + sd.releaseScale * releaseMs (p[release]), sr);
  2194. const auto holdSamples = (int) (holdMs (p[hold]) * sd.holdScale * 0.001 * sr)
  2195. + (st == Style::guitar ? (int) (guitarWaitMs * 0.001 * sr) : 0);
  2196. const auto levelRel = coef (5.0, sr);
  2197. const auto dryGain = std::clamp (p[dry], 0.0f, 1.0f);
  2198. const auto outGain = (float) dbToGain (lin (p[output], -24.0, 24.0));
  2199. const auto la = laOn > 0 ? lookaheadMs (p[lookahead]) : 0.0;
  2200. gainDelay.setLength (std::max (0, laSamples - (int) std::lround (la * 0.001 * sr)));
  2201. double maxGr = 0.0;
  2202. const bool over = osFactor > 1;
  2203. for (int i = 0; i < n; ++i)
  2204. {
  2205. float sa = external ? scL[i] : l[i], sb = external ? scR[i] : r[i];
  2206. if (expertSc)
  2207. {
  2208. float a0 = sa, b0 = sb;
  2209. if (msMode)
  2210. {
  2211. a0 = 0.5f * (sa + sb);
  2212. b0 = 0.5f * (sa - sb);
  2213. }
  2214. // each detector channel: its own input at mix 0, moving to the first (−1) or second (+1) channel
  2215. const auto pick = [] (float own, float first, float second, float m) {
  2216. return m < 0.0f ? own + (-m) * (first - own) : own + m * (second - own);
  2217. };
  2218. sa = gL * pick (a0, a0, b0, mL);
  2219. sb = gR * pick (b0, a0, b0, mR);
  2220. }
  2221. if (hpOn)
  2222. {
  2223. sa = hp.process (sa, 0);
  2224. sb = hp.process (sb, 1);
  2225. }
  2226. if (lpOn)
  2227. {
  2228. sa = lp.process (sa, 0);
  2229. sb = lp.process (sb, 1);
  2230. }
  2231. if (listen)
  2232. {
  2233. l[i] = sa;
  2234. r[i] = sb;
  2235. continue;
  2236. }
  2237. // peak detector: instant attack, 5 ms release
  2238. const auto m = (double) std::max (std::abs (sa), std::abs (sb));
  2239. level = m > level ? m : levelRel * level + (1.0 - levelRel) * m;
  2240. auto target = dbToGain (gateCurve (p, gainToDb (level)));
  2241. if (duck) // ducking: an open gate is the deepest cut
  2242. target = duckFloor / std::max (1e-9, target);
  2243. // the gain moves in the linear domain: opening with the attack, closing (after hold) with the release
  2244. if (target >= gain)
  2245. {
  2246. gain = aA * gain + (1.0 - aA) * target;
  2247. holdLeft = holdSamples;
  2248. }
  2249. else if (holdLeft > 0)
  2250. --holdLeft;
  2251. else
  2252. gain = aR * gain + (1.0 - aR) * target;
  2253. maxGr = std::max (maxGr, -gainToDb (gain));
  2254. const auto g = gainDelay.process ((float) gain);
  2255. float a = l[i], b = r[i];
  2256. delay.process (a, b);
  2257. if (over) // round 135: the gain is upsampled with the audio and applied at the high rate (below)
  2258. {
  2259. gains[(std::size_t) i] = g;
  2260. l[i] = a;
  2261. r[i] = b;
  2262. continue;
  2263. }
  2264. if (panned)
  2265. {
  2266. l[i] = (a * g * wetA + a * dryGain * dryA) * outGain;
  2267. r[i] = (b * g * wetB + b * dryGain * dryB) * outGain;
  2268. }
  2269. else
  2270. {
  2271. l[i] = (a * g + a * dryGain) * outGain;
  2272. r[i] = (b * g + b * dryGain) * outGain;
  2273. }
  2274. }
  2275. if (over)
  2276. {
  2277. const auto m = n * osFactor;
  2278. if (listen) // the side chain heard through the same path (the latency stays)
  2279. for (int c = 0; c < 2; ++c)
  2280. os[(std::size_t) c].process (c == 0 ? l : r, n, [] (float x) noexcept { return x; });
  2281. else
  2282. {
  2283. int k = 0;
  2284. osGain.process (gains.data(), n, [&] (float x) noexcept { upGain[(std::size_t) std::min (k++, m - 1)] = x; return 0.0f; });
  2285. for (int c = 0; c < 2; ++c)
  2286. {
  2287. const auto wet = (c == 0 ? wetA : wetB) * outGain, dryK = (c == 0 ? dryA : dryB) * dryGain * outGain;
  2288. int j = 0;
  2289. os[(std::size_t) c].process (c == 0 ? l : r, n, [&] (float x) noexcept {
  2290. return x * upGain[(std::size_t) std::min (j++, m - 1)] * wet + x * dryK;
  2291. });
  2292. }
  2293. }
  2294. }
  2295. meters.set (0, (float) std::clamp (maxGr / 30.0, 0.0, 1.0));
  2296. meters.set (2, inPeak);
  2297. meters.set (3, blockPeak (l, r, n));
  2298. scL = scR = nullptr;
  2299. }
  2300. // the look-ahead switch sets the latency (10 ms), the knob only how much of it the detector leads; the
  2301. // oversampler adds its own (round 135)
  2302. void configure (const EffectParams& p) noexcept
  2303. {
  2304. const int want = on (p[lookaheadOn]) ? 1 : 0;
  2305. const int factor = crest::oversamplingOf (p[oversampling]);
  2306. if (want == laOn && factor == osFactor)
  2307. return;
  2308. if (factor != osFactor)
  2309. {
  2310. osFactor = factor;
  2311. for (auto& o : os) { o.setFactor (std::max (2, factor)); o.reset(); }
  2312. osGain.setFactor (std::max (2, factor));
  2313. osGain.reset();
  2314. }
  2315. laOn = want;
  2316. laSamples = want ? (int) std::lround (0.010 * sr) : 0;
  2317. delay.setLength (laSamples);
  2318. latency.store (laSamples + (osFactor > 1 ? mixsuite::Oversampler::latency() : 0), std::memory_order_relaxed);
  2319. }
  2320. static constexpr int maxBlock = 1024, maxFactor = 8;
  2321. int osFactor = 0;
  2322. std::array<mixsuite::Oversampler, 2> os;
  2323. mixsuite::Oversampler osGain;
  2324. std::array<float, maxBlock> gains {};
  2325. std::array<float, maxBlock * maxFactor> upGain {};
  2326. double sr = 48000.0;
  2327. int laOn = -1, laSamples = 0;
  2328. std::atomic<int> latency { 0 };
  2329. EffectParams lastParams = [] {
  2330. EffectParams p {};
  2331. const auto& info = sentryInfo();
  2332. for (std::size_t i = 0; i < info.params.size(); ++i)
  2333. p[i] = info.params[i].defaultValue;
  2334. return p;
  2335. }();
  2336. StereoDelay delay;
  2337. MonoDelay gainDelay;
  2338. Biquad hp, lp;
  2339. double level = 0.0, gain = 0.0;
  2340. int holdLeft = 0;
  2341. const float* scL = nullptr;
  2342. const float* scR = nullptr;
  2343. LiveMeters meters;
  2344. };
  2345. } // namespace
  2346. } // namespace sentry
  2347. // ================================================================== registry
  2348. const EffectInfo& crestInfo()
  2349. {
  2350. static const EffectInfo info { "Crest Compressor",
  2351. { { "Style", 0.0f }, { "Threshold", 0.7f }, { "Ratio", 0.6f }, { "Knee", 0.0f }, { "Range", 1.0f },
  2352. { "Attack", 0.68f }, { "Release", 0.55f }, { "Auto release", 0.0f }, { "Hold", 0.0f },
  2353. { "Lookahead", 0.0f }, { "Max lookahead", 0.0f },
  2354. { "Character", 0.0f }, { "Character pre", 0.0f }, { "Drive", 0.5f },
  2355. { "SC level", 0.5f }, { "External SC", 0.0f }, { "Stereo link", 1.0f }, { "SC listen", 0.0f },
  2356. { "SC1 shape", 0.0f }, { "SC1 freq.", 0.30f }, { "SC1 gain", 0.5f }, { "SC1 Q", 0.5f }, { "SC1 slope", 0.125f },
  2357. { "SC2 shape", 0.0f }, { "SC2 freq.", 0.575f }, { "SC2 gain", 0.5f }, { "SC2 Q", 0.5f }, { "SC2 slope", 0.125f },
  2358. { "SC3 shape", 0.0f }, { "SC3 freq.", 0.80f }, { "SC3 gain", 0.5f }, { "SC3 Q", 0.5f }, { "SC3 slope", 0.125f },
  2359. { "Oversampling", 0.0f }, { "Auto gain", 1.0f }, { "Mix", 1.0f }, { "Input", 0.5f }, { "Output", 0.5f },
  2360. { "Dry", 0.0f }, { "Auto threshold", 0.0f }, { "Link mode", 0.0f }, { "Meter scale", 0.75f },
  2361. { "Input meter", 1.0f },
  2362. { "Wet pan", 0.5f }, { "Dry pan", 0.5f }, // round 135
  2363. // round 137: the side-chain trigger (off), 1/4 note, rate 100 %, length 10 %, no channel
  2364. { "Trigger", 0.0f }, { "Trigger sync", 0.5f }, { "Trigger rate", 0.5f }, { "Trigger length", 0.1f },
  2365. { "Trigger channel", 0.0f } } };
  2366. return info;
  2367. }
  2368. const EffectInfo& prismInfo()
  2369. {
  2370. static const EffectInfo info = [] {
  2371. EffectInfo i { "Prism Multiband", {} };
  2372. static const char* names[prism::bands][prism::fieldsPerBand] {
  2373. { "B1 threshold", "B1 ratio", "B1 range", "B1 expand", "B1 knee", "B1 attack", "B1 release", "B1 level", "B1 on", "B1 solo" },
  2374. { "B2 threshold", "B2 ratio", "B2 range", "B2 expand", "B2 knee", "B2 attack", "B2 release", "B2 level", "B2 on", "B2 solo" },
  2375. { "B3 threshold", "B3 ratio", "B3 range", "B3 expand", "B3 knee", "B3 attack", "B3 release", "B3 level", "B3 on", "B3 solo" },
  2376. { "B4 threshold", "B4 ratio", "B4 range", "B4 expand", "B4 knee", "B4 attack", "B4 release", "B4 level", "B4 on", "B4 solo" },
  2377. { "B5 threshold", "B5 ratio", "B5 range", "B5 expand", "B5 knee", "B5 attack", "B5 release", "B5 level", "B5 on", "B5 solo" },
  2378. { "B6 threshold", "B6 ratio", "B6 range", "B6 expand", "B6 knee", "B6 attack", "B6 release", "B6 level", "B6 on", "B6 solo" }
  2379. };
  2380. // defaults: −18 dB, 4.5 : 1, range −12 dB (downward), knee 24 dB, attack 20 %, release 20 %, 0 dB, on
  2381. const float defaults[prism::fieldsPerBand] { prism::thresholdValue (-18.0), 0.6f, 0.3f, 0.0f, 0.5f, 0.2f, 0.2f, 0.5f, 1.0f, 0.0f };
  2382. for (int b = 0; b < prism::legacyBands; ++b)
  2383. for (int f = 0; f < prism::fieldsPerBand; ++f)
  2384. i.params.push_back ({ names[b][f], defaults[f] });
  2385. i.params.push_back ({ "Crossover 1", prism::crossoverValue (120.0) });
  2386. i.params.push_back ({ "Crossover 2", prism::crossoverValue (1000.0) });
  2387. i.params.push_back ({ "Crossover 3", prism::crossoverValue (6000.0) });
  2388. i.params.push_back ({ "Slope", 0.5f });
  2389. i.params.push_back ({ "Lookahead", 0.0f });
  2390. i.params.push_back ({ "Mix", 1.0f });
  2391. i.params.push_back ({ "Input", 0.5f });
  2392. i.params.push_back ({ "Output", 0.5f });
  2393. for (const auto* n : { "B1 lookahead", "B2 lookahead", "B3 lookahead", "B4 lookahead" })
  2394. i.params.push_back ({ n, 1.0f }); // 20 ms: each band leads by the whole global look-ahead (as before)
  2395. // round 135: bands 5 and 6, crossovers 4 and 5, their look-aheads, the band count (4), each band's output pan,
  2396. // the external side chain
  2397. for (int b = prism::legacyBands; b < prism::bands; ++b)
  2398. for (int f = 0; f < prism::fieldsPerBand; ++f)
  2399. i.params.push_back ({ names[b][f], defaults[f] });
  2400. i.params.push_back ({ "Crossover 4", prism::crossoverValue (10000.0) });
  2401. i.params.push_back ({ "Crossover 5", prism::crossoverValue (14000.0) });
  2402. i.params.push_back ({ "B5 lookahead", 1.0f });
  2403. i.params.push_back ({ "B6 lookahead", 1.0f });
  2404. i.params.push_back ({ "Bands", prism::bandCountValue (4) });
  2405. for (const auto* n : { "B1 pan", "B2 pan", "B3 pan", "B4 pan", "B5 pan", "B6 pan" })
  2406. i.params.push_back ({ n, 0.5f });
  2407. i.params.push_back ({ "External SC", 0.0f });
  2408. // round 144: the processing mode (dynamic phase = the old engine) and the oversampling (off)
  2409. i.params.push_back ({ "Processing", 0.5f });
  2410. i.params.push_back ({ "Oversampling", 0.0f });
  2411. i.params.push_back ({ "Pan mode", 0.0f });
  2412. // round 147: the measured Dynamic phase engine for new instances; projects saved before it load the old one
  2413. // (engine/ProjectFile.cpp sets 0 when the saved parameter list ends before this index)
  2414. i.params.push_back ({ "Dynamic engine", 1.0f });
  2415. // round 147: the expert panel — stereo link (100 %), its mode (mid), side-chain filtering (band), free low / high
  2416. for (const auto* n : { "B1 link", "B2 link", "B3 link", "B4 link", "B5 link", "B6 link" })
  2417. i.params.push_back ({ n, 0.5f });
  2418. for (const auto* n : { "B1 link mode", "B2 link mode", "B3 link mode", "B4 link mode", "B5 link mode", "B6 link mode" })
  2419. i.params.push_back ({ n, 0.0f });
  2420. for (const auto* n : { "B1 SC filter", "B2 SC filter", "B3 SC filter", "B4 SC filter", "B5 SC filter", "B6 SC filter" })
  2421. i.params.push_back ({ n, 0.0f });
  2422. for (const auto* n : { "B1 SC low", "B2 SC low", "B3 SC low", "B4 SC low", "B5 SC low", "B6 SC low" })
  2423. i.params.push_back ({ n, 0.0f });
  2424. for (const auto* n : { "B1 SC high", "B2 SC high", "B3 SC high", "B4 SC high", "B5 SC high", "B6 SC high" })
  2425. i.params.push_back ({ n, 1.0f });
  2426. // round 147: each crossover's own slope (0 = the global Slope, the old sound)
  2427. for (const auto* n : { "Crossover 1 slope", "Crossover 2 slope", "Crossover 3 slope", "Crossover 4 slope", "Crossover 5 slope" })
  2428. i.params.push_back ({ n, 0.0f });
  2429. // round 150: the band layout (split), each band's own edges / slopes for the free layout (the split layout's
  2430. // defaults: 30 – 120 – 1000 – 6000 – 30k, then 10k – 14k – 30k; 24 dB/oct), each band's side-chain input (the
  2431. // global switch) and the detector law (measured for new instances; projects saved before keep the old one)
  2432. i.params.push_back ({ "Band layout", 0.0f });
  2433. {
  2434. static constexpr double lo[prism::bands] { 30.0, 120.0, 1000.0, 6000.0, 10000.0, 14000.0 };
  2435. static constexpr double hi[prism::bands] { 120.0, 1000.0, 6000.0, 30000.0, 14000.0, 30000.0 };
  2436. static const char* loN[prism::bands] { "B1 low", "B2 low", "B3 low", "B4 low", "B5 low", "B6 low" };
  2437. static const char* hiN[prism::bands] { "B1 high", "B2 high", "B3 high", "B4 high", "B5 high", "B6 high" };
  2438. static const char* lsN[prism::bands] { "B1 low slope", "B2 low slope", "B3 low slope", "B4 low slope", "B5 low slope", "B6 low slope" };
  2439. static const char* hsN[prism::bands] { "B1 high slope", "B2 high slope", "B3 high slope", "B4 high slope", "B5 high slope", "B6 high slope" };
  2440. static const char* scN[prism::bands] { "B1 SC input", "B2 SC input", "B3 SC input", "B4 SC input", "B5 SC input", "B6 SC input" };
  2441. for (int b = 0; b < prism::bands; ++b)
  2442. i.params.push_back ({ loN[b], prism::edgeValue (lo[b]) });
  2443. for (int b = 0; b < prism::bands; ++b)
  2444. i.params.push_back ({ hiN[b], prism::edgeValue (hi[b]) });
  2445. for (int b = 0; b < prism::bands; ++b)
  2446. i.params.push_back ({ lsN[b], 0.5f });
  2447. for (int b = 0; b < prism::bands; ++b)
  2448. i.params.push_back ({ hsN[b], 0.5f });
  2449. for (int b = 0; b < prism::bands; ++b)
  2450. i.params.push_back ({ scN[b], 0.0f });
  2451. }
  2452. i.params.push_back ({ "Detector", 1.0f });
  2453. return i;
  2454. }();
  2455. return info;
  2456. }
  2457. const EffectInfo& sentryInfo()
  2458. {
  2459. static const EffectInfo info { "Sentry Gate",
  2460. { { "Style", 0.0f }, { "Threshold", 0.5f }, { "Ratio", 1.0f }, { "Range", 1.0f }, { "Attack", 0.1f },
  2461. { "Release", 0.31f }, { "Hold", 0.28f }, { "Knee", 0.0f }, { "Lookahead", 0.0f },
  2462. { "Lookahead on", 0.0f }, { "High pass", 0.0f }, { "Low pass", 1.0f }, { "External SC", 0.0f },
  2463. { "SC listen", 0.0f }, { "Up threshold", 0.8f }, { "Up ratio", 0.25f }, { "Dry", 0.0f },
  2464. { "Output", 0.5f },
  2465. { "Channel mode", 0.0f }, { "SC gain L", 0.5f }, { "SC mix L", 0.5f }, { "SC gain R", 0.5f },
  2466. { "SC mix R", 0.5f }, { "Wet pan", 0.5f }, { "Dry pan", 0.5f }, { "Ducking", 0.0f },
  2467. { "Input", 0.5f },
  2468. { "Oversampling", 0.0f } } }; // round 135
  2469. return info;
  2470. }
  2471. bool isDynKind (EffectKind kind) noexcept
  2472. {
  2473. return kind == EffectKind::crestCompressor || kind == EffectKind::prismMultiband || kind == EffectKind::sentryGate;
  2474. }
  2475. std::unique_ptr<Effect> make (EffectKind kind, const EffectParams* initial)
  2476. {
  2477. switch (kind)
  2478. {
  2479. case EffectKind::crestCompressor: return std::make_unique<crest::Compressor> (initial);
  2480. case EffectKind::prismMultiband: return std::make_unique<prism::Multiband> (initial);
  2481. case EffectKind::sentryGate: return std::make_unique<sentry::Gate> (initial);
  2482. default: return nullptr;
  2483. }
  2484. }
  2485. std::string paramText (EffectKind kind, int param, float v)
  2486. {
  2487. const auto db = [] (double x) { return fmt ("%+.1f dB", x); };
  2488. if (kind == EffectKind::crestCompressor)
  2489. {
  2490. using namespace crest;
  2491. if (param >= sc1Shape && param <= sc3Slope)
  2492. {
  2493. const auto field = (param - sc1Shape) % 5;
  2494. switch (field)
  2495. {
  2496. case 0: return facet::shapeName (facet::shape (v));
  2497. case 1: return hzText (facet::hz (v));
  2498. case 2: return db (facet::gainDb (v));
  2499. case 3: return fmt ("Q %.2f", facet::q (v));
  2500. default: return std::to_string (facet::slopeDb (v)) + " dB/oct";
  2501. }
  2502. }
  2503. switch (param)
  2504. {
  2505. case style:
  2506. {
  2507. static const char* names[styles] { "Clean", "Allround", "Punch", "Upward", "Two-way", "Vari-mu", "Classic", "Opto",
  2508. "Vocal", "Bus", "Pumping" };
  2509. return names[(int) styleOf (v)];
  2510. }
  2511. case threshold: return fmt ("%.1f dB", thresholdDb (v));
  2512. case ratio: return ratioText (ratioOf (v));
  2513. case knee: return fmt ("%.1f dB", kneeDb (v));
  2514. case range: return fmt ("%.1f dB", rangeDb (v));
  2515. case attack: return msText (attackMs (v));
  2516. case release: return msText (releaseMs (v));
  2517. case hold: return msText (holdMs (v));
  2518. case lookahead: return msText (lookaheadMs (v));
  2519. case maxLookahead: return maxLookaheadMs (v) <= 0.0 ? "off" : msText (maxLookaheadMs (v));
  2520. case character:
  2521. {
  2522. static const char* names[] { "off", "warm", "crisp", "bright" };
  2523. return names[(int) characterOf (v)];
  2524. }
  2525. case characterPre: return on (v) ? "pre" : "post";
  2526. case drive: return db (driveDb (v));
  2527. case scLevel: return db (scLevelDb (v));
  2528. case stereoLink: case mix: return fmt ("%.0f%%", v * 100.0);
  2529. case oversampling: return oversamplingOf (v) == 1 ? "off" : std::to_string (oversamplingOf (v)) + "x";
  2530. case input: case output: return db (trimDb (v));
  2531. case dryGain: return v <= 0.0f ? "-inf dB" : db (dryDb (v));
  2532. case linkMode:
  2533. {
  2534. static const char* names[linkModes] { "Stereo", "Mid only", "Side only", "Mid > side", "Side > mid" };
  2535. return names[(int) linkModeOf (v)];
  2536. }
  2537. case meterScale: return fmt ("%.0f dB", meterRangeDb (v));
  2538. case inputMeter: return on (v) ? "shown" : "hidden";
  2539. case wetPan: case dryPan:
  2540. {
  2541. const auto x = panOf (v);
  2542. return std::abs (x) < 0.005 ? std::string ("C") : fmt (x < 0 ? "%.0f%% L" : "%.0f%% R", std::abs (x) * 100.0);
  2543. }
  2544. case trigger:
  2545. {
  2546. static const char* names[3] { "Off", "Host sync", "MIDI" };
  2547. return names[(int) triggerOf (v)];
  2548. }
  2549. case triggerSync:
  2550. {
  2551. static const char* names[5] { "1/1", "1/2", "1/4", "1/8", "1/16" };
  2552. return names[pick (v, 5)];
  2553. }
  2554. case triggerRate: return fmt ("%.0f%%", 100.0 * triggerRateOf (v));
  2555. case triggerLength: return fmt ("%.0f%%", 100.0 * triggerLengthOf (v));
  2556. case triggerChannel:
  2557. return triggerChannelOf (v) < 0 ? std::string ("Off") : fmt ("Channel %.0f", (double) (triggerChannelOf (v) + 1));
  2558. default: return on (v) ? "on" : "off";
  2559. }
  2560. }
  2561. if (kind == EffectKind::prismMultiband)
  2562. {
  2563. using namespace prism;
  2564. const bool bandField = param < legacyBands * fieldsPerBand || (param >= band5 && param < band5 + 2 * fieldsPerBand);
  2565. if (bandField)
  2566. {
  2567. switch ((param < band5 ? param : param - band5) % fieldsPerBand)
  2568. {
  2569. case fThreshold: return fmt ("%.1f dB", thresholdDb (v));
  2570. case fRatio: return ratioText (ratioOf (v));
  2571. case fRange: return db (rangeDb (v));
  2572. case fMode: return on (v) ? "expand" : "compress";
  2573. case fKnee: return fmt ("%.1f dB", kneeDb (v));
  2574. case fAttack: case fRelease: return fmt ("%.0f%%", v * 100.0);
  2575. case fLevel: return db (levelDb (v));
  2576. default: return on (v) ? "on" : "off";
  2577. }
  2578. }
  2579. switch (param)
  2580. {
  2581. case xover1: case xover2: case xover3: case xover4: case xover5: return hzText (crossoverHz (v));
  2582. case bandCountParam: return std::to_string (1 + pick (v, bands));
  2583. case scExternal: return on (v) ? "external" : "internal";
  2584. case processingMode:
  2585. {
  2586. static const char* const names[3] { "Linear Phase", "Dynamic Phase", "Minimum Phase" };
  2587. return names[(int) phaseOf (v)];
  2588. }
  2589. case oversampling: return oversamplingOf (v) == 1 ? "Off" : std::to_string (oversamplingOf (v)) + "x";
  2590. case panMode: return on (v) ? "mid / side" : "left / right";
  2591. case dynamicEngine: return on (v) ? "measured" : "classic";
  2592. case bandLink0: case bandLink0 + 1: case bandLink0 + 2: case bandLink0 + 3: case bandLink0 + 4: case bandLink0 + 5:
  2593. return v <= 0.5f ? fmt ("%.0f%%", 100.0 * linkAmount (v)) : fmt ("100%%, %.0f%% only", 100.0 * linkOnly (v));
  2594. case bandLinkMode0: case bandLinkMode0 + 1: case bandLinkMode0 + 2: case bandLinkMode0 + 3: case bandLinkMode0 + 4: case bandLinkMode0 + 5:
  2595. return on (v) ? "side" : "mid";
  2596. case bandScFree0: case bandScFree0 + 1: case bandScFree0 + 2: case bandScFree0 + 3: case bandScFree0 + 4: case bandScFree0 + 5:
  2597. return on (v) ? "free" : "band";
  2598. case bandScLow0: case bandScLow0 + 1: case bandScLow0 + 2: case bandScLow0 + 3: case bandScLow0 + 4: case bandScLow0 + 5:
  2599. case bandScHigh0: case bandScHigh0 + 1: case bandScHigh0 + 2: case bandScHigh0 + 3: case bandScHigh0 + 4: case bandScHigh0 + 5:
  2600. return hzText (scFilterHz (v));
  2601. case xoverSlope0: case xoverSlope0 + 1: case xoverSlope0 + 2: case xoverSlope0 + 3: case xoverSlope0 + 4:
  2602. {
  2603. static const char* const names[4] { "global", "12 dB/oct", "24 dB/oct", "48 dB/oct" };
  2604. return names[pick (v, 4)];
  2605. }
  2606. case slope: return std::to_string (slopeDbOct (v)) + " dB/oct";
  2607. case bandLayout: return on (v) ? "free" : "split";
  2608. case detectorLaw: return on (v) ? "measured" : "classic";
  2609. case lookahead: return v <= 0.0f ? "off" : msText (lookaheadMs (v));
  2610. case mix: return fmt ("%.0f%%", v * 100.0);
  2611. case input: case output: return db (trimDb (v));
  2612. default:
  2613. if (param >= bandLo0 && param < bandLoSlope0) // round 150
  2614. return hzText (edgeHz (v));
  2615. if (param >= bandLoSlope0 && param < bandScInput0)
  2616. return fmt ("%.1f dB/oct", slopeOfValue (v));
  2617. if (param >= bandScInput0 && param < bandScInput0 + bands)
  2618. return v < 0.25f ? "global" : (v < 0.75f ? "plug-in input" : "external");
  2619. if (param >= bandPan0 && param < bandPan0 + bands)
  2620. {
  2621. const auto x = panOf (v);
  2622. return std::abs (x) < 0.005 ? std::string ("C") : fmt (x < 0 ? "%.0f%% L" : "%.0f%% R", std::abs (x) * 100.0);
  2623. }
  2624. return msText (lookaheadMs (v)); // the bands' own look-ahead
  2625. }
  2626. }
  2627. if (kind == EffectKind::sentryGate)
  2628. {
  2629. using namespace sentry;
  2630. switch (param)
  2631. {
  2632. case style:
  2633. {
  2634. static const char* names[styles] { "Classic", "Clean", "Vocal", "Guitar", "Upward" };
  2635. return names[(int) styleOf (v)];
  2636. }
  2637. case threshold: return fmt ("%.1f dB", thresholdDb (v));
  2638. case ratio: return ratioText (ratioOf (v));
  2639. case range: return fmt ("%.1f dB", rangeDb (v));
  2640. case attack: return msText (attackMs (v));
  2641. case release: return msText (releaseMs (v));
  2642. case hold: return msText (holdMs (v));
  2643. case knee: return fmt ("%.1f dB", kneeDb (v));
  2644. case lookahead: return msText (lookaheadMs (v));
  2645. case highPass: return v <= 0.0f ? "off" : hzText (filterHz (v));
  2646. case lowPass: return v >= 1.0f ? "off" : hzText (filterHz (v));
  2647. case upThreshold: return fmt ("%.1f dB", upThresholdDb (v));
  2648. case upRatio: return fmt ("%.2f : 1", upRatioOf (v));
  2649. case dry: return fmt ("%.0f%%", v * 100.0);
  2650. case output: case input: return db (lin (v, -24.0, 24.0));
  2651. case oversampling: return crest::oversamplingOf (v) == 1 ? "off" : std::to_string (crest::oversamplingOf (v)) + "x";
  2652. case channelMode: return on (v) ? "Mid/Side" : "Left/Right";
  2653. case scGainL: case scGainR: return db (scGainDb (v));
  2654. case scMixL: case scMixR: return fmt ("%+.2f", mixOf (v));
  2655. case wetPan: case dryPan:
  2656. {
  2657. const auto x = panOf (v);
  2658. return std::abs (x) < 0.005 ? std::string ("C") : fmt (x < 0 ? "%.0f%% L" : "%.0f%% R", std::abs (x) * 100.0);
  2659. }
  2660. default: return on (v) ? "on" : "off";
  2661. }
  2662. }
  2663. return fmt ("%.2f", v);
  2664. }
  2665. } // namespace lynx::dyn