VoiceMatch.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. #include "core/VoiceMatch.h"
  2. #include <algorithm>
  3. #include <cmath>
  4. #include <cstring>
  5. #include <iterator>
  6. namespace lynx::vmatch
  7. {
  8. namespace
  9. {
  10. constexpr double pi = 3.141592653589793;
  11. constexpr double refRate = 48000.0; // the rate the calibration was measured at
  12. inline double dbToGain (double db) noexcept { return std::pow (10.0, db / 20.0); }
  13. inline double gainToDb (double g) noexcept { return 20.0 * std::log10 (std::max (g, 1e-12)); }
  14. inline double coefMs (double ms, double sr) noexcept { return ms <= 0.0 ? 1.0 : 1.0 - std::exp (-1000.0 / (ms * sr)); }
  15. inline double roundTo (double v, double step) noexcept { return std::round (v / step) * step; }
  16. // piecewise-linear lookup in a sorted table
  17. double interp (const float* xs, const float* ys, std::size_t N, double x) noexcept
  18. {
  19. if (x <= xs[0])
  20. return ys[0];
  21. if (x >= xs[N - 1])
  22. return ys[N - 1];
  23. const auto* it = std::upper_bound (xs, xs + N, (float) x);
  24. const auto i = (std::size_t) (it - xs) - 1;
  25. const auto t = (x - xs[i]) / (xs[i + 1] - xs[i]);
  26. return ys[i] + t * (ys[i + 1] - ys[i]);
  27. }
  28. // bilinear transform of an analog biquad (n2 s^2 + n1 s + n0) / (s^2 + d1 s + d0) with s = K (1 - z^-1) / (1 + z^-1)
  29. void bilinear (const double n[3], const double d[2], double K, Biquad& b) noexcept
  30. {
  31. const double K2 = K * K;
  32. const double b0 = n[0] * K2 + n[1] * K + n[2], b1 = 2.0 * (n[2] - n[0] * K2), b2 = n[0] * K2 - n[1] * K + n[2];
  33. const double a0 = K2 + d[0] * K + d[1], a1 = 2.0 * (d[1] - K2), a2 = K2 - d[0] * K + d[1];
  34. b.set (b0, b1, b2, a0, a1, a2);
  35. }
  36. double biquadMagnitude (const Biquad& b, double w) noexcept
  37. {
  38. const double c1 = std::cos (w), s1 = std::sin (w), c2 = std::cos (2 * w), s2 = std::sin (2 * w);
  39. const double nr = b.b0 + b.b1 * c1 + b.b2 * c2, ni = -(b.b1 * s1 + b.b2 * s2);
  40. const double dr = 1.0 + b.a1 * c1 + b.a2 * c2, di = -(b.a1 * s1 + b.a2 * s2);
  41. return std::sqrt ((nr * nr + ni * ni) / std::max (dr * dr + di * di, 1e-300));
  42. }
  43. } // namespace
  44. namespace echannel
  45. {
  46. namespace
  47. {
  48. #include "core/VoiceMatchTables.inc"
  49. constexpr double gainNodes[21] = { -15, -13.5, -12, -10.5, -9, -7.5, -6, -4.5, -3, -1.5, 0, 1.5, 3, 4.5, 6, 7.5, 9, 10.5, 12, 13.5, 15 };
  50. // Catmull-Rom over the gain nodes of one segment ([-15,-7.5], [-7.5,0], [0,7.5], [7.5,15]: the band's law changes
  51. // slope at the segment ends, measured), `at(i)` = the feature vector of gain node i
  52. template <typename At>
  53. void gainInterp (double g, At at, double out[5]) noexcept
  54. {
  55. g = std::clamp (g, -15.0, 15.0);
  56. const int seg = g < -7.5 ? 0 : (g < 0.0 ? 1 : (g < 7.5 ? 2 : 3));
  57. const int lo = seg * 5, hi = lo + 5; // node indexes of the segment ends
  58. int i = std::clamp ((int) std::floor ((g + 15.0) / 1.5), lo, hi - 1);
  59. const double t = (g - gainNodes[i]) / 1.5;
  60. double p0[5], p1[5], p2[5], p3[5];
  61. at (i, p1);
  62. at (i + 1, p2);
  63. if (i > lo) at (i - 1, p0); else for (int k = 0; k < 5; ++k) p0[k] = 2 * p1[k] - p2[k];
  64. if (i + 2 <= hi) at (i + 2, p3); else for (int k = 0; k < 5; ++k) p3[k] = 2 * p2[k] - p1[k];
  65. const double t2 = t * t, t3 = t2 * t;
  66. for (int k = 0; k < 5; ++k)
  67. {
  68. const double m1 = 0.5 * (p2[k] - p0[k]), m2 = 0.5 * (p3[k] - p1[k]);
  69. out[k] = (2 * t3 - 3 * t2 + 1) * p1[k] + (t3 - 2 * t2 + t) * m1 + (-2 * t3 + 3 * t2) * p2[k] + (t3 - t2) * m2;
  70. }
  71. }
  72. struct Axis { int i; double t; };
  73. Axis axis (const float* nodes, std::size_t N, double x) noexcept
  74. {
  75. int i = 0;
  76. while (i < (int) N - 2 && x > nodes[i + 1])
  77. ++i;
  78. const double t = std::clamp ((x - nodes[i]) / (nodes[i + 1] - nodes[i]), 0.0, 1.0);
  79. return { i, t };
  80. }
  81. // the analog-domain biquad (normalised features x reference frequency) of one band, and its reference frequency
  82. bool bandAnalog (int band, const Settings& s, double n[3], double d[2], double& wref) noexcept
  83. {
  84. double g = 0.0, f = 0.0, q = 0.0;
  85. bool bell = false;
  86. switch (band)
  87. {
  88. case 0: g = s.lfGain; f = roundTo (std::clamp (s.lfHz, 30.0, 450.0), 1.0); bell = s.lfBell; break;
  89. case 1: g = s.lmfGain; f = roundTo (std::clamp (s.lmfKHz, 0.2, 2.5), 0.01) * 1000.0; q = s.lmfQ; break;
  90. case 2: g = s.hmfGain; f = roundTo (std::clamp (s.hmfKHz, 0.6, 7.0), 0.01) * 1000.0; q = s.hmfQ; break;
  91. default: g = s.hfGain; f = roundTo (std::clamp (s.hfKHz, 1.5, 16.0), 0.01) * 1000.0; bell = s.hfBell; break;
  92. }
  93. g = roundTo (g, 0.1);
  94. if (std::abs (g) < 0.05)
  95. return false;
  96. double u[5];
  97. if (band == 0 || band == 3)
  98. {
  99. const bool lo = band == 0;
  100. const float* feat = lo ? lfFeat : hfFeat;
  101. const double lw = lo ? interp (lfLawText, lfLawLogW, std::size (lfLawText), f) : interp (hfLawText, hfLawLogW, std::size (hfLawText), f);
  102. wref = std::exp (lw);
  103. const auto ax = lo ? axis (lfNodeLogW, std::size (lfNodeLogW), lw) : axis (hfNodeLogW, std::size (hfNodeLogW), lw);
  104. const int nf = (int) (lo ? std::size (lfNodeLogW) : std::size (hfNodeLogW)), type = bell ? 1 : 0;
  105. gainInterp (g, [&] (int gi, double* o) {
  106. const float* a = feat + ((type * 21 + gi) * nf + ax.i) * 5;
  107. for (int k = 0; k < 5; ++k)
  108. o[k] = (1 - ax.t) * a[k] + ax.t * a[5 + k];
  109. }, u);
  110. }
  111. else
  112. {
  113. const bool lo = band == 1;
  114. const float* feat = lo ? lmfFeat : hmfFeat;
  115. const double lw = lo ? interp (lmfLawText, lmfLawLogW, std::size (lmfLawText), f) : interp (hmfLawText, hmfLawLogW, std::size (hmfLawText), f);
  116. wref = std::exp (lw);
  117. const auto ax = lo ? axis (lmfNodeLogW, std::size (lmfNodeLogW), lw) : axis (hmfNodeLogW, std::size (hmfNodeLogW), lw);
  118. const auto aq = lo ? axis (lmfQv, std::size (lmfQv), dialFromQ (roundTo (q, 0.01))) : axis (hmfQv, std::size (hmfQv), dialFromQ (roundTo (q, 0.01)));
  119. const int nf = (int) (lo ? std::size (lmfNodeLogW) : std::size (hmfNodeLogW)), nq = (int) std::size (lmfQv);
  120. gainInterp (g, [&] (int gi, double* o) {
  121. for (int k = 0; k < 5; ++k)
  122. o[k] = 0.0;
  123. for (int df = 0; df < 2; ++df)
  124. for (int dq = 0; dq < 2; ++dq)
  125. {
  126. const double w = (df ? ax.t : 1 - ax.t) * (dq ? aq.t : 1 - aq.t);
  127. const float* a = feat + ((gi * nf + ax.i + df) * nq + aq.i + dq) * 5;
  128. for (int k = 0; k < 5; ++k)
  129. o[k] += w * a[k];
  130. }
  131. }, u);
  132. }
  133. n[0] = u[0];
  134. n[1] = u[1] * wref;
  135. n[2] = u[2] * wref * wref;
  136. d[0] = u[3] * wref;
  137. d[1] = u[4] * wref * wref;
  138. return true;
  139. }
  140. // At other sample rates the 48 kHz analog-domain response is kept at the band's own frequency: the prototype is
  141. // scaled so that bilinear(K = 2 sr) maps that frequency where bilinear(K = 96000) mapped it at 48 kHz [model]
  142. double rateScale (double wref, double sr) noexcept
  143. {
  144. if (std::abs (sr - refRate) < 1.0)
  145. return 1.0;
  146. const double f0 = refRate / pi * std::atan (wref / (2.0 * refRate)); // the band's frequency in Hz (48 kHz design)
  147. const double fs = std::min (f0, 0.45 * sr);
  148. return (2.0 * sr * std::tan (pi * fs / sr)) / (2.0 * refRate * std::tan (pi * fs / refRate)) * (fs / f0);
  149. }
  150. } // namespace
  151. double qFromDial (double v) noexcept
  152. {
  153. v = std::clamp (v, 0.0, 1.0) * 20.0;
  154. const int i = std::min ((int) v, 19);
  155. return qText[i] + (v - i) * (qText[i + 1] - qText[i]);
  156. }
  157. double dialFromQ (double q) noexcept
  158. {
  159. q = std::clamp (q, (double) qText[20], (double) qText[0]);
  160. for (int i = 0; i < 20; ++i)
  161. if (q <= qText[i] && q >= qText[i + 1])
  162. return (i + (qText[i] - q) / (qText[i] - qText[i + 1])) / 20.0;
  163. return 1.0;
  164. }
  165. bool bandBiquad (int band, const Settings& s, double sampleRate, Biquad& out)
  166. {
  167. double n[3], d[2], wref = 0.0;
  168. if (! bandAnalog (band, s, n, d, wref))
  169. return false;
  170. const double a = rateScale (wref, sampleRate);
  171. n[1] *= a; n[2] *= a * a; d[0] *= a; d[1] *= a * a;
  172. bilinear (n, d, 2.0 * sampleRate, out);
  173. return true;
  174. }
  175. bool highPass (const Settings& s, double sampleRate, Biquad& first, Biquad& second)
  176. {
  177. if (s.hpHz < 16.5)
  178. return false;
  179. // 3rd-order Butterworth in the analog domain (a real pole and a Q = 1 pair at the same frequency), measured
  180. double w = interp (hpText, hpW, std::size (hpText), roundTo (std::clamp (s.hpHz, 17.0, 350.0), 1.0));
  181. w *= rateScale (w, sampleRate);
  182. const double K = 2.0 * sampleRate;
  183. // first order s / (s + w)
  184. first.set (K, -K, 0.0, K + w, w - K, 0.0);
  185. const double n[3] = { 1.0, 0.0, 0.0 }, dd[2] = { w, w * w };
  186. bilinear (n, dd, K, second);
  187. return true;
  188. }
  189. bool lowPass (const Settings& s, double sampleRate, Biquad& out)
  190. {
  191. if (s.lpKHz <= 0.0)
  192. return false;
  193. const double f = roundTo (std::clamp (s.lpKHz, 3.0, 19.5), 0.1) * 1000.0;
  194. // the table holds (n2, n1, n0, d1, d0) per displayed frequency
  195. constexpr auto count = std::size (lpText);
  196. std::size_t i = 0;
  197. while (i < count - 2 && f > lpText[i + 1])
  198. ++i;
  199. const double t = std::clamp ((f - lpText[i]) / (lpText[i + 1] - lpText[i]), 0.0, 1.0);
  200. double c[5];
  201. for (int k = 0; k < 5; ++k)
  202. c[k] = (1 - t) * lpCoef[i * 5 + k] + t * lpCoef[(i + 1) * 5 + k];
  203. double n[3] = { c[0], c[1], c[2] }, d[2] = { c[3], c[4] };
  204. const double a = rateScale (std::sqrt (std::max (d[1], 1.0)), sampleRate);
  205. n[1] *= a; n[2] *= a * a; d[0] *= a; d[1] *= a * a;
  206. bilinear (n, d, 2.0 * sampleRate, out);
  207. return true;
  208. }
  209. double responseDb (const Settings& s, double sampleRate, double hz)
  210. {
  211. const double w = 2.0 * pi * hz / sampleRate;
  212. double m = 1.0;
  213. Biquad a, b;
  214. if (highPass (s, sampleRate, a, b))
  215. m *= biquadMagnitude (a, w) * biquadMagnitude (b, w);
  216. if (lowPass (s, sampleRate, a))
  217. m *= biquadMagnitude (a, w);
  218. if (s.eqOn)
  219. for (int band = 0; band < 4; ++band)
  220. if (bandBiquad (band, s, sampleRate, a))
  221. m *= biquadMagnitude (a, w);
  222. return gainToDb (m);
  223. }
  224. // ---- dynamics ----
  225. namespace
  226. {
  227. #include "core/VoiceMatchDynamics.inc"
  228. double softplus (double o, double k) noexcept { return o > 30.0 * k ? o : k * std::log1p (std::exp (o / k)); }
  229. } // namespace
  230. double compStaticGainDb (const Settings& s, double sineDbfs)
  231. {
  232. // iterate the feedback loop to its fixed point for a steady sine (peak detector on the output)
  233. const auto law = compLaw (s);
  234. double gr = 0.0;
  235. for (int it = 0; it < 200; ++it)
  236. {
  237. const double o = sineDbfs - gr - (s.compThreshold + law.thresholdOffset);
  238. const double target = law.slope * softplus (o, law.knee);
  239. gr += 0.3 * (target - gr);
  240. }
  241. return law.makeup - gr;
  242. }
  243. double compMakeupDb (const Settings& s) noexcept
  244. {
  245. return s.compRatio > 1.0 ? compLaw (s).makeup : 0.0;
  246. }
  247. void Channel::prepare (double sampleRate) noexcept
  248. {
  249. sr = sampleRate;
  250. designedOnce = false;
  251. reset();
  252. }
  253. void Channel::reset() noexcept
  254. {
  255. hp1.reset(); hp2.reset(); lp.reset();
  256. for (auto& b : bands)
  257. b.reset();
  258. env = gr = gr1 = yl = yr = genv = ggr = 0.0;
  259. gateOpen = false;
  260. }
  261. void Channel::design (const Settings& s) noexcept
  262. {
  263. const auto eq = [] (const Settings& a, const Settings& b) {
  264. return a.hpHz == b.hpHz && a.lpKHz == b.lpKHz && a.lfGain == b.lfGain && a.lfHz == b.lfHz && a.lfBell == b.lfBell
  265. && a.lmfGain == b.lmfGain && a.lmfKHz == b.lmfKHz && a.lmfQ == b.lmfQ && a.hmfGain == b.hmfGain && a.hmfKHz == b.hmfKHz
  266. && a.hmfQ == b.hmfQ && a.hfGain == b.hfGain && a.hfKHz == b.hfKHz && a.hfBell == b.hfBell;
  267. };
  268. if (designedOnce && eq (s, designed))
  269. return;
  270. designed = s;
  271. designedOnce = true;
  272. Biquad a, b;
  273. hpOn = highPass (s, sr, a, b);
  274. if (hpOn) { hp1.b0 = a.b0; hp1.b1 = a.b1; hp1.b2 = a.b2; hp1.a1 = a.a1; hp1.a2 = a.a2; hp2.b0 = b.b0; hp2.b1 = b.b1; hp2.b2 = b.b2; hp2.a1 = b.a1; hp2.a2 = b.a2; }
  275. lpOn = lowPass (s, sr, a);
  276. if (lpOn) { lp.b0 = a.b0; lp.b1 = a.b1; lp.b2 = a.b2; lp.a1 = a.a1; lp.a2 = a.a2; }
  277. for (int i = 0; i < 4; ++i)
  278. {
  279. bandOn[i] = bandBiquad (i, s, sr, a);
  280. if (bandOn[i]) { bands[i].b0 = a.b0; bands[i].b1 = a.b1; bands[i].b2 = a.b2; bands[i].a1 = a.a1; bands[i].a2 = a.a2; }
  281. }
  282. }
  283. void Channel::process (float* l, float* r, int n, const Settings& s) noexcept
  284. {
  285. design (s);
  286. const double inG = dbToGain (roundTo (s.inputDb, 0.1)), outG = dbToGain (roundTo (s.outputDb, 0.1)) * (s.phase ? -1.0 : 1.0);
  287. const auto law = compLaw (s);
  288. const bool compOn = s.dynOn && s.compRatio > 1.0005;
  289. const double cA = coefMs (s.compFast ? law.attackFastMs : law.attackSlowMs, sr), cR = coefMs (law.releaseMs, sr), cR1 = coefMs (law.release1Ms, sr);
  290. const double frac = law.release1Fraction;
  291. const double dA = coefMs (law.detectorAttackMs, sr), dR = coefMs (law.detectorReleaseMs, sr);
  292. const double makeup = s.dynOn ? dbToGain (law.makeup) : 1.0;
  293. const auto gl = gateLaw (s);
  294. const bool gateOn = s.dynOn && gl.range > 0.05;
  295. const double gA = coefMs (gl.attackMs, sr), gR = coefMs (gl.releaseMs, sr), gD = coefMs (gl.detectorReleaseMs, sr);
  296. float maxComp = 0.0f, maxGate = 0.0f;
  297. auto filters = [this] (double& a, double& b) {
  298. if (hpOn)
  299. {
  300. a = hp2.process (hp1.process ((float) a, 0), 0);
  301. b = hp2.process (hp1.process ((float) b, 1), 1);
  302. }
  303. if (lpOn)
  304. {
  305. a = lp.process ((float) a, 0);
  306. b = lp.process ((float) b, 1);
  307. }
  308. };
  309. auto eq = [this] (double& a, double& b) {
  310. for (int i = 0; i < 4; ++i)
  311. if (bandOn[i])
  312. {
  313. a = bands[i].process ((float) a, 0);
  314. b = bands[i].process ((float) b, 1);
  315. }
  316. };
  317. for (int i = 0; i < n; ++i)
  318. {
  319. double a = l[i] * inG, b = r[i] * inG;
  320. if (s.filtersBeforeDynamics || s.dynamicsAfterEq)
  321. filters (a, b);
  322. if (s.dynamicsAfterEq && s.eqOn)
  323. eq (a, b);
  324. if (gateOn)
  325. {
  326. const double lev = std::max (std::abs (a), std::abs (b));
  327. genv = lev > genv ? lev : genv + gD * (lev - genv);
  328. const double levDb = gainToDb (genv);
  329. double target;
  330. if (gl.gate)
  331. {
  332. if (levDb >= gl.threshold) gateOpen = true;
  333. else if (levDb < gl.threshold - gl.hysteresis) gateOpen = false;
  334. target = gateOpen ? 0.0 : gl.range;
  335. }
  336. else
  337. {
  338. const double u = gl.threshold - levDb;
  339. target = std::min (gl.range, gl.slope * (u > 30.0 * gl.knee ? u : gl.knee * std::log1p (std::exp (u / gl.knee))));
  340. }
  341. ggr += (target < ggr ? gA : gR) * (target - ggr); // less reduction = opening (attack), more = closing (release)
  342. const double g = dbToGain (-ggr);
  343. a *= g;
  344. b *= g;
  345. maxGate = std::max (maxGate, (float) ggr);
  346. }
  347. if (compOn)
  348. {
  349. // feedback compressor: the detector hears the compressor's own output (the previous sample)
  350. const double sc = std::max (std::abs (yl), std::abs (yr));
  351. env += (sc > env ? dA : dR) * (sc - env);
  352. const double o = gainToDb (env) - (s.compThreshold + law.thresholdOffset);
  353. const double target = law.slope * softplus (o, law.knee);
  354. gr1 += (target > gr1 ? cA : cR1) * (target - gr1);
  355. gr += (target > gr ? cA : cR) * (target - gr);
  356. const double g = dbToGain (-(frac * gr1 + (1.0 - frac) * gr));
  357. yl = a * g;
  358. yr = b * g;
  359. a = yl;
  360. b = yr;
  361. maxComp = std::max (maxComp, (float) (frac * gr1 + (1.0 - frac) * gr));
  362. }
  363. a *= makeup;
  364. b *= makeup;
  365. if (! s.dynamicsAfterEq)
  366. {
  367. if (! s.filtersBeforeDynamics)
  368. filters (a, b);
  369. if (s.eqOn)
  370. eq (a, b);
  371. }
  372. l[i] = (float) (a * outG);
  373. r[i] = (float) (b * outG);
  374. }
  375. lastComp = maxComp;
  376. lastGate = maxGate;
  377. }
  378. } // namespace echannel
  379. // ================================================================== split-band de-esser
  380. // [EXEC] Fitted on the official DeEsser trial (her state and sweeps of threshold -40 .. -5 dB and frequency 2.5 .. 14.4
  381. // kHz; 6 kHz sine stairs, pink noise, her takes; tools/fxmeasure/py/vm123/decfg.py): the side chain is a 4th-order
  382. // high-pass (two Butterworth sections) or a band-pass at the dial's frequency, an energy (power) detector with a
  383. // 0.3 ms attack and a 12 ms release, a 7.1 : 1 soft-knee (1.26 dB) gain computer 0.6 dB below the dial; Split
  384. // attenuates only what lies above a first-order crossover at 0.33 x the dial's frequency (so the attenuation of a
  385. // sibilant floors near -11 dB: no range control), Wideband the whole signal. Her state: null -38 / -50 / -44 dB.
  386. namespace deesser
  387. {
  388. namespace
  389. {
  390. constexpr double thrOffset = -0.6009, thrSlope = -0.0097, ratio = 7.1171, knee = 1.2597, attackMs = 0.3027, releaseMs = 12.1503;
  391. constexpr double splitK = 0.3306, splitExp = 0.0491, scK = 1.0120, scExp = -0.0353, bpQ = 1.2988, bpOffset = 3.9011;
  392. void rbj (Biquad& b, int type, double f, double q, double sr) noexcept
  393. {
  394. const double w = 2.0 * pi * std::min (f, sr * 0.49) / sr, cw = std::cos (w), al = std::sin (w) / (2.0 * q);
  395. if (type == 0) b.set ((1 + cw) / 2, -(1 + cw), (1 + cw) / 2, 1 + al, -2 * cw, 1 - al); // high-pass
  396. else b.set (al, 0.0, -al, 1 + al, -2 * cw, 1 - al); // band-pass (0 dB peak)
  397. }
  398. } // namespace
  399. void DeEsser::prepare (double sampleRate) noexcept
  400. {
  401. sr = sampleRate;
  402. designedHz = -1.0;
  403. reset();
  404. }
  405. void DeEsser::reset() noexcept
  406. {
  407. sc1.reset();
  408. sc2.reset();
  409. lpX[0] = lpX[1] = lpY[0] = lpY[1] = 0.0;
  410. env = gr = 0.0;
  411. }
  412. void DeEsser::design (const Settings& s) noexcept
  413. {
  414. const double f = std::clamp (s.hz, 2000.0, 16000.0);
  415. if (f == designedHz && s.bandPass == designedBp)
  416. return;
  417. designedHz = f;
  418. designedBp = s.bandPass;
  419. const double rel = f / 5506.0;
  420. const double fsc = f * scK * std::pow (rel, scExp);
  421. rbj (sc1, s.bandPass ? 1 : 0, fsc, s.bandPass ? bpQ : 0.70710678, sr);
  422. sc2.b0 = sc1.b0; sc2.b1 = sc1.b1; sc2.b2 = sc1.b2; sc2.a1 = sc1.a1; sc2.a2 = sc1.a2;
  423. const double k = std::tan (pi * std::min (f * splitK * std::pow (rel, splitExp), 0.45 * sr) / sr);
  424. lpB = k / (1.0 + k);
  425. lpA = (k - 1.0) / (k + 1.0);
  426. }
  427. void DeEsser::process (float* l, float* r, int n, const Settings& s) noexcept
  428. {
  429. design (s);
  430. const double T = std::clamp (s.thresholdDb, -80.0, 0.0);
  431. const double thr = T + thrOffset + thrSlope * (T + 24.2) + (s.bandPass ? bpOffset : 0.0);
  432. const double aA = coefMs (attackMs, sr), aR = coefMs (releaseMs, sr), out = dbToGain (s.outputDb);
  433. double maxGr = 0.0, maxO = -200.0;
  434. for (int i = 0; i < n; ++i)
  435. {
  436. const double a = sc2.process (sc1.process (l[i], 0), 0), b = sc2.process (sc1.process (r[i], 1), 1);
  437. const double p = 0.5 * (a * a + b * b);
  438. env += (p > env ? aA : aR) * (p - env);
  439. const double o = 10.0 * std::log10 (std::max (env, 1e-24)) - thr;
  440. maxO = std::max (maxO, o);
  441. gr = (1.0 - 1.0 / ratio) * (o > 30.0 * knee ? o : knee * std::log1p (std::exp (o / knee)));
  442. const double g = dbToGain (-gr);
  443. maxGr = std::max (maxGr, gr);
  444. if (s.listen)
  445. {
  446. l[i] = (float) (a * out);
  447. r[i] = (float) (b * out);
  448. continue;
  449. }
  450. double x[2] = { l[i], r[i] };
  451. for (int c = 0; c < 2; ++c)
  452. {
  453. if (s.wideband)
  454. x[c] *= g;
  455. else
  456. {
  457. const double lo = lpB * (x[c] + lpX[c]) - lpA * lpY[c];
  458. lpX[c] = x[c];
  459. lpY[c] = lo;
  460. x[c] = lo + (x[c] - lo) * g;
  461. }
  462. }
  463. l[i] = (float) (x[0] * out);
  464. r[i] = (float) (x[1] * out);
  465. }
  466. last = (float) maxGr;
  467. lastDet = (float) (maxO + T); // where the energy sits against the threshold dial: reduction starts at T
  468. }
  469. } // namespace deesser
  470. // ================================================================== electro-optical leveler
  471. // [EXEC] Fitted on the official CLA-2A trial (tools/fxmeasure/py/vm123: sine stairs at 100 Hz … 10 kHz, 1 kHz bursts,
  472. // a 1 kHz tone with a quiet pink probe at five levels, pink noise, her takes; dynfit "cla5"). A feedback leveler: the
  473. // side chain hears the cell's output through a peaking emphasis (+9.4 dB at 9 kHz); the cell's conductance C follows
  474. // the light — C = ((level - Yt) / Y0)^gamma above a threshold — with an attack in the log domain that speeds up with C,
  475. // a hyperbolic release (dC/dt = -a C^n: about half the reduction back in 60 ms, the rest over seconds) and a slow
  476. // second conductance; the audio sees g = 1 / (1 + C) with a high-frequency bypass that opens under reduction (the
  477. // measured tilt: up to +7 dB at 20 kHz), then the gain dial's make-up, a little 2nd / 3rd harmonic, and the unit's
  478. // idle response (a 4 Hz high-pass and a 0.7 dB dip around 12 kHz, measured).
  479. namespace opto
  480. {
  481. namespace
  482. {
  483. #include "core/VoiceMatchOpto.inc"
  484. } // namespace
  485. void Leveler::prepare (double sampleRate) noexcept
  486. {
  487. sr = sampleRate;
  488. reset();
  489. }
  490. void Leveler::reset() noexcept
  491. {
  492. cf = cs = el = mem = 0.0;
  493. for (int c = 0; c < 2; ++c)
  494. {
  495. yc[c] = fx1[c] = fy1[c] = 0.0;
  496. for (int k = 0; k < 4; ++k)
  497. tx[c][k] = ty[c][k] = 0.0;
  498. }
  499. sc.reset();
  500. }
  501. void Leveler::process (float* l, float* r, int n, const Settings& s) noexcept
  502. {
  503. const double dt = 1.0 / sr;
  504. if (scDesignedRate != sr)
  505. {
  506. scDesignedRate = sr;
  507. const double A = std::pow (10.0, scDb / 40.0), w = 2.0 * pi * std::min (scHz, 0.45 * sr) / sr, al = std::sin (w) / (2.0 * scQ), cw = std::cos (w);
  508. sc.set (1 + al * A, -2 * cw, 1 - al * A, 1 + al / A, -2 * cw, 1 - al / A);
  509. }
  510. const double shift = sensitivityDb (s.peakReduction, s.hiFreq) + (s.limit ? limitShiftDb : 0.0);
  511. const double Y0 = dbToGain (y0Db + shift), Yt = dbToGain (ytDb + shift), gam = s.limit ? limitGamma : gamma;
  512. const double mk = dbToGain (makeupDb (s.gain) + idleMakeupDb);
  513. const double cA = 1.0 - std::exp (-dt * 1000.0 / attackSlowMs), mUp = 1.0 - std::exp (-dt * 1000.0 / memUpMs), mDn = 1.0 - std::exp (-dt * 1000.0 / memDownMs);
  514. const double K = 2.0 * sr;
  515. // the idle response measured at 48 kHz; other rates take its bilinear analog prototype (approximate)
  516. const double* tb = idleB;
  517. const double* ta = idleA;
  518. double maxGr = 0.0;
  519. for (int i = 0; i < n; ++i)
  520. {
  521. const double e0 = sc.process ((float) yc[0], 0), e1 = sc.process ((float) yc[1], 1);
  522. el = std::max (std::abs (e0), std::abs (e1)); // the light follows the drive within the sample (fitted)
  523. const double ct = (el > Yt ? std::pow ((el - Yt) / Y0, gam) : 0.0) * (1.0 + memGain * mem);
  524. const double ctf = (1.0 - slowShare) * ct, cts = slowShare * ct;
  525. if (ctf > cf)
  526. {
  527. double cd = std::log1p (cf);
  528. cd += (std::log1p (ctf) - cd) * (1.0 - std::exp (-dt * 1000.0 * std::pow (1.0 + cf, attackBeta) / attackMs));
  529. cf = std::expm1 (cd);
  530. }
  531. else
  532. cf = std::max (ctf, cf - dt * releaseA * std::pow (cf, releaseN));
  533. if (cts > cs)
  534. cs += (cts - cs) * cA;
  535. else
  536. cs = std::max (cts, cs - dt * releaseA2 * std::pow (cs, releaseN2));
  537. const double g = 1.0 / (1.0 + cf + cs);
  538. mem += ((1.0 - g) > mem ? mUp : mDn) * ((1.0 - g) - mem);
  539. const double gp = g + (1.0 - g) * (tiltC0 - tiltC1 * g);
  540. const double wz = 2.0 * pi * tiltHz * (1.0 + g);
  541. const double a0 = 1.0 + K * gp / wz, b0 = g * (1.0 + K / wz) / a0, b1 = g * (1.0 - K / wz) / a0, a1 = (1.0 - K * gp / wz) / a0;
  542. float* ch[2] = { &l[i], &r[i] };
  543. for (int c = 0; c < 2; ++c)
  544. {
  545. const double x = *ch[c];
  546. const double y = b0 * x + b1 * fx1[c] - a1 * fy1[c];
  547. fx1[c] = x;
  548. fy1[c] = y;
  549. yc[c] = y;
  550. double o = y * mk;
  551. o = o + h2 * o * o + h3 * o * o * o;
  552. for (int j = 3; j > 0; --j) { tx[c][j] = tx[c][j - 1]; ty[c][j] = ty[c][j - 1]; }
  553. tx[c][0] = o;
  554. const double t = tb[0] * tx[c][0] + tb[1] * tx[c][1] + tb[2] * tx[c][2] + tb[3] * tx[c][3] - ta[1] * ty[c][1] - ta[2] * ty[c][2] - ta[3] * ty[c][3];
  555. ty[c][0] = t;
  556. *ch[c] = (float) t;
  557. }
  558. maxGr = std::max (maxGr, -gainToDb (g));
  559. }
  560. last = (float) maxGr;
  561. }
  562. } // namespace opto
  563. // ================================================================== program-dependent peak compressor
  564. // [EXEC] Fitted on the official Renaissance Compressor trial at her state (-15 dB, 2.95:1, 0.5 ms, 160 ms, ARC, Warm,
  565. // Electro) on 1 kHz stairs, tone bursts, pink noise and her takes (dynfit "rc2"): a 64-sample (1.33 ms at 48 kHz)
  566. // delay of the audio against the detector, a linked peak detector (9 ms release), a 21.7 dB-wide soft knee 2.8 dB
  567. // under the threshold, a fast gain path (attack 2.1 x the knob, release 25 ms) and a slow "program" path that
  568. // charges in ~220 ms and releases at a constant rate in linear gain (3.8 /s x 160 ms / the release knob) — so short
  569. // peaks recover in milliseconds and long phrases slowly (its ARC / Electro behaviour at her state). Her takes:
  570. // null -26 dB (stairs and bursts -40 … -50 dB). [model] The knob laws away from her state, ARC / manual, Opto and
  571. // Smooth are not separated yet (REA_rodada123 §3).
  572. namespace progcomp
  573. {
  574. namespace
  575. {
  576. constexpr double thrOffset = -2.8056, kneeDb = 21.7431, ratioScale = 1.3191, attackScale = 2.1395, fastReleaseMs = 24.5151;
  577. constexpr double slowChargeMs = 222.5718, slowRate = 3.8413, slowShape = -1.1528, detectorReleaseMs = 9.2761;
  578. } // namespace
  579. void Compressor::prepare (double sampleRate) noexcept
  580. {
  581. sr = sampleRate;
  582. delayLen = std::clamp ((int) std::lround (lookahead * sr / 48000.0), 1, (int) dl.size() - 1);
  583. reset();
  584. }
  585. void Compressor::reset() noexcept
  586. {
  587. dl.fill (0.0f);
  588. dr.fill (0.0f);
  589. pos = 0;
  590. env = grf = grs = 0.0;
  591. }
  592. void Compressor::process (float* l, float* r, int n, const Settings& s) noexcept
  593. {
  594. const double T = s.thresholdDb + thrOffset, R = 1.0 + (std::max (1.0, s.ratio) - 1.0) * (s.smooth ? 1.0 : ratioScale), W = kneeDb;
  595. const double aA = coefMs (std::max (0.01, s.attackMs) * attackScale, sr), sC = coefMs (slowChargeMs, sr);
  596. const double fR = coefMs (s.manual ? std::max (1.0, s.releaseMs) : fastReleaseMs, sr);
  597. const double shape = s.opto ? -slowShape : slowShape;
  598. const double dR = coefMs (detectorReleaseMs, sr), relK = 160.0 / std::max (1.0, s.releaseMs), dt = 1.0 / sr;
  599. const double makeup = s.gainDb, trim = dbToGain (s.trimDb);
  600. const int N = (int) dl.size();
  601. double maxGr = 0.0;
  602. for (int i = 0; i < n; ++i)
  603. {
  604. const double a = std::max (std::abs ((double) l[i]), std::abs ((double) r[i]));
  605. env = a > env ? a : env + dR * (a - env);
  606. const double x = gainToDb (env), o = x - T;
  607. double y;
  608. if (2.0 * o < -W) y = x;
  609. else if (2.0 * std::abs (o) <= W) y = x + (1.0 / R - 1.0) * (o + W / 2.0) * (o + W / 2.0) / (2.0 * W);
  610. else y = T + o / R;
  611. const double target = std::max (0.0, x - y);
  612. grf += (target > grf ? aA : fR) * (target - grf);
  613. if (s.manual)
  614. grs = 0.0;
  615. else if (grf > grs)
  616. grs += sC * (grf - grs);
  617. else
  618. {
  619. double gs = dbToGain (-grs);
  620. gs += slowRate * relK * (1.0 + shape * (1.0 - gs)) * dt;
  621. grs = gs >= 1.0 ? 0.0 : -gainToDb (gs);
  622. grs = std::max (grs, grf);
  623. }
  624. const double gr = std::max (grf, grs);
  625. maxGr = std::max (maxGr, gr);
  626. const double g = (dbToGain (makeup - gr) * s.mix + (1.0 - s.mix)) * trim;
  627. dl[(std::size_t) pos] = l[i];
  628. dr[(std::size_t) pos] = r[i];
  629. int rd = pos - delayLen;
  630. if (rd < 0) rd += N;
  631. l[i] = (float) (dl[(std::size_t) rd] * g);
  632. r[i] = (float) (dr[(std::size_t) rd] * g);
  633. if (++pos == N) pos = 0;
  634. }
  635. last = (float) maxGr;
  636. }
  637. } // namespace progcomp
  638. } // namespace lynx::vmatch