DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
BiquadCascade.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
54#include "AudioBuffer.h"
55#include "Biquad.h"
56#include "DenormalGuard.h"
57#include "SimdOps.h"
58
59#include <algorithm>
60#include <array>
61#include <cassert>
62#include <cmath>
63#include <cstdint>
64
65namespace dspark {
66
76template <typename T, int MaxSections = 8, int MaxChannels = 8>
78{
79public:
81 static constexpr int kGroup = 4;
82
83 BiquadCascade() noexcept
84 {
85 enabled_.fill(true);
86 rampLeft_.fill(0);
87 rebuildRoute();
88 }
89
99 void setNumSections(int count) noexcept
100 {
101 const int clamped = std::clamp(count, 0, MaxSections);
102 if (clamped == numSections_) return;
103 const int before = numSections_;
104 numSections_ = clamped;
105 rebuildRoute();
106 for (int s = std::max(before, 0); s < clamped; ++s)
107 if (enabled_[static_cast<size_t>(s)]) seedFromInput(s);
108 }
109
111 [[nodiscard]] int getNumSections() const noexcept { return numSections_; }
112
123 void setCoeffs(int section, const BiquadCoeffs& c) noexcept
124 {
125 if (section < 0 || section >= MaxSections) return;
126 const auto s = static_cast<size_t>(section);
127 current_[s] = c;
128 target_[s] = c;
129 rampLeft_[s] = 0;
130 updateRamping();
131 }
132
145 void rampCoeffs(int section, const BiquadCoeffs& target, int samples) noexcept
146 {
147 if (section < 0 || section >= MaxSections) return;
148 if (samples <= 0) { setCoeffs(section, target); return; }
149 const auto s = static_cast<size_t>(section);
150 target_[s] = target;
151 rampLeft_[s] = samples;
152 const double inverse = 1.0 / static_cast<double>(samples);
153 step_[s].b0 = (target.b0 - current_[s].b0) * inverse;
154 step_[s].b1 = (target.b1 - current_[s].b1) * inverse;
155 step_[s].b2 = (target.b2 - current_[s].b2) * inverse;
156 step_[s].a1 = (target.a1 - current_[s].a1) * inverse;
157 step_[s].a2 = (target.a2 - current_[s].a2) * inverse;
158 ramping_ = true;
159 }
160
172 void rampToBypass(int section, int samples) noexcept
173 {
174 if (section < 0 || section >= MaxSections) return;
175 rampCoeffs(section, target_[static_cast<size_t>(section)].bypassed(), samples);
176 }
177
179 [[nodiscard]] BiquadCoeffs getCoeffs(int section) const noexcept
180 {
181 return current_[static_cast<size_t>(std::clamp(section, 0, MaxSections - 1))];
182 }
183
185 [[nodiscard]] BiquadCoeffs getTargetCoeffs(int section) const noexcept
186 {
187 return target_[static_cast<size_t>(std::clamp(section, 0, MaxSections - 1))];
188 }
189
191 [[nodiscard]] bool isRamping(int section) const noexcept
192 {
193 return section >= 0 && section < MaxSections && rampLeft_[static_cast<size_t>(section)] > 0;
194 }
195
197 [[nodiscard]] bool isRamping() const noexcept { return ramping_; }
198
211 void setSectionEnabled(int section, bool on) noexcept
212 {
213 if (section < 0 || section >= MaxSections) return;
214 const auto s = static_cast<size_t>(section);
215 if (enabled_[s] == on) return;
216 enabled_[s] = on;
217 rebuildRoute();
218 if (on && section < numSections_) seedFromInput(section);
219 }
220
222 [[nodiscard]] bool isSectionEnabled(int section) const noexcept
223 {
224 return section >= 0 && section < MaxSections && enabled_[static_cast<size_t>(section)];
225 }
226
228 void reset() noexcept
229 {
230 for (auto& channel : node_)
231 for (auto& each : channel) each = {};
232 }
233
243 void processBlock(AudioBufferView<T> buffer) noexcept
244 {
245 const int numChannels = std::min(buffer.getNumChannels(), MaxChannels);
246 const int numSamples = buffer.getNumSamples();
247 if (numChannels <= 0 || numSamples <= 0) return;
248 if (numActive_ == 0)
249 {
250 // Nothing in the path: the input node still has to remember what went by.
251 for (int ch = 0; ch < numChannels; ++ch)
252 {
253 const T* data = buffer.getChannel(ch);
254 auto& input = node_[static_cast<size_t>(ch)][0];
255 if (numSamples >= 2) input.h2 = static_cast<double>(data[numSamples - 2]);
256 else input.h2 = input.h1;
257 input.h1 = static_cast<double>(data[numSamples - 1]);
258 }
259 advanceRamps(numSamples);
260 return;
261 }
262
263 DenormalGuard guard;
264 int pos = 0;
265 while (pos < numSamples)
266 {
267 int length = std::min(kChunk, numSamples - pos);
268 if (ramping_)
269 for (int k = 0; k < numActive_; ++k)
270 {
271 const int left = rampLeft_[static_cast<size_t>(active_[static_cast<size_t>(k)])];
272 if (left > 0) length = std::min(length, left);
273 }
274
275 int ch = 0;
276 if constexpr (kPairChannels)
277 for (; ch + 1 < numChannels; ch += 2)
278 runChunk<simd::kVecDoubleNarrow>(buffer.getChannel(ch) + pos, buffer.getChannel(ch + 1) + pos,
279 length, ch, ch + 1);
280 for (; ch < numChannels; ++ch)
281 runChunk<1>(buffer.getChannel(ch) + pos, nullptr, length, ch, ch);
282
283 advanceRamps(length);
284 pos += length;
285 }
286
287 for (int ch = 0; ch < numChannels; ++ch)
288 recover(ch);
289 }
290
302 [[nodiscard]] double processSample(double input, int channel) noexcept
303 {
304 assert(channel >= 0 && channel < MaxChannels && "Channel index out of bounds");
305 auto& nodes = node_[static_cast<size_t>(channel)];
306 double u = input;
307 double u1 = nodes[0].h1, u2 = nodes[0].h2;
308 nodes[0].h2 = nodes[0].h1;
309 nodes[0].h1 = input;
310 for (int k = 0; k < numActive_; ++k)
311 {
312 const auto s = static_cast<size_t>(active_[static_cast<size_t>(k)]);
313 const BiquadCoeffs& c = current_[s];
314 auto& out = nodes[s + 1];
315 const double p = (c.b1 * u1 + c.b2 * u2) - c.a2 * out.h2;
316 const double y = (p + c.b0 * u) - c.a1 * out.h1;
317 u1 = out.h1;
318 u2 = out.h2;
319 out.h2 = out.h1;
320 out.h1 = y;
321 u = y;
322 }
323 return u;
324 }
325
342 [[nodiscard]] double processSample(double input, int channel, std::uint64_t skip) noexcept
343 {
344 static_assert(MaxSections <= 64, "the mask has one bit per section");
345 assert(channel >= 0 && channel < MaxChannels && "Channel index out of bounds");
346 auto& nodes = node_[static_cast<size_t>(channel)];
347 double u = input;
348 double u1 = nodes[0].h1, u2 = nodes[0].h2;
349 nodes[0].h2 = nodes[0].h1;
350 nodes[0].h1 = input;
351 for (int k = 0; k < numActive_; ++k)
352 {
353 const auto s = static_cast<size_t>(active_[static_cast<size_t>(k)]);
354 if ((skip & (std::uint64_t { 1 } << s)) != 0) continue;
355 const BiquadCoeffs& c = current_[s];
356 auto& out = nodes[s + 1];
357 const double p = (c.b1 * u1 + c.b2 * u2) - c.a2 * out.h2;
358 const double y = (p + c.b0 * u) - c.a1 * out.h1;
359 u1 = out.h1;
360 u2 = out.h2;
361 out.h2 = out.h1;
362 out.h1 = y;
363 u = y;
364 }
365 return u;
366 }
367
386 void turnPairMemory(int first, int second, bool back) noexcept
387 {
388 if (first < 0 || second < 0 || first >= MaxChannels || second >= MaxChannels || first == second) return;
389 auto& a = node_[static_cast<size_t>(first)];
390 auto& b = node_[static_cast<size_t>(second)];
391 const double scale = back ? 1.0 : 0.5;
392 for (size_t n = 0; n < a.size(); ++n)
393 {
394 const double sum1 = a[n].h1 + b[n].h1, difference1 = a[n].h1 - b[n].h1;
395 const double sum2 = a[n].h2 + b[n].h2, difference2 = a[n].h2 - b[n].h2;
396 a[n].h1 = scale * sum1;
397 b[n].h1 = scale * difference1;
398 a[n].h2 = scale * sum2;
399 b[n].h2 = scale * difference2;
400 }
401 }
402
407 void advanceRamps(int samples) noexcept
408 {
409 if (!ramping_ || samples <= 0) return;
410 for (int section = 0; section < MaxSections; ++section)
411 {
412 const auto s = static_cast<size_t>(section);
413 if (rampLeft_[s] <= 0) continue;
414 if (samples >= rampLeft_[s])
415 {
416 current_[s] = target_[s];
417 rampLeft_[s] = 0;
418 continue;
419 }
420 rampLeft_[s] -= samples;
421 if (moved_[s])
422 {
423 // The loop that played the section moved it, sample by sample.
424 current_[s] = next_[s];
425 }
426 else
427 {
428 // Out of the path, or played one sample at a time: it moves here.
429 const double count = static_cast<double>(samples);
430 current_[s].b0 += step_[s].b0 * count;
431 current_[s].b1 += step_[s].b1 * count;
432 current_[s].b2 += step_[s].b2 * count;
433 current_[s].a1 += step_[s].a1 * count;
434 current_[s].a2 += step_[s].a2 * count;
435 }
436 }
437 moved_.fill(false);
438 updateRamping();
439 }
440
441private:
442 static constexpr int kChunk = 64;
443 static constexpr int kMaxGroups = (MaxSections + kGroup - 1) / kGroup > 0 ? (MaxSections + kGroup - 1) / kGroup : 1;
444 static constexpr bool kPairChannels = simd::kVecDoubleNarrow == 2 && sizeof(void*) == 8;
445
446 struct Node
447 {
448 double h1 = 0.0;
449 double h2 = 0.0;
450 };
451
453 template <int W>
454 struct Lanes
455 {
456 using O = simd::Vec<double, W>;
457 using V = typename O::V;
458 static V pair(double first, double second) noexcept
459 {
460 if constexpr (W == 1) { (void)second; return first; }
461 else return O::set2(first, second);
462 }
463 static double first(V v) noexcept
464 {
465 if constexpr (W == 1) return v;
466 else return O::lane0(v);
467 }
468 static double second(V v) noexcept
469 {
470 if constexpr (W == 1) return v;
471 else return O::lane1(v);
472 }
473 };
474
476 template <int W>
477 void runChunk(T* left, T* right, int length, int chLeft, int chRight) noexcept
478 {
479 using L = Lanes<W>;
480 using V = typename L::V;
481 V io[kChunk];
482 if constexpr (W == 1)
483 {
484 (void)right;
485 for (int i = 0; i < length; ++i) io[i] = static_cast<double>(left[i]);
486 }
487 else
488 {
489 for (int i = 0; i < length; ++i)
490 io[i] = L::pair(static_cast<double>(left[i]), static_cast<double>(right[i]));
491 }
492
493 auto& nodesLeft = node_[static_cast<size_t>(chLeft)];
494 auto& nodesRight = node_[static_cast<size_t>(chRight)];
495
496 // Each group reads the history its input node had BEFORE this chunk;
497 // the group ahead of it leaves that node at the end of the chunk.
498 V startU1[kMaxGroups], startU2[kMaxGroups];
499 for (int first = 0, group = 0; first < numActive_; first += kGroup, ++group)
500 {
501 const auto node = static_cast<size_t>(input_[static_cast<size_t>(active_[static_cast<size_t>(first)])]);
502 startU1[group] = L::pair(nodesLeft[node].h1, nodesRight[node].h1);
503 startU2[group] = L::pair(nodesLeft[node].h2, nodesRight[node].h2);
504 }
505
506 for (int first = 0, group = 0; first < numActive_; first += kGroup, ++group)
507 {
508 const int count = std::min(kGroup, numActive_ - first);
509 bool moving = false;
510 for (int k = 0; k < count; ++k)
511 moving = moving || rampLeft_[static_cast<size_t>(active_[static_cast<size_t>(first + k)])] > 0;
512 switch (count)
513 {
514 case 1: runGroup<1, W>(io, length, first, moving, startU1[group], startU2[group], nodesLeft, nodesRight); break;
515 case 2: runGroup<2, W>(io, length, first, moving, startU1[group], startU2[group], nodesLeft, nodesRight); break;
516 case 3: runGroup<3, W>(io, length, first, moving, startU1[group], startU2[group], nodesLeft, nodesRight); break;
517 default: runGroup<4, W>(io, length, first, moving, startU1[group], startU2[group], nodesLeft, nodesRight); break;
518 }
519 }
520
521 for (int i = 0; i < length; ++i)
522 {
523 left[i] = static_cast<T>(L::first(io[i]));
524 if constexpr (W != 1) right[i] = static_cast<T>(L::second(io[i]));
525 }
526 }
527
536 template <int M, int W>
537 void runGroup(typename Lanes<W>::V* io, int length, int first, bool moving,
538 typename Lanes<W>::V u1, typename Lanes<W>::V u2,
539 std::array<Node, MaxSections + 1>& nodesLeft,
540 std::array<Node, MaxSections + 1>& nodesRight) noexcept
541 {
542 using L = Lanes<W>;
543 using O = typename L::O;
544 using V = typename L::V;
545
546 size_t section[M];
547 V b0[M], b1[M], b2[M], a1[M], a2[M];
548 V y1[M], y2[M];
549 for (int k = 0; k < M; ++k)
550 {
551 section[k] = static_cast<size_t>(active_[static_cast<size_t>(first + k)]);
552 const BiquadCoeffs& c = current_[section[k]];
553 b0[k] = O::set1(c.b0); b1[k] = O::set1(c.b1); b2[k] = O::set1(c.b2);
554 a1[k] = O::set1(c.a1); a2[k] = O::set1(c.a2);
555 y1[k] = L::pair(nodesLeft[section[k] + 1].h1, nodesRight[section[k] + 1].h1);
556 y2[k] = L::pair(nodesLeft[section[k] + 1].h2, nodesRight[section[k] + 1].h2);
557 }
558
559 if (!moving)
560 {
561 for (int i = 0; i < length; ++i)
562 {
563 V u = io[i];
564 V p1 = u1, p2 = u2;
565 u2 = u1;
566 u1 = u;
567 for (int k = 0; k < M; ++k)
568 {
569 const V past = O::sub(O::add(O::mul(b1[k], p1), O::mul(b2[k], p2)), O::mul(a2[k], y2[k]));
570 const V y = O::sub(O::add(past, O::mul(b0[k], u)), O::mul(a1[k], y1[k]));
571 p1 = y1[k];
572 p2 = y2[k];
573 y2[k] = y1[k];
574 y1[k] = y;
575 u = y;
576 }
577 io[i] = u;
578 }
579 }
580 else
581 {
582 V s0[M], s1[M], s2[M], t1[M], t2[M];
583 for (int k = 0; k < M; ++k)
584 {
585 const bool ramps = rampLeft_[section[k]] > 0;
586 const BiquadCoeffs& d = step_[section[k]];
587 s0[k] = O::set1(ramps ? d.b0 : 0.0); s1[k] = O::set1(ramps ? d.b1 : 0.0);
588 s2[k] = O::set1(ramps ? d.b2 : 0.0); t1[k] = O::set1(ramps ? d.a1 : 0.0);
589 t2[k] = O::set1(ramps ? d.a2 : 0.0);
590 }
591 for (int i = 0; i < length; ++i)
592 {
593 V u = io[i];
594 V p1 = u1, p2 = u2;
595 u2 = u1;
596 u1 = u;
597 for (int k = 0; k < M; ++k)
598 {
599 b0[k] = O::add(b0[k], s0[k]); b1[k] = O::add(b1[k], s1[k]); b2[k] = O::add(b2[k], s2[k]);
600 a1[k] = O::add(a1[k], t1[k]); a2[k] = O::add(a2[k], t2[k]);
601 const V past = O::sub(O::add(O::mul(b1[k], p1), O::mul(b2[k], p2)), O::mul(a2[k], y2[k]));
602 const V y = O::sub(O::add(past, O::mul(b0[k], u)), O::mul(a1[k], y1[k]));
603 p1 = y1[k];
604 p2 = y2[k];
605 y2[k] = y1[k];
606 y1[k] = y;
607 u = y;
608 }
609 io[i] = u;
610 }
611 // Where the ramp has brought the coefficients: every channel walks
612 // the same steps, so the last one to run leaves the same values.
613 for (int k = 0; k < M; ++k)
614 {
615 if (rampLeft_[section[k]] <= 0) continue;
616 next_[section[k]].b0 = L::first(b0[k]); next_[section[k]].b1 = L::first(b1[k]);
617 next_[section[k]].b2 = L::first(b2[k]); next_[section[k]].a1 = L::first(a1[k]);
618 next_[section[k]].a2 = L::first(a2[k]);
619 moved_[section[k]] = true;
620 }
621 }
622
623 // The input node of the cascade is this loop's to keep; the input of
624 // a later group is the output node the group ahead has just written.
625 if (first == 0)
626 {
627 nodesLeft[0].h1 = L::first(u1);
628 nodesLeft[0].h2 = L::first(u2);
629 }
630 for (int k = 0; k < M; ++k)
631 {
632 nodesLeft[section[k] + 1].h1 = L::first(y1[k]);
633 nodesLeft[section[k] + 1].h2 = L::first(y2[k]);
634 }
635 if constexpr (W != 1)
636 {
637 if (first == 0)
638 {
639 nodesRight[0].h1 = L::second(u1);
640 nodesRight[0].h2 = L::second(u2);
641 }
642 for (int k = 0; k < M; ++k)
643 {
644 nodesRight[section[k] + 1].h1 = L::second(y1[k]);
645 nodesRight[section[k] + 1].h2 = L::second(y2[k]);
646 }
647 }
648 }
649
651 void rebuildRoute() noexcept
652 {
653 numActive_ = 0;
654 int previous = 0;
655 for (int s = 0; s < numSections_; ++s)
656 {
657 if (!enabled_[static_cast<size_t>(s)]) continue;
658 active_[static_cast<size_t>(numActive_++)] = s;
659 input_[static_cast<size_t>(s)] = previous;
660 previous = s + 1;
661 }
662 }
663
665 void seedFromInput(int section) noexcept
666 {
667 const auto from = static_cast<size_t>(input_[static_cast<size_t>(section)]);
668 for (auto& channel : node_)
669 channel[static_cast<size_t>(section) + 1] = channel[from];
670 }
671
672 void updateRamping() noexcept
673 {
674 ramping_ = false;
675 for (int left : rampLeft_) ramping_ = ramping_ || left > 0;
676 }
677
679 void recover(int channel) noexcept
680 {
681 auto& nodes = node_[static_cast<size_t>(channel)];
682 double sum = nodes[0].h1 + nodes[0].h2;
683 for (int k = 0; k < numActive_; ++k)
684 {
685 const Node& each = nodes[static_cast<size_t>(active_[static_cast<size_t>(k)]) + 1];
686 sum += each.h1 + each.h2;
687 }
688 if (!std::isfinite(sum))
689 for (auto& each : nodes) each = {};
690 }
691
692 std::array<BiquadCoeffs, MaxSections> current_ {};
693 std::array<BiquadCoeffs, MaxSections> target_ {};
694 std::array<BiquadCoeffs, MaxSections> step_ {};
695 std::array<BiquadCoeffs, MaxSections> next_ {};
696 std::array<bool, MaxSections> moved_ {};
697 std::array<int, MaxSections> rampLeft_ {};
698 std::array<bool, MaxSections> enabled_ {};
699 std::array<int, MaxSections> active_ {};
700 std::array<int, MaxSections> input_ {};
701 int numSections_ = 0;
702 int numActive_ = 0;
703 bool ramping_ = false;
704
705 std::array<std::array<Node, MaxSections + 1>, MaxChannels> node_ {};
706};
707
708} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Up to MaxSections second-order sections in series, run in one pass.
static constexpr int kGroup
Sections run together in one pass over the samples.
void reset() noexcept
Clears the memory of every node. Coefficients and ramps are kept.
void advanceRamps(int samples) noexcept
Moves every ramp on by a number of samples (for processSample() callers).
int getNumSections() const noexcept
Number of sections in the cascade.
void setCoeffs(int section, const BiquadCoeffs &c) noexcept
Makes a coefficient set a section's own from the next sample.
void setNumSections(int count) noexcept
Sets how many sections the cascade has.
void processBlock(AudioBufferView< T > buffer) noexcept
Runs a block through the cascade, in place.
void rampCoeffs(int section, const BiquadCoeffs &target, int samples) noexcept
Moves a section's five coefficients linearly to a set.
void rampToBypass(int section, int samples) noexcept
Takes a section out of the path without a click.
BiquadCoeffs getCoeffs(int section) const noexcept
The coefficients a section is using now (mid ramp, where the ramp is).
void turnPairMemory(int first, int second, bool back) noexcept
Rewrites the memory of a pair of channels as its middle and its sides, or back.
bool isRamping() const noexcept
Whether any section's coefficients are moving.
void setSectionEnabled(int section, bool on) noexcept
Switches a section in or out of the path.
double processSample(double input, int channel) noexcept
One sample of one channel through the cascade, in double.
BiquadCoeffs getTargetCoeffs(int section) const noexcept
The coefficients a section is heading to (its own when it is not ramping).
double processSample(double input, int channel, std::uint64_t skip) noexcept
As processSample(), leaving some sections out for this call.
bool isRamping(int section) const noexcept
Whether a section's coefficients are moving.
bool isSectionEnabled(int section) const noexcept
Whether a section is computed.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Main namespace for the DSPark framework.
Stores normalised biquad coefficients (b0, b1, b2, a1, a2), always double.
Definition Biquad.h:107