DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
NormalizedLadder.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
50#include "AudioBuffer.h"
51#include "Biquad.h"
52#include "DenormalGuard.h"
53#include "SimdOps.h"
54
55#include <algorithm>
56#include <array>
57#include <cassert>
58#include <cmath>
59
60namespace dspark {
61
70template <typename T, int MaxChannels = 8>
72{
73public:
75 struct Coeffs
76 {
77 double c1 = 1.0, s1 = 0.0;
78 double c2 = 1.0, s2 = 0.0;
79 double v0 = 1.0, v1 = 0.0, v2 = 0.0;
80 };
81
92 [[nodiscard]] static Coeffs fromBiquad(const BiquadCoeffs& b) noexcept
93 {
94 constexpr double kLimit = 1.0 - 1e-12;
95 Coeffs l;
96 const double k2 = std::clamp(b.a2, -kLimit, kLimit);
97 const double k1 = std::clamp(b.a1 / (1.0 + k2), -kLimit, kLimit);
98 // The denominator the rotations realise (the given one for a stable set).
99 const double a1 = k1 * (1.0 + k2);
100 const double a2 = k2;
101 l.s1 = k1; l.c1 = std::sqrt(1.0 - k1 * k1);
102 l.s2 = k2; l.c2 = std::sqrt(1.0 - k2 * k2);
103 l.v2 = b.b2;
104 const double middle = b.b1 - b.b2 * a1;
105 l.v1 = middle / l.c2;
106 l.v0 = (b.b0 - b.b2 * a2 - middle * k1) / (l.c1 * l.c2);
107 return l;
108 }
109
115 [[nodiscard]] static BiquadCoeffs toBiquad(const Coeffs& l) noexcept
116 {
117 BiquadCoeffs b;
118 b.a2 = l.s2;
119 b.a1 = l.s1 * (1.0 + l.s2);
120 b.b2 = l.v2;
121 b.b1 = l.v2 * b.a1 + l.v1 * l.c2;
122 b.b0 = l.v2 * b.a2 + l.v1 * l.c2 * l.s1 + l.v0 * l.c1 * l.c2;
123 return b;
124 }
125
127 void setCoeffs(const BiquadCoeffs& b) noexcept { setLadder(fromBiquad(b)); }
128
130 void setLadder(const Coeffs& l) noexcept
131 {
132 current_ = l;
133 target_ = l;
134 rampLeft_ = 0;
135 }
136
147 void rampCoeffs(const BiquadCoeffs& target, int samples) noexcept
148 {
149 if (samples <= 0) { setCoeffs(target); return; }
150 target_ = fromBiquad(target);
151 rampLeft_ = samples;
152 const double inverse = 1.0 / static_cast<double>(samples);
153 step_.c1 = (target_.c1 - current_.c1) * inverse; step_.s1 = (target_.s1 - current_.s1) * inverse;
154 step_.c2 = (target_.c2 - current_.c2) * inverse; step_.s2 = (target_.s2 - current_.s2) * inverse;
155 step_.v0 = (target_.v0 - current_.v0) * inverse; step_.v1 = (target_.v1 - current_.v1) * inverse;
156 step_.v2 = (target_.v2 - current_.v2) * inverse;
157 }
158
160 [[nodiscard]] Coeffs getLadder() const noexcept { return current_; }
161
163 [[nodiscard]] bool isRamping() const noexcept { return rampLeft_ > 0; }
164
166 void reset() noexcept
167 {
168 for (auto& each : state_) each = {};
169 }
170
172 [[nodiscard]] double getStateEnergy(int channel) const noexcept
173 {
174 const State& s = state_[static_cast<size_t>(std::clamp(channel, 0, MaxChannels - 1))];
175 return s.x1 * s.x1 + s.x2 * s.x2;
176 }
177
187 void processBlock(AudioBufferView<T> buffer) noexcept
188 {
189 const int numChannels = std::min(buffer.getNumChannels(), MaxChannels);
190 const int numSamples = buffer.getNumSamples();
191 if (numChannels <= 0 || numSamples <= 0) return;
192
193 DenormalGuard guard;
194 const int moving = std::min(rampLeft_, numSamples);
195 Coeffs after = current_;
196 for (int ch = 0; ch < numChannels; ++ch)
197 {
198 T* data = buffer.getChannel(ch);
199 State& s = state_[static_cast<size_t>(ch)];
200 double x1 = s.x1, x2 = s.x2;
201 Coeffs c = current_;
202 for (int i = 0; i < moving; ++i)
203 {
204 c.c1 += step_.c1; c.s1 += step_.s1; c.c2 += step_.c2; c.s2 += step_.s2;
205 c.v0 += step_.v0; c.v1 += step_.v1; c.v2 += step_.v2;
206 data[i] = static_cast<T>(advance(static_cast<double>(data[i]), c, x1, x2));
207 }
208 if (moving > 0 && moving == rampLeft_) c = target_; // landed: exactly the target from here
209 for (int i = moving; i < numSamples; ++i)
210 data[i] = static_cast<T>(advance(static_cast<double>(data[i]), c, x1, x2));
211 if (!std::isfinite(x1 + x2)) { x1 = 0.0; x2 = 0.0; }
212 s.x1 = x1;
213 s.x2 = x2;
214 after = c;
215 }
216 current_ = after;
217 rampLeft_ -= moving;
218 }
219
228 [[nodiscard]] double processSample(double input, int channel) noexcept
229 {
230 assert(channel >= 0 && channel < MaxChannels && "Channel index out of bounds");
231 State& s = state_[static_cast<size_t>(channel)];
232 return advance(input, current_, s.x1, s.x2);
233 }
234
249 void processSegment(double* data, int numSamples, int channel) noexcept
250 {
251 assert(channel >= 0 && channel < MaxChannels && "Channel index out of bounds");
252 if (numSamples <= 0) return;
253 State& s = state_[static_cast<size_t>(channel)];
254 double x1 = s.x1, x2 = s.x2;
255 const int moving = std::min(rampLeft_, numSamples);
256 Coeffs c = current_;
257 for (int i = 0; i < moving; ++i)
258 {
259 c.c1 += step_.c1; c.s1 += step_.s1; c.c2 += step_.c2; c.s2 += step_.s2;
260 c.v0 += step_.v0; c.v1 += step_.v1; c.v2 += step_.v2;
261 data[i] = advance(data[i], c, x1, x2);
262 }
263 if (moving > 0 && moving == rampLeft_) c = target_;
264 for (int i = moving; i < numSamples; ++i)
265 data[i] = advance(data[i], c, x1, x2);
266 if (!std::isfinite(x1 + x2)) { x1 = 0.0; x2 = 0.0; }
267 s.x1 = x1;
268 s.x2 = x2;
269 }
270
275 void advanceRamp(int samples) noexcept
276 {
277 if (rampLeft_ <= 0 || samples <= 0) return;
278 if (samples >= rampLeft_)
279 {
280 current_ = target_;
281 rampLeft_ = 0;
282 return;
283 }
284 rampLeft_ -= samples;
285 for (int i = 0; i < samples; ++i)
286 {
287 current_.c1 += step_.c1; current_.s1 += step_.s1; current_.c2 += step_.c2; current_.s2 += step_.s2;
288 current_.v0 += step_.v0; current_.v1 += step_.v1; current_.v2 += step_.v2;
289 }
290 }
291
292private:
293 struct State
294 {
295 double x1 = 0.0;
296 double x2 = 0.0;
297 };
298
300 static double advance(double u, const Coeffs& c, double& x1, double& x2) noexcept
301 {
302 const double f1 = c.c2 * u - c.s2 * x2;
303 const double g2 = c.s2 * u + c.c2 * x2;
304 const double f0 = c.c1 * f1 - c.s1 * x1;
305 const double g1 = c.s1 * f1 + c.c1 * x1;
306 x2 = g1;
307 x1 = f0;
308 return c.v0 * f0 + c.v1 * g1 + c.v2 * g2;
309 }
310
311 Coeffs current_ {};
312 Coeffs target_ {};
313 Coeffs step_ {};
314 int rampLeft_ = 0;
315 std::array<State, MaxChannels> state_ {};
316};
317
318
360template <typename T, int Order, int MaxChannels = 8>
362{
363 static_assert(Order >= 1 && Order <= 16, "orders 1 to 16");
364
365public:
367 struct Coeffs
368 {
369 std::array<double, Order + 1> c {};
370 std::array<double, Order + 1> s {};
371 std::array<double, Order + 1> v {};
372 };
373
380 [[nodiscard]] static bool design(const double* b, const double* a, Coeffs& out) noexcept
381 {
382 if (!(std::abs(a[0]) > 0.0)) return false;
383 std::array<double, Order + 1> poly {}, num {};
384 for (int i = 0; i <= Order; ++i)
385 {
386 poly[static_cast<size_t>(i)] = a[i] / a[0];
387 num[static_cast<size_t>(i)] = b[i] / a[0];
388 }
389 // The polynomials of every order, top down (kept for the taps).
390 std::array<std::array<double, Order + 1>, Order + 1> stepped {};
391 stepped[static_cast<size_t>(Order)] = poly;
392 Coeffs l;
393 for (int m = Order; m >= 1; --m)
394 {
395 const auto& am = stepped[static_cast<size_t>(m)];
396 const double k = am[static_cast<size_t>(m)];
397 if (!(std::abs(k) < 1.0)) return false;
398 l.s[static_cast<size_t>(m)] = k;
399 l.c[static_cast<size_t>(m)] = std::sqrt((1.0 - k) * (1.0 + k));
400 auto& below = stepped[static_cast<size_t>(m - 1)];
401 const double inverse = 1.0 / ((1.0 - k) * (1.0 + k));
402 for (int i = 0; i < m; ++i)
403 below[static_cast<size_t>(i)] = (am[static_cast<size_t>(i)] - k * am[static_cast<size_t>(m - i)]) * inverse;
404 }
405 // The taps, from the top: B_m is A_m reversed.
406 double above = 1.0; // the product of the c above m
407 std::array<double, Order + 1> prod {};
408 for (int m = Order; m >= 0; --m)
409 {
410 prod[static_cast<size_t>(m)] = above;
411 if (m >= 1) above *= l.c[static_cast<size_t>(m)];
412 }
413 for (int m = Order; m >= 0; --m)
414 {
415 const double w = num[static_cast<size_t>(m)];
416 l.v[static_cast<size_t>(m)] = w / prod[static_cast<size_t>(m)];
417 const auto& am = stepped[static_cast<size_t>(m)];
418 for (int i = 0; i <= m; ++i) num[static_cast<size_t>(i)] -= w * am[static_cast<size_t>(m - i)];
419 }
420 out = l;
421 return true;
422 }
423
425 bool setCoeffs(const double* b, const double* a) noexcept
426 {
427 Coeffs l;
428 if (!design(b, a, l)) return false;
429 current_ = target_ = l;
430 rampLeft_ = 0;
431 return true;
432 }
433
435 bool rampCoeffs(const double* b, const double* a, int samples) noexcept
436 {
437 Coeffs l;
438 if (!design(b, a, l)) return false;
439 if (samples <= 0)
440 {
441 current_ = target_ = l;
442 rampLeft_ = 0;
443 return true;
444 }
445 target_ = l;
446 rampLeft_ = samples;
447 const double inverse = 1.0 / static_cast<double>(samples);
448 for (int m = 0; m <= Order; ++m)
449 {
450 const auto i = static_cast<size_t>(m);
451 step_.c[i] = (l.c[i] - current_.c[i]) * inverse;
452 step_.s[i] = (l.s[i] - current_.s[i]) * inverse;
453 step_.v[i] = (l.v[i] - current_.v[i]) * inverse;
454 }
455 return true;
456 }
457
458 [[nodiscard]] Coeffs getLadder() const noexcept { return current_; }
459 [[nodiscard]] bool isRamping() const noexcept { return rampLeft_ > 0; }
460
462 void reset() noexcept
463 {
464 for (auto& s : state_) s = {};
465 }
466
468 [[nodiscard]] double getStateEnergy(int channel) const noexcept
469 {
470 if (channel < 0 || channel >= MaxChannels) return 0.0;
471 double e = 0.0;
472 for (double x : state_[static_cast<size_t>(channel)]) e += x * x;
473 return e;
474 }
475
477 void processBlock(AudioBufferView<T> buffer) noexcept
478 {
479 const int numChannels = std::min(buffer.getNumChannels(), MaxChannels);
480 const int numSamples = buffer.getNumSamples();
481 if (numChannels <= 0 || numSamples <= 0) return;
482 DenormalGuard guard;
483 const int moving = std::min(rampLeft_, numSamples);
484 Coeffs after = current_;
485 // Channels go two at a time, as the two lanes of one register where
486 // the target has one: each walks the same coefficients.
487 for (int ch = 0; ch < numChannels; ch += 2)
488 {
489 const bool pair = ch + 1 < numChannels;
490 auto& left = state_[static_cast<size_t>(ch)];
491 auto& right = state_[static_cast<size_t>(pair ? ch + 1 : ch)];
492 Coeffs c = current_;
493 if constexpr (kPairChannels)
494 {
495 if (pair)
496 {
497 runLanes<simd::kVecDoubleNarrow>(buffer.getChannel(ch), buffer.getChannel(ch + 1), numSamples,
498 moving, c, left, right);
499 after = c;
500 continue;
501 }
502 }
503 runLanes<1>(buffer.getChannel(ch), nullptr, numSamples, moving, c, left, left);
504 if (pair)
505 {
506 c = current_;
507 runLanes<1>(buffer.getChannel(ch + 1), nullptr, numSamples, moving, c, right, right);
508 }
509 after = c;
510 }
511 current_ = after;
512 rampLeft_ -= moving;
513 }
514
520 [[nodiscard]] double processSample(double input, int channel) noexcept
521 {
522 assert(channel >= 0 && channel < MaxChannels && "Channel index out of bounds");
523 return advance(input, current_, state_[static_cast<size_t>(channel)]);
524 }
525
527 void advanceRamp(int samples) noexcept
528 {
529 if (rampLeft_ <= 0 || samples <= 0) return;
530 if (samples >= rampLeft_)
531 {
532 current_ = target_;
533 rampLeft_ = 0;
534 return;
535 }
536 rampLeft_ -= samples;
537 const double n = static_cast<double>(samples);
538 for (int m = 0; m <= Order; ++m)
539 {
540 const auto k = static_cast<size_t>(m);
541 current_.c[k] += step_.c[k] * n;
542 current_.s[k] += step_.s[k] * n;
543 current_.v[k] += step_.v[k] * n;
544 }
545 }
546
547private:
548 using State = std::array<double, Order + 1>;
549
551 static double advance(double u, const Coeffs& c, State& x) noexcept
552 {
553 std::array<double, Order + 1> g {};
554 double f = u;
555 for (int m = Order; m >= 1; --m)
556 {
557 const auto k = static_cast<size_t>(m);
558 const double xm = x[k];
559 g[k] = c.s[k] * f + c.c[k] * xm;
560 f = c.c[k] * f - c.s[k] * xm;
561 }
562 double y = c.v[0] * f;
563 for (int m = 1; m <= Order; ++m) y += c.v[static_cast<size_t>(m)] * g[static_cast<size_t>(m)];
564 for (int m = Order; m >= 2; --m) x[static_cast<size_t>(m)] = g[static_cast<size_t>(m - 1)];
565 x[1] = f;
566 return y;
567 }
568
569 static constexpr bool kPairChannels = simd::kVecDoubleNarrow == 2 && sizeof(void*) == 8;
570
575 template <int W>
576 void runLanes(T* left, T* right, int numSamples, int moving, Coeffs& c, State& memLeft, State& memRight) noexcept
577 {
578 using O = simd::Vec<double, W>;
579 using V = typename O::V;
580 const auto lanes = [](double a, double b) noexcept -> V {
581 if constexpr (W == 1) { (void)b; return a; }
582 else return O::set2(a, b);
583 };
584 V x[Order + 1] {}; // C arrays: a template argument would drop the vector type's attributes
585 for (int m = 1; m <= Order; ++m)
586 x[static_cast<size_t>(m)] = lanes(memLeft[static_cast<size_t>(m)], memRight[static_cast<size_t>(m)]);
587
588 V vc[Order + 1] {}, vs[Order + 1] {}, vv[Order + 1] {};
589 const auto broadcast = [&]() noexcept {
590 for (int m = 0; m <= Order; ++m)
591 {
592 const auto k = static_cast<size_t>(m);
593 vc[k] = O::set1(c.c[k]);
594 vs[k] = O::set1(c.s[k]);
595 vv[k] = O::set1(c.v[k]);
596 }
597 };
598 const auto sample = [&](int i) noexcept {
599 V f {};
600 if constexpr (W == 1) f = static_cast<double>(left[i]);
601 else f = lanes(static_cast<double>(left[i]), static_cast<double>(right[i]));
602 V g[Order + 1] {};
603 for (int m = Order; m >= 1; --m)
604 {
605 const auto k = static_cast<size_t>(m);
606 const V xm = x[k];
607 g[k] = O::mulAdd(vs[k], f, vc[k], xm);
608 f = O::mulSub(vc[k], f, vs[k], xm);
609 }
610 V y = O::mul(vv[0], f);
611 for (int m = 1; m <= Order; ++m) y = O::madd(vv[static_cast<size_t>(m)], g[static_cast<size_t>(m)], y);
612 for (int m = Order; m >= 2; --m) x[static_cast<size_t>(m)] = g[static_cast<size_t>(m - 1)];
613 x[1] = f;
614 if constexpr (W == 1) left[i] = static_cast<T>(y);
615 else
616 {
617 left[i] = static_cast<T>(O::lane0(y));
618 right[i] = static_cast<T>(O::lane1(y));
619 }
620 };
621 for (int i = 0; i < moving; ++i)
622 {
623 for (int m = 0; m <= Order; ++m)
624 {
625 const auto k = static_cast<size_t>(m);
626 c.c[k] += step_.c[k];
627 c.s[k] += step_.s[k];
628 c.v[k] += step_.v[k];
629 }
630 broadcast();
631 sample(i);
632 }
633 if (moving > 0 && moving == rampLeft_) c = target_;
634 broadcast();
635 for (int i = moving; i < numSamples; ++i) sample(i);
636
637 double sum = 0.0;
638 for (int m = 1; m <= Order; ++m)
639 {
640 const auto k = static_cast<size_t>(m);
641 if constexpr (W == 1) memLeft[k] = x[k];
642 else
643 {
644 memLeft[k] = O::lane0(x[k]);
645 memRight[k] = O::lane1(x[k]);
646 }
647 sum += memLeft[k] + memRight[k];
648 }
649 if (!std::isfinite(sum))
650 {
651 memLeft = {};
652 memRight = {};
653 }
654 }
655
656 Coeffs current_ {}, target_ {}, step_ {};
657 int rampLeft_ = 0;
658 std::array<State, MaxChannels> state_ {};
659};
660
661} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
A whole filter of order N as one normalized ladder (Gray and Markel), designed from its polynomials,...
bool isRamping() const noexcept
void processBlock(AudioBufferView< T > buffer) noexcept
Runs a block, in place; a ramp moves on by its samples. Channels beyond MaxChannels are left untouche...
bool setCoeffs(const double *b, const double *a) noexcept
Takes a filter b(z) / a(z) at once; false (nothing changes) if it is not stable.
double getStateEnergy(int channel) const noexcept
The energy of a channel's memory (the sum of the squares of its states).
Coeffs getLadder() const noexcept
void reset() noexcept
Clears the memory of every channel.
bool rampCoeffs(const double *b, const double *a, int samples) noexcept
Moves every rotation and tap linearly to a filter's over samples; false if it is not stable.
void advanceRamp(int samples) noexcept
Moves a ramp on by a number of samples (for processSample() callers).
double processSample(double input, int channel) noexcept
One sample of one channel, in double, with the coefficients as they are (a ramp moves on with advance...
static bool design(const double *b, const double *a, Coeffs &out) noexcept
The ladder of a digital filter b(z) / a(z), each Order + 1 coefficients from z^0 (a[0] scales both).
One second-order section in normalized ladder form, per channel.
void reset() noexcept
Clears the memory of every channel. Coefficients and ramp are kept.
static BiquadCoeffs toBiquad(const Coeffs &l) noexcept
The biquad a ladder realises (for curves and checks).
void processSegment(double *data, int numSamples, int channel) noexcept
Runs one channel's samples through the section, in double and in place, walking the ramp from where i...
Coeffs getLadder() const noexcept
Rotations and taps in use now (mid ramp, where the ramp is).
void setCoeffs(const BiquadCoeffs &b) noexcept
Makes a biquad's response the section's own from the next sample; ends a ramp.
void setLadder(const Coeffs &l) noexcept
Sets rotations and taps directly from the next sample; ends a ramp.
void advanceRamp(int samples) noexcept
Moves the ramp on by a number of samples (for processSample() callers).
void rampCoeffs(const BiquadCoeffs &target, int samples) noexcept
Moves the rotations and the taps linearly to those of a biquad.
double processSample(double input, int channel) noexcept
One sample of one channel, in double, with the coefficients as they are.
void processBlock(AudioBufferView< T > buffer) noexcept
Runs a block through the section, in place.
double getStateEnergy(int channel) const noexcept
The energy in a channel's memory, x1^2 + x2^2 (it only falls with no input).
bool isRamping() const noexcept
Whether the coefficients are moving.
static Coeffs fromBiquad(const BiquadCoeffs &b) noexcept
The ladder of a biquad.
Main namespace for the DSPark framework.
Stores normalised biquad coefficients (b0, b1, b2, a1, a2), always double.
Definition Biquad.h:107
The ladder's rotations and taps.
std::array< double, Order+1 > v
v_0 .. v_N, the taps.
std::array< double, Order+1 > s
s_1 .. s_N = the reflection coefficients.
std::array< double, Order+1 > c
c_1 .. c_N (index 0 unused).
The two rotations and the three taps (the identity by default).
double s2
Outer rotation: s2 = k2 = a2.
double s1
Inner rotation: s1 = k1 = a1 / (1 + a2).
double v2
Taps on f0, g1 and g2.