DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Saturation.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
42#include "../Core/AudioBuffer.h"
43#include "../Core/AudioSpec.h"
44#include "../Core/Biquad.h"
45#include "../Core/BiquadCascade.h"
46#include "../Core/DryWetMixer.h"
47#include "../Core/DspMath.h"
48#include "../Core/Interpolation.h"
49#include "../Core/Oversampling.h"
50#include "../Core/Smoothers.h"
51#include "../Core/AnalogRandom.h"
52#include "../Core/SpscQueue.h"
53#include "../Core/SpinLock.h"
54#include "../Core/StateBlob.h"
55#include "DCBlocker.h"
56#include "MidSide.h"
57
58#include <algorithm>
59#include <array>
60#include <atomic>
61#include <bit>
62#include "../Core/detail/Adaa.h"
63#include "../Core/detail/LogCosh.h"
64
65#include <cmath>
66#include <cstdint>
67#include <cstdio>
68#include <cstring>
69#include <limits>
70#include <memory>
71#include <numbers>
72#include <type_traits>
73#include <vector>
74
75namespace dspark {
76
77template <typename SampleType> class Saturation;
78
79namespace detail {
80
81template <typename T>
83{
84public:
85 static constexpr int kAaCh = 16;
86
87 virtual ~SaturationAlgorithm() = default;
88
90 virtual void prepare(const AudioSpec& spec) noexcept = 0;
91
93 virtual void reset() noexcept = 0;
94
96 virtual void update(T /*driveGain*/, T /*character*/, const AudioSpec& /*spec*/) noexcept {}
97
99 virtual typename Saturation<T>::Algorithm getType() const noexcept = 0;
100
110 void setAntialias(int order) noexcept { antialias_.store(std::clamp(order, 0, 2), std::memory_order_relaxed); }
111
122 void latchOrder(int commonDelay = 1) noexcept
123 {
124 const int o = antialias_.load(std::memory_order_relaxed);
125 if (o == 2 && order_ != 2) { armMask_ = ~0u; delayArm_ = ~0u; halfArm_ = ~0u; }
126 order_ = o;
127 delay_ = std::clamp(commonDelay, 1, kMaxDelay);
128 }
129
131 [[nodiscard]] int order() const noexcept { return order_; }
132
134 [[nodiscard]] int commonDelay() const noexcept { return delay_; }
135
137 T align(T y, int ch) noexcept { return delayBy(y, ch, delay_); }
138
140 T padKernel(T y, int ch) noexcept { return delay_ > 1 ? delayBy(y, ch, delay_ - 1) : y; }
141
142 static constexpr int kMaxDelay = 4;
143
144protected:
145 std::atomic<int> antialias_ { 0 };
146 int order_ = 0;
147 int delay_ = 1;
148 unsigned armMask_ = ~0u;
149 unsigned delayArm_ = ~0u;
150 unsigned halfArm_ = ~0u;
151
153 bool takeArm(int c) noexcept
154 {
155 const unsigned bit = 1u << (c & (kAaCh - 1));
156 if ((armMask_ & bit) == 0u) return false;
157 armMask_ &= ~bit;
158 return true;
159 }
160
162 T delayBy(T y, int ch, int n) noexcept
163 {
164 const auto c = static_cast<size_t>(ch & (kAaCh - 1));
165 auto& line = alignHold_[c];
166 const unsigned bit = 1u << c;
167 if (delayArm_ & bit) [[unlikely]]
168 {
169 delayArm_ &= ~bit;
170 line.fill(y);
171 }
172 const T out = line[static_cast<size_t>(n - 1)];
173 for (int k = kMaxDelay - 1; k > 0; --k) line[static_cast<size_t>(k)] = line[static_cast<size_t>(k - 1)];
174 line[0] = y;
175 return out;
176 }
177
185 T delayHalfSample(T y, int ch) noexcept
186 {
187 constexpr T kOuter = T(-0.0824), kInner = T(0.5824);
188 const auto c = static_cast<size_t>(ch & (kAaCh - 1));
189 auto& line = halfHold_[c];
190 const unsigned bit = 1u << c;
191 if (halfArm_ & bit) [[unlikely]]
192 {
193 halfArm_ &= ~bit;
194 line.fill(y);
195 }
196 const T out = kOuter * (y + line[2]) + kInner * (line[0] + line[1]);
197 line[2] = line[1];
198 line[1] = line[0];
199 line[0] = y;
200 return out;
201 }
202
203 void resetAlign() noexcept
204 {
205 for (auto& line : alignHold_) line.fill(T(0));
206 for (auto& line : halfHold_) line.fill(T(0));
207 armMask_ = ~0u;
208 delayArm_ = ~0u;
209 halfArm_ = ~0u;
210 }
211 std::array<std::array<T, kMaxDelay>, kAaCh> alignHold_ {};
212 std::array<std::array<T, 3>, kAaCh> halfHold_ {};
213};
214
215// -- SoftClip (tanh) ---------------------------------------------------------
216// The ADAA difference quotients below run in double whatever T is: the
217// antiderivative is O(1) while successive inputs can differ by 1e-5, so in
218// float the quotient kept only a few correct bits (measured on 20-200 Hz
219// tones: errors up to -48 dB re peak, spiking at every waveform crest).
220template <typename T>
221class TanhAlgorithm final : public SaturationAlgorithm<T>
222{
223 std::array<double, SaturationAlgorithm<T>::kAaCh> prevX_ {};
224 std::array<detail::Adaa2, SaturationAlgorithm<T>::kAaCh> adaa2_ {};
225 std::array<double, SaturationAlgorithm<T>::kAaCh> prevBias_ {};
226public:
227 void prepare(const AudioSpec&) noexcept override { reset(); }
228 void reset() noexcept override
229 {
230 prevX_.fill(0.0);
231 for (auto& a : adaa2_) a.reset();
232 prevBias_.fill(0.0);
233 this->resetAlign();
234 }
235 typename Saturation<T>::Algorithm getType() const noexcept override { return Saturation<T>::Algorithm::SoftClip; }
236
239 inline T processSecond(T sample, T drive, T character, int ch) noexcept
240 {
241 const T x = sample * drive;
242 const T bias = character * T(0.3);
243 const int c = ch & (SaturationAlgorithm<T>::kAaCh - 1);
244 // Second order on u = x + bias; the resting offset tanh(bias)
245 // is taken one sample back, where the output is centred.
246 const double u = static_cast<double>(x) + static_cast<double>(bias);
247 if (this->takeArm(c)) [[unlikely]]
248 {
249 adaa2_[static_cast<size_t>(c)].reset(u);
250 prevBias_[static_cast<size_t>(c)] = static_cast<double>(bias);
251 }
252 const double y = adaa2_[static_cast<size_t>(c)].template process<detail::AdaaTanh>(u);
253 const double tb = std::tanh(prevBias_[static_cast<size_t>(c)]);
254 prevBias_[static_cast<size_t>(c)] = static_cast<double>(bias);
255 prevX_[static_cast<size_t>(c)] = static_cast<double>(x);
256 return static_cast<T>(y - tb);
257 }
258
259 inline T processSample(T sample, T drive, T character, int ch) noexcept
260 {
261 T x = sample * drive;
262 T bias = character * T(0.3);
263 const int c = ch & (SaturationAlgorithm<T>::kAaCh - 1);
264 const int order = this->order_;
265 if (order == 0)
266 {
267 // Keep the ADAA history current, so enabling ADAA mid-stream
268 // starts from the real previous input (a stale one glitched).
269 prevX_[static_cast<size_t>(c)] = static_cast<double>(x);
270 return fastTanh(x + bias) - fastTanh(bias);
271 }
272
273 // ADAA of f(x) = tanh(x+bias) - tanh(bias); antiderivative log(cosh(x+bias)) - tanh(bias)*x.
274 const double xd = static_cast<double>(x);
275 const double b = static_cast<double>(bias);
276 const double x0 = prevX_[static_cast<size_t>(c)];
277 prevX_[static_cast<size_t>(c)] = xd;
278 const double tb = std::tanh(b);
279 const double dx = xd - x0;
280 if (std::abs(dx) > 1e-7)
281 return static_cast<T>((logCosh(xd + b) - logCosh(x0 + b)) / dx - tb);
282 return static_cast<T>(std::tanh(0.5 * (xd + x0) + b) - tb);
283 }
284};
285
286// -- Tube (12AX7-style asymmetric triode model) -----------------------------
287// A biased tanh, DC-free at rest and normalised to unit small-signal slope:
288// f(x) = (tanh(x + b) - tanh(b)) / (1 - tanh(b)^2). The bias moves the
289// operating point, so the curve is smooth everywhere and its even harmonics
290// grow with level as a triode's do. (The previous form switched between
291// tanh(x) and tanh(1.15 x) at x = 0: a slope kink that left a 2nd harmonic of
292// -30.6 dBc at every level down to -60 dBFS and aliased at -42.7 dBc at 2x.)
293// b = -0.7 * (asym - 1), asym = 1.15 + 0.5 * character, matches the former
294// 2nd harmonic at -6 dBFS; negative excursions still compress first.
295template <typename T>
296class TubeAlgorithm final : public SaturationAlgorithm<T>
297{
298 std::array<double, SaturationAlgorithm<T>::kAaCh> prevX_ {};
299 std::array<detail::Adaa2, SaturationAlgorithm<T>::kAaCh> adaa2_ {};
300 std::array<double, SaturationAlgorithm<T>::kAaCh> prevBias_ {};
301
302public:
303 void prepare(const AudioSpec&) noexcept override { reset(); }
304 void reset() noexcept override
305 {
306 prevX_.fill(0.0);
307 for (auto& a : adaa2_) a.reset();
308 prevBias_.fill(0.0);
309 this->resetAlign();
310 }
311 typename Saturation<T>::Algorithm getType() const noexcept override { return Saturation<T>::Algorithm::Tube; }
312
315 inline T processSecond(T sample, T drive, T character, int ch) noexcept
316 {
317 const T x = sample * drive;
318 const T b = T(-0.7) * (T(0.15) + character * T(0.5));
319 const int c = ch & (SaturationAlgorithm<T>::kAaCh - 1);
320 // Second order on u = x + b; offset and slope normalisation use
321 // the bias one sample back, where the output is centred.
322 const double u = static_cast<double>(x) + static_cast<double>(b);
323 if (this->takeArm(c)) [[unlikely]]
324 {
325 adaa2_[static_cast<size_t>(c)].reset(u);
326 prevBias_[static_cast<size_t>(c)] = static_cast<double>(b);
327 }
328 const double y = adaa2_[static_cast<size_t>(c)].template process<detail::AdaaTanh>(u);
329 const double tb = std::tanh(prevBias_[static_cast<size_t>(c)]);
330 prevBias_[static_cast<size_t>(c)] = static_cast<double>(b);
331 prevX_[static_cast<size_t>(c)] = static_cast<double>(x);
332 return static_cast<T>((y - tb) / (1.0 - tb * tb));
333 }
334
335 inline T processSample(T sample, T drive, T character, int ch) noexcept
336 {
337 const T x = sample * drive;
338 const T b = T(-0.7) * (T(0.15) + character * T(0.5));
339 const int c = ch & (SaturationAlgorithm<T>::kAaCh - 1);
340 const int order = this->order_;
341 if (order == 0)
342 {
343 prevX_[static_cast<size_t>(c)] = static_cast<double>(x);
344 const T tb = fastTanh(b);
345 return (fastTanh(x + b) - tb) / (T(1) - tb * tb);
346 }
347
348 // ADAA: antiderivative (log(cosh(x + b)) - tanh(b) * x) / (1 - tanh(b)^2).
349 const double xd = static_cast<double>(x);
350 const double bd = static_cast<double>(b);
351 const double tb = std::tanh(bd);
352 const double norm = 1.0 / (1.0 - tb * tb);
353 const double x0 = prevX_[static_cast<size_t>(c)];
354 prevX_[static_cast<size_t>(c)] = xd;
355 const double dx = xd - x0;
356 if (std::abs(dx) > 1e-7)
357 return static_cast<T>(((logCosh(xd + bd) - logCosh(x0 + bd)) / dx - tb) * norm);
358 return static_cast<T>((std::tanh(0.5 * (xd + x0) + bd) - tb) * norm);
359 }
360};
361
362// -- HardClip ----------------------------------------------------------------
363// First-order ADAA over every sample, in double. (A "linear body" shortcut
364// used to pass unclipped pairs through un-averaged: it switched between a 0
365// and a 0.5 sample delay at every clip edge, and that made the antialiased
366// path alias MORE than the plain one, e.g. -51.6 vs -135.2 dBc at 2x, +6 dB.)
367template <typename T>
369{
370 std::array<double, SaturationAlgorithm<T>::kAaCh> prevX_ {};
371 std::array<detail::Adaa2, SaturationAlgorithm<T>::kAaCh> adaa2_ {};
372 std::array<double, SaturationAlgorithm<T>::kAaCh> prevBias_ {};
373
375 static inline double g(double u) noexcept
376 {
377 const double a = std::abs(u);
378 return (a <= 1.0) ? 0.5 * u * u : a - 0.5;
379 }
380public:
381 void prepare(const AudioSpec&) noexcept override { reset(); }
382 void reset() noexcept override
383 {
384 prevX_.fill(0.0);
385 for (auto& a : adaa2_) a.reset();
386 prevBias_.fill(0.0);
387 this->resetAlign();
388 }
389 typename Saturation<T>::Algorithm getType() const noexcept override { return Saturation<T>::Algorithm::HardClip; }
390
393 inline T processSecond(T sample, T drive, T character, int ch) noexcept
394 {
395 const T bias = character * T(0.3);
396 const T d = sample * drive;
397 const int c = ch & (SaturationAlgorithm<T>::kAaCh - 1);
398 // Exact second-order kernel (Core/detail/Adaa.h) on u = d + bias.
399 const double u = static_cast<double>(d) + static_cast<double>(bias);
400 if (this->takeArm(c)) [[unlikely]]
401 {
402 adaa2_[static_cast<size_t>(c)].reset(u);
403 prevBias_[static_cast<size_t>(c)] = static_cast<double>(bias);
404 }
405 const double y = adaa2_[static_cast<size_t>(c)].template process<detail::AdaaHardClip>(u);
406 const double cbPrev = std::clamp(prevBias_[static_cast<size_t>(c)], -1.0, 1.0);
407 prevBias_[static_cast<size_t>(c)] = static_cast<double>(bias);
408 prevX_[static_cast<size_t>(c)] = static_cast<double>(d);
409 return static_cast<T>(y - cbPrev);
410 }
411
412 inline T processSample(T sample, T drive, T character, int ch) noexcept
413 {
414 const T bias = character * T(0.3);
415 const T cb = std::clamp(bias, T(-1), T(1));
416 const T d = sample * drive;
417 const int c = ch & (SaturationAlgorithm<T>::kAaCh - 1);
418 const int order = this->order_;
419 if (order == 0)
420 {
421 prevX_[static_cast<size_t>(c)] = static_cast<double>(d);
422 return std::clamp(d + bias, T(-1), T(1)) - cb;
423 }
424
425 const double dd = static_cast<double>(d), b = static_cast<double>(bias);
426 const double d0 = prevX_[static_cast<size_t>(c)];
427 prevX_[static_cast<size_t>(c)] = dd;
428 const double u = dd + b, u0 = d0 + b, diff = dd - d0;
429 if (std::abs(diff) > 1e-7)
430 return static_cast<T>((g(u) - g(u0)) / diff - static_cast<double>(cb));
431 return static_cast<T>(std::clamp(0.5 * (u + u0), -1.0, 1.0) - static_cast<double>(cb));
432 }
433};
434
435// -- Exciter (polynomial waveshaper) -----------------------------------------
436
452{
453 static constexpr double kB = 0.15, kLimit = 10.0;
454
455 double A = 0.0;
456 double crit[2] = { 0.0, 0.0 };
457 double critValue[2] = { 0.0, 0.0 };
458
459 void setCharacter(double a) noexcept
460 {
461 if (a == A && critValue[1] != 0.0) return;
462 A = a;
463 const double r = std::sqrt(A * A + 3.0 * kB);
464 crit[0] = (A - r) / (3.0 * kB);
465 crit[1] = (A + r) / (3.0 * kB);
466 critValue[0] = p(crit[0]);
467 critValue[1] = p(crit[1]);
468 }
469
470 [[nodiscard]] double p(double u) const noexcept { return u * (1.0 + u * (A - kB * u)); }
471 [[nodiscard]] double f(double u) const noexcept
472 {
473 return std::clamp(p(std::clamp(u, -kLimit, kLimit)), -1.0, 1.0);
474 }
475
477 [[nodiscard]] double average(double u0, double u1, double u2) const noexcept
478 {
479 double lo = u0, mid = u1, hi = u2;
480 if (lo > mid) std::swap(lo, mid);
481 if (mid > hi) std::swap(mid, hi);
482 if (lo > mid) std::swap(lo, mid);
483 const double span = hi - lo;
484 if (!(span > 1e-9)) return f((u0 + u1 + u2) * (1.0 / 3.0));
485 if (lo >= -kLimit && hi <= kLimit)
486 {
487 double top = std::max(p(lo), p(hi)), bottom = std::min(p(lo), p(hi));
488 for (int k = 0; k < 2; ++k)
489 if (crit[k] > lo && crit[k] < hi)
490 {
491 top = std::max(top, critValue[k]);
492 bottom = std::min(bottom, critValue[k]);
493 }
494 if (top <= 1.0 && bottom >= -1.0)
495 {
496 // E[u^k] = 2 h_k / ((k + 1)(k + 2)) for the complete symmetric h_k.
497 const double h1 = u0 + u1 + u2;
498 const double h2 = u0 * u0 + u1 * u1 + u2 * u2 + u0 * u1 + u1 * u2 + u0 * u2;
499 const double h3 = u0 * u0 * u0 + u1 * u1 * u1 + u2 * u2 * u2
500 + u0 * u0 * (u1 + u2) + u1 * u1 * (u0 + u2) + u2 * u2 * (u0 + u1)
501 + u0 * u1 * u2;
502 return h1 * (1.0 / 3.0) + A * h2 * (1.0 / 6.0) - kB * h3 * (1.0 / 10.0);
503 }
504 if (bottom >= 1.0) return 1.0;
505 if (top <= -1.0) return -1.0;
506 }
507
508 // General case: break points inside (lo, hi), at most 1 + 2 + 6.
509 double cuts[12];
510 int n = 0;
511 cuts[n++] = lo;
512 cuts[n++] = mid;
513 for (const double edge : { -kLimit, kLimit })
514 if (edge > lo && edge < hi) cuts[n++] = edge;
515 const double a = std::max(lo, -kLimit), b = std::min(hi, kLimit);
516 if (a < b)
517 {
518 double piece[4] = { a, 0.0, 0.0, 0.0 };
519 int pieces = 1;
520 for (int k = 0; k < 2; ++k)
521 if (crit[k] > a && crit[k] < b) piece[pieces++] = crit[k];
522 piece[pieces] = b;
523 for (int k = 0; k < pieces; ++k)
524 for (const double level : { -1.0, 1.0 })
525 {
526 double s = piece[k], e = piece[k + 1];
527 double fs = p(s) - level, fe = p(e) - level;
528 if (!(fs * fe < 0.0)) continue;
529 double t = s + (e - s) * fs / (fs - fe);
530 for (int it = 0; it < 60; ++it)
531 {
532 const double ft = p(t) - level;
533 if (ft == 0.0) break;
534 if ((ft < 0.0) == (fs < 0.0)) { s = t; fs = ft; } else { e = t; fe = ft; }
535 const double slope = 1.0 + t * (2.0 * A - 3.0 * kB * t);
536 double next = t - ft / slope;
537 if (!(next > s && next < e)) next = 0.5 * (s + e);
538 if (std::abs(next - t) <= 1e-15 * (1.0 + std::abs(t))) { t = next; break; }
539 t = next;
540 }
541 if (t > lo && t < hi) cuts[n++] = t;
542 }
543 }
544 cuts[n++] = hi;
545 for (int k = 1; k < n; ++k) // insertion sort: at most 11 points
546 for (int j = k; j > 0 && cuts[j - 1] > cuts[j]; --j) std::swap(cuts[j - 1], cuts[j]);
547
548 // Linear weight: rising on [lo, mid], falling on [mid, hi]; a side
549 // narrower than 1e-12 of the span carries no measurable mass.
550 const bool rising = mid - lo > 1e-12 * span, falling = hi - mid > 1e-12 * span;
551 const double riseSlope = rising ? 2.0 / (span * (mid - lo)) : 0.0;
552 const double fallSlope = falling ? -2.0 / (span * (hi - mid)) : 0.0;
553 double sum = 0.0;
554 for (int k = 0; k + 1 < n; ++k)
555 {
556 const double s = cuts[k], e = cuts[k + 1];
557 if (!(e > s)) continue;
558 const double c = 0.5 * (s + e), hh = 0.5 * (e - s);
559 const bool up = c < mid;
560 if ((up && !rising) || (!up && !falling)) continue;
561 const double w0 = up ? riseSlope * (c - lo) : -fallSlope * (hi - c);
562 const double w1 = up ? riseSlope : fallSlope;
563 double g0, g1 = 0.0, g2 = 0.0, g3 = 0.0;
564 if (std::abs(c) > kLimit) g0 = f(c);
565 else
566 {
567 g0 = p(c);
568 if (g0 > 1.0 || g0 < -1.0) g0 = g0 > 1.0 ? 1.0 : -1.0;
569 else
570 {
571 g1 = 1.0 + c * (2.0 * A - 3.0 * kB * c);
572 g2 = A - 3.0 * kB * c;
573 g3 = -kB;
574 }
575 }
576 const double h3 = hh * hh * hh;
577 sum += 2.0 * hh * g0 * w0 + (2.0 / 3.0) * h3 * (g2 * w0 + g1 * w1)
578 + 0.4 * h3 * hh * hh * g3 * w1;
579 }
580 return sum;
581 }
582};
583
584template <typename T>
586{
587 std::array<double, SaturationAlgorithm<T>::kAaCh> u1_ {}, u2_ {};
588 AdaaExciter curve_;
589
590public:
591 void prepare(const AudioSpec&) noexcept override { reset(); }
592 typename Saturation<T>::Algorithm getType() const noexcept override { return Saturation<T>::Algorithm::Exciter; }
593
594 void reset() noexcept override
595 {
596 u1_.fill(0.0);
597 u2_.fill(0.0);
598 this->resetAlign();
599 }
600
603 inline T processSecond(T sample, T drive, T character, int ch) noexcept
604 {
605 const double u = static_cast<double>(sample) * static_cast<double>(drive);
606 const auto c = static_cast<size_t>(ch & (SaturationAlgorithm<T>::kAaCh - 1));
607 if (this->takeArm(static_cast<int>(c))) [[unlikely]] u1_[c] = u2_[c] = u;
608 curve_.setCharacter(0.25 * static_cast<double>(character));
609 const double y = curve_.average(u, u1_[c], u2_[c]);
610 u2_[c] = u1_[c];
611 u1_[c] = u;
612 return static_cast<T>(y);
613 }
614
615 inline T processSample(T sample, T drive, T character, int) noexcept
616 {
617 T x = std::clamp(sample * drive, T(-10), T(10));
618 T x2 = x * x;
619 T x3 = x2 * x;
620 T result = x + character * T(0.25) * x2 - T(0.15) * x3;
621 return std::clamp(result, T(-1), T(1));
622 }
623};
624
625// -- Wavefolder (sin + first-order ADAA) -------------------------------------
626template <typename T>
628{
629 static constexpr int kMaxCh = 16;
630 std::array<T, kMaxCh> lastX_ {};
631 std::array<detail::Adaa2, kMaxCh> adaa2_ {};
632 std::array<double, kMaxCh> prevBias_ {};
633
634public:
635 void prepare(const AudioSpec&) noexcept override { reset(); }
636 void reset() noexcept override
637 {
638 lastX_.fill(T(0));
639 for (auto& a : adaa2_) a.reset();
640 prevBias_.fill(0.0);
641 this->resetAlign();
642 }
643 typename Saturation<T>::Algorithm getType() const noexcept override { return Saturation<T>::Algorithm::Wavefolder; }
644
658 inline T processSecond(T sample, T drive, T character, int ch) noexcept
659 {
660 const T bias = character * (pi<T> / T(4));
661 const T x = sample * drive + bias;
662 const int c = ch & (kMaxCh - 1);
663 // Second order on sin (antiderivatives -cos, -sin); the resting
664 // offset sin(bias) is taken one sample back, at the centre.
665 if (this->takeArm(c)) [[unlikely]]
666 {
667 adaa2_[static_cast<size_t>(c)].reset(static_cast<double>(x));
668 prevBias_[static_cast<size_t>(c)] = static_cast<double>(bias);
669 }
670 const double y = adaa2_[static_cast<size_t>(c)].template process<detail::AdaaSine>(static_cast<double>(x));
671 const double sbPrev = std::sin(prevBias_[static_cast<size_t>(c)]);
672 prevBias_[static_cast<size_t>(c)] = static_cast<double>(bias);
673 lastX_[static_cast<size_t>(c)] = x;
674 return static_cast<T>(y - sbPrev);
675 }
676
677 inline T processSample(T sample, T drive, T character, int ch) noexcept
678 {
679 const T bias = character * (pi<T> / T(4));
680 const T x = sample * drive + bias;
681 const int c = ch & (kMaxCh - 1);
682 const T sb = std::sin(bias);
683
684 // Mean of sin over [x0, x], (cos x0 - cos x) / (x - x0), written as
685 // sin(mid) * sinc(half) via the sum-to-product identity: exact, with
686 // no cancellation (the difference of cosines lost most of its digits
687 // in float whenever consecutive inputs were close).
688 const T half = T(0.5) * (x - lastX_[static_cast<size_t>(c)]);
689 const T mid = T(0.5) * (x + lastX_[static_cast<size_t>(c)]);
690 const T sinc = (std::abs(half) > T(1e-4)) ? std::sin(half) / half
691 : T(1) - half * half / T(6);
692 lastX_[static_cast<size_t>(c)] = x;
693 return std::sin(mid) * sinc - sb;
694 }
695};
696
697// -- Bitcrusher (TPDF dither) ------------------------------------------------
698template <typename T>
700{
701 // Per-sample TPDF dither needs a true white PRNG. (The previous
702 // AnalogRandom-based source was a 1 Hz sample-and-hold: two consecutive
703 // reads were almost always identical, so the dither was effectively zero
704 // and the crusher truncated with audible quantisation distortion.)
705 uint32_t rngState_ = 0x9E3779B9u;
706 T steps_ = T(1);
707 T invSteps_ = T(1);
708
709 [[nodiscard]] inline T nextRandom() noexcept
710 {
711 rngState_ ^= rngState_ << 13;
712 rngState_ ^= rngState_ >> 17;
713 rngState_ ^= rngState_ << 5;
714 constexpr T scale = T(1) / static_cast<T>(0xFFFFFFFFu);
715 return static_cast<T>(rngState_) * scale - T(0.5);
716 }
717
718public:
719 void prepare(const AudioSpec&) noexcept override
720 {
721 if (rngState_ == 0) rngState_ = 1; // xorshift fixed point guard
722 }
723 void reset() noexcept override { this->resetAlign(); }
724 typename Saturation<T>::Algorithm getType() const noexcept override { return Saturation<T>::Algorithm::Bitcrusher; }
725
726 void update(T drive, T /*character*/, const AudioSpec&) noexcept override
727 {
728 T clamped = std::clamp(drive, T(1), T(100));
729 T bitDepth = mapRange(clamped, T(1), T(100), T(16), T(2));
730 steps_ = std::pow(T(2), bitDepth);
731 invSteps_ = T(1) / steps_;
732 }
733
734 inline T processSample(T sample, T, T, int) noexcept
735 {
736 // True TPDF: difference of two independent uniforms, +-1 LSB peak.
737 T dither = (nextRandom() - nextRandom()) * invSteps_;
738 return invSteps_ * std::round((sample + dither) * steps_);
739 }
740};
741
742// -- Tape second-order kernel -------------------------------------------------
743
766{
767public:
769 static const AdaaTapeTable& instance()
770 {
771 static const AdaaTapeTable table;
772 return table;
773 }
774
776 static void langevin(double x, double& L, double& Lp) noexcept
777 {
778 if (x < kStart)
779 {
780 const double u = x * x;
781 double l = kL[12], lp = kLp[12];
782 for (int n = 11; n >= 0; --n) { l = l * u + kL[n]; lp = lp * u + kLp[n]; }
783 L = x * l;
784 Lp = lp;
785 return;
786 }
787 const double e = std::exp(-2.0 * x), om = 1.0 - e;
788 L = (1.0 + e) / om - 1.0 / x;
789 Lp = 1.0 / (x * x) - 4.0 * e / (om * om);
790 }
791
793 void antiderivatives(double x, double L, double& G, double& P, double& Q) const noexcept
794 {
795 if (x < kStart)
796 {
797 const double u = x * x, x3 = u * x;
798 double g = kG[12], pp = kP[12], q = kQ[12];
799 for (int n = 11; n >= 0; --n) { g = g * u + kG[n]; pp = pp * u + kP[n]; q = q * u + kQ[n]; }
800 G = u * g;
801 P = x3 * pp;
802 Q = x3 * q;
803 return;
804 }
805 G = x + std::log((1.0 - std::exp(-2.0 * x)) / (2.0 * x));
806 double a = 0.0, b = 0.0;
807 if (x < kEnd)
808 {
809 // Eight cells per octave: exponent and top three mantissa bits.
810 const auto k = static_cast<size_t>((std::bit_cast<std::uint64_t>(x) >> 49) - kFirstCell);
811 const double t = (x - mid_[k]) * invHalf_[k];
812 a = clenshaw(a_[k], t);
813 b = clenshaw(b_[k], t);
814 }
815 P = x * (1.0 + G) - 0.5 * x * x - kPiSquaredOver12 + a;
816 Q = x - L - 2.0 * ((x - G) - kLn2 + 1.0 / x + cR_ + b);
817 }
818
819private:
820 static constexpr int kDeg = 11, kCells = 48;
821 static constexpr double kStart = 0.5, kEnd = 32.0;
822 static constexpr std::uint64_t kFirstCell = 0x1FF0u; // bits(0.5) >> 49
823 static constexpr double kPiSquaredOver12 = 0.82246703342411321824;
824 static constexpr double kLn2 = 0.69314718055994530942;
825 // Taylor coefficients in u = x^2 (from the Bernoulli numbers): L = x sum
826 // kL u^n, its slope sum kLp u^n, G = u sum kG u^n, P = x^3 sum kP u^n,
827 // Q = x^3 sum kQ u^n. Thirteen terms reach rounding below x = 0.5.
828 static constexpr double kL[13] = { 0.3333333333333333, -0.022222222222222223, 0.0021164021164021165,
829 -0.00021164021164021165, 2.1377799155576935e-05, -2.1644042808063972e-06, 2.1925947851873778e-07,
830 -2.2214608789979678e-08, 2.2507846516808994e-09, -2.2805151204592183e-10, 2.3106432599002624e-11,
831 -2.3411706819824882e-12, 2.3721017400233653e-13 };
832 static constexpr double kLp[13] = { 0.3333333333333333, -0.06666666666666667, 0.010582010582010581,
833 -0.0014814814814814814, 0.0001924001924001924, -2.380844708887037e-05, 2.8503732207435913e-06,
834 -3.332191318496952e-07, 3.8263339078575285e-08, -4.332978728872515e-09, 4.852350845790551e-10,
835 -5.3846925685597234e-11, 5.930254350058414e-12 };
836 static constexpr double kG[13] = { 0.16666666666666666, -0.005555555555555556, 0.0003527336860670194,
837 -2.6455026455026456e-05, 2.1377799155576935e-06, -1.803670234005331e-07, 1.5661391322766983e-08,
838 -1.3884130493737299e-09, 1.2504359176004997e-10, -1.1402575602296091e-11, 1.0502923908637557e-12,
839 -9.754877841593701e-14, 9.123468230859098e-15 };
840 static constexpr double kP[13] = { 0.05555555555555555, -0.0011111111111111111, 5.039052658100277e-05,
841 -2.9394473838918285e-06, 1.9434362868706303e-07, -1.3874386415425623e-08, 1.0440927548511323e-09,
842 -8.167135584551352e-11, 6.581241671581577e-12, -5.429797905855281e-13, 4.5664886559293725e-14,
843 -3.9019511366374804e-15, 3.379062307725592e-16 };
844 static constexpr double kQ[13] = { 0.037037037037037035, -0.002962962962962963, 0.00027210884353741496,
845 -2.6128421190149586e-05, 2.5579323318621057e-06, -2.5299170598315896e-07, 2.5176556628643635e-08,
846 -2.5155828459962992e-09, 2.520569343665452e-10, -2.5307045227479064e-11, 2.5447507412853134e-12,
847 -2.5618698792252346e-13, 2.5814742395034203e-14 };
848
849 using Row = std::array<double, kDeg + 1>;
850
851 static double clenshaw(const Row& c, double t) noexcept
852 {
853 double b1 = 0.0, b2 = 0.0;
854 const double t2 = 2.0 * t;
855 for (int n = kDeg; n >= 1; --n)
856 {
857 const double b0 = c[static_cast<size_t>(n)] + t2 * b1 - b2;
858 b2 = b1;
859 b1 = b0;
860 }
861 return c[0] + t * b1 - b2;
862 }
863
865 static double e1(double z) noexcept
866 {
867 double b = z + 1.0, c = 1e300, d = 1.0 / b, h = d;
868 for (int i = 1; i < 300; ++i)
869 {
870 const double an = -static_cast<double>(i) * i;
871 b += 2.0;
872 d = 1.0 / (an * d + b);
873 c = b + an / c;
874 const double del = c * d;
875 h *= del;
876 if (std::abs(del - 1.0) < 4e-16) break;
877 }
878 return h * std::exp(-z);
879 }
880
882 static double tail(double x) noexcept
883 {
884 double t = 0.0;
885 for (int k = 1; k < 400; ++k)
886 {
887 const double v = e1(2.0 * k * x);
888 t += v;
889 if (v < 1e-25) break;
890 }
891 return 2.0 * t;
892 }
893
894 AdaaTapeTable()
895 {
896 for (int k = 0; k < kCells; ++k)
897 {
898 const double lo = std::ldexp(1.0 + (k % 8) / 8.0, k / 8 - 1);
899 const double hi = lo + std::ldexp(1.0 / 8.0, k / 8 - 1);
900 mid_[static_cast<size_t>(k)] = 0.5 * (lo + hi);
901 invHalf_[static_cast<size_t>(k)] = 2.0 / (hi - lo);
902 double av[kDeg + 1], bv[kDeg + 1];
903 for (int j = 0; j <= kDeg; ++j)
904 {
905 const double x = 0.5 * (lo + hi)
906 + 0.5 * (hi - lo) * std::cos(std::numbers::pi * (j + 0.5) / (kDeg + 1));
907 const double e = std::exp(-2.0 * x);
908 double li = 0.0, ek = e;
909 for (int m = 1; m < 400 && ek > 1e-26; ++m, ek *= e)
910 li += ek / (static_cast<double>(m) * m);
911 av[j] = 0.5 * li - x * std::log1p(-e);
912 bv[j] = std::log1p(-e) - tail(x);
913 }
914 for (int n = 0; n <= kDeg; ++n)
915 {
916 double sa = 0.0, sb = 0.0;
917 for (int j = 0; j <= kDeg; ++j)
918 {
919 const double w = std::cos(std::numbers::pi * n * (j + 0.5) / (kDeg + 1));
920 sa += av[j] * w;
921 sb += bv[j] * w;
922 }
923 a_[static_cast<size_t>(k)][static_cast<size_t>(n)] = (n == 0 ? 1.0 : 2.0) * sa / (kDeg + 1);
924 b_[static_cast<size_t>(k)][static_cast<size_t>(n)] = (n == 0 ? 1.0 : 2.0) * sb / (kDeg + 1);
925 }
926 }
927 // C = R(0.5) - ln 0.5 - 2 + T(0.5), R(0.5) = sum kL[n] 0.5^(2n+1) / (2n+1).
928 double r = 0.0;
929 for (int n = 12; n >= 0; --n) r = r * 0.25 + kL[n] / (2 * n + 1);
930 cR_ = 0.5 * r + kLn2 - 2.0 + tail(0.5);
931 }
932
933 std::array<Row, kCells> a_ {}, b_ {};
934 std::array<double, kCells> mid_ {}, invHalf_ {};
935 double cR_ = 0.0;
936};
937
950{
951 struct Point { double H = 0.0, x = 0.0, f = 0.0, fp = 0.0, F1 = 0.0, F2 = 0.0; };
952
953 const AdaaTapeTable* table = nullptr;
954 double alpha = -1.0, a = 1.0, rho = 0.0;
955 double h1 = 0.0, h2 = 0.0;
957
959 void reset(double u, double alphaIn) noexcept
960 {
961 h1 = h2 = u;
962 setCurve(alphaIn);
963 p1 = point(u, 3.0 * u);
964 p2 = p1;
965 }
966
968 double process(double H, double alphaIn) noexcept
969 {
970 if (alphaIn != alpha)
971 {
972 setCurve(alphaIn);
973 p1 = point(h1, p1.x);
974 p2 = point(h2, p2.x);
975 }
976 const Point p0 = point(H, p1.x);
977 const double y = average(p0, p1, p2);
978 p2 = p1;
979 p1 = p0;
980 h2 = h1;
981 h1 = H;
982 return y;
983 }
984
985 void setCurve(double alphaIn) noexcept
986 {
987 alpha = alphaIn;
988 a = 1.0 / (3.0 * (1.0 - alpha));
989 rho = alpha / (1.0 - alpha);
990 }
991
993 [[nodiscard]] Point point(double H, double seed) const noexcept
994 {
995 const double s = H < 0.0 ? -1.0 : 1.0, h = std::abs(H);
996 double x = std::max(0.0, s * seed), L = 0.0, Lp = 0.0;
997 for (int it = 0; it < 40; ++it)
998 {
999 AdaaTapeTable::langevin(x, L, Lp);
1000 const double step = (a * x - rho * L - h) / (a - rho * Lp);
1001 x = std::max(0.0, x - step);
1002 if (!(std::abs(step) > 1e-15 * (1.0 + x))) break;
1003 }
1004 AdaaTapeTable::langevin(x, L, Lp);
1005 double G = 0.0, P = 0.0, Q = 0.0;
1006 table->antiderivatives(x, L, G, P, Q);
1007 Point p;
1008 p.H = H;
1009 p.x = s * x;
1010 p.f = s * L;
1011 p.fp = Lp / (a - rho * Lp);
1012 p.F1 = a * G - 0.5 * rho * L * L;
1013 p.F2 = s * (a * a * P - a * rho * G * L + 0.5 * a * rho * Q + rho * rho * L * L * L * (1.0 / 6.0));
1014 return p;
1015 }
1016
1017 [[nodiscard]] static double div(const Point& p, const Point& q) noexcept
1018 {
1019 const double d = p.H - q.H;
1020 if (std::abs(d) > 3e-3) return (p.F2 - q.F2) / d;
1021 return 0.5 * (p.F1 + q.F1) - d * (p.f - q.f) * (1.0 / 12.0);
1022 }
1023
1024 [[nodiscard]] static double average(const Point& p0, const Point& p1, const Point& p2) noexcept
1025 {
1026 const double d02 = p0.H - p2.H;
1027 if (std::abs(d02) > 1e-3) return 2.0 * (div(p0, p1) - div(p1, p2)) / d02;
1028 // p0 and p2 merge into their mean b: F1, F2 and f at b from both sides.
1029 const double dd = 0.125 * d02 * d02;
1030 Point b;
1031 b.H = 0.5 * (p0.H + p2.H);
1032 b.fp = 0.5 * (p0.fp + p2.fp);
1033 b.f = 0.5 * (p0.f + p2.f);
1034 b.F1 = 0.5 * (p0.F1 + p2.F1) - dd * b.fp;
1035 b.F2 = 0.5 * (p0.F2 + p2.F2) - dd * b.f;
1036 const double e = b.H - p1.H;
1037 if (std::abs(e) > 1e-4) return 2.0 * (b.F1 - div(b, p1)) / e;
1038 return p1.f + p1.fp * ((p0.H + p1.H + p2.H) * (1.0 / 3.0) - p1.H);
1039 }
1040};
1041
1042// -- Tape (anhysteretic Langevin magnetisation + head bump + HF rolloff) -----
1043template <typename T>
1044class TapeAlgorithm final : public SaturationAlgorithm<T>
1045{
1046 static constexpr int kMaxCh = 16;
1047 std::array<Biquad<T, 1>, kMaxCh> preFilters_;
1048 std::array<Biquad<T, 1>, kMaxCh> postFilters_;
1049 std::array<T, kMaxCh> M_ {};
1050 std::array<AdaaTape, kMaxCh> kernel_ {};
1051 int numChannels_ = 0;
1052 T lastDrive_ = T(-1);
1053 double lastSampleRate_ = 0.0;
1054
1058 static inline T langevin(T x) noexcept
1059 {
1060 const T ax = std::abs(x);
1061 if (ax < T(0.5))
1062 {
1063 const T x2 = x * x;
1064 return x * (T(1) / T(3) - x2 * (T(1) / T(45) - x2 * (T(2) / T(945))));
1065 }
1066 if (ax > T(20)) return std::copysign(T(1), x) - T(1) / x;
1067 return T(1) / std::tanh(x) - T(1) / x;
1068 }
1069
1071 static inline T langevinDeriv(T x) noexcept
1072 {
1073 const T ax = std::abs(x);
1074 if (ax < T(0.5))
1075 {
1076 const T x2 = x * x;
1077 return T(1) / T(3) - x2 * (T(1) / T(15) - x2 * (T(2) / T(189)));
1078 }
1079 if (ax > T(20)) return T(1) / (x * x);
1080 const T s = std::sinh(x);
1081 return T(1) / (x * x) - T(1) / (s * s);
1082 }
1083
1084public:
1085 void prepare(const AudioSpec& spec) noexcept override
1086 {
1087 numChannels_ = std::min(spec.numChannels, kMaxCh); // clamp per-channel state
1088 for (auto& k : kernel_) k.table = &AdaaTapeTable::instance();
1089 // Invalidate the filter-design cache: a re-prepare can widen the
1090 // channel count at an unchanged rate/drive, and the new channels'
1091 // filters must still receive coefficients on the next update().
1092 lastDrive_ = T(-1);
1093 lastSampleRate_ = 0.0;
1094 reset();
1095 }
1096 void reset() noexcept override
1097 {
1098 for (auto& f : preFilters_) f.reset();
1099 for (auto& f : postFilters_) f.reset();
1100 M_.fill(T(0));
1101 this->resetAlign();
1102 }
1103 typename Saturation<T>::Algorithm getType() const noexcept override { return Saturation<T>::Algorithm::Tape; }
1104
1105 void update(T drive, T /*character*/, const AudioSpec& spec) noexcept override
1106 {
1107 // Both filters depend only on drive and sample rate; skip the
1108 // trig-heavy redesign when neither changed since the last block.
1109 if (drive == lastDrive_ && spec.sampleRate == lastSampleRate_) return;
1110 lastDrive_ = drive;
1111 lastSampleRate_ = spec.sampleRate;
1112
1113 auto driveDb = gainToDecibels(drive, T(-100));
1114 T bumpGain = T(1.5) + std::min(driveDb * T(0.05), T(3.0));
1115 auto peakCoeffs = BiquadCoeffs::makePeak(spec.sampleRate, 80.0, 0.6, static_cast<double>(bumpGain));
1116 auto lpFreq = std::max(6000.0, 19000.0 - static_cast<double>(driveDb) * 200.0);
1117 auto lpCoeffs = BiquadCoeffs::makeLowPass(spec.sampleRate, lpFreq, 0.55);
1118
1119 for (int ch = 0; ch < numChannels_; ++ch)
1120 {
1121 preFilters_[ch].setCoeffs(peakCoeffs);
1122 postFilters_[ch].setCoeffs(lpCoeffs);
1123 }
1124 }
1125
1141 inline T processSample(T sample, T drive, T character, int ch) noexcept
1142 {
1143 const T filtered = preFilters_[ch].processSample(sample, 0);
1144 const T H = filtered * drive;
1145
1146 // character (clamped [-1,1] upstream) sets the mean-field coupling:
1147 // harder knee and more mid-level bloom as alpha rises.
1148 const T alpha = T(0.35) + T(0.15) * character;
1149 const T a = T(1) / (T(3) * (T(1) - alpha));
1150 const T Ms = T(3) * a;
1151
1152 T M = M_[ch];
1153 for (int it = 0; it < 3; ++it)
1154 {
1155 const T x = (H + alpha * M) / a;
1156 const T f = M - Ms * langevin(x);
1157 const T fp = T(1) - T(3) * alpha * langevinDeriv(x);
1158 M -= f / fp;
1159 }
1160 M = std::clamp(M, -Ms, Ms);
1161 M_[ch] = M;
1162
1163 return postFilters_[ch].processSample((T(1) - alpha) * M, 0);
1164 }
1165
1169 inline T processSecond(T sample, T drive, T character, int ch) noexcept
1170 {
1171 const T filtered = preFilters_[ch].processSample(sample, 0);
1172 const double H = static_cast<double>(filtered) * static_cast<double>(drive);
1173 const T alpha = T(0.35) + T(0.15) * character;
1174 auto& k = kernel_[static_cast<size_t>(ch)];
1175 if (this->takeArm(ch)) [[unlikely]] k.reset(H, static_cast<double>(alpha));
1176 const double y = k.process(H, static_cast<double>(alpha));
1177 M_[ch] = static_cast<T>(k.p1.f / (1.0 - k.alpha)); // M = Ms L, Ms = 1 / (1 - alpha)
1178 return postFilters_[ch].processSample(static_cast<T>(y), 0);
1179 }
1180};
1181
1182// -- Transformer (frequency-dependent: heavy LF, light HF) ------------------
1183template <typename T>
1185{
1186 static constexpr int kMaxCh = 16;
1187 std::array<Biquad<T, 1>, kMaxCh> lpFilters_;
1188 std::array<detail::Adaa2, kMaxCh> adaaLow_ {}, adaaHigh_ {};
1189 std::array<double, kMaxCh> prevRestLow_ {}, prevRestHigh_ {};
1190 std::array<double, kMaxCh> firstLow_ {}, firstHigh_ {};
1191 std::array<double, kMaxCh> firstLowF_ {}, firstHighF_ {};
1192 int numChannels_ = 0;
1193 double lastSampleRate_ = 0.0;
1194
1195public:
1196 void prepare(const AudioSpec& spec) noexcept override
1197 {
1198 numChannels_ = std::min(spec.numChannels, kMaxCh); // clamp per-channel state
1199 lastSampleRate_ = 0.0; // force a redesign so channels added by a re-prepare get coefficients
1200 reset();
1201 }
1202 void reset() noexcept override
1203 {
1204 for (auto& f : lpFilters_) f.reset();
1205 for (auto& a : adaaLow_) a.reset();
1206 for (auto& a : adaaHigh_) a.reset();
1207 prevRestLow_.fill(0.0);
1208 prevRestHigh_.fill(0.0);
1209 firstLow_.fill(0.0);
1210 firstHigh_.fill(0.0);
1211 firstLowF_.fill(0.0);
1212 firstHighF_.fill(0.0);
1213 this->resetAlign();
1214 }
1215 typename Saturation<T>::Algorithm getType() const noexcept override { return Saturation<T>::Algorithm::Transformer; }
1216
1217 void update(T /*drive*/, T /*character*/, const AudioSpec& spec) noexcept override
1218 {
1219 // The crossover is fixed at 250 Hz: only recompute when the effective
1220 // sample rate changes (update() runs every block from the pipeline).
1221 if (spec.sampleRate == lastSampleRate_) return;
1222 lastSampleRate_ = spec.sampleRate;
1223
1224 auto c = BiquadCoeffs::makeLowPass(spec.sampleRate, 250.0, 0.707);
1225 for (int ch = 0; ch < numChannels_; ++ch)
1226 lpFilters_[ch].setCoeffs(c);
1227 }
1228
1241 inline T processSecond(T sample, T drive, T character, int ch) noexcept
1242 {
1243 const T low = lpFilters_[ch].processSample(sample, 0);
1244 const T high = sample - low;
1245 const T bias = character * T(0.2);
1246 const T kLo = drive * T(1.4);
1247 const T kHi = drive * T(0.85);
1248 const auto c = static_cast<size_t>(ch & (kMaxCh - 1));
1249 // Second order on each band's tanh input; resting offsets one
1250 // sample back, where the outputs are centred.
1251 const double uLo = static_cast<double>((low + bias) * kLo);
1252 const double uHi = static_cast<double>((high + bias) * kHi);
1253 if (this->takeArm(static_cast<int>(c))) [[unlikely]]
1254 armSecond(c, uLo, uHi, bias, kLo, kHi);
1255 return static_cast<T>(secondBands(c, uLo, uHi, bias, kLo, kHi));
1256 }
1257
1261 inline void processBoth(T sample, T drive, T character, int ch, T& first, T& second) noexcept
1262 {
1263 const T low = lpFilters_[ch].processSample(sample, 0);
1264 const T high = sample - low;
1265 const T bias = character * T(0.2);
1266 const T kLo = drive * T(1.4);
1267 const T kHi = drive * T(0.85);
1268 const auto c = static_cast<size_t>(ch & (kMaxCh - 1));
1269 const double uLo = static_cast<double>((low + bias) * kLo);
1270 const double uHi = static_cast<double>((high + bias) * kHi);
1271 if (this->takeArm(static_cast<int>(c))) [[unlikely]]
1272 {
1273 armSecond(c, uLo, uHi, bias, kLo, kHi);
1274 armFirst(c, uLo, uHi);
1275 }
1276 first = static_cast<T>(firstBands(c, uLo, uHi, bias, kLo, kHi));
1277 second = static_cast<T>(secondBands(c, uLo, uHi, bias, kLo, kHi));
1278 }
1279
1280private:
1281 void armSecond(size_t c, double uLo, double uHi, T bias, T kLo, T kHi) noexcept
1282 {
1283 adaaLow_[c].reset(uLo);
1284 adaaHigh_[c].reset(uHi);
1285 prevRestLow_[c] = static_cast<double>(bias * kLo);
1286 prevRestHigh_[c] = static_cast<double>(bias * kHi);
1287 }
1288 void armFirst(size_t c, double uLo, double uHi) noexcept
1289 {
1290 firstLow_[c] = uLo;
1291 firstHigh_[c] = uHi;
1292 firstLowF_[c] = logCosh(uLo);
1293 firstHighF_[c] = logCosh(uHi);
1294 }
1295 double secondBands(size_t c, double uLo, double uHi, T bias, T kLo, T kHi) noexcept
1296 {
1297 const double yLo = adaaLow_[c].template process<detail::AdaaTanh>(uLo) - std::tanh(prevRestLow_[c]);
1298 const double yHi = adaaHigh_[c].template process<detail::AdaaTanh>(uHi) - std::tanh(prevRestHigh_[c]);
1299 prevRestLow_[c] = static_cast<double>(bias * kLo);
1300 prevRestHigh_[c] = static_cast<double>(bias * kHi);
1301 return yLo / 1.4 + yHi / 0.85;
1302 }
1305 double firstBands(size_t c, double uLo, double uHi, T bias, T kLo, T kHi) noexcept
1306 {
1307 const auto mean = [](double u, double u0, double f, double f0) noexcept {
1308 const double d = u - u0;
1309 return std::abs(d) > 1e-7 ? (f - f0) / d : std::tanh(0.5 * (u + u0));
1310 };
1311 const double fLo = logCosh(uLo), fHi = logCosh(uHi);
1312 const double yLo = mean(uLo, firstLow_[c], fLo, firstLowF_[c]) - std::tanh(static_cast<double>(bias * kLo));
1313 const double yHi = mean(uHi, firstHigh_[c], fHi, firstHighF_[c]) - std::tanh(static_cast<double>(bias * kHi));
1314 firstLow_[c] = uLo;
1315 firstHigh_[c] = uHi;
1316 firstLowF_[c] = fLo;
1317 firstHighF_[c] = fHi;
1318 return yLo / 1.4 + yHi / 0.85;
1319 }
1320
1321public:
1322
1327 inline T processFirst(T sample, T drive, T character, int ch) noexcept
1328 {
1329 const T low = lpFilters_[ch].processSample(sample, 0);
1330 const T high = sample - low;
1331 const T bias = character * T(0.2);
1332 const T kLo = drive * T(1.4);
1333 const T kHi = drive * T(0.85);
1334 const auto c = static_cast<size_t>(ch & (kMaxCh - 1));
1335 const double uLo = static_cast<double>((low + bias) * kLo);
1336 const double uHi = static_cast<double>((high + bias) * kHi);
1337 if (this->takeArm(static_cast<int>(c))) [[unlikely]]
1338 armFirst(c, uLo, uHi);
1339 return static_cast<T>(firstBands(c, uLo, uHi, bias, kLo, kHi));
1340 }
1341
1342 inline T processSample(T sample, T drive, T character, int ch) noexcept
1343 {
1344 const T low = lpFilters_[ch].processSample(sample, 0);
1345 const T high = sample - low;
1346 const T bias = character * T(0.2);
1347 const T kLo = drive * T(1.4);
1348 const T kHi = drive * T(0.85);
1349 const T satLow = (fastTanh((low + bias) * kLo) - fastTanh(bias * kLo)) / T(1.4);
1350 const T satHigh = (fastTanh((high + bias) * kHi) - fastTanh(bias * kHi)) / T(0.85);
1351 return satLow + satHigh;
1352 }
1353};
1354
1355// -- Downsample (sample rate reduction) --------------------------------------
1356template <typename T>
1358{
1359 static constexpr int kMaxCh = 16;
1360 std::array<Biquad<T, 1>, kMaxCh> aaFilters_;
1361 std::array<T, kMaxCh> lastSample_ {};
1362 std::array<int, kMaxCh> counter_ {};
1363 int numChannels_ = 0;
1364 int reduction_ = 1;
1365
1366public:
1367 void prepare(const AudioSpec& spec) noexcept override
1368 {
1369 numChannels_ = std::min(spec.numChannels, kMaxCh); // clamp per-channel state
1370 reset();
1371 }
1372 void reset() noexcept override
1373 {
1374 for (auto& f : aaFilters_) f.reset();
1375 lastSample_.fill(T(0));
1376 counter_.fill(0);
1377 this->resetAlign();
1378 }
1379 typename Saturation<T>::Algorithm getType() const noexcept override { return Saturation<T>::Algorithm::Downsample; }
1380
1381 void update(T drive, T, const AudioSpec& spec) noexcept override
1382 {
1383 T clamped = std::clamp(drive, T(1), T(100));
1384 reduction_ = std::max(1, static_cast<int>(mapRange(clamped, T(1), T(100), T(1), T(50))));
1385
1386 auto c = BiquadCoeffs::makeLowPass(spec.sampleRate, spec.sampleRate / (2.5 * reduction_), 0.707);
1387 for (int ch = 0; ch < numChannels_; ++ch)
1388 aaFilters_[ch].setCoeffs(c);
1389 }
1390
1391 inline T processSample(T sample, T, T, int ch) noexcept
1392 {
1393 T filtered = aaFilters_[ch].processSample(sample, 0);
1394 if (++counter_[ch] >= reduction_)
1395 {
1396 counter_[ch] = 0;
1397 lastSample_[ch] = filtered;
1398 }
1399 return lastSample_[ch];
1400 }
1401};
1402
1403// -- Curve (a family with three controls) -------------------------------------
1422template <typename T>
1424{
1425 std::atomic<T> hardness_ { T(0) }, curvature_ { T(1) }, asymmetry_ { T(0) };
1426 std::atomic<int> base_ { 0 };
1427 T knee_ = T(0), span_ = T(1), invSpan_ = T(1), power_ = T(1), invPower_ = T(1), negative_ = T(1), positive_ = T(1);
1428 int baseNow_ = 0;
1429
1430public:
1431 void prepare(const AudioSpec&) noexcept override {}
1432 void reset() noexcept override { this->resetAlign(); }
1433 typename Saturation<T>::Algorithm getType() const noexcept override { return Saturation<T>::Algorithm::Curve; }
1434
1436 void setShape(T hardness, T curvature, T asymmetry) noexcept
1437 {
1438 if (std::isfinite(hardness)) hardness_.store(std::clamp(hardness, T(0), T(0.95)), std::memory_order_relaxed);
1439 if (std::isfinite(curvature)) curvature_.store(std::clamp(curvature, T(0.5), T(4)), std::memory_order_relaxed);
1440 if (std::isfinite(asymmetry)) asymmetry_.store(std::clamp(asymmetry, T(-1), T(1)), std::memory_order_relaxed);
1441 }
1442 [[nodiscard]] T getHardness() const noexcept { return hardness_.load(std::memory_order_relaxed); }
1443 [[nodiscard]] T getCurvature() const noexcept { return curvature_.load(std::memory_order_relaxed); }
1444 [[nodiscard]] T getAsymmetry() const noexcept { return asymmetry_.load(std::memory_order_relaxed); }
1446 void setBase(int base) noexcept { base_.store(std::clamp(base, 0, 6), std::memory_order_relaxed); }
1447 [[nodiscard]] int getBase() const noexcept { return base_.load(std::memory_order_relaxed); }
1448
1449 void update(T, T, const AudioSpec&) noexcept override
1450 {
1451 baseNow_ = base_.load(std::memory_order_relaxed);
1452 knee_ = hardness_.load(std::memory_order_relaxed);
1453 span_ = T(1) - knee_;
1454 invSpan_ = T(1) / span_;
1455 power_ = curvature_.load(std::memory_order_relaxed);
1456 invPower_ = T(1) / power_;
1457 const T asym = asymmetry_.load(std::memory_order_relaxed);
1458 negative_ = (asym > T(0)) ? std::pow(T(2), asym) : T(1);
1459 positive_ = (asym < T(0)) ? std::pow(T(2), -asym) : T(1);
1460 }
1461
1471 [[nodiscard]] inline T bend(T v, bool negative) const noexcept
1472 {
1473 switch (baseNow_)
1474 {
1475 case 1: return v / std::sqrt(T(1) + v * v);
1476 case 2: return T(0.6366197723675814) * std::atan(T(1.5707963267948966) * v);
1477 case 3: return std::erf(T(0.886226925452758) * v);
1478 case 4: return v >= T(1.5) ? T(1) : v - T(4.0 / 27.0) * v * v * v;
1479 case 5: return negative ? v / std::sqrt(T(1) + v * v) : -std::expm1(-v);
1480 case 6: return negative ? std::tanh(v) * std::exp(-v) : std::tanh(v);
1481 default: return std::tanh(v);
1482 }
1483 }
1484
1486 [[nodiscard]] inline T shape(T x) const noexcept
1487 {
1488 const T side = (x < T(0)) ? negative_ : positive_;
1489 const T u = std::abs(x) * side;
1490 if (u <= knee_) return x;
1491 const T v = (u - knee_) * invSpan_;
1492 T bent;
1493 if (baseNow_ == 0) [[likely]]
1494 bent = (power_ == T(1)) ? std::tanh(v) : std::pow(std::tanh(std::pow(v, power_)), invPower_);
1495 else
1496 {
1497 const bool neg = x < T(0);
1498 bent = (power_ == T(1)) ? bend(v, neg) : std::pow(std::max(T(0), bend(std::pow(v, power_), neg)), invPower_);
1499 }
1500 return std::copysign((knee_ + span_ * bent) / side, x);
1501 }
1502
1503 inline T processSample(T sample, T drive, T, int) noexcept { return shape(sample * drive); }
1504};
1505
1506// -- MultiStage (Tube -> Tape -> Transformer cascade) -------------------------
1507template <typename T>
1509{
1510 TubeAlgorithm<T> tube_;
1511 TapeAlgorithm<T> tape_;
1513
1514public:
1515 void prepare(const AudioSpec& spec) noexcept override
1516 {
1517 tube_.prepare(spec);
1518 tape_.prepare(spec);
1519 xfmr_.prepare(spec);
1520 }
1521 void reset() noexcept override { tube_.reset(); tape_.reset(); xfmr_.reset(); this->resetAlign(); }
1522 typename Saturation<T>::Algorithm getType() const noexcept override { return Saturation<T>::Algorithm::MultiStage; }
1523
1525 static constexpr bool kSelfAligned = true;
1526
1527 void update(T drive, T character, const AudioSpec& spec) noexcept override
1528 {
1529 // The stages are private instances (not the pool's), so the owner's
1530 // setAntialiasing() never reaches them directly: forward the orders
1531 // that processSecond() needs for the common delay (see there).
1532 const bool second = this->order_ == 2;
1533 const int delay = this->delay_;
1534 tube_.setAntialias(second ? (delay == 2 || delay == 4 ? 1 : 2) : this->order_);
1535 tube_.latchOrder();
1536 tape_.setAntialias(second && delay >= 2 ? 2 : 0);
1537 tape_.latchOrder();
1538 xfmr_.setAntialias(second && delay >= 2 ? 2 : 0);
1539 xfmr_.latchOrder();
1540 tape_.update(drive * T(0.6), character, spec);
1541 xfmr_.update(drive * T(0.8), character, spec);
1542 }
1543
1544 inline T processSample(T sample, T drive, T character, int ch) noexcept
1545 {
1546 // Inter-stage makeup undoes each stage's fixed small-signal factor
1547 // (1/0.5, 1/0.6, 1/0.8) so the cascade is gain-staged: transparent
1548 // at neutral drive instead of a flat -15 dB drop, and every stage
1549 // keeps receiving a healthy level. (The last stage's 0.8 used to be
1550 // left in, a -1.9 dB loss that the old Tube curve's +0.6 dB kink gain
1551 // partly hid.)
1552 T tubeOut = tube_.processSample(sample, drive * T(0.5), character, ch) * T(2);
1553 T tapeOut = tape_.processSample(tubeOut, drive * T(0.6), character, ch) * (T(1) / T(0.6));
1554 return xfmr_.processSample(tapeOut, drive * T(0.8), character, ch) * (T(1) / T(0.8));
1555 }
1556
1588 inline T processSecond(T sample, T drive, T character, int ch) noexcept
1589 {
1590 const int delay = this->delay_;
1591 if (delay == 1)
1592 {
1593 T tubeOut = tube_.processSecond(sample, drive * T(0.5), character, ch) * T(2);
1594 T tapeOut = tape_.processSample(tubeOut, drive * T(0.6), character, ch) * (T(1) / T(0.6));
1595 return xfmr_.processSample(tapeOut, drive * T(0.8), character, ch) * (T(1) / T(0.8));
1596 }
1597 if (delay == 2)
1598 {
1599 T tubeOut = tube_.processSample(sample, drive * T(0.5), character, ch) * T(2);
1600 T tapeOut = tape_.processSecond(tubeOut, drive * T(0.6), character, ch) * (T(1) / T(0.6));
1601 return xfmr_.processFirst(tapeOut, drive * T(0.8), character, ch) * (T(1) / T(0.8));
1602 }
1603 if (delay == 4)
1604 {
1605 // Both transformer forms run on every sample, so the blend
1606 // between them never meets stale history.
1607 T tubeOut = tube_.processSample(sample, drive * T(0.5), character, ch) * T(2);
1608 T tapeOut = tape_.processSecond(tubeOut, drive * T(0.6), character, ch) * (T(1) / T(0.6));
1609 T first = T(0), second = T(0);
1610 xfmr_.processBoth(tapeOut, drive * T(0.8), character, ch, first, second);
1611 const T low = this->delayBy(first * (T(1) / T(0.8)), ch, 2);
1612 const T high = this->delayHalfSample(second * (T(1) / T(0.8)), ch);
1613 // Smoothstep in drive gain from +14 to +16 dB, where the two
1614 // chains alias alike; the blend is a sum of the two outputs, so
1615 // no component exceeds the larger of the two.
1616 constexpr T kFrom = T(5.011872336272722), kSpan = T(6.309573444801933 - 5.011872336272722);
1617 const T u = std::clamp((drive - kFrom) / kSpan, T(0), T(1));
1618 return low + (u * u * (T(3) - T(2) * u)) * (high - low);
1619 }
1620 T tubeOut = tube_.processSecond(sample, drive * T(0.5), character, ch) * T(2);
1621 T tapeOut = tape_.processSecond(tubeOut, drive * T(0.6), character, ch) * (T(1) / T(0.6));
1622 return xfmr_.processSecond(tapeOut, drive * T(0.8), character, ch) * (T(1) / T(0.8));
1623 }
1624};
1625
1626} // namespace detail
1627
1628// ============================================================================
1629// Saturation - Public API
1630// ============================================================================
1631
1632template <FloatType T, int MaxBands>
1633class MultibandSaturation;
1634
1651template <typename SampleType>
1653{
1654 static_assert(std::is_floating_point_v<SampleType>,
1655 "Saturation: SampleType must be float or double.");
1656
1657public:
1658 // -- Enums ---------------------------------------------------------------
1659
1663 enum class Algorithm
1664 {
1665 Tube,
1666 Tape,
1667 Transformer,
1668 SoftClip,
1669 HardClip,
1670 Exciter,
1671 Wavefolder,
1672 Bitcrusher,
1673 Downsample,
1674 MultiStage,
1675 Curve
1676 };
1677
1681
1683 {
1684 LinearPhase,
1686 };
1687
1690
1693
1695 enum class OutputMode { Normal, WetOnly, Delta };
1696
1731
1732 // -- Lifecycle -----------------------------------------------------------
1733
1735 {
1736 pool_[0] = std::make_unique<detail::TubeAlgorithm<SampleType>>();
1737 pool_[1] = std::make_unique<detail::TapeAlgorithm<SampleType>>();
1738 pool_[2] = std::make_unique<detail::TransformerAlgorithm<SampleType>>();
1739 pool_[3] = std::make_unique<detail::TanhAlgorithm<SampleType>>();
1740 pool_[4] = std::make_unique<detail::HardClipAlgorithm<SampleType>>();
1741 pool_[5] = std::make_unique<detail::ExciterAlgorithm<SampleType>>();
1742 pool_[6] = std::make_unique<detail::WavefolderAlgorithm<SampleType>>();
1743 pool_[7] = std::make_unique<detail::BitcrusherAlgorithm<SampleType>>();
1744 pool_[8] = std::make_unique<detail::DownsampleAlgorithm<SampleType>>();
1745 pool_[9] = std::make_unique<detail::MultiStageAlgorithm<SampleType>>();
1746 pool_[10] = std::make_unique<detail::CurveAlgorithm<SampleType>>();
1747
1748 active_.store(pool_[static_cast<int>(Algorithm::SoftClip)].get());
1749 next_.store(nullptr);
1750 }
1751
1752 ~Saturation() = default;
1753 Saturation(const Saturation&) = delete;
1755
1767 void prepare(const AudioSpec& spec)
1768 {
1769 if (!spec.isValid()) return;
1770 spec_ = spec;
1772 {
1774 if (automatic != oversamplingFactor_)
1775 {
1776 oversamplingFactor_ = automatic;
1777 oversampler_.reset(); // rebuilt below for the new factor
1778 }
1779 }
1780 for (auto& algo : pool_)
1781 if (algo) algo->prepare(spec);
1782
1783 preFilter_.reset();
1785 // Order 2 at 5 Hz: the same Butterworth design this stage always used,
1786 // now run in the double core (see DCBlocker.h). Prepared for the full
1787 // channel range so it covers every channel the pipeline touches, not
1788 // just the first eight.
1791 dryDc_.setOrder(2);
1793 dcStep_ = 1.0 / std::max(1.0, kDcFadeSeconds * spec.sampleRate);
1794 modeDipStep_ = 1.0 / std::max(1.0, kModeDipSeconds * spec.sampleRate);
1796 if (!tone_) tone_ = std::make_unique<BiquadCascade<SampleType, 4, 16>>();
1797 tone_->setNumSections(kToneSections);
1798 for (int s = 0; s < kToneSections; ++s) tone_->setSectionEnabled(s, false);
1799 toneLeft_.fill(-1);
1800 toneOn_ = false;
1801 toneDirty_.store(true, std::memory_order_release);
1802 designTone(0);
1804 dcShare_ = dcWanted_ ? 1.0 : 0.0;
1805 dcSnap_ = true;
1806 modeDipping_ = false;
1807 modeDip_ = 0.0;
1808 dryPre_.reset();
1809 dryPreLead_.prepare(spec.sampleRate, std::min(spec.numChannels, 8)); // as many as the pre-filter reaches
1811
1812 lastPreHpFreq_ = -1.0f;
1813 lastPostTiltFreq_ = -1.0f;
1814 lastPostTiltGain_ = std::numeric_limits<float>::quiet_NaN();
1815 dryWetMixer_.prepare(spec);
1816
1819 if (oversampler_) oversampler_->prepare(spec);
1820 prepareStages();
1821
1824 msKeepBuffer_.resize(1, spec.maxBlockSize * std::max(1, oversamplingFactor_));
1826 driveRamp_.assign(static_cast<size_t>(spec.maxBlockSize * std::max(1, oversamplingFactor_)), SampleType(1));
1827 charRamp_.assign(static_cast<size_t>(spec.maxBlockSize * std::max(1, oversamplingFactor_)), SampleType(0));
1828
1829 // Keep the dry path aligned with the (latent) oversampled wet path so the
1830 // dry/wet, Delta and adaptive-blend mixes do not comb-filter.
1831 alignDryPath();
1832
1833 // Base-rate smoothers (consumed once per base sample).
1834 auto sr = spec.sampleRate;
1835 mixSmoother_.reset(sr, 20.0f, 1.0f);
1836 preHpSmoother_.reset(sr, 30.0f, 0.707f, 20.0f);
1837 postTiltFreqSmoother_.reset(sr, 30.0f, 0.707f, 1000.0f);
1838 postTiltGainSmoother_.reset(sr, 30.0f, 0.0f);
1839 outputGainSmoother_.reset(sr, 20.0f, 0.0f);
1840 // Processing-rate state (drive, character, drift, crossfade).
1842
1843 // Re-apply the parameters: the smoother resets above restored the
1844 // defaults, and a second prepare() (a host re-activation) used to
1845 // drop every setting until the next setter (-9.8 dB measured for
1846 // drive +24, mix 0.5, output -6 while getState() still reported them).
1847 {
1848 Params pending;
1849 while (paramQueue_.pop(pending)) {}
1850 paramsPending_.store(false, std::memory_order_relaxed);
1851 Params current;
1852 {
1854 current = lastParams_;
1855 }
1856 applyParamSnapshot(current);
1857 }
1858
1859 reset();
1860 if (driveCompensation_.load(std::memory_order_relaxed)) prepareCalibrator();
1861 calibrate();
1863 calibrationWait_ = 0;
1864 prepared_ = true;
1865 }
1866
1873 void reset() noexcept
1874 {
1875 // Complete any pending algorithm switch instantly: every algorithm's
1876 // state is cleared below anyway, and after a reset the most recently
1877 // requested algorithm must be the one playing. (Leaving next_ armed
1878 // made a later request of that same algorithm a silent no-op.)
1879 if (auto* pending = next_.load())
1880 {
1881 active_.store(pending);
1882 next_.store(nullptr);
1883 }
1884
1885 for (auto& algo : pool_)
1886 if (algo) algo->reset();
1887
1888 preFilter_.reset();
1890 dcBlocker_.reset();
1892 dcSnap_ = true;
1893 if (tone_) tone_->reset();
1894 modeDipping_ = false;
1895 modeDip_ = 0.0;
1897 dryRunning_ = false;
1898 dryHoldSamples_ = 0;
1899 if (oversampler_) oversampler_->reset();
1900
1910
1911 prevBlendSample_.fill(SampleType(0));
1912 prevSlewSample_.fill(SampleType(0));
1913 alignFresh_ = true;
1914 dryPath_.reset();
1915 resetStages();
1916 }
1917
1918 // -- Audio Processing ----------------------------------------------------
1919
1925 void process(AudioBufferView<SampleType> buffer) noexcept { processBlock(buffer); }
1926
1939 void processBlock(AudioBufferView<SampleType> buffer) noexcept { processPieces(buffer, nullptr, false); }
1940
1941private:
1942 // MultibandSaturation takes the dry side of each band from here: it is
1943 // already as late as the band, behind its filters and in its phase.
1944 template <FloatType, int> friend class MultibandSaturation;
1945
1952 void processPieces(AudioBufferView<SampleType> buffer, const AudioBufferView<SampleType>* dryOut, bool dryTurn) noexcept
1953 {
1954 if (!prepared_) return;
1956
1957 // Blocks longer than the prepared maximum are processed in pieces
1958 // (the scratch buffers and the oversampler hold one maximum block).
1959 // The tuned feedback reads what left the curve one delay ago: a piece
1960 // is never longer than that delay.
1961 const int total = buffer.getNumSamples();
1962 maybeCalibrate(total);
1963 const int maxBlock = std::min(std::max(1, spec_.maxBlockSize), syncStages());
1964 for (int off = 0; off < total; off += maxBlock)
1965 {
1966 const int n = std::min(maxBlock, total - off);
1967 processChunk(buffer.getSubView(off, n), dryOut, off, dryTurn);
1968 }
1969 }
1970
1977 [[nodiscard]] static std::unique_ptr<Oversampling<SampleType>> makeOversampler(int factor, OversamplingMode mode,
1978 OversamplingBand band)
1979 {
1980 using Os = Oversampling<SampleType>;
1981 return std::make_unique<Os>(factor, Os::Quality::High,
1982 mode == OversamplingMode::MinimumPhase ? Os::Mode::PolyphaseIir
1983 : Os::Mode::LinearPhaseFir,
1984 factor >= 8 ? Os::Depth::Deep : Os::Depth::Preset, band);
1985 }
1986
1990 void alignDryPath()
1991 {
1992 const bool oversampled = oversampler_ && oversamplingFactor_ > 1;
1995 dryWetMixer_.setLatencyCompensation((oversampled && !dryThroughFilters_) ? oversampler_->getLatency() : 0);
1996 }
1997
2003 bool aimDryPhase(int samples, bool asked, bool askedTurn) noexcept
2004 {
2005 const float mix = mixSmoother_.getTargetValue();
2006 const bool normal = outputMode_ == OutputMode::Normal;
2007 const bool delta = outputMode_ == OutputMode::Delta;
2008 const bool heard = asked || delta || adaptiveBlend_.load(std::memory_order_relaxed) || (normal && mix < 1.0f);
2009 if (heard) dryHoldSamples_ = static_cast<int>(spec_.sampleRate * kDryHoldSeconds);
2010 const bool run = heard || dryHoldSamples_ > 0;
2011 if (!heard) dryHoldSamples_ = std::max(0, dryHoldSamples_ - samples);
2012
2013 const bool turn = (!normal || mix > 0.0f) && (!asked || askedTurn);
2014 dryPreLead_.aim(turn);
2015 dryDcLead_.aim(turn && dcWanted_);
2017 if (run && (!dryRunning_ || delta != dryExact_))
2018 {
2020 dryDcLead_.reset();
2021 dryPreLead_.land();
2022 dryDcLead_.land();
2023 dryPre_.reset();
2024 dryDc_.reset();
2025 }
2026 dryRunning_ = run;
2027 dryExact_ = delta;
2028 return run;
2029 }
2030
2031 void processChunk(AudioBufferView<SampleType> buffer, const AudioBufferView<SampleType>* dryOut = nullptr,
2032 int dryOffset = 0, bool dryTurn = false) noexcept
2033 {
2035 if (dcSnap_)
2036 {
2037 // The first block after prepare() or reset(): the filter as the
2038 // curve in play wants it, with nothing to fade from.
2039 dcSnap_ = false;
2040 dcShare_ = dcWanted_ ? 1.0 : 0.0;
2041 dcBlocker_.reset();
2042 dryDc_.reset();
2043 }
2044 {
2045 const SampleType pan = drivePan_.load(std::memory_order_relaxed);
2046 panning_ = pan != SampleType(0) || panNow_ != SampleType(0);
2047 if (panning_)
2048 {
2049 const auto gains = [](SampleType p) {
2050 const SampleType g = static_cast<SampleType>(std::pow(10.0, kDrivePanDb * static_cast<double>(p) / 20.0));
2051 return std::array<SampleType, 2> { SampleType(1) / g, g };
2052 };
2053 panFrom_ = gains(panNow_);
2054 panTo_ = gains(pan);
2055 panNow_ = pan;
2056 }
2057 }
2058 const bool dryWork = aimDryPhase(buffer.getNumSamples(), dryOut != nullptr, dryTurn);
2059 // Second-order antialiasing delays the wet path by whole base
2060 // samples (two at 2x, one otherwise; inside the algorithms and
2061 // padded after them); the dry capture and the untouched M/S
2062 // channel follow.
2063 const bool second = antialiasOrder_.load(std::memory_order_relaxed) == 2;
2064 if (second != secondActive_)
2065 {
2066 secondActive_ = second;
2067 alignFresh_ = true; // hold the first sample in the delay lines
2068 }
2069 const bool seed = second && alignFresh_;
2070 if (second) alignFresh_ = false;
2071 if (second)
2072 {
2073 const int nCh = std::min({buffer.getNumChannels(), dryAligned_.getNumChannels(), kMaxCh});
2074 const int nS = std::min(buffer.getNumSamples(), dryAligned_.getNumSamples());
2075 for (int ch = 0; ch < nCh; ++ch)
2076 {
2077 const SampleType* in = buffer.getChannel(ch);
2078 SampleType* out = dryAligned_.getChannel(ch);
2079 SampleType& hold = dryHold_[static_cast<size_t>(ch)];
2080 if (secondOrderBaseDelay() == 2)
2081 {
2082 SampleType& older = dryHold2_[static_cast<size_t>(ch)];
2083 if (seed && nS > 0) hold = older = in[0];
2084 for (int i = 0; i < nS; ++i)
2085 {
2086 out[i] = older;
2087 older = hold;
2088 hold = in[i];
2089 }
2090 continue;
2091 }
2092 if (seed && nS > 0) hold = in[0];
2093 for (int i = 0; i < nS; ++i)
2094 {
2095 out[i] = hold;
2096 hold = in[i];
2097 }
2098 }
2099 auto dryView = dryAligned_.toView().getSubView(0, nS);
2100 if (dryThroughFilters_) dryPath_.process(dryView);
2101 }
2102 else if (dryThroughFilters_ || dryWork)
2103 {
2104 const int nCh = std::min(buffer.getNumChannels(), dryAligned_.getNumChannels());
2105 const int nS = std::min(buffer.getNumSamples(), dryAligned_.getNumSamples());
2106 for (int ch = 0; ch < nCh; ++ch)
2107 std::memcpy(dryAligned_.getChannel(ch), buffer.getChannel(ch),
2108 static_cast<std::size_t>(nS) * sizeof(SampleType));
2109 if (dryThroughFilters_) dryPath_.process(dryAligned_.toView().getSubView(0, nS));
2110 }
2111 else
2112 {
2113 dryWetMixer_.pushDry(buffer);
2114 }
2115
2116 // Pre-filter
2117 {
2118 const int numSamples = buffer.getNumSamples();
2119 constexpr int kCoefRefresh = 16;
2120 for (int i = 0; i < numSamples; i += kCoefRefresh)
2121 {
2122 const int chunk = std::min(kCoefRefresh, numSamples - i);
2123 float curFreq = lastPreHpFreq_;
2124 for (int k = 0; k < chunk; ++k)
2125 curFreq = preHpSmoother_.getNextValue();
2126
2127 if (curFreq != lastPreHpFreq_)
2128 {
2129 auto c = BiquadCoeffs::makeHighPass(spec_.sampleRate, static_cast<double>(curFreq));
2131 dryPre_.setCoeffs(c);
2132 lastPreHpFreq_ = curFreq;
2133 }
2134 auto subView = buffer.getSubView(i, chunk);
2135 preFilter_.processBlock(subView);
2136 if (dryWork)
2137 {
2138 auto drySub = dryAligned_.toView().getSubView(i, chunk);
2139 if (dryExact_)
2140 {
2141 // Delta is what the curve adds: the dry copy crosses
2142 // the very filters the wet side does.
2143 dryPre_.processBlock(drySub);
2144 continue;
2145 }
2146 dryPreLead_.setCorner(detail::DryPhase::kButterworthShare * static_cast<double>(curFreq));
2147 dryPreLead_.process(drySub);
2148 dryDcLead_.process(drySub);
2149 }
2150 }
2151 }
2152 if (second || dryThroughFilters_ || dryWork)
2153 {
2154 auto dryView = dryAligned_.toView().getSubView(0, std::min(buffer.getNumSamples(), dryAligned_.getNumSamples()));
2155 if (dryWork && dryExact_ && (dcShare_ > 0.0 || dcWanted_)) applyDcShare(dryDc_, dryView, dcShare_);
2156 dryWetMixer_.pushDry(dryView);
2157 }
2158 if (dryOut != nullptr)
2159 {
2160 const int channels = std::min({ buffer.getNumChannels(), dryOut->getNumChannels(), dryWetMixer_.getDryNumChannels() });
2161 const int samples = std::min(buffer.getNumSamples(), dryWetMixer_.getDryCapturedSamples());
2162 for (int ch = 0; ch < channels; ++ch)
2163 std::copy_n(dryWetMixer_.getDryChannel(ch), samples, dryOut->getChannel(ch) + dryOffset);
2164 }
2165
2166 const bool isMidSide = (procMode_ == ProcessingMode::MidOnly || procMode_ == ProcessingMode::SideOnly || procMode_ == ProcessingMode::MidSide) && buffer.getNumChannels() == 2;
2167 if (isMidSide) MidSide<SampleType>::encode(buffer);
2168
2169 // MidOnly / SideOnly: snapshot the channel that must stay UNPROCESSED
2170 // and restore it after the saturation pipeline. The snapshot lives in
2171 // the SAME domain the pipeline runs in (oversampled when OS is active),
2172 // so the restored channel shares the wet path's half-band round-trip
2173 // and group delay - perfectly time-aligned with the processed channel.
2174 // (The old in-pipeline routing read the DryWetMixer's base-rate L/R
2175 // capture from inside the oversampled loop: wrong domain AND an
2176 // out-of-bounds read, caught by AddressSanitizer.)
2177 const int keepChannel =
2178 (isMidSide && procMode_ == ProcessingMode::MidOnly) ? 1 :
2179 (isMidSide && procMode_ == ProcessingMode::SideOnly) ? 0 : -1;
2180
2181 // The stages around the curve, in the domain the curve works in and
2182 // away from the channel that stays unprocessed.
2183 if (stagesOn_) stagesBefore(buffer, keepChannel);
2184
2186 {
2187 auto upView = oversampler_->upsample(buffer);
2188
2189 const int upSamples = std::min(upView.getNumSamples(), msKeepBuffer_.getNumSamples());
2190 if (keepChannel >= 0 && keepChannel < upView.getNumChannels() && upSamples > 0)
2191 std::memcpy(msKeepBuffer_.getChannel(0), upView.getChannel(keepChannel),
2192 static_cast<std::size_t>(upSamples) * sizeof(SampleType));
2193
2195 if (second)
2196 alignSecondOrder(upView, keepChannel, upSamples, oversamplingFactor_, seed);
2197
2198 if (keepChannel >= 0 && keepChannel < upView.getNumChannels() && upSamples > 0)
2199 std::memcpy(upView.getChannel(keepChannel), msKeepBuffer_.getChannel(0),
2200 static_cast<std::size_t>(upSamples) * sizeof(SampleType));
2201
2202 oversampler_->downsample(buffer);
2203 }
2204 else
2205 {
2206 const int baseSamples = std::min(buffer.getNumSamples(), msKeepBuffer_.getNumSamples());
2207 if (keepChannel >= 0 && keepChannel < buffer.getNumChannels() && baseSamples > 0)
2208 std::memcpy(msKeepBuffer_.getChannel(0), buffer.getChannel(keepChannel),
2209 static_cast<std::size_t>(baseSamples) * sizeof(SampleType));
2210
2212 if (second)
2213 alignSecondOrder(buffer, keepChannel, baseSamples, 1, seed);
2214
2215 if (keepChannel >= 0 && keepChannel < buffer.getNumChannels() && baseSamples > 0)
2216 std::memcpy(buffer.getChannel(keepChannel), msKeepBuffer_.getChannel(0),
2217 static_cast<std::size_t>(baseSamples) * sizeof(SampleType));
2218 }
2219
2220 if (stagesOn_) stagesAfter(buffer, keepChannel);
2221
2222 if (isMidSide) MidSide<SampleType>::decode(buffer);
2223
2224 // The tone after the curve. With every section out the cascade only
2225 // remembers the last two samples, so a section that comes in starts
2226 // from what has just gone by.
2227 designTone(static_cast<int>(kToneRampSeconds * spec_.sampleRate));
2228 tone_->processBlock(buffer);
2229 if (toneOn_)
2230 {
2231 for (int s = 0; s < kToneSections; ++s)
2232 {
2233 int& left = toneLeft_[static_cast<std::size_t>(s)];
2234 if (left < 0) continue;
2235 left -= buffer.getNumSamples();
2236 if (left <= 0 && !tone_->isRamping(s))
2237 {
2238 tone_->setSectionEnabled(s, false);
2239 left = -1;
2240 }
2241 }
2242 toneOn_ = false;
2243 for (int s = 0; s < kToneSections; ++s) toneOn_ = toneOn_ || tone_->isSectionEnabled(s);
2244 }
2245
2246 // Program-dependent adaptive blend, applied at BASE rate in the L/R
2247 // domain where the latency-compensated dry capture is valid.
2248 if (adaptiveBlend_.load(std::memory_order_relaxed))
2249 applyAdaptiveBlend(buffer);
2250
2251 // Post-filter
2252 {
2253 const int numSamples = buffer.getNumSamples();
2254 constexpr int kCoefRefresh = 16;
2255 for (int i = 0; i < numSamples; i += kCoefRefresh)
2256 {
2257 const int chunk = std::min(kCoefRefresh, numSamples - i);
2258 float curFreq = lastPostTiltFreq_;
2259 float curGain = lastPostTiltGain_;
2260 for (int k = 0; k < chunk; ++k)
2261 {
2264 }
2265
2266 if (curFreq != lastPostTiltFreq_ || curGain != lastPostTiltGain_)
2267 {
2268 // A genuine tilt shelf, as the setter documents. (This used
2269 // to be makePeak: a bell AT the pivot, which mid-boosted
2270 // instead of brightening/darkening.)
2271 auto c = BiquadCoeffs::makeTilt(spec_.sampleRate, static_cast<double>(curFreq), static_cast<double>(curGain));
2273 lastPostTiltFreq_ = curFreq;
2274 lastPostTiltGain_ = curGain;
2275 }
2276 auto subView = buffer.getSubView(i, chunk);
2277 postFilter_.processBlock(subView);
2278 }
2279 }
2280
2281 if (dcShare_ > 0.0 || dcWanted_) dcShare_ = applyDcShare(dcBlocker_, buffer, dcShare_);
2282 applyOutputGain(buffer);
2283 if (modeDipping_) applyModeDip(buffer);
2284
2285 // Mix Output
2287 else if (outputMode_ == OutputMode::Delta)
2288 {
2289 const int nCh = std::min(buffer.getNumChannels(), dryWetMixer_.getDryNumChannels());
2290 const int nS = std::min(buffer.getNumSamples(), dryWetMixer_.getDryCapturedSamples());
2291 for (int ch = 0; ch < nCh; ++ch)
2292 {
2293 SampleType* wet = buffer.getChannel(ch);
2294 const SampleType* dry = dryWetMixer_.getDryChannel(ch);
2295 for (int i = 0; i < nS; ++i) wet[i] -= dry[i];
2296 }
2297 }
2298 else
2299 {
2300 dryWetMixer_.mixWet(buffer, static_cast<SampleType>(mixSmoother_.getTargetValue()));
2301 }
2302 }
2303
2304public:
2305
2311 void setAlgorithm(Algorithm algo) { pushParam([&](auto& p){ p.algorithm = algo; }); }
2312
2318 void setDrive(SampleType dB) { pushParam([&](auto& p){ p.driveDb = dB; }); }
2319
2331 void setMix(SampleType mix01) { pushParam([&](auto& p){ p.mix = mix01; }); }
2332
2345 void setCharacter(SampleType c) { pushParam([&](auto& p){ p.character = c; }); }
2346
2354 void setProcessingMode(ProcessingMode m){ pushParam([&](auto& p){ p.processingMode = m; }); }
2355
2361 void setOutputMode(OutputMode m) { pushParam([&](auto& p){ p.outputMode = m; }); }
2362
2368 void setAnalogDrift(SampleType i) { pushParam([&](auto& p){ p.analogDrift = i; }); }
2369
2375 void setPreFilterHpFrequency(SampleType hz) { pushParam([&](auto& p){ p.preFilterHpFreq = hz; }); }
2376
2382 void setOutputGain(SampleType dB) { pushParam([&](auto& p){ p.outputGain = dB; }); }
2383
2394 void setDcBlocking(bool on) { pushParam([&](auto& p){ p.dcBlocking = on; }); }
2395
2401 void setAdaptiveBlend(bool on) noexcept { adaptiveBlend_.store(on, std::memory_order_relaxed); }
2402
2416 void setAntialiasing(bool on) noexcept
2417 {
2419 }
2420
2426 void setAntialiasing(Antialiasing mode) noexcept
2427 {
2428 const int order = std::clamp(static_cast<int>(mode), 0, 2);
2429 antialiasOrder_.store(order, std::memory_order_relaxed); // serialization readback
2430 for (auto& a : pool_) if (a) a->setAntialias(order);
2431 calibrationRequested_.store(true, std::memory_order_release);
2432 }
2433
2435 [[nodiscard]] Antialiasing getAntialiasing() const noexcept
2436 {
2437 return static_cast<Antialiasing>(antialiasOrder_.load(std::memory_order_relaxed));
2438 }
2439
2450 void setTone(int section, SampleType hz, SampleType gainDb) noexcept
2451 {
2452 if (section < 0 || section >= kToneSections || !std::isfinite(hz) || !std::isfinite(gainDb)) return;
2453 const auto s = static_cast<std::size_t>(section);
2454 toneHz_[s].store(std::clamp(hz, SampleType(20), SampleType(20000)), std::memory_order_relaxed);
2455 toneDb_[s].store(std::clamp(gainDb, SampleType(-18), SampleType(18)), std::memory_order_relaxed);
2456 toneDirty_.store(true, std::memory_order_release);
2457 }
2458
2460 [[nodiscard]] SampleType getToneFrequency(int section) const noexcept
2461 {
2462 return toneHz_[static_cast<std::size_t>(std::clamp(section, 0, kToneSections - 1))].load(std::memory_order_relaxed);
2463 }
2464
2466 [[nodiscard]] SampleType getToneGain(int section) const noexcept
2467 {
2468 return toneDb_[static_cast<std::size_t>(std::clamp(section, 0, kToneSections - 1))].load(std::memory_order_relaxed);
2469 }
2470
2481 void setDrivePan(SampleType pan) noexcept
2482 {
2483 if (std::isfinite(pan)) drivePan_.store(std::clamp(pan, SampleType(-1), SampleType(1)), std::memory_order_relaxed);
2484 }
2485
2487 [[nodiscard]] SampleType getDrivePan() const noexcept { return drivePan_.load(std::memory_order_relaxed); }
2488
2495 void setSlewSensitivity(SampleType amount) noexcept
2496 {
2497 if (!std::isfinite(amount)) return;
2498 slewSensitivity_.store(std::clamp(amount, SampleType(0), SampleType(1)), std::memory_order_relaxed);
2499 }
2500
2508 void setCurveBase(CurveBase base) noexcept { curve().setBase(static_cast<int>(base)); }
2509
2511 [[nodiscard]] CurveBase getCurveBase() const noexcept { return static_cast<CurveBase>(curve().getBase()); }
2512
2527 void setCurveShape(SampleType hardness, SampleType curvature, SampleType asymmetry) noexcept
2528 {
2529 curve().setShape(hardness, curvature, asymmetry);
2530 calibrationRequested_.store(true, std::memory_order_release);
2531 }
2532
2534 [[nodiscard]] SampleType getCurveHardness() const noexcept { return curve().getHardness(); }
2536 [[nodiscard]] SampleType getCurveCurvature() const noexcept { return curve().getCurvature(); }
2538 [[nodiscard]] SampleType getCurveAsymmetry() const noexcept { return curve().getAsymmetry(); }
2539
2550 void setAsymmetry(SampleType amount) noexcept
2551 {
2552 if (!std::isfinite(amount)) return;
2553 asymmetry_.store(std::clamp(amount, SampleType(-1), SampleType(1)), std::memory_order_relaxed);
2554 }
2555
2557 [[nodiscard]] SampleType getAsymmetry() const noexcept { return asymmetry_.load(std::memory_order_relaxed); }
2558
2571 void setProgramNoise(SampleType levelDb) noexcept
2572 {
2573 if (!std::isfinite(levelDb)) return;
2574 programNoiseDb_.store(std::clamp(levelDb, kNoiseOffDb, SampleType(-20)), std::memory_order_relaxed);
2575 }
2576
2578 [[nodiscard]] SampleType getProgramNoise() const noexcept { return programNoiseDb_.load(std::memory_order_relaxed); }
2579
2596 void setLevelTracking(SampleType amount) noexcept
2597 {
2598 if (!std::isfinite(amount)) return;
2599 levelTracking_.store(std::clamp(amount, SampleType(-1), SampleType(1)), std::memory_order_relaxed);
2600 }
2601
2603 [[nodiscard]] SampleType getLevelTracking() const noexcept { return levelTracking_.load(std::memory_order_relaxed); }
2604
2616 void setTrackingCorner(SampleType hz) noexcept
2617 {
2618 if (!std::isfinite(hz)) return;
2619 trackingCornerHz_.store(hz <= SampleType(0) ? SampleType(0) : std::clamp(hz, SampleType(20), SampleType(2000)),
2620 std::memory_order_relaxed);
2621 }
2622
2624 [[nodiscard]] SampleType getTrackingCorner() const noexcept { return trackingCornerHz_.load(std::memory_order_relaxed); }
2625
2646 void setCombLoop(SampleType amount, SampleType hz) noexcept
2647 {
2648 if (std::isfinite(amount))
2649 combLoop_.store(std::clamp(amount, SampleType(-0.95), SampleType(0.95)), std::memory_order_relaxed);
2650 if (std::isfinite(hz) && hz > SampleType(0))
2651 combLoopHz_.store(std::clamp(hz, kMinFeedbackHz, SampleType(20000)), std::memory_order_relaxed);
2652 }
2653
2665 void setCombLoopClosing(bool on) noexcept { combLoopClosing_.store(on, std::memory_order_relaxed); }
2666
2668 [[nodiscard]] bool getCombLoopClosing() const noexcept { return combLoopClosing_.load(std::memory_order_relaxed); }
2669
2671 [[nodiscard]] SampleType getCombLoop() const noexcept { return combLoop_.load(std::memory_order_relaxed); }
2672
2674 [[nodiscard]] SampleType getCombLoopFrequency() const noexcept
2675 {
2676 if (!(spec_.sampleRate > 0)) return combLoopHz_.load(std::memory_order_relaxed);
2677 return static_cast<SampleType>(spec_.sampleRate / static_cast<double>(feedbackDelayFor(getLatency()) + getLatency()));
2678 }
2679
2698 {
2699 if (on == driveCompensation_.load(std::memory_order_relaxed)) return;
2700 // The twin is ready before the audio thread can see the flag.
2701 if (on && prepared_) prepareCalibrator();
2702 driveCompensation_.store(on, std::memory_order_release);
2703 calibrationRequested_.store(true, std::memory_order_release);
2704 }
2705
2707 [[nodiscard]] bool isDriveCompensation() const noexcept { return driveCompensation_.load(std::memory_order_relaxed); }
2708
2710 [[nodiscard]] SampleType getDriveCompensationDb() const noexcept { return compensationDb_.load(std::memory_order_relaxed); }
2711
2723 void setPostFilterTilt(SampleType centerHz, SampleType amountDb)
2724 {
2725 pushParam([&](auto& p){ p.postFilterTiltFreq = centerHz; p.postFilterTiltGain = amountDb; });
2726 }
2727
2747 void setOversampling(int factor)
2748 {
2749 if (factor < 1 || factor > 16 || (factor & (factor - 1)) != 0) return;
2750 oversamplingAutomatic_ = false;
2751 applyOversampling(factor);
2752 }
2753
2768 {
2769 if (on == oversamplingAutomatic_) return;
2771 if (on && spec_.sampleRate > 0)
2772 {
2774 if (automatic != oversamplingFactor_) applyOversampling(automatic);
2775 }
2776 }
2777
2779 [[nodiscard]] bool isOversamplingAutomatic() const noexcept { return oversamplingAutomatic_; }
2780
2794 {
2795 mode = static_cast<OversamplingMode>(std::clamp(static_cast<int>(mode), 0, 1));
2796 if (mode == oversamplingMode_) return;
2797 oversamplingMode_ = mode;
2798 applyOversampling(oversamplingFactor_);
2799 }
2800
2802 [[nodiscard]] OversamplingMode getOversamplingMode() const noexcept { return oversamplingMode_; }
2803
2819 {
2820 band = static_cast<OversamplingBand>(std::clamp(static_cast<int>(band), 0, 1));
2821 if (band == oversamplingBand_) return;
2822 oversamplingBand_ = band;
2823 applyOversampling(oversamplingFactor_);
2824 }
2825
2827 [[nodiscard]] OversamplingBand getOversamplingBand() const noexcept { return oversamplingBand_; }
2828
2829private:
2830 void applyOversampling(int factor)
2831 {
2832 oversamplingFactor_ = factor;
2833 if (factor > 1)
2834 {
2835 oversampler_ = makeOversampler(factor, oversamplingMode_, oversamplingBand_);
2836 if (spec_.sampleRate > 0) oversampler_->prepare(spec_);
2837 }
2838 else
2839 oversampler_.reset();
2840
2841 // If prepare() already ran, grow the scratch buffers to hold the
2842 // upsampled block and realign the dry path; otherwise prepare() does it.
2843 if (prepared_)
2844 {
2845 const int upBlock = spec_.maxBlockSize * std::max(1, oversamplingFactor_);
2846 if (tempBuffer_.getNumSamples() < upBlock)
2848 if (driftBuffer_.getNumSamples() < upBlock)
2850 if (msKeepBuffer_.getNumSamples() < upBlock)
2851 msKeepBuffer_.resize(1, upBlock);
2852
2853 alignDryPath();
2854
2855 // The drive/character/drift/crossfade clocks follow the factor.
2857 reset();
2858 if (driveCompensation_.load(std::memory_order_relaxed)) prepareCalibrator();
2859 calibrate();
2860 }
2861 }
2862
2863public:
2864
2865 // -- Thread-Safe Getters (GUI / Metering) --------------------------------
2866
2871 [[nodiscard]] int getOversamplingFactor() const noexcept { return oversamplingFactor_; }
2872
2880 [[nodiscard]] int getLatency() const noexcept
2881 {
2882 return ((oversampler_ && oversamplingFactor_ > 1) ? oversampler_->getLatency() : 0)
2883 + (antialiasOrder_.load(std::memory_order_relaxed) == 2 ? secondOrderBaseDelay() : 0);
2884 }
2885
2887 [[nodiscard]] int getLatencySamples() const noexcept { return getLatency(); }
2888
2894 [[nodiscard]] Algorithm getCurrentAlgorithm() const noexcept { return currentAlgoType_.load(std::memory_order_relaxed); }
2895
2901 [[nodiscard]] SampleType getGainReductionDb() const noexcept { return gainReductionDb_.load(std::memory_order_relaxed); }
2902
2903
2905 [[nodiscard]] std::vector<uint8_t> getState() const
2906 {
2907 Params p;
2908 {
2910 p = lastParams_;
2911 }
2912 StateWriter w(stateId("SATU"), 1);
2913 w.write("algorithm", static_cast<int32_t>(p.algorithm));
2914 w.write("procMode", static_cast<int32_t>(p.processingMode));
2915 w.write("outMode", static_cast<int32_t>(p.outputMode));
2916 w.write("drive", static_cast<float>(p.driveDb));
2917 w.write("mix", static_cast<float>(p.mix));
2918 w.write("character", static_cast<float>(p.character));
2919 w.write("drift", static_cast<float>(p.analogDrift));
2920 w.write("preHp", static_cast<float>(p.preFilterHpFreq));
2921 w.write("tiltFreq", static_cast<float>(p.postFilterTiltFreq));
2922 w.write("tiltGain", static_cast<float>(p.postFilterTiltGain));
2923 w.write("outputGain", static_cast<float>(p.outputGain));
2924 w.write("dcBlocking", p.dcBlocking);
2925 w.write("antialias", antialiasOrder_.load(std::memory_order_relaxed) != 0);
2926 w.write("antialiasOrder", antialiasOrder_.load(std::memory_order_relaxed));
2927 w.write("adaptiveBlend", adaptiveBlend_.load(std::memory_order_relaxed));
2928 w.write("slewSens", static_cast<float>(slewSensitivity_.load(std::memory_order_relaxed)));
2929 w.write("oversampling", oversamplingFactor_);
2930 w.write("oversamplingAuto", oversamplingAutomatic_);
2931 w.write("oversamplingMode", static_cast<int32_t>(oversamplingMode_));
2932 w.write("oversamplingBand", static_cast<int32_t>(oversamplingBand_));
2933 w.write("curveHardness", static_cast<float>(getCurveHardness()));
2934 w.write("curveCurvature", static_cast<float>(getCurveCurvature()));
2935 w.write("curveAsymmetry", static_cast<float>(getCurveAsymmetry()));
2936 w.write("curveBase", static_cast<int32_t>(curve().getBase()));
2937 w.write("drivePan", static_cast<float>(getDrivePan()));
2938 for (int s = 0; s < kToneSections; ++s)
2939 {
2940 char key[16];
2941 std::snprintf(key, sizeof(key), "tone%dHz", s);
2942 w.write(key, static_cast<float>(getToneFrequency(s)));
2943 std::snprintf(key, sizeof(key), "tone%dDb", s);
2944 w.write(key, static_cast<float>(getToneGain(s)));
2945 }
2946 w.write("asymmetry", static_cast<float>(getAsymmetry()));
2947 w.write("programNoise", static_cast<float>(getProgramNoise()));
2948 w.write("levelTracking", static_cast<float>(getLevelTracking()));
2949 w.write("trackingCorner", static_cast<float>(getTrackingCorner()));
2950 w.write("combLoop", static_cast<float>(getCombLoop()));
2951 w.write("combLoopClosing", getCombLoopClosing());
2952 w.write("combLoopHz", static_cast<float>(combLoopHz_.load(std::memory_order_relaxed)));
2953 w.write("driveCompensation", driveCompensation_.load(std::memory_order_relaxed));
2954 return w.blob();
2955 }
2956
2960 bool setState(const uint8_t* data, size_t size)
2961 {
2962 StateReader r(data, size);
2963 if (!r.isValid() || r.processorId() != stateId("SATU")) return false;
2964 setAlgorithm(static_cast<Algorithm>(r.read("algorithm", 0)));
2965 setProcessingMode(static_cast<ProcessingMode>(r.read("procMode", 0)));
2966 setOutputMode(static_cast<OutputMode>(r.read("outMode", 0)));
2967 setDrive(static_cast<SampleType>(r.read("drive", 0.0f)));
2968 setMix(static_cast<SampleType>(r.read("mix", 1.0f)));
2969 setCharacter(static_cast<SampleType>(r.read("character", 0.0f)));
2970 setAnalogDrift(static_cast<SampleType>(r.read("drift", 0.0f)));
2971 setPreFilterHpFrequency(static_cast<SampleType>(r.read("preHp", 20.0f)));
2972 setPostFilterTilt(static_cast<SampleType>(r.read("tiltFreq", 1000.0f)),
2973 static_cast<SampleType>(r.read("tiltGain", 0.0f)));
2974 setOutputGain(static_cast<SampleType>(r.read("outputGain", 0.0f)));
2975 setDcBlocking(r.read("dcBlocking", true));
2976 // "antialiasOrder" (0/1/2) supersedes the older boolean, which
2977 // meant first order.
2978 setAntialiasing(static_cast<Antialiasing>(
2979 r.read("antialiasOrder", r.read("antialias", false) ? 1 : 0)));
2980 setAdaptiveBlend(r.read("adaptiveBlend", false));
2981 setSlewSensitivity(static_cast<SampleType>(r.read("slewSens", 0.0f)));
2982 setOversampling(r.read("oversampling", 1));
2983 setAutomaticOversampling(r.read("oversamplingAuto", false));
2984 setOversamplingMode(static_cast<OversamplingMode>(r.read("oversamplingMode", 0)));
2985 setOversamplingBand(static_cast<OversamplingBand>(r.read("oversamplingBand", 0)));
2986 setCurveShape(static_cast<SampleType>(r.read("curveHardness", 0.0f)),
2987 static_cast<SampleType>(r.read("curveCurvature", 1.0f)),
2988 static_cast<SampleType>(r.read("curveAsymmetry", 0.0f)));
2989 setCurveBase(static_cast<CurveBase>(std::clamp(static_cast<int>(r.read("curveBase", 0)), 0, 6)));
2990 setDrivePan(static_cast<SampleType>(r.read("drivePan", 0.0f)));
2991 for (int s = 0; s < kToneSections; ++s)
2992 {
2993 constexpr float kDefault[4] = { 100.0f, 500.0f, 2500.0f, 8000.0f };
2994 char hz[16], db[16];
2995 std::snprintf(hz, sizeof(hz), "tone%dHz", s);
2996 std::snprintf(db, sizeof(db), "tone%dDb", s);
2997 setTone(s, static_cast<SampleType>(r.read(hz, kDefault[s])), static_cast<SampleType>(r.read(db, 0.0f)));
2998 }
2999 setAsymmetry(static_cast<SampleType>(r.read("asymmetry", 0.0f)));
3000 setProgramNoise(static_cast<SampleType>(r.read("programNoise", -120.0f)));
3001 setLevelTracking(static_cast<SampleType>(r.read("levelTracking", 0.0f)));
3002 setTrackingCorner(static_cast<SampleType>(r.read("trackingCorner", 0.0f)));
3003 setCombLoop(static_cast<SampleType>(r.read("combLoop", 0.0f)),
3004 static_cast<SampleType>(r.read("combLoopHz", 200.0f)));
3005 setCombLoopClosing(r.read("combLoopClosing", false));
3006 setDriveCompensation(r.read("driveCompensation", false));
3007 return true;
3008 }
3009
3010protected:
3017 void configureProcessingRate(bool keepTargets)
3018 {
3019 const double pr = spec_.sampleRate * static_cast<double>(std::max(1, oversamplingFactor_));
3020 driveSmoother_.reset(pr, 20.0f, 0.707f, keepTargets ? driveSmoother_.getTargetValue() : 0.0f);
3021 characterSmoother_.reset(pr, 20.0f, keepTargets ? characterSmoother_.getTargetValue() : 0.0f);
3022 driftSmoother_.reset(pr, 500.0f, keepTargets ? driftSmoother_.getTargetValue() : 0.0f);
3023 crossfader_.reset(pr, 10.0f, 1.0f);
3024
3025 leftDrift_.prepare(pr);
3026 rightDrift_.prepare(pr);
3027 leftDrift_.reseed(0x9E3779B97F4A7C15ULL);
3028 rightDrift_.reseed(0xBF58476D1CE4E5B9ULL);
3029 // Smooth the random drift targets (~100 ms): without smoothing the
3030 // generators step once per second, modulating the drive in audible
3031 // jumps instead of an analog-style slow wander.
3032 leftDrift_.setSmoothing(true, SampleType(100));
3033 rightDrift_.setSmoothing(true, SampleType(100));
3034
3035 // Slew sensitivity is defined per sample at 96 kHz (48 kHz at the
3036 // default 2x): a raw sample delta halves with every doubling of rate.
3037 slewRateScale_ = static_cast<SampleType>(pr / 96000.0);
3038
3039 const auto up = static_cast<size_t>(std::max(1, spec_.maxBlockSize) * std::max(1, oversamplingFactor_));
3040 if (driveRamp_.size() < up) driveRamp_.assign(up, SampleType(1));
3041 if (charRamp_.size() < up) charRamp_.assign(up, SampleType(0));
3042 }
3043
3044 struct Params
3045 {
3049 SampleType driveDb = SampleType(0);
3050 SampleType mix = SampleType(1);
3051 SampleType character = SampleType(0);
3052 SampleType analogDrift = SampleType(0);
3053 SampleType preFilterHpFreq = SampleType(20);
3054 SampleType postFilterTiltFreq = SampleType(1000);
3055 SampleType postFilterTiltGain = SampleType(0);
3056 SampleType outputGain = SampleType(0);
3057 bool dcBlocking = true;
3058 };
3059
3066 static void sanitizeParams(Params& p, const Params& prev) noexcept
3067 {
3068 const auto keepFinite = [](SampleType& v, SampleType old) noexcept
3069 {
3070 if (!std::isfinite(v)) v = old;
3071 };
3072 keepFinite(p.driveDb, prev.driveDb);
3073 keepFinite(p.mix, prev.mix);
3074 keepFinite(p.character, prev.character);
3075 keepFinite(p.analogDrift, prev.analogDrift);
3076 keepFinite(p.preFilterHpFreq, prev.preFilterHpFreq);
3077 keepFinite(p.postFilterTiltFreq, prev.postFilterTiltFreq);
3078 keepFinite(p.postFilterTiltGain, prev.postFilterTiltGain);
3079 keepFinite(p.outputGain, prev.outputGain);
3080
3081 const auto clampEnum = [](auto& e, int hi) noexcept
3082 {
3083 using E = std::remove_reference_t<decltype(e)>;
3084 e = static_cast<E>(std::clamp(static_cast<int>(e), 0, hi));
3085 };
3086 clampEnum(p.algorithm, kNumAlgorithms - 1);
3087 clampEnum(p.processingMode, static_cast<int>(ProcessingMode::MidSide));
3088 clampEnum(p.outputMode, static_cast<int>(OutputMode::Delta));
3089 }
3090
3091 template <typename Fn>
3092 void pushParam(Fn&& mutate)
3093 {
3095 const Params prev = lastParams_;
3096 mutate(lastParams_);
3098 if (!paramQueue_.push(lastParams_))
3099 {
3100 // Queue full (a burst of GUI edits within one audio block).
3101 // lastParams_ already holds the complete state, so flag the audio
3102 // thread to fetch it directly; without this the newest edit would
3103 // silently wait for the NEXT parameter change to become audible.
3104 paramsPending_.store(true, std::memory_order_release);
3105 }
3106 }
3107
3109 {
3110 Params p;
3111 while (paramQueue_.pop(p))
3113
3114 // Recover an edit that could not be queued. lastParams_ is always the
3115 // newest complete state, so applying it can never move backwards.
3116 if (paramsPending_.exchange(false, std::memory_order_acquire))
3117 {
3119 if (guard.isLocked())
3121 else
3122 paramsPending_.store(true, std::memory_order_release); // retry next block
3123 }
3124 }
3125
3133 [[nodiscard]] bool curveMakesDc() noexcept
3134 {
3135 if (asymmetry_.load(std::memory_order_relaxed) != SampleType(0)) return true;
3136 const auto makes = [this](Algorithm a) {
3137 switch (a)
3138 {
3139 case Algorithm::Tube:
3140 case Algorithm::MultiStage: return true;
3144 case Algorithm::Exciter:
3145 case Algorithm::Wavefolder: return applied_.character != SampleType(0);
3146 case Algorithm::Curve: return curve().getAsymmetry() != SampleType(0) || curve().getBase() >= static_cast<int>(CurveBase::Valve);
3147 case Algorithm::Tape:
3149 case Algorithm::Downsample: return false;
3150 }
3151 return true;
3152 };
3153 if (makes(applied_.algorithm)) return true;
3154 for (int a = 0; a < static_cast<int>(pool_.size()); ++a)
3155 if (pool_[static_cast<std::size_t>(a)].get() == active_.load() && makes(static_cast<Algorithm>(a))) return true;
3156 return false;
3157 }
3158
3165 double applyDcShare(DCBlocker<SampleType>& filter, AudioBufferView<SampleType> view, double share) noexcept
3166 {
3167 const bool wanted = dcWanted_;
3168 if (wanted && share >= 1.0)
3169 {
3170 filter.processBlock(view);
3171 return 1.0;
3172 }
3173 if (wanted && share <= 0.0) filter.reset();
3174 const int nS = std::min(view.getNumSamples(), dcScratch_.getNumSamples());
3175 const int nCh = std::min(view.getNumChannels(), dcScratch_.getNumChannels());
3176 for (int ch = 0; ch < nCh; ++ch)
3177 std::copy_n(view.getChannel(ch), nS, dcScratch_.getChannel(ch));
3178 filter.processBlock(dcScratch_.toView().getSubView(0, nS));
3179 double s = share;
3180 for (int i = 0; i < nS; ++i)
3181 {
3182 s = wanted ? std::min(1.0, s + dcStep_) : std::max(0.0, s - dcStep_);
3183 const SampleType g = static_cast<SampleType>(s);
3184 for (int ch = 0; ch < nCh; ++ch)
3185 {
3186 SampleType* x = view.getChannel(ch);
3187 x[i] += g * (dcScratch_.getChannel(ch)[i] - x[i]);
3188 }
3189 }
3190 return s;
3191 }
3192
3199 {
3200 const int nCh = std::min(buffer.getNumChannels(), dryWetMixer_.getDryNumChannels());
3201 const int nS = std::min(buffer.getNumSamples(), dryWetMixer_.getDryCapturedSamples());
3202 for (int i = 0; i < nS; ++i)
3203 {
3204 if (modeDipDown_) modeDip_ = std::min(1.0, modeDip_ + modeDipStep_);
3205 else modeDip_ = std::max(0.0, modeDip_ - modeDipStep_ * kModeRiseShare);
3206 const SampleType g = static_cast<SampleType>(modeDip_);
3207 for (int ch = 0; ch < nCh; ++ch)
3208 {
3209 SampleType* wet = buffer.getChannel(ch);
3210 wet[i] += g * (dryWetMixer_.getDryChannel(ch)[i] - wet[i]);
3211 }
3212 }
3213 if (modeDipDown_ && modeDip_ >= 1.0)
3214 {
3215 // At the bottom: the new mode from the next block on.
3217 for (auto& algo : pool_)
3218 if (algo) algo->reset();
3219 modeDipDown_ = false;
3220 }
3221 else if (!modeDipDown_ && modeDip_ <= 0.0)
3222 {
3223 modeDipping_ = false;
3224 if (pendingMode_ != procMode_)
3225 {
3226 modeDipping_ = true;
3227 modeDipDown_ = true;
3228 }
3229 }
3230 }
3231
3233 {
3234 driveSmoother_.setTargetValue(std::clamp(static_cast<float>(p.driveDb), -24.0f, 48.0f));
3235 mixSmoother_.setTargetValue(std::clamp(static_cast<float>(p.mix), 0.0f, 1.0f));
3236 characterSmoother_.setTargetValue(std::clamp(static_cast<float>(p.character), -1.0f, 1.0f));
3237 driftSmoother_.setTargetValue(std::clamp(static_cast<float>(p.analogDrift), 0.0f, 1.0f));
3238 userOutputGainDb_ = static_cast<float>(p.outputGain);
3240 + static_cast<float>(compensationDb_.load(std::memory_order_relaxed)));
3242 calibrationDirty_ = true;
3243 applied_ = p;
3244
3245 float nyquist = static_cast<float>(spec_.sampleRate) / 2.0f;
3246 preHpSmoother_.setTargetValue(std::clamp(static_cast<float>(p.preFilterHpFreq), 10.0f, nyquist));
3247 postTiltFreqSmoother_.setTargetValue(std::clamp(static_cast<float>(p.postFilterTiltFreq), 100.0f, nyquist));
3248 postTiltGainSmoother_.setTargetValue(std::clamp(static_cast<float>(p.postFilterTiltGain), -12.0f, 12.0f));
3249
3252 {
3255 {
3256 modeDipping_ = true;
3257 modeDipDown_ = true;
3258 }
3259 }
3261 currentAlgoType_.store(p.algorithm, std::memory_order_relaxed);
3262
3263 // Algorithm switching state machine. The crossfader fades active_ out
3264 // towards next_ (1 -> 0); processSaturationPipeline resolves the end
3265 // of the fade by its final value (0 = promote next_, 1 = discard it).
3266 auto* requested = pool_[static_cast<int>(p.algorithm)].get();
3267 auto* act = active_.load();
3268 auto* nxt = next_.load();
3269 if (requested == act)
3270 {
3271 // Return to the algorithm still playing: steer any running fade
3272 // back to 1 so the pending algorithm is discarded when it lands.
3273 // (Ignoring this case made a quick B-then-back-to-A edit complete
3274 // the fade to B: the wrong algorithm played forever while
3275 // getCurrentAlgorithm() reported A.)
3276 if (nxt != nullptr)
3277 {
3279 if (!crossfader_.isSmoothing())
3280 {
3281 // The fade had not moved yet (still at 1): discard now, or
3282 // the un-smoothing crossfader would leave nxt armed and a
3283 // later reset() would wrongly promote it.
3284 nxt->reset();
3285 next_.store(nullptr);
3286 }
3287 }
3288 }
3289 else if (requested == nxt)
3290 {
3291 // Re-request of the incoming algorithm (e.g. after a revert
3292 // started): make sure the fade heads towards it again.
3294 }
3295 else
3296 {
3297 // New target. It has not been audible for a while, so clear its
3298 // state: stale filter/ADAA history would leak an old-signal
3299 // transient into the fade-in. If a fade was already running, its
3300 // pending algorithm is simply replaced (one fade-weighted step,
3301 // bounded like a hard switch; the abandoned one is re-cleared
3302 // here whenever it is next requested).
3303 requested->reset();
3304 next_.store(requested);
3306 }
3307 }
3308
3312 [[nodiscard]] int secondOrderDelay() const noexcept
3313 {
3314 return oversamplingFactor_ == 2 ? 4 : std::clamp(oversamplingFactor_, 1, 3);
3315 }
3316
3318 [[nodiscard]] int secondOrderBaseDelay() const noexcept
3319 {
3320 return (oversampler_ && oversamplingFactor_ == 2) ? 2 : 1;
3321 }
3322
3323 // Data-Oriented Pipeline to eliminate per-sample virtual dispatch
3325 {
3326 auto* primary = active_.load();
3327 auto* secondary = next_.load();
3328 bool xfading = secondary != nullptr && crossfader_.isSmoothing();
3329
3330 // Clamp to per-channel state capacity (prevSlewSample_/prevBlendSample_
3331 // are kMaxCh) AND to the prepared channel count: driftBuffer_ and
3332 // tempBuffer_ only hold spec_.numChannels channels, so a caller view
3333 // with more channels used to read/write past them (out of bounds in
3334 // release) as soon as drift or an algorithm crossfade was active.
3335 // Channels beyond the prepared spec now bypass the saturation stage.
3336 const int nCh = std::min({ buffer.getNumChannels(), kMaxCh, spec_.numChannels });
3337 const int nS = buffer.getNumSamples();
3338
3339 auto driveDbTarget = static_cast<SampleType>(driveSmoother_.getTargetValue());
3340 auto driveGainTarget = decibelsToGain(driveDbTarget);
3341 auto characterTarget = static_cast<SampleType>(characterSmoother_.getTargetValue());
3342
3343 AudioSpec updateSpec = spec_;
3344 if (oversamplingFactor_ > 1) updateSpec.sampleRate *= oversamplingFactor_;
3345
3346 const int commonDelay = secondOrderDelay();
3347 if (primary) { primary->latchOrder(commonDelay); primary->update(driveGainTarget, characterTarget, updateSpec); }
3348 if (secondary) { secondary->latchOrder(commonDelay); secondary->update(driveGainTarget, characterTarget, updateSpec); }
3349
3350 SampleType peakInOriginal = SampleType(0);
3351 for (int ch = 0; ch < nCh; ++ch) {
3352 const SampleType* d = buffer.getChannel(ch);
3353 for (int i = 0; i < nS; ++i) peakInOriginal = std::max(peakInOriginal, std::abs(d[i]));
3354 }
3355
3356 // 1. Slew (In-place)
3357 auto slewAmt = slewSensitivity_.load(std::memory_order_relaxed);
3358 if (slewAmt > SampleType(0))
3359 {
3360 for (int ch = 0; ch < nCh; ++ch) {
3361 SampleType* data = buffer.getChannel(ch);
3362 for (int i = 0; i < nS; ++i) {
3363 SampleType dry = data[i];
3364 SampleType delta = (dry - prevSlewSample_[ch]) * slewRateScale_;
3365 data[i] += std::tanh(std::abs(delta)) * slewAmt * dry;
3366 prevSlewSample_[ch] = dry;
3367 }
3368 }
3369 }
3370
3371 // 2. Pre-generate Drift
3372 auto driftIntensity = driftSmoother_.getTargetValue();
3373 bool useDrift = driftIntensity > 0.01f;
3374 if (useDrift)
3375 {
3376 auto driftView = driftBuffer_.toView();
3377 for (int i = 0; i < nS; ++i) {
3378 auto driftS = driftSmoother_.getNextValue();
3379 // Exactly one draw per generator per sample (stereo-identical
3380 // to drawing inside the channel loop). Channels beyond the
3381 // second share the right generator's value; drawing per
3382 // channel instead advanced its clock nCh-1 times per sample,
3383 // speeding the wander up with the channel count.
3384 const SampleType noiseL = leftDrift_.getNextSample();
3385 const SampleType noiseR = (nCh > 1) ? rightDrift_.getNextSample() : SampleType(0);
3386 for (int ch = 0; ch < nCh; ++ch) {
3387 driftView.getChannel(ch)[i] =
3388 SampleType(1) + static_cast<SampleType>(driftS) * (ch == 0 ? noiseL : noiseR);
3389 }
3390 }
3391 }
3392
3393 // 3. Drive and character trajectories, advanced ONCE per sample and
3394 // shared by both algorithms of a crossfade (each used to advance
3395 // the smoothers again, so a preset change depended on the host's
3396 // block partition by up to 0.45 of full scale).
3397 // With the knob still the smoother gives its target at every sample:
3398 // one gain for the block (the same bits) instead of a power a sample.
3400 {
3401 const SampleType still = decibelsToGain(static_cast<SampleType>(driveSmoother_.getNextValue()));
3402 for (int i = 0; i < nS; ++i)
3403 {
3404 driveRamp_[static_cast<size_t>(i)] = still;
3405 charRamp_[static_cast<size_t>(i)] = static_cast<SampleType>(characterSmoother_.getNextValue());
3406 }
3407 }
3408 else
3409 for (int i = 0; i < nS; ++i)
3410 {
3411 driveRamp_[static_cast<size_t>(i)] =
3412 decibelsToGain(static_cast<SampleType>(driveSmoother_.getNextValue()));
3413 charRamp_[static_cast<size_t>(i)] = static_cast<SampleType>(characterSmoother_.getNextValue());
3414 }
3415
3416 // 4. Primary Saturation (and secondary if xfade)
3417 if (xfading)
3418 {
3419 auto tempView = tempBuffer_.toView().getSubView(0, nS);
3420 for (int ch = 0; ch < nCh; ++ch)
3421 std::memcpy(tempView.getChannel(ch), buffer.getChannel(ch), static_cast<std::size_t>(nS) * sizeof(SampleType));
3422
3423 dispatchSaturator(primary, buffer, useDrift);
3424 dispatchSaturator(secondary, tempView, useDrift);
3425
3426 for (int i = 0; i < nS; ++i) {
3427 auto fade = static_cast<SampleType>(crossfader_.getNextValue());
3428 for (int ch = 0; ch < nCh; ++ch) {
3429 SampleType* out = buffer.getChannel(ch);
3430 const SampleType* alt = tempView.getChannel(ch);
3431 out[i] = out[i] * fade + alt[i] * (SampleType(1) - fade);
3432 }
3433 }
3434
3435 if (!crossfader_.isSmoothing()) {
3436 if (crossfader_.getCurrentValue() < 0.5f) {
3437 // Fade ran to 0: the pending algorithm takes over.
3438 active_.store(secondary);
3439 next_.store(nullptr);
3440 if (primary) primary->reset();
3441 } else {
3442 // Reverted fade landed back on the active algorithm:
3443 // discard the pending one.
3444 secondary->reset();
3445 next_.store(nullptr);
3446 }
3448 }
3449 }
3450 else
3451 {
3452 dispatchSaturator(primary, buffer, useDrift);
3453 }
3454
3455 // (Adaptive blend and the MidOnly/SideOnly channel passthrough run at
3456 // BASE rate in process() - see the snapshot/restore logic there.)
3457
3458 // Gain Reduction Tracking
3459 SampleType peakOut = SampleType(0);
3460 for (int ch = 0; ch < nCh; ++ch) {
3461 const SampleType* d = buffer.getChannel(ch);
3462 for (int i = 0; i < nS; ++i) peakOut = std::max(peakOut, std::abs(d[i]));
3463 }
3464
3465 SampleType peakInDriven = peakInOriginal * driveGainTarget;
3466 if (peakInDriven > SampleType(1e-6)) {
3467 SampleType ratio = std::min(peakOut / peakInDriven, SampleType(1));
3468 gainReductionDb_.store(gainToDecibels(ratio, SampleType(-100)), std::memory_order_relaxed);
3469 } else {
3470 gainReductionDb_.store(SampleType(0), std::memory_order_relaxed);
3471 }
3472 }
3473
3484 void alignSecondOrder(AudioBufferView<SampleType> view, int keepChannel, int keepSamples,
3485 int factor, bool seed) noexcept
3486 {
3487 const int nCh = std::min({view.getNumChannels(), kMaxCh, spec_.numChannels});
3488 const int nS = view.getNumSamples();
3489 const int target = factor == 2 ? 4 : std::clamp(factor, 1, kAlignRing - 1);
3490 const int pad = target - (factor == 2 ? 4 : std::clamp(factor, 1, 3));
3491 int pos = alignPos_;
3492 if (pad > 0)
3493 for (int ch = 0; ch < nCh; ++ch)
3494 {
3495 if (ch == keepChannel) continue;
3496 SampleType* d = view.getChannel(ch);
3497 auto& ring = alignRing_[static_cast<size_t>(ch)];
3498 if (seed && nS > 0) ring.fill(d[0]);
3499 pos = alignPos_;
3500 for (int i = 0; i < nS; ++i)
3501 {
3502 ring[static_cast<size_t>(pos)] = d[i];
3503 d[i] = ring[static_cast<size_t>((pos - pad) & (kAlignRing - 1))];
3504 pos = (pos + 1) & (kAlignRing - 1);
3505 }
3506 }
3507 if (keepChannel >= 0 && keepSamples > 0)
3508 {
3509 SampleType* d = msKeepBuffer_.getChannel(0);
3510 auto& ring = keepRing_;
3511 if (seed) ring.fill(d[0]);
3512 pos = alignPos_;
3513 const int delay = target;
3514 for (int i = 0; i < keepSamples; ++i)
3515 {
3516 ring[static_cast<size_t>(pos)] = d[i];
3517 d[i] = ring[static_cast<size_t>((pos - delay) & (kAlignRing - 1))];
3518 pos = (pos + 1) & (kAlignRing - 1);
3519 }
3520 }
3521 alignPos_ = (alignPos_ + nS) & (kAlignRing - 1);
3522 }
3523
3528 {
3529 const int nCh = std::min({ buffer.getNumChannels(),
3531 const int nS = std::min(buffer.getNumSamples(),
3533
3534 for (int ch = 0; ch < nCh; ++ch)
3535 {
3536 SampleType* wetData = buffer.getChannel(ch);
3537 const SampleType* dryData = dryWetMixer_.getDryChannel(ch);
3538 for (int i = 0; i < nS; ++i)
3539 {
3540 SampleType dry = dryData[i];
3541 SampleType wet = wetData[i];
3542 SampleType avg = (std::abs(prevBlendSample_[ch]) + std::abs(dry)) * SampleType(0.5);
3543 SampleType apply = std::clamp(avg, SampleType(0), SampleType(1));
3544 wetData[i] = dry * (SampleType(1) - apply) + wet * apply;
3545 prevBlendSample_[ch] = dry;
3546 }
3547 }
3548 }
3549
3550 // Compile-time resolver (Zero virtual dispatch in hot path)
3552 {
3553 if (!baseAlgo) return;
3554 switch (baseAlgo->getType())
3555 {
3556 case Algorithm::Tube: processCore(static_cast<detail::TubeAlgorithm<SampleType>*>(baseAlgo), buffer, useDrift); break;
3557 case Algorithm::Tape: processCore(static_cast<detail::TapeAlgorithm<SampleType>*>(baseAlgo), buffer, useDrift); break;
3558 case Algorithm::Transformer: processCore(static_cast<detail::TransformerAlgorithm<SampleType>*>(baseAlgo), buffer, useDrift); break;
3559 case Algorithm::SoftClip: processCore(static_cast<detail::TanhAlgorithm<SampleType>*>(baseAlgo), buffer, useDrift); break;
3560 case Algorithm::HardClip: processCore(static_cast<detail::HardClipAlgorithm<SampleType>*>(baseAlgo), buffer, useDrift); break;
3561 case Algorithm::Exciter: processCore(static_cast<detail::ExciterAlgorithm<SampleType>*>(baseAlgo), buffer, useDrift); break;
3562 case Algorithm::Wavefolder: processCore(static_cast<detail::WavefolderAlgorithm<SampleType>*>(baseAlgo), buffer, useDrift); break;
3563 case Algorithm::Bitcrusher: processCore(static_cast<detail::BitcrusherAlgorithm<SampleType>*>(baseAlgo), buffer, useDrift); break;
3564 case Algorithm::Downsample: processCore(static_cast<detail::DownsampleAlgorithm<SampleType>*>(baseAlgo), buffer, useDrift); break;
3565 case Algorithm::MultiStage: processCore(static_cast<detail::MultiStageAlgorithm<SampleType>*>(baseAlgo), buffer, useDrift); break;
3566 case Algorithm::Curve: processCore(static_cast<detail::CurveAlgorithm<SampleType>*>(baseAlgo), buffer, useDrift); break;
3567 }
3568 }
3569
3570 template <typename ExactAlgo>
3571 void processCore(ExactAlgo* algo, AudioBufferView<SampleType> buffer, bool useDrift) noexcept
3572 {
3573 // Same channel clamp as processSaturationPipeline: per-channel algorithm
3574 // state is bounded to kMaxCh and driftBuffer_ to spec_.numChannels.
3575 const int nCh = std::min({ buffer.getNumChannels(), kMaxCh, spec_.numChannels });
3576 const int nS = buffer.getNumSamples();
3577 auto driftView = driftBuffer_.toView();
3578
3579 if (algo->order() == 2)
3580 {
3581 // Second order: the curve's kernel where one exists, otherwise
3582 // the plain curve delayed by one sample to the same alignment.
3583 for (int i = 0; i < nS; ++i)
3584 {
3585 const SampleType driveGainS = driveRamp_[static_cast<size_t>(i)];
3586 const SampleType charS = charRamp_[static_cast<size_t>(i)];
3587 for (int ch = 0; ch < nCh; ++ch)
3588 {
3589 SampleType drift = useDrift ? driftView.getChannel(ch)[i] : SampleType(1);
3590 SampleType* data = buffer.getChannel(ch);
3591 const SampleType pg = panning_ && ch < 2 ? panGain(ch, i, nS) : SampleType(1);
3592 if constexpr (requires { ExactAlgo::kSelfAligned; })
3593 data[i] = algo->processSecond(data[i], driveGainS * drift * pg, charS * drift, ch);
3594 else if constexpr (requires { algo->processSecond(data[i], driveGainS, charS, ch); })
3595 data[i] = algo->padKernel(algo->processSecond(data[i], driveGainS * drift * pg, charS * drift, ch), ch);
3596 else
3597 data[i] = algo->align(algo->processSample(data[i], driveGainS * drift * pg, charS * drift, ch), ch);
3598 if (pg != SampleType(1)) data[i] /= pg;
3599 }
3600 }
3601 return;
3602 }
3603
3604 for (int i = 0; i < nS; ++i)
3605 {
3606 const SampleType driveGainS = driveRamp_[static_cast<size_t>(i)];
3607 const SampleType charS = charRamp_[static_cast<size_t>(i)];
3608
3609 for (int ch = 0; ch < nCh; ++ch)
3610 {
3611 SampleType drift = useDrift ? driftView.getChannel(ch)[i] : SampleType(1);
3612 SampleType* data = buffer.getChannel(ch);
3613 if (panning_ && ch < 2) [[unlikely]]
3614 {
3615 const SampleType pg = panGain(ch, i, nS);
3616 data[i] = algo->processSample(data[i], driveGainS * drift * pg, charS * drift, ch) / pg;
3617 continue;
3618 }
3619 data[i] = algo->processSample(data[i], driveGainS * drift, charS * drift, ch);
3620 }
3621 }
3622 }
3623
3629 void designTone(int ramp) noexcept
3630 {
3631 if (!tone_ || !toneDirty_.load(std::memory_order_relaxed) || !toneDirty_.exchange(false, std::memory_order_acquire)) return;
3632 const double fs = spec_.sampleRate;
3633 for (int s = 0; s < kToneSections; ++s)
3634 {
3635 const auto i = static_cast<std::size_t>(s);
3636 const double hz = std::min(static_cast<double>(toneHz_[i].load(std::memory_order_relaxed)), 0.45 * fs);
3637 const double db = static_cast<double>(toneDb_[i].load(std::memory_order_relaxed));
3638 if (db == 0.0)
3639 {
3640 if (tone_->isSectionEnabled(s) && toneLeft_[i] < 0)
3641 {
3642 // Out of the path once the ramp is over and what the
3643 // section still adds has died away with its poles.
3644 tone_->rampToBypass(s, ramp);
3645 toneLeft_[i] = ramp + poleDecaySamples(tone_->getTargetCoeffs(s));
3646 }
3647 continue;
3648 }
3649 const BiquadCoeffs c = s == 0 ? BiquadCoeffs::makeLowShelf(fs, hz, db)
3650 : s == 3 ? BiquadCoeffs::makeHighShelf(fs, hz, db)
3651 : BiquadCoeffs::makePeak(fs, hz, 0.7, db);
3652 if (!tone_->isSectionEnabled(s))
3653 {
3654 tone_->setCoeffs(s, c.bypassed());
3655 tone_->setSectionEnabled(s, true);
3656 }
3657 toneLeft_[i] = -1;
3658 tone_->rampCoeffs(s, c, ramp);
3659 toneOn_ = true;
3660 }
3661 }
3662
3664 [[nodiscard]] int poleDecaySamples(const BiquadCoeffs& c) const noexcept
3665 {
3666 const double disc = c.a1 * c.a1 - 4.0 * c.a2;
3667 const double radius = disc < 0.0 ? std::sqrt(std::max(0.0, c.a2))
3668 : 0.5 * (std::abs(c.a1) + std::sqrt(disc));
3669 if (!(radius > 0.0)) return 0;
3670 if (!(radius < 1.0)) return static_cast<int>(spec_.sampleRate);
3671 return static_cast<int>(std::min(spec_.sampleRate, std::ceil(std::log(1e-7) / std::log(radius))));
3672 }
3673
3675 [[nodiscard]] SampleType panGain(int ch, int i, int samples) const noexcept
3676 {
3677 const auto c = static_cast<std::size_t>(ch);
3678 return panFrom_[c] + (panTo_[c] - panFrom_[c]) * static_cast<SampleType>(i + 1) / static_cast<SampleType>(std::max(1, samples));
3679 }
3680
3682 {
3683 auto targetGainDb = outputGainSmoother_.getTargetValue();
3684 if (std::abs(targetGainDb - outputGainSmoother_.getCurrentValue()) < 0.001f)
3685 {
3686 buffer.applyGain(decibelsToGain(static_cast<SampleType>(targetGainDb)));
3687 }
3688 else
3689 {
3690 const int nCh = buffer.getNumChannels();
3691 const int nS = buffer.getNumSamples();
3692 for (int i = 0; i < nS; ++i)
3693 {
3694 auto gain = decibelsToGain(static_cast<SampleType>(outputGainSmoother_.getNextValue()));
3695 for (int ch = 0; ch < nCh; ++ch) buffer.getChannel(ch)[i] *= gain;
3696 }
3697 }
3698 }
3699
3700 // -- Stages around the curve ---------------------------------------------
3701
3703 {
3704 return *static_cast<detail::CurveAlgorithm<SampleType>*>(pool_[static_cast<size_t>(Algorithm::Curve)].get());
3705 }
3706 [[nodiscard]] const detail::CurveAlgorithm<SampleType>& curve() const noexcept
3707 {
3708 return *static_cast<const detail::CurveAlgorithm<SampleType>*>(pool_[static_cast<size_t>(Algorithm::Curve)].get());
3709 }
3710
3712 [[nodiscard]] int feedbackDelayFor(int latency) const noexcept
3713 {
3714 const double hz = static_cast<double>(combLoopHz_.load(std::memory_order_relaxed));
3715 const int period = static_cast<int>(std::lround(spec_.sampleRate / std::max(hz, 1.0)));
3716 return std::clamp(period - latency, kMinFeedbackDelay, std::max(kMinFeedbackDelay, feedbackSize_ / 2));
3717 }
3718
3721 {
3722 const int block = std::max(1, spec_.maxBlockSize);
3723 const auto pow2 = [](int n) { int p = 64; while (p < n) p <<= 1; return p; };
3724 gainSize_ = pow2(block + 1024);
3725 gainRing_.assign(static_cast<size_t>(gainSize_), SampleType(1));
3726 feedbackSize_ = pow2(2 * static_cast<int>(std::ceil(spec_.sampleRate / static_cast<double>(kMinFeedbackHz))) + 16);
3727 feedbackRing_.assign(static_cast<size_t>(feedbackSize_) * static_cast<size_t>(std::clamp(spec_.numChannels, 1, kMaxCh)),
3728 SampleType(0));
3729 const double fs = spec_.sampleRate;
3730 stageRate_ = 1.0 - std::exp(-1.0 / (0.02 * fs));
3731 evenRate_ = 1.0 - std::exp(-2.0 * std::numbers::pi * 10.0 / fs);
3732 followUp_ = 1.0 - std::exp(-1.0 / (0.010 * fs));
3733 followDown_ = 1.0 - std::exp(-1.0 / (0.150 * fs));
3734 dynamicsSmoothRate_ = 1.0 - std::exp(-1.0 / (0.005 * fs));
3735 noiseHoldSamples_ = static_cast<int>(0.050 * fs);
3736 loopGlide_ = std::pow(2.0, 1.0 / (kLoopOctaveSeconds * fs));
3737 programFall_ = std::exp(-1.0 / (kLoopCloseSeconds * fs));
3738 noiseFall_ = 1.0 - std::exp(-1.0 / (0.150 * fs));
3739 }
3740
3742 void resetStages() noexcept
3743 {
3744 std::fill(gainRing_.begin(), gainRing_.end(), SampleType(1));
3745 std::fill(feedbackRing_.begin(), feedbackRing_.end(), SampleType(0));
3746 gainPos_ = 0;
3747 feedbackPos_ = 0;
3748 evenMean_.fill(0.0);
3749 focusState_.fill(0.0);
3750 followPower_ = 0.0;
3751 dynamicsGainDb_ = 0.0;
3752 noisePeak_ = 0.0;
3753 noiseHoldLeft_ = 0;
3754 asymmetryNow_ = static_cast<double>(asymmetry_.load(std::memory_order_relaxed));
3755 dynamicsNow_ = static_cast<double>(levelTracking_.load(std::memory_order_relaxed));
3756 feedbackNow_ = static_cast<double>(combLoop_.load(std::memory_order_relaxed));
3757 gainTail_ = 0;
3758 stagesOn_ = false;
3759 feedingBefore_ = false;
3760 loopDelayNow_ = 0.0;
3761 programPeak_ = 0.0;
3762 loopOpen_ = 1.0;
3763 }
3764
3770 [[nodiscard]] int syncStages() noexcept
3771 {
3772 asymmetryTarget_ = static_cast<double>(asymmetry_.load(std::memory_order_relaxed));
3773 dynamicsTarget_ = static_cast<double>(levelTracking_.load(std::memory_order_relaxed));
3774 feedbackTarget_ = static_cast<double>(combLoop_.load(std::memory_order_relaxed));
3775 const SampleType noiseDb = programNoiseDb_.load(std::memory_order_relaxed);
3776 noiseGain_ = (noiseDb > kNoiseOffDb) ? static_cast<double>(decibelsToGain(noiseDb)) : 0.0;
3777 const double focusHz = static_cast<double>(trackingCornerHz_.load(std::memory_order_relaxed));
3778 focusRate_ = (focusHz > 0.0) ? 1.0 - std::exp(-2.0 * std::numbers::pi * focusHz / spec_.sampleRate) : 0.0;
3779
3781 const bool feeding = feedbackTarget_ != 0.0 || feedbackNow_ != 0.0;
3782 if (feeding && !feedingBefore_) std::fill(feedbackRing_.begin(), feedbackRing_.end(), SampleType(0));
3784 // A loop that starts is at its delay at once; one that runs glides to a new one.
3785 if (!feedingBefore_ || !(loopDelayNow_ > 0.0)) loopDelayNow_ = static_cast<double>(feedbackDelay_);
3786 feedingBefore_ = feeding;
3787 closingOn_ = combLoopClosing_.load(std::memory_order_relaxed);
3788 if (!closingOn_) loopOpen_ = 1.0;
3789 feedbackScale_ = SampleType(1) / decibelsToGain(static_cast<SampleType>(driveSmoother_.getTargetValue()));
3790 const bool moving = dynamicsTarget_ != 0.0 || dynamicsNow_ != 0.0 || gainTail_ > 0;
3791 stagesOn_ = feeding || moving || noiseGain_ > 0.0
3792 || asymmetryTarget_ != 0.0 || asymmetryNow_ != 0.0;
3793 if (!feeding) return std::numeric_limits<int>::max();
3794 // At rest a piece is as long as the delay; while the delay glides the
3795 // read between samples needs its neighbours, so two samples less
3796 // than the shortest delay of the way.
3797 if (loopDelayNow_ == static_cast<double>(feedbackDelay_)) return feedbackDelay_;
3798 return std::max(1, static_cast<int>(std::min(loopDelayNow_, static_cast<double>(feedbackDelay_))) - 2);
3799 }
3800
3802 static void approach(double& now, double target, double rate) noexcept
3803 {
3804 now += rate * (target - now);
3805 if (target == 0.0 && std::abs(now) < 1e-5) now = 0.0;
3806 }
3807
3809 [[nodiscard]] SampleType stageNoise(int ch) noexcept
3810 {
3811 uint32_t& s = noiseSeed_[static_cast<size_t>(ch)];
3812 s = s * 1664525u + 1013904223u;
3813 return static_cast<SampleType>(static_cast<double>(static_cast<int32_t>(s)) * (1.0 / 2147483648.0));
3814 }
3815
3822 void stagesBefore(AudioBufferView<SampleType> buffer, int keepChannel) noexcept
3823 {
3824 const int nCh = std::min({ buffer.getNumChannels(), kMaxCh, spec_.numChannels });
3825 const int nS = buffer.getNumSamples();
3826 const int gainMask = gainSize_ - 1, feedbackMask = feedbackSize_ - 1;
3827 for (int i = 0; i < nS; ++i)
3828 {
3832
3833 if (feedbackNow_ != 0.0)
3834 {
3835 // The loop that closes without programme: the level of what
3836 // comes in, falling over kLoopCloseSeconds, opens it.
3837 SampleType amount = static_cast<SampleType>(feedbackNow_);
3838 if (closingOn_)
3839 {
3840 double top = 0.0;
3841 for (int ch = 0; ch < nCh; ++ch)
3842 if (ch != keepChannel)
3843 {
3844 const double level = std::abs(static_cast<double>(buffer.getChannel(ch)[i]));
3845 if (std::isfinite(level)) top = std::max(top, level);
3846 }
3847 programPeak_ = std::max(top, programPeak_ * programFall_);
3849 amount = static_cast<SampleType>(feedbackNow_ * loopOpen_);
3850 }
3851 const double goal = static_cast<double>(feedbackDelay_);
3852 if (loopDelayNow_ == goal)
3853 {
3854 const auto at = static_cast<size_t>((feedbackPos_ + i - feedbackDelay_) & feedbackMask);
3855 for (int ch = 0; ch < nCh; ++ch)
3856 {
3857 if (ch == keepChannel) continue;
3858 const SampleType back = feedbackRing_[static_cast<size_t>(ch) * static_cast<size_t>(feedbackSize_) + at];
3859 buffer.getChannel(ch)[i] -= amount * back;
3860 }
3861 }
3862 else
3863 {
3864 // The delay glides to its new length by a constant ratio
3865 // per sample and is read between samples (four points).
3866 loopDelayNow_ = loopDelayNow_ < goal ? std::min(goal, loopDelayNow_ * loopGlide_)
3867 : std::max(goal, loopDelayNow_ / loopGlide_);
3868 const int whole = static_cast<int>(loopDelayNow_);
3869 const auto part = static_cast<SampleType>(loopDelayNow_ - static_cast<double>(whole));
3870 const int at = feedbackPos_ + i - whole;
3871 for (int ch = 0; ch < nCh; ++ch)
3872 {
3873 if (ch == keepChannel) continue;
3874 const SampleType* line = feedbackRing_.data() + static_cast<size_t>(ch) * static_cast<size_t>(feedbackSize_);
3875 const SampleType back = interpolateHermite(line[static_cast<size_t>((at + 1) & feedbackMask)],
3876 line[static_cast<size_t>(at & feedbackMask)],
3877 line[static_cast<size_t>((at - 1) & feedbackMask)],
3878 line[static_cast<size_t>((at - 2) & feedbackMask)], part);
3879 buffer.getChannel(ch)[i] -= amount * back;
3880 }
3881 }
3882 }
3883
3884 // The dynamics: one gain for every channel, kept for its inverse.
3885 SampleType gain = SampleType(1);
3886 if (dynamicsNow_ != 0.0)
3887 {
3888 double top = 0.0;
3889 for (int ch = 0; ch < nCh; ++ch)
3890 {
3891 if (ch == keepChannel) continue;
3892 double heard = static_cast<double>(buffer.getChannel(ch)[i]);
3893 if (!std::isfinite(heard)) heard = 0.0;
3894 if (focusRate_ > 0.0)
3895 {
3896 double& low = focusState_[static_cast<size_t>(ch)];
3897 low += focusRate_ * (heard - low);
3898 heard = low;
3899 }
3900 top = std::max(top, std::abs(heard));
3901 }
3902 const double power = top * top;
3903 followPower_ += (power > followPower_ ? followUp_ : followDown_) * (power - followPower_);
3904 const double levelDb = 10.0 * std::log10(followPower_ + 1e-12);
3905 const double gainDb = std::clamp(-dynamicsNow_ * (levelDb - kDynamicsReferenceDb), -kDynamicsReachDb, kDynamicsReachDb);
3906 // (The follower ripples at twice the frequency of a tone; its
3907 // inverse arrives a latency later, so the gain is smoothed.)
3909 gain = decibelsToGain(static_cast<SampleType>(dynamicsGainDb_));
3911 }
3912 else
3913 {
3914 dynamicsGainDb_ = 0.0;
3915 if (gainTail_ > 0) --gainTail_; // the inverse of the last gains is still on its way out
3916 }
3917 gainRing_[static_cast<size_t>((gainPos_ + i) & gainMask)] = gain;
3918
3919 for (int ch = 0; ch < nCh; ++ch)
3920 {
3921 if (ch == keepChannel) continue;
3922 SampleType& x = buffer.getChannel(ch)[i];
3923 x *= gain;
3924 if (asymmetryNow_ != 0.0)
3925 {
3926 const double square = static_cast<double>(x) * static_cast<double>(x);
3927 double& mean = evenMean_[static_cast<size_t>(ch)];
3928 if (std::isfinite(square)) mean += evenRate_ * (square - mean);
3929 x += static_cast<SampleType>(asymmetryNow_ * kEvenShare * (square - mean));
3930 }
3931 }
3932
3933 if (noiseGain_ > 0.0)
3934 {
3935 double top = 0.0;
3936 for (int ch = 0; ch < nCh; ++ch)
3937 if (ch != keepChannel)
3938 {
3939 const double level = std::abs(static_cast<double>(buffer.getChannel(ch)[i]));
3940 if (std::isfinite(level)) top = std::max(top, level);
3941 }
3942 if (top >= noisePeak_) { noisePeak_ = top; noiseHoldLeft_ = noiseHoldSamples_; }
3943 else if (noiseHoldLeft_ > 0) --noiseHoldLeft_;
3944 else noisePeak_ += noiseFall_ * (top - noisePeak_);
3945 if (noisePeak_ < 1e-9) noisePeak_ = 0.0;
3946 const SampleType level = static_cast<SampleType>(noisePeak_ * noiseGain_);
3947 for (int ch = 0; ch < nCh; ++ch)
3948 if (ch != keepChannel) buffer.getChannel(ch)[i] += level * stageNoise(ch);
3949 }
3950 }
3951 }
3952
3958 void stagesAfter(AudioBufferView<SampleType> buffer, int keepChannel) noexcept
3959 {
3960 const int nCh = std::min({ buffer.getNumChannels(), kMaxCh, spec_.numChannels });
3961 const int nS = buffer.getNumSamples();
3962 const int gainMask = gainSize_ - 1, feedbackMask = feedbackSize_ - 1;
3963 const bool feeding = feedbackTarget_ != 0.0 || feedbackNow_ != 0.0;
3964 for (int i = 0; i < nS; ++i)
3965 {
3966 const SampleType gain = gainRing_[static_cast<size_t>((gainPos_ + i - stageLatency_) & gainMask)];
3967 const SampleType back = (gain != SampleType(1)) ? SampleType(1) / gain : SampleType(1);
3968 const auto at = static_cast<size_t>((feedbackPos_ + i) & feedbackMask);
3969 for (int ch = 0; ch < nCh; ++ch)
3970 {
3971 if (ch == keepChannel) continue;
3972 SampleType& x = buffer.getChannel(ch)[i];
3973 x *= back;
3974 if (feeding)
3975 {
3976 const SampleType fed = x * feedbackScale_;
3977 feedbackRing_[static_cast<size_t>(ch) * static_cast<size_t>(feedbackSize_) + at] =
3978 std::isfinite(fed) ? std::clamp(fed, SampleType(-2), SampleType(2)) : SampleType(0);
3979 }
3980 }
3981 }
3982 gainPos_ = (gainPos_ + nS) & gainMask;
3983 feedbackPos_ = (feedbackPos_ + nS) & feedbackMask;
3984 }
3985
3987 void maybeCalibrate(int samples) noexcept
3988 {
3989 const bool asked = calibrationRequested_.exchange(false, std::memory_order_acquire);
3990 calibrationWait_ -= samples;
3991 if (!asked && (!calibrationDirty_ || calibrationWait_ > 0)) return;
3992 calibrate();
3993 calibrationWait_ = static_cast<int>(kCalibrationEvery * spec_.sampleRate);
3994 }
3995
3998 {
3999 if (!calibrator_) calibrator_ = std::make_unique<Saturation>();
4000 calibrator_->oversamplingAutomatic_ = false;
4001 calibrator_->oversamplingMode_ = oversamplingMode_;
4002 calibrator_->oversamplingBand_ = oversamplingBand_;
4003 calibrator_->applyOversampling(oversamplingFactor_);
4005
4006 // Pink noise at -18 dBFS RMS over the stretch that is measured, the
4007 // same every time.
4008 calibrationNoise_.assign(static_cast<size_t>(kCalibrationSamples), SampleType(0));
4009 calibrationWork_.assign(static_cast<size_t>(kCalibrationSamples), SampleType(0));
4010 uint32_t seed = 0x2545F491u;
4011 double b0 = 0.0, b1 = 0.0, b2 = 0.0, sum = 0.0;
4012 for (auto& sample : calibrationNoise_)
4013 {
4014 seed = seed * 1664525u + 1013904223u;
4015 const double white = static_cast<double>(static_cast<int32_t>(seed)) * (1.0 / 2147483648.0);
4016 b0 = 0.99765 * b0 + white * 0.0990460;
4017 b1 = 0.96300 * b1 + white * 0.2965164;
4018 b2 = 0.57000 * b2 + white * 1.0526913;
4019 const double pink = b0 + b1 + b2 + white * 0.1848;
4020 sample = static_cast<SampleType>(pink);
4021 }
4022 for (int i = kCalibrationSkip; i < kCalibrationSamples; ++i)
4023 {
4024 const double pink = static_cast<double>(calibrationNoise_[static_cast<size_t>(i)]);
4025 sum += pink * pink;
4026 }
4027 const double scale = std::pow(10.0, kCalibrationLevelDb / 20.0)
4028 / std::sqrt(sum / static_cast<double>(kCalibrationSamples - kCalibrationSkip));
4029 for (auto& sample : calibrationNoise_) sample = static_cast<SampleType>(static_cast<double>(sample) * scale);
4030 }
4031
4037 void calibrate() noexcept
4038 {
4039 calibrationDirty_ = false;
4040 double compensation = 0.0;
4041 if (driveCompensation_.load(std::memory_order_acquire) && calibrator_ && !calibrationNoise_.empty())
4042 {
4043 Saturation& twin = *calibrator_;
4044 Params p = applied_;
4045 p.mix = SampleType(1);
4046 p.outputGain = SampleType(0);
4047 p.analogDrift = SampleType(0);
4050 twin.setAntialiasing(static_cast<Antialiasing>(antialiasOrder_.load(std::memory_order_relaxed)));
4052
4053 // The gain of the curve is the energy of the noise through the
4054 // twin as it stands over the energy of the same noise, 40 dB
4055 // down, through the twin at no drive: everything but the curve
4056 // (the input high-pass on a short stretch of pink noise above
4057 // all) is linear and cancels between the two.
4058 const auto energy = [&](const Params& run, double scale) noexcept {
4059 twin.applyParamSnapshot(run);
4060 twin.reset();
4061 for (size_t i = 0; i < calibrationNoise_.size(); ++i)
4062 calibrationWork_[i] = static_cast<SampleType>(static_cast<double>(calibrationNoise_[i]) * scale);
4063 for (int off = 0; off < kCalibrationSamples; off += kCalibrationBlock)
4064 {
4065 SampleType* channel = calibrationWork_.data() + off;
4066 twin.processChunk(AudioBufferView<SampleType>(&channel, 1, std::min(kCalibrationBlock, kCalibrationSamples - off)));
4067 }
4068 double sum = 0.0;
4069 for (int i = kCalibrationSkip; i < kCalibrationSamples; ++i)
4070 {
4071 const double y = static_cast<double>(calibrationWork_[static_cast<size_t>(i)]);
4072 sum += y * y;
4073 }
4074 return sum;
4075 };
4076 Params linear = p;
4077 linear.driveDb = SampleType(0);
4078 const double reference = energy(linear, kCalibrationQuiet) / (kCalibrationQuiet * kCalibrationQuiet);
4079 const double driven = energy(p, 1.0);
4080 if (reference > 0.0 && driven > 0.0 && std::isfinite(driven) && std::isfinite(reference))
4081 compensation = std::clamp(-kCompensationShare * 10.0 * std::log10(driven / reference), -48.0, 24.0);
4082 }
4083 compensationDb_.store(static_cast<SampleType>(compensation), std::memory_order_relaxed);
4084 outputGainSmoother_.setTargetValue(userOutputGainDb_ + static_cast<float>(compensation));
4085 }
4086
4087 static constexpr int kStageChannels = 16;
4088 static constexpr SampleType kNoiseOffDb = SampleType(-120);
4089 static constexpr SampleType kMinFeedbackHz = SampleType(20);
4090 static constexpr int kMinFeedbackDelay = 16;
4091 static constexpr double kLoopOctaveSeconds = 0.1;
4092 static constexpr double kLoopCloseSeconds = 0.02;
4093 static constexpr double kLoopCloseLevel = 3.1622776601683794e-4;
4094 static constexpr double kDynamicsReferenceDb = -18.0;
4095 static constexpr double kDynamicsReachDb = 24.0;
4096 static constexpr double kEvenShare = 0.25;
4097 static constexpr double kCompensationShare = 0.75;
4098 static constexpr double kCalibrationLevelDb = -18.0;
4099 static constexpr int kCalibrationSamples = 4096;
4100 static constexpr int kCalibrationSkip = 1024;
4101 static constexpr double kCalibrationQuiet = 0.01;
4102 static constexpr int kCalibrationBlock = 256;
4103 static constexpr double kCalibrationEvery = 0.05;
4104
4105 std::atomic<SampleType> asymmetry_ { SampleType(0) };
4106 std::atomic<SampleType> programNoiseDb_ { kNoiseOffDb };
4107 std::atomic<SampleType> levelTracking_ { SampleType(0) };
4108 std::atomic<SampleType> trackingCornerHz_ { SampleType(0) };
4109 std::atomic<SampleType> combLoop_ { SampleType(0) };
4110 std::atomic<SampleType> combLoopHz_ { SampleType(200) };
4111
4112 // Audio thread.
4113 bool stagesOn_ = false;
4114 bool feedingBefore_ = false;
4115 double asymmetryNow_ = 0.0, asymmetryTarget_ = 0.0;
4116 double dynamicsNow_ = 0.0, dynamicsTarget_ = 0.0;
4117 double feedbackNow_ = 0.0, feedbackTarget_ = 0.0;
4118 double loopDelayNow_ = 0.0, loopGlide_ = 1.0;
4119 double programPeak_ = 0.0, programFall_ = 0.999, loopOpen_ = 1.0;
4120 std::atomic<bool> combLoopClosing_ { false };
4121 bool closingOn_ = false;
4122 double stageRate_ = 0.0, evenRate_ = 0.0, followUp_ = 0.0, followDown_ = 0.0, focusRate_ = 0.0;
4123 double followPower_ = 0.0, noiseGain_ = 0.0, noisePeak_ = 0.0, noiseFall_ = 0.0;
4127 SampleType feedbackScale_ = SampleType(1);
4128 std::array<double, kStageChannels> evenMean_ {}, focusState_ {};
4129 std::array<uint32_t, kStageChannels> noiseSeed_ { 0x1234567u, 0x89ABCDEu, 0x3C6EF37u, 0x5851F42u,
4130 0x14057B7u, 0x2B992DDu, 0x7F4A7C1u, 0x61C8864u,
4131 0x0BADF00u, 0x1F123BBu, 0x5DEECE6u, 0x41C64E6u,
4132 0x6C07896u, 0x27D4EB2u, 0x165667Bu, 0x4F6CDD1u };
4133 std::vector<SampleType> gainRing_, feedbackRing_;
4135
4136 // Drive compensation.
4137 std::atomic<bool> driveCompensation_ { false };
4139 bool calibrationDirty_ = false;
4140 std::atomic<bool> calibrationRequested_ { false };
4141 std::atomic<SampleType> compensationDb_ { SampleType(0) };
4142 float userOutputGainDb_ = 0.0f;
4143 std::unique_ptr<Saturation> calibrator_;
4144 std::vector<SampleType> calibrationNoise_, calibrationWork_;
4145
4146 // Minimum-phase oversampling: the dry path through the same filters.
4148 OversamplingBand oversamplingBand_ = OversamplingBand::Preset;
4151
4153 bool prepared_ = false;
4154
4155 static constexpr int kNumAlgorithms = 11;
4156 std::array<std::unique_ptr<detail::SaturationAlgorithm<SampleType>>, kNumAlgorithms> pool_;
4157 std::atomic<detail::SaturationAlgorithm<SampleType>*> active_ { nullptr };
4158 std::atomic<detail::SaturationAlgorithm<SampleType>*> next_ { nullptr };
4159
4164 std::atomic<bool> paramsPending_ { false }; // set when a full queue dropped a snapshot
4165 std::atomic<int> antialiasOrder_ { 0 };
4166
4170 std::atomic<Algorithm> currentAlgoType_ { Algorithm::SoftClip };
4171
4176
4178 // A dedicated DCBlocker, not a Biquad: a 5 Hz high-pass keeps its poles
4179 // 1e-4 from the unit circle, where a float biquad recursion cannot hold
4180 // the zero at DC (it degenerates into an integrator of its own rounding
4181 // error above ~96 kHz and sources the very offset it is here to remove).
4184
4185 // The dry side of the mix (audio thread): the phase of the two
4186 // high-passes, or the filters themselves for the Delta output.
4187 static constexpr double kDcCornerHz = 5.0;
4188 static constexpr double kDcFadeSeconds = 0.05;
4189 static constexpr double kModeDipSeconds = 0.005;
4190 static constexpr double kModeRiseShare = 0.25;
4191 static constexpr double kDryHoldSeconds = 0.05;
4195 // The DC filter in use: its share of the output (1 = filtered), heading for 1
4196 // while a curve in play makes DC and for 0 otherwise (setDcBlocking()).
4197 double dcShare_ = 1.0, dcStep_ = 1.0 / 2400.0;
4198 // The panorama of the drive: its value now and the gains of a block's two ends.
4199 std::atomic<SampleType> drivePan_ { SampleType(0) };
4200 SampleType panNow_ = SampleType(0);
4201 std::array<SampleType, 2> panFrom_ { SampleType(1), SampleType(1) }, panTo_ { SampleType(1), SampleType(1) };
4202 bool panning_ = false;
4203 static constexpr double kDrivePanDb = 6.0;
4204 // The tone after the curve (setTone()).
4205 static constexpr int kToneSections = 4;
4206 static constexpr double kToneRampSeconds = 0.02;
4207 std::array<std::atomic<SampleType>, 4> toneHz_ { SampleType(100), SampleType(500), SampleType(2500), SampleType(8000) };
4208 std::array<std::atomic<SampleType>, 4> toneDb_ { SampleType(0), SampleType(0), SampleType(0), SampleType(0) };
4209 std::atomic<bool> toneDirty_ { false };
4210 std::unique_ptr<BiquadCascade<SampleType, 4, 16>> tone_;
4211 std::array<int, 4> toneLeft_ { -1, -1, -1, -1 }; // samples before a leaving section is switched off, -1 when it is not leaving
4212 bool toneOn_ = false;
4213 bool dcWanted_ = true;
4214 bool dcSnap_ = true;
4216 // A change of processing mode: the wet side dips to the dry over a
4217 // ramp, the mode changes at the bottom, and it comes back.
4219 double modeDip_ = 0.0, modeDipStep_ = 1.0 / 240.0;
4220 bool modeDipping_ = false, modeDipDown_ = false;
4221 bool dryRunning_ = false, dryExact_ = false;
4223
4225
4229
4230 std::unique_ptr<Oversampling<SampleType>> oversampler_;
4233 static constexpr double kAutomaticInternalRate = 88200.0;
4234
4235 std::atomic<SampleType> gainReductionDb_ { SampleType(0) };
4236
4237 std::atomic<bool> adaptiveBlend_ { false };
4238 static constexpr int kMaxCh = 16;
4239 std::array<SampleType, kMaxCh> prevBlendSample_ {};
4240
4241 std::atomic<SampleType> slewSensitivity_ { SampleType(0) };
4242 SampleType slewRateScale_ = SampleType(1);
4243 std::vector<SampleType> driveRamp_, charRamp_;
4244 std::array<SampleType, kMaxCh> prevSlewSample_ {};
4245
4246 float lastPreHpFreq_ = -1.0f;
4247 float lastPostTiltFreq_ = -1.0f;
4248 float lastPostTiltGain_ = std::numeric_limits<float>::quiet_NaN();
4249
4250 // Second-order antialiasing alignment (audio thread).
4251 static constexpr int kAlignRing = 32;
4252 bool secondActive_ = false;
4253 bool alignFresh_ = true;
4254 std::array<std::array<SampleType, kAlignRing>, kMaxCh> alignRing_ {};
4255 std::array<SampleType, kAlignRing> keepRing_ {};
4256 int alignPos_ = 0;
4257 std::array<SampleType, kMaxCh> dryHold_ {};
4258 std::array<SampleType, kMaxCh> dryHold2_ {};
4260};
4261
4262} // namespace dspark
Main generator class for analog-style random modulation.
void setSmoothing(bool shouldBeEnabled, Real timeInMs=static_cast< Real >(50.0)) noexcept
Enables one-pole smoothing of the held targets.
void reseed(std::uint64_t newSeed) noexcept
Request a lock-free reseed of the internal PRNG.
void prepare(double sampleRate) noexcept
Prepare the generator with the audio sample rate.
Real getNextSample() noexcept
Generate and return the next modulation sample.
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Owning audio buffer with contiguous, 32-byte aligned storage.
AudioBufferView< T, MaxChannels > toView() noexcept
Returns a non-owning mutable view of this buffer. The view's channel capacity is propagated from MaxC...
int getNumChannels() const noexcept
Returns the number of active channels.
T * getChannel(int ch) noexcept
Returns a pointer to the sample data.
int getNumSamples() const noexcept
Returns the number of samples per channel.
void resize(int numChannels, int numSamples)
Allocates the buffer for the given dimensions.
Biquad filter using Transposed Direct Form II (TDF-II) with thread-safe updates.
Definition Biquad.h:853
void setCoeffs(const BiquadCoeffs &c) noexcept
Sets the filter coefficients asynchronously (control thread).
Definition Biquad.h:904
void reset() noexcept
Resets all per-channel filter states to zero to avoid ringing/clicks.
Definition Biquad.h:1003
void processBlock(AudioBufferView< T > buffer) noexcept
Processes a full audio buffer in-place.
Definition Biquad.h:1146
DC blocking filter with configurable Butterworth order (1-10).
Definition DCBlocker.h:91
void prepare(double sampleRate, int numChannels=2, double cutoffHz=-1.0)
Prepares the DC blocker, resetting internal states and precalculating coefficients.
Definition DCBlocker.h:113
void setOrder(int order) noexcept
Sets the filter order (1-10). Thread-safe.
Definition DCBlocker.h:148
void reset() noexcept
Clears the internal history states to zero.
Definition DCBlocker.h:285
Pre-allocated, SIMD-friendly dry/wet blender for real-time audio.
Definition DryWetMixer.h:83
void setLatencyCompensation(int samples)
Delays the captured dry signal to compensate for an effect's internal latency (e.g....
int getDryCapturedSamples() const noexcept
Returns the number of samples valid from the last pushDry() call.
void mixWet(AudioBufferView< T > wetBuffer, T targetMix) noexcept
Blends the stored dry signal with the current (wet) buffer in-place.
void reset() noexcept
Resets the internal buffer and smoothing states to zero.
int getDryNumChannels() const noexcept
Returns the internal capacity of channels in the dry buffer.
void pushDry(const AudioBufferView< const T > &input) noexcept
Captures a snapshot of the dry (unprocessed) signal.
void prepare(const AudioSpec &spec)
Allocates the internal dry buffer for the given audio spec.
const T * getDryChannel(int ch) const noexcept
Retrieves a read-only pointer to the captured dry channel data.
Multi-band saturation: crossover split, a Saturation per band, sum.
Carries a dry signal through the same round trip as an Oversampling engine, so that a dry/wet mix add...
void process(AudioBufferView< T > dry) noexcept
Passes a block of the dry signal through the path, in place.
void prepare(const AudioSpec &spec, const Engine &engine)
Sizes the path for an engine.
void reset() noexcept
Clears the path's memory.
Band
The band the first stage keeps (see the constructor).
static constexpr int factorForRate(double sampleRate, double minimumInternalRate=176400.0, int maxFactor=1<< kMaxStages) noexcept
The smallest factor that brings a host rate up to an internal rate.
Professional multi-algorithm saturation processor with analog simulation.
ProcessingMode procMode_
static constexpr double kModeDipSeconds
The fall of a mode change's dip.
void pushParam(Fn &&mutate)
void calibrate() noexcept
std::vector< SampleType > calibrationWork_
std::atomic< bool > combLoopClosing_
static constexpr double kAutomaticInternalRate
Rate the automatic factor reaches.
void stagesBefore(AudioBufferView< SampleType > buffer, int keepChannel) noexcept
std::array< double, kStageChannels > evenMean_
static constexpr double kDryHoldSeconds
It is kept up this long after the mix has gone full wet.
SampleType getCurveCurvature() const noexcept
How fast the Curve algorithm turns (see setCurveShape()).
void dispatchSaturator(detail::SaturationAlgorithm< SampleType > *baseAlgo, AudioBufferView< SampleType > buffer, bool useDrift) noexcept
Smoothers::StateVariableSmoother driveSmoother_
SampleType getCurveAsymmetry() const noexcept
How unlike the two halves of the Curve algorithm are (see setCurveShape()).
SampleType getCurveHardness() const noexcept
How far the Curve algorithm stays straight (see setCurveShape()).
@ LinearPhase
Linear-phase half-bands: the latency of the factor, the dry path a delay.
@ MinimumPhase
Elliptic allpass half-bands: a few samples of latency, the dry path through the same filters.
void setDrivePan(SampleType pan) noexcept
The panorama of the drive, -1 to 1 (0, the default, is centred): the first channel the curve sees get...
std::atomic< SampleType > gainReductionDb_
OversamplingBand getOversamplingBand() const noexcept
The band of the oversampler's first stage (see setOversamplingBand()).
int feedbackDelayFor(int latency) const noexcept
Antialiasing getAntialiasing() const noexcept
The selected antialiasing order.
bool oversamplingAutomatic_
The factor follows the host rate (setAutomaticOversampling()).
void setProcessingMode(ProcessingMode m)
Sets the routing configuration for multi-channel processing.
detail::DryPhase dryPreLead_
static constexpr SampleType kMinFeedbackHz
Lowest frequency of the tuned feedback.
void setMix(SampleType mix01)
Sets the global Dry/Wet blend.
void maybeCalibrate(int samples) noexcept
AudioBuffer< SampleType > dryAligned_
std::array< SampleType, kAlignRing > keepRing_
SampleType getToneFrequency(int section) const noexcept
void designTone(int ramp) noexcept
The tone's sections from what was published: a section at 0 dB ramps to the identity and leaves; one ...
std::atomic< bool > adaptiveBlend_
std::atomic< SampleType > slewSensitivity_
SampleType getCombLoopFrequency() const noexcept
The frequency of the tuned feedback as it runs: what the latency allows of the one asked for.
std::atomic< bool > paramsPending_
AnalogRandom::Generator< SampleType > rightDrift_
ProcessingMode pendingMode_
detail::CurveAlgorithm< SampleType > & curve() noexcept
void setAlgorithm(Algorithm algo)
Sets the saturation algorithm topology.
void resetStages() noexcept
void setOversampling(int factor)
Configures internal polyphase oversampling to reduce aliasing.
double loopOpen_
The loop that closes: the level of the input, its fall, how open the loop is.
std::atomic< bool > toneDirty_
void setLevelTracking(SampleType amount) noexcept
Dynamics around the curve: how much the level into it depends on the level of the programme.
std::atomic< int > antialiasOrder_
Antialiasing order, mirror for getState.
void setOversamplingMode(OversamplingMode mode)
Chooses the filters of the oversampler (NOT real-time safe, as setOversampling()).
std::atomic< SampleType > asymmetry_
std::vector< SampleType > driveRamp_
SampleType slewRateScale_
Processing rate / 96 kHz.
void applyOutputGain(AudioBufferView< SampleType > buffer) noexcept
std::unique_ptr< Saturation > calibrator_
AudioBuffer< SampleType > msKeepBuffer_
MidOnly/SideOnly channel snapshot.
std::atomic< SampleType > levelTracking_
static constexpr double kLoopOctaveSeconds
Time the loop's delay takes to glide an octave.
bool curveMakesDc() noexcept
Whether a curve in play makes DC from a signal without it (the pre-filter takes the input's away): me...
static constexpr int kAlignRing
‍largest delay (16 processing samples).
static constexpr double kModeRiseShare
Its rise takes four times as long (the curves settle from rest).
void setCurveBase(CurveBase base) noexcept
The base curve of the Curve algorithm, the shape its three controls bend (see CurveBase); tanh by def...
void setCharacter(SampleType c)
Adjusts the specific character/bias of the selected algorithm.
std::atomic< SampleType > programNoiseDb_
std::unique_ptr< Oversampling< SampleType > > oversampler_
int poleDecaySamples(const BiquadCoeffs &c) const noexcept
Samples for the poles of a section to fall 140 dB (what it adds once transparent).
bool calibrationDirty_
The curve moved since the last measurement (audio thread).
std::atomic< detail::SaturationAlgorithm< SampleType > * > active_
OversamplingBand oversamplingBand_
setOversamplingBand() (setup thread).
static constexpr double kDynamicsReachDb
Most gain the dynamics apply, either way.
std::atomic< detail::SaturationAlgorithm< SampleType > * > next_
void setOutputGain(SampleType dB)
Sets the post-saturation make-up or trim gain.
static constexpr double kDcFadeSeconds
The DC filter comes in or goes out in this time.
static constexpr double kCompensationShare
Share of the measured gain taken back.
SampleType stageNoise(int ch) noexcept
std::array< std::atomic< SampleType >, 4 > toneHz_
static constexpr SampleType kNoiseOffDb
Programme noise at or under this is off.
static constexpr double kCalibrationEvery
Seconds between two measurements while the curve moves.
std::atomic< Algorithm > currentAlgoType_
std::array< SampleType, kMaxCh > prevSlewSample_
void setProgramNoise(SampleType levelDb) noexcept
Adds noise that follows the programme, before the curve.
static constexpr int kNumAlgorithms
SpscQueue< Params > paramQueue_
AudioBuffer< SampleType > tempBuffer_
static constexpr double kCalibrationQuiet
Level of the reference run (-40 dB).
Smoothers::LinearSmoother crossfader_
std::atomic< bool > calibrationRequested_
A setter outside the parameter queue moved it.
DryWetMixer< SampleType > dryWetMixer_
OversamplingMode oversamplingMode_
Smoothers::LinearSmoother mixSmoother_
AudioBuffer< SampleType > driftBuffer_
Biquad< SampleType > preFilter_
int secondOrderDelay() const noexcept
Smoothers::StateVariableSmoother postTiltFreqSmoother_
void setCurveShape(SampleType hardness, SampleType curvature, SampleType asymmetry) noexcept
Shapes the Curve algorithm.
std::array< int, 4 > toneLeft_
SampleType getGainReductionDb() const noexcept
Calculates the peak gain reduction (clipping amount) for metering.
void applyModeDip(AudioBufferView< SampleType > &buffer) noexcept
A change of processing mode: the wet side goes to the aligned dry over a ramp, the mode changes at th...
OutputMode outputMode_
void processSaturationPipeline(AudioBufferView< SampleType > buffer) noexcept
void setAntialiasing(Antialiasing mode) noexcept
Selects the antialiasing order (see Antialiasing). Any thread; SecondOrder changes getLatency() at on...
void setAntialiasing(bool on) noexcept
Enables first-order antiderivative anti-aliasing (ADAA) on the memoryless curves (SoftClip / Tube / H...
Params applied_
The snapshot the audio thread applied last.
typename Oversampling< SampleType >::Band OversamplingBand
The band the oversampler's first stage keeps (see setOversamplingBand()).
const detail::CurveAlgorithm< SampleType > & curve() const noexcept
static constexpr double kDynamicsReferenceDb
Level the dynamics bring the programme to.
Algorithm
Defines the harmonic generation topology.
SampleType feedbackScale_
Smoothers::StateVariableSmoother preHpSmoother_
void setPreFilterHpFrequency(SampleType hz)
Configures a pre-saturation high-pass filter.
std::atomic< bool > driveCompensation_
static constexpr double kCalibrationLevelDb
RMS level of the measuring noise.
std::array< std::array< SampleType, kAlignRing >, kMaxCh > alignRing_
static constexpr double kDrivePanDb
std::vector< SampleType > charRamp_
Per-sample drive/character (processing rate).
void reset() noexcept
Clears all internal states, phase memory, and history buffers.
void setAdaptiveBlend(bool on) noexcept
Enables program-dependent saturation density.
std::array< SampleType, 2 > panTo_
static constexpr int kStageChannels
Channels the stages keep a memory for.
int getOversamplingFactor() const noexcept
Retrieves the current oversampling factor.
static constexpr int kToneSections
double loopGlide_
The loop's delay now, in samples (0: not started), and its glide per sample.
static constexpr int kCalibrationSkip
Samples left out while the twin settles.
static constexpr double kDcCornerHz
void setOversamplingBand(OversamplingBand band)
Chooses the band the oversampler's first stage keeps (NOT real-time safe, as setOversampling()).
SampleType getDrivePan() const noexcept
std::atomic< SampleType > combLoop_
~Saturation()=default
OutputMode
Determines the final output signal routing.
SampleType getDriveCompensationDb() const noexcept
The gain the drive compensation is applying, in decibels (0 while it is off).
OversamplingDryPath< SampleType > dryPath_
bool isOversamplingAutomatic() const noexcept
Whether the factor follows the host rate (setAutomaticOversampling()).
std::array< SampleType, 2 > panFrom_
static constexpr double kLoopCloseSeconds
Time constant the programme's level falls with, for the loop that closes.
void applyAdaptiveBlend(AudioBufferView< SampleType > buffer) noexcept
Program-dependent dry/wet density blend (base rate, L/R domain). The dry reference is the DryWetMixer...
void applyParamSnapshot(const Params &p)
static constexpr double kToneRampSeconds
void processCore(ExactAlgo *algo, AudioBufferView< SampleType > buffer, bool useDrift) noexcept
int syncStages() noexcept
static void approach(double &now, double target, double rate) noexcept
void setCombLoop(SampleType amount, SampleType hz) noexcept
Feeds the output of the curve back into it, inverted, one period of a frequency late.
void setCombLoopClosing(bool on) noexcept
Closes the tuned feedback when the programme stops.
double applyDcShare(DCBlocker< SampleType > &filter, AudioBufferView< SampleType > view, double share) noexcept
The DC filter on a block by its share, which moves toward 1 while wanted and toward 0 otherwise (the ...
void stagesAfter(AudioBufferView< SampleType > buffer, int keepChannel) noexcept
void setDriveCompensation(bool on)
Takes back, at the output, the level the drive adds.
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (setup/UI threads: it forwards the stored oversampling factor to setO...
void process(AudioBufferView< SampleType > buffer) noexcept
Compatibility alias of processBlock(), with the same thread and preparation contract....
void setOutputMode(OutputMode m)
Sets the output signal path.
SampleType getCombLoop() const noexcept
The amount of the tuned feedback (see setCombLoop()).
std::unique_ptr< BiquadCascade< SampleType, 4, 16 > > tone_
bool getCombLoopClosing() const noexcept
std::atomic< SampleType > drivePan_
std::atomic< SampleType > compensationDb_
static constexpr double kLoopCloseLevel
-70 dBFS: under it there is no programme.
Smoothers::LinearSmoother postTiltGainSmoother_
std::atomic< SampleType > combLoopHz_
void alignSecondOrder(AudioBufferView< SampleType > view, int keepChannel, int keepSamples, int factor, bool seed) noexcept
Completes the second-order delay to whole base samples.
std::atomic< SampleType > trackingCornerHz_
ProcessingMode
Determines how the stereo field is processed.
bool feedingBefore_
The feedback ran in the last block.
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
SampleType getTrackingCorner() const noexcept
The band the dynamics follower listens to, in hertz (0: all of it).
SampleType panGain(int ch, int i, int samples) const noexcept
The drive's gain of a channel at a sample of the block (a straight line between its ends).
void setTrackingCorner(SampleType hz) noexcept
The band the follower of setLevelTracking() listens to.
static constexpr int kMaxCh
std::vector< SampleType > calibrationNoise_
int oversamplingFactor_
2x by default: the curves alias at 1x (see setOversampling()).
void processBlock(AudioBufferView< SampleType > buffer) noexcept
Processes an audio block in-place (AudioProcessor standard contract).
int getLatency() const noexcept
Reports the processor's algorithmic latency in samples.
DCBlocker< SampleType > dcBlocker_
std::array< double, kStageChannels > focusState_
static constexpr int kCalibrationBlock
std::array< SampleType, kMaxCh > dryHold2_
Second dry sample (2x).
SampleType getAsymmetry() const noexcept
The second-order term before the curve (see setAsymmetry()).
static constexpr int kCalibrationSamples
Length of a measurement.
AnalogRandom::Generator< SampleType > leftDrift_
Smoothers::LinearSmoother driftSmoother_
OversamplingMode getOversamplingMode() const noexcept
The filters of the oversampler (see setOversamplingMode()).
static constexpr double kEvenShare
Share of the square added at asymmetry 1.
Smoothers::LinearSmoother characterSmoother_
bool isDriveCompensation() const noexcept
Whether the level the drive adds is taken back (see setDriveCompensation()).
SampleType getLevelTracking() const noexcept
The dynamics around the curve (see setLevelTracking()).
void setPostFilterTilt(SampleType centerHz, SampleType amountDb)
Configures a post-saturation first-order tilt EQ.
SampleType getToneGain(int section) const noexcept
void setAsymmetry(SampleType amount) noexcept
Adds a second-order term before the curve of any algorithm.
void setTone(int section, SampleType hz, SampleType gainDb) noexcept
A section of the tone after the curve: 0 a low shelf (100 Hz by default), 1 and 2 bells of Q 0....
void setAutomaticOversampling(bool on)
Lets the host rate choose the factor (NOT real-time safe, as setOversampling()).
Saturation & operator=(const Saturation &)=delete
AudioBuffer< SampleType > dcScratch_
void handleParameterChanges()
CurveBase
How the oversampler filters (see setOversamplingMode()).
void setDcBlocking(bool on)
Enables or disables the fixed 5 Hz DC blocker.
int getLatencySamples() const noexcept
Compatibility alias of getLatency(), in prepared-rate samples.
std::array< std::atomic< SampleType >, 4 > toneDb_
CurveBase getCurveBase() const noexcept
DCBlocker< SampleType > dryDc_
Smoothers::LinearSmoother outputGainSmoother_
void prepare(const AudioSpec &spec)
Prepares all internal resources, filters, and buffers.
std::array< std::unique_ptr< detail::SaturationAlgorithm< SampleType > >, kNumAlgorithms > pool_
void setAnalogDrift(SampleType i)
Injects true-stereo pseudo-random low-frequency modulation (drift) into the saturation drive.
std::array< SampleType, kMaxCh > dryHold_
static constexpr int kMinFeedbackDelay
Shortest feedback line (and piece of a block).
Biquad< SampleType > dryPre_
std::vector< SampleType > feedbackRing_
void setDrive(SampleType dB)
Sets the input drive gain.
void configureProcessingRate(bool keepTargets)
double modeDipStep_
0 = the wet side, 1 = the dry
void setSlewSensitivity(SampleType amount) noexcept
Sets a derivative-based (slew rate) saturation multiplier.
int calibrationWait_
Samples before the next measurement may run (audio thread).
std::array< uint32_t, kStageChannels > noiseSeed_
detail::DryPhase dryDcLead_
std::array< SampleType, kMaxCh > prevBlendSample_
Biquad< SampleType > postFilter_
Antialiasing
Antiderivative antialiasing order (see setAntialiasing()).
std::vector< SampleType > gainRing_
int secondOrderBaseDelay() const noexcept
SampleType getProgramNoise() const noexcept
Level of the programme noise under the peak, in decibels (see setProgramNoise()).
static void sanitizeParams(Params &p, const Params &prev) noexcept
Saturation(const Saturation &)=delete
Algorithm getCurrentAlgorithm() const noexcept
Retrieves the currently active underlying algorithm.
RAII wrapper that acquires the lock on construction and releases on destruction.
Definition SpinLock.h:143
RAII wrapper that tries to acquire the lock without blocking.
Definition SpinLock.h:169
bool isLocked() const noexcept
Queries whether the lock acquisition was successful.
Definition SpinLock.h:185
A minimal, real-time safe spin lock with a TTAS wait loop.
Definition SpinLock.h:77
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
static void langevin(double x, double &L, double &Lp) noexcept
Definition Saturation.h:776
void antiderivatives(double x, double L, double &G, double &P, double &Q) const noexcept
Definition Saturation.h:793
static const AdaaTapeTable & instance()
Definition Saturation.h:769
void reset() noexcept override
Resets internal states (filters, phase, memory).
Definition Saturation.h:723
void update(T drive, T, const AudioSpec &) noexcept override
Updates internal coefficients dependent on block-rate parameters.
Definition Saturation.h:726
Saturation< T >::Algorithm getType() const noexcept override
Identifies the exact algorithm type for CRTP static dispatch.
Definition Saturation.h:724
T processSample(T sample, T, T, int) noexcept
Definition Saturation.h:734
void prepare(const AudioSpec &) noexcept override
Prepares the algorithm with the current audio specification.
Definition Saturation.h:719
void setShape(T hardness, T curvature, T asymmetry) noexcept
void setBase(int base) noexcept
T shape(T x) const noexcept
void prepare(const AudioSpec &) noexcept override
Prepares the algorithm with the current audio specification.
T processSample(T sample, T drive, T, int) noexcept
T getAsymmetry() const noexcept
int getBase() const noexcept
T getCurvature() const noexcept
void reset() noexcept override
Resets internal states (filters, phase, memory).
T getHardness() const noexcept
Saturation< T >::Algorithm getType() const noexcept override
Identifies the exact algorithm type for CRTP static dispatch.
void update(T, T, const AudioSpec &) noexcept override
Updates internal coefficients dependent on block-rate parameters.
T bend(T v, bool negative) const noexcept
T processSample(T sample, T, T, int ch) noexcept
void reset() noexcept override
Resets internal states (filters, phase, memory).
void update(T drive, T, const AudioSpec &spec) noexcept override
Updates internal coefficients dependent on block-rate parameters.
void prepare(const AudioSpec &spec) noexcept override
Prepares the algorithm with the current audio specification.
Saturation< T >::Algorithm getType() const noexcept override
Identifies the exact algorithm type for CRTP static dispatch.
Gives the dry side of a mix the phase that a high-pass leaves in the wet side, and none of its magnit...
void reset() noexcept
Clears the memory (the amount stays).
void process(AudioBufferView< T > buffer) noexcept
A stretch of a buffer, in place.
void prepare(double sampleRate, int channels)
Sizes the state (allocates).
void aim(bool on) noexcept
Where the amount goes.
void land() noexcept
Puts the amount where it goes, without the fade.
void setCorner(double hz) noexcept
Moves the corner (a tangent, when it changes).
static constexpr double kButterworthShare
T processSecond(T sample, T drive, T character, int ch) noexcept
Definition Saturation.h:603
T processSample(T sample, T drive, T character, int) noexcept
Definition Saturation.h:615
Saturation< T >::Algorithm getType() const noexcept override
Identifies the exact algorithm type for CRTP static dispatch.
Definition Saturation.h:592
void reset() noexcept override
Resets internal states (filters, phase, memory).
Definition Saturation.h:594
void prepare(const AudioSpec &) noexcept override
Prepares the algorithm with the current audio specification.
Definition Saturation.h:591
T processSample(T sample, T drive, T character, int ch) noexcept
Definition Saturation.h:412
T processSecond(T sample, T drive, T character, int ch) noexcept
Definition Saturation.h:393
void reset() noexcept override
Resets internal states (filters, phase, memory).
Definition Saturation.h:382
Saturation< T >::Algorithm getType() const noexcept override
Identifies the exact algorithm type for CRTP static dispatch.
Definition Saturation.h:389
void prepare(const AudioSpec &) noexcept override
Prepares the algorithm with the current audio specification.
Definition Saturation.h:381
void reset() noexcept override
Resets internal states (filters, phase, memory).
void prepare(const AudioSpec &spec) noexcept override
Prepares the algorithm with the current audio specification.
Saturation< T >::Algorithm getType() const noexcept override
Identifies the exact algorithm type for CRTP static dispatch.
T processSecond(T sample, T drive, T character, int ch) noexcept
T processSample(T sample, T drive, T character, int ch) noexcept
static constexpr bool kSelfAligned
processSecond() delays by exactly the common delay (no padding).
void update(T drive, T character, const AudioSpec &spec) noexcept override
Updates internal coefficients dependent on block-rate parameters.
int delay_
Latched common second-order delay.
Definition Saturation.h:147
unsigned delayArm_
Channels whose delay line must be seeded.
Definition Saturation.h:149
T delayBy(T y, int ch, int n) noexcept
Definition Saturation.h:162
int order_
Latched order (audio thread).
Definition Saturation.h:146
virtual void reset() noexcept=0
Resets internal states (filters, phase, memory).
virtual void update(T, T, const AudioSpec &) noexcept
Updates internal coefficients dependent on block-rate parameters.
Definition Saturation.h:96
int commonDelay() const noexcept
The latched common second-order delay (processing samples).
Definition Saturation.h:134
void setAntialias(int order) noexcept
Antiderivative antialiasing order on the memoryless curves: 0 off, 1 first order (SoftClip/Tube/HardC...
Definition Saturation.h:110
std::array< std::array< T, kMaxDelay >, kAaCh > alignHold_
Definition Saturation.h:211
T padKernel(T y, int ch) noexcept
Definition Saturation.h:140
unsigned halfArm_
Channels whose interpolator must be seeded.
Definition Saturation.h:150
void latchOrder(int commonDelay=1) noexcept
Latches the order for the coming block (audio thread, before update()) and the common second-order de...
Definition Saturation.h:122
T align(T y, int ch) noexcept
Definition Saturation.h:137
virtual Saturation< T >::Algorithm getType() const noexcept=0
Identifies the exact algorithm type for CRTP static dispatch.
virtual void prepare(const AudioSpec &spec) noexcept=0
Prepares the algorithm with the current audio specification.
std::array< std::array< T, 3 >, kAaCh > halfHold_
Definition Saturation.h:212
virtual ~SaturationAlgorithm()=default
T delayHalfSample(T y, int ch) noexcept
Definition Saturation.h:185
unsigned armMask_
Channels whose order-2 history must be seeded.
Definition Saturation.h:148
int order() const noexcept
The latched order (audio thread).
Definition Saturation.h:131
Saturation< T >::Algorithm getType() const noexcept override
Identifies the exact algorithm type for CRTP static dispatch.
Definition Saturation.h:235
void reset() noexcept override
Resets internal states (filters, phase, memory).
Definition Saturation.h:228
T processSample(T sample, T drive, T character, int ch) noexcept
Definition Saturation.h:259
void prepare(const AudioSpec &) noexcept override
Prepares the algorithm with the current audio specification.
Definition Saturation.h:227
T processSecond(T sample, T drive, T character, int ch) noexcept
Definition Saturation.h:239
T processSecond(T sample, T drive, T character, int ch) noexcept
void reset() noexcept override
Resets internal states (filters, phase, memory).
void prepare(const AudioSpec &spec) noexcept override
Prepares the algorithm with the current audio specification.
T processSample(T sample, T drive, T character, int ch) noexcept
void update(T drive, T, const AudioSpec &spec) noexcept override
Updates internal coefficients dependent on block-rate parameters.
Saturation< T >::Algorithm getType() const noexcept override
Identifies the exact algorithm type for CRTP static dispatch.
void update(T, T, const AudioSpec &spec) noexcept override
Updates internal coefficients dependent on block-rate parameters.
T processSample(T sample, T drive, T character, int ch) noexcept
T processSecond(T sample, T drive, T character, int ch) noexcept
Saturation< T >::Algorithm getType() const noexcept override
Identifies the exact algorithm type for CRTP static dispatch.
void reset() noexcept override
Resets internal states (filters, phase, memory).
void processBoth(T sample, T drive, T character, int ch, T &first, T &second) noexcept
T processFirst(T sample, T drive, T character, int ch) noexcept
void prepare(const AudioSpec &spec) noexcept override
Prepares the algorithm with the current audio specification.
T processSecond(T sample, T drive, T character, int ch) noexcept
Definition Saturation.h:315
void reset() noexcept override
Resets internal states (filters, phase, memory).
Definition Saturation.h:304
void prepare(const AudioSpec &) noexcept override
Prepares the algorithm with the current audio specification.
Definition Saturation.h:303
T processSample(T sample, T drive, T character, int ch) noexcept
Definition Saturation.h:335
Saturation< T >::Algorithm getType() const noexcept override
Identifies the exact algorithm type for CRTP static dispatch.
Definition Saturation.h:311
T processSecond(T sample, T drive, T character, int ch) noexcept
Definition Saturation.h:658
Saturation< T >::Algorithm getType() const noexcept override
Identifies the exact algorithm type for CRTP static dispatch.
Definition Saturation.h:643
void prepare(const AudioSpec &) noexcept override
Prepares the algorithm with the current audio specification.
Definition Saturation.h:635
void reset() noexcept override
Resets internal states (filters, phase, memory).
Definition Saturation.h:636
T processSample(T sample, T drive, T character, int ch) noexcept
Definition Saturation.h:677
double logCosh(double x) noexcept
Stable log(cosh(x)), shared by the tanh antiderivative kernels.
Definition LogCosh.h:18
Main namespace for the DSPark framework.
T decibelsToGain(T dB, T minusInfinityDb=T(-100)) noexcept
Converts a value in decibels to linear gain.
Definition DspMath.h:77
T interpolateHermite(T y0, T y1, T y2, T y3, T frac) noexcept
4-point, 3rd-order Hermite interpolation (optimized x-form).
T mapRange(T value, T inMin, T inMax, T outMin, T outMax) noexcept
Maps a value from one range to another (linear interpolation).
Definition DspMath.h:117
T gainToDecibels(T gain, T minusInfinityDb=T(-100)) noexcept
Converts a linear gain value to decibels.
Definition DspMath.h:92
T fastTanh(T x) noexcept
Fast tanh approximation using a Pade [5,4] rational function.
Definition DspMath.h:169
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
int maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
Stores normalised biquad coefficients (b0, b1, b2, a1, a2), always double.
Definition Biquad.h:107
static BiquadCoeffs makeHighPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
High-pass filter.
Definition Biquad.h:143
static BiquadCoeffs makePeak(double sampleRate, double freq, double Q, double gainDb) noexcept
Peak (parametric EQ) filter.
Definition Biquad.h:201
static BiquadCoeffs makeTilt(double sampleRate, double pivotFreq, double gainDb) noexcept
Creates a first-order tilt filter.
Definition Biquad.h:578
BiquadCoeffs bypassed() const noexcept
The set with these poles whose numerator equals its denominator.
Definition Biquad.h:661
static BiquadCoeffs makeLowPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Low-pass filter.
Definition Biquad.h:119
static BiquadCoeffs makeLowShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
Low-shelf filter.
Definition Biquad.h:417
static BiquadCoeffs makeHighShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
High-shelf filter.
Definition Biquad.h:447
Static utility for Mid/Side stereo encoding and decoding.
Definition MidSide.h:59
static void encode(AudioBufferView< T > buffer) noexcept
Encodes an entire stereo buffer from Left/Right to Mid/Side.
Definition MidSide.h:108
static void decode(AudioBufferView< T > buffer) noexcept
Decodes an entire stereo buffer from Mid/Side back to Left/Right.
Definition MidSide.h:138
ProcessingMode processingMode
Linear ramp smoother for predictable, uniform interpolation.
Definition Smoothers.h:60
void setCurrentAndTargetValue(float value) noexcept
Definition Smoothers.h:412
void reset(double sampleRate, float rampTimeMilliseconds, float initialValue=0.0f) noexcept
Definition Smoothers.h:383
float getTargetValue() const noexcept
Definition Smoothers.h:69
void setTargetValue(float newTarget) noexcept
Definition Smoothers.h:392
bool isSmoothing() const noexcept
Definition Smoothers.h:420
float getCurrentValue() const noexcept
Definition Smoothers.h:68
Second-order state variable filter (SVF) smoother (TPT implementation).
Definition Smoothers.h:259
void reset(double sampleRate, float timeConstantMilliseconds, float q=0.707f, float initialValue=0.0f) noexcept
Definition Smoothers.h:687
void setTargetValue(float newTarget) noexcept
Definition Smoothers.h:714
float getTargetValue() const noexcept
Definition Smoothers.h:268
static constexpr double kB
Definition Saturation.h:453
double p(double u) const noexcept
Definition Saturation.h:470
void setCharacter(double a) noexcept
Definition Saturation.h:459
double f(double u) const noexcept
Definition Saturation.h:471
static constexpr double kLimit
Definition Saturation.h:453
double average(double u0, double u1, double u2) const noexcept
Definition Saturation.h:477
double crit[2]
Critical points of p, ascending.
Definition Saturation.h:456
double A
Quadratic coefficient (0.25 character).
Definition Saturation.h:455
double h2
Inputs one and two samples ago.
Definition Saturation.h:955
Point point(double H, double seed) const noexcept
Definition Saturation.h:993
static double div(const Point &p, const Point &q) noexcept
void reset(double u, double alphaIn) noexcept
Definition Saturation.h:959
const AdaaTapeTable * table
Definition Saturation.h:953
static double average(const Point &p0, const Point &p1, const Point &p2) noexcept
double rho
Curve of the points held.
Definition Saturation.h:954
double process(double H, double alphaIn) noexcept
Definition Saturation.h:968
void setCurve(double alphaIn) noexcept
Definition Saturation.h:985