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"
84template <
typename T,
int MaxChannels = 16>
133 for (
auto& ladder :
ladders_) ladder.reset();
135 if (
const std::uint64_t seed =
driftSeed_.load(std::memory_order_relaxed); seed != 0)
155 void setLowPass(
float freq,
float Q = 0.707f,
int slopeDb = 12)
348 std::memory_order_relaxed);
368 if (!std::isfinite(slope))
return;
369 shelfSlope_.store(std::clamp(slope, 0.0001f, 1.0f), std::memory_order_relaxed);
375 return shelfSlope_.load(std::memory_order_relaxed);
403 for (
int i = 0; i < c.numSecondOrder && i < 4; ++i) info.
qValues[i] = c.qValues[i];
424 newShape =
static_cast<Shape>(std::clamp(
static_cast<int>(newShape), 0,
449 if (!std::isfinite(freq))
return;
450 targetFreq_.store(freq, std::memory_order_relaxed);
465 if (!std::isfinite(Q))
return;
466 targetRes_.store(Q, std::memory_order_relaxed);
475 if (!std::isfinite(dB))
return;
486 if (!std::isfinite(amount))
return;
487 targetNonlinearity_.store(
static_cast<float>(std::clamp(amount, T(0), T(1))), std::memory_order_relaxed);
503 if (!std::isfinite(intensity))
return;
530 driftSeed_.store(seed, std::memory_order_relaxed);
538 return driftSeed_.load(std::memory_order_relaxed);
556 const int nCh = std::min(buffer.getNumChannels(), MaxChannels);
557 const int nS = buffer.getNumSamples();
562 for (
int ch = 0; ch < nCh; ++ch)
564 T* d = buffer.getChannel(ch);
565 for (
int i = 0; i < nS; ++i)
566 if (!std::isfinite(d[i])) d[i] = T(0);
570 const float rawFreq =
targetFreq_.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);
599 const bool dynamicPath = needSmoothing || drift || (nonLin > T(0));
614 f = std::clamp(f, 10.0f, nyquist);
615 q = std::max(q, 0.1f);
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);
623 const float ssl =
shelfSlope_.load(std::memory_order_relaxed);
639 for (
int ch = 0; ch < nCh; ++ch)
641 T* channelData = buffer.getChannel(ch);
642 for (
int i = 0; i < nS; ++i)
644 double sample =
static_cast<double>(channelData[i]);
645 for (
int s = 0; s < ns; ++s)
647 channelData[i] =
static_cast<T
>(sample);
673 for (
int j = 0; j < seg; ++j)
681 float freq = gliding ? std::exp2(logFreq) : rawFreq;
683 freq *= (1.0f + driftValue);
695 for (
int ch = 0; ch < nCh; ++ch)
696 avgAbs += std::abs(buffer.getChannel(ch)[i]);
697 avgAbs /=
static_cast<T
>(nCh);
699 const T bounded = avgAbs / (T(1) + avgAbs);
700 freq *=
static_cast<float>(T(1) + nonLin * T(2) * bounded);
708 for (
int s = 0; s < n; ++s)
728 std::array<double, kChunkSize> tmp;
729 for (
int ch = 0; ch < nCh; ++ch)
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)]);
737 for (
int s = 0; s < ns; ++s)
ladders_[s].advanceRamp(seg);
742 cascade_.processBlock(buffer.getSubView(i, seg));
753 for (
int s = 0; s < ns; ++s)
776 if (channel < 0 || channel >= MaxChannels)
return input;
777 double sample =
static_cast<double>(input);
781 for (
int s = 0; s < ns; ++s)
783 return static_cast<T
>(sample);
785 sample =
cascade_.processSample(sample, channel);
786 return static_cast<T
>(sample);
800 const float rawFreq =
targetFreq_.load(std::memory_order_relaxed);
813 f = std::clamp(f, 10.0f, nyquist);
814 q = std::max(q, 0.1f);
829 [[nodiscard]] std::vector<uint8_t>
getState()
const
832 w.
write(
"shape",
static_cast<int32_t
>(
shape_.load(std::memory_order_relaxed)));
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);
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 }
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];
926 int order = std::clamp(slopeDb / 6, 1,
kMaxOrder);
927 return (order + 1) / 2;
941 for (
int s = 0; s < n; ++s)
960 const Shape sh =
shape_.load(std::memory_order_relaxed);
961 const int sdb =
slopeDb_.load(std::memory_order_relaxed);
963 const bool sameTopology = n ==
numStages_.load(std::memory_order_relaxed)
967 for (
int s = 0; s < n; ++s)
980 std::array<BiquadCoeffs, kMaxStages>& out)
const noexcept
983 double f =
static_cast<double>(freq);
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));
994 if (cascade.hasFirstOrder)
1005 out[stageIdx++] = c;
1008 for (
int s = 0; s < cascade.numSecondOrder; ++s)
1010 float stageQ = cascade.qValues[s];
1016 s == cascade.numSecondOrder - 1)
1025 stageQ *= Q / 0.707f;
1060 out[stageIdx++] = c;
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.
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.
void setNonlinearity(T amount) noexcept
Sets the nonlinearity amount. Thread-safe.
int getSlopeDb() const noexcept
Returns the active slope in dB/oct (LP/HP only - others = 12).
std::atomic< float > targetGain_
float getShelfSlope() const noexcept
Returns the shelf slope S used by the shelf shapes.
void setHighShelf(float freq, float gainDb, float slope=1.0f)
Configures a high-shelf EQ filter.
static constexpr int kMaxOrder
std::atomic< bool > matchedFilters_
static constexpr int kChunkSize
Samples between coefficient designs in the dynamic path.
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
void setLowPass(float freq, float Q=0.707f, int slopeDb=12)
Configures a low-pass filter.
void setHighPass(float freq, float Q=0.707f, int slopeDb=12)
Configures a high-pass filter.
std::atomic< Shape > shape_
std::array< BiquadCoeffs, kMaxStages > rampTo_
static constexpr int kMaxStages
Smoothers::LinearSmoother resSmoother_
std::atomic< float > targetFreq_
std::atomic< std::uint64_t > driftSeed_
0 = the instance's unique seed.
Shape
Supported filter shapes.
Smoothers::LinearSmoother gainSmoother_
void setTilt(float centerFreq, float gainDb)
Configures a tilt EQ filter (boost highs/cut lows or vice versa).
void applyParametersNow() noexcept
Applies pending parameter targets immediately and rebuilds the coefficients (no smoothing: values jum...
void setAllPass(float freq, float Q=0.707f)
Configures an all-pass filter (shifts phase, flat frequency response).
std::atomic< float > shelfSlope_
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...
int activeStages() const noexcept
Stages in use; bounded here so every loop over them is seen to stay inside the stage arrays.
void setLowShelf(float freq, float gainDb, float slope=1.0f)
Configures a low-shelf EQ filter.
void setBandPass(float freq, float Q=0.707f)
Configures a band-pass filter (fixed 12 dB/oct).
std::atomic< bool > matchedPeak_
bool ladderActive_
The audio thread runs the ladders.
std::atomic< int > numStages_
Smoothers::HermiteSmoother freqSmoother_
int designCoefficients(float freq, float Q, float gainDb, std::array< BiquadCoeffs, kMaxStages > &out) const noexcept
Designs the cascade into out[]; returns the stage count.
void setMatchedFilters(bool enabled) noexcept
Selects the analog-matched designs for the other shapes.
static constexpr float kFreqGlideMs
Cutoff glide time (10-90% in 100 ms).
std::atomic< bool > driftEnabled_
std::atomic< float > targetNonlinearity_
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
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 ...
void setShelfSlope(float slope) noexcept
Sets the shelf slope S on its own (LowShelf/HighShelf shapes).
void reset() noexcept
Resets the internal state of all cascaded biquads and smoothers. Prevents clicks when relocating play...
unsigned chunkPhase_
Stream position in the 16-sample refresh grid.
void setGain(float dB) noexcept
Sets the target gain in dB. Thread-safe.
void updateCoefficients(float freq, float Q, float gainDb) noexcept
Designs and installs the coefficients at once (static path).
void setStructure(Structure structure) noexcept
Chooses how the sections are realised.
std::atomic< float > targetRes_
void syncLadders() noexcept
The ladders take the sections' coefficients at once (ends their ramps).
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an entire block of audio data. Internally branches into static, smoothed,...
bool isMatchedFilters() const noexcept
Returns whether the non-bell shapes use the matched designs.
std::atomic< float > driftIntensity_
void setFrequency(float freq) noexcept
Sets the target cutoff/center frequency. Thread-safe.
static ButterworthCascade computeCascade(int slopeDb) noexcept
void setResonance(float Q) noexcept
Sets the target resonance/Q. Thread-safe.
bool isMatchedPeak() const noexcept
Returns whether Peak bells use the matched (de-cramped) design.
Shape getShape() const noexcept
Returns the active filter shape.
void enableAnalogDrift(AnalogRandom::AnalogComponent component, float intensity=0.5f)
Enables analog-style low-frequency modulation of the cutoff.
AnalogRandom::Generator< float > driftGen_
float lastShelfSlope_
Shelf S: a slope-only change must rebuild coeffs.
std::uint64_t getDriftSeed() const noexcept
The drift seed set by setDriftSeed(); 0 when the drift uses the instance's own unique seed.
void prepare(const AudioSpec &spec)
Initializes the filter engine with the current audio specification.
void setPeaking(float freq, float gainDb, float Q=1.0f)
Configures a peaking / bell EQ filter.
bool snapNext_
Next block skips the smoothers to their targets.
T processSample(T input, int channel) noexcept
Processes a single sample without parameter smoothing or coefficient updates.
BiquadCascade< T, kMaxStages, MaxChannels > cascade_
The sections, run in one pass.
int rampPos_
Samples into the ramp; kChunkSize = settled on rampTo_.
std::atomic< Structure > structure_
Structure getStructure() const noexcept
void setNotch(float freq, float Q=10.0f)
Configures a notch (band-reject) filter.
std::atomic< int > slopeDb_
std::array< BiquadCoeffs, kMaxStages > stageCoeffs_
The coefficients in use (their record for the ramps and the ladders).
void setDriftSeed(std::uint64_t seed) noexcept
Makes the analog drift reproducible.
void setShape(Shape newShape, int slopeDb=12) noexcept
Switches the filter topology while keeping the current frequency, resonance, and gain unchanged.
void disableAnalogDrift() noexcept
Disables analog-style drift modulation. Thread-safe.
static int slopeToStages(int slopeDb) noexcept
std::array< NormalizedLadder< T, MaxChannels >, kMaxStages > ladders_
The sections as ladders (setStructure()).
Structure
How each second-order section is realised (see setStructure()).
@ 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.
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
bool isValid() const noexcept
uint32_t processorId() const noexcept
Serializes key/value parameters into a versioned blob.
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
void write(const char *key, float value)
Writes a float parameter.
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").
Describes the audio environment for a DSP processor.
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
double sampleRate
Sample rate in Hz.
Stores normalised biquad coefficients (b0, b1, b2, a1, a2), always double.
static BiquadCoeffs makeFirstOrderHighPass(double sampleRate, double frequency) noexcept
First-order (6 dB/oct) high-pass filter.
static BiquadCoeffs makePeakMatched(double sampleRate, double freq, double Q, double gainDb) noexcept
Analog-matched ("de-cramped") peaking filter (Vicanek design).
static BiquadCoeffs makeHighPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
High-pass filter.
static BiquadCoeffs makeHighShelfMatched(double sampleRate, double freq, double gainDb) noexcept
Analog-matched Butterworth high shelf (see makeLowShelfMatched()).
static BiquadCoeffs makeAllPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
All-pass filter.
static BiquadCoeffs makeBandPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Band-pass filter (constant 0 dB peak gain).
static BiquadCoeffs makeLowShelfMatched(double sampleRate, double freq, double gainDb) noexcept
Analog-matched Butterworth low shelf (Vicanek, "Matched Two-Pole Digital Shelving Filters",...
static BiquadCoeffs makePeak(double sampleRate, double freq, double Q, double gainDb) noexcept
Peak (parametric EQ) filter.
static BiquadCoeffs makeFirstOrderLowPass(double sampleRate, double frequency) noexcept
First-order (6 dB/oct) low-pass filter.
static BiquadCoeffs makeTilt(double sampleRate, double pivotFreq, double gainDb) noexcept
Creates a first-order tilt filter.
static BiquadCoeffs makeLowPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Low-pass filter.
static BiquadCoeffs makeBandPassMatched(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Analog-matched band-pass, 0 dB at the centre (Vicanek 2016).
static BiquadCoeffs makeLowShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
Low-shelf filter.
static BiquadCoeffs makeLowPassMatched(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Analog-matched second-order low-pass (Vicanek, "Matched Second Order Digital Filters",...
static BiquadCoeffs makeHighShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
High-shelf filter.
static BiquadCoeffs makeHighPassMatched(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Analog-matched second-order high-pass (Vicanek 2016).
static BiquadCoeffs makeNotch(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Notch (band-reject) filter.
float qValues[kMaxStages]
Per-stage Butterworth cascade layout for an LP/HP slope (for analysis).
Cubic glide that lands exactly on the target after a fixed time, with a continuous slope.
bool isSmoothing() const noexcept
void reset(double sampleRate, float rampTimeMilliseconds, float initialValue=0.0f) noexcept
float getNextValue() noexcept
void setTargetValue(float newTarget) noexcept
Linear ramp smoother for predictable, uniform interpolation.
void reset(double sampleRate, float rampTimeMilliseconds, float initialValue=0.0f) noexcept
float getNextValue() noexcept
void setTargetValue(float newTarget) noexcept
bool isSmoothing() const noexcept
float getCurrentValue() const noexcept