57#include "../Core/DspMath.h"
58#include "../Core/AudioSpec.h"
59#include "../Core/AudioBuffer.h"
60#include "../Core/DenormalGuard.h"
61#include "../Core/KeyEqualizer.h"
62#include "../Core/RingBuffer.h"
63#include "../Core/StateBlob.h"
115 void prepare(
double sampleRate,
int numChannels = 2) noexcept
117 if (!(sampleRate > 0.0) || !std::isfinite(sampleRate))
return;
149 const int nCh = buffer.getNumChannels();
150 const int nS = buffer.getNumSamples();
151 if (nCh <= 0 || nS <= 0)
return;
158 for (
int i = 0; i < nS; ++i)
167 level =
placedKeyFrame([&](
int ch)
noexcept {
return buffer.getChannel(ch)[i]; }, det0);
169 for (
int ch = 0; ch < nCh; ++ch)
177 heard_[
static_cast<size_t>(ch)] = s;
179 if (ch == 0) det0 = s;
180 level = std::max(level, std::abs(s));
193 for (
int ch = 0; ch < nCh; ++ch)
195 T* d = buffer.getChannel(ch);
221 if (sidechain.getNumChannels() <= 0 || sidechain.getNumSamples() < audio.getNumSamples())
230 const int nCh = audio.getNumChannels();
231 const int nS = audio.getNumSamples();
232 const int scCh = sidechain.getNumChannels();
233 if (nCh <= 0 || nS <= 0)
return;
238 if (nCh == 1 && scCh == 1)
240 T* __restrict outL = audio.getChannel(0);
241 const T* __restrict scL = sidechain.getChannel(0);
242 for (
int i = 0; i < nS; ++i)
250 for (
int i = 0; i < nS; ++i)
255 scMax =
placedKeyFrame([&](
int c)
noexcept {
return sidechain.getChannel(c)[i]; }, det0);
257 for (
int c = 0; c < scCh; ++c)
265 heard_[
static_cast<size_t>(c)] = s;
267 if (c == 0) det0 = s;
269 if (a > scMax) scMax = a;
280 for (
int ch = 0; ch < nCh; ++ch)
282 T* d = audio.getChannel(ch);
302 if (!std::isfinite(dB))
return;
303 threshold_.store(dB, std::memory_order_relaxed);
338 if (!std::isfinite(dB))
return;
339 hysteresis_.store(std::max(T(0), dB), std::memory_order_relaxed);
346 if (!std::isfinite(ms))
return;
347 attackMs_.store(std::max(T(0.01), ms), std::memory_order_relaxed);
354 if (!std::isfinite(ms))
return;
355 holdMs_.store(std::max(T(0), ms), std::memory_order_relaxed);
362 if (!std::isfinite(ms))
return;
363 releaseMs_.store(std::max(T(0.01), ms), std::memory_order_relaxed);
373 if (!std::isfinite(dB))
return;
374 rangeDb_.store(std::min(T(0), dB), std::memory_order_relaxed);
381 duckMode_.store(enabled, std::memory_order_relaxed);
388 const int m = std::clamp(
static_cast<int>(mode), 0,
static_cast<int>(
GateMode::Frequency));
406 if (!std::isfinite(ms))
return;
440 if (std::isfinite(cutoffHz) && cutoffHz > 0.0)
441 scHpfFreq_.store(
static_cast<T
>(cutoffHz), std::memory_order_relaxed);
558 [[nodiscard]] std::vector<uint8_t>
getState()
const
561 w.
write(
"threshold",
static_cast<float>(
threshold_.load(std::memory_order_relaxed)));
562 w.
write(
"hysteresis",
static_cast<float>(
hysteresis_.load(std::memory_order_relaxed)));
563 w.
write(
"attack",
static_cast<float>(
attackMs_.load(std::memory_order_relaxed)));
564 w.
write(
"hold",
static_cast<float>(
holdMs_.load(std::memory_order_relaxed)));
565 w.
write(
"release",
static_cast<float>(
releaseMs_.load(std::memory_order_relaxed)));
566 w.
write(
"range",
static_cast<float>(
rangeDb_.load(std::memory_order_relaxed)));
568 w.
write(
"gateMode",
static_cast<int32_t
>(
gateMode_.load(std::memory_order_relaxed)));
571 w.
write(
"scHpfFreq",
static_cast<float>(
scHpfFreq_.load(std::memory_order_relaxed)));
572 w.
write(
"lookahead",
static_cast<float>(
lookaheadMs_.load(std::memory_order_relaxed)));
593 static_cast<double>(r.
read(
"scHpfFreq", 80.0f)));
608 &&
paramsDirty_.exchange(
false, std::memory_order_acquire))
618 if (!(fs > T(0)))
return;
632 T thDb =
threshold_.load(std::memory_order_relaxed);
633 T hystDb =
hysteresis_.load(std::memory_order_relaxed);
638 T attMs = std::max(
attackMs_.load(std::memory_order_relaxed), T(0.01));
639 T relMs = std::max(
releaseMs_.load(std::memory_order_relaxed), T(0.01));
640 attackCoeff_ = T(1) - std::exp(T(-1) / (fs * attMs / T(1000)));
641 releaseCoeff_ = T(1) - std::exp(T(-1) / (fs * relMs / T(1000)));
651 T hMs = std::max(
holdMs_.load(std::memory_order_relaxed), T(0));
652 holdSamples_ =
static_cast<int>(std::min(fs *
static_cast<double>(hMs) / 1000.0, 1.0e9));
656 const double scFreq = std::clamp(
657 static_cast<double>(
scHpfFreq_.load(std::memory_order_relaxed)),
659 scHpfCoeff_ =
static_cast<T
>(std::exp(-std::numbers::pi * 2.0 * scFreq /
static_cast<double>(fs)));
671 const double samples = std::round(
static_cast<double>(ms) *
sampleRate_ / 1000.0);
677 [[nodiscard]]
inline T
delayed(T x,
int ch)
noexcept
680 auto& line =
lookahead_[
static_cast<size_t>(ch)];
707 const double level =
static_cast<double>(envelopeLinear);
708 const bool quiet = level < static_cast<double>(closeAt) *
autoRef_;
711 closeAt *=
static_cast<T
>(
autoRef_);
713 bool above = envelopeLinear > openAt;
714 bool below = envelopeLinear < closeAt;
717 std::swap(above, below);
754 bool sign = sample >= T(0);
788 if (!std::isfinite(input))
return input;
792 T targetHp = T(20) + (
cachedNyquist_ * T(0.4)) * (T(1) - gateOpenness);
821 [[nodiscard]]
static T
detectorSafe(T x)
noexcept {
return std::isfinite(x) ? x : T(0); }
831 template <
typename Sample>
834 for (
int ch = 0; ch < 2; ++ch)
838 heard_[
static_cast<size_t>(ch)] = s;
842 return std::max(std::abs(
heard_[0]), std::abs(
heard_[1]));
857 T rawLevel = std::abs(sidechain);
873 return listen_ ? sidechain : shaped;
877 return listen_ ? sidechain : gated;
Non-owning view over audio channel data.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
void writeState(StateWriter &w, const char *prefix) const
Writes the bands under keys that start with a prefix ("<prefix><band>.shape", ".freq",...
bool sync() noexcept
Takes the settings published since the last call.
void processFrame(T *frame, int channels) noexcept
One frame of the key, every channel of it, in place.
Placement
The part of a two-channel key a band acts on (see processFrame()).
void advance(int samples) noexcept
Moves the equalizer on in time: the coefficients between two designs, the bands on the move to their ...
void reset() noexcept
Clears the memory of the filters (settings and glides are kept).
Response getResponse(Placement part=Placement::Stereo) const noexcept
The sections of the published bands, designed as the audio thread designs them, for a display.
void readState(const StateReader &r, const char *prefix) noexcept
Reads the bands writeState() wrote (a band that is missing reads as Off, a placement that is missing ...
Shape
What a band does to the key.
Band getBand(int band) const noexcept
The published settings of a band (a band out of range reads as Off).
void setBand(int band, const Band &settings) noexcept
Publishes the settings of a band.
T processSample(T input, int channel) noexcept
One sample of one channel of the key through the equalizer.
bool isPlaced() const noexcept
Whether a band in the path is placed on the middle or on the sides: only processFrame() gives those t...
void prepare(double sampleRate) noexcept
Prepares the equalizer for a sample rate and clears its memory.
The key of a dynamics processor as it is listened to: late by the processor's latency and held under ...
void processFrame(T *frame, int channels, int delay) noexcept
One frame: the key of every channel goes in and comes out late and under the ceiling.
void prepare(double sampleRate, int maxDelaySamples) noexcept
Sets the rate and the longest delay (allocates).
void reset() noexcept
Clears the delay and lets the gain go.
High-performance noise gate with state machine, hysteresis, and zero-allocation processing.
T getLookahead() const noexcept
Returns the lookahead in milliseconds.
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an AudioBufferView in-place.
int getLatency() const noexcept
Latency in samples (the lookahead), correct right after setLookahead().
void prepare(double sampleRate, int numChannels=2) noexcept
Prepares the noise gate for processing.
std::array< T, kMaxScChannels > scHpfPrev_
static constexpr double kAutoRefFloor
The reference never goes under -100 dBFS.
std::array< T, kMaxChannels > freqLpState_
KeyEq keyEq_
Equalizer of the key, after the high-pass.
T applyFrequencyGate(T input, int ch) noexcept
T processSample(T input) noexcept
Processes a single mono sample.
void setLookahead(T ms) noexcept
Sets the lookahead: the audio is delayed so the gate opens (and closes) ahead of it....
void setSidechainHPF(bool enabled, double cutoffHz=80.0) noexcept
Configures sidechain High-Pass filter.
void setRange(T dB) noexcept
Sets maximum attenuation range.
int lookaheadChannels_
Channels with a prepared delay line.
static T detectorSafe(T x) noexcept
Non-finite detector samples read as silence (they would latch in the envelope and filter state).
std::array< T, kMaxScChannels > scHpfState_
std::atomic< bool > autoThreshold_
The thresholds count from the key's recent level.
void processBlock(AudioBufferView< T > audio, AudioBufferView< T > sidechain) noexcept
Processes audio with an external sidechain signal.
T processSampleWithSidechain(T input, T sidechain) noexcept
Processes a mono sample using an external sidechain.
KeyMonitor< T, 16 > keyMonitor_
The listened key: late by the lookahead, under full scale.
std::array< RingBuffer< T >, kMaxLookaheadChannels > lookahead_
static constexpr int kZeroCrossWindow
void setAttack(T ms) noexcept
Sets attack time in milliseconds. Non-finite values are ignored.
void updateStateMachine(T envelopeLinear) noexcept
std::atomic< T > lookaheadMs_
bool keyOn_
The equalizer has bands in the path (audio thread).
bool listen_
scListen_ as the audio thread took it.
void setRelease(T ms) noexcept
Sets release time in milliseconds. Non-finite values are ignored.
void prepare(const AudioSpec &spec) noexcept
Prepares from AudioSpec (unified API).
static constexpr int kMaxChannels
std::atomic< T > threshold_
void setHold(T ms) noexcept
Sets hold time in milliseconds. Non-finite values are ignored.
std::array< T, kMaxChannels > freqLpFreq_
void setGateMode(GateMode mode) noexcept
Selects the processing mode (Amplitude or Frequency; wild enum values clamp).
void updateZeroCrossing(T sample) noexcept
std::atomic< bool > scListen_
The key goes out instead of the audio.
GateMode
Operating mode for the gate processing.
@ Frequency
Gatelope-style: narrows bandpass dynamically instead of direct gain reduction.
@ Amplitude
Standard amplitude gain reduction (default).
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
KeyBand getSidechainBand(int band) const noexcept
The settings of a band of the key equalizer.
T placedKeyFrame(Sample sample, T &det0) noexcept
One frame of a two-channel key whose equalizer has bands on the middle or the sides: both channels ma...
std::array< T, kMaxScChannels > heard_
The key of each channel in this frame.
T cachedCloseThresholdLinear_
std::array< T, kMaxChannels > freqHpState_
double autoFallQuiet_
The same while the key is quiet.
void syncParamsIfDirty() noexcept
double autoFall_
Its fall per sample (a factor).
bool isAutoThreshold() const noexcept
Whether the threshold counts from the key's recent level (see setAutoThreshold()).
T processSampleInternal(T input, T sidechain, int ch) noexcept
std::atomic< T > releaseMs_
typename KeyEq::Shape KeyShape
What a band of the key equalizer does.
T getCurrentGain() noexcept
bool isSidechainListen() const noexcept
Whether the key is being played instead of the audio.
std::atomic< GateMode > gateMode_
std::array< T, kMaxChannels > freqHpFreq_
KeyEq::Response getSidechainResponse() const noexcept
The curve of the key equalizer, for a display.
State
Gate state machine phases.
@ Closed
Gate is fully closed (applying range attenuation).
@ Hold
Gate is open but counting down hold time before closing.
@ Open
Gate is fully open (passing audio).
static constexpr double kMaxLookaheadMs
bool cachedAutoThreshold_
std::atomic< T > rangeDb_
int lookaheadSamplesFor(T ms) const noexcept
std::atomic< T > attackMs_
T computeEnvelopeFollower(T rawLevel) noexcept
Updates envelope state to prevent intra-cycle chattering.
typename KeyEq::Band KeyBand
The settings of one band of the key equalizer.
static constexpr int kMaxScChannels
std::atomic< T > hysteresis_
void setHysteresis(T dB) noexcept
Sets the hysteresis amount (gap between open and close thresholds).
static constexpr double kAutoRefFallDb
dB per second its reference falls.
T applyScHpf(T input, int ch) noexcept
Per-channel one-pole sidechain high-pass (unity gain at Nyquist).
void setThreshold(T dB) noexcept
Sets the opening threshold.
std::atomic< T > scHpfFreq_
void setAutoThreshold(bool on) noexcept
Counts the threshold from the key's own recent level.
void setDuckMode(bool enabled) noexcept
Toggles ducking mode (invert gate logic).
std::array< T, kMaxChannels > freqHpPrev_
void setSidechainBand(int band, const KeyBand &settings) noexcept
Sets a band of the equalizer of the key.
int maxLookaheadSamples_
Allocated delay (0 before prepare()).
void reset() noexcept
Resets DSP state (clears filters, sets state to Closed).
static constexpr double kAutoRefQuiet
Share of that fall while the key is under the closing threshold.
void setAdaptiveHold(bool enabled) noexcept
Toggles adaptive hold based on zero-crossing rate.
std::atomic< bool > paramsDirty_
std::atomic< bool > duckMode_
void setSidechainListen(bool on) noexcept
Plays the key instead of the gated audio.
static constexpr int kMaxLookaheadChannels
int lookaheadSamples_
Audio-side value (consumed in syncParams()).
double autoRef_
The reference (linear).
void syncParams() noexcept
std::atomic< bool > adaptiveHold_
typename KeyEq::Placement KeyPlacement
The part of a two-channel key a band of the key equalizer acts on.
T delayed(T x, int ch) noexcept
std::atomic< bool > scHpfEnabled_
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.
T decibelsToGain(T dB, T minusInfinityDb=T(-100)) noexcept
Converts a value in decibels to linear gain.
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.