48#include "../Core/DspMath.h"
49#include "../Core/AudioSpec.h"
50#include "../Core/AudioBuffer.h"
51#include "../Core/DenormalGuard.h"
52#include "../Core/Hilbert.h"
53#include "../Core/KeyEqualizer.h"
54#include "../Core/RingBuffer.h"
55#include "../Core/StateBlob.h"
91 void prepare(
double sampleRate,
int numChannels = 2) noexcept
93 if (!std::isfinite(sampleRate) || sampleRate <= 0.0)
return;
117 if (!spec.isValid())
return;
118 prepare(spec.sampleRate, spec.numChannels);
132 processBlockInternal<true, false>(buffer,
nullptr);
134 processBlockInternal<false, false>(buffer,
nullptr);
153 if (sidechain.getNumChannels() <= 0 ||
154 sidechain.getNumSamples() < buffer.getNumSamples())
157 processBlockInternal<true, false>(buffer,
nullptr);
159 processBlockInternal<false, false>(buffer,
nullptr);
164 processBlockInternal<true, true>(buffer, &sidechain);
166 processBlockInternal<false, true>(buffer, &sidechain);
177 if (!std::isfinite(dB))
return;
178 threshold_.store(dB, std::memory_order_relaxed);
184 if (!std::isfinite(ratio))
return;
185 ratio_.store(std::max(ratio, T(1)), std::memory_order_relaxed);
191 if (!std::isfinite(dB))
return;
192 hysteresis_.store(std::max(dB, T(0)), std::memory_order_relaxed);
198 if (!std::isfinite(dB))
return;
199 const T r = std::min(dB, T(0));
200 rangeDb_.store(r, std::memory_order_relaxed);
207 if (!std::isfinite(ms))
return;
208 attackMs_.store(std::max(ms, T(0.01)), std::memory_order_relaxed);
215 if (!std::isfinite(ms))
return;
216 holdMs_.store(std::max(ms, T(0)), std::memory_order_relaxed);
221 const double h = std::min(
224 holdSamples_.store(
static_cast<int>(h), std::memory_order_relaxed);
231 if (!std::isfinite(ms))
return;
232 releaseMs_.store(std::max(ms, T(0.01)), std::memory_order_relaxed);
250 if (std::isfinite(cutoffHz) && cutoffHz > 0.0)
251 scHpfFreqHz_.store(
static_cast<T
>(cutoffHz), std::memory_order_relaxed);
319 if (!std::isfinite(ms))
return;
395 [[nodiscard]] std::vector<uint8_t>
getState()
const
400 w.
write(
"threshold",
static_cast<float>(
threshold_.load(std::memory_order_relaxed)));
401 w.
write(
"ratio",
static_cast<float>(
ratio_.load(std::memory_order_relaxed)));
402 w.
write(
"hysteresis",
static_cast<float>(
hysteresis_.load(std::memory_order_relaxed)));
403 w.
write(
"attack",
static_cast<float>(
attackMs_.load(std::memory_order_relaxed)));
404 w.
write(
"hold",
static_cast<float>(
holdMs_.load(std::memory_order_relaxed)));
405 w.
write(
"release",
static_cast<float>(
releaseMs_.load(std::memory_order_relaxed)));
406 w.
write(
"rangeDb",
static_cast<float>(
rangeDb_.load(std::memory_order_relaxed)));
408 w.
write(
"scHpfFreq",
static_cast<float>(
scHpfFreqHz_.load(std::memory_order_relaxed)));
409 w.
write(
"lookahead",
static_cast<float>(
lookaheadMs_.load(std::memory_order_relaxed)));
428 static_cast<double>(r.
read(
"scHpfFreq", 80.0f)));
459 const double samples = std::round(
static_cast<double>(ms) *
sampleRate_ / 1000.0);
467 template <
bool UseHPF>
470 T input = std::isfinite(raw) ? raw : T(0);
471 if constexpr (UseHPF)
491 template <
bool UseHPF,
bool UseSc>
495 const int nCh = buffer.getNumChannels();
496 const int nS = buffer.getNumSamples();
499 const int detCh = UseSc ? std::min(sidechain->getNumChannels(),
MAX_CHANNELS)
502 for (
int c0 = 0; c0 < nS; c0 +=
kDetChunk)
504 const int m = std::min(
kDetChunk, nS - c0);
512 for (
int ch = 0; ch < 2; ++ch)
514 const T* src = (UseSc ? sidechain->getChannel(ch) : buffer.getChannel(ch)) + c0;
515 for (
int j = 0; j < m; ++j)
516 heard_[
static_cast<size_t>(ch)][
static_cast<size_t>(j)] = keyInput<UseHPF>(src[j], ch);
518 for (
int j = 0; j < m; ++j)
520 T pair[2] = {
heard_[0][
static_cast<size_t>(j)],
heard_[1][
static_cast<size_t>(j)] };
522 heard_[0][
static_cast<size_t>(j)] = pair[0];
523 heard_[1][
static_cast<size_t>(j)] = pair[1];
530 for (
int ch = 0; ch < detCh; ++ch)
532 const T* src = (UseSc ? sidechain->getChannel(ch) : buffer.getChannel(ch)) + c0;
533 for (
int j = 0; j < m; ++j)
536 if (keyFrames) input =
heard_[
static_cast<size_t>(ch)][
static_cast<size_t>(j)];
539 input = keyInput<UseHPF>(src[j], ch);
541 if (
listen_)
heard_[
static_cast<size_t>(ch)][
static_cast<size_t>(j)] = input;
543 detIn_[
static_cast<size_t>(j)] =
static_cast<double>(input);
546 for (
int j = 0; j < m; ++j)
548 const T level =
static_cast<T
>(std::max(std::abs(
detIn_[
static_cast<size_t>(j)]),
549 detMag_[
static_cast<size_t>(j)]));
550 if (level >
detLevel_[
static_cast<size_t>(j)])
detLevel_[
static_cast<size_t>(j)] = level;
555 for (
int j = 0; j < m; ++j)
557 const int i = c0 + j;
558 const T sc =
detLevel_[
static_cast<size_t>(j)];
589 for (
int ch = 0; ch < detCh; ++ch) frame[ch] = heard_[static_cast<size_t>(ch)][
static_cast<size_t>(j)];
591 for (
int ch = 0; ch < detCh; ++ch) heard_[static_cast<size_t>(ch)][
static_cast<size_t>(j)] = frame[ch];
595 for (
int ch = 0; ch < nCh; ++ch)
597 T& x = buffer.getChannel(ch)[i];
600 auto& line =
lookahead_[
static_cast<size_t>(ch)];
607 x =
heard_[
static_cast<size_t>(std::min(ch, detCh - 1))][
static_cast<size_t>(j)];
639 if (levelDb < closeThresh)
646 if (levelDb > openThresh)
690 attackCoeff_.store(T(1) - std::exp(T(-1) / (fs *
attackMs_.load(std::memory_order_relaxed) / T(1000))),
691 std::memory_order_relaxed);
693 std::memory_order_relaxed);
696 detRelCoeff_.store(T(1) - std::exp(T(-1) / (fs * T(0.005))), std::memory_order_relaxed);
702 const double scFreq = std::clamp(
703 static_cast<double>(
scHpfFreqHz_.load(std::memory_order_relaxed)),
705 const T c =
static_cast<T
>(std::exp(-std::numbers::pi * 2.0 * scFreq /
sampleRate_));
707 scHpfA0_.store((T(1) + c) / T(2), std::memory_order_relaxed);
Non-owning view over audio channel data.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Downward expander with ratio control, hysteresis, and sidechain.
void publishMeters() noexcept
Publishes the metering words for cross-thread readout.
void setHysteresis(T dB) noexcept
Sets the hysteresis gap in decibels to prevent chattering.
typename KeyEq::Shape KeyShape
What a band of the key equalizer does.
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
void setRange(T dB) noexcept
Sets the maximum gain reduction limit in decibels (<= 0).
std::atomic< T > hysteresis_
void updateStateMachine(T levelDb) noexcept
std::atomic< T > rangeDb_
typename KeyEq::Placement KeyPlacement
The part of a two-channel key a band of the key equalizer acts on.
std::atomic< T > scHpfA0_
typename KeyEq::Band KeyBand
The settings of one band of the key equalizer.
KeyBand getSidechainBand(int band) const noexcept
The settings of a band of the key equalizer.
void reset() noexcept
Resets all internal DSP states to prevent clicks on playback start.
std::atomic< bool > scListen_
The key goes out instead of the audio.
double autoRefDb_
The reference (dB).
static constexpr double kAutoRefFallDb
dB per second its reference falls.
static constexpr int kDetChunk
void setRatio(T ratio) noexcept
Sets the expansion ratio (e.g., 4.0 for 4:1).
void cacheParams() noexcept
State getGateState() const noexcept
std::atomic< State > publishedState_
std::array< std::array< T, kDetChunk >, MAX_CHANNELS > heard_
The key of each channel in this chunk.
bool listen_
scListen_ as the audio thread took it.
T computeGain(T levelDb) noexcept
bool isSidechainListen() const noexcept
Whether the key is being played instead of the audio.
int maxLookaheadSamples_
Allocated delay (0 before prepare()).
std::atomic< T > releaseCoeff_
std::array< T, MAX_CHANNELS > scHpfPrev_
std::array< T, MAX_CHANNELS > scHpfState_
void setRelease(T ms) noexcept
Sets the release time in milliseconds.
std::atomic< bool > scHpfEnabled_
bool keyOn_
The equalizer has bands in the path (audio thread).
double autoRefFall_
Its fall per sample (dB).
std::array< double, kDetChunk > detIn_
void setAutoThreshold(bool on) noexcept
Counts the threshold from the key's own recent level.
std::array< HilbertIIR< double >, MAX_CHANNELS > analytic_
void setThreshold(T dB) noexcept
Sets the threshold in decibels.
std::atomic< T > publishedGateGain_
T getCurrentGainDb() const noexcept
std::atomic< T > rangeLinear_
void setSidechainListen(bool on) noexcept
Plays the key instead of the expanded audio.
std::atomic< T > attackCoeff_
void setAttack(T ms) noexcept
Sets the attack time in milliseconds.
static constexpr double kAutoRefQuiet
Share of that fall while the key is under the closing threshold.
void setHold(T ms) noexcept
Sets the hold time in milliseconds before release begins.
void processBlockInternal(AudioBufferView< T > buffer, const AudioBufferView< T > *sidechain) noexcept
Internal processing loop templated on HPF/sidechain to avoid branching.
void setLookahead(T ms) noexcept
Sets the lookahead: the audio is delayed so the gain moves ahead of it. 0 (default) is latency-free.
int getLatency() const noexcept
Latency in samples (the lookahead), correct right after setLookahead().
std::atomic< bool > autoThreshold_
The threshold counts from the key's recent level.
std::atomic< T > releaseMs_
std::array< RingBuffer< T >, MAX_CHANNELS > lookahead_
std::atomic< T > scHpfFreqHz_
static constexpr double kMaxLookaheadMs
std::atomic< T > detRelCoeff_
std::array< double, kDetChunk > detMag_
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an audio block in place (internal detector key).
KeyEq::Response getSidechainResponse() const noexcept
The curve of the key equalizer, for a display.
int lookaheadChannels_
Channels with a prepared delay line.
int lookaheadSamplesFor(T ms) const noexcept
std::atomic< T > scHpfCoeff_
bool cachedAutoThreshold_
KeyEq keyEq_
Equalizer of the key, after the high-pass.
std::atomic< T > threshold_
void prepare(const AudioSpec &spec) noexcept
Initializes the expander using an AudioSpec struct.
void processBlock(AudioBufferView< T > buffer, AudioBufferView< T > sidechain) noexcept
Processes an audio block in place, keyed by an external sidechain.
std::atomic< int > holdSamples_
std::atomic< T > lookaheadMs_
int cachedLookahead_
Audio-side samples (per block).
void prepare(double sampleRate, int numChannels=2) noexcept
Initializes the expander with a specific sample rate.
std::array< T, kDetChunk > detLevel_
static constexpr int MAX_CHANNELS
bool isAutoThreshold() const noexcept
Whether the threshold counts from the key's recent level (see setAutoThreshold()).
std::atomic< T > attackMs_
T keyInput(T raw, int ch) noexcept
One sample of a channel's key before its equalizer: made finite and, when UseHPF, through the sidecha...
T thresholdNow_
Threshold of the frame (dB).
T getLookahead() const noexcept
Returns the lookahead in milliseconds.
KeyMonitor< T, 16 > keyMonitor_
The listened key: late by the lookahead, under full scale.
void updateCoefficients() noexcept
void setSidechainHPF(bool enabled, double cutoffHz=80.0) noexcept
Enables and configures the sidechain high-pass filter.
void setSidechainBand(int band, const KeyBand &settings) noexcept
Sets a band of the equalizer of the key.
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.
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.
T gainToDecibels(T gain, T minusInfinityDb=T(-100)) noexcept
Converts a linear gain value to decibels.
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.