FacetEq.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. #include "core/FacetEq.h"
  2. #include <algorithm>
  3. #include <atomic>
  4. #include <cmath>
  5. #include <complex>
  6. #include <cstdio>
  7. #include <vector>
  8. namespace lynx::facet
  9. {
  10. namespace
  11. {
  12. constexpr double pi = 3.14159265358979323846;
  13. using cd = std::complex<double>;
  14. // Analog section in normalized frequency (s = jω/ω0): (n2 s² + n1 s + n0) / (d2 s² + d1 s + d0)
  15. struct Analog { double n2 = 0, n1 = 0, n0 = 1, d2 = 0, d1 = 0, d0 = 1; };
  16. cd evalAnalog (const Analog& a, double w) noexcept // w = ω/ω0
  17. {
  18. const cd s (0.0, w);
  19. return (a.n2 * s * s + a.n1 * s + a.n0) / (a.d2 * s * s + a.d1 * s + a.d0);
  20. }
  21. double mag2 (const Analog& a, double w) noexcept { return std::norm (evalAnalog (a, w)); }
  22. // Magnitude-matched digital section for an analog section at w0 = 2π f0 / fs. `ok` reports whether the numerator
  23. // was realisable as asked (false = the magnitude at the match point had to be clamped).
  24. Section matched (const Analog& a, double w0, bool& ok) noexcept
  25. {
  26. Section s;
  27. ok = true;
  28. if (a.n1 < 0.0 && a.n2 == a.d2 && a.n0 == a.d0 && a.d2 != 0.0)
  29. {
  30. // all pass (round 135): no magnitude to match — the bilinear all-pass at the band frequency, same Q
  31. const double qb = 1.0 / a.d1, alpha = std::sin (std::min (w0, 0.98 * pi)) / (2.0 * qb), c = std::cos (std::min (w0, 0.98 * pi));
  32. const double a0 = 1.0 + alpha;
  33. s.b0 = (1.0 - alpha) / a0; s.b1 = -2.0 * c / a0; s.b2 = 1.0;
  34. s.a1 = -2.0 * c / a0; s.a2 = (1.0 - alpha) / a0;
  35. return s;
  36. }
  37. const double nyq = pi / w0; // digital Nyquist on the normalized analog axis
  38. if (a.d2 == 0.0)
  39. {
  40. // first order: (n1 s + n0) / (d1 s + d0); pole by impulse invariance, zero matched at DC and Nyquist
  41. const double wp = std::min (a.d0 / a.d1 * w0, 0.999 * pi);
  42. const double p = std::exp (-wp);
  43. const double h0 = std::sqrt (mag2 (a, 0.0)), hn = std::sqrt (mag2 (a, nyq));
  44. const double sum = h0 * (1.0 - p), diff = hn * (1.0 + p);
  45. s.b0 = 0.5 * (sum + diff);
  46. s.b1 = 0.5 * (sum - diff);
  47. s.a1 = -p;
  48. return s;
  49. }
  50. // poles of d2 s² + d1 s + d0: natural frequency wp, damping zeta
  51. const double wpn = std::sqrt (a.d0 / a.d2);
  52. const double zeta = a.d1 / (2.0 * std::sqrt (a.d0 * a.d2));
  53. const double wp = std::min (wpn * w0, 0.999 * pi);
  54. const double e = std::exp (-zeta * wp);
  55. s.a2 = e * e;
  56. s.a1 = zeta <= 1.0 ? -2.0 * e * std::cos (std::sqrt (1.0 - zeta * zeta) * wp)
  57. : -2.0 * e * std::cosh (std::sqrt (zeta * zeta - 1.0) * wp);
  58. // squared magnitude of a digital polynomial as A0 φ0 + A1 φ1 + A2 φ2 (φ0 = cos²(w/2), φ1 = sin²(w/2), φ2 = 4 φ0 φ1)
  59. const double A0 = (1.0 + s.a1 + s.a2) * (1.0 + s.a1 + s.a2);
  60. const double A1 = (1.0 - s.a1 + s.a2) * (1.0 - s.a1 + s.a2);
  61. const double A2 = -4.0 * s.a2;
  62. auto den = [&] (double w) {
  63. const double p1 = std::sin (w * 0.5) * std::sin (w * 0.5), p0 = 1.0 - p1;
  64. return A0 * p0 + A1 * p1 + A2 * 4.0 * p0 * p1;
  65. };
  66. const double wm = std::min (w0, 0.9 * pi);
  67. const double p1 = std::sin (wm * 0.5) * std::sin (wm * 0.5), p0 = 1.0 - p1;
  68. const double target = mag2 (a, wm / w0) * den (wm);
  69. if (a.n1 == 0.0 && a.n0 == 0.0)
  70. {
  71. // high-pass: double zero at DC, k (1 − z⁻¹)², matched at the band frequency
  72. const double k = std::sqrt (target) / (4.0 * p1);
  73. s.b0 = k; s.b1 = -2.0 * k; s.b2 = k;
  74. return s;
  75. }
  76. if (a.n1 == 0.0 && a.n2 != 0.0 && a.n0 != 0.0)
  77. {
  78. // notch: zeros on the unit circle at the notch frequency, gain matched at DC
  79. const double wz = std::min (std::sqrt (a.n0 / a.n2) * w0, 0.999 * pi);
  80. const double k = std::sqrt (mag2 (a, 0.0)) * (1.0 + s.a1 + s.a2) / (2.0 - 2.0 * std::cos (wz));
  81. s.b0 = k; s.b1 = -2.0 * k * std::cos (wz); s.b2 = k;
  82. return s;
  83. }
  84. // numerator matched at DC, Nyquist and the match point (the band frequency, kept inside the band)
  85. const double B0 = A0 * mag2 (a, 0.0);
  86. const double B1 = A1 * mag2 (a, nyq);
  87. double B2 = (target - B0 * p0 - B1 * p1) / (4.0 * p0 * p1);
  88. const double sb0 = std::sqrt (std::max (0.0, B0)), sb1 = std::sqrt (std::max (0.0, B1));
  89. const double W = 0.5 * (sb0 + sb1);
  90. if (B2 < -W * W) { B2 = -W * W; ok = false; }
  91. s.b0 = 0.5 * (W + std::sqrt (W * W + B2));
  92. s.b1 = 0.5 * (sb0 - sb1);
  93. s.b2 = s.b0 != 0.0 ? -B2 / (4.0 * s.b0) : 0.0;
  94. return s;
  95. }
  96. // matched design; when the numerator cannot be realised (cuts near Nyquist), the reciprocal section is designed
  97. // instead and inverted (its zeros become the poles)
  98. Section matched (const Analog& a, double w0) noexcept
  99. {
  100. bool ok = true;
  101. const auto s = matched (a, w0, ok);
  102. if (ok || a.d2 == 0.0 || a.n2 == 0.0 || a.n0 == 0.0)
  103. return s;
  104. const Analog inv { a.d2, a.d1, a.d0, a.n2, a.n1, a.n0 };
  105. bool ok2 = true;
  106. const auto r = matched (inv, w0, ok2);
  107. if (! ok2 || r.b0 == 0.0)
  108. return s;
  109. Section out;
  110. out.b0 = 1.0 / r.b0; out.b1 = r.a1 / r.b0; out.b2 = r.a2 / r.b0;
  111. out.a1 = r.b1 / r.b0; out.a2 = r.b2 / r.b0;
  112. return out;
  113. }
  114. double bandQ (const EffectParams& p, int b) noexcept { return q (p[(std::size_t) param (b, 3)]); }
  115. // Butterworth section Qs of an order-n filter, ascending
  116. int butterworthQs (int n, double* qs) noexcept
  117. {
  118. const int m = n / 2;
  119. for (int k = 0; k < m; ++k)
  120. qs[k] = 1.0 / (2.0 * std::sin ((2 * k + 1) * pi / (2.0 * n)));
  121. std::sort (qs, qs + m);
  122. return m;
  123. }
  124. // analog sections of one band (normalized to the band frequency); returns the count
  125. int analogSections (const EffectParams& p, int b, Analog* out, double extraDb = 0.0, bool keepFlat = false) noexcept
  126. {
  127. if (! bandPower (p, b)) return 0; // a band switched off (round 128) keeps its settings and does nothing
  128. const auto sh = shape (p[(std::size_t) param (b, 0)]);
  129. const double scale = gainScale (p[(std::size_t) scaleParam]);
  130. const double g = (gainDb (p[(std::size_t) param (b, 2)]) + extraDb) * scale;
  131. const double Q = bandQ (p, b);
  132. const int slope = slopeDb (p[(std::size_t) param (b, 4)]);
  133. switch (sh)
  134. {
  135. case Shape::off: return 0;
  136. case Shape::bell:
  137. {
  138. // symmetric bell: (s² + s·A/Qb + 1) / (s² + s/(A·Qb) + 1), Qb = Q/√2 (measured convention)
  139. if (std::abs (g) < 1e-9 && ! keepFlat) return 0;
  140. const double A = std::pow (10.0, g / 40.0), qb = Q / std::sqrt (2.0);
  141. out[0] = { 1.0, A / qb, 1.0, 1.0, 1.0 / (A * qb), 1.0 };
  142. return 1;
  143. }
  144. case Shape::lowShelf:
  145. case Shape::highShelf:
  146. case Shape::tiltShelf:
  147. {
  148. if (std::abs (g) < 1e-9 && ! keepFlat) return 0;
  149. const bool tilt = sh == Shape::tiltShelf;
  150. const double gg = tilt ? 2.0 * g : g;
  151. const double A = std::pow (10.0, gg / 40.0), sa = std::sqrt (A);
  152. const double norm = tilt ? std::pow (10.0, -g / 20.0) : 1.0;
  153. const bool high = sh != Shape::lowShelf;
  154. if (slope <= 6)
  155. {
  156. // first-order shelf, geometric half-gain point at the band frequency: high (A s + 1)/(s/A + 1), low (s + A)/(s + 1/A)
  157. if (high) out[0] = { 0.0, A * norm, norm, 0.0, 1.0 / A, 1.0 };
  158. else out[0] = { 0.0, norm, A * norm, 0.0, 1.0, 1.0 / A };
  159. return 1;
  160. }
  161. // second-order cookbook shelf, Qs = 0.7071·Q^0.4697 (measured), gain independent
  162. const double qs = std::sqrt (0.5) * std::pow (Q, 0.4697);
  163. if (high) out[0] = { A * A * norm, A * sa / qs * norm, A * norm, 1.0, sa / qs, A };
  164. else out[0] = { A * norm, A * sa / qs * norm, A * A * norm, A, sa / qs, 1.0 };
  165. return 1;
  166. }
  167. case Shape::lowCut:
  168. case Shape::highCut:
  169. {
  170. const bool hp = sh == Shape::lowCut;
  171. const int n = std::max (1, slope / 6);
  172. double qs[16];
  173. const int m = butterworthQs (n, qs);
  174. if (m > 0) qs[m - 1] *= Q / 1.0; // the highest-Q section carries the band's resonance (Q 1 = Butterworth)
  175. int c = 0;
  176. for (int k = 0; k < m; ++k)
  177. out[c++] = hp ? Analog { 1.0, 0.0, 0.0, 1.0, 1.0 / qs[k], 1.0 } : Analog { 0.0, 0.0, 1.0, 1.0, 1.0 / qs[k], 1.0 };
  178. if (n % 2)
  179. out[c++] = hp ? Analog { 0.0, 1.0, 0.0, 0.0, 1.0, 1.0 } : Analog { 0.0, 0.0, 1.0, 0.0, 1.0, 1.0 };
  180. return c;
  181. }
  182. case Shape::notch:
  183. {
  184. const double qb = Q / std::sqrt (2.0);
  185. out[0] = { 1.0, 0.0, 1.0, 1.0, 1.0 / qb, 1.0 };
  186. return 1;
  187. }
  188. case Shape::bandPass:
  189. {
  190. const double qb = Q / std::sqrt (2.0);
  191. out[0] = { 0.0, 1.0 / qb, 0.0, 1.0, 1.0 / qb, 1.0 };
  192. return 1;
  193. }
  194. case Shape::allPass: // round 135: (s² − s/Qb + 1) / (s² + s/Qb + 1)
  195. {
  196. const double qb = Q / std::sqrt (2.0);
  197. out[0] = { 1.0, -1.0 / qb, 1.0, 1.0, 1.0 / qb, 1.0 };
  198. return 1;
  199. }
  200. case Shape::flatTilt:
  201. {
  202. // round 135: eight first-order shelves 1.25 octaves apart (±5 octaves around the band frequency), each
  203. // a step of g / 4 dB: a constant slope of g / 5 dB per octave, 0 dB at the band frequency
  204. if (std::abs (g) < 1e-9 && ! keepFlat) return 0;
  205. const double A = std::pow (10.0, (g / 4.0) / 40.0);
  206. double at1 = 1.0;
  207. for (int k = 0; k < 8; ++k)
  208. {
  209. const double c = std::pow (2.0, (k - 3.5) * 1.25);
  210. out[k] = { 0.0, A / c, 1.0, 0.0, 1.0 / (A * c), 1.0 };
  211. at1 *= std::sqrt (mag2 (out[k], 1.0));
  212. }
  213. out[0].n1 /= at1;
  214. out[0].n0 /= at1;
  215. return 8;
  216. }
  217. }
  218. return 0;
  219. }
  220. cd evalDigital (const Section& s, double w) noexcept
  221. {
  222. const cd z1 = std::polar (1.0, -w), z2 = z1 * z1;
  223. return (s.b0 + s.b1 * z1 + s.b2 * z2) / (1.0 + s.a1 * z1 + s.a2 * z2);
  224. }
  225. // the FIR grid factor of a phase mode: 1 up to 48 kHz, 2 up to 96 kHz, 4 above
  226. int rateFactor (double sr) noexcept { return sr <= 50000.0 ? 1 : sr <= 100000.0 ? 2 : 4; }
  227. constexpr int naturalBlock = 128, naturalDelay = 192, linearBlock = 512, firTaps = 8192;
  228. // --- FFT and the partitioned convolver (the FIR phase modes) ------------------------------------------------------
  229. struct Fft
  230. {
  231. int n = 0;
  232. std::vector<cd> tw;
  233. std::vector<int> rev;
  234. void init (int size)
  235. {
  236. n = size;
  237. tw.resize ((std::size_t) n / 2);
  238. for (int k = 0; k < n / 2; ++k) tw[(std::size_t) k] = std::polar (1.0, -2.0 * pi * k / n);
  239. rev.resize ((std::size_t) n);
  240. int bits = 0;
  241. while ((1 << bits) < n) ++bits;
  242. for (int i = 0; i < n; ++i)
  243. {
  244. int r = 0;
  245. for (int b = 0; b < bits; ++b) r |= ((i >> b) & 1) << (bits - 1 - b);
  246. rev[(std::size_t) i] = r;
  247. }
  248. }
  249. // in place, unscaled (the inverse is n times too large)
  250. void run (cd* a, bool inverse) const noexcept
  251. {
  252. for (int i = 0; i < n; ++i)
  253. if (i < rev[(std::size_t) i]) std::swap (a[i], a[rev[(std::size_t) i]]);
  254. for (int len = 2; len <= n; len <<= 1)
  255. {
  256. const int half = len / 2, step = n / len;
  257. for (int i = 0; i < n; i += len)
  258. for (int j = 0; j < half; ++j)
  259. {
  260. const double wr = tw[(std::size_t) (j * step)].real(), wi = inverse ? -tw[(std::size_t) (j * step)].imag() : tw[(std::size_t) (j * step)].imag();
  261. const double xr = a[i + j + half].real(), xi = a[i + j + half].imag();
  262. const cd u = a[i + j], v (xr * wr - xi * wi, xr * wi + xi * wr);
  263. a[i + j] = u + v;
  264. a[i + j + half] = u - v;
  265. }
  266. }
  267. }
  268. };
  269. // Uniformly partitioned overlap-save convolution of a stereo signal (left + j·right) with a real FIR; block P, latency
  270. // P. Buffers are sized once for the largest configuration; a new kernel is cross-faded in over one block.
  271. class Convolver
  272. {
  273. public:
  274. void allocate (int maxTaps, int maxBlock)
  275. {
  276. fdl.assign ((std::size_t) maxTaps * 2, {});
  277. kern[0].assign ((std::size_t) maxTaps * 2, {});
  278. kern[1].assign ((std::size_t) maxTaps * 2, {});
  279. timeBuf.assign ((std::size_t) maxBlock * 2, {});
  280. acc.assign ((std::size_t) maxBlock * 2, {});
  281. acc2.assign ((std::size_t) maxBlock * 2, {});
  282. in.assign ((std::size_t) maxBlock, {});
  283. out.assign ((std::size_t) maxBlock, {});
  284. }
  285. // P must be a power of two whose FFT (2P) is `fft`
  286. void configure (const Fft& f, int blockSize, int taps) noexcept
  287. {
  288. fft = &f;
  289. P = blockSize;
  290. K = taps / blockSize;
  291. reset();
  292. }
  293. void reset() noexcept
  294. {
  295. std::fill (fdl.begin(), fdl.end(), cd {});
  296. std::fill (timeBuf.begin(), timeBuf.end(), cd {});
  297. std::fill (in.begin(), in.end(), cd {});
  298. std::fill (out.begin(), out.end(), cd {});
  299. pos = head = 0;
  300. pending = -1;
  301. }
  302. // a new FIR (K·P taps); the first one is used at once, later ones fade in over the next block
  303. void load (const double* h, bool immediate) noexcept
  304. {
  305. const int next = immediate ? active : 1 - active;
  306. auto* frame = acc2.data();
  307. for (int k = 0; k < K; ++k)
  308. {
  309. for (int i = 0; i < P; ++i) frame[i] = cd (h[k * P + i], 0.0);
  310. for (int i = P; i < 2 * P; ++i) frame[i] = {};
  311. fft->run (frame, false);
  312. std::copy (frame, frame + 2 * P, kern[(std::size_t) next].begin() + (std::ptrdiff_t) k * 2 * P);
  313. }
  314. pending = immediate ? -1 : next;
  315. }
  316. bool fading() const noexcept { return pending >= 0; }
  317. void step (float& l, float& r) noexcept
  318. {
  319. in[(std::size_t) pos] = cd (l, r);
  320. const auto y = out[(std::size_t) pos];
  321. l = (float) y.real();
  322. r = (float) y.imag();
  323. if (++pos == P) block();
  324. }
  325. private:
  326. void accumulate (int which, cd* dst) noexcept
  327. {
  328. const int n2 = 2 * P;
  329. std::fill (dst, dst + n2, cd {});
  330. const auto* kr = kern[(std::size_t) which].data();
  331. for (int k = 0; k < K; ++k)
  332. {
  333. const auto* x = fdl.data() + (std::ptrdiff_t) (((head - k + K) % K) * n2);
  334. const auto* hk = kr + (std::ptrdiff_t) k * n2;
  335. // plain products (std::complex's operator* checks for infinities, several times slower)
  336. for (int i = 0; i < n2; ++i)
  337. {
  338. const double xr = x[i].real(), xi = x[i].imag(), hr = hk[i].real(), hi = hk[i].imag();
  339. dst[i] += cd (xr * hr - xi * hi, xr * hi + xi * hr);
  340. }
  341. }
  342. fft->run (dst, true);
  343. }
  344. void block() noexcept
  345. {
  346. const int n2 = 2 * P;
  347. auto* tb = timeBuf.data();
  348. std::copy (tb + P, tb + n2, tb);
  349. std::copy (in.begin(), in.begin() + P, tb + P);
  350. auto* x = fdl.data() + (std::ptrdiff_t) head * n2;
  351. std::copy (tb, tb + n2, x);
  352. fft->run (x, false);
  353. const double scale = 1.0 / n2;
  354. accumulate (active, acc.data());
  355. if (pending >= 0)
  356. {
  357. accumulate (pending, acc2.data());
  358. for (int i = 0; i < P; ++i)
  359. {
  360. const double t = (i + 0.5) / P;
  361. out[(std::size_t) i] = (acc[(std::size_t) (P + i)] * (1.0 - t) + acc2[(std::size_t) (P + i)] * t) * scale;
  362. }
  363. active = pending;
  364. pending = -1;
  365. }
  366. else
  367. for (int i = 0; i < P; ++i) out[(std::size_t) i] = acc[(std::size_t) (P + i)] * scale;
  368. head = (head + 1) % K;
  369. pos = 0;
  370. }
  371. const Fft* fft = nullptr;
  372. int P = 128, K = 1, pos = 0, head = 0, active = 0, pending = -1;
  373. std::vector<cd> fdl, kern[2], timeBuf, acc, acc2, in, out;
  374. };
  375. // a biquad on doubles (detector / solo filters)
  376. struct Biquad
  377. {
  378. double b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0;
  379. double z1[2] {}, z2[2] {};
  380. double run (double x, int ch) noexcept
  381. {
  382. const double y = b0 * x + z1[ch];
  383. z1[ch] = b1 * x - a1 * y + z2[ch];
  384. z2[ch] = b2 * x - a2 * y;
  385. return y;
  386. }
  387. void clear() noexcept { z1[0] = z1[1] = z2[0] = z2[1] = 0.0; }
  388. };
  389. // the band's region: band pass at its frequency and Q (low pass / high pass for the shelves and cuts)
  390. void regionFilter (Biquad& f, const EffectParams& p, int b, double sr) noexcept
  391. {
  392. const auto sh = shape (p[(std::size_t) param (b, 0)]);
  393. const double f0 = std::min (hz (p[(std::size_t) param (b, 1)]), 0.45 * sr);
  394. const double w0 = 2.0 * pi * f0 / sr, cw = std::cos (w0), sw = std::sin (w0);
  395. const bool low = sh == Shape::lowShelf || sh == Shape::highCut;
  396. const bool high = sh == Shape::highShelf || sh == Shape::lowCut;
  397. const double Q = low || high ? std::sqrt (0.5) : std::clamp (q (p[(std::size_t) param (b, 3)]), 0.1, 40.0);
  398. const double alpha = sw / (2.0 * Q), a0 = 1.0 + alpha;
  399. if (low) { f.b0 = (1.0 - cw) * 0.5 / a0; f.b1 = (1.0 - cw) / a0; f.b2 = f.b0; }
  400. else if (high) { f.b0 = (1.0 + cw) * 0.5 / a0; f.b1 = -(1.0 + cw) / a0; f.b2 = f.b0; }
  401. else { f.b0 = alpha / a0; f.b1 = 0.0; f.b2 = -alpha / a0; }
  402. f.a1 = -2.0 * cw / a0;
  403. f.a2 = (1.0 - alpha) / a0;
  404. }
  405. class FacetEqEffect final : public Effect
  406. {
  407. public:
  408. explicit FacetEqEffect (const EffectParams* initial)
  409. {
  410. if (initial != nullptr) mode = phase ((*initial)[(std::size_t) phaseParam]);
  411. }
  412. void prepare (double sr) noexcept override
  413. {
  414. sampleRate = sr;
  415. const int fct = rateFactor (sr);
  416. taps = firTaps * fct;
  417. fftNatural.init (2 * naturalBlock * fct);
  418. fftLinear.init (2 * linearBlock * fct);
  419. fftDesign.init (taps);
  420. conv.allocate (taps, linearBlock * fct);
  421. spec.assign ((std::size_t) taps, {});
  422. fir.assign ((std::size_t) taps, 0.0);
  423. delayLen = latencyFor (Phase::linear, sr) + 1;
  424. delay[0].assign ((std::size_t) delayLen, 0.0f);
  425. delay[1].assign ((std::size_t) delayLen, 0.0f);
  426. cached.fill (-1.0f);
  427. configureMode (mode);
  428. reset();
  429. }
  430. void reset() noexcept override
  431. {
  432. for (auto& band : state)
  433. for (auto& st : band)
  434. st = {};
  435. for (auto& d : det) { d.filter.clear(); d.ms = 0.0; d.gain = 0.0; }
  436. solo.clear();
  437. conv.reset();
  438. firLoaded = false;
  439. for (auto& d : delay) std::fill (d.begin(), d.end(), 0.0f);
  440. delayPos = 0;
  441. dynUsed.fill (0.0);
  442. for (auto& m : meters) m.store (0.0f, std::memory_order_relaxed);
  443. }
  444. void setSidechain (const float* left, const float* right) noexcept override
  445. {
  446. sideL = left;
  447. sideR = right;
  448. sideGiven = true;
  449. }
  450. float controlOutput (int o) const noexcept override
  451. {
  452. return o >= 0 && o < bands ? meters[(std::size_t) o].load (std::memory_order_relaxed) / 60.0f : 0.0f;
  453. }
  454. int latencySamples() const noexcept override { return latencyNow.load (std::memory_order_relaxed); }
  455. void process (float* left, float* right, int n, const EffectParams& params, double) noexcept override
  456. {
  457. bool changed = false;
  458. for (int i = 0; i < paramCount; ++i)
  459. if (params[(std::size_t) i] != cached[(std::size_t) i]) { changed = true; break; }
  460. if (changed)
  461. update (params);
  462. // the detector: the slot's sidechain when asked for and routed (nullptr = a silent source), else the input
  463. const bool useSide = sideGiven && sidechainDetector (params[(std::size_t) detectorParam]);
  464. const float* dl = useSide ? sideL : left;
  465. const float* dr = useSide ? (sideR != nullptr ? sideR : sideL) : right;
  466. sideGiven = false;
  467. sideL = sideR = nullptr;
  468. constexpr int chunk = 32;
  469. for (int off = 0; off < n; off += chunk)
  470. {
  471. const int m = std::min (chunk, n - off);
  472. if (anyDynamic)
  473. detect (dl != nullptr ? dl + off : nullptr, dr != nullptr ? dr + off : nullptr, left + off, right + off, m, useSide);
  474. if (soloOn)
  475. {
  476. runSolo (left + off, right + off, m);
  477. continue;
  478. }
  479. if (mode == Phase::zeroLatency)
  480. {
  481. if (anyDynamic) redesignDynamic (false);
  482. runIir (left + off, right + off, m, false);
  483. }
  484. else
  485. {
  486. sinceDesign += m;
  487. if (! firLoaded || (sinceDesign >= updateEvery && ! conv.fading() && (firDirty || (anyDynamic && dynamicMoved()))))
  488. loadFir();
  489. for (int i = 0; i < m; ++i) conv.step (left[off + i], right[off + i]);
  490. // bands on one channel or on mid / side (round 128) are not in the stereo FIR: they run as the
  491. // zero-latency sections after it (minimum phase)
  492. if (anyPlaced)
  493. {
  494. if (anyDynamic) redesignDynamic (true);
  495. runIir (left + off, right + off, m, true);
  496. }
  497. }
  498. }
  499. if (outMidSide)
  500. for (int i = 0; i < n; ++i)
  501. {
  502. const float mid = 0.5f * (left[i] + right[i]) * outL, side = 0.5f * (left[i] - right[i]) * outR;
  503. left[i] = mid + side;
  504. right[i] = mid - side;
  505. }
  506. else if (outL != outR)
  507. for (int i = 0; i < n; ++i) { left[i] *= outL; right[i] *= outR; }
  508. else if (outL != 1.0f)
  509. for (int i = 0; i < n; ++i) { left[i] *= outL; right[i] *= outL; }
  510. if (characterNow > 0) // round 135: the character stage (Clean = untouched)
  511. for (int i = 0; i < n; ++i)
  512. {
  513. left[i] = characterSample (characterNow, left[i]);
  514. right[i] = characterSample (characterNow, right[i]);
  515. }
  516. for (int b = 0; b < bands; ++b) meters[(std::size_t) b].store ((float) det[(std::size_t) b].gain, std::memory_order_relaxed);
  517. }
  518. private:
  519. struct State { double z1[2] {}, z2[2] {}; };
  520. struct Detector
  521. {
  522. Biquad filter;
  523. double ms = 0.0, gain = 0.0, msCoef = 0.0, threshold = -20.0, range = 0.0;
  524. bool on = false;
  525. };
  526. void configureMode (Phase p) noexcept
  527. {
  528. mode = p;
  529. const int fct = rateFactor (sampleRate);
  530. if (p == Phase::natural) conv.configure (fftNatural, naturalBlock * fct, taps);
  531. else if (p == Phase::linear) conv.configure (fftLinear, linearBlock * fct, taps);
  532. updateEvery = std::max (1024 * fct, p == Phase::linear ? linearBlock * fct : naturalBlock * fct);
  533. firLoaded = false;
  534. latencyNow.store (latencyFor (p, sampleRate), std::memory_order_relaxed);
  535. }
  536. void update (const EffectParams& params) noexcept
  537. {
  538. for (int i = 0; i < paramCount; ++i) cached[(std::size_t) i] = params[(std::size_t) i];
  539. current = params;
  540. const auto newMode = phase (params[(std::size_t) phaseParam]);
  541. if (newMode != mode)
  542. {
  543. configureMode (newMode);
  544. conv.reset();
  545. for (auto& d : delay) std::fill (d.begin(), d.end(), 0.0f);
  546. }
  547. anyDynamic = false;
  548. for (int b = 0; b < bands; ++b)
  549. {
  550. auto& d = det[(std::size_t) b];
  551. const bool was = d.on;
  552. d.on = isDynamic (params, b);
  553. d.threshold = thresholdDb (params[(std::size_t) (thresholdParam0 + b)]);
  554. d.range = rangeDb (params[(std::size_t) (rangeParam0 + b)]);
  555. if (d.on)
  556. {
  557. regionFilter (d.filter, params, b, sampleRate);
  558. const double f0 = hz (params[(std::size_t) param (b, 1)]);
  559. d.msCoef = 1.0 - std::exp (-1.0 / (std::max (0.001, 1.5 / f0) * sampleRate));
  560. anyDynamic = true;
  561. if (! was) { d.filter.clear(); d.ms = 0.0; }
  562. }
  563. else
  564. d.gain = 0.0;
  565. const int before = counts[(std::size_t) b];
  566. counts[(std::size_t) b] = facet::design (params, b, sampleRate, sections[(std::size_t) b], d.gain);
  567. if (d.on && counts[(std::size_t) b] == 0) // a dynamic band at 0 dB keeps its (flat) section to move it later
  568. counts[(std::size_t) b] = designKeep (b, d.gain);
  569. if (counts[(std::size_t) b] != before) // the structure changed: start this band clean
  570. for (auto& st : state[(std::size_t) b]) st = {};
  571. dynUsed[(std::size_t) b] = d.gain;
  572. }
  573. attackCoef = 1.0 - std::exp (-1.0 / (attackMs (params[(std::size_t) attackParam]) * 0.001 * sampleRate));
  574. releaseCoef = 1.0 - std::exp (-1.0 / (releaseMs (params[(std::size_t) releaseParam]) * 0.001 * sampleRate));
  575. outGain = (float) std::pow (10.0, outputDb (params[(std::size_t) outputParam]) / 20.0);
  576. anyPlaced = anyMidSide = false;
  577. for (int b = 0; b < bands; ++b)
  578. {
  579. placed[(std::size_t) b] = placement (params[(std::size_t) (placementParam0 + b)]);
  580. if (placed[(std::size_t) b] != Placement::stereo && counts[(std::size_t) b] > 0) anyPlaced = true;
  581. if ((placed[(std::size_t) b] == Placement::mid || placed[(std::size_t) b] == Placement::side) && counts[(std::size_t) b] > 0) anyMidSide = true;
  582. }
  583. // the output stage: level, auto gain, polarity, pan (left / right or mid / side)
  584. float level = outGain;
  585. if (params[(std::size_t) autoGainParam] >= 0.5f) level *= (float) std::pow (10.0, -autoGainDb (params, sampleRate) / 20.0);
  586. if (params[(std::size_t) invertParam] >= 0.5f) level = -level;
  587. const auto pan = panAmount (params[(std::size_t) panParam]);
  588. outL = level * (float) (pan > 0.0 ? 1.0 - pan : 1.0);
  589. outR = level * (float) (pan < 0.0 ? 1.0 + pan : 1.0);
  590. outMidSide = panMidSide (params[(std::size_t) panModeParam]) && outL != outR;
  591. characterNow = character (params[(std::size_t) characterParam]);
  592. const int sb = soloBand (params[(std::size_t) soloParam]);
  593. const bool wasSolo = soloOn;
  594. soloOn = sb >= 0 && shape (params[(std::size_t) param (sb, 0)]) != Shape::off;
  595. if (soloOn) regionFilter (solo, params, sb, sampleRate);
  596. if (soloOn && ! wasSolo) solo.clear();
  597. firDirty = true;
  598. }
  599. int designKeep (int b, double extra) noexcept
  600. {
  601. Analog a[maxSections];
  602. const int n = analogSections (current, b, a, extra, true);
  603. const double f0 = std::min (hz (current[(std::size_t) param (b, 1)]), 0.4999 * sampleRate);
  604. const double w0 = 2.0 * pi * f0 / sampleRate;
  605. for (int k = 0; k < n; ++k) sections[(std::size_t) b][(std::size_t) k] = matched (a[k], w0);
  606. return n;
  607. }
  608. // detector levels and the dynamic gains, sample by sample over one chunk
  609. void detect (const float* dl, const float* dr, const float* inL, const float* inR, int m, bool side) noexcept
  610. {
  611. for (int b = 0; b < bands; ++b)
  612. {
  613. auto& d = det[(std::size_t) b];
  614. if (! d.on) continue;
  615. for (int i = 0; i < m; ++i)
  616. {
  617. double x = 0.0;
  618. if (side) x = dl != nullptr ? 0.5 * ((double) dl[i] + (double) dr[i]) : 0.0;
  619. else x = 0.5 * ((double) inL[i] + (double) inR[i]);
  620. if (! std::isfinite (x)) x = 0.0;
  621. const double y = d.filter.run (x, 0);
  622. d.ms += d.msCoef * (y * y - d.ms);
  623. const double level = 10.0 * std::log10 (2.0 * d.ms + 1e-20);
  624. const double target = dynamicGainDb (level, d.threshold, d.range);
  625. d.gain += (std::abs (target) > std::abs (d.gain) ? attackCoef : releaseCoef) * (target - d.gain);
  626. }
  627. if (std::abs (d.ms) < 1e-30) d.ms = 0.0;
  628. }
  629. }
  630. // `placedOnly`: in the FIR modes only the bands outside the FIR (one channel, mid or side) run as sections
  631. void redesignDynamic (bool placedOnly) noexcept
  632. {
  633. for (int b = 0; b < bands; ++b)
  634. {
  635. const auto& d = det[(std::size_t) b];
  636. if (placedOnly && placed[(std::size_t) b] == Placement::stereo) continue;
  637. if (! d.on || std::abs (d.gain - dynUsed[(std::size_t) b]) < 0.01) continue;
  638. const int before = counts[(std::size_t) b];
  639. const int c = designKeep (b, d.gain);
  640. if (c != before)
  641. {
  642. for (auto& st : state[(std::size_t) b]) st = {};
  643. counts[(std::size_t) b] = c;
  644. }
  645. dynUsed[(std::size_t) b] = d.gain;
  646. }
  647. }
  648. bool dynamicMoved() const noexcept
  649. {
  650. for (int b = 0; b < bands; ++b)
  651. if (det[(std::size_t) b].on && std::abs (det[(std::size_t) b].gain - dynUsed[(std::size_t) b]) > 0.05) return true;
  652. return false;
  653. }
  654. // the bands as digital sections: stereo bands on both channels, left / right bands on theirs, then mid / side
  655. // bands on the mid / side signals (round 128). `placedOnly`: only the bands outside the FIR (the FIR modes).
  656. void runIir (float* left, float* right, int n, bool placedOnly) noexcept
  657. {
  658. for (int b = 0; b < bands; ++b)
  659. {
  660. const auto pl = placed[(std::size_t) b];
  661. if (pl == Placement::mid || pl == Placement::side || (placedOnly && pl == Placement::stereo)) continue;
  662. runBand (b, left, right, n, pl == Placement::left ? 1 : pl == Placement::right ? 2 : 3);
  663. }
  664. if (! anyMidSide) return;
  665. for (int i = 0; i < n; ++i)
  666. {
  667. const float l = left[i], r = right[i];
  668. left[i] = 0.5f * (l + r);
  669. right[i] = 0.5f * (l - r);
  670. }
  671. for (int b = 0; b < bands; ++b)
  672. {
  673. const auto pl = placed[(std::size_t) b];
  674. if (pl == Placement::mid) runBand (b, left, right, n, 1);
  675. else if (pl == Placement::side) runBand (b, left, right, n, 2);
  676. }
  677. for (int i = 0; i < n; ++i)
  678. {
  679. const float m = left[i], sd = right[i];
  680. left[i] = m + sd;
  681. right[i] = m - sd;
  682. }
  683. }
  684. // one band's sections on the channels in `mask` (bit 0 = the first buffer, bit 1 = the second)
  685. void runBand (int b, float* left, float* right, int n, int mask) noexcept
  686. {
  687. for (int k = 0; k < counts[(std::size_t) b]; ++k)
  688. {
  689. const auto& c = sections[(std::size_t) b][(std::size_t) k];
  690. auto& st = state[(std::size_t) b][(std::size_t) k];
  691. for (int ch = 0; ch < 2; ++ch)
  692. {
  693. if ((mask & (1 << ch)) == 0) continue;
  694. float* x = ch == 0 ? left : right;
  695. double z1 = st.z1[ch], z2 = st.z2[ch];
  696. for (int i = 0; i < n; ++i)
  697. {
  698. const double in = x[i];
  699. const double y = c.b0 * in + z1;
  700. z1 = c.b1 * in - c.a1 * y + z2;
  701. z2 = c.b2 * in - c.a2 * y;
  702. x[i] = (float) y;
  703. }
  704. // denormal guard
  705. st.z1[ch] = std::abs (z1) < 1e-30 ? 0.0 : z1;
  706. st.z2[ch] = std::abs (z2) < 1e-30 ? 0.0 : z2;
  707. }
  708. }
  709. }
  710. // solo: the band's region alone (delayed like the FIR modes so switching does not jump)
  711. void runSolo (float* left, float* right, int n) noexcept
  712. {
  713. const int lat = mode == Phase::zeroLatency ? 0 : latencyFor (mode, sampleRate);
  714. for (int i = 0; i < n; ++i)
  715. {
  716. const float yl = (float) solo.run (left[i], 0), yr = (float) solo.run (right[i], 1);
  717. if (lat == 0) { left[i] = yl; right[i] = yr; continue; }
  718. delay[0][(std::size_t) delayPos] = yl;
  719. delay[1][(std::size_t) delayPos] = yr;
  720. const int rd = (delayPos - lat + delayLen) % delayLen;
  721. left[i] = delay[0][(std::size_t) rd];
  722. right[i] = delay[1][(std::size_t) rd];
  723. delayPos = (delayPos + 1) % delayLen;
  724. }
  725. }
  726. // the FIR of the current response (analog magnitude; analog phase in natural mode), windowed around its delay
  727. void loadFir() noexcept
  728. {
  729. const int M = taps;
  730. const bool natural = mode == Phase::natural;
  731. const int fct = rateFactor (sampleRate);
  732. const int D = natural ? naturalDelay * fct : M / 2;
  733. // every band's analog sections once, then the product of their responses on the FFT grid
  734. Analog a[bands * maxSections];
  735. double f0[bands * maxSections];
  736. int used = 0;
  737. for (int b = 0; b < bands; ++b)
  738. {
  739. if (shape (current[(std::size_t) param (b, 0)]) == Shape::off || placed[(std::size_t) b] != Placement::stereo) continue;
  740. const int c = analogSections (current, b, a + used, det[(std::size_t) b].on ? det[(std::size_t) b].gain : 0.0);
  741. for (int k = 0; k < c; ++k) f0[used + k] = hz (current[(std::size_t) param (b, 1)]);
  742. used += c;
  743. }
  744. const cd rot = std::polar (1.0, -2.0 * pi * D / M);
  745. cd phasor (1.0, 0.0);
  746. for (int k = 0; k <= M / 2; ++k)
  747. {
  748. const double f = std::max ((double) k * sampleRate / M, 0.01);
  749. double hr = 1.0, hi = 0.0;
  750. for (int j = 0; j < used; ++j)
  751. {
  752. const auto& s = a[j];
  753. const double w = f / f0[j], w2 = w * w;
  754. const double nr = s.n0 - s.n2 * w2, ni = s.n1 * w, dr = s.d0 - s.d2 * w2, di = s.d1 * w;
  755. const double dd = dr * dr + di * di;
  756. const double qr = (nr * dr + ni * di) / dd, qi = (ni * dr - nr * di) / dd;
  757. const double tr = hr * qr - hi * qi;
  758. hi = hr * qi + hi * qr;
  759. hr = tr;
  760. }
  761. cd h = natural ? cd (hr, hi) : cd (std::sqrt (hr * hr + hi * hi), 0.0);
  762. h = cd (h.real() * phasor.real() - h.imag() * phasor.imag(), h.real() * phasor.imag() + h.imag() * phasor.real());
  763. if ((k & 255) == 255) phasor = std::polar (1.0, -2.0 * pi * (double) (k + 1) * D / M); // no drift
  764. else phasor *= rot;
  765. if (k == M / 2 || k == 0) h = cd (h.real(), 0.0);
  766. spec[(std::size_t) k] = h;
  767. if (k > 0 && k < M / 2) spec[(std::size_t) (M - k)] = std::conj (h);
  768. }
  769. fftDesign.run (spec.data(), true);
  770. for (int i = 0; i < M; ++i)
  771. {
  772. const double w = i < D ? 0.5 * (1.0 - std::cos (pi * (i + 0.5) / D)) : 0.5 * (1.0 + std::cos (pi * (i - D) / (double) (M - D)));
  773. fir[(std::size_t) i] = spec[(std::size_t) i].real() / M * w;
  774. }
  775. conv.load (fir.data(), ! firLoaded);
  776. firLoaded = true;
  777. firDirty = false;
  778. sinceDesign = 0;
  779. for (int b = 0; b < bands; ++b) dynUsed[(std::size_t) b] = det[(std::size_t) b].gain;
  780. }
  781. double sampleRate = 48000.0;
  782. Phase mode = Phase::zeroLatency;
  783. EffectParams current {};
  784. std::array<float, paramCount> cached {};
  785. std::array<std::array<Section, maxSections>, bands> sections {};
  786. std::array<std::array<State, maxSections>, bands> state {};
  787. std::array<int, bands> counts {};
  788. std::array<Detector, bands> det {};
  789. std::array<double, bands> dynUsed {};
  790. std::array<std::atomic<float>, bands> meters {};
  791. double attackCoef = 0.1, releaseCoef = 0.001;
  792. float outGain = 1.0f, outL = 1.0f, outR = 1.0f;
  793. int characterNow = 0;
  794. std::array<Placement, bands> placed {};
  795. bool anyPlaced = false, anyMidSide = false, outMidSide = false;
  796. bool anyDynamic = false, soloOn = false, firLoaded = false, firDirty = true, sideGiven = false;
  797. Biquad solo;
  798. const float* sideL = nullptr;
  799. const float* sideR = nullptr;
  800. Fft fftNatural, fftLinear, fftDesign;
  801. Convolver conv;
  802. int taps = firTaps, updateEvery = 1024, sinceDesign = 0;
  803. std::vector<cd> spec;
  804. std::vector<double> fir;
  805. std::vector<float> delay[2];
  806. int delayLen = 1, delayPos = 0;
  807. std::atomic<int> latencyNow { 0 };
  808. };
  809. } // namespace
  810. // the nine original shapes sit at k / 8 (saved projects); round 135's at 1/16 (flat tilt) and 3/16 (all pass)
  811. Shape shape (float v) noexcept
  812. {
  813. const int k = std::clamp ((int) std::lround (v * 16.0f), 0, 16);
  814. if (k % 2 == 0) return (Shape) (k / 2);
  815. if (k == 1 && std::abs (v - 1.0f / 16.0f) < 0.02f) return Shape::flatTilt;
  816. if (k == 3 && std::abs (v - 3.0f / 16.0f) < 0.02f) return Shape::allPass;
  817. return (Shape) std::clamp ((int) std::lround (v * 8.0f), 0, 8);
  818. }
  819. float shapeValue (Shape s) noexcept
  820. {
  821. if (s == Shape::flatTilt) return 1.0f / 16.0f;
  822. if (s == Shape::allPass) return 3.0f / 16.0f;
  823. return (float) (int) s / 8.0f;
  824. }
  825. const std::array<Shape, shapeCount - 1>& menuShapes() noexcept
  826. {
  827. static const std::array<Shape, shapeCount - 1> m { Shape::bell, Shape::lowShelf, Shape::lowCut, Shape::highShelf, Shape::highCut,
  828. Shape::notch, Shape::bandPass, Shape::tiltShelf, Shape::flatTilt, Shape::allPass };
  829. return m;
  830. }
  831. int character (float v) noexcept { return std::clamp ((int) std::lround (v * 2.0f), 0, 2); }
  832. float characterSample (int c, float x) noexcept
  833. {
  834. // Subtle: a soft knee that bends hot peaks a little (odd harmonics); Warm: an earlier, rounder knee. Both are unity
  835. // at low level (below about −20 dBFS the curve is within 0.1 dB of a straight line).
  836. if (c == 1) return x / std::sqrt (1.0f + 0.12f * x * x);
  837. if (c == 2) return x / std::sqrt (1.0f + 0.3f * x * x) * (1.0f + 0.02f * std::min (1.0f, x * x));
  838. return x;
  839. }
  840. double hz (float v) noexcept { return 10.0 * std::pow (3000.0, (double) std::clamp (v, 0.0f, 1.0f)); }
  841. float hzValue (double f) noexcept { return (float) std::clamp (std::log (f / 10.0) / std::log (3000.0), 0.0, 1.0); }
  842. double gainDb (float v) noexcept { return ((double) v - 0.5) * 60.0; }
  843. float gainValue (double db) noexcept { return (float) std::clamp (db / 60.0 + 0.5, 0.0, 1.0); }
  844. double q (float v) noexcept { return 0.025 * std::pow (1600.0, (double) std::clamp (v, 0.0f, 1.0f)); }
  845. float qValue (double qq) noexcept { return (float) std::clamp (std::log (qq / 0.025) / std::log (1600.0), 0.0, 1.0); }
  846. int slopeDb (float v) noexcept { return slopes[(std::size_t) std::clamp ((int) std::lround (v * 8.0f), 0, 8)]; }
  847. float slopeValue (int d) noexcept
  848. {
  849. for (int i = 0; i < 9; ++i)
  850. if (slopes[(std::size_t) i] >= d) return (float) i / 8.0f;
  851. return 1.0f;
  852. }
  853. double outputDb (float v) noexcept { return ((double) v - 0.5) * 48.0; }
  854. double gainScale (float v) noexcept { return (double) v * 2.0; }
  855. const char* shapeName (Shape s) noexcept
  856. {
  857. static const char* names[] = { "Off", "Bell", "Low Shelf", "High Shelf", "Low Cut", "High Cut", "Notch", "Band Pass", "Tilt Shelf",
  858. "Flat Tilt", "All Pass" };
  859. return names[(int) s];
  860. }
  861. const EffectInfo& info()
  862. {
  863. static const EffectInfo i = [] {
  864. EffectInfo e { "Facet EQ", {} };
  865. static std::array<std::array<char, 24>, bands * fieldsPerBand> names {};
  866. const char* fields[] = { "Shape", "Freq", "Gain", "Q", "Slope" };
  867. for (int b = 0; b < bands; ++b)
  868. for (int f = 0; f < fieldsPerBand; ++f)
  869. {
  870. auto& n = names[(std::size_t) param (b, f)];
  871. std::snprintf (n.data(), n.size(), "%d %s", b + 1, fields[f]);
  872. const float def = f == 0 ? 0.0f : f == 1 ? hzValue (std::array<double, 8> { 50, 120, 300, 700, 1500, 3500, 8000, 15000 }[(std::size_t) b])
  873. : f == 2 ? 0.5f : f == 3 ? 0.5f : slopeValue (12);
  874. e.params.push_back ({ n.data(), def });
  875. }
  876. e.params.push_back ({ "Output", 0.5f });
  877. e.params.push_back ({ "Gain Scale", 0.5f });
  878. static std::array<std::array<char, 24>, bands * 2> dynNames {};
  879. for (int k = 0; k < bands * 2; ++k)
  880. {
  881. auto& n = dynNames[(std::size_t) k];
  882. std::snprintf (n.data(), n.size(), k < bands ? "%d Range" : "%d Threshold", k % bands + 1);
  883. e.params.push_back ({ n.data(), k < bands ? 0.5f : thresholdValue (-20.0) });
  884. }
  885. e.params.push_back ({ "Attack", 0.5f });
  886. e.params.push_back ({ "Release", 0.5f });
  887. e.params.push_back ({ "Phase", 0.0f });
  888. e.params.push_back ({ "Solo", 0.0f });
  889. e.params.push_back ({ "Detector", 0.0f });
  890. e.params.push_back ({ "Analyzer", 1.0f });
  891. // round 128 (Pro-Q parity): band power and stereo placement, output options, display settings
  892. static std::array<std::array<char, 24>, bands * 2> bandExtras {};
  893. for (int k = 0; k < bands * 2; ++k)
  894. {
  895. auto& n = bandExtras[(std::size_t) k];
  896. std::snprintf (n.data(), n.size(), k < bands ? "%d Bypass" : "%d Placement", k % bands + 1);
  897. e.params.push_back ({ n.data(), 0.0f });
  898. }
  899. e.params.push_back ({ "Auto Gain", 0.0f });
  900. e.params.push_back ({ "Invert", 0.0f });
  901. e.params.push_back ({ "Pan", 0.5f });
  902. e.params.push_back ({ "Pan Mode", 0.0f });
  903. e.params.push_back ({ "Analyzer Range", 0.5f });
  904. e.params.push_back ({ "Analyzer Speed", 0.5f });
  905. e.params.push_back ({ "Analyzer Tilt", 0.75f });
  906. e.params.push_back ({ "Display Range", displayRangeValue (12.0) });
  907. e.params.push_back ({ "Character", 0.0f }); // round 135
  908. return e;
  909. }();
  910. return i;
  911. }
  912. std::string paramText (int p, float v)
  913. {
  914. char t[48];
  915. if (p == outputParam) { std::snprintf (t, sizeof (t), "%+.2f dB", outputDb (v)); return t; }
  916. if (p == scaleParam) { std::snprintf (t, sizeof (t), "%.0f%%", gainScale (v) * 100.0); return t; }
  917. if (p >= rangeParam0 && p < rangeParam0 + bands) { std::snprintf (t, sizeof (t), "%+.2f dB", rangeDb (v)); return t; }
  918. if (p >= thresholdParam0 && p < thresholdParam0 + bands) { std::snprintf (t, sizeof (t), "%.1f dB", thresholdDb (v)); return t; }
  919. if (p == attackParam) { std::snprintf (t, sizeof (t), attackMs (v) < 10.0 ? "%.2f ms" : "%.1f ms", attackMs (v)); return t; }
  920. if (p == releaseParam) { const auto ms = releaseMs (v); std::snprintf (t, sizeof (t), ms < 1000.0 ? "%.0f ms" : "%.2f s", ms < 1000.0 ? ms : ms / 1000.0); return t; }
  921. if (p == phaseParam) return phaseName (phase (v));
  922. if (p == soloParam) { const auto b = soloBand (v); if (b < 0) return "Off"; std::snprintf (t, sizeof (t), "Band %d", b + 1); return t; }
  923. if (p == detectorParam) return sidechainDetector (v) ? "Sidechain" : "Input";
  924. if (p == analyzerParam) { static const char* a[] = { "Off", "Pre", "Post", "Pre + Post" }; return a[(int) analyzer (v)]; }
  925. if (p >= powerParam0 && p < powerParam0 + bands) return v >= 0.5f ? "Off" : "On";
  926. if (p >= placementParam0 && p < placementParam0 + bands) return placementName (placement (v));
  927. if (p == autoGainParam) return v >= 0.5f ? "On" : "Off";
  928. if (p == invertParam) return v >= 0.5f ? "Inverted" : "Normal";
  929. if (p == panParam)
  930. {
  931. const auto a = panAmount (v);
  932. if (std::abs (a) < 0.005) return "Centre";
  933. std::snprintf (t, sizeof (t), "%s %.0f%%", a < 0.0 ? "L" : "R", std::abs (a) * 100.0);
  934. return t;
  935. }
  936. if (p == panModeParam) return panMidSide (v) ? "Mid/Side" : "Left/Right";
  937. if (p == specRangeParam) { std::snprintf (t, sizeof (t), "%.0f dB", analyzerRangeDb (v)); return t; }
  938. if (p == specSpeedParam) { static const char* a[] = { "Very slow", "Slow", "Medium", "Fast", "Very fast" }; return a[analyzerSpeed (v)]; }
  939. if (p == specTiltParam) { std::snprintf (t, sizeof (t), "%.1f dB/oct", analyzerTiltDb (v)); return t; }
  940. if (p == displayRangeParam) { std::snprintf (t, sizeof (t), "%.0f dB", displayRangeDb (v)); return t; }
  941. if (p == characterParam) { static const char* a[] = { "Clean", "Subtle", "Warm" }; return a[character (v)]; }
  942. switch (p % fieldsPerBand)
  943. {
  944. case 0: return shapeName (shape (v));
  945. case 1: { const auto f = hz (v); std::snprintf (t, sizeof (t), f < 1000 ? "%.1f Hz" : "%.2f kHz", f < 1000 ? f : f / 1000.0); return t; }
  946. case 2: std::snprintf (t, sizeof (t), "%+.2f dB", gainDb (v)); return t;
  947. case 3: std::snprintf (t, sizeof (t), "%.3f", q (v)); return t;
  948. default: std::snprintf (t, sizeof (t), "%d dB/oct", slopeDb (v)); return t;
  949. }
  950. }
  951. int design (const EffectParams& params, int band, double sampleRate, std::array<Section, maxSections>& out, double extraDb) noexcept
  952. {
  953. Analog a[maxSections];
  954. const int n = analogSections (params, band, a, extraDb);
  955. const double f0 = std::min (hz (params[(std::size_t) param (band, 1)]), 0.4999 * sampleRate);
  956. const double w0 = 2.0 * pi * f0 / sampleRate;
  957. for (int k = 0; k < n; ++k)
  958. out[(std::size_t) k] = matched (a[k], w0);
  959. return n;
  960. }
  961. double analogDb (const EffectParams& params, int band, double f, double extraDb) noexcept
  962. {
  963. Analog a[maxSections];
  964. const int n = analogSections (params, band, a, extraDb);
  965. const double w = f / hz (params[(std::size_t) param (band, 1)]);
  966. double m = 1.0;
  967. for (int k = 0; k < n; ++k) m *= std::sqrt (mag2 (a[k], w));
  968. return 20.0 * std::log10 (std::max (m, 1e-15));
  969. }
  970. double bandResponseDb (const EffectParams& params, int band, double sampleRate, double f, double extraDb) noexcept
  971. {
  972. if (phase (params[(std::size_t) phaseParam]) != Phase::zeroLatency)
  973. return analogDb (params, band, f, extraDb);
  974. std::array<Section, maxSections> s;
  975. const int n = design (params, band, sampleRate, s, extraDb);
  976. const double w = 2.0 * pi * std::min (f, 0.5 * sampleRate) / sampleRate;
  977. double m = 1.0;
  978. for (int k = 0; k < n; ++k) m *= std::abs (evalDigital (s[(std::size_t) k], w));
  979. return 20.0 * std::log10 (std::max (m, 1e-15));
  980. }
  981. void bandCurveDb (const EffectParams& params, int band, double sampleRate, const double* f, int n, double* out, double extraDb) noexcept
  982. {
  983. if (phase (params[(std::size_t) phaseParam]) != Phase::zeroLatency)
  984. {
  985. Analog a[maxSections];
  986. const int c = analogSections (params, band, a, extraDb);
  987. const double f0 = hz (params[(std::size_t) param (band, 1)]);
  988. for (int i = 0; i < n; ++i)
  989. {
  990. double m = 1.0;
  991. for (int k = 0; k < c; ++k) m *= mag2 (a[k], f[i] / f0);
  992. out[i] = 10.0 * std::log10 (std::max (m, 1e-30));
  993. }
  994. return;
  995. }
  996. std::array<Section, maxSections> s;
  997. const int c = design (params, band, sampleRate, s, extraDb);
  998. for (int i = 0; i < n; ++i)
  999. {
  1000. const double w = 2.0 * pi * std::min (f[i], 0.5 * sampleRate) / sampleRate;
  1001. double m = 1.0;
  1002. for (int k = 0; k < c; ++k) m *= std::abs (evalDigital (s[(std::size_t) k], w));
  1003. out[i] = 20.0 * std::log10 (std::max (m, 1e-15));
  1004. }
  1005. }
  1006. double responseDb (const EffectParams& params, double sampleRate, double f, const float* dynamicDb) noexcept
  1007. {
  1008. double db = outputDb (params[(std::size_t) outputParam]);
  1009. for (int b = 0; b < bands; ++b)
  1010. db += bandResponseDb (params, b, sampleRate, f, dynamicDb != nullptr && isDynamic (params, b) ? (double) dynamicDb[b] : 0.0);
  1011. return db;
  1012. }
  1013. bool hasGain (Shape s) noexcept
  1014. {
  1015. return s == Shape::bell || s == Shape::lowShelf || s == Shape::highShelf || s == Shape::tiltShelf || s == Shape::flatTilt;
  1016. }
  1017. double rangeDb (float v) noexcept { return ((double) std::clamp (v, 0.0f, 1.0f) - 0.5) * 60.0; }
  1018. float rangeValue (double db) noexcept { return (float) std::clamp (db / 60.0 + 0.5, 0.0, 1.0); }
  1019. double thresholdDb (float v) noexcept { return -80.0 + 80.0 * (double) std::clamp (v, 0.0f, 1.0f); }
  1020. float thresholdValue (double db) noexcept { return (float) std::clamp ((db + 80.0) / 80.0, 0.0, 1.0); }
  1021. double attackMs (float v) noexcept { return 0.25 * std::pow (200.0, (double) std::clamp (v, 0.0f, 1.0f)); }
  1022. double releaseMs (float v) noexcept { return 20.0 * std::pow (200.0, (double) std::clamp (v, 0.0f, 1.0f)); }
  1023. Phase phase (float v) noexcept { return (Phase) std::clamp ((int) std::lround (v * (phaseCount - 1)), 0, phaseCount - 1); }
  1024. float phaseValue (Phase p) noexcept { return (float) (int) p / (float) (phaseCount - 1); }
  1025. int soloBand (float v) noexcept { return std::clamp ((int) std::lround (v * bands), 0, bands) - 1; }
  1026. float soloValue (int band) noexcept { return band < 0 ? 0.0f : (float) (band + 1) / (float) bands; }
  1027. bool sidechainDetector (float v) noexcept { return v >= 0.5f; }
  1028. Analyzer analyzer (float v) noexcept { return (Analyzer) std::clamp ((int) std::lround (v * 3.0f), 0, 3); }
  1029. float analyzerValue (Analyzer a) noexcept { return (float) (int) a / 3.0f; }
  1030. const char* phaseName (Phase p) noexcept
  1031. {
  1032. static const char* names[] = { "Zero Latency", "Natural Phase", "Linear Phase" };
  1033. return names[(int) p];
  1034. }
  1035. bool isDynamic (const EffectParams& p, int b) noexcept
  1036. {
  1037. return hasGain (shape (p[(std::size_t) param (b, 0)])) && bandPower (p, b) && std::abs (rangeDb (p[(std::size_t) (rangeParam0 + b)])) > 0.01;
  1038. }
  1039. double dynamicGainDb (double level, double threshold, double range) noexcept
  1040. {
  1041. const double x = level - threshold;
  1042. constexpr double knee = 10.0; // fitted to the reference (REA_rodada103 §2.1)
  1043. const double over = x <= -0.5 * knee ? 0.0 : x < 0.5 * knee ? (x + 0.5 * knee) * (x + 0.5 * knee) / (2.0 * knee) : x;
  1044. return range < 0.0 ? -std::min (-range, over) : std::min (range, over);
  1045. }
  1046. int latencyFor (Phase p, double sampleRate) noexcept
  1047. {
  1048. const int f = rateFactor (sampleRate);
  1049. switch (p)
  1050. {
  1051. case Phase::natural: return (naturalBlock + naturalDelay) * f;
  1052. case Phase::linear: return linearBlock * f + firTaps * f / 2;
  1053. default: return 0;
  1054. }
  1055. }
  1056. Placement placement (float v) noexcept { return (Placement) std::clamp ((int) std::lround (v * (placementCount - 1)), 0, placementCount - 1); }
  1057. float placementValue (Placement p) noexcept { return (float) (int) p / (float) (placementCount - 1); }
  1058. const char* placementName (Placement p) noexcept
  1059. {
  1060. static const char* names[] = { "Stereo", "Left", "Right", "Mid", "Side" };
  1061. return names[(int) p];
  1062. }
  1063. bool bandPower (const EffectParams& p, int b) noexcept { return p[(std::size_t) (powerParam0 + b)] < 0.5f; } // stored as "bypassed" so a zeroed array is on
  1064. double panAmount (float v) noexcept { return std::clamp ((double) v * 2.0 - 1.0, -1.0, 1.0); }
  1065. bool panMidSide (float v) noexcept { return v >= 0.5f; }
  1066. double analyzerRangeDb (float v) noexcept { return 60.0 + 30.0 * std::clamp ((int) std::lround (v * 2.0f), 0, 2); }
  1067. int analyzerSpeed (float v) noexcept { return std::clamp ((int) std::lround (v * 4.0f), 0, 4); }
  1068. double analyzerTiltDb (float v) noexcept { return 1.5 * std::clamp ((int) std::lround (v * 4.0f), 0, 4); }
  1069. double displayRangeDb (float v) noexcept
  1070. {
  1071. static constexpr double r[] { 3.0, 6.0, 12.0, 30.0 };
  1072. return r[std::clamp ((int) std::lround (v * 3.0f), 0, 3)];
  1073. }
  1074. float displayRangeValue (double db) noexcept { return db <= 4.5 ? 0.0f : db <= 9.0 ? 1.0f / 3.0f : db <= 21.0 ? 2.0f / 3.0f : 1.0f; }
  1075. double autoGainDb (const EffectParams& params, double sampleRate) noexcept
  1076. {
  1077. constexpr int points = 32;
  1078. double sum = 0.0;
  1079. for (int b = 0; b < bands; ++b)
  1080. {
  1081. Analog a[maxSections];
  1082. const int c = analogSections (params, b, a);
  1083. if (c == 0) continue;
  1084. const double f0 = hz (params[(std::size_t) param (b, 1)]);
  1085. for (int i = 0; i < points; ++i)
  1086. {
  1087. const double f = std::min (20.0 * std::pow (1000.0, (i + 0.5) / points), 0.49 * sampleRate);
  1088. double m = 1.0;
  1089. for (int k = 0; k < c; ++k) m *= mag2 (a[k], f / f0);
  1090. sum += 10.0 * std::log10 (std::max (m, 1e-30));
  1091. }
  1092. }
  1093. return sum / points;
  1094. }
  1095. std::unique_ptr<Effect> make (const EffectParams* initial) { return std::make_unique<FacetEqEffect> (initial); }
  1096. } // namespace lynx::facet