ParametricEqLinear.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. #include "core/ParametricEqLinear.h"
  2. #include <algorithm>
  3. #include <cmath>
  4. #include <cstring>
  5. #include <map>
  6. #include <memory>
  7. #include <mutex>
  8. // bit-exactness needs every product and sum rounded on its own (no fused multiply-add)
  9. #if defined(__clang__)
  10. #pragma clang fp contract(off)
  11. #elif defined(__GNUC__)
  12. #pragma GCC optimize("fp-contract=off")
  13. #endif
  14. // Parametric EQ 2 linear-phase mode (docs/analise/REA_rodada50.md §5). The float/double roundings of the magnitude
  15. // table follow the plugin; the FFT convolution is computed here in double precision (the plugin's single-precision
  16. // FFT rounding is not reproduced, §5.6).
  17. namespace lynx::peqfl
  18. {
  19. namespace
  20. {
  21. constexpr double twoPi = 6.283185307179586;
  22. constexpr double ln2 = 0.69314718055994529;
  23. constexpr double freqStep = 0.00015206580024203624;
  24. constexpr float smoothingSeconds[4] = { 0.1f, 0.25f, 0.01f, 0.02f };
  25. // 2^y for |y| ≤ 100/6 with the plugin's cubic approximation of 2^f on [0, 1): integer part through the exponent
  26. // bits, negative arguments as the reciprocal of the positive one (§5.2)
  27. float pow2Approx (float y)
  28. {
  29. auto power = [] (float v) {
  30. const int i = (int) (double) v;
  31. const double f = (double) (v - (float) i);
  32. std::uint32_t bits = (std::uint32_t) (i + 127) << 23;
  33. float scale;
  34. std::memcpy (&scale, &bits, 4);
  35. return (float) ((double) scale * (f * (f * (f * 0.079064658211 + 0.224328091473) + 0.69659850257) + 0.999862219597));
  36. };
  37. if (y > 0.0f)
  38. return power (y);
  39. if ((double) y < 0.0)
  40. return 1.0f / power (-y);
  41. return 1.0f;
  42. }
  43. // Twiddle factors of the radix-2 transform below for size n, stage by stage (len = 2, 4, … n: the len/2 factors
  44. // e^(±2πik/len) start at len/2 − 1). Built once per size and shared; the values are the ones the transform computed
  45. // per butterfly before (std::polar of the same angle), so the output is unchanged — only the audio thread no longer
  46. // evaluates a sine and a cosine for every butterfly (REA round 87: this was most of a heavy project's CPU)
  47. std::shared_ptr<const Twiddles> twiddlesFor (int n)
  48. {
  49. static std::mutex lock;
  50. static std::map<int, std::shared_ptr<const Twiddles>> cache;
  51. const std::lock_guard<std::mutex> guard (lock);
  52. auto& entry = cache[n];
  53. if (entry == nullptr)
  54. {
  55. auto t = std::make_shared<Twiddles>();
  56. for (auto* table : { &t->forward, &t->inverse })
  57. {
  58. const bool inverse = table == &t->inverse;
  59. table->reserve ((std::size_t) std::max (0, n - 1));
  60. for (std::size_t len = 2; len <= (std::size_t) n; len <<= 1)
  61. {
  62. const double ang = (inverse ? twoPi : -twoPi) / (double) len;
  63. for (std::size_t k = 0; k < len / 2; ++k)
  64. table->push_back (std::polar (1.0, ang * (double) k));
  65. }
  66. }
  67. entry = std::move (t);
  68. }
  69. return entry;
  70. }
  71. // (a + bi)(c + di) as std::complex computes it for finite values, without its NaN/infinity recovery branch
  72. inline std::complex<double> mul (const std::complex<double>& z, const std::complex<double>& w) noexcept
  73. {
  74. const double a = z.real(), b = z.imag(), c = w.real(), d = w.imag();
  75. const double ac = a * c;
  76. const double bd = b * d;
  77. const double ad = a * d;
  78. const double bc = b * c;
  79. const double x = ac - bd;
  80. const double y = ad + bc;
  81. if (std::isnan (x) && std::isnan (y))
  82. return z * w;
  83. return { x, y };
  84. }
  85. void fft (std::complex<double>* a, std::size_t n, const std::vector<std::complex<double>>& tw) noexcept
  86. {
  87. for (std::size_t i = 1, j = 0; i < n; ++i)
  88. {
  89. auto bit = n >> 1;
  90. for (; j & bit; bit >>= 1)
  91. j ^= bit;
  92. j ^= bit;
  93. if (i < j)
  94. std::swap (a[i], a[j]);
  95. }
  96. for (std::size_t len = 2; len <= n; len <<= 1)
  97. {
  98. const auto* w = tw.data() + (len / 2 - 1);
  99. const auto half = len / 2;
  100. for (std::size_t i = 0; i < n; i += len)
  101. for (std::size_t k = 0; k < half; ++k)
  102. {
  103. const auto u = a[i + k], v = mul (a[i + k + half], w[k]);
  104. a[i + k] = u + v;
  105. a[i + k + half] = u - v;
  106. }
  107. }
  108. }
  109. // The plugin's main-level stage (§5.5, shared with its other modes): a change glides linearly over the block, at
  110. // most maxStep per frame; the per-frame gains are built by repeated float additions, even and odd frames on
  111. // separate running sums in groups of eight frames, the remainder one frame at a time
  112. void applyMainGain (float* io, int n, float target, float& now, float maxStep, bool snap) noexcept
  113. {
  114. if (snap)
  115. now = target;
  116. const float g0 = now;
  117. float step = target - g0;
  118. std::uint32_t stepBits;
  119. std::memcpy (&stepBits, &step, 4);
  120. if (stepBits != 0)
  121. {
  122. now = target;
  123. step = step / (float) n;
  124. if (std::abs (step) > maxStep)
  125. {
  126. step = std::copysign (maxStep, step);
  127. now = g0 + step * (float) n;
  128. std::uint32_t b;
  129. std::memcpy (&b, &now, 4);
  130. if ((b & 0x7FFFFFFFu) < 0x33800000u)
  131. {
  132. now = 0.0f;
  133. step = -g0 / (float) n;
  134. }
  135. }
  136. }
  137. else
  138. {
  139. if (g0 == 0.0f)
  140. std::fill (io, io + 2 * n, 0.0f);
  141. else if (g0 != 1.0f)
  142. for (int i = 0; i < 2 * n; ++i)
  143. io[i] *= g0;
  144. return;
  145. }
  146. float even = g0 + 0.0f, odd = g0 + step;
  147. const float step2 = step + step;
  148. int i = 0;
  149. for (int g = 0; g < (n >> 3); ++g)
  150. for (int m = 0; m < 4; ++m, i += 2)
  151. {
  152. io[2 * i] *= even, io[2 * i + 1] *= even;
  153. io[2 * i + 2] *= odd, io[2 * i + 3] *= odd;
  154. even += step2, odd += step2;
  155. }
  156. for (; i < n; ++i)
  157. {
  158. io[2 * i] *= even, io[2 * i + 1] *= even;
  159. even += step;
  160. }
  161. }
  162. std::int32_t i32At (const std::vector<std::uint8_t>& d, std::size_t offset)
  163. {
  164. std::int32_t v = 0;
  165. if (offset + 4 <= d.size())
  166. std::memcpy (&v, d.data() + offset, 4);
  167. return v;
  168. }
  169. } // namespace
  170. void mainLevel (float* io, int n, float target, float& now, float maxStep, bool snap) noexcept
  171. {
  172. applyMainGain (io, n, target, now, maxStep, snap);
  173. }
  174. int linearFftSize (int quality, int hostRate) noexcept
  175. {
  176. const int base = 512 << std::clamp (quality, 0, 7);
  177. if (hostRate < 44100)
  178. return base / 2;
  179. const int e = (int) (std::log ((double) hostRate * 2.2675736961451248e-05) * 1.4426950408889634 + 0.5);
  180. return std::min (base << std::max (e, 0), 65536);
  181. }
  182. LinearOptions parseLinearOptions (const std::vector<std::uint8_t>& d)
  183. {
  184. LinearOptions o;
  185. if (i32At (d, 0) >= 4 && d.size() >= 0x13D)
  186. {
  187. o.quality = std::clamp ((int) i32At (d, 0x135), 0, 7);
  188. o.smoothing = std::clamp ((int) i32At (d, 0x139), 0, 3);
  189. }
  190. return o;
  191. }
  192. std::vector<float> linearMagnitudes (const Settings& s, int hostRate, int n)
  193. {
  194. // the bands are designed at the plugin's processing rate (×2 with HQ oversampling on), but the grid spans the host
  195. // rate's 0…rate/2 (§5.1)
  196. const bool twice = s.processing == Processing::hq || s.processing == Processing::hqExternal;
  197. const double procRate = twice ? 2.0 * hostRate : (double) hostRate;
  198. const auto limit = (float) ((double) (int) procRate * 0.4999);
  199. const double wk = (1.0 / procRate) * twoPi;
  200. std::array<Band, 7> bands {};
  201. std::array<float, 7> freq {};
  202. std::array<bool, 7> snap {}, used {};
  203. for (int b = 0; b < 7; ++b)
  204. {
  205. designBand (s, b, procRate, bands[(std::size_t) b]);
  206. freq[(std::size_t) b] = (float) (std::exp ((double) (float) s.freq[(std::size_t) b] * freqStep * ln2) * 20.0);
  207. const int ui = s.type[(std::size_t) b];
  208. // narrow band-pass / notch / peaking bands (width < 1/8) pull the nearest grid point onto their centre
  209. snap[(std::size_t) b] = s.width[(std::size_t) b] < 0x2000 && ui >= 0 && ui < 8 && ((0x54 >> ui) & 1) != 0;
  210. used[(std::size_t) b] = (s.mask & (1u << b)) != 0 && bands[(std::size_t) b].type > 0;
  211. }
  212. std::vector<float> t ((std::size_t) (n / 2 + 1));
  213. const float spacing = (float) hostRate / (float) n;
  214. float previous = 0.0f;
  215. for (int k = 0; k <= n / 2; ++k)
  216. {
  217. float f = (float) k * spacing;
  218. if (0.1f > f)
  219. f = 0.1f;
  220. float level = 0.0f; // response in units of 18 dB
  221. if (! (f > limit))
  222. {
  223. for (int b = 0; b < 7; ++b)
  224. if (snap[(std::size_t) b] && freq[(std::size_t) b] > previous && f >= freq[(std::size_t) b])
  225. {
  226. f = freq[(std::size_t) b];
  227. break;
  228. }
  229. previous = f;
  230. const auto w = (float) ((double) f * wk);
  231. const double s1 = std::sin ((double) w), c1 = std::cos ((double) w);
  232. const auto w2 = w * 2.0f;
  233. const double s2 = std::sin ((double) w2), c2 = std::cos ((double) w2);
  234. float product = 1.0f;
  235. for (int b = 0; b < 7; ++b)
  236. {
  237. if (! used[(std::size_t) b])
  238. continue;
  239. float g = 1.0f;
  240. const auto& band = bands[(std::size_t) b];
  241. for (int st = 0; st < band.stages; ++st)
  242. {
  243. const auto& c = band.stage[(std::size_t) st];
  244. const double nr = c.b0 * c2 + c.b1 * c1 + c.b2, ni = c.b1 * s1 + c.b0 * s2;
  245. const double dr = c2 + c.a1 * c1 + c.a2, di = c.a1 * s1 + s2;
  246. g = (float) (((double) g * (nr * nr + ni * ni)) / (dr * dr + di * di));
  247. }
  248. product *= g;
  249. }
  250. level = (float) (std::log10 ((double) product) * 0.5555555555555556);
  251. level = std::clamp (level, -1000.0f, 1000.0f);
  252. }
  253. const float db = level * 18.0f;
  254. float amp;
  255. if (db < -100.0f)
  256. amp = 0.0f;
  257. else if (db > 100.0f)
  258. amp = (float) std::pow (2.0, (double) (db * 0.166666672f)); // not reached by the plugin's ranges
  259. else
  260. amp = pow2Approx (db * 0.166666672f);
  261. t[(std::size_t) k] = amp;
  262. }
  263. t[(std::size_t) (n / 2)] = t[(std::size_t) (n / 2 - 1)];
  264. return t;
  265. }
  266. // ------------------------------------------------------------------------------------------------- convolver
  267. void FftConvolver::init (int size)
  268. {
  269. n = size;
  270. hop = size / 2;
  271. pos = 0;
  272. kernel.assign ((std::size_t) n, {});
  273. work.assign ((std::size_t) n, {});
  274. work2.assign ((std::size_t) n, {});
  275. twiddles = twiddlesFor (n);
  276. for (int c = 0; c < 2; ++c)
  277. {
  278. in[c].assign ((std::size_t) hop, 0.0f);
  279. out[c].assign ((std::size_t) n, 0.0f);
  280. }
  281. }
  282. void FftConvolver::clear() noexcept
  283. {
  284. pos = 0;
  285. for (int c = 0; c < 2; ++c)
  286. {
  287. std::fill (in[c].begin(), in[c].end(), 0.0f);
  288. std::fill (out[c].begin(), out[c].end(), 0.0f);
  289. }
  290. }
  291. void FftConvolver::setKernel (const std::vector<float>& t)
  292. {
  293. // zero-phase impulse centred at n/2: (1/n)·IFFT of the table times (−1)^k, mirrored; its middle half is kept,
  294. // weighted by a sine window, and becomes an n/2-tap FIR with its centre at tap n/4 (§5.3)
  295. // (in the preallocated buffers: a new response is loaded on the audio thread)
  296. auto& spec = work;
  297. std::fill (spec.begin(), spec.end(), std::complex<double> {});
  298. for (int k = 0; k <= n / 2; ++k)
  299. spec[(std::size_t) k] = (k & 1) ? -(double) t[(std::size_t) k] : (double) t[(std::size_t) k];
  300. for (int k = 1; k < n / 2; ++k)
  301. spec[(std::size_t) (n - k)] = spec[(std::size_t) k];
  302. fft (spec.data(), (std::size_t) n, twiddles->inverse);
  303. const float span = 1.0f / (float) (hop - 1);
  304. auto& taps = work2;
  305. std::fill (taps.begin(), taps.end(), std::complex<double> {});
  306. for (int i = 0; i < hop; ++i)
  307. {
  308. const auto h = (float) (spec[(std::size_t) (n / 4 + i)].real() / (double) n);
  309. const auto w = (float) std::sin ((double) ((float) i * span * 3.14159274f));
  310. taps[(std::size_t) i] = (double) (w * h);
  311. }
  312. fft (taps.data(), (std::size_t) n, twiddles->forward);
  313. std::copy (taps.begin(), taps.end(), kernel.begin());
  314. }
  315. void FftConvolver::block() noexcept
  316. {
  317. const auto scale = 1.0f / (float) n;
  318. auto& x = work;
  319. for (int c = 0; c < 2; ++c)
  320. {
  321. std::fill (x.begin(), x.end(), std::complex<double> {});
  322. for (int i = 0; i < hop; ++i)
  323. x[(std::size_t) i] = (double) in[c][(std::size_t) i];
  324. fft (x.data(), (std::size_t) n, twiddles->forward);
  325. for (int k = 0; k < n; ++k)
  326. x[(std::size_t) k] = mul (x[(std::size_t) k], kernel[(std::size_t) k]);
  327. fft (x.data(), (std::size_t) n, twiddles->inverse);
  328. auto& o = out[c];
  329. std::copy (o.begin() + hop, o.end(), o.begin());
  330. std::fill (o.begin() + hop, o.end(), 0.0f);
  331. for (int i = 0; i < n; ++i)
  332. o[(std::size_t) i] = scale * (float) x[(std::size_t) i].real() + o[(std::size_t) i];
  333. }
  334. }
  335. void FftConvolver::step (float& l, float& r) noexcept
  336. {
  337. in[0][(std::size_t) pos] = l;
  338. in[1][(std::size_t) pos] = r;
  339. l = out[0][(std::size_t) pos];
  340. r = out[1][(std::size_t) pos];
  341. if (++pos == hop)
  342. {
  343. pos = 0;
  344. block();
  345. }
  346. }
  347. // ------------------------------------------------------------------------------------------------- engine
  348. void LinearPhase::setOptions (LinearOptions o) noexcept
  349. {
  350. quality = std::clamp (o.quality, 0, 7);
  351. smoothingIndex = std::clamp (o.smoothing, 0, 3);
  352. }
  353. void LinearPhase::prepare (int hostRate) noexcept
  354. {
  355. rate = hostRate;
  356. size = linearFftSize (quality, rate);
  357. for (auto& c : conv)
  358. c.init (size);
  359. for (auto& h : history)
  360. h.assign ((std::size_t) size, 0.0f);
  361. reset();
  362. }
  363. void LinearPhase::reset() noexcept
  364. {
  365. for (auto& c : conv)
  366. c.clear();
  367. for (auto& h : history)
  368. std::fill (h.begin(), h.end(), 0.0f);
  369. historyPos = 0;
  370. fadeCount = fadeLength = 0;
  371. gainSnap = true;
  372. active = 0;
  373. if (configured)
  374. {
  375. // the response is (re)loaded with the first sample, faded in from silence
  376. for (auto& c : conv)
  377. c.setKernel (std::vector<float> ((std::size_t) (size / 2 + 1), 0.0f));
  378. pending = true;
  379. }
  380. }
  381. void LinearPhase::set (const Settings& s)
  382. {
  383. settings = s;
  384. mainGain = (float) std::exp ((double) ((float) s.main * 0.01f * 0.115129255f));
  385. // the glide limit follows the plugin's processing rate (×2 when HQ oversampling is on)
  386. const bool twice = s.processing == Processing::hq || s.processing == Processing::hqExternal;
  387. gainStepMax = (float) (44100.0 / (double) (twice ? 2 * rate : rate) * 0.001);
  388. if (size != linearFftSize (quality, rate) || conv[0].n != size)
  389. prepare (rate);
  390. table = linearMagnitudes (s, rate, size);
  391. pending = true;
  392. configured = true;
  393. }
  394. void LinearPhase::load() noexcept
  395. {
  396. // the convolver not in use takes the new response, is primed with the last n input samples and becomes the
  397. // current one; the output then cross-fades from the old one over the smoothing time (§5.4)
  398. pending = false;
  399. fadeCount = 0;
  400. fadeLength = (int) ((float) rate * smoothingSeconds[smoothingIndex]);
  401. auto& c = conv[(std::size_t) active];
  402. c.clear();
  403. c.setKernel (table);
  404. for (int k = 0, p = historyPos; k < size; ++k)
  405. {
  406. float l = history[0][(std::size_t) p], r = history[1][(std::size_t) p];
  407. c.step (l, r);
  408. if (++p == size)
  409. p = 0;
  410. }
  411. active = active == 0 ? 1 : 0;
  412. }
  413. void LinearPhase::process (float* io, int n) noexcept
  414. {
  415. if (! configured)
  416. return;
  417. applyMainGain (io, n, mainGain, gainNow, gainStepMax, gainSnap);
  418. gainSnap = false;
  419. for (int i = 0; i < n; ++i)
  420. {
  421. if (pending && fadeLength <= fadeCount)
  422. load();
  423. float& l = io[2 * i];
  424. float& r = io[2 * i + 1];
  425. history[0][(std::size_t) historyPos] = l;
  426. history[1][(std::size_t) historyPos] = r;
  427. if (++historyPos == size)
  428. historyPos = 0;
  429. if (fadeLength <= fadeCount)
  430. {
  431. conv[active == 0 ? 1u : 0u].step (l, r);
  432. continue;
  433. }
  434. float al = l, ar = r, bl = l, br = r;
  435. conv[0].step (al, ar);
  436. conv[1].step (bl, br);
  437. float f = (float) fadeCount / (float) fadeLength;
  438. if (active == 0)
  439. f = 1.0f - f;
  440. const float g = 1.0f - f;
  441. l = bl * g + al * f;
  442. r = br * g + ar * f;
  443. ++fadeCount;
  444. }
  445. }
  446. } // namespace lynx::peqfl