DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
DCBlocker.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
49#include "../Core/DspMath.h"
50#include "../Core/Biquad.h"
51#include "../Core/SimdOps.h"
52#include "../Core/AudioSpec.h"
53#include "../Core/AudioBuffer.h"
54#include "../Core/StateBlob.h"
55#include "../Core/detail/DcBlock.h"
56
57#include <algorithm>
58#include <array>
59#include <atomic>
60#include <cassert>
61#include <cmath>
62#include <cstddef>
63#include <cstdint>
64#include <numbers>
65#include <vector>
66
67namespace dspark {
68
89template <FloatType T>
91{
92public:
93 static constexpr int kMaxBiquadStages = 5;
94 static constexpr int kMaxChannels = 16;
95
98
99 ~DCBlocker() = default; // Non-virtual to avoid vtable injection
100
113 void prepare(double sampleRate, int numChannels = 2, double cutoffHz = -1.0)
114 {
115 if (!(sampleRate > 0.0)) return;
116 sampleRate_ = sampleRate;
117 numChannels_ = std::clamp(numChannels, 1, kMaxChannels);
118
119 reset();
120
121 // Use the thread-safe setter to clamp and initialize safely
122 if (cutoffHz > 0.0)
123 setCutoff(static_cast<T>(cutoffHz));
125 }
126
128 void prepare(const AudioSpec& spec)
129 {
130 prepare(spec.sampleRate, spec.numChannels);
131 }
132
148 void setOrder(int order) noexcept
149 {
150 order_.store(std::clamp(order, 1, 10), std::memory_order_relaxed);
151 }
152
154 [[nodiscard]] int getOrder() const noexcept
155 {
156 return order_.load(std::memory_order_relaxed);
157 }
158
170 void setCutoff(T hz) noexcept
171 {
172 if (!std::isfinite(hz)) return;
173 cutoffHz_.store(std::max(hz, T(1)), std::memory_order_relaxed);
174 }
175
177 [[nodiscard]] T getCutoff() const noexcept
178 {
179 return cutoffHz_.load(std::memory_order_relaxed);
180 }
181
190 void processBlock(AudioBufferView<T> buffer) noexcept
191 {
193
194 // lastOrder_ is the order the live coefficients were designed for.
195 // Reloading the atomic here could pick up a setOrder() that landed
196 // after the rebuild and enable stages that hold no coefficients yet.
197 const int currentOrder = lastOrder_;
198 const int nCh = std::min(buffer.getNumChannels(), numChannels_);
199 const int nS = buffer.getNumSamples();
200 if (nS <= 0) return;
201
202 // Pairs of channels share the two lanes of one register; an odd last
203 // channel runs alone. Each lane computes the single-channel operations.
204 int ch = 0;
205 if constexpr (kPairChannels)
206 {
207 for (; ch + 1 < nCh; ch += 2)
208 runPair<simd::kVecDoubleNarrow>(buffer.getChannel(ch), buffer.getChannel(ch + 1), nS, ch, ch + 1, currentOrder);
209 }
210 for (; ch < nCh; ++ch)
211 {
212 if (currentOrder <= 1)
213 runOnePole(buffer.getChannel(ch), nS, ch);
214 else
215 runCascade(buffer.getChannel(ch), nS, ch, std::clamp(currentOrder / 2, 1, kMaxBiquadStages));
216 }
217 }
218
228 void processBlock(int channel, T* data, int numSamples) noexcept
229 {
230 if (channel < 0 || channel >= kMaxChannels) return;
231 if (data == nullptr || numSamples <= 0) return;
233 const int currentOrder = lastOrder_;
234
235 if (currentOrder <= 1)
236 runOnePole(data, numSamples, channel);
237 else
238 runCascade(data, numSamples, channel,
239 std::clamp(currentOrder / 2, 1, kMaxBiquadStages));
240 }
241
262 [[nodiscard]] T processSample(int channel, T input) noexcept
263 {
264 if (channel < 0 || channel >= kMaxChannels) return input;
266 const auto ch = static_cast<size_t>(channel);
267 const double x = std::isfinite(input) ? static_cast<double>(input) : 0.0;
268
269 if (lastOrder_ <= 1)
270 return static_cast<T>(stepOnePole(onePoleR_, onePole_[ch], x));
271
272 const int numStages = std::clamp(lastOrder_ / 2, 1, kMaxBiquadStages);
273 double v = x;
274 for (int s = 0; s < numStages; ++s)
275 {
276 auto& sec = sections_[static_cast<size_t>(s)];
277 v = stepSection(sec.b0, sec.a1, sec.a2, sec.state[ch], v);
278 }
279 return static_cast<T>(v);
280 }
281
285 void reset() noexcept
286 {
287 onePole_.fill(OnePoleState{});
288 for (auto& s : sections_)
289 s.state.fill(SectionState{});
290 }
291
292
294 [[nodiscard]] std::vector<uint8_t> getState() const
295 {
296 StateWriter w(stateId("DCBL"), 1);
297 w.write("order", order_.load(std::memory_order_relaxed));
298 w.write("cutoff", static_cast<float>(cutoffHz_.load(std::memory_order_relaxed)));
299 return w.blob();
300 }
301
303 bool setState(const uint8_t* data, size_t size)
304 {
305 StateReader r(data, size);
306 if (!r.isValid() || r.processorId() != stateId("DCBL")) return false;
307 setOrder(r.read("order", 1));
308 setCutoff(static_cast<T>(r.read("cutoff", 5.0f)));
309 return true;
310 }
311
312protected:
314 {
315 // The ORDER is part of the design, not just a stage count: each order
316 // has its own Q table row, and a larger order enables stages that may
317 // never have received coefficients. Rebuilding only on cutoff changes
318 // left a live setOrder() running a broken hybrid (old-Q first stage +
319 // identity stages) until the cutoff happened to move.
320 const T cutoff = cutoffHz_.load(std::memory_order_relaxed);
321 const int order = order_.load(std::memory_order_relaxed);
322 if (cutoff != lastCutoff_ || order != lastOrder_)
323 {
324 forceUpdateCoefficients(cutoff);
325 }
326 }
327
328 void forceUpdateCoefficients(T explicitCutoff = T(0)) noexcept
329 {
330 const T cutoff = explicitCutoff > T(0) ? explicitCutoff : cutoffHz_.load(std::memory_order_relaxed);
331 const double fc = static_cast<double>(cutoff);
332 // Loaded ONCE: reading order_ again below could pick up a concurrent
333 // setOrder() and record a design (lastOrder_) whose stages were never
334 // built, which the processing paths would then run as silent sections.
335 const int order = order_.load(std::memory_order_relaxed);
336
337 // 1-Pole update
338 onePoleR_ = std::exp(-std::numbers::pi * 2.0 * fc / sampleRate_);
339
340 // Biquad updates
341 static constexpr float qTable[6][kMaxBiquadStages] = {
342 {}, // index 0 (unused)
343 { 0.7071f }, // order 2
344 { 0.5412f, 1.3066f }, // order 4
345 { 0.5177f, 0.7071f, 1.9319f }, // order 6
346 { 0.5098f, 0.6013f, 0.8999f, 2.5628f }, // order 8
347 { 0.5062f, 0.5612f, 0.7071f, 1.1013f, 3.1962f } // order 10
348 };
349
350 const int tableIdx = std::clamp(order / 2, 1, 5);
351 for (int s = 0; s < tableIdx; ++s)
352 {
353 // Designed in double and used as b0 * (1 - z^-1)^2 / A(z): the RBJ
354 // high-pass numerator IS b0 * (1, -2, 1) - exactly so in binary
355 // floating point, since halving and doubling are exact and all
356 // three share the same 1/a0 factor - which is what lets the DC
357 // zero be applied structurally in the inner loop.
358 const auto c = BiquadCoeffs::makeHighPass(
359 sampleRate_, fc, static_cast<double>(qTable[tableIdx][s]));
360 assert(c.b1 == -2.0 * c.b0 && c.b2 == c.b0
361 && "RBJ high-pass numerator is no longer b0 * (1, -2, 1)");
362
363 auto& sec = sections_[static_cast<size_t>(s)];
364 sec.b0 = c.b0;
365 sec.a1 = c.a1;
366 sec.a2 = c.a2;
367 }
368
369 lastCutoff_ = cutoff;
370 lastOrder_ = order;
371 }
372
373 // -- Double-precision filter core -----------------------------------------
374
376 struct SectionState { double x1 = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0; };
377
379 struct Section
380 {
381 double b0 = 0.0, a1 = 0.0, a2 = 0.0;
382 std::array<SectionState, kMaxChannels> state {};
383 };
384
386 static double stepOnePole(double r, OnePoleState& z, double x) noexcept
387 {
388 return detail::dcBlockStep(r, z, x);
389 }
390
392 static double stepSection(double b0, double a1, double a2, SectionState& z, double x) noexcept
393 {
394 // (x - x1) - (x1 - x2) is exactly zero for a constant input in IEEE
395 // arithmetic, so steady DC never reaches the recursion at all.
396 const double d = (x - z.x1) - (z.x1 - z.x2);
397 const double y = b0 * d - a1 * z.y1 - a2 * z.y2;
398 z.x2 = z.x1; z.x1 = x;
399 z.y2 = z.y1; z.y1 = y;
400 return y;
401 }
402
414 static constexpr double kDenormalFloor = 1e-30;
415
416 static void flushDenormals(OnePoleState& z) noexcept
417 {
418 if (std::abs(z.y1) + std::abs(z.x1) < kDenormalFloor)
419 z = OnePoleState{};
420 }
421
422 static void flushDenormals(SectionState& z) noexcept
423 {
424 if (std::abs(z.y1) + std::abs(z.y2) + std::abs(z.x1) + std::abs(z.x2) < kDenormalFloor)
425 z = SectionState{};
426 }
427
428 void runOnePole(T* data, int numSamples, int channel) noexcept
429 {
430 const double r = onePoleR_;
431 OnePoleState z = onePole_[static_cast<size_t>(channel)];
432 // A non-finite sample enters as 0: the recursion would otherwise latch
433 // it forever (no-op on finite input).
434 for (int i = 0; i < numSamples; ++i)
435 data[i] = static_cast<T>(stepOnePole(r, z, std::isfinite(data[i]) ? static_cast<double>(data[i]) : 0.0));
436 flushDenormals(z);
437 onePole_[static_cast<size_t>(channel)] = z;
438 }
439
440 void runCascade(T* data, int numSamples, int channel, int numStages) noexcept
441 {
442 // Coefficients and history are lifted into locals for the whole block:
443 // the intermediate signal then stays in double across the cascade and
444 // the compiler is free to keep the state in registers (writing to
445 // data[i] would otherwise be assumed to alias the member state).
446 double b0[kMaxBiquadStages] {}, a1[kMaxBiquadStages] {}, a2[kMaxBiquadStages] {};
447 SectionState z[kMaxBiquadStages] {};
448 const auto ch = static_cast<size_t>(channel);
449 for (int s = 0; s < numStages; ++s)
450 {
451 const auto& sec = sections_[static_cast<size_t>(s)];
452 b0[s] = sec.b0; a1[s] = sec.a1; a2[s] = sec.a2;
453 z[s] = sec.state[ch];
454 }
455
456 for (int i = 0; i < numSamples; ++i)
457 {
458 double v = std::isfinite(data[i]) ? static_cast<double>(data[i]) : 0.0;
459 for (int s = 0; s < numStages; ++s)
460 v = stepSection(b0[s], a1[s], a2[s], z[s], v);
461 data[i] = static_cast<T>(v);
462 }
463
464 for (int s = 0; s < numStages; ++s)
465 {
466 flushDenormals(z[s]);
467 sections_[static_cast<size_t>(s)].state[ch] = z[s];
468 }
469 }
470
471 // Two lanes of doubles in one register; on 32-bit x86 the eight vector
472 // registers do not hold a pair's cascade, so channels run one at a time.
473 static constexpr bool kPairChannels = simd::kVecDoubleNarrow == 2 && sizeof(void*) == 8;
474
476 template <int W>
477 void runPair(T* left, T* right, int numSamples, int chLeft, int chRight, int order) noexcept
478 {
479 if (order <= 1)
480 {
481 runOnePolePair<W>(left, right, numSamples, chLeft, chRight);
482 return;
483 }
484 switch (std::clamp(order / 2, 1, kMaxBiquadStages))
485 {
486 case 1: runCascadePair<W, 1>(left, right, numSamples, chLeft, chRight); break;
487 case 2: runCascadePair<W, 2>(left, right, numSamples, chLeft, chRight); break;
488 case 3: runCascadePair<W, 3>(left, right, numSamples, chLeft, chRight); break;
489 case 4: runCascadePair<W, 4>(left, right, numSamples, chLeft, chRight); break;
490 default: runCascadePair<W, 5>(left, right, numSamples, chLeft, chRight); break;
491 }
492 }
493
494 static double finiteOrZero(T x) noexcept { return std::isfinite(x) ? static_cast<double>(x) : 0.0; }
495
496 template <int W>
497 void runOnePolePair(T* left, T* right, int numSamples, int chLeft, int chRight) noexcept
498 {
499 using O = simd::Vec<double, W>;
500 auto& zl = onePole_[static_cast<size_t>(chLeft)];
501 auto& zr = onePole_[static_cast<size_t>(chRight)];
502 const auto r = O::set1(onePoleR_);
503 auto x1 = O::set2(zl.x1, zr.x1);
504 auto y1 = O::set2(zl.y1, zr.y1);
505 for (int i = 0; i < numSamples; ++i)
506 {
507 const auto x = O::set2(finiteOrZero(left[i]), finiteOrZero(right[i]));
508 y1 = O::add(O::sub(x, x1), O::mul(r, y1));
509 x1 = x;
510 left[i] = static_cast<T>(O::lane0(y1));
511 right[i] = static_cast<T>(O::lane1(y1));
512 }
513 zl = { O::lane0(x1), O::lane0(y1) };
514 zr = { O::lane1(x1), O::lane1(y1) };
515 flushDenormals(zl);
516 flushDenormals(zr);
517 }
518
519 template <int W, int S>
520 void runCascadePair(T* left, T* right, int numSamples, int chLeft, int chRight) noexcept
521 {
522 using O = simd::Vec<double, W>;
523 using V = typename O::V;
524 const auto cl = static_cast<size_t>(chLeft), cr = static_cast<size_t>(chRight);
525 V b0[S], a1[S], a2[S], x1[S], x2[S], y1[S], y2[S];
526 for (int s = 0; s < S; ++s)
527 {
528 const auto& sec = sections_[static_cast<size_t>(s)];
529 b0[s] = O::set1(sec.b0); a1[s] = O::set1(sec.a1); a2[s] = O::set1(sec.a2);
530 x1[s] = O::set2(sec.state[cl].x1, sec.state[cr].x1);
531 x2[s] = O::set2(sec.state[cl].x2, sec.state[cr].x2);
532 y1[s] = O::set2(sec.state[cl].y1, sec.state[cr].y1);
533 y2[s] = O::set2(sec.state[cl].y2, sec.state[cr].y2);
534 }
535 for (int i = 0; i < numSamples; ++i)
536 {
537 V v = O::set2(finiteOrZero(left[i]), finiteOrZero(right[i]));
538 for (int s = 0; s < S; ++s)
539 {
540 // stepSection() in each lane, operation for operation.
541 const V d = O::sub(O::sub(v, x1[s]), O::sub(x1[s], x2[s]));
542 const V y = O::sub(O::sub(O::mul(b0[s], d), O::mul(a1[s], y1[s])), O::mul(a2[s], y2[s]));
543 x2[s] = x1[s]; x1[s] = v;
544 y2[s] = y1[s]; y1[s] = y;
545 v = y;
546 }
547 left[i] = static_cast<T>(O::lane0(v));
548 right[i] = static_cast<T>(O::lane1(v));
549 }
550 for (int s = 0; s < S; ++s)
551 {
552 auto& sec = sections_[static_cast<size_t>(s)];
553 sec.state[cl] = { O::lane0(x1[s]), O::lane0(x2[s]), O::lane0(y1[s]), O::lane0(y2[s]) };
554 sec.state[cr] = { O::lane1(x1[s]), O::lane1(x2[s]), O::lane1(y1[s]), O::lane1(y2[s]) };
555 flushDenormals(sec.state[cl]);
556 flushDenormals(sec.state[cr]);
557 }
558 }
559
560 double sampleRate_ = 48000.0;
561 int numChannels_ = 2;
562 double onePoleR_ = 0.0;
563
564 std::atomic<int> order_ { 1 };
565 std::atomic<T> cutoffHz_ { T(5) };
566 T lastCutoff_ = T(-1);
567 int lastOrder_ = -1;
568
569 // Fixed-size per-channel state (scalar loops: no SIMD alignment needed).
570 std::array<OnePoleState, kMaxChannels> onePole_ {};
571 std::array<Section, kMaxBiquadStages> sections_ {};
572};
573
574} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
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
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
Definition DCBlocker.h:294
std::array< OnePoleState, kMaxChannels > onePole_
Definition DCBlocker.h:570
std::atomic< T > cutoffHz_
Definition DCBlocker.h:565
void runOnePole(T *data, int numSamples, int channel) noexcept
Definition DCBlocker.h:428
static constexpr int kMaxBiquadStages
Definition DCBlocker.h:93
DCBlocker() noexcept
Builds a filter coherent with the documented defaults (5 Hz @ 48 kHz).
Definition DCBlocker.h:97
void runCascadePair(T *left, T *right, int numSamples, int chLeft, int chRight) noexcept
Definition DCBlocker.h:520
~DCBlocker()=default
T processSample(int channel, T input) noexcept
Processes a single sample for a given channel.
Definition DCBlocker.h:262
void forceUpdateCoefficients(T explicitCutoff=T(0)) noexcept
Definition DCBlocker.h:328
void setCutoff(T hz) noexcept
Requests a cutoff frequency update.
Definition DCBlocker.h:170
static constexpr bool kPairChannels
Definition DCBlocker.h:473
void reset() noexcept
Clears the internal history states to zero.
Definition DCBlocker.h:285
std::atomic< int > order_
Definition DCBlocker.h:564
static void flushDenormals(OnePoleState &z) noexcept
Definition DCBlocker.h:416
void runOnePolePair(T *left, T *right, int numSamples, int chLeft, int chRight) noexcept
Definition DCBlocker.h:497
int getOrder() const noexcept
Returns the current filter order.
Definition DCBlocker.h:154
double onePoleR_
Derived from the documented defaults in the constructor.
Definition DCBlocker.h:562
void runCascade(T *data, int numSamples, int channel, int numStages) noexcept
Definition DCBlocker.h:440
void updateCoefficientsIfNeeded() noexcept
Definition DCBlocker.h:313
static void flushDenormals(SectionState &z) noexcept
Definition DCBlocker.h:422
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an AudioBufferView in-place.
Definition DCBlocker.h:190
void processBlock(int channel, T *data, int numSamples) noexcept
Processes a block of samples for one channel in-place.
Definition DCBlocker.h:228
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
Definition DCBlocker.h:303
static double stepSection(double b0, double a1, double a2, SectionState &z, double x) noexcept
Direct Form I with the numerator applied as a second difference.
Definition DCBlocker.h:392
static double finiteOrZero(T x) noexcept
Definition DCBlocker.h:494
std::array< Section, kMaxBiquadStages > sections_
Definition DCBlocker.h:571
void runPair(T *left, T *right, int numSamples, int chLeft, int chRight, int order) noexcept
Two channels through the filter in the lanes of one register (W = 2).
Definition DCBlocker.h:477
void prepare(const AudioSpec &spec)
Prepares from AudioSpec (unified API); keeps the configured cutoff.
Definition DCBlocker.h:128
static double stepOnePole(double r, OnePoleState &z, double x) noexcept
y[n] = (x[n] - x[n-1]) + R*y[n-1]; the difference zeroes DC exactly.
Definition DCBlocker.h:386
static constexpr int kMaxChannels
Definition DCBlocker.h:94
T getCutoff() const noexcept
Returns the requested cutoff frequency in Hz.
Definition DCBlocker.h:177
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
double dcBlockStep(double pole, DcBlockState &state, double input) noexcept
Applies (1 - z^-1) / (1 - pole * z^-1), with a pole in [0, 1).
Definition DcBlock.h:24
Main namespace for the DSPark framework.
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
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
static BiquadCoeffs makeHighPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
High-pass filter.
Definition Biquad.h:143
Second-order section: b0 * (1 - z^-1)^2 / (1 + a1 z^-1 + a2 z^-2).
Definition DCBlocker.h:380
Previous input and output of the one-pole DC blocker.
Definition DcBlock.h:18