DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
StateVariableFilter.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
60#include "DspMath.h"
61#include "AudioSpec.h"
62#include "AudioBuffer.h"
63#include "DenormalGuard.h"
64#include "detail/TptSvf.h"
65
66#include <algorithm>
67#include <array>
68#include <cmath>
69
70namespace dspark {
71
91template <FloatType T>
93{
94public:
96 enum class Mode
97 {
98 LowPass,
99 HighPass,
100 BandPass,
101 Notch,
102 AllPass,
103 Bell,
104 LowShelf,
105 HighShelf
106 };
107
115 {
119 };
120
122
123 // -- Lifecycle --------------------------------------------------------------
124
133 void prepare(const AudioSpec& spec) noexcept
134 {
135 if (!(spec.sampleRate > 0.0)) return;
136 spec_ = spec;
137 updateCoefficients();
138 reset();
139 }
140
150 void processBlock(AudioBufferView<T> buffer) noexcept
151 {
152 DenormalGuard guard;
153 const int nCh = std::min(buffer.getNumChannels(), kMaxChannels);
154 const int nS = buffer.getNumSamples();
155
156 // One loop per mode with the coefficients and the state in locals: the
157 // compiler can no longer assume the sample pointer aliases the members,
158 // so nothing is reloaded per sample (measured: MSVC x64 LP 4.74 ->
159 // 2.41 ns/sample; GCC 15 at the default parameters 6.0 -> 2.3).
160 // Same arithmetic as processSample(), same output.
161 switch (mode_)
162 {
163 case Mode::LowPass: processBlockMode<Mode::LowPass>(buffer, nCh, nS); break;
164 case Mode::HighPass: processBlockMode<Mode::HighPass>(buffer, nCh, nS); break;
165 case Mode::BandPass: processBlockMode<Mode::BandPass>(buffer, nCh, nS); break;
166 case Mode::Notch: processBlockMode<Mode::Notch>(buffer, nCh, nS); break;
167 case Mode::AllPass: processBlockMode<Mode::AllPass>(buffer, nCh, nS); break;
168 case Mode::Bell: processBlockMode<Mode::Bell>(buffer, nCh, nS); break;
169 case Mode::LowShelf: processBlockMode<Mode::LowShelf>(buffer, nCh, nS); break;
170 case Mode::HighShelf: processBlockMode<Mode::HighShelf>(buffer, nCh, nS); break;
171 }
172 }
173
190 [[nodiscard]] T processSample(T input, int channel) noexcept
191 {
192 if (channel < 0 || channel >= kMaxChannels) return input;
193 return processOne(input, channel);
194 }
195
208 [[nodiscard]] MultiOutput processMultiOutput(T input, int channel) noexcept
209 {
210 if (channel < 0 || channel >= kMaxChannels) return { input, T(0), T(0) };
211 return processCore(input, channel);
212 }
213
215 void reset() noexcept
216 {
217 for (auto& s : state_)
218 {
219 s.ic1eq = T(0);
220 s.ic2eq = T(0);
221 }
222 }
223
224 // -- Parameters (Level 1) ---------------------------------------------------
225
237 void setCutoff(T hz) noexcept
238 {
239 if (!std::isfinite(hz)) return;
240 cutoff_ = std::max(hz, T(0));
241 updateCoefficients();
242 }
243
251 void setResonance(T resonance) noexcept
252 {
253 if (!std::isfinite(resonance)) return; // NaN would poison R_
254 resonance_ = std::clamp(resonance, T(0), T(1));
255 // Map 0-1 to Q: 0.5 (wide) to 50 (near self-osc). R = 1/(2*Q).
256 const T Q = T(0.5) + resonance_ * T(49.5);
257 R_ = T(1) / (T(2) * Q);
258 updateBellR();
259 updateDerivedCoeffs();
260 }
261
271 void setQ(T q) noexcept
272 {
273 if (!std::isfinite(q)) return; // NaN would poison R_
274 q = std::max(q, T(0.01));
275 R_ = T(1) / (T(2) * q);
276 resonance_ = std::clamp((q - T(0.5)) / T(49.5), T(0), T(1));
277 updateBellR();
278 updateDerivedCoeffs();
279 }
280
282 void setMode(Mode mode) noexcept
283 {
284 mode_ = mode;
285 updateDerivedCoeffs();
286 }
287
292 void setGain(T dB) noexcept
293 {
294 if (!std::isfinite(dB)) return; // NaN/Inf would poison A_
295 gainDb_ = dB;
296 A_ = std::pow(T(10), std::abs(dB) / T(40)); // sqrt(linear gain)
297 updateBellR();
298 updateDerivedCoeffs();
299 }
300
301 // -- Getters ----------------------------------------------------------------
302
303 [[nodiscard]] T getCutoff() const noexcept { return cutoff_; }
304 [[nodiscard]] T getResonance() const noexcept { return resonance_; }
305 [[nodiscard]] T getQ() const noexcept { return T(1) / (T(2) * R_); }
306 [[nodiscard]] T getGain() const noexcept { return gainDb_; }
307 [[nodiscard]] Mode getMode() const noexcept { return mode_; }
308
309protected:
310 static constexpr int kMaxChannels = 16;
311
313
314 std::array<ChannelState, kMaxChannels> state_ {};
316 T cutoff_ = T(1000);
317 T resonance_ = T(0);
318 T gainDb_ = T(0);
319 T g_ = T(0); // tan(pi * fc / fs) - TPT coefficient
320 T R_ = T(1); // 1/(2*Q) - damping
321 T Rbell_ = T(1); // Mode-specific R for Bell (Zavalishin gain-dependent damping)
322 T A_ = T(1); // sqrt(gain) for shelving/bell
324
325 // Cached derived coefficients (recomputed by updateDerivedCoeffs()).
326 T effG_ = T(0); // possibly shelf-prewarped g
327 T effR_ = T(1); // mode-effective damping (R_ or Rbell_)
328 T a1_ = T(1), a2_ = T(0), a3_ = T(0);
329
330private:
338 void updateCoefficients() noexcept
339 {
340 if (spec_.sampleRate > 0)
341 {
342 cutoff_ = std::clamp(cutoff_, T(20),
343 static_cast<T>(spec_.sampleRate) * T(0.499));
344 g_ = static_cast<T>(std::tan(pi<double> * static_cast<double>(cutoff_)
345 / spec_.sampleRate));
346 }
347 updateBellR();
348 updateDerivedCoeffs();
349 }
350
352 void updateBellR() noexcept
353 {
354 // Zavalishin Bell EQ topology: modify damping by gain factor A
355 // (A_ >= 1 always - setGain uses |dB| and rejects non-finite input).
356 // Boost: decrease R (increase Q) => narrower peak compensates for gain spread
357 // Cut: increase R (decrease Q) => wider notch compensates for gain spread
358 if (gainDb_ >= T(0))
359 Rbell_ = R_ / A_;
360 else
361 Rbell_ = R_ * A_;
362 }
363
375 void updateDerivedCoeffs() noexcept
376 {
377 effR_ = (mode_ == Mode::Bell) ? Rbell_ : R_;
378
379 T gEff = g_;
381 {
382 const T sqrtAs = std::sqrt((gainDb_ >= T(0)) ? A_ : T(1) / A_);
383 gEff = (mode_ == Mode::LowShelf) ? g_ / sqrtAs : g_ * sqrtAs;
384 }
385
386 effG_ = gEff;
387 a1_ = T(1) / (T(1) + T(2) * effR_ * gEff + gEff * gEff);
388 a2_ = gEff * a1_;
389 a3_ = gEff * a2_;
390 }
391
395 template <Mode M>
396 void processBlockMode(AudioBufferView<T> buffer, int nCh, int nS) noexcept
397 {
398 const T a1 = a1_, a2 = a2_, a3 = a3_;
399 const T twoEffR = T(2) * effR_;
400 const T twoR = T(2) * R_;
401 const T As = (gainDb_ >= T(0)) ? A_ : T(1) / A_;
402 const T shelf0 = As * As, shelf1 = As * twoR;
403 const T k = T(2) * Rbell_;
404 const T bell = (gainDb_ >= T(0)) ? (A_ * A_ - T(1)) * k : (T(1) / (A_ * A_) - T(1)) * k;
405 for (int ch = 0; ch < nCh; ++ch)
406 {
407 T* data = buffer.getChannel(ch);
408 ChannelState st = state_[ch];
409 for (int i = 0; i < nS; ++i)
410 {
411 const T x = data[i];
412 const auto o = detail::tptSvfStep(x, st, a1, a2, a3);
413 const T lp = o.lowpass, bp = o.bandpass;
414 const T hp = x - twoEffR * bp - lp;
415 T y;
416 if constexpr (M == Mode::LowPass) y = lp;
417 else if constexpr (M == Mode::HighPass) y = hp;
418 else if constexpr (M == Mode::BandPass) y = bp;
419 else if constexpr (M == Mode::Notch) y = lp + hp;
420 else if constexpr (M == Mode::AllPass) y = lp + hp - twoR * bp;
421 else if constexpr (M == Mode::Bell) y = x + bell * bp;
422 else if constexpr (M == Mode::LowShelf) y = shelf0 * lp + shelf1 * bp + hp;
423 else y = lp + shelf1 * bp + shelf0 * hp;
424 data[i] = y;
425 }
426 if (!std::isfinite(st.ic1eq + st.ic2eq)) st = ChannelState {};
427 state_[ch] = st;
428 }
429 }
430
432 [[nodiscard]] T processOne(T input, int channel) noexcept
433 {
434 const MultiOutput m = processCore(input, channel);
435 return selectOutput(input, m.lowpass, m.highpass, m.bandpass);
436 }
437
451 [[nodiscard]] MultiOutput processCore(T input, int channel) noexcept
452 {
453 const auto output = detail::tptSvfStep(input, state_[channel], a1_, a2_, a3_);
454 return { output.lowpass, input - T(2) * effR_ * output.bandpass - output.lowpass,
455 output.bandpass };
456 }
457
458 [[nodiscard]] T selectOutput(T input, T lp, T hp, T bp) const noexcept
459 {
460 switch (mode_)
461 {
462 case Mode::LowPass: return lp;
463 case Mode::HighPass: return hp;
464 case Mode::BandPass: return bp;
465 case Mode::Notch: return lp + hp; // LP + HP = Notch
466 case Mode::AllPass: return lp + hp - T(2) * R_ * bp; // HP - 2R*BP + LP
467 case Mode::Bell:
468 {
469 // Bell EQ (Zavalishin ch. 4): bandwidth-correct topology.
470 // processCore already used Rbell_ for the SVF damping,
471 // so the BP bandwidth is correct. Apply gain via mixing:
472 // boost: output = input + (A^2 - 1) * 2*Rbell * BP
473 // cut: output = input + (1/A^2 - 1) * 2*Rbell * BP
474 // At the centre frequency 2*Rbell*bp == input, so the mix factor
475 // must be (A^2 - 1) to reach gain A^2 (boost) and (1/A^2 - 1) to
476 // reach gain 1/A^2 (cut). The cut term must be NEGATIVE - the old
477 // (1 - 1/A^2) was positive and boosted instead of cutting.
478 const T k = T(2) * Rbell_;
479 return (gainDb_ >= T(0))
480 ? input + (A_ * A_ - T(1)) * k * bp
481 : input + (T(1) / (A_ * A_) - T(1)) * k * bp;
482 }
483 case Mode::LowShelf:
484 {
485 // Canonical Simper low shelf. With As = A_ (boost) or 1/A_
486 // (cut), where A_ = 10^(|dB|/40) = sqrt(linear gain), and the
487 // pre-warped g from updateDerivedCoeffs():
488 // out = As^2 * LP + 2R * As * BP + HP
489 // DC gain = As^2 (= linear gain), Nyquist gain = 1, and the
490 // half-gain point sits exactly on the nominal frequency.
491 const T As = (gainDb_ >= T(0)) ? A_ : T(1) / A_;
492 const T twoR = T(2) * R_;
493 return As * As * lp + As * twoR * bp + hp;
494 }
495 case Mode::HighShelf:
496 {
497 // Canonical Simper high shelf (mirror of the low shelf):
498 // out = LP + 2R * As * BP + As^2 * HP
499 const T As = (gainDb_ >= T(0)) ? A_ : T(1) / A_;
500 const T twoR = T(2) * R_;
501 return lp + As * twoR * bp + As * As * hp;
502 }
503 }
504 return lp;
505 }
506};
507
508} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
TPT State Variable Filter with simultaneous multi-output.
void setResonance(T resonance) noexcept
Sets the resonance amount.
void setCutoff(T hz) noexcept
Sets the cutoff/center frequency.
std::array< ChannelState, kMaxChannels > state_
void setQ(T q) noexcept
Sets the Q factor directly.
void reset() noexcept
Resets internal state.
void setGain(T dB) noexcept
Sets gain for Bell/Shelf modes (in dB).
static constexpr int kMaxChannels
void setMode(Mode mode) noexcept
Sets the output mode.
MultiOutput processMultiOutput(T input, int channel) noexcept
Processes a single sample returning LP, HP, BP simultaneously.
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an audio buffer in-place using the selected Mode.
detail::TptSvfState< T > ChannelState
Mode
Filter output mode for processBlock/processSample.
@ LowShelf
Low shelf (boost/cut below frequency).
@ BandPass
Bandpass (constant skirt gain).
@ AllPass
Allpass (phase shift, unity gain).
@ LowPass
2nd-order lowpass (12 dB/oct).
@ Bell
Parametric bell (boost/cut at frequency).
@ Notch
Band-reject (notch).
@ HighShelf
High shelf (boost/cut above frequency).
@ HighPass
2nd-order highpass (12 dB/oct).
T processSample(T input, int channel) noexcept
Processes a single sample (selected Mode output).
void prepare(const AudioSpec &spec) noexcept
Prepares the filter.
TptSvfOutput< T > tptSvfStep(T input, TptSvfState< T > &state, T a1, T a2, T a3) noexcept
Advances the expanded Simper TPT recurrence by one sample.
Definition TptSvf.h:43
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
Result struct for simultaneous multi-output processing.
Equivalent-current memories of the two trapezoidal integrators.
Definition TptSvf.h:20