DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Filters.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
54#include "../Core/AudioBuffer.h"
55#include "../Core/AudioSpec.h"
56#include "../Core/Biquad.h"
57#include "../Core/BiquadCascade.h"
58#include "../Core/DspMath.h"
59#include "../Core/NormalizedLadder.h"
60#include "../Core/Smoothers.h"
61#include "../Core/AnalogRandom.h"
62#include "../Core/DenormalGuard.h"
63#include "../Core/StateBlob.h"
64
65#include <algorithm>
66#include <array>
67#include <atomic>
68#include <cmath>
69#include <cstdint>
70#include <vector>
71
72namespace dspark {
73
84template <typename T, int MaxChannels = 16>
86{
87public:
88 // Removed virtual destructor to avoid vptr overhead and maintain cache alignment.
89 ~FilterEngine() = default;
90
94 enum class Shape
95 {
98 };
99
100 // -- Lifecycle -----------------------------------------------------------
101
107 void prepare(const AudioSpec& spec)
108 {
109 if (!spec.isValid()) return;
110 spec_ = spec;
111 // The cutoff is smoothed as log2(Hz): equal steps per octave, along
112 // a monotonic cubic that arrives exactly after kFreqGlideMs.
113 freqSmoother_.reset(spec.sampleRate, kFreqGlideMs, std::log2(1000.0f));
114 resSmoother_.reset(spec.sampleRate, 20.0f, 0.707f);
115 gainSmoother_.reset(spec.sampleRate, 20.0f, 0.0f);
116 // Coefficients depend on the sample rate: force a rebuild on the next
117 // block. (Without this, re-preparing at a new rate with unchanged
118 // parameters kept the OLD rate's coefficients: the cutoff landed at
119 // freq * newRate / oldRate.)
120 lastFreq_ = -1.0f;
121 if (driftEnabled_.load(std::memory_order_relaxed))
122 driftGen_.prepare(spec.sampleRate); // re-sync the drift LFO clock
123 reset();
124 }
125
130 void reset() noexcept
131 {
132 cascade_.reset();
133 for (auto& ladder : ladders_) ladder.reset();
134 // A pinned drift restarts from its seed, so a reset render replays it.
135 if (const std::uint64_t seed = driftSeed_.load(std::memory_order_relaxed); seed != 0)
136 driftGen_.reseed(seed);
140 // The next block starts on its targets: no glide from stale values.
141 snapNext_ = true;
142 chunkPhase_ = 0;
144 rampSlopeDb_ = -1; // the first design after a reset installs at once
145 }
146
147 // -- Configuration -------------------------------------------------------
148
155 void setLowPass(float freq, float Q = 0.707f, int slopeDb = 12)
156 {
158 slopeDb_ = slopeDb;
159 numStages_ = slopeToStages(slopeDb);
160 setFrequency(freq);
161 setResonance(Q);
162 }
163
170 void setHighPass(float freq, float Q = 0.707f, int slopeDb = 12)
171 {
173 slopeDb_ = slopeDb;
174 numStages_ = slopeToStages(slopeDb);
175 setFrequency(freq);
176 setResonance(Q);
177 }
178
184 void setBandPass(float freq, float Q = 0.707f)
185 {
187 slopeDb_ = 12;
188 numStages_ = 1;
189 setFrequency(freq);
190 setResonance(Q);
191 }
192
199 void setPeaking(float freq, float gainDb, float Q = 1.0f)
200 {
202 slopeDb_ = 12;
203 numStages_ = 1;
204 setFrequency(freq);
205 setResonance(Q);
206 setGain(gainDb);
207 }
208
215 void setLowShelf(float freq, float gainDb, float slope = 1.0f)
216 {
218 slopeDb_ = 12;
219 numStages_ = 1;
220 setShelfSlope(slope);
221 setFrequency(freq);
222 setGain(gainDb);
223 }
224
231 void setHighShelf(float freq, float gainDb, float slope = 1.0f)
232 {
234 slopeDb_ = 12;
235 numStages_ = 1;
236 setShelfSlope(slope);
237 setFrequency(freq);
238 setGain(gainDb);
239 }
240
246 void setNotch(float freq, float Q = 10.0f)
247 {
249 slopeDb_ = 12;
250 numStages_ = 1;
251 setFrequency(freq);
252 setResonance(Q);
253 }
254
260 void setAllPass(float freq, float Q = 0.707f)
261 {
263 slopeDb_ = 12;
264 numStages_ = 1;
265 setFrequency(freq);
266 setResonance(Q);
267 }
268
274 void setTilt(float centerFreq, float gainDb)
275 {
277 slopeDb_ = 12;
278 numStages_ = 1;
279 setFrequency(centerFreq);
280 setGain(gainDb);
281 }
282
292 void setMatchedPeak(bool enabled) noexcept
293 {
294 matchedPeak_.store(enabled, std::memory_order_relaxed);
295 }
296
298 [[nodiscard]] bool isMatchedPeak() const noexcept
299 {
300 return matchedPeak_.load(std::memory_order_relaxed);
301 }
302
315 void setMatchedFilters(bool enabled) noexcept
316 {
317 matchedFilters_.store(enabled, std::memory_order_relaxed);
318 }
319
321 [[nodiscard]] bool isMatchedFilters() const noexcept
322 {
323 return matchedFilters_.load(std::memory_order_relaxed);
324 }
325
327 enum class Structure
328 {
329 DirectForm,
330 Ladder
331 };
332
345 void setStructure(Structure structure) noexcept
346 {
347 structure_.store(static_cast<Structure>(std::clamp(static_cast<int>(structure), 0, 1)),
348 std::memory_order_relaxed);
349 }
350
352 [[nodiscard]] Structure getStructure() const noexcept { return structure_.load(std::memory_order_relaxed); }
353
366 void setShelfSlope(float slope) noexcept
367 {
368 if (!std::isfinite(slope)) return;
369 shelfSlope_.store(std::clamp(slope, 0.0001f, 1.0f), std::memory_order_relaxed);
370 }
371
373 [[nodiscard]] float getShelfSlope() const noexcept
374 {
375 return shelfSlope_.load(std::memory_order_relaxed);
376 }
377
379 [[nodiscard]] Shape getShape() const noexcept { return shape_.load(std::memory_order_relaxed); }
380
382 [[nodiscard]] int getSlopeDb() const noexcept { return slopeDb_.load(std::memory_order_relaxed); }
383
385 struct CascadeInfo { bool hasFirstOrder = false; int numSecondOrder = 0; float qValues[4] = {}; };
386
397 [[nodiscard]] static CascadeInfo cascadeForSlope(int slopeDb, float userQ = 0.707f) noexcept
398 {
399 auto c = computeCascade(slopeDb);
400 CascadeInfo info;
401 info.hasFirstOrder = c.hasFirstOrder;
402 info.numSecondOrder = c.numSecondOrder;
403 for (int i = 0; i < c.numSecondOrder && i < 4; ++i) info.qValues[i] = c.qValues[i];
404 if (std::isfinite(userQ) && info.numSecondOrder > 0)
405 info.qValues[info.numSecondOrder - 1] *= userQ / 0.707f;
406 return info;
407 }
408
422 void setShape(Shape newShape, int slopeDb = 12) noexcept
423 {
424 newShape = static_cast<Shape>(std::clamp(static_cast<int>(newShape), 0,
425 static_cast<int>(Shape::Tilt)));
426 shape_ = newShape;
427 slopeDb_ = slopeDb;
428 switch (newShape)
429 {
430 case Shape::LowPass:
431 case Shape::HighPass:
432 numStages_ = slopeToStages(slopeDb);
433 break;
434 default:
435 slopeDb_ = 12;
436 numStages_ = 1;
437 break;
438 }
439 }
440
441 // -- Real-time parameter changes (Thread-safe) ---------------------------
442
447 void setFrequency(float freq) noexcept
448 {
449 if (!std::isfinite(freq)) return;
450 targetFreq_.store(freq, std::memory_order_relaxed);
451 }
452
463 void setResonance(float Q) noexcept
464 {
465 if (!std::isfinite(Q)) return;
466 targetRes_.store(Q, std::memory_order_relaxed);
467 }
468
473 void setGain(float dB) noexcept
474 {
475 if (!std::isfinite(dB)) return;
476 targetGain_.store(dB, std::memory_order_relaxed);
477 }
478
484 void setNonlinearity(T amount) noexcept
485 {
486 if (!std::isfinite(amount)) return;
487 targetNonlinearity_.store(static_cast<float>(std::clamp(amount, T(0), T(1))), std::memory_order_relaxed);
488 }
489
490 // -- Analog drift --------------------------------------------------------
491
501 void enableAnalogDrift(AnalogRandom::AnalogComponent component, float intensity = 0.5f)
502 {
503 if (!std::isfinite(intensity)) return;
504 driftIntensity_.store(intensity, std::memory_order_relaxed);
505 driftGen_.setAnalogDefault(component);
507 driftEnabled_.store(true, std::memory_order_release);
508 }
509
513 void disableAnalogDrift() noexcept { driftEnabled_.store(false, std::memory_order_relaxed); }
514
528 void setDriftSeed(std::uint64_t seed) noexcept
529 {
530 driftSeed_.store(seed, std::memory_order_relaxed);
531 if (seed != 0) driftGen_.reseed(seed);
532 }
533
536 [[nodiscard]] std::uint64_t getDriftSeed() const noexcept
537 {
538 return driftSeed_.load(std::memory_order_relaxed);
539 }
540
541 // -- Processing ----------------------------------------------------------
542
550 void processBlock(AudioBufferView<T> buffer) noexcept
551 {
552 // Before prepare() there is no rate to design for: pass through.
553 if (!(spec_.sampleRate > 0.0)) return;
554
555 DenormalGuard guard;
556 const int nCh = std::min(buffer.getNumChannels(), MaxChannels);
557 const int nS = buffer.getNumSamples();
558
559 // Front-door non-finite guard: the recursive biquad cascade latches
560 // a NaN/Inf input permanently. Scrub non-finite input to 0
561 // before the cascade. No-op on finite input (metrics byte-identical).
562 for (int ch = 0; ch < nCh; ++ch)
563 {
564 T* d = buffer.getChannel(ch);
565 for (int i = 0; i < nS; ++i)
566 if (!std::isfinite(d[i])) d[i] = T(0);
567 }
568
569 // Update smoothers with latest atomic targets
570 const float rawFreq = targetFreq_.load(std::memory_order_relaxed);
571 freqSmoother_.setTargetValue(std::log2(std::max(rawFreq, 1.0f)));
572 resSmoother_.setTargetValue(targetRes_.load(std::memory_order_relaxed));
573 gainSmoother_.setTargetValue(targetGain_.load(std::memory_order_relaxed));
574 if (snapNext_)
575 {
576 snapNext_ = false;
580 }
581 T nonLin = static_cast<T>(targetNonlinearity_.load(std::memory_order_relaxed));
582 const bool drift = driftEnabled_.load(std::memory_order_relaxed);
583 const float driftInt = driftIntensity_.load(std::memory_order_relaxed);
584
585 // A change of structure restarts the memory of the sections.
586 const bool ladder = structure_.load(std::memory_order_relaxed) == Structure::Ladder;
587 if (ladder != ladderActive_)
588 {
589 ladderActive_ = ladder;
590 cascade_.reset();
591 for (int s = 0; s < kMaxStages; ++s)
592 {
593 ladders_[s].reset();
594 ladders_[s].setCoeffs(stageCoeffs_[s]);
595 }
596 }
597
598 const bool needSmoothing = freqSmoother_.isSmoothing() || resSmoother_.isSmoothing() || gainSmoother_.isSmoothing();
599 const bool dynamicPath = needSmoothing || drift || (nonLin > T(0));
600
601
602 if (!dynamicPath)
603 {
604 // -- Fast Path: SIMD Friendly, Outer Channel Loop --
605 if (nS > 0)
606 {
607 // Settled: design from the exact target, not exp2(log2(f)),
608 // so static coefficients never move by a rounding step.
609 float f = rawFreq;
610 float q = resSmoother_.getCurrentValue();
611 float g = gainSmoother_.getCurrentValue();
612
613 float nyquist = static_cast<float>(spec_.sampleRate) * 0.499f;
614 f = std::clamp(f, 10.0f, nyquist);
615 q = std::max(q, 0.1f);
616
617 // Skip the trig-heavy coefficient rebuild when absolutely
618 // nothing changed since the last block (the common case).
619 const Shape sh = shape_.load(std::memory_order_relaxed);
620 const int sdb = slopeDb_.load(std::memory_order_relaxed);
621 const bool mp = matchedPeak_.load(std::memory_order_relaxed);
622 const bool mf = matchedFilters_.load(std::memory_order_relaxed);
623 const float ssl = shelfSlope_.load(std::memory_order_relaxed);
624 if (f != lastFreq_ || q != lastQ_ || g != lastGain_ ||
625 sh != lastShape_ || sdb != lastSlopeDb_ || mp != lastMatched_ ||
626 mf != lastMatchedFilters_ || ssl != lastShelfSlope_)
627 {
628 updateCoefficients(f, q, g);
629 if (ladder) syncLadders();
630 lastFreq_ = f; lastQ_ = q; lastGain_ = g;
631 lastShape_ = sh; lastSlopeDb_ = sdb; lastMatched_ = mp;
633 lastShelfSlope_ = ssl;
634 }
635
636 const int ns = activeStages();
637 if (ladder)
638 {
639 for (int ch = 0; ch < nCh; ++ch)
640 {
641 T* channelData = buffer.getChannel(ch);
642 for (int i = 0; i < nS; ++i)
643 {
644 double sample = static_cast<double>(channelData[i]);
645 for (int s = 0; s < ns; ++s)
646 sample = ladders_[s].processSample(sample, ch);
647 channelData[i] = static_cast<T>(sample);
648 }
649 }
650 return;
651 }
652 // One pass: every section on every channel together, the
653 // memory in double (re-quantising to T between sections would
654 // put back part of the error the double memory removes).
655 (void)ns;
656 cascade_.processBlock(buffer);
657 }
658 }
659 else
660 {
661 // -- Dynamic Path: Modulated / Smoothed (Chunked designs) --
662 // The coefficients are designed every kChunkSize samples (the
663 // trig stays out of the per-sample path) and ramp linearly
664 // between designs. The grid runs on a stream counter, so the
665 // design points (and the output) do not depend on the host's
666 // blocks. Audio runs segment by segment: a segment ends at the
667 // next design point, and each stage filters it with the ramping
668 // coefficients held in registers.
669 int i = 0;
670 while (i < nS)
671 {
672 const int seg = std::min(nS - i, kChunkSize - static_cast<int>(chunkPhase_));
673 for (int j = 0; j < seg; ++j)
674 {
675 const bool gliding = freqSmoother_.isSmoothing();
676 const float logFreq = freqSmoother_.getNextValue();
677 const float res = resSmoother_.getNextValue();
678 const float gain = gainSmoother_.getNextValue();
679 if (j == 0 && chunkPhase_ == 0)
680 {
681 float freq = gliding ? std::exp2(logFreq) : rawFreq;
682 float driftValue = drift ? (driftGen_.getNextSample() * driftInt) : 0.0f;
683 freq *= (1.0f + driftValue);
684
685 if (nonLin > T(0))
686 {
687 // Signal-dependent cutoff modulation ("dielectric"
688 // FM, chunk-rate). A bounded depth control:
689 // freq *= 1 + depth * 2 * g(level), g = x/(1+x) in [0,1)
690 // so depth -> 0 is exactly neutral and depth = 1
691 // sweeps up to one octave on loud material. (The
692 // previous |2-(x+n)/n| form DIVERGED as the knob
693 // approached 0.)
694 T avgAbs = T(0);
695 for (int ch = 0; ch < nCh; ++ch)
696 avgAbs += std::abs(buffer.getChannel(ch)[i]);
697 avgAbs /= static_cast<T>(nCh);
698
699 const T bounded = avgAbs / (T(1) + avgAbs);
700 freq *= static_cast<float>(T(1) + nonLin * T(2) * bounded);
701 }
702
703 float nyquist = static_cast<float>(spec_.sampleRate) * 0.499f;
704 startCoefficientRamp(std::clamp(freq, 10.0f, nyquist), std::max(res, 0.1f), gain);
705 if (ladder)
706 {
707 const int n = activeStages();
708 for (int s = 0; s < n; ++s)
709 {
710 if (rampPos_ == 0) ladders_[s].rampCoeffs(rampTo_[s], kChunkSize);
711 else ladders_[s].setCoeffs(rampTo_[s]);
712 }
713 }
714 lastFreq_ = -1.0f; // invalidate the static-path cache
715 }
716 else if (drift)
717 {
718 (void)driftGen_.getNextSample(); // Advance LFO phase to keep sync
719 }
720 }
721
722 // The segment, with the coefficients ramping linearly from
723 // one design to the next over the 16-sample grid.
724 const int ns = activeStages();
725 const bool ramping = rampPos_ < kChunkSize;
726 if (ladder)
727 {
728 std::array<double, kChunkSize> tmp;
729 for (int ch = 0; ch < nCh; ++ch)
730 {
731 T* d = buffer.getChannel(ch) + i;
732 for (int j = 0; j < seg; ++j) tmp[static_cast<size_t>(j)] = static_cast<double>(d[j]);
733 for (int s = 0; s < ns; ++s)
734 ladders_[s].processSegment(tmp.data(), seg, ch);
735 for (int j = 0; j < seg; ++j) d[j] = static_cast<T>(tmp[static_cast<size_t>(j)]);
736 }
737 for (int s = 0; s < ns; ++s) ladders_[s].advanceRamp(seg);
738 }
739 else
740 {
741 // One pass over the segment (the ramps advance inside).
742 cascade_.processBlock(buffer.getSubView(i, seg));
743 }
744
745 if (ramping)
746 {
747 rampPos_ += seg;
748 if (rampPos_ >= kChunkSize)
749 {
750 // Land exactly on the design (the ramp sum misses it
751 // by rounding).
753 for (int s = 0; s < ns; ++s)
754 stageCoeffs_[s] = rampTo_[s];
755 }
756 }
757 chunkPhase_ = (chunkPhase_ + static_cast<unsigned>(seg)) & (kChunkSize - 1);
758 i += seg;
759 }
760 }
761 }
762
774 T processSample(T input, int channel) noexcept
775 {
776 if (channel < 0 || channel >= MaxChannels) return input;
777 double sample = static_cast<double>(input);
778 const int ns = activeStages();
779 if (ladderActive_)
780 {
781 for (int s = 0; s < ns; ++s)
782 sample = ladders_[s].processSample(sample, channel);
783 return static_cast<T>(sample);
784 }
785 sample = cascade_.processSample(sample, channel);
786 return static_cast<T>(sample);
787 }
788
797 void applyParametersNow() noexcept
798 {
799 if (!(spec_.sampleRate > 0.0)) return; // nothing to design for yet
800 const float rawFreq = targetFreq_.load(std::memory_order_relaxed);
801 freqSmoother_.setTargetValue(std::log2(std::max(rawFreq, 1.0f)));
802 resSmoother_.setTargetValue(targetRes_.load(std::memory_order_relaxed));
803 gainSmoother_.setTargetValue(targetGain_.load(std::memory_order_relaxed));
807 snapNext_ = false;
808
809 float f = rawFreq;
810 float q = resSmoother_.getCurrentValue();
811 float g = gainSmoother_.getCurrentValue();
812 const float nyquist = static_cast<float>(spec_.sampleRate) * 0.499f;
813 f = std::clamp(f, 10.0f, nyquist);
814 q = std::max(q, 0.1f);
815
816 updateCoefficients(f, q, g);
817 ladderActive_ = structure_.load(std::memory_order_relaxed) == Structure::Ladder;
819 lastFreq_ = f; lastQ_ = q; lastGain_ = g;
820 lastShape_ = shape_.load(std::memory_order_relaxed);
821 lastSlopeDb_ = slopeDb_.load(std::memory_order_relaxed);
822 lastMatched_ = matchedPeak_.load(std::memory_order_relaxed);
823 lastMatchedFilters_ = matchedFilters_.load(std::memory_order_relaxed);
824 lastShelfSlope_ = shelfSlope_.load(std::memory_order_relaxed);
825 }
826
827
829 [[nodiscard]] std::vector<uint8_t> getState() const
830 {
831 StateWriter w(stateId("FENG"), 1);
832 w.write("shape", static_cast<int32_t>(shape_.load(std::memory_order_relaxed)));
833 w.write("slope", slopeDb_.load(std::memory_order_relaxed));
834 w.write("shelfSlope", shelfSlope_.load(std::memory_order_relaxed));
835 w.write("freq", targetFreq_.load(std::memory_order_relaxed));
836 w.write("res", targetRes_.load(std::memory_order_relaxed));
837 w.write("gain", targetGain_.load(std::memory_order_relaxed));
838 w.write("nonlin", static_cast<float>(targetNonlinearity_.load(std::memory_order_relaxed)));
839 w.write("structure", static_cast<int32_t>(getStructure()));
840 return w.blob();
841 }
842
844 bool setState(const uint8_t* data, size_t size)
845 {
846 StateReader r(data, size);
847 if (!r.isValid() || r.processorId() != stateId("FENG")) return false;
848 const auto shape = static_cast<Shape>(r.read("shape", 0));
849 const float freq = r.read("freq", 1000.0f);
850 const float res = r.read("res", 0.707f);
851 const float gain = r.read("gain", 0.0f);
852 switch (shape)
853 {
854 case Shape::LowShelf:
855 setLowShelf(freq, gain, r.read("shelfSlope", 1.0f));
856 break;
857 case Shape::HighShelf:
858 setHighShelf(freq, gain, r.read("shelfSlope", 1.0f));
859 break;
860 case Shape::Peak:
861 setPeaking(freq, gain, res);
862 break;
863 case Shape::Tilt:
864 setTilt(freq, gain);
865 break;
866 default:
867 setShape(shape, r.read("slope", 12));
868 setFrequency(freq);
869 setResonance(res);
870 setGain(gain);
871 break;
872 }
873 // Every parameter round-trips, whatever the shape (the shelf and
874 // tilt helpers above do not take the resonance).
875 setResonance(res);
876 setShelfSlope(r.read("shelfSlope", getShelfSlope()));
877 setStructure(static_cast<Structure>(r.read("structure", 0)));
878 setGain(gain);
879 setNonlinearity(static_cast<T>(r.read("nonlin", 0.0f)));
880 return true;
881 }
882
883protected:
884 static constexpr int kMaxStages = 4;
885 static constexpr int kChunkSize = 16;
886 static constexpr int kMaxOrder = 8;
887
889 [[nodiscard]] int activeStages() const noexcept
890 {
891 return std::min(numStages_.load(std::memory_order_relaxed), kMaxStages);
892 }
893
895 {
896 int order = 0;
897 bool hasFirstOrder = false;
899 float qValues[kMaxStages] {};
900 };
901
902 static ButterworthCascade computeCascade(int slopeDb) noexcept
903 {
904 static constexpr float qTable[kMaxOrder + 1][kMaxStages] = {
905 {}, {},
906 { 0.7071f },
907 { 1.0f },
908 { 0.5412f, 1.3066f },
909 { 0.6180f, 1.6180f },
910 { 0.5176f, 0.7071f, 1.9319f },
911 { 0.5549f, 0.8019f, 2.2470f },
912 { 0.5098f, 0.6013f, 0.9000f, 2.5628f }
913 };
914
915 ButterworthCascade result {};
916 result.order = std::clamp(slopeDb / 6, 1, kMaxOrder);
917 result.hasFirstOrder = (result.order % 2 != 0);
918 result.numSecondOrder = result.order / 2;
919 for (int i = 0; i < result.numSecondOrder; ++i)
920 result.qValues[i] = qTable[result.order][i];
921 return result;
922 }
923
924 static int slopeToStages(int slopeDb) noexcept
925 {
926 int order = std::clamp(slopeDb / 6, 1, kMaxOrder);
927 return (order + 1) / 2;
928 }
929
931 void syncLadders() noexcept
932 {
933 const int n = activeStages();
934 for (int s = 0; s < n; ++s) ladders_[s].setCoeffs(stageCoeffs_[s]);
935 }
936
938 void updateCoefficients(float freq, float Q, float gainDb) noexcept
939 {
940 const int n = designCoefficients(freq, Q, gainDb, rampTo_);
941 for (int s = 0; s < n; ++s)
942 {
943 stageCoeffs_[s] = rampTo_[s];
944 cascade_.setCoeffs(s, rampTo_[s]);
945 }
946 cascade_.setNumSections(n);
947 numStages_ = n;
948 rampPos_ = kChunkSize; // a ramp in flight ends on this exact design
949 }
950
958 void startCoefficientRamp(float freq, float Q, float gainDb) noexcept
959 {
960 const Shape sh = shape_.load(std::memory_order_relaxed);
961 const int sdb = slopeDb_.load(std::memory_order_relaxed);
962 const int n = designCoefficients(freq, Q, gainDb, rampTo_);
963 const bool sameTopology = n == numStages_.load(std::memory_order_relaxed)
964 && sh == rampShape_ && sdb == rampSlopeDb_;
965 rampShape_ = sh;
966 rampSlopeDb_ = sdb;
967 for (int s = 0; s < n; ++s)
968 {
969 if (!sameTopology) stageCoeffs_[s] = rampTo_[s];
970 if (sameTopology) cascade_.rampCoeffs(s, rampTo_[s], kChunkSize);
971 else cascade_.setCoeffs(s, rampTo_[s]);
972 }
973 cascade_.setNumSections(n);
974 numStages_ = n;
975 rampPos_ = sameTopology ? 0 : kChunkSize;
976 }
977
979 int designCoefficients(float freq, float Q, float gainDb,
980 std::array<BiquadCoeffs, kMaxStages>& out) const noexcept
981 {
982 double sr = spec_.sampleRate;
983 double f = static_cast<double>(freq);
984
985 // Snapshot atomic topology once.
986 const Shape sh = shape_.load(std::memory_order_relaxed);
987 const int sdb = slopeDb_.load(std::memory_order_relaxed);
988 const double ssl = static_cast<double>(shelfSlope_.load(std::memory_order_relaxed));
989
990 const bool mf = matchedFilters_.load(std::memory_order_relaxed);
991 auto cascade = computeCascade(sdb);
992 int stageIdx = 0;
993
994 if (cascade.hasFirstOrder)
995 {
996 BiquadCoeffs c;
997 switch (sh)
998 {
1001 default: c = BiquadCoeffs::makeFirstOrderLowPass(sr, f); break;
1002 }
1003 // The audio thread installs these with the direct write, not
1004 // the control-thread seqlock (docs/threading.md, origin rule).
1005 out[stageIdx++] = c;
1006 }
1007
1008 for (int s = 0; s < cascade.numSecondOrder; ++s)
1009 {
1010 float stageQ = cascade.qValues[s];
1011
1012 if (sh == Shape::Peak || sh == Shape::BandPass ||
1013 sh == Shape::Notch || sh == Shape::AllPass)
1014 stageQ = Q;
1015 else if ((sh == Shape::LowPass || sh == Shape::HighPass) &&
1016 s == cascade.numSecondOrder - 1)
1017 {
1018 // The user Q scales the FINAL (most resonant) stage of the
1019 // Butterworth cascade: at the 0.707 default the ratio is
1020 // exactly 1 (bit-identical Butterworth), larger values add the
1021 // classic resonant peak at the cutoff. Before this, the table
1022 // silently overrode the user Q for every LP/HP slope, so
1023 // setLowPass(f, 5.0f) sounded identical to Butterworth and
1024 // setResonance() was dead for LP/HP.
1025 stageQ *= Q / 0.707f;
1026 }
1027
1028 BiquadCoeffs c;
1029 switch (sh)
1030 {
1031 case Shape::LowPass:
1032 c = mf ? BiquadCoeffs::makeLowPassMatched(sr, f, stageQ)
1033 : BiquadCoeffs::makeLowPass(sr, f, stageQ);
1034 break;
1035 case Shape::HighPass:
1036 c = mf ? BiquadCoeffs::makeHighPassMatched(sr, f, stageQ)
1037 : BiquadCoeffs::makeHighPass(sr, f, stageQ);
1038 break;
1039 case Shape::BandPass:
1040 c = mf ? BiquadCoeffs::makeBandPassMatched(sr, f, stageQ)
1041 : BiquadCoeffs::makeBandPass(sr, f, stageQ);
1042 break;
1043 case Shape::Peak:
1044 c = matchedPeak_.load(std::memory_order_relaxed)
1045 ? BiquadCoeffs::makePeakMatched(sr, f, stageQ, gainDb)
1046 : BiquadCoeffs::makePeak(sr, f, stageQ, gainDb);
1047 break;
1048 case Shape::LowShelf:
1049 c = (mf && ssl >= 1.0) ? BiquadCoeffs::makeLowShelfMatched(sr, f, gainDb)
1050 : BiquadCoeffs::makeLowShelf(sr, f, gainDb, ssl);
1051 break;
1052 case Shape::HighShelf:
1053 c = (mf && ssl >= 1.0) ? BiquadCoeffs::makeHighShelfMatched(sr, f, gainDb)
1054 : BiquadCoeffs::makeHighShelf(sr, f, gainDb, ssl);
1055 break;
1056 case Shape::Notch: c = BiquadCoeffs::makeNotch(sr, f, stageQ); break;
1057 case Shape::AllPass: c = BiquadCoeffs::makeAllPass(sr, f, stageQ); break;
1058 case Shape::Tilt: c = BiquadCoeffs::makeTilt(sr, f, gainDb); break;
1059 }
1060 out[stageIdx++] = c;
1061 }
1062
1063 return stageIdx;
1064 }
1065
1067 // Topology state is atomic: setLowPass()/setShape()/... may be called from a
1068 // control thread while processBlock() reads these on the audio thread.
1069 // (Reads happen once per block, so atomics impose no hot-path cost.)
1070 std::atomic<Shape> shape_ { Shape::LowPass };
1071 std::atomic<int> numStages_ { 1 };
1072 std::atomic<int> slopeDb_ { 12 };
1073 std::atomic<float> shelfSlope_ { 1.0f };
1074 std::atomic<bool> matchedPeak_ { false };
1075 std::atomic<bool> matchedFilters_ { false };
1076
1077 std::array<BiquadCoeffs, kMaxStages> stageCoeffs_ {};
1079 std::array<NormalizedLadder<T, MaxChannels>, kMaxStages> ladders_ {};
1080 std::atomic<Structure> structure_ { Structure::DirectForm };
1081 bool ladderActive_ = false;
1082
1083 static constexpr float kFreqGlideMs = 165.0f;
1086
1087 // Atomics for thread-safe UI->Audio communication
1088 std::atomic<float> targetFreq_{1000.0f};
1089 std::atomic<float> targetRes_{0.707f};
1090 std::atomic<float> targetGain_{0.0f};
1091 std::atomic<float> targetNonlinearity_{0.0f};
1092
1093 // Atomic: enable/disable may come from a control thread while the audio
1094 // thread reads them each block (the generator itself is only reconfigured
1095 // from the setup thread, as enableAnalogDrift documents).
1096 std::atomic<bool> driftEnabled_ { false };
1097 std::atomic<float> driftIntensity_ { 0.0f };
1098 std::atomic<std::uint64_t> driftSeed_ { 0 };
1100
1101 // Static-path coefficient cache (skip rebuilds when nothing changed).
1102 float lastFreq_ = -1.0f;
1103 float lastQ_ = -1.0f;
1104 float lastGain_ = -1e9f;
1107 bool lastMatched_ = false;
1109 float lastShelfSlope_ = -1.0f;
1110 bool snapNext_ = true;
1111 unsigned chunkPhase_ = 0;
1112
1113 // Per-sample coefficient ramp between chunk designs (audio thread).
1114 std::array<BiquadCoeffs, kMaxStages> rampTo_ {};
1118};
1119
1120} // namespace dspark
Main generator class for analog-style random modulation.
void reseed(std::uint64_t newSeed) noexcept
Request a lock-free reseed of the internal PRNG.
void prepare(double sampleRate) noexcept
Prepare the generator with the audio sample rate.
void setAnalogDefault(AnalogComponent component) noexcept
Real getNextSample() noexcept
Generate and return the next modulation sample.
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Up to MaxSections second-order sections in series, run in one pass.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Professional multi-mode filter with cascaded biquad stages.
Definition Filters.h:86
void setNonlinearity(T amount) noexcept
Sets the nonlinearity amount. Thread-safe.
Definition Filters.h:484
int getSlopeDb() const noexcept
Returns the active slope in dB/oct (LP/HP only - others = 12).
Definition Filters.h:382
std::atomic< float > targetGain_
Definition Filters.h:1090
float getShelfSlope() const noexcept
Returns the shelf slope S used by the shelf shapes.
Definition Filters.h:373
void setHighShelf(float freq, float gainDb, float slope=1.0f)
Configures a high-shelf EQ filter.
Definition Filters.h:231
static constexpr int kMaxOrder
Definition Filters.h:886
std::atomic< bool > matchedFilters_
Definition Filters.h:1075
static constexpr int kChunkSize
Samples between coefficient designs in the dynamic path.
Definition Filters.h:885
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
Definition Filters.h:829
void setLowPass(float freq, float Q=0.707f, int slopeDb=12)
Configures a low-pass filter.
Definition Filters.h:155
void setHighPass(float freq, float Q=0.707f, int slopeDb=12)
Configures a high-pass filter.
Definition Filters.h:170
std::atomic< Shape > shape_
Definition Filters.h:1070
std::array< BiquadCoeffs, kMaxStages > rampTo_
Definition Filters.h:1114
static constexpr int kMaxStages
Definition Filters.h:884
Smoothers::LinearSmoother resSmoother_
Definition Filters.h:1085
std::atomic< float > targetFreq_
Definition Filters.h:1088
std::atomic< std::uint64_t > driftSeed_
0 = the instance's unique seed.
Definition Filters.h:1098
Shape
Supported filter shapes.
Definition Filters.h:95
Smoothers::LinearSmoother gainSmoother_
Definition Filters.h:1085
void setTilt(float centerFreq, float gainDb)
Configures a tilt EQ filter (boost highs/cut lows or vice versa).
Definition Filters.h:274
void applyParametersNow() noexcept
Applies pending parameter targets immediately and rebuilds the coefficients (no smoothing: values jum...
Definition Filters.h:797
void setAllPass(float freq, float Q=0.707f)
Configures an all-pass filter (shifts phase, flat frequency response).
Definition Filters.h:260
std::atomic< float > shelfSlope_
Definition Filters.h:1073
static CascadeInfo cascadeForSlope(int slopeDb, float userQ=0.707f) noexcept
Returns the exact Butterworth cascade (first-order flag + per-stage Q values) used internally for a g...
Definition Filters.h:397
int activeStages() const noexcept
Stages in use; bounded here so every loop over them is seen to stay inside the stage arrays.
Definition Filters.h:889
void setLowShelf(float freq, float gainDb, float slope=1.0f)
Configures a low-shelf EQ filter.
Definition Filters.h:215
void setBandPass(float freq, float Q=0.707f)
Configures a band-pass filter (fixed 12 dB/oct).
Definition Filters.h:184
std::atomic< bool > matchedPeak_
Definition Filters.h:1074
bool ladderActive_
The audio thread runs the ladders.
Definition Filters.h:1081
std::atomic< int > numStages_
Definition Filters.h:1071
Smoothers::HermiteSmoother freqSmoother_
Definition Filters.h:1084
int designCoefficients(float freq, float Q, float gainDb, std::array< BiquadCoeffs, kMaxStages > &out) const noexcept
Designs the cascade into out[]; returns the stage count.
Definition Filters.h:979
void setMatchedFilters(bool enabled) noexcept
Selects the analog-matched designs for the other shapes.
Definition Filters.h:315
static constexpr float kFreqGlideMs
Cutoff glide time (10-90% in 100 ms).
Definition Filters.h:1083
std::atomic< bool > driftEnabled_
Definition Filters.h:1096
std::atomic< float > targetNonlinearity_
Definition Filters.h:1091
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
Definition Filters.h:844
void startCoefficientRamp(float freq, float Q, float gainDb) noexcept
Designs the coefficients of a chunk refresh and starts the ramp from the active coefficients towards ...
Definition Filters.h:958
void setShelfSlope(float slope) noexcept
Sets the shelf slope S on its own (LowShelf/HighShelf shapes).
Definition Filters.h:366
void reset() noexcept
Resets the internal state of all cascaded biquads and smoothers. Prevents clicks when relocating play...
Definition Filters.h:130
unsigned chunkPhase_
Stream position in the 16-sample refresh grid.
Definition Filters.h:1111
void setGain(float dB) noexcept
Sets the target gain in dB. Thread-safe.
Definition Filters.h:473
void updateCoefficients(float freq, float Q, float gainDb) noexcept
Designs and installs the coefficients at once (static path).
Definition Filters.h:938
void setStructure(Structure structure) noexcept
Chooses how the sections are realised.
Definition Filters.h:345
std::atomic< float > targetRes_
Definition Filters.h:1089
void syncLadders() noexcept
The ladders take the sections' coefficients at once (ends their ramps).
Definition Filters.h:931
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an entire block of audio data. Internally branches into static, smoothed,...
Definition Filters.h:550
bool isMatchedFilters() const noexcept
Returns whether the non-bell shapes use the matched designs.
Definition Filters.h:321
std::atomic< float > driftIntensity_
Definition Filters.h:1097
void setFrequency(float freq) noexcept
Sets the target cutoff/center frequency. Thread-safe.
Definition Filters.h:447
static ButterworthCascade computeCascade(int slopeDb) noexcept
Definition Filters.h:902
void setResonance(float Q) noexcept
Sets the target resonance/Q. Thread-safe.
Definition Filters.h:463
bool isMatchedPeak() const noexcept
Returns whether Peak bells use the matched (de-cramped) design.
Definition Filters.h:298
Shape getShape() const noexcept
Returns the active filter shape.
Definition Filters.h:379
void enableAnalogDrift(AnalogRandom::AnalogComponent component, float intensity=0.5f)
Enables analog-style low-frequency modulation of the cutoff.
Definition Filters.h:501
AnalogRandom::Generator< float > driftGen_
Definition Filters.h:1099
float lastShelfSlope_
Shelf S: a slope-only change must rebuild coeffs.
Definition Filters.h:1109
std::uint64_t getDriftSeed() const noexcept
The drift seed set by setDriftSeed(); 0 when the drift uses the instance's own unique seed.
Definition Filters.h:536
void prepare(const AudioSpec &spec)
Initializes the filter engine with the current audio specification.
Definition Filters.h:107
void setPeaking(float freq, float gainDb, float Q=1.0f)
Configures a peaking / bell EQ filter.
Definition Filters.h:199
bool snapNext_
Next block skips the smoothers to their targets.
Definition Filters.h:1110
T processSample(T input, int channel) noexcept
Processes a single sample without parameter smoothing or coefficient updates.
Definition Filters.h:774
BiquadCascade< T, kMaxStages, MaxChannels > cascade_
The sections, run in one pass.
Definition Filters.h:1078
int rampPos_
Samples into the ramp; kChunkSize = settled on rampTo_.
Definition Filters.h:1115
std::atomic< Structure > structure_
Definition Filters.h:1080
Structure getStructure() const noexcept
Definition Filters.h:352
void setNotch(float freq, float Q=10.0f)
Configures a notch (band-reject) filter.
Definition Filters.h:246
std::atomic< int > slopeDb_
Definition Filters.h:1072
std::array< BiquadCoeffs, kMaxStages > stageCoeffs_
The coefficients in use (their record for the ramps and the ladders).
Definition Filters.h:1077
void setDriftSeed(std::uint64_t seed) noexcept
Makes the analog drift reproducible.
Definition Filters.h:528
void setShape(Shape newShape, int slopeDb=12) noexcept
Switches the filter topology while keeping the current frequency, resonance, and gain unchanged.
Definition Filters.h:422
void disableAnalogDrift() noexcept
Disables analog-style drift modulation. Thread-safe.
Definition Filters.h:513
static int slopeToStages(int slopeDb) noexcept
Definition Filters.h:924
std::array< NormalizedLadder< T, MaxChannels >, kMaxStages > ladders_
The sections as ladders (setStructure()).
Definition Filters.h:1079
Structure
How each second-order section is realised (see setStructure()).
Definition Filters.h:328
@ Ladder
Normalized ladder: passive under any change of its coefficients.
@ DirectForm
Direct form with a double memory: the cheapest (default).
void setMatchedPeak(bool enabled) noexcept
Selects the analog-matched (de-cramped) design for Peak bells.
Definition Filters.h:292
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
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
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
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
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 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 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
Per-stage Butterworth cascade layout for an LP/HP slope (for analysis).
Definition Filters.h:385
Cubic glide that lands exactly on the target after a fixed time, with a continuous slope.
Definition Smoothers.h:354
bool isSmoothing() const noexcept
Definition Smoothers.h:362
void reset(double sampleRate, float rampTimeMilliseconds, float initialValue=0.0f) noexcept
Definition Smoothers.h:840
void setTargetValue(float newTarget) noexcept
Definition Smoothers.h:851
Linear ramp smoother for predictable, uniform interpolation.
Definition Smoothers.h:60
void reset(double sampleRate, float rampTimeMilliseconds, float initialValue=0.0f) noexcept
Definition Smoothers.h:383
void setTargetValue(float newTarget) noexcept
Definition Smoothers.h:392
bool isSmoothing() const noexcept
Definition Smoothers.h:420
float getCurrentValue() const noexcept
Definition Smoothers.h:68