DynamicsSuite.cpp 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  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/MixSuite.h"
  13. // REA_rodada108. Published material the designs rest on:
  14. // - feed-forward compressor with a log-domain level detector (branching attack / release), soft-knee gain computer:
  15. // D. Giannoulis, M. Massberg, J. D. Reiss, "Digital Dynamic Range Compressor Design — A Tutorial and Analysis",
  16. // JAES 60(6), 2012 (§2.2 gain computer, §3 detectors, §4 auto make-up gain);
  17. // - look-ahead by delaying the audio against the side chain: U. Zölzer (ed.), "DAFX", 2nd ed., ch. 4.2;
  18. // - upward compression / expansion as mirrored gain curves of the same computer: ibid. ch. 4.2.2;
  19. // - Linkwitz-Riley crossovers (two cascaded Butterworth sections per side): S. Linkwitz, "Active Crossover
  20. // Networks for Non-coincident Drivers", JAES 24(1), 1976;
  21. // - waveshaping families (smooth odd polynomial, asymmetric clipping, even-order rectifier terms) and their
  22. // harmonic signatures: DAFX ch. 4.3, J. Pakarinen / D. T. Yeh, CMJ 33(2), 2009.
  23. // Every constant that shapes a "style" was fitted by us to the black-box measurements (MEASURE_fabfilter.md); the
  24. // fitted values and their residuals are in REA_rodada108.md.
  25. namespace lynx::dyn
  26. {
  27. namespace
  28. {
  29. constexpr double pi = 3.141592653589793;
  30. inline double dbToGain (double db) noexcept { return std::pow (10.0, db / 20.0); }
  31. inline double gainToDb (double g) noexcept { return 20.0 * std::log10 (std::max (g, 1e-6)); }
  32. inline double logMap (float v, double lo, double hi) noexcept { return lo * std::pow (hi / lo, (double) std::clamp (v, 0.0f, 1.0f)); }
  33. 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); }
  34. inline double lin (float v, double lo, double hi) noexcept { return lo + (hi - lo) * (double) std::clamp (v, 0.0f, 1.0f); }
  35. inline bool on (float v) noexcept { return v >= 0.5f; }
  36. inline double coef (double ms, double sr) noexcept { return ms <= 0.0 ? 0.0 : std::exp (-1.0 / (ms * 0.001 * sr)); }
  37. 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); }
  38. // the shared ratio law: 1 .. 100 : 1, 0.5 ≈ 2.7 : 1, 0.6 ≈ 4.5 : 1, 0.75 ≈ 11 : 1
  39. double ratioLaw (float v) noexcept { return std::exp (std::log (100.0) * std::pow ((double) std::clamp (v, 0.0f, 1.0f), 2.2)); }
  40. 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); }
  41. // Giannoulis et al. eq. (4): reduction (dB, ≥ 0) for an overshoot `o` (dB above the threshold), slope s = 1 − 1/R
  42. double kneeCurve (double o, double s, double knee) noexcept
  43. {
  44. if (2.0 * o <= -knee)
  45. return 0.0;
  46. if (knee > 0.0 && 2.0 * std::abs (o) < knee)
  47. return s * (o + knee * 0.5) * (o + knee * 0.5) / (2.0 * knee);
  48. return s * o;
  49. }
  50. float blockPeak (const float* l, const float* r, int n) noexcept
  51. {
  52. float p = 0.0f;
  53. for (int i = 0; i < n; ++i)
  54. p = std::max (p, std::max (std::abs (l[i]), std::abs (r[i])));
  55. return std::min (p, 1.0f);
  56. }
  57. // Stereo delay line, fixed capacity (no allocation after construction).
  58. struct StereoDelay
  59. {
  60. static constexpr int capacity = 8192; // 20 ms look-ahead at 192 kHz + the oversampler, with room
  61. std::array<float, capacity> l {}, r {};
  62. int pos = 0, len = 0;
  63. void setLength (int n) noexcept
  64. {
  65. n = std::clamp (n, 0, capacity - 1);
  66. if (n != len)
  67. {
  68. len = n;
  69. reset();
  70. }
  71. }
  72. void reset() noexcept { l.fill (0.0f); r.fill (0.0f); pos = 0; }
  73. void process (float& a, float& b) noexcept
  74. {
  75. if (len == 0)
  76. return;
  77. l[(std::size_t) pos] = a;
  78. r[(std::size_t) pos] = b;
  79. auto rd = pos - len;
  80. if (rd < 0)
  81. rd += capacity;
  82. a = l[(std::size_t) rd];
  83. b = r[(std::size_t) rd];
  84. if (++pos == capacity)
  85. pos = 0;
  86. }
  87. };
  88. // mono float delay (the side chain's gain against the look-ahead)
  89. struct MonoDelay
  90. {
  91. static constexpr int capacity = 8192;
  92. std::array<float, capacity> d {};
  93. int pos = 0, len = 0;
  94. void setLength (int n) noexcept { len = std::clamp (n, 0, capacity - 1); }
  95. void reset() noexcept { d.fill (0.0f); pos = 0; }
  96. float process (float x) noexcept
  97. {
  98. if (len == 0)
  99. return x;
  100. d[(std::size_t) pos] = x;
  101. auto rd = pos - len;
  102. if (rd < 0)
  103. rd += capacity;
  104. const auto y = d[(std::size_t) rd];
  105. if (++pos == capacity)
  106. pos = 0;
  107. return y;
  108. }
  109. };
  110. // first-order DC blocker (stereo)
  111. struct DcBlock
  112. {
  113. double a = 0.9995, x1[2] {}, y1[2] {};
  114. void set (double sr) noexcept { a = std::exp (-2.0 * pi * 5.0 / sr); }
  115. void reset() noexcept { x1[0] = x1[1] = y1[0] = y1[1] = 0.0; }
  116. float process (float x, int c) noexcept
  117. {
  118. const auto y = (double) x - x1[c] + a * y1[c];
  119. x1[c] = x;
  120. y1[c] = y;
  121. return (float) y;
  122. }
  123. };
  124. struct LiveMeters
  125. {
  126. std::array<std::atomic<float>, 8> v {};
  127. float read (int k) const noexcept { return k >= 0 && k < 8 ? v[(std::size_t) k].load (std::memory_order_relaxed) : 0.0f; }
  128. void set (int k, float x) noexcept { v[(std::size_t) k].store (x, std::memory_order_relaxed); }
  129. };
  130. std::string fmt (const char* f, double v)
  131. {
  132. char t[48];
  133. std::snprintf (t, sizeof (t), f, v);
  134. return t;
  135. }
  136. std::string hzText (double f)
  137. {
  138. return f >= 1000.0 ? fmt ("%.2f kHz", f / 1000.0) : fmt ("%.0f Hz", f);
  139. }
  140. std::string msText (double ms)
  141. {
  142. if (ms >= 1000.0)
  143. return fmt ("%.2f s", ms / 1000.0);
  144. if (ms >= 100.0)
  145. return fmt ("%.0f ms", ms);
  146. if (ms >= 10.0)
  147. return fmt ("%.1f ms", ms);
  148. return fmt ("%.2f ms", ms);
  149. }
  150. std::string ratioText (double r) { return r >= 99.5 ? "100 : 1" : fmt (r < 10.0 ? "%.2f : 1" : "%.1f : 1", r); }
  151. } // namespace
  152. // ================================================================== Crest Compressor
  153. namespace crest
  154. {
  155. Style styleOf (float v) noexcept { return (Style) pick (v, styles); }
  156. float styleValue (Style s) noexcept { return (float) (int) s / (float) (styles - 1); }
  157. double thresholdDb (float v) noexcept { return lin (v, -60.0, 0.0); }
  158. double ratioOf (float v) noexcept { return ratioLaw (v); }
  159. float ratioValue (double r) noexcept { return ratioLawValue (r); }
  160. double kneeDb (float v) noexcept { return lin (v, 0.0, 72.0); }
  161. double rangeDb (float v) noexcept { return lin (v, 0.0, 60.0); }
  162. double attackMs (float v) noexcept { return logMap (v, 0.005, 250.0); }
  163. float attackValue (double ms) noexcept { return logValue (std::clamp (ms, 0.005, 250.0), 0.005, 250.0); }
  164. double releaseMs (float v) noexcept { return logMap (v, 10.0, 2500.0); }
  165. float releaseValue (double ms) noexcept { return logValue (std::clamp (ms, 10.0, 2500.0), 10.0, 2500.0); }
  166. double holdMs (float v) noexcept { return 500.0 * (double) v * (double) v; }
  167. float holdValue (double ms) noexcept { return (float) std::sqrt (std::clamp (ms / 500.0, 0.0, 1.0)); }
  168. double lookaheadMs (float v) noexcept { return lin (v, 0.0, 20.0); }
  169. double maxLookaheadMs (float v) noexcept
  170. {
  171. static constexpr double ms[] { 0.0, 1.0, 2.0, 5.0, 10.0, 20.0 };
  172. return ms[pick (v, 6)];
  173. }
  174. Character characterOf (float v) noexcept { return (Character) pick (v, 4); }
  175. double driveDb (float v) noexcept { return lin (v, -24.0, 24.0); }
  176. double scLevelDb (float v) noexcept { return lin (v, -36.0, 36.0); }
  177. int oversamplingOf (float v) noexcept { return 1 << pick (v, 4); }
  178. double trimDb (float v) noexcept { return lin (v, -36.0, 36.0); }
  179. namespace
  180. {
  181. // The style families (fitted to MEASURE_fabfilter §2, see REA_rodada108 §3): time-constant scales of the level
  182. // detector (τ = scale × knob), the knee every curve gets on top of the knob, and the curve family.
  183. enum class Curve { downward, upward, twoWay, vocal, variMu };
  184. struct StyleDef
  185. {
  186. double attackScale; // detector attack τ = scale × knob
  187. double releaseScale; // detector release τ = scale × 200 ms × (knob / 200 ms)^releaseExp
  188. double releaseExp; // how much the release follows its knob (1 = proportional, 0 = fixed)
  189. double kneeAdd, kneeScale; // knee = add + scale × knob
  190. Curve curve;
  191. double windowMs; // > 0: the level is the peak over this window (a ripple-free detector for fast releases)
  192. };
  193. constexpr StyleDef styleDefs[styles] {
  194. { 0.265, 1.27, 0.77, 6.0, 0.50, Curve::downward, 0.0 }, // clean
  195. { 0.56, 0.94, 0.15, 6.0, 1.00, Curve::downward, 0.0 }, // allround
  196. { 0.31, 1.10, 0.65, 4.0, 0.80, Curve::downward, 0.0 }, // punch
  197. { 0.31, 2.50, 1.00, 0.0, 1.00, Curve::upward, 0.0 }, // upward
  198. { 0.235, 0.01, 0.00, 0.0, 1.00, Curve::twoWay, 1.3 }, // two-way (recovers within about a millisecond)
  199. { 0.335, 0.65, 0.98, 0.0, 1.00, Curve::variMu, 0.0 }, // vari-mu
  200. { 0.30, 1.57, 0.53, 4.0, 0.17, Curve::downward, 0.0 }, // classic
  201. { 0.32, 1.52, 0.88, 4.0, 0.65, Curve::downward, 0.0 }, // opto
  202. { 1.08, 1.70, 0.04, 0.0, 1.00, Curve::vocal, 0.0 }, // vocal
  203. { 0.24, 3.57, 0.19, 0.0, 1.00, Curve::downward, 0.0 }, // bus
  204. { 0.08, 2.36, 1.00, 0.0, 1.00, Curve::downward, 0.0 }, // pumping
  205. };
  206. double releaseTau (const StyleDef& d, double knobMs) noexcept
  207. {
  208. return d.releaseScale * 200.0 * std::pow (knobMs / 200.0, d.releaseExp);
  209. }
  210. // vari-mu: the share of the full ratio reached at an overshoot o (dB), by slope s = 1 − 1/R — measured (§2.1 data,
  211. // slopes 1/3 … 0.99, overshoots 0 … 18 dB) and divided by our detector's own shortfall (0.96)
  212. double variMuShare (double s, double o) noexcept
  213. {
  214. static constexpr double slopes[6] { 0.3333, 0.5, 0.75, 0.875, 0.95, 0.99 };
  215. static constexpr double table[6][10] {
  216. { 0, 0.071, 0.118, 0.189, 0.28, 0.383, 0.491, 0.599, 0.701, 0.797 },
  217. { 0, 0.102, 0.2, 0.311, 0.422, 0.524, 0.615, 0.695, 0.764, 0.824 },
  218. { 0, 0.263, 0.442, 0.561, 0.645, 0.708, 0.758, 0.797, 0.829, 0.856 },
  219. { 0, 0.478, 0.637, 0.723, 0.776, 0.813, 0.841, 0.863, 0.881, 0.896 },
  220. { 0, 0.545, 0.677, 0.742, 0.783, 0.812, 0.833, 0.85, 0.863, 0.875 },
  221. { 0, 0.665, 0.767, 0.811, 0.839, 0.857, 0.871, 0.882, 0.892, 0.9 } };
  222. if (o <= 0.0)
  223. return 0.0;
  224. const auto row = [&] (int k) {
  225. if (o >= 18.0)
  226. return 1.0 - (1.0 - table[k][9]) * 18.0 / o;
  227. const auto x = o / 2.0;
  228. const int i = std::min (8, (int) x);
  229. return table[k][i] + (table[k][i + 1] - table[k][i]) * (x - i);
  230. };
  231. double f;
  232. if (s <= slopes[0])
  233. f = row (0) * s / slopes[0];
  234. else if (s >= slopes[5])
  235. f = row (5);
  236. else
  237. {
  238. int k = 0;
  239. while (s > slopes[k + 1])
  240. ++k;
  241. const auto t = (s - slopes[k]) / (slopes[k + 1] - slopes[k]);
  242. f = row (k) + (row (k + 1) - row (k)) * t;
  243. }
  244. return std::min (1.0, f / 0.96);
  245. }
  246. // target gain change (dB; negative = reduction) for a detector level `x` (dB)
  247. double curveGain (Style st, double x, double thr, double r, double knee, double range) noexcept
  248. {
  249. const auto& d = styleDefs[(int) st];
  250. const auto s = 1.0 - 1.0 / r;
  251. switch (d.curve)
  252. {
  253. case Curve::upward:
  254. {
  255. // upward: quiet parts are lifted toward a point 10.5 dB under the threshold; above it the gain holds
  256. const auto g = s * (thr - 10.5 - std::min (x, thr));
  257. return std::clamp (g, -range, range);
  258. }
  259. case Curve::twoWay:
  260. {
  261. // two-way: a fixed offset, upward compression below (threshold − 6 dB), downward above (threshold + 4 dB)
  262. 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);
  263. return std::clamp (g, -range, range);
  264. }
  265. case Curve::vocal:
  266. {
  267. // a long smooth curve that already reduces far below the threshold (softplus in dB), steeper on top
  268. const auto k = 8.0 + knee * 0.5;
  269. const auto sv = std::min (1.0, 1.1667 * s);
  270. const auto z = (x - (thr - 2.1)) / k;
  271. const auto soft = z > 30.0 ? z : std::log1p (std::exp (z));
  272. return -std::min (range, sv * k * soft);
  273. }
  274. case Curve::variMu:
  275. {
  276. // the ratio grows with the reduction (variable-mu tube behaviour), as measured
  277. const auto o = std::max (0.0, x - thr);
  278. const auto soft = knee > 0.0 ? kneeCurve (x - thr, 1.0, knee) : o;
  279. return -std::min (range, s * soft * variMuShare (s, o + knee * 0.25));
  280. }
  281. case Curve::downward:
  282. default:
  283. return -std::min (range, kneeCurve (x - thr, s, d.kneeAdd + d.kneeScale * knee));
  284. }
  285. }
  286. void scEqParams (const EffectParams& p, EffectParams& out) noexcept
  287. {
  288. out.fill (0.0f);
  289. for (int b = 0; b < scBands; ++b)
  290. for (int f = 0; f < 5; ++f)
  291. out[(std::size_t) facet::param (b, f)] = p[(std::size_t) scParam (b, f)];
  292. out[(std::size_t) facet::outputParam] = 0.5f;
  293. out[(std::size_t) facet::scaleParam] = 0.5f;
  294. }
  295. } // namespace
  296. double staticGainDb (const EffectParams& p, double inputDb)
  297. {
  298. return curveGain (styleOf (p[style]), inputDb, thresholdDb (p[threshold]), ratioOf (p[ratio]), kneeDb (p[knee]),
  299. std::max (0.01, rangeDb (p[range])));
  300. }
  301. float characterCurve (Character c, float x) noexcept
  302. {
  303. switch (c)
  304. {
  305. case Character::warm:
  306. {
  307. // clean up to about +9 dBFS, then an asymmetric soft limit (the negative side gives first): even + odd
  308. constexpr float tp = 6.5f, tn = 3.0f, sp = 2.0f, sn = 1.5f;
  309. if (x > tp)
  310. return tp + sp * std::tanh ((x - tp) / sp);
  311. if (x < -tn)
  312. return -tn - sn * std::tanh ((-x - tn) / sn);
  313. return x;
  314. }
  315. case Character::crisp:
  316. {
  317. // a slightly expanding cubic (odd harmonics growing with the square of the level), then an asymmetric
  318. // limit far above full scale
  319. const auto u = x + 0.0083f * x * x * x;
  320. return u >= 0.0f ? 16.0f * std::tanh (u / 16.0f) : 12.0f * std::tanh (u / 12.0f);
  321. }
  322. case Character::bright:
  323. {
  324. // an even, rectifier-like term (second harmonic from low levels) and a gentle, slightly asymmetric limit
  325. constexpr float s = 0.1f;
  326. const auto u = x + 0.007f * s * (std::sqrt (1.0f + (x / s) * (x / s)) - 1.0f);
  327. const auto limit = u >= 0.0f ? 7.75f : 5.5f;
  328. const auto a = std::abs (u / limit);
  329. const auto d = 1.0f + a * std::sqrt (a);
  330. return u / std::cbrt (d * d); // u / (1 + |u/L|^1.5)^(1/1.5)
  331. }
  332. case Character::off:
  333. default: return x;
  334. }
  335. }
  336. namespace
  337. {
  338. class Compressor final : public Effect
  339. {
  340. public:
  341. explicit Compressor (const EffectParams* initial)
  342. {
  343. for (auto& d : gainDelay)
  344. d.assign ((std::size_t) gainCapacity, 1.0f);
  345. if (initial != nullptr)
  346. configure (*initial);
  347. }
  348. void prepare (double rate) noexcept override
  349. {
  350. sr = rate;
  351. dc.set (sr);
  352. latencyMs = -1.0; // re-apply the delays
  353. configure (lastParams);
  354. reset();
  355. }
  356. void reset() noexcept override
  357. {
  358. audioDelay.reset();
  359. dryLa.reset();
  360. dryDelay.reset();
  361. for (auto& d : gainDelay)
  362. std::fill (d.begin(), d.end(), 1.0f);
  363. gainPos = 0;
  364. for (auto& o : os)
  365. o.reset();
  366. for (auto& o : osSide)
  367. o.reset();
  368. for (auto& b : scEq)
  369. for (auto& s : b)
  370. s.reset();
  371. for (auto& d : det)
  372. d = {};
  373. for (auto& pk : peaks)
  374. pk.fill (0.0f);
  375. dc.reset();
  376. }
  377. int latencySamples() const noexcept override { return latency.load (std::memory_order_relaxed); }
  378. float controlOutput (int k) const noexcept override { return meters.read (k); }
  379. void setSidechain (const float* l, const float* r) noexcept override
  380. {
  381. scL = l;
  382. scR = r;
  383. }
  384. void process (float* l, float* r, int n, const EffectParams& p, double) noexcept override
  385. {
  386. lastParams = p;
  387. configure (p);
  388. designScEq (p);
  389. for (int off = 0; off < n; off += maxBlock)
  390. chunk (l + off, r + off, std::min (maxBlock, n - off), p, off);
  391. scL = scR = nullptr;
  392. }
  393. private:
  394. static constexpr int maxBlock = 1024, maxFactor = 8;
  395. static constexpr int gainCapacity = 1 << 17; // the side chain's lead at up to 8x the rate (20 ms at 768 kHz)
  396. static constexpr int peakWindow = 4096;
  397. // the detector of one channel
  398. struct Detector
  399. {
  400. double env = -120.0, sustain = 0.0;
  401. int holdLeft = 0, peakPos = 0;
  402. };
  403. // per-chunk settings at the rate the detector runs at
  404. struct Ctx
  405. {
  406. Style st;
  407. double thr, rat, kn, rng, aA, relMs, rate, slowCoef;
  408. int holdSamples, window;
  409. bool autoRel;
  410. };
  411. // latency = the chosen maximum look-ahead (+ the oversampler when on), as the reference does (§2: 960 samples
  412. // for "maximum 20 ms" whatever the look-ahead knob says)
  413. void configure (const EffectParams& p) noexcept
  414. {
  415. const auto la = maxLookaheadMs (p[maxLookahead]);
  416. const auto factor = oversamplingOf (p[oversampling]);
  417. if (la == latencyMs && factor == osFactor)
  418. return;
  419. latencyMs = la;
  420. osFactor = factor;
  421. laSamples = (int) std::lround (la * 0.001 * sr);
  422. const auto osLat = osFactor > 1 ? mixsuite::Oversampler::latency() : 0;
  423. audioDelay.setLength (laSamples);
  424. dryLa.setLength (laSamples);
  425. dryDelay.setLength (osLat);
  426. for (auto* set : { &os, &osSide })
  427. for (auto& o : *set)
  428. o.setFactor (std::max (2, osFactor));
  429. latency.store (laSamples + osLat, std::memory_order_relaxed);
  430. }
  431. void designScEq (const EffectParams& p) noexcept
  432. {
  433. EffectParams fp;
  434. scEqParams (p, fp);
  435. bool any = false;
  436. for (int b = 0; b < scBands; ++b)
  437. {
  438. std::array<facet::Section, facet::maxSections> sec;
  439. const auto count = facet::design (fp, b, sr, sec);
  440. scCount[(std::size_t) b] = count;
  441. for (int k = 0; k < count; ++k)
  442. {
  443. auto& q = scEq[(std::size_t) b][(std::size_t) k];
  444. q.b0 = sec[(std::size_t) k].b0; q.b1 = sec[(std::size_t) k].b1; q.b2 = sec[(std::size_t) k].b2;
  445. q.a1 = sec[(std::size_t) k].a1; q.a2 = sec[(std::size_t) k].a2;
  446. }
  447. any = any || count > 0;
  448. }
  449. scEqOn = any;
  450. }
  451. Ctx context (const EffectParams& p, double rate) const noexcept
  452. {
  453. Ctx c;
  454. c.st = styleOf (p[style]);
  455. const auto& sd = styleDefs[(int) c.st];
  456. c.thr = thresholdDb (p[threshold]);
  457. c.rat = ratioOf (p[ratio]);
  458. c.kn = kneeDb (p[knee]);
  459. c.rng = std::max (0.01, rangeDb (p[range]));
  460. c.aA = coef (std::max (0.002, attackMs (p[attack]) * sd.attackScale), rate);
  461. c.relMs = std::max (0.5, releaseTau (sd, releaseMs (p[release])));
  462. c.autoRel = on (p[autoRelease]) && sd.curve != Curve::twoWay;
  463. c.rate = rate;
  464. c.slowCoef = coef (1000.0, rate);
  465. c.holdSamples = (int) (holdMs (p[hold]) * 0.001 * rate);
  466. c.window = sd.windowMs > 0.0 ? std::clamp ((int) (sd.windowMs * 0.001 * rate), 1, peakWindow) : 0;
  467. return c;
  468. }
  469. // one detector step: the level → the gain (dB) the compressor applies now
  470. double detect (int c, double level, const Ctx& x) noexcept
  471. {
  472. auto& d = det[(std::size_t) c];
  473. if (x.window > 0) // the peak of the last `window` samples
  474. {
  475. auto& ring = peaks[(std::size_t) c];
  476. ring[(std::size_t) (d.peakPos % x.window)] = (float) level;
  477. d.peakPos = (d.peakPos + 1) % x.window;
  478. for (int k = 0; k < x.window; ++k)
  479. level = std::max (level, (double) ring[(std::size_t) k]);
  480. }
  481. const auto in = std::max (-120.0, 20.0 * std::log10 (level + 1e-12));
  482. if (in > d.env)
  483. {
  484. d.env = x.aA * d.env + (1.0 - x.aA) * in;
  485. d.holdLeft = x.holdSamples;
  486. }
  487. else if (d.holdLeft > 0)
  488. --d.holdLeft;
  489. else
  490. {
  491. auto ms = x.relMs;
  492. if (x.autoRel) // program-dependent: short peaks recover faster than sustained reduction
  493. {
  494. const auto now = -curveGain (x.st, d.env, x.thr, x.rat, x.kn, x.rng);
  495. const auto fraction = now > 0.1 ? std::clamp (d.sustain / now, 0.0, 1.0) : 1.0;
  496. ms *= 0.35 + 0.65 * fraction;
  497. }
  498. const auto aR = coef (ms, x.rate);
  499. d.env = aR * d.env + (1.0 - aR) * in;
  500. }
  501. const auto g = curveGain (x.st, d.env, x.thr, x.rat, x.kn, x.rng);
  502. d.sustain = x.slowCoef * d.sustain + (1.0 - x.slowCoef) * std::max (0.0, -g);
  503. return g;
  504. }
  505. // the gains of a run of side-chain samples (per channel, or linked), through the look-ahead's gain delay
  506. double gains (const float* a, const float* b, int count, double link, int lag, const Ctx& x, float* outL, float* outR) noexcept
  507. {
  508. double maxGr = 0.0;
  509. const bool both = link >= 0.999;
  510. for (int i = 0; i < count; ++i)
  511. {
  512. const auto la = std::abs (a[i]), lb = std::abs (b[i]);
  513. const auto m = (double) std::max (la, lb);
  514. float g[2];
  515. const auto g0 = detect (0, link * m + (1.0 - link) * la, x);
  516. g[0] = (float) dbToGain (g0);
  517. maxGr = std::max (maxGr, -g0);
  518. if (both)
  519. g[1] = g[0];
  520. else
  521. {
  522. const auto g1 = detect (1, link * m + (1.0 - link) * lb, x);
  523. g[1] = (float) dbToGain (g1);
  524. maxGr = std::max (maxGr, -g1);
  525. }
  526. for (int c = 0; c < 2; ++c)
  527. {
  528. auto& line = gainDelay[(std::size_t) c];
  529. line[(std::size_t) gainPos] = g[c];
  530. const auto rd = (gainPos - lag + gainCapacity) % gainCapacity;
  531. (c == 0 ? outL : outR)[i] = line[(std::size_t) rd];
  532. }
  533. gainPos = (gainPos + 1) % gainCapacity;
  534. }
  535. return maxGr;
  536. }
  537. void chunk (float* l, float* r, int n, const EffectParams& p, int offset) noexcept
  538. {
  539. const auto inPeak = blockPeak (l, r, n);
  540. const auto ch = characterOf (p[character]);
  541. const bool pre = on (p[characterPre]);
  542. const auto drv = (float) dbToGain (driveDb (p[drive]));
  543. const auto scGain = (float) dbToGain (scLevelDb (p[scLevel]));
  544. const bool external = on (p[scExternal]) && scL != nullptr && scR != nullptr;
  545. const auto link = (double) std::clamp (p[stereoLink], 0.0f, 1.0f);
  546. const auto inGain = (float) dbToGain (trimDb (p[input]));
  547. const auto outGain = (float) dbToGain (trimDb (p[output]));
  548. const auto mx = std::clamp (p[mix], 0.0f, 1.0f);
  549. const auto st = styleOf (p[style]);
  550. float makeup = 1.0f;
  551. if (on (p[autoGain]) && styleDefs[(int) st].curve != Curve::upward)
  552. {
  553. const auto rng = std::max (0.01, rangeDb (p[range]));
  554. makeup = (float) dbToGain (std::min (rng, -0.5 * curveGain (st, 0.0, thresholdDb (p[threshold]), ratioOf (p[ratio]), kneeDb (p[knee]), rng)));
  555. }
  556. const auto la = std::min (lookaheadMs (p[lookahead]), latencyMs);
  557. const auto factor = osFactor > 1 ? osFactor : 1;
  558. const auto lag = std::clamp ((int) std::lround ((latencyMs - la) * 0.001 * sr * factor), 0, gainCapacity - 1);
  559. // the side chain (base rate) and the audio through the look-ahead delay
  560. for (int i = 0; i < n; ++i)
  561. {
  562. float a = l[i] * inGain, b = r[i] * inGain;
  563. float sa, sb;
  564. if (external)
  565. {
  566. sa = scL[offset + i] * inGain;
  567. sb = scR[offset + i] * inGain;
  568. }
  569. else if (pre && ch != Character::off)
  570. {
  571. sa = characterCurve (ch, a * drv) / drv;
  572. sb = characterCurve (ch, b * drv) / drv;
  573. }
  574. else
  575. {
  576. sa = a;
  577. sb = b;
  578. }
  579. sa *= scGain;
  580. sb *= scGain;
  581. if (scEqOn)
  582. for (int q = 0; q < scBands; ++q)
  583. for (int k = 0; k < scCount[(std::size_t) q]; ++k)
  584. {
  585. auto& f = scEq[(std::size_t) q][(std::size_t) k];
  586. sa = f.process (sa, 0);
  587. sb = f.process (sb, 1);
  588. }
  589. sideL[(std::size_t) i] = sa;
  590. sideR[(std::size_t) i] = sb;
  591. dl[(std::size_t) i] = a;
  592. dr[(std::size_t) i] = b;
  593. audioDelay.process (a, b);
  594. wl[(std::size_t) i] = a;
  595. wr[(std::size_t) i] = b;
  596. }
  597. if (on (p[scListen])) // the detector's signal
  598. {
  599. for (int i = 0; i < n; ++i)
  600. l[i] = r[i] = 0.5f * (sideL[(std::size_t) i] + sideR[(std::size_t) i]);
  601. meters.set (0, 0.0f);
  602. meters.set (2, inPeak);
  603. meters.set (3, blockPeak (l, r, n));
  604. return;
  605. }
  606. double maxGr = 0.0;
  607. if (factor == 1)
  608. {
  609. maxGr = gains (sideL.data(), sideR.data(), n, link, lag, context (p, sr), gl.data(), gr.data());
  610. for (int i = 0; i < n; ++i)
  611. {
  612. wl[(std::size_t) i] = stage (wl[(std::size_t) i], gl[(std::size_t) i] * makeup, ch, pre, drv);
  613. wr[(std::size_t) i] = stage (wr[(std::size_t) i], gr[(std::size_t) i] * makeup, ch, pre, drv);
  614. }
  615. }
  616. else
  617. {
  618. // oversampled: the side chain is upsampled (the same path as the audio, so both stay aligned), the
  619. // detector and the gain run at the high rate, and the gain multiplies the upsampled audio
  620. const auto m = n * factor;
  621. for (int c = 0; c < 2; ++c)
  622. {
  623. auto* src = c == 0 ? sideL.data() : sideR.data();
  624. auto* dst = c == 0 ? upL.data() : upR.data();
  625. int k = 0;
  626. osSide[(std::size_t) c].process (src, n, [&] (float v) noexcept {
  627. dst[std::min (k++, m - 1)] = v;
  628. return 0.0f;
  629. });
  630. }
  631. maxGr = gains (upL.data(), upR.data(), m, link, lag, context (p, sr * factor), upGl.data(), upGr.data());
  632. for (int c = 0; c < 2; ++c)
  633. {
  634. const auto* g = c == 0 ? upGl.data() : upGr.data();
  635. int k = 0;
  636. os[(std::size_t) c].process (c == 0 ? wl.data() : wr.data(), n, [&] (float v) noexcept {
  637. return stage (v, g[std::min (k++, m - 1)] * makeup, ch, pre, drv);
  638. });
  639. }
  640. }
  641. for (int i = 0; i < n; ++i)
  642. {
  643. float a = wl[(std::size_t) i], b = wr[(std::size_t) i];
  644. if (ch != Character::off)
  645. {
  646. a = dc.process (a, 0);
  647. b = dc.process (b, 1);
  648. }
  649. float da = dl[(std::size_t) i], db = dr[(std::size_t) i];
  650. dryLa.process (da, db);
  651. dryDelay.process (da, db);
  652. l[i] = (da + (a - da) * mx) * outGain;
  653. r[i] = (db + (b - db) * mx) * outGain;
  654. }
  655. meters.set (0, (float) std::clamp (maxGr / 30.0, 0.0, 1.0));
  656. meters.set (2, inPeak);
  657. meters.set (3, blockPeak (l, r, n));
  658. }
  659. static float stage (float x, float g, Character ch, bool pre, float drv) noexcept
  660. {
  661. if (ch == Character::off)
  662. return x * g;
  663. if (pre)
  664. return characterCurve (ch, x * drv) / drv * g;
  665. return characterCurve (ch, x * g * drv) / drv;
  666. }
  667. double sr = 48000.0, latencyMs = -1.0;
  668. int osFactor = 0, laSamples = 0;
  669. std::atomic<int> latency { 0 };
  670. EffectParams lastParams = [] {
  671. EffectParams p {};
  672. const auto& info = crestInfo();
  673. for (std::size_t i = 0; i < info.params.size(); ++i)
  674. p[i] = info.params[i].defaultValue;
  675. return p;
  676. }();
  677. StereoDelay audioDelay, dryLa, dryDelay;
  678. std::array<std::vector<float>, 2> gainDelay;
  679. int gainPos = 0;
  680. std::array<mixsuite::Oversampler, 2> os, osSide;
  681. std::array<std::array<Biquad, facet::maxSections>, scBands> scEq;
  682. std::array<int, scBands> scCount {};
  683. bool scEqOn = false;
  684. std::array<Detector, 2> det {};
  685. std::array<std::array<float, peakWindow>, 2> peaks {};
  686. DcBlock dc;
  687. const float* scL = nullptr;
  688. const float* scR = nullptr;
  689. std::array<float, maxBlock> wl {}, wr {}, gl {}, gr {}, dl {}, dr {}, sideL {}, sideR {};
  690. std::array<float, maxBlock * maxFactor> upL {}, upR {}, upGl {}, upGr {};
  691. LiveMeters meters;
  692. };
  693. } // namespace
  694. } // namespace crest
  695. // ================================================================== Prism Multiband
  696. namespace prism
  697. {
  698. double thresholdDb (float v) noexcept { return -90.0 * (1.0 - std::sqrt ((double) std::clamp (v, 0.0f, 1.0f))); }
  699. float thresholdValue (double db) noexcept
  700. {
  701. const auto u = 1.0 - std::clamp (-db / 90.0, 0.0, 1.0);
  702. return (float) (u * u);
  703. }
  704. double ratioOf (float v) noexcept { return ratioLaw (v); }
  705. double rangeDb (float v) noexcept { return lin (v, -30.0, 30.0); }
  706. double kneeDb (float v) noexcept { return lin (v, 0.0, 48.0); }
  707. double attackMs (float v) noexcept { return 0.11 + 89.0 * std::pow ((double) std::clamp (v, 0.0f, 1.0f), 3.9); }
  708. double releaseMs (float v) noexcept { return 130.0 + 3500.0 * std::pow ((double) std::clamp (v, 0.0f, 1.0f), 3.0); }
  709. double levelDb (float v) noexcept { return lin (v, -30.0, 30.0); }
  710. double crossoverHz (float v) noexcept { return logMap (v, 30.0, 18000.0); }
  711. float crossoverValue (double hz) noexcept { return logValue (std::clamp (hz, 30.0, 18000.0), 30.0, 18000.0); }
  712. int slopeDbOct (float v) noexcept
  713. {
  714. static constexpr int s[] { 12, 24, 48 };
  715. return s[pick (v, 3)];
  716. }
  717. double lookaheadMs (float v) noexcept { return lin (v, 0.0, 20.0); }
  718. double trimDb (float v) noexcept { return lin (v, -36.0, 36.0); }
  719. namespace
  720. {
  721. // gain change (dB) of a band for a detector level x (dB)
  722. double bandCurve (const EffectParams& p, int b, double x) noexcept
  723. {
  724. const auto at = [&] (int f) { return p[(std::size_t) param (b, f)]; };
  725. const auto thr = thresholdDb (at (fThreshold));
  726. const auto r = ratioOf (at (fRatio));
  727. const auto rng = rangeDb (at (fRange));
  728. const auto kn = kneeDb (at (fKnee));
  729. if (std::abs (rng) < 0.01)
  730. return 0.0;
  731. const bool expand = on (at (fMode));
  732. if (! expand)
  733. {
  734. if (rng < 0.0) // downward compression above the threshold
  735. return -std::min (-rng, kneeCurve (x - thr, 1.0 - 1.0 / r, kn));
  736. return std::min (rng, kneeCurve (thr - x, 1.0 - 1.0 / r, kn)); // upward compression below it
  737. }
  738. if (rng < 0.0) // downward expansion below the threshold
  739. return -std::min (-rng, kneeCurve (thr - x, r - 1.0, kn));
  740. return std::min (rng, kneeCurve (x - thr, 1.0 - 1.0 / r, kn)); // upward expansion above it
  741. }
  742. using Split = LrSplit;
  743. std::array<double, 3> crossovers (const EffectParams& p) noexcept
  744. {
  745. std::array<double, 3> f { crossoverHz (p[xover1]), crossoverHz (p[xover2]), crossoverHz (p[xover3]) };
  746. f[1] = std::max (f[1], f[0] * 1.05);
  747. f[2] = std::max (f[2], f[1] * 1.05);
  748. return f;
  749. }
  750. } // namespace
  751. double bandStaticDb (const EffectParams& p, int b, double inputDb)
  752. {
  753. if (! on (p[(std::size_t) param (b, fEnabled)]))
  754. return 0.0;
  755. return bandCurve (p, b, inputDb) + levelDb (p[(std::size_t) param (b, fLevel)]);
  756. }
  757. double responseDb (const EffectParams& p, const double* bandGainDb, double sampleRate, double hz)
  758. {
  759. const auto f = crossovers (p);
  760. const auto slope = slopeDbOct (p[Global::slope]);
  761. std::array<Split, 3> s;
  762. for (int k = 0; k < 3; ++k)
  763. s[(std::size_t) k].design (sampleRate, f[(std::size_t) k], slope);
  764. const auto w = 2.0 * pi * hz / sampleRate;
  765. // bands of the tree: B0 = L1, B1 = H1·L2, B2 = H1·H2·L3, B3 = H1·H2·H3; out = x + Σ (g − 1)·Bk
  766. const auto l1 = s[0].response (false, w), h1 = s[0].response (true, w);
  767. const auto l2 = s[1].response (false, w), h2 = s[1].response (true, w);
  768. const auto l3 = s[2].response (false, w), h3 = s[2].response (true, w);
  769. const std::complex<double> band[4] { l1, h1 * l2, h1 * h2 * l3, h1 * h2 * h3 };
  770. bool solo = false;
  771. for (int b = 0; b < bands; ++b)
  772. solo = solo || on (p[(std::size_t) param (b, fSolo)]);
  773. std::complex<double> y = solo ? std::complex<double> {} : std::complex<double> { 1.0, 0.0 };
  774. for (int b = 0; b < bands; ++b)
  775. {
  776. const auto g = dbToGain (bandGainDb[b]);
  777. if (solo)
  778. {
  779. if (on (p[(std::size_t) param (b, fSolo)]))
  780. y += g * band[b];
  781. }
  782. else
  783. y += (g - 1.0) * band[b];
  784. }
  785. return gainToDb (std::abs (y)) + trimDb (p[output]);
  786. }
  787. namespace
  788. {
  789. class Multiband final : public Effect
  790. {
  791. public:
  792. explicit Multiband (const EffectParams* initial)
  793. {
  794. if (initial != nullptr)
  795. configure (*initial);
  796. }
  797. void prepare (double rate) noexcept override
  798. {
  799. sr = rate;
  800. laMs = -1.0;
  801. configure (lastParams);
  802. designed = false;
  803. reset();
  804. }
  805. void reset() noexcept override
  806. {
  807. for (auto& s : split)
  808. s.reset();
  809. delay.reset();
  810. for (auto& d : bandDelay)
  811. d.reset();
  812. env.fill (-120.0);
  813. gains.fill (1.0f);
  814. }
  815. int latencySamples() const noexcept override { return latency.load (std::memory_order_relaxed); }
  816. float controlOutput (int k) const noexcept override { return meters.read (k); }
  817. void process (float* l, float* r, int n, const EffectParams& p, double) noexcept override
  818. {
  819. lastParams = p;
  820. configure (p);
  821. const auto f = crossovers (p);
  822. const auto slope = slopeDbOct (p[Global::slope]);
  823. if (! designed || f != lastF || slope != lastSlope)
  824. {
  825. for (int k = 0; k < 3; ++k)
  826. split[(std::size_t) k].design (sr, f[(std::size_t) k], slope);
  827. lastF = f;
  828. lastSlope = slope;
  829. designed = true;
  830. }
  831. const auto inPeak = blockPeak (l, r, n);
  832. const auto inGain = (float) dbToGain (trimDb (p[input]));
  833. const auto outGain = (float) dbToGain (trimDb (p[output]));
  834. const auto mx = std::clamp (p[mix], 0.0f, 1.0f);
  835. std::array<double, bands> aA {}, aR {}, level {};
  836. std::array<bool, bands> enabled {}, soloed {};
  837. bool anySolo = false;
  838. for (int b = 0; b < bands; ++b)
  839. {
  840. aA[(std::size_t) b] = coef (attackMs (p[(std::size_t) param (b, fAttack)]), sr);
  841. aR[(std::size_t) b] = coef (releaseMs (p[(std::size_t) param (b, fRelease)]), sr);
  842. level[(std::size_t) b] = levelDb (p[(std::size_t) param (b, fLevel)]);
  843. enabled[(std::size_t) b] = on (p[(std::size_t) param (b, fEnabled)]);
  844. soloed[(std::size_t) b] = on (p[(std::size_t) param (b, fSolo)]);
  845. anySolo = anySolo || soloed[(std::size_t) b];
  846. }
  847. std::array<double, bands> extreme {};
  848. for (int i = 0; i < n; ++i)
  849. {
  850. const float xl = l[i] * inGain, xr = r[i] * inGain;
  851. float bl[bands], br[bands];
  852. float lo, hi, lo2, hi2;
  853. split[0].run (xl, 0, bl[0], hi);
  854. split[1].run (hi, 0, bl[1], hi2);
  855. split[2].run (hi2, 0, bl[2], bl[3]);
  856. split[0].run (xr, 1, br[0], lo);
  857. split[1].run (lo, 1, br[1], lo2);
  858. split[2].run (lo2, 1, br[2], br[3]);
  859. float dl = xl, dr = xr;
  860. delay.process (dl, dr); // the look-ahead: the audio waits, the detectors don't
  861. float yl = anySolo ? 0.0f : dl, yr = anySolo ? 0.0f : dr;
  862. for (int b = 0; b < bands; ++b)
  863. {
  864. float g = 1.0f;
  865. if (enabled[(std::size_t) b])
  866. {
  867. const auto m = std::max (std::abs (bl[b]), std::abs (br[b]));
  868. const auto x = std::max (-120.0, 20.0 * std::log10 ((double) m + 1e-12));
  869. auto& e = env[(std::size_t) b];
  870. e = x > e ? aA[(std::size_t) b] * e + (1.0 - aA[(std::size_t) b]) * x
  871. : aR[(std::size_t) b] * e + (1.0 - aR[(std::size_t) b]) * x;
  872. const auto gdb = bandCurve (p, b, e);
  873. if (std::abs (gdb) > std::abs (extreme[(std::size_t) b]))
  874. extreme[(std::size_t) b] = gdb;
  875. g = (float) dbToGain (gdb + level[(std::size_t) b]);
  876. }
  877. float sl = bl[b], sr2 = br[b];
  878. bandDelay[(std::size_t) b].process (sl, sr2);
  879. if (anySolo)
  880. {
  881. if (soloed[(std::size_t) b])
  882. {
  883. yl += g * sl;
  884. yr += g * sr2;
  885. }
  886. }
  887. else if (g != 1.0f)
  888. {
  889. yl += (g - 1.0f) * sl;
  890. yr += (g - 1.0f) * sr2;
  891. }
  892. }
  893. l[i] = (dl + (yl - dl) * mx) * outGain;
  894. r[i] = (dr + (yr - dr) * mx) * outGain;
  895. }
  896. for (int b = 0; b < bands; ++b)
  897. meters.set (b, (float) std::clamp (extreme[(std::size_t) b] / 30.0, -1.0, 1.0));
  898. meters.set (4, inPeak);
  899. meters.set (5, blockPeak (l, r, n));
  900. }
  901. private:
  902. void configure (const EffectParams& p) noexcept
  903. {
  904. const auto la = lookaheadMs (p[lookahead]);
  905. if (la == laMs)
  906. return;
  907. laMs = la;
  908. const auto s = (int) std::lround (la * 0.001 * sr);
  909. delay.setLength (s);
  910. for (auto& d : bandDelay)
  911. d.setLength (s);
  912. latency.store (s, std::memory_order_relaxed);
  913. }
  914. double sr = 48000.0, laMs = -1.0;
  915. std::atomic<int> latency { 0 };
  916. EffectParams lastParams = [] {
  917. EffectParams p {};
  918. const auto& info = prismInfo();
  919. for (std::size_t i = 0; i < info.params.size(); ++i)
  920. p[i] = info.params[i].defaultValue;
  921. return p;
  922. }();
  923. std::array<Split, 3> split;
  924. std::array<double, 3> lastF {};
  925. int lastSlope = 0;
  926. bool designed = false;
  927. StereoDelay delay;
  928. std::array<StereoDelay, bands> bandDelay;
  929. std::array<double, bands> env {};
  930. std::array<float, bands> gains {};
  931. LiveMeters meters;
  932. };
  933. } // namespace
  934. } // namespace prism
  935. // ================================================================== Sentry Gate
  936. namespace sentry
  937. {
  938. Style styleOf (float v) noexcept { return (Style) pick (v, styles); }
  939. float styleValue (Style s) noexcept { return (float) (int) s / (float) (styles - 1); }
  940. double thresholdDb (float v) noexcept { return lin (v, -60.0, 0.0); }
  941. double ratioOf (float v) noexcept { return ratioLaw (v); }
  942. double rangeDb (float v) noexcept { return lin (v, 0.0, 100.0); }
  943. double attackMs (float v) noexcept { return 1000.0 * std::pow ((double) std::clamp (v, 0.0f, 1.0f), 4.0); }
  944. double releaseMs (float v) noexcept { return 5000.0 * std::pow ((double) std::clamp (v, 0.0f, 1.0f), 3.0); }
  945. double holdMs (float v) noexcept { return 250.0 * (double) v * (double) v; }
  946. double kneeDb (float v) noexcept { return lin (v, 0.0, 30.0); }
  947. double lookaheadMs (float v) noexcept { return lin (v, 0.0, 10.0); }
  948. double filterHz (float v) noexcept { return logMap (v, 5.0, 30000.0); }
  949. float filterValue (double hz) noexcept { return logValue (std::clamp (hz, 5.0, 30000.0), 5.0, 30000.0); }
  950. double upThresholdDb (float v) noexcept { return lin (v, -30.0, 0.0); }
  951. double upRatioOf (float v) noexcept { return lin (v, 1.0, 3.0); }
  952. namespace
  953. {
  954. // style families (fitted to MEASURE_fabfilter §7): where an expander starts under the threshold (divided by
  955. // ratio − 1, so a gate of high ratio opens right at the threshold), the fastest opening, release = base + scale ×
  956. // knob, the share of the hold knob that delays the release
  957. struct StyleDef
  958. {
  959. double offsetDb, attackMinMs, attackScale, releaseBaseMs, releaseScale, holdScale;
  960. };
  961. constexpr StyleDef styleDefs[styles] {
  962. { 7.9, 0.0, 0.49, 45.0, 0.10, 0.50 }, // classic
  963. { 4.3, 0.15, 0.49, 120.0, 0.25, 0.50 }, // clean
  964. { 0.2, 17.0, 0.49, 100.0, 0.20, 0.50 }, // vocal
  965. { 0.0, 0.7, 0.49, 20.0, 0.05, 0.60 }, // guitar (its release waits ~110 ms, then falls fast)
  966. { 0.0, 0.0, 0.49, 45.0, 0.10, 0.50 }, // upward
  967. };
  968. constexpr double guitarWaitMs = 110.0;
  969. // target gain (dB) for a detector level x
  970. double gateCurve (const EffectParams& p, double x) noexcept
  971. {
  972. const auto st = styleOf (p[style]);
  973. if (st == Style::upward)
  974. {
  975. const auto ut = upThresholdDb (p[upThreshold]);
  976. return kneeCurve (x - ut, 1.0 - 1.0 / upRatioOf (p[upRatio]), kneeDb (p[knee]));
  977. }
  978. const auto r = ratioOf (p[ratio]);
  979. if (r <= 1.0001)
  980. return 0.0;
  981. const auto start = thresholdDb (p[threshold]) - styleDefs[(int) st].offsetDb / std::max (1.0, r - 1.0);
  982. return -std::min (rangeDb (p[range]), kneeCurve (start - x, r - 1.0, kneeDb (p[knee])));
  983. }
  984. } // namespace
  985. double hysteresisDb (Style s) noexcept { return styleDefs[(int) s].offsetDb; }
  986. double staticGainDb (const EffectParams& p, double inputDb, bool)
  987. {
  988. return gateCurve (p, inputDb);
  989. }
  990. namespace
  991. {
  992. class Gate final : public Effect
  993. {
  994. public:
  995. explicit Gate (const EffectParams* initial)
  996. {
  997. if (initial != nullptr)
  998. configure (*initial);
  999. }
  1000. void prepare (double rate) noexcept override
  1001. {
  1002. sr = rate;
  1003. laOn = -1;
  1004. configure (lastParams);
  1005. reset();
  1006. }
  1007. void reset() noexcept override
  1008. {
  1009. delay.reset();
  1010. gainDelay.reset();
  1011. hp.reset();
  1012. lp.reset();
  1013. level = 0.0;
  1014. gain = 0.0;
  1015. holdLeft = 0;
  1016. }
  1017. int latencySamples() const noexcept override { return latency.load (std::memory_order_relaxed); }
  1018. float controlOutput (int k) const noexcept override { return meters.read (k); }
  1019. void setSidechain (const float* l, const float* r) noexcept override
  1020. {
  1021. scL = l;
  1022. scR = r;
  1023. }
  1024. void process (float* l, float* r, int n, const EffectParams& p, double) noexcept override
  1025. {
  1026. lastParams = p;
  1027. configure (p);
  1028. const auto inPeak = blockPeak (l, r, n);
  1029. const auto st = styleOf (p[style]);
  1030. const auto& sd = styleDefs[(int) st];
  1031. const auto hpHz = filterHz (p[highPass]), lpHz = filterHz (p[lowPass]);
  1032. const bool hpOn = hpHz > 6.0, lpOn = lpHz < std::min (29000.0, sr * 0.45);
  1033. if (hpOn)
  1034. hp.filter (sr, 1, std::min (hpHz, sr * 0.45), 0.70710678);
  1035. if (lpOn)
  1036. lp.filter (sr, 0, std::min (lpHz, sr * 0.45), 0.70710678);
  1037. const bool external = on (p[scExternal]) && scL != nullptr && scR != nullptr;
  1038. const bool listen = on (p[scListen]);
  1039. const auto attMs = std::max (sd.attackMinMs, attackMs (p[attack]) * sd.attackScale);
  1040. const auto aA = coef (attMs, sr);
  1041. const auto aR = coef (sd.releaseBaseMs + sd.releaseScale * releaseMs (p[release]), sr);
  1042. const auto holdSamples = (int) (holdMs (p[hold]) * sd.holdScale * 0.001 * sr)
  1043. + (st == Style::guitar ? (int) (guitarWaitMs * 0.001 * sr) : 0);
  1044. const auto levelRel = coef (5.0, sr);
  1045. const auto dryGain = std::clamp (p[dry], 0.0f, 1.0f);
  1046. const auto outGain = (float) dbToGain (lin (p[output], -24.0, 24.0));
  1047. const auto la = laOn > 0 ? lookaheadMs (p[lookahead]) : 0.0;
  1048. gainDelay.setLength (std::max (0, laSamples - (int) std::lround (la * 0.001 * sr)));
  1049. double maxGr = 0.0;
  1050. for (int i = 0; i < n; ++i)
  1051. {
  1052. float sa = external ? scL[i] : l[i], sb = external ? scR[i] : r[i];
  1053. if (hpOn)
  1054. {
  1055. sa = hp.process (sa, 0);
  1056. sb = hp.process (sb, 1);
  1057. }
  1058. if (lpOn)
  1059. {
  1060. sa = lp.process (sa, 0);
  1061. sb = lp.process (sb, 1);
  1062. }
  1063. if (listen)
  1064. {
  1065. l[i] = sa;
  1066. r[i] = sb;
  1067. continue;
  1068. }
  1069. // peak detector: instant attack, 5 ms release
  1070. const auto m = (double) std::max (std::abs (sa), std::abs (sb));
  1071. level = m > level ? m : levelRel * level + (1.0 - levelRel) * m;
  1072. const auto target = dbToGain (gateCurve (p, gainToDb (level)));
  1073. // the gain moves in the linear domain: opening with the attack, closing (after hold) with the release
  1074. if (target >= gain)
  1075. {
  1076. gain = aA * gain + (1.0 - aA) * target;
  1077. holdLeft = holdSamples;
  1078. }
  1079. else if (holdLeft > 0)
  1080. --holdLeft;
  1081. else
  1082. gain = aR * gain + (1.0 - aR) * target;
  1083. maxGr = std::max (maxGr, -gainToDb (gain));
  1084. const auto g = gainDelay.process ((float) gain);
  1085. float a = l[i], b = r[i];
  1086. delay.process (a, b);
  1087. l[i] = (a * g + a * dryGain) * outGain;
  1088. r[i] = (b * g + b * dryGain) * outGain;
  1089. }
  1090. meters.set (0, (float) std::clamp (maxGr / 30.0, 0.0, 1.0));
  1091. meters.set (2, inPeak);
  1092. meters.set (3, blockPeak (l, r, n));
  1093. scL = scR = nullptr;
  1094. }
  1095. private:
  1096. // the look-ahead switch sets the latency (10 ms), the knob only how much of it the detector leads
  1097. void configure (const EffectParams& p) noexcept
  1098. {
  1099. const int want = on (p[lookaheadOn]) ? 1 : 0;
  1100. if (want == laOn)
  1101. return;
  1102. laOn = want;
  1103. laSamples = want ? (int) std::lround (0.010 * sr) : 0;
  1104. delay.setLength (laSamples);
  1105. latency.store (laSamples, std::memory_order_relaxed);
  1106. }
  1107. double sr = 48000.0;
  1108. int laOn = -1, laSamples = 0;
  1109. std::atomic<int> latency { 0 };
  1110. EffectParams lastParams = [] {
  1111. EffectParams p {};
  1112. const auto& info = sentryInfo();
  1113. for (std::size_t i = 0; i < info.params.size(); ++i)
  1114. p[i] = info.params[i].defaultValue;
  1115. return p;
  1116. }();
  1117. StereoDelay delay;
  1118. MonoDelay gainDelay;
  1119. Biquad hp, lp;
  1120. double level = 0.0, gain = 0.0;
  1121. int holdLeft = 0;
  1122. const float* scL = nullptr;
  1123. const float* scR = nullptr;
  1124. LiveMeters meters;
  1125. };
  1126. } // namespace
  1127. } // namespace sentry
  1128. // ================================================================== registry
  1129. const EffectInfo& crestInfo()
  1130. {
  1131. static const EffectInfo info { "Crest Compressor",
  1132. { { "Style", 0.0f }, { "Threshold", 0.7f }, { "Ratio", 0.6f }, { "Knee", 0.0f }, { "Range", 1.0f },
  1133. { "Attack", 0.68f }, { "Release", 0.55f }, { "Auto release", 0.0f }, { "Hold", 0.0f },
  1134. { "Lookahead", 0.0f }, { "Max lookahead", 0.0f },
  1135. { "Character", 0.0f }, { "Character pre", 0.0f }, { "Drive", 0.5f },
  1136. { "SC level", 0.5f }, { "External SC", 0.0f }, { "Stereo link", 1.0f }, { "SC listen", 0.0f },
  1137. { "SC1 shape", 0.0f }, { "SC1 freq.", 0.30f }, { "SC1 gain", 0.5f }, { "SC1 Q", 0.5f }, { "SC1 slope", 0.125f },
  1138. { "SC2 shape", 0.0f }, { "SC2 freq.", 0.575f }, { "SC2 gain", 0.5f }, { "SC2 Q", 0.5f }, { "SC2 slope", 0.125f },
  1139. { "SC3 shape", 0.0f }, { "SC3 freq.", 0.80f }, { "SC3 gain", 0.5f }, { "SC3 Q", 0.5f }, { "SC3 slope", 0.125f },
  1140. { "Oversampling", 0.0f }, { "Auto gain", 1.0f }, { "Mix", 1.0f }, { "Input", 0.5f }, { "Output", 0.5f } } };
  1141. return info;
  1142. }
  1143. const EffectInfo& prismInfo()
  1144. {
  1145. static const EffectInfo info = [] {
  1146. EffectInfo i { "Prism Multiband", {} };
  1147. static const char* names[prism::bands][prism::fieldsPerBand] {
  1148. { "B1 threshold", "B1 ratio", "B1 range", "B1 expand", "B1 knee", "B1 attack", "B1 release", "B1 level", "B1 on", "B1 solo" },
  1149. { "B2 threshold", "B2 ratio", "B2 range", "B2 expand", "B2 knee", "B2 attack", "B2 release", "B2 level", "B2 on", "B2 solo" },
  1150. { "B3 threshold", "B3 ratio", "B3 range", "B3 expand", "B3 knee", "B3 attack", "B3 release", "B3 level", "B3 on", "B3 solo" },
  1151. { "B4 threshold", "B4 ratio", "B4 range", "B4 expand", "B4 knee", "B4 attack", "B4 release", "B4 level", "B4 on", "B4 solo" }
  1152. };
  1153. // defaults: −18 dB, 4.5 : 1, range −12 dB (downward), knee 24 dB, attack 20 %, release 20 %, 0 dB, on
  1154. 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 };
  1155. for (int b = 0; b < prism::bands; ++b)
  1156. for (int f = 0; f < prism::fieldsPerBand; ++f)
  1157. i.params.push_back ({ names[b][f], defaults[f] });
  1158. i.params.push_back ({ "Crossover 1", prism::crossoverValue (120.0) });
  1159. i.params.push_back ({ "Crossover 2", prism::crossoverValue (1000.0) });
  1160. i.params.push_back ({ "Crossover 3", prism::crossoverValue (6000.0) });
  1161. i.params.push_back ({ "Slope", 0.5f });
  1162. i.params.push_back ({ "Lookahead", 0.0f });
  1163. i.params.push_back ({ "Mix", 1.0f });
  1164. i.params.push_back ({ "Input", 0.5f });
  1165. i.params.push_back ({ "Output", 0.5f });
  1166. return i;
  1167. }();
  1168. return info;
  1169. }
  1170. const EffectInfo& sentryInfo()
  1171. {
  1172. static const EffectInfo info { "Sentry Gate",
  1173. { { "Style", 0.0f }, { "Threshold", 0.5f }, { "Ratio", 1.0f }, { "Range", 1.0f }, { "Attack", 0.1f },
  1174. { "Release", 0.31f }, { "Hold", 0.28f }, { "Knee", 0.0f }, { "Lookahead", 0.0f },
  1175. { "Lookahead on", 0.0f }, { "High pass", 0.0f }, { "Low pass", 1.0f }, { "External SC", 0.0f },
  1176. { "SC listen", 0.0f }, { "Up threshold", 0.8f }, { "Up ratio", 0.25f }, { "Dry", 0.0f },
  1177. { "Output", 0.5f } } };
  1178. return info;
  1179. }
  1180. bool isDynKind (EffectKind kind) noexcept
  1181. {
  1182. return kind == EffectKind::crestCompressor || kind == EffectKind::prismMultiband || kind == EffectKind::sentryGate;
  1183. }
  1184. std::unique_ptr<Effect> make (EffectKind kind, const EffectParams* initial)
  1185. {
  1186. switch (kind)
  1187. {
  1188. case EffectKind::crestCompressor: return std::make_unique<crest::Compressor> (initial);
  1189. case EffectKind::prismMultiband: return std::make_unique<prism::Multiband> (initial);
  1190. case EffectKind::sentryGate: return std::make_unique<sentry::Gate> (initial);
  1191. default: return nullptr;
  1192. }
  1193. }
  1194. std::string paramText (EffectKind kind, int param, float v)
  1195. {
  1196. const auto db = [] (double x) { return fmt ("%+.1f dB", x); };
  1197. if (kind == EffectKind::crestCompressor)
  1198. {
  1199. using namespace crest;
  1200. if (param >= sc1Shape && param <= sc3Slope)
  1201. {
  1202. const auto field = (param - sc1Shape) % 5;
  1203. switch (field)
  1204. {
  1205. case 0: return facet::shapeName (facet::shape (v));
  1206. case 1: return hzText (facet::hz (v));
  1207. case 2: return db (facet::gainDb (v));
  1208. case 3: return fmt ("Q %.2f", facet::q (v));
  1209. default: return std::to_string (facet::slopeDb (v)) + " dB/oct";
  1210. }
  1211. }
  1212. switch (param)
  1213. {
  1214. case style:
  1215. {
  1216. static const char* names[styles] { "Clean", "Allround", "Punch", "Upward", "Two-way", "Vari-mu", "Classic", "Opto",
  1217. "Vocal", "Bus", "Pumping" };
  1218. return names[(int) styleOf (v)];
  1219. }
  1220. case threshold: return fmt ("%.1f dB", thresholdDb (v));
  1221. case ratio: return ratioText (ratioOf (v));
  1222. case knee: return fmt ("%.1f dB", kneeDb (v));
  1223. case range: return fmt ("%.1f dB", rangeDb (v));
  1224. case attack: return msText (attackMs (v));
  1225. case release: return msText (releaseMs (v));
  1226. case hold: return msText (holdMs (v));
  1227. case lookahead: return msText (lookaheadMs (v));
  1228. case maxLookahead: return maxLookaheadMs (v) <= 0.0 ? "off" : msText (maxLookaheadMs (v));
  1229. case character:
  1230. {
  1231. static const char* names[] { "off", "warm", "crisp", "bright" };
  1232. return names[(int) characterOf (v)];
  1233. }
  1234. case characterPre: return on (v) ? "pre" : "post";
  1235. case drive: return db (driveDb (v));
  1236. case scLevel: return db (scLevelDb (v));
  1237. case stereoLink: case mix: return fmt ("%.0f%%", v * 100.0);
  1238. case oversampling: return oversamplingOf (v) == 1 ? "off" : std::to_string (oversamplingOf (v)) + "x";
  1239. case input: case output: return db (trimDb (v));
  1240. default: return on (v) ? "on" : "off";
  1241. }
  1242. }
  1243. if (kind == EffectKind::prismMultiband)
  1244. {
  1245. using namespace prism;
  1246. if (param < bands * fieldsPerBand)
  1247. {
  1248. switch (param % fieldsPerBand)
  1249. {
  1250. case fThreshold: return fmt ("%.1f dB", thresholdDb (v));
  1251. case fRatio: return ratioText (ratioOf (v));
  1252. case fRange: return db (rangeDb (v));
  1253. case fMode: return on (v) ? "expand" : "compress";
  1254. case fKnee: return fmt ("%.1f dB", kneeDb (v));
  1255. case fAttack: case fRelease: return fmt ("%.0f%%", v * 100.0);
  1256. case fLevel: return db (levelDb (v));
  1257. default: return on (v) ? "on" : "off";
  1258. }
  1259. }
  1260. switch (param)
  1261. {
  1262. case xover1: case xover2: case xover3: return hzText (crossoverHz (v));
  1263. case slope: return std::to_string (slopeDbOct (v)) + " dB/oct";
  1264. case lookahead: return v <= 0.0f ? "off" : msText (lookaheadMs (v));
  1265. case mix: return fmt ("%.0f%%", v * 100.0);
  1266. default: return db (trimDb (v));
  1267. }
  1268. }
  1269. if (kind == EffectKind::sentryGate)
  1270. {
  1271. using namespace sentry;
  1272. switch (param)
  1273. {
  1274. case style:
  1275. {
  1276. static const char* names[styles] { "Classic", "Clean", "Vocal", "Guitar", "Upward" };
  1277. return names[(int) styleOf (v)];
  1278. }
  1279. case threshold: return fmt ("%.1f dB", thresholdDb (v));
  1280. case ratio: return ratioText (ratioOf (v));
  1281. case range: return fmt ("%.1f dB", rangeDb (v));
  1282. case attack: return msText (attackMs (v));
  1283. case release: return msText (releaseMs (v));
  1284. case hold: return msText (holdMs (v));
  1285. case knee: return fmt ("%.1f dB", kneeDb (v));
  1286. case lookahead: return msText (lookaheadMs (v));
  1287. case highPass: return v <= 0.0f ? "off" : hzText (filterHz (v));
  1288. case lowPass: return v >= 1.0f ? "off" : hzText (filterHz (v));
  1289. case upThreshold: return fmt ("%.1f dB", upThresholdDb (v));
  1290. case upRatio: return fmt ("%.2f : 1", upRatioOf (v));
  1291. case dry: return fmt ("%.0f%%", v * 100.0);
  1292. case output: return db (lin (v, -24.0, 24.0));
  1293. default: return on (v) ? "on" : "off";
  1294. }
  1295. }
  1296. return fmt ("%.2f", v);
  1297. }
  1298. } // namespace lynx::dyn