DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Biquad.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
53#include <algorithm>
54#include <array>
55#include <cmath>
56#include <numbers>
57#include <span>
58#include <atomic>
59#include <cassert>
60
61#include "AudioBuffer.h"
62#include "DenormalGuard.h"
63#include "SimdOps.h"
64
65// Keeps a cold path out of a hot caller's stack frame. Needed exactly once here
66// (see Biquad::adoptStagedCoeffs), where inlining the coefficient adoption into
67// the per-sample entry points costs four instructions on EVERY sample. Locally
68// defined and guarded, the same way Core/SimdOps.h spells DSPARK_RESTRICT.
69#ifndef DSPARK_NOINLINE
70 #if defined(_MSC_VER)
71 #define DSPARK_NOINLINE __declspec(noinline)
72 #elif defined(__GNUC__) || defined(__clang__)
73 #define DSPARK_NOINLINE __attribute__((noinline))
74 #else
75 #define DSPARK_NOINLINE
76 #endif
77#endif
78
79namespace dspark {
80
81// ============================================================================
82// BiquadCoeffs -- Coefficient storage + factory methods
83// ============================================================================
84
106struct alignas(32) BiquadCoeffs
107{
108 double b0 = 1.0, b1 = 0.0, b2 = 0.0;
109 double a1 = 0.0, a2 = 0.0;
110
111 // -- Factory methods (Audio EQ Cookbook) ----------------------------------
112
119 [[nodiscard]] static BiquadCoeffs makeLowPass(double sampleRate, double freq, double Q = 0.7071067811865476) noexcept
120 {
121 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
122 Q = std::max(Q, 0.001);
123 const double w0 = 2.0 * std::numbers::pi * freq / sampleRate;
124 const double cosw0 = std::cos(w0);
125 const double sinw0 = std::sin(w0);
126 const double alpha = sinw0 / (2.0 * Q);
127
128 const double a0 = 1.0 + alpha;
129 return normalise(a0,
130 (1.0 - cosw0) / 2.0,
131 1.0 - cosw0,
132 (1.0 - cosw0) / 2.0,
133 -2.0 * cosw0,
134 1.0 - alpha);
135 }
136
143 [[nodiscard]] static BiquadCoeffs makeHighPass(double sampleRate, double freq, double Q = 0.7071067811865476) noexcept
144 {
145 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
146 Q = std::max(Q, 0.001);
147 const double w0 = 2.0 * std::numbers::pi * freq / sampleRate;
148 const double cosw0 = std::cos(w0);
149 const double sinw0 = std::sin(w0);
150 const double alpha = sinw0 / (2.0 * Q);
151
152 const double a0 = 1.0 + alpha;
153 return normalise(a0,
154 (1.0 + cosw0) / 2.0,
155 -(1.0 + cosw0),
156 (1.0 + cosw0) / 2.0,
157 -2.0 * cosw0,
158 1.0 - alpha);
159 }
160
172 [[nodiscard]] static BiquadCoeffs makeBandPass(double sampleRate, double freq, double Q = 0.7071067811865476) noexcept
173 {
174 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
175 Q = std::max(Q, 0.001);
176 const double w0 = 2.0 * std::numbers::pi * freq / sampleRate;
177 const double cosw0 = std::cos(w0);
178 const double sinw0 = std::sin(w0);
179 const double alpha = sinw0 / (2.0 * Q);
180
181 const double a0 = 1.0 + alpha;
182 return normalise(a0,
183 alpha,
184 0.0,
185 -alpha,
186 -2.0 * cosw0,
187 1.0 - alpha);
188 }
189
201 [[nodiscard]] static BiquadCoeffs makePeak(double sampleRate, double freq, double Q, double gainDb) noexcept
202 {
203 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
204 Q = std::max(Q, 0.001);
205 const double A = std::pow(10.0, gainDb / 40.0); // dB/40 = sqrt of linear gain
206 const double w0 = 2.0 * std::numbers::pi * freq / sampleRate;
207 const double cosw0 = std::cos(w0);
208 const double sinw0 = std::sin(w0);
209 const double alpha = sinw0 / (2.0 * Q);
210
211 const double a0 = 1.0 + alpha / A;
212 return normalise(a0,
213 1.0 + alpha * A,
214 -2.0 * cosw0,
215 1.0 - alpha * A,
216 -2.0 * cosw0,
217 1.0 - alpha / A);
218 }
219
248 [[nodiscard]] static BiquadCoeffs makePeakMatched(double sampleRate, double freq,
249 double Q, double gainDb) noexcept
250 {
251 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
252 Q = std::max(Q, 0.001);
253 if (std::abs(gainDb) < 0.01)
254 return { 1.0, 0.0, 0.0, 0.0, 0.0 };
255
256 const double G = std::pow(10.0, gainDb / 20.0);
257 const double w0 = 2.0 * std::numbers::pi * freq / sampleRate;
258
259 // Poles: impulse invariance of s^2 + 2*q*w0*s + w0^2, q = 1/(2*Qpole)
260 // with the prototype's pole Q = sqrt(G) * Q.
261 const double q = 1.0 / (2.0 * Q * std::sqrt(G));
262 double a1 = 0.0;
263 const double a2 = std::exp(-2.0 * q * w0);
264 if (q <= 1.0)
265 {
266 a1 = -2.0 * std::exp(-q * w0) * std::cos(std::sqrt(1.0 - q * q) * w0);
267 }
268 else
269 {
270 // Two real poles z = e^((-q +/- r) w0). Evaluated one by one (each
271 // is <= 1) rather than as e^(-q w0) * cosh(r w0), whose cosh
272 // overflows for small Q; -q + r is taken as -1/(q + r) to avoid
273 // the cancellation.
274 const double r = std::sqrt(q * q - 1.0);
275 a1 = -(std::exp(-w0 / (q + r)) + std::exp(-(q + r) * w0));
276 }
277
278 // Magnitude matching in the paper's (A, B, phi) form: |H|^2 =
279 // (B0 phi0 + B1 phi1 + B2 phi2) / (A0 phi0 + A1 phi1 + A2 phi2).
280 const double A0 = (1.0 + a1 + a2) * (1.0 + a1 + a2);
281 const double A1 = (1.0 - a1 + a2) * (1.0 - a1 + a2);
282 const double A2 = -4.0 * a2;
283 const double s = std::sin(0.5 * w0);
284 const double phi1 = s * s;
285 const double phi0 = 1.0 - phi1;
286 const double phi2 = 4.0 * phi0 * phi1;
287
288 const double G2 = G * G;
289 const double B0 = A0; // unity at DC
290 const double R1 = (A0 * phi0 + A1 * phi1 + A2 * phi2) * G2; // |H(w0)| = G
291 const double R2 = (-A0 + A1 + 4.0 * (phi0 - phi1) * A2) * G2; // extremum at w0
292 const double B2 = (R1 - R2 * phi1 - B0) / (4.0 * phi1 * phi1);
293 const double B1 = R2 + B0 + 4.0 * (phi1 - phi0) * B2;
294
295 // Minimum-phase numerator from (B0, B1, B2).
296 const double sqrtB0 = std::sqrt(std::max(0.0, B0));
297 const double sqrtB1 = std::sqrt(std::max(0.0, B1));
298 const double W = 0.5 * (sqrtB0 + sqrtB1);
299 BiquadCoeffs c;
300 c.b0 = 0.5 * (W + std::sqrt(std::max(0.0, W * W + B2)));
301 c.b1 = 0.5 * (sqrtB0 - sqrtB1);
302 c.b2 = -B2 / (4.0 * c.b0);
303 c.a1 = a1;
304 c.a2 = a2;
305 return c;
306 }
307
308
321 [[nodiscard]] static BiquadCoeffs makeLowPassMatched(double sampleRate, double freq,
322 double Q = 0.7071067811865476) noexcept
323 {
324 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
325 Q = std::max(Q, 0.001);
326 const MatchedPoles m = matchedPoles(2.0 * std::numbers::pi * freq / sampleRate, 1.0 / (2.0 * Q));
327 const double R1 = (m.A0 * m.phi0 + m.A1 * m.phi1 + m.A2 * m.phi2) * Q * Q;
328 const double B0 = m.A0;
329 const double B1 = (R1 - B0 * m.phi0) / m.phi1;
330 BiquadCoeffs c;
331 c.b0 = 0.5 * (std::sqrt(B0) + std::sqrt(std::max(0.0, B1)));
332 c.b1 = std::sqrt(B0) - c.b0;
333 c.b2 = 0.0;
334 c.a1 = m.a1;
335 c.a2 = m.a2;
336 return c;
337 }
338
347 [[nodiscard]] static BiquadCoeffs makeHighPassMatched(double sampleRate, double freq,
348 double Q = 0.7071067811865476) noexcept
349 {
350 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
351 Q = std::max(Q, 0.001);
352 const MatchedPoles m = matchedPoles(2.0 * std::numbers::pi * freq / sampleRate, 1.0 / (2.0 * Q));
353 BiquadCoeffs c;
354 c.b0 = std::sqrt(std::max(0.0, m.A0 * m.phi0 + m.A1 * m.phi1 + m.A2 * m.phi2)) * Q / (4.0 * m.phi1);
355 c.b1 = -2.0 * c.b0;
356 c.b2 = c.b0;
357 c.a1 = m.a1;
358 c.a2 = m.a2;
359 return c;
360 }
361
370 [[nodiscard]] static BiquadCoeffs makeBandPassMatched(double sampleRate, double freq,
371 double Q = 0.7071067811865476) noexcept
372 {
373 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
374 Q = std::max(Q, 0.001);
375 const MatchedPoles m = matchedPoles(2.0 * std::numbers::pi * freq / sampleRate, 1.0 / (2.0 * Q));
376 const double R1 = m.A0 * m.phi0 + m.A1 * m.phi1 + m.A2 * m.phi2;
377 const double R2 = -m.A0 + m.A1 + 4.0 * (m.phi0 - m.phi1) * m.A2;
378 const double B2 = (R1 - R2 * m.phi1) / (4.0 * m.phi1 * m.phi1);
379 const double B1 = R2 + 4.0 * (m.phi1 - m.phi0) * B2;
380 BiquadCoeffs c;
381 c.b1 = -0.5 * std::sqrt(std::max(0.0, B1));
382 c.b0 = 0.5 * (std::sqrt(std::max(0.0, B2 + c.b1 * c.b1)) - c.b1);
383 c.b2 = -c.b0 - c.b1;
384 c.a1 = m.a1;
385 c.a2 = m.a2;
386 return c;
387 }
388
399 [[nodiscard]] static BiquadCoeffs makeLowShelfMatched(double sampleRate, double freq, double gainDb) noexcept
400 {
401 return matchedShelf(sampleRate, freq, gainDb, true);
402 }
403
405 [[nodiscard]] static BiquadCoeffs makeHighShelfMatched(double sampleRate, double freq, double gainDb) noexcept
406 {
407 return matchedShelf(sampleRate, freq, gainDb, false);
408 }
409
417 [[nodiscard]] static BiquadCoeffs makeLowShelf(double sampleRate, double freq, double gainDb, double slope = 1.0) noexcept
418 {
419 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
420 // Shelf slope S must stay in (0, 1]: for S > 1 the radicand below goes
421 // negative and std::sqrt yields NaN coefficients that poison the audio.
422 slope = std::clamp(slope, 0.0001, 1.0);
423 const double A = std::pow(10.0, gainDb / 40.0);
424 const double w0 = 2.0 * std::numbers::pi * freq / sampleRate;
425 const double cosw0 = std::cos(w0);
426 const double sinw0 = std::sin(w0);
427 const double radicand = (A + 1.0 / A) * (1.0 / slope - 1.0) + 2.0;
428 const double alpha = sinw0 / 2.0 * std::sqrt(std::max(0.0, radicand));
429 const double twoSqrtAAlpha = 2.0 * std::sqrt(A) * alpha;
430
431 const double a0 = (A + 1.0) + (A - 1.0) * cosw0 + twoSqrtAAlpha;
432 return normalise(a0,
433 A * ((A + 1.0) - (A - 1.0) * cosw0 + twoSqrtAAlpha),
434 2.0 * A * ((A - 1.0) - (A + 1.0) * cosw0),
435 A * ((A + 1.0) - (A - 1.0) * cosw0 - twoSqrtAAlpha),
436 -2.0 * ((A - 1.0) + (A + 1.0) * cosw0),
437 (A + 1.0) + (A - 1.0) * cosw0 - twoSqrtAAlpha);
438 }
439
447 [[nodiscard]] static BiquadCoeffs makeHighShelf(double sampleRate, double freq, double gainDb, double slope = 1.0) noexcept
448 {
449 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
450 // Shelf slope S must stay in (0, 1]: for S > 1 the radicand below goes
451 // negative and std::sqrt yields NaN coefficients that poison the audio.
452 slope = std::clamp(slope, 0.0001, 1.0);
453 const double A = std::pow(10.0, gainDb / 40.0);
454 const double w0 = 2.0 * std::numbers::pi * freq / sampleRate;
455 const double cosw0 = std::cos(w0);
456 const double sinw0 = std::sin(w0);
457 const double radicand = (A + 1.0 / A) * (1.0 / slope - 1.0) + 2.0;
458 const double alpha = sinw0 / 2.0 * std::sqrt(std::max(0.0, radicand));
459 const double twoSqrtAAlpha = 2.0 * std::sqrt(A) * alpha;
460
461 const double a0 = (A + 1.0) - (A - 1.0) * cosw0 + twoSqrtAAlpha;
462 return normalise(a0,
463 A * ((A + 1.0) + (A - 1.0) * cosw0 + twoSqrtAAlpha),
464 -2.0 * A * ((A - 1.0) + (A + 1.0) * cosw0),
465 A * ((A + 1.0) + (A - 1.0) * cosw0 - twoSqrtAAlpha),
466 2.0 * ((A - 1.0) - (A + 1.0) * cosw0),
467 (A + 1.0) - (A - 1.0) * cosw0 - twoSqrtAAlpha);
468 }
469
476 [[nodiscard]] static BiquadCoeffs makeNotch(double sampleRate, double freq, double Q = 0.7071067811865476) noexcept
477 {
478 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
479 Q = std::max(Q, 0.001);
480 const double w0 = 2.0 * std::numbers::pi * freq / sampleRate;
481 const double cosw0 = std::cos(w0);
482 const double sinw0 = std::sin(w0);
483 const double alpha = sinw0 / (2.0 * Q);
484
485 const double a0 = 1.0 + alpha;
486 return normalise(a0,
487 1.0,
488 -2.0 * cosw0,
489 1.0,
490 -2.0 * cosw0,
491 1.0 - alpha);
492 }
493
500 [[nodiscard]] static BiquadCoeffs makeAllPass(double sampleRate, double freq, double Q = 0.7071067811865476) noexcept
501 {
502 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
503 Q = std::max(Q, 0.001);
504 const double w0 = 2.0 * std::numbers::pi * freq / sampleRate;
505 const double cosw0 = std::cos(w0);
506 const double sinw0 = std::sin(w0);
507 const double alpha = sinw0 / (2.0 * Q);
508
509 const double a0 = 1.0 + alpha;
510 return normalise(a0,
511 1.0 - alpha,
512 -2.0 * cosw0,
513 1.0 + alpha,
514 -2.0 * cosw0,
515 1.0 - alpha);
516 }
517
518 // -- First-order filter factory methods ------------------------------------
519
529 [[nodiscard]] static BiquadCoeffs makeFirstOrderLowPass(double sampleRate, double frequency) noexcept
530 {
531 frequency = std::clamp(frequency, 1.0, std::max(1.0, sampleRate * 0.499));
532 const double w = std::tan(std::numbers::pi * frequency / sampleRate);
533 const double n = 1.0 / (1.0 + w);
534 BiquadCoeffs c;
535 c.b0 = w * n;
536 c.b1 = w * n;
537 c.b2 = 0.0;
538 c.a1 = (w - 1.0) * n;
539 c.a2 = 0.0;
540 return c;
541 }
542
552 [[nodiscard]] static BiquadCoeffs makeFirstOrderHighPass(double sampleRate, double frequency) noexcept
553 {
554 frequency = std::clamp(frequency, 1.0, std::max(1.0, sampleRate * 0.499));
555 const double w = std::tan(std::numbers::pi * frequency / sampleRate);
556 const double n = 1.0 / (1.0 + w);
557 BiquadCoeffs c;
558 c.b0 = n;
559 c.b1 = -n;
560 c.b2 = 0.0;
561 c.a1 = (w - 1.0) * n;
562 c.a2 = 0.0;
563 return c;
564 }
565
578 [[nodiscard]] static BiquadCoeffs makeTilt(double sampleRate, double pivotFreq, double gainDb) noexcept
579 {
580 pivotFreq = std::clamp(pivotFreq, 1.0, std::max(1.0, sampleRate * 0.499));
581 const double g = std::pow(10.0, gainDb / 20.0);
582 const double sqrtG = std::sqrt(g);
583 const double c = std::tan(std::numbers::pi * pivotFreq / sampleRate);
584
585 // First-order tilt shelf via bilinear transform:
586 // DC gain = 1/sqrt(g), pivot gain = 1, Nyquist gain = sqrt(g)
587 // Total swing = gainDb (half below pivot, half above).
588 const double norm = 1.0 / (1.0 + sqrtG * c);
589
590 BiquadCoeffs coeffs;
591 coeffs.b0 = (sqrtG + c) * norm;
592 coeffs.b1 = (c - sqrtG) * norm;
593 coeffs.b2 = 0.0;
594 coeffs.a1 = (sqrtG * c - 1.0) * norm;
595 coeffs.a2 = 0.0;
596 return coeffs;
597 }
598
607 [[nodiscard]] static BiquadCoeffs makeKWeightingShelf(double sampleRate) noexcept
608 {
609 const double G = 3.999843853973347; // dB
610 const double Q = 0.7071752369554196;
611 const double fc = 1681.9744509555319; // Hz
612 const double K = std::tan(std::numbers::pi * fc / sampleRate);
613 const double Vh = std::pow(10.0, G / 20.0);
614 const double Vb = std::pow(Vh, 0.4996667741545416);
615 const double a0 = 1.0 + K / Q + K * K;
616 BiquadCoeffs c;
617 c.b0 = (Vh + Vb * K / Q + K * K) / a0;
618 c.b1 = 2.0 * (K * K - Vh) / a0;
619 c.b2 = (Vh - Vb * K / Q + K * K) / a0;
620 c.a1 = 2.0 * (K * K - 1.0) / a0;
621 c.a2 = (1.0 - K / Q + K * K) / a0;
622 return c;
623 }
624
632 [[nodiscard]] static BiquadCoeffs makeKWeightingHighPass(double sampleRate) noexcept
633 {
634 const double Q = 0.5003270373238773;
635 const double fc = 38.13547087602444; // Hz
636 const double K = std::tan(std::numbers::pi * fc / sampleRate);
637 const double a0 = 1.0 + K / Q + K * K;
638 BiquadCoeffs c;
639 c.b0 = 1.0;
640 c.b1 = -2.0;
641 c.b2 = 1.0;
642 c.a1 = 2.0 * (K * K - 1.0) / a0;
643 c.a2 = (1.0 - K / Q + K * K) / a0;
644 return c;
645 }
646
647 // -- Transparent set with the same poles ------------------------------------
648
661 [[nodiscard]] BiquadCoeffs bypassed() const noexcept
662 {
663 BiquadCoeffs c;
664 c.b0 = 1.0; c.b1 = a1; c.b2 = a2;
665 c.a1 = a1; c.a2 = a2;
666 return c;
667 }
668
669 // -- Frequency response analysis -------------------------------------------
670
683 [[nodiscard]] double getMagnitude(double frequency, double sampleRate) const noexcept
684 {
685 const double w = 2.0 * std::numbers::pi * frequency / sampleRate;
686 const double cosW = std::cos(w);
687 const double cos2W = std::cos(2.0 * w);
688 const double sinW = std::sin(w);
689 const double sin2W = std::sin(2.0 * w);
690
691 const double nRe = b0 + b1 * cosW + b2 * cos2W;
692 const double nIm = -b1 * sinW - b2 * sin2W;
693 const double dRe = 1.0 + a1 * cosW + a2 * cos2W;
694 const double dIm = -a1 * sinW - a2 * sin2W;
695
696 const double numMag2 = nRe * nRe + nIm * nIm;
697 const double denMag2 = dRe * dRe + dIm * dIm;
698
699 return (denMag2 > 1e-30) ? std::sqrt(numMag2 / denMag2) : 0.0;
700 }
701
714 template <typename U>
715 void getMagnitudeForFrequencyArray(std::span<const U> frequencies,
716 std::span<U> magnitudes,
717 double sampleRate) const noexcept
718 {
719 assert(magnitudes.size() >= frequencies.size());
720 for (size_t i = 0; i < frequencies.size(); ++i)
721 magnitudes[i] = static_cast<U>(getMagnitude(static_cast<double>(frequencies[i]), sampleRate));
722 }
723
724private:
727 struct MatchedPoles { double a1, a2, A0, A1, A2, phi0, phi1, phi2; };
728 [[nodiscard]] static MatchedPoles matchedPoles(double w0, double q) noexcept
729 {
730 MatchedPoles m {};
731 m.a2 = std::exp(-2.0 * q * w0);
732 if (q <= 1.0)
733 m.a1 = -2.0 * std::exp(-q * w0) * std::cos(std::sqrt(1.0 - q * q) * w0);
734 else
735 {
736 // Two real poles, evaluated one by one (each <= 1); -q + r as
737 // -1/(q + r) avoids the cancellation (see makePeakMatched()).
738 const double r = std::sqrt(q * q - 1.0);
739 m.a1 = -(std::exp(-w0 / (q + r)) + std::exp(-(q + r) * w0));
740 }
741 m.A0 = (1.0 + m.a1 + m.a2) * (1.0 + m.a1 + m.a2);
742 m.A1 = (1.0 - m.a1 + m.a2) * (1.0 - m.a1 + m.a2);
743 m.A2 = -4.0 * m.a2;
744 const double s = std::sin(0.5 * w0);
745 m.phi1 = s * s;
746 m.phi0 = 1.0 - m.phi1;
747 m.phi2 = 4.0 * m.phi0 * m.phi1;
748 return m;
749 }
750
754 [[nodiscard]] static BiquadCoeffs matchedShelf(double sampleRate, double freq, double gainDb, bool low) noexcept
755 {
756 freq = std::clamp(freq, 1.0, std::max(1.0, sampleRate * 0.499));
757 if (!(std::abs(gainDb) >= 0.01)) return { 1.0, 0.0, 0.0, 0.0, 0.0 };
758 constexpr double kPi = std::numbers::pi;
759 const double G = std::pow(10.0, (low ? -gainDb : gainDb) / 20.0);
760 const double fc = freq / (0.5 * sampleRate); // in units of Nyquist
761 const double fc2 = fc * fc, fc4 = fc2 * fc2;
762 const double hNy = (fc4 + G) / (fc4 + 1.0 / G); // |H|^2 at Nyquist
763 const double f1 = fc / std::sqrt(0.160 + 1.543 * fc2);
764 const double f2 = fc / std::sqrt(0.947 + 3.806 * fc2);
765 double ph1 = std::sin(0.5 * kPi * f1); ph1 *= ph1;
766 double ph2 = std::sin(0.5 * kPi * f2); ph2 *= ph2;
767 const double f14 = f1 * f1 * f1 * f1, f24 = f2 * f2 * f2 * f2;
768 const double h1 = (fc4 + f14 * G) / (fc4 + f14 / G);
769 const double h2 = (fc4 + f24 * G) / (fc4 + f24 / G);
770 const double d1 = (h1 - 1.0) * (1.0 - ph1), d2 = (h2 - 1.0) * (1.0 - ph2);
771 const double c11 = -ph1 * d1, c21 = -ph2 * d2;
772 const double c12 = (hNy - h1) * ph1 * ph1, c22 = (hNy - h2) * ph2 * ph2;
773 const double alpha1 = (c22 * d1 - c12 * d2) / (c11 * c22 - c12 * c21);
774 const double alpha2 = (d1 - c11 * alpha1) / c12;
775 const double beta1 = alpha1, beta2 = hNy * alpha2;
776 const double A1 = alpha2, A2 = 0.25 * (alpha1 - alpha2);
777 const double B1 = beta2, B2 = 0.25 * (beta1 - beta2);
778 const double V = 0.5 * (1.0 + std::sqrt(std::max(0.0, A1)));
779 const double Wn = 0.5 * (1.0 + std::sqrt(std::max(0.0, B1)));
780 const double a0 = 0.5 * (V + std::sqrt(std::max(0.0, V * V + A2)));
781 const double b0 = 0.5 * (Wn + std::sqrt(std::max(0.0, Wn * Wn + B2)));
782 const double scale = low ? std::pow(10.0, gainDb / 20.0) : 1.0;
783 BiquadCoeffs c;
784 c.b0 = scale * b0 / a0;
785 c.b1 = scale * (1.0 - Wn) / a0;
786 c.b2 = scale * (-0.25 * B2 / b0) / a0;
787 c.a1 = (1.0 - V) / a0;
788 c.a2 = (-0.25 * A2 / a0) / a0;
789 return c;
790 }
791
796 [[nodiscard]] static BiquadCoeffs normalise(double a0, double b0r, double b1r, double b2r,
797 double a1r, double a2r) noexcept
798 {
799 const double invA0 = 1.0 / a0;
800 return { b0r * invA0, b1r * invA0, b2r * invA0, a1r * invA0, a2r * invA0 };
801 }
802};
803
804// ============================================================================
805// Biquad -- Filter processor with per-channel state
806// ============================================================================
807
851template <typename T, int MaxChannels = 8>
852class alignas(32) Biquad
853{
854public:
855 Biquad() noexcept = default;
856
857 // std::atomic<bool> makes the default copy/move ops vanish. Provide manual
858 // move semantics so this class can live inside std::array / std::vector
859 // (e.g. CrossoverFilter::AllPassChain). Copying is left deleted on
860 // purpose: it would imply two threads observing the same staged coefficient
861 // dirty flag, which is semantically ambiguous and not needed in practice.
862 // Moves only happen during setup (single-threaded relocation into a
863 // container), so the seqlock counter is simply reset to an even value.
864 Biquad(Biquad&& other) noexcept
865 : activeCoeffs_(other.activeCoeffs_),
866 coeffsDirty_(other.coeffsDirty_.load(std::memory_order_relaxed)),
867 coeffsSeq_(0),
868 state_(other.state_)
869 {
870 copyStagedRelaxed(other); // Word-wise: the staging words are atomics.
871 }
872
873 Biquad& operator=(Biquad&& other) noexcept
874 {
875 if (this == &other) return *this;
876 activeCoeffs_ = other.activeCoeffs_;
877 copyStagedRelaxed(other); // Word-wise: the staging words are atomics.
878 coeffsDirty_.store(other.coeffsDirty_.load(std::memory_order_relaxed),
879 std::memory_order_relaxed);
880 coeffsSeq_.store(0, std::memory_order_relaxed);
881 state_ = other.state_;
882 return *this;
883 }
884
885 Biquad(const Biquad&) = delete;
886 Biquad& operator=(const Biquad&) = delete;
887
904 void setCoeffs(const BiquadCoeffs& c) noexcept
905 {
906 // Seqlock publish (single producer). An odd sequence number marks a
907 // write in progress; the audio thread retries its read while odd or if
908 // the counter moved, so a concurrent update can never be observed as a
909 // torn coefficient set (mixing a1 of one filter with a2 of another).
910 //
911 // Data-race freedom: the staging slot is 5 std::atomic<double> words
912 // stored relaxed inside the critical section, so every cross-thread
913 // word access is defined by the C++ memory model (the previous plain
914 // struct copy was formal UB -- the same defect class CI TSan flagged in
915 // FIRFilter). The release fence below pairs with the
916 // reader's acquire fence ([atomics.fences]/2): a reader that observes
917 // any mid-publish word must also observe the odd counter and retry
918 // (Boehm, "Can Seqlocks Get Along With Programming Language Memory
919 // Models?", MSPC 2012). Control-thread only: zero audio-path cost.
920 coeffsSeq_.fetch_add(1, std::memory_order_acq_rel); // -> odd
921 std::atomic_thread_fence(std::memory_order_release);
922 stagedCoeffs_.b0.store(c.b0, std::memory_order_relaxed);
923 stagedCoeffs_.b1.store(c.b1, std::memory_order_relaxed);
924 stagedCoeffs_.b2.store(c.b2, std::memory_order_relaxed);
925 stagedCoeffs_.a1.store(c.a1, std::memory_order_relaxed);
926 stagedCoeffs_.a2.store(c.a2, std::memory_order_relaxed);
927 coeffsSeq_.fetch_add(1, std::memory_order_release); // -> even
928 coeffsDirty_.store(true, std::memory_order_release);
929 }
930
963 void setCoeffsNow(const BiquadCoeffs& c) noexcept { activeCoeffs_ = c; }
964
986 bool applyPendingCoeffs() noexcept
987 {
988 if (!coeffsDirty_.exchange(false, std::memory_order_acquire)) return false;
989 return adoptStagedCoeffs();
990 }
991
1000 [[nodiscard]] const BiquadCoeffs& getCoeffs() const noexcept { return activeCoeffs_; }
1001
1003 void reset() noexcept
1004 {
1005 for (auto& s : state_)
1006 s = {};
1007 }
1008
1029 T processSample(T input, int channel) noexcept
1030 {
1031 return static_cast<T>(processSampleCore(static_cast<double>(input), channel));
1032 }
1033
1049 double processSampleCore(double input, int channel) noexcept
1050 {
1051 assert(channel >= 0 && channel < MaxChannels && "Channel index out of bounds");
1052
1053 // Lock-free fast path: relaxed load is free on every modern CPU.
1054 // Branch is marked unlikely so the compiler keeps the hot DSP path
1055 // straight-line; the dirty flag is only true on the first sample
1056 // of a block where setCoeffs() landed since last process call.
1057 if (coeffsDirty_.load(std::memory_order_relaxed)) [[unlikely]]
1059
1060 auto& s = state_[channel];
1061
1062 const double output = activeCoeffs_.b0 * input + s.z1;
1063 s.z1 = activeCoeffs_.b1 * input - activeCoeffs_.a1 * output + s.z2;
1064 s.z2 = activeCoeffs_.b2 * input - activeCoeffs_.a2 * output;
1065
1066 return output;
1067 }
1068
1092 void processRampCore(double* data, int n, int channel, const BiquadCoeffs& c0,
1093 const BiquadCoeffs& step) noexcept
1094 {
1095 assert(channel >= 0 && channel < MaxChannels && "Channel index out of bounds");
1096 if (n <= 0) return;
1097 auto& s = state_[channel];
1098 double z1 = s.z1, z2 = s.z2;
1099 double b0 = c0.b0, b1 = c0.b1, b2 = c0.b2, a1 = c0.a1, a2 = c0.a2;
1100 for (int k = 0; k < n; ++k)
1101 {
1102 b0 += step.b0; b1 += step.b1; b2 += step.b2; a1 += step.a1; a2 += step.a2;
1103 const double input = data[k];
1104 const double output = b0 * input + z1;
1105 z1 = b1 * input - a1 * output + z2;
1106 z2 = b2 * input - a2 * output;
1107 data[k] = output;
1108 }
1109 s.z1 = z1;
1110 s.z2 = z2;
1111 activeCoeffs_.b0 = b0;
1112 activeCoeffs_.b1 = b1;
1113 activeCoeffs_.b2 = b2;
1114 activeCoeffs_.a1 = a1;
1115 activeCoeffs_.a2 = a2;
1116 }
1117
1146 void processBlock(AudioBufferView<T> buffer) noexcept
1147 {
1148 DenormalGuard guard;
1149
1150 // Pick up any pending lock-free coefficient update from the GUI thread.
1152
1153 const int numChannels = std::min(buffer.getNumChannels(), MaxChannels);
1154 const int numSamples = buffer.getNumSamples();
1155
1156 // Block-local coefficient copy: stable for the whole block by design
1157 // (updates land at the next block boundary), and register-friendly.
1158 const BiquadCoeffs c = activeCoeffs_;
1159
1160 int ch = 0;
1161 if constexpr (kPairChannels)
1162 for (; ch + 1 < numChannels; ch += 2)
1163 processPair<simd::kVecDoubleNarrow>(buffer.getChannel(ch), buffer.getChannel(ch + 1),
1164 numSamples, c, state_[ch], state_[ch + 1]);
1165
1166 for (; ch < numChannels; ++ch)
1167 {
1168 T* data = buffer.getChannel(ch);
1169 auto& s = state_[ch];
1170 double z1 = s.z1;
1171 double z2 = s.z2;
1172
1173 for (int i = 0; i < numSamples; ++i)
1174 {
1175 const double input = static_cast<double>(data[i]);
1176 const double output = c.b0 * input + z1;
1177 z1 = c.b1 * input - c.a1 * output + z2;
1178 z2 = c.b2 * input - c.a2 * output;
1179 data[i] = static_cast<T>(output);
1180 }
1181
1182 recoverState(z1, z2);
1183 s.z1 = z1;
1184 s.z2 = z2;
1185 }
1186 }
1187
1188private:
1194 static constexpr int kSeqlockMaxAttempts = 3;
1195
1224 DSPARK_NOINLINE bool adoptStagedCoeffs() noexcept
1225 {
1226 BiquadCoeffs tmp;
1227 bool adopted = false;
1228 for (int attempt = 0; attempt < kSeqlockMaxAttempts; ++attempt)
1229 {
1230 const unsigned s0 = coeffsSeq_.load(std::memory_order_acquire);
1231 // Odd counter: the writer is mid-publish, so do not copy at all.
1232 // Testing this BEFORE the copy makes a collision cost one relaxed
1233 // load instead of a full word-set copy that would be thrown away,
1234 // which is what keeps the bound cheap enough for the per-sample
1235 // entry point.
1236 if ((s0 & 1u) != 0u) continue;
1237 // Relaxed word loads: each access is race-free because the staging
1238 // words are std::atomic<double>. The destination is a stack
1239 // temporary, NOT the live activeCoeffs_ the hot path reads, so a
1240 // give-up leaves the active set untouched (commit-on-validate).
1241 tmp.b0 = stagedCoeffs_.b0.load(std::memory_order_relaxed);
1242 tmp.b1 = stagedCoeffs_.b1.load(std::memory_order_relaxed);
1243 tmp.b2 = stagedCoeffs_.b2.load(std::memory_order_relaxed);
1244 tmp.a1 = stagedCoeffs_.a1.load(std::memory_order_relaxed);
1245 tmp.a2 = stagedCoeffs_.a2.load(std::memory_order_relaxed);
1246 // The fence keeps the copy above from sinking below the re-read of
1247 // the counter. A plain acquire load only orders LATER accesses;
1248 // without the fence, both the compiler and weakly-ordered CPUs
1249 // (ARM) may complete the copy after the counter is re-read, and a
1250 // torn copy would pass the equality check. It also pairs with the
1251 // writer's release fence, so a copy that read any mid-publish word
1252 // cannot pass validation.
1253 std::atomic_thread_fence(std::memory_order_acquire);
1254 if (s0 == coeffsSeq_.load(std::memory_order_relaxed))
1255 {
1256 adopted = true;
1257 break;
1258 }
1259 }
1260 if (!adopted)
1261 {
1262 // Adopt nothing; keep the set in use and pick the update up later.
1263 coeffsDirty_.store(true, std::memory_order_release);
1264 return false;
1265 }
1266 activeCoeffs_ = tmp;
1267 return true;
1268 }
1269
1270 // Kept compact on purpose (no over-alignment): the states are only ever
1271 // touched by the processing thread, sequentially per channel, so packing
1272 // adjacent channels into the same cache line is strictly better than
1273 // padding each one out to its own.
1274 struct State
1275 {
1276 double z1 = 0.0;
1277 double z2 = 0.0;
1278 };
1279
1281 static void recoverState(double& z1, double& z2) noexcept
1282 {
1283 if (!std::isfinite(z1 + z2)) { z1 = 0.0; z2 = 0.0; }
1284 }
1285
1288 static constexpr bool kPairChannels = simd::kVecDoubleNarrow == 2 && sizeof(void*) == 8;
1289
1291 template <int W>
1292 static void processPair(T* left, T* right, int numSamples, const BiquadCoeffs& c,
1293 State& sl, State& sr) noexcept
1294 {
1295 using O = simd::Vec<double, W>;
1296 const auto b0 = O::set1(c.b0), b1 = O::set1(c.b1), b2 = O::set1(c.b2);
1297 const auto a1 = O::set1(c.a1), a2 = O::set1(c.a2);
1298 auto z1 = O::set2(sl.z1, sr.z1);
1299 auto z2 = O::set2(sl.z2, sr.z2);
1300 for (int i = 0; i < numSamples; ++i)
1301 {
1302 const auto x = O::set2(static_cast<double>(left[i]), static_cast<double>(right[i]));
1303 const auto y = O::add(O::mul(b0, x), z1);
1304 z1 = O::add(O::sub(O::mul(b1, x), O::mul(a1, y)), z2);
1305 z2 = O::sub(O::mul(b2, x), O::mul(a2, y));
1306 left[i] = static_cast<T>(O::lane0(y));
1307 right[i] = static_cast<T>(O::lane1(y));
1308 }
1309 double l1 = O::lane0(z1), l2 = O::lane0(z2), r1 = O::lane1(z1), r2 = O::lane1(z2);
1310 recoverState(l1, l2);
1311 recoverState(r1, r2);
1312 sl.z1 = l1; sl.z2 = l2;
1313 sr.z1 = r1; sr.z2 = r2;
1314 }
1315
1316 // Shared staging slot for the seqlock publish: written word-by-word by the
1317 // control thread inside the odd/even critical section and read word-by-word
1318 // by the audio thread's retry loop. Every word is std::atomic<double>
1319 // (relaxed) so each cross-thread access is defined by the C++ memory model
1320 // (no non-atomic concurrent read/write, i.e. no data-race UB); the seq
1321 // counter plus the writer release / reader acquire fence pair order and
1322 // tear-protect the 5-word set. std::atomic<double> is lock-free and one
1323 // machine word on every supported target, so the publish stays lock- and
1324 // allocation-free. Defaults mirror BiquadCoeffs{} (identity filter).
1325 struct StagedCoeffs
1326 {
1327 std::atomic<double> b0{1.0}, b1{0.0}, b2{0.0};
1328 std::atomic<double> a1{0.0}, a2{0.0};
1329 };
1330
1332 void copyStagedRelaxed(const Biquad& other) noexcept
1333 {
1334 stagedCoeffs_.b0.store(other.stagedCoeffs_.b0.load(std::memory_order_relaxed),
1335 std::memory_order_relaxed);
1336 stagedCoeffs_.b1.store(other.stagedCoeffs_.b1.load(std::memory_order_relaxed),
1337 std::memory_order_relaxed);
1338 stagedCoeffs_.b2.store(other.stagedCoeffs_.b2.load(std::memory_order_relaxed),
1339 std::memory_order_relaxed);
1340 stagedCoeffs_.a1.store(other.stagedCoeffs_.a1.load(std::memory_order_relaxed),
1341 std::memory_order_relaxed);
1342 stagedCoeffs_.a2.store(other.stagedCoeffs_.a2.load(std::memory_order_relaxed),
1343 std::memory_order_relaxed);
1344 }
1345
1346 BiquadCoeffs activeCoeffs_ {};
1347 StagedCoeffs stagedCoeffs_ {};
1348 std::atomic<bool> coeffsDirty_{false};
1349 std::atomic<unsigned> coeffsSeq_{0};
1350
1351 std::array<State, MaxChannels> state_ {};
1352};
1353
1354} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Biquad filter using Transposed Direct Form II (TDF-II) with thread-safe updates.
Definition Biquad.h:853
Biquad(const Biquad &)=delete
void setCoeffs(const BiquadCoeffs &c) noexcept
Sets the filter coefficients asynchronously (control thread).
Definition Biquad.h:904
void setCoeffsNow(const BiquadCoeffs &c) noexcept
Stream-owner direct set: makes c the active set immediately.
Definition Biquad.h:963
void reset() noexcept
Resets all per-channel filter states to zero to avoid ringing/clicks.
Definition Biquad.h:1003
const BiquadCoeffs & getCoeffs() const noexcept
Returns the active coefficient set currently in use by the DSP thread.
Definition Biquad.h:1000
bool applyPendingCoeffs() noexcept
Promotes any pending staged coefficients to active.
Definition Biquad.h:986
Biquad & operator=(Biquad &&other) noexcept
Definition Biquad.h:873
void processBlock(AudioBufferView< T > buffer) noexcept
Processes a full audio buffer in-place.
Definition Biquad.h:1146
Biquad & operator=(const Biquad &)=delete
void processRampCore(double *data, int n, int channel, const BiquadCoeffs &c0, const BiquadCoeffs &step) noexcept
Runs n samples of one channel through the filter while the coefficients move linearly,...
Definition Biquad.h:1092
T processSample(T input, int channel) noexcept
Processes a single sample for a specific channel.
Definition Biquad.h:1029
double processSampleCore(double input, int channel) noexcept
One recursion step in the core's own precision (double).
Definition Biquad.h:1049
Biquad() noexcept=default
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
static BiquadCoeffs makeFirstOrderHighPass(double sampleRate, double frequency) noexcept
First-order (6 dB/oct) high-pass filter.
Definition Biquad.h:552
static BiquadCoeffs makePeakMatched(double sampleRate, double freq, double Q, double gainDb) noexcept
Analog-matched ("de-cramped") peaking filter (Vicanek design).
Definition Biquad.h:248
void getMagnitudeForFrequencyArray(std::span< const U > frequencies, std::span< U > magnitudes, double sampleRate) const noexcept
Computes magnitude responses for a batch of frequencies.
Definition Biquad.h:715
static BiquadCoeffs makeHighPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
High-pass filter.
Definition Biquad.h:143
static BiquadCoeffs makeHighShelfMatched(double sampleRate, double freq, double gainDb) noexcept
Analog-matched Butterworth high shelf (see makeLowShelfMatched()).
Definition Biquad.h:405
static BiquadCoeffs makeAllPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
All-pass filter.
Definition Biquad.h:500
static BiquadCoeffs makeBandPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Band-pass filter (constant 0 dB peak gain).
Definition Biquad.h:172
static BiquadCoeffs makeLowShelfMatched(double sampleRate, double freq, double gainDb) noexcept
Analog-matched Butterworth low shelf (Vicanek, "Matched Two-Pole Digital Shelving Filters",...
Definition Biquad.h:399
static BiquadCoeffs makePeak(double sampleRate, double freq, double Q, double gainDb) noexcept
Peak (parametric EQ) filter.
Definition Biquad.h:201
static BiquadCoeffs makeKWeightingHighPass(double sampleRate) noexcept
ITU-R BS.1770 K-weighting, stage 2: the RLB high-pass.
Definition Biquad.h:632
double getMagnitude(double frequency, double sampleRate) const noexcept
Evaluates magnitude response |H(f)| at a single frequency.
Definition Biquad.h:683
static BiquadCoeffs makeFirstOrderLowPass(double sampleRate, double frequency) noexcept
First-order (6 dB/oct) low-pass filter.
Definition Biquad.h:529
static BiquadCoeffs makeTilt(double sampleRate, double pivotFreq, double gainDb) noexcept
Creates a first-order tilt filter.
Definition Biquad.h:578
static BiquadCoeffs makeKWeightingShelf(double sampleRate) noexcept
ITU-R BS.1770 K-weighting, stage 1: the head-related high shelf.
Definition Biquad.h:607
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 makeBandPassMatched(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Analog-matched band-pass, 0 dB at the centre (Vicanek 2016).
Definition Biquad.h:370
static BiquadCoeffs makeLowShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
Low-shelf filter.
Definition Biquad.h:417
static BiquadCoeffs makeLowPassMatched(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Analog-matched second-order low-pass (Vicanek, "Matched Second Order Digital Filters",...
Definition Biquad.h:321
static BiquadCoeffs makeHighShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
High-shelf filter.
Definition Biquad.h:447
static BiquadCoeffs makeHighPassMatched(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Analog-matched second-order high-pass (Vicanek 2016).
Definition Biquad.h:347
static BiquadCoeffs makeNotch(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Notch (band-reject) filter.
Definition Biquad.h:476