6#include "../Core/detail/BoxAverage.h"
86#include "../Core/DspMath.h"
87#include "../Core/AudioSpec.h"
88#include "../Core/AudioBuffer.h"
89#include "../Core/RingBuffer.h"
90#include "../Core/SmoothedValue.h"
91#include "../Core/DenormalGuard.h"
92#include "../Core/TruePeakDetector.h"
93#include "../Core/SimdOps.h"
94#include "../Core/StateBlob.h"
107#ifndef DSPARK_NOINLINE
108 #if defined(_MSC_VER)
109 #define DSPARK_NOINLINE __declspec(noinline)
110 #elif defined(__GNUC__) || defined(__clang__)
111 #define DSPARK_NOINLINE __attribute__((noinline))
113 #define DSPARK_NOINLINE
125template <FloatType T>
149 void prepare(
double sampleRate,
int numChannels = 2,
double initialLookaheadMs = -1.0)
151 if (!(sampleRate > 0.0))
return;
169 const int maxLookaheadSamples =
static_cast<int>(std::min(maxLaExact, 1.0e7)) + 1 +
kTpHighDelay;
177 dl.prepare(maxLookaheadSamples * 2 +
kChunk);
187 while (hist <
kSteps * (maxLookaheadSamples + 4)) hist <<= 1;
195 eHist_.assign(
static_cast<size_t>(hist), 1.0);
196 avgHist_.assign(
static_cast<size_t>(hist), 1.0);
197 rHist_.assign(
static_cast<size_t>(holdHist), 1.0);
198 sufMin_.assign(
static_cast<size_t>(holdHist) + 1, 1.0);
209 for (
int p = 0; p <
kSteps - 1; ++p)
212 if (std::isfinite(initialLookaheadMs) && initialLookaheadMs > 0.0)
213 lookaheadMs_.store(std::clamp(
static_cast<T
>(initialLookaheadMs),
215 std::memory_order_relaxed);
229 const T ceilDb =
ceilingDb_.load(std::memory_order_relaxed);
270 const int nCh = std::min(buffer.getNumChannels(),
numChannels_);
271 const int nS = buffer.getNumSamples();
281 const T relMs = std::max(
releaseMs_.load(std::memory_order_relaxed), T(1));
285 for (
int ch = 0; ch < nCh; ++ch)
286 chData[ch] = buffer.getChannel(ch);
293 for (
int start = 0; start < nS; start +=
kChunk)
295 const int n = std::min(
kChunk, nS - start);
308 for (
int ch = 0; ch < nCh; ++ch)
310 const T* x = chData[ch] + start;
311 for (
int i = 0; i < n; ++i)
319 for (
int i = 0; i < n; ++i)
323 for (
int i = 0; i < n; ++i)
345 for (
int ch = 0; ch < nCh; ++ch)
347 T* x = chData[ch] + start;
349 line.pushBlock(x, n);
350 for (
int i = 0; i < n; ++i)
358 out = std::clamp(out, -ceiling, ceiling);
363 if (std::abs(out) > clipCeil)
394 if (channel < 0 || channel >=
numChannels_)
return input;
416 T chPeak = std::abs(input);
417 T chAnnex = T(0), chSlow = T(0);
429 const T relMs = std::max(
releaseMs_.load(std::memory_order_relaxed), T(1));
456 for (
int s = 0; s <
kSteps; ++s)
461 out = std::clamp(out, -ceiling, ceiling);
466 if (std::abs(out) > clipCeil)
510 if (!std::isfinite(dB))
return;
511 ceilingDb_.store(dB, std::memory_order_relaxed);
523 if (!std::isfinite(ms))
return;
524 releaseMs_.store(std::max(T(1), ms), std::memory_order_relaxed);
541 if (!std::isfinite(ms))
return;
543 std::memory_order_relaxed);
566 if (!std::isfinite(ms))
return;
568 std::memory_order_relaxed);
737 if (!std::isfinite(ms))
return;
738 holdMs_.store(std::clamp(ms, T(0), T(50)), std::memory_order_relaxed);
742 [[nodiscard]] T
getHold() const noexcept {
return holdMs_.load(std::memory_order_relaxed); }
809 const bool high = truePeak &&
truePeakPrecision_.load(std::memory_order_relaxed) == 1;
810 const bool points = !truePeak &&
precision_.load(std::memory_order_relaxed) == 1;
812 truePeak, high, points);
829 [[nodiscard]] std::vector<uint8_t>
getState()
const
832 w.
write(
"ceiling",
static_cast<float>(
ceilingDb_.load(std::memory_order_relaxed)));
833 w.
write(
"release",
static_cast<float>(
releaseMs_.load(std::memory_order_relaxed)));
834 w.
write(
"lookahead",
static_cast<float>(
lookaheadMs_.load(std::memory_order_relaxed)));
838 w.
write(
"hold",
static_cast<float>(
holdMs_.load(std::memory_order_relaxed)));
839 w.
write(
"holdMode",
static_cast<int32_t
>(
holdMode_.load(std::memory_order_relaxed)));
842 w.
write(
"precision",
static_cast<int32_t
>(
precision_.load(std::memory_order_relaxed)));
915 "alignment rings hold the fast readings");
923 void detectTruePeak(
const T* x,
int n,
int ch, T* peak, T* annex, T* slow)
noexcept
975 for (
int ch = 0; ch < nCh; ++ch)
981 for (
int c = kChunks; c > 0; --c)
986 for (
int ch = 0; ch < nCh; ++ch)
988 const auto& line =
delayLines_[
static_cast<size_t>(ch)];
989 for (
int i = 0; i <
kChunk; ++i)
991 block[i] = line.read(c *
kChunk - 1 - i);
996 for (
int i = 0; i <
kChunk; ++i)
1007 if (
tpChannels_.size() <
static_cast<size_t>(nCh))
return;
1009 for (
int ch = 0; ch < nCh; ++ch)
1011 auto& state =
tpChannels_[
static_cast<size_t>(ch)];
1012 for (
int k = 0; k < kHistory; ++k)
1013 state.history[kHistory - 1 - k] =
delayLines_[
static_cast<size_t>(ch)].read(k);
1033 const double clampedMs = std::clamp(
static_cast<double>(ms), 0.5,
kMaxLookaheadMs);
1034 const double exact =
sampleRate_ * clampedMs / 1000.0;
1035 const int samples = std::max(1,
static_cast<int>(std::min(exact, 1.0e7)));
1039 if (!truePeak)
return points ? samples +
kPointDelay : samples;
1064 const T* window = &h[at + 1];
1066 for (
int p = 0; p <
kSteps - 1; ++p)
1081 if (!fromDelayLines || ch >= nCh)
continue;
1104 const bool points = !isp &&
precision_.load(std::memory_order_relaxed) == 1;
1121 [[nodiscard]]
int latencyFor(
int lookahead,
bool truePeak,
bool highPrecision,
bool points)
const noexcept
1124 return (maxMs > T(0)) ? std::max(lookahead,
lookaheadSamplesFor(maxMs, truePeak, highPrecision, points))
1152 [[nodiscard]]
inline T
heldGain(
int look,
int& delay)
noexcept
1193 const int span = std::max(0, L - isp);
1203 const int spanSteps = S * span;
1204 boxA_ = spanSteps / 2 + 1;
1222 for (
int k = 0; k <
boxA_; ++k)
1225 for (
int k = 0; k <
boxB_; ++k)
1240 for (
int j =
holdLen_ - 1; j >= 0; --j)
1242 m = std::min(m,
rHist_[
static_cast<size_t>((firstFrame + j) &
holdMask_)]);
1243 sufMin_[
static_cast<size_t>(j)] = m;
1271 if (!(g >= 0.0 && g <= 1.0)) g = 1.0;
1284 inline void advanceGain(T peak, T ceiling,
bool adaptive, T relMs)
noexcept
1293 stepGain(
static_cast<double>(ceiling / std::max(ceiling, peak)), adaptive, relMs);
1300 for (
int s = 0; s <
kSteps; ++s)
1301 stepGain(
static_cast<double>(ceiling / std::max(ceiling, points[s])), adaptive, relMs);
1305 inline void stepGain(
double required,
bool adaptive, T relMs)
noexcept
1323 T baseFactor = T(1);
1328 baseFactor = T(1) + std::min(durationMs / T(100), T(2));
1375 const T ceilDb =
ceilingDb_.load(std::memory_order_relaxed);
1382 const T relMs = std::max(
releaseMs_.load(std::memory_order_relaxed), T(1));
1389 const T holdMs =
holdMs_.load(std::memory_order_relaxed);
1390 const int holdMode =
holdMode_.load(std::memory_order_relaxed);
1393 const bool resize = holdMode !=
lastHoldMode_ || holdMode == 1;
1419 T sign = (out >= T(0)) ? T(1) : T(-1);
1420 T excess = std::abs(out) - clipCeil;
1421 T blend = T(1) / (T(1) + excess * T(10));
1422 out = sign * (clipCeil * blend + std::abs(out) * (T(1) - blend));
1424 const T hardCeil = clipCeil * T(1.05);
1425 if (std::abs(out) > hardCeil)
1426 out = std::clamp(out, -hardCeil, hardCeil);
Non-owning view over audio channel data.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
High-performance brickwall lookahead limiter.
void setLookahead(T ms) noexcept
Sets the lookahead time dynamically.
void prepare(double sampleRate, int numChannels=2, double initialLookaheadMs=-1.0)
Allocates memory and prepares the limiter for processing.
void setRelease(T ms) noexcept
Sets the base release time.
T latencyCurrent_
Its smoothed value while kept.
T alignSlow_[2]
Last two analyzer readings.
int latencySamples_
Delay the audio is asked to have (audio thread).
std::vector< double > rHist_
Required-gain history.
T chunkPoints_[kChunk][kSteps]
processBlock() points per frame (loudest channel).
bool isAdaptiveReleaseEnabled() const noexcept
std::atomic< T > lookaheadMs_
T processSample(T input, int channel) noexcept
Processes a single sample of one channel.
T getGainReductionDb() const noexcept
Current gain reduction in dB (metering).
T lookaheadCurrent_
Smoothed read offset (glides on live changes).
void stepGain(double required, bool adaptive, T relMs) noexcept
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
static constexpr int kTpMinLookahead
Leaves at least a 16-sample ramp.
int maxHoldSamples_
Hold length of kMaxHoldMs.
void prepare(const AudioSpec &spec)
Prepares from AudioSpec (unified API).
T getMaxLookahead() const noexcept
Latency kept for the lookahead in milliseconds (0: none; see setMaxLookahead()).
std::vector< typename TpAnalyzer::Channel > tpHighChannels_
Per channel history of the high-precision reading.
T alignAnnex_[kAlignRecent]
Recent Annex 2 readings.
T sampleGainNow_
Gain heard in the frame.
bool kept_
The gain is being held back.
static constexpr int kAlignRecent
Power of two holding kAnnexWindow frames.
RingBuffer< T > gainLine_
Gains waiting for the audio they belong to.
T pointPhase_[kSteps - 1][kPointTaps]
Interpolation phases (prepare()).
static constexpr int kTpDelay
Samples a reading reaches back.
int maxLimitSamples_
Adaptive-release duration cap (2 s).
static constexpr int kPointDelay
Samples the points reach back.
void configureGainComputer() noexcept
void setSafetyClip(bool enabled) noexcept
Enables the post-limiter soft-knee safety clipper. RT-Safe.
std::atomic< int > holdMode_
void resetGainComputer() noexcept
bool ispApplied_
Detection mode the gain computer is sized for.
int lastHoldMode_
Applied HoldMode (0 Deepest, 1 EveryPeak).
std::atomic< bool > lookaheadDirty_
void advanceGain(T peak, T ceiling, bool adaptive, T relMs) noexcept
void syncParameters() noexcept
void setPrecision(Precision precision) noexcept
Selects how finely the gain computer works (see Precision). RT-Safe.
std::atomic< bool > truePeakEnabled_
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
int getLatency() const noexcept
Reports the processing latency (the lookahead) in samples.
T alignFast_[kAlignRing]
Fast readings per sample, waiting for the analyzer.
bool pointsApplied_
Readings at eight points per sample applied (sample-peak mode).
int blockPos_
Position inside the current hold block.
void seedPointHistory(bool fromDelayLines) noexcept
T pendingPeak_
Other channels' peaks for the next processSample() frame.
void advanceGainPoints(const T *points, T ceiling, bool adaptive, T relMs) noexcept
T alignSample_[kAlignRecent]
Recent sample peaks.
std::atomic< bool > safetyClipEnabled_
std::unique_ptr< TpAnalyzer > tpAnalyzer_
High-precision kernels and scratch (prepare()).
void reset() noexcept
Resets the internal state (delays, gain reduction). RT-Safe.
void updateReleaseCoefficient() noexcept
SmoothedValue< T > ceilingSmooth_
int lookaheadSamples_
Audio-side lookahead (consumed from lookaheadMs_).
static constexpr int kPointTaps
Taps of the interpolation.
TruePeakPrecision getTruePeakPrecision() const noexcept
std::atomic< int > precision_
Published Precision (0 Standard, 1 High).
T applySafetyClipper(T out, T clipCeil) const noexcept
std::atomic< int > truePeakPrecision_
Published TruePeakPrecision (0 Standard, 1 High).
int chunkDelay_[kChunk]
Delay of the audio per frame (the lookahead, or the latency kept).
int holdLeft_
Hold samples left before the release may act.
T pendingPoints_[kSteps]
Other channels' points for the next processSample() frame.
int latencyFor(int lookahead, bool truePeak, bool highPrecision, bool points) const noexcept
std::vector< double > eHist_
Released envelope history.
void applyLookaheadTarget() noexcept
void setTruePeak(bool enabled) noexcept
Enables ISP true-peak detection. RT-Safe.
int counterHold_
Hold-counter restart value (Deepest mode).
T pendingAnnex_
The same for their Annex 2 readings (high precision).
std::vector< double > sufMin_
Suffix minima of the last complete hold block (+1 empty).
bool isSafetyClipEnabled() const noexcept
void detectTruePeak(const T *x, int n, int ch, T *peak, T *annex, T *slow) noexcept
static constexpr double kPointBeta
Kaiser beta of the interpolation.
int holdSamples_
Hold length in samples.
TpEstimator tpEstimator_
Kernel and phase scratch.
std::vector< RingBuffer< T > > delayLines_
std::atomic< T > releaseMs_
void setAdaptiveRelease(bool enabled) noexcept
Enables program-dependent adaptive release. RT-Safe. The release time grows with how long peaks have ...
static constexpr int kChunk
int pointAt_[kMaxChannels]
Next write position in it.
void restartGainComputerAt(double g) noexcept
int sampleDelayNow_
Delay of the audio for the frame.
void readPoints(T x, int ch, T *points) noexcept
T heldGain(int look, int &delay) noexcept
int stepsPerSample_
Steps of the gain computer per sample (1 or kSteps).
void resetHighAlignment() noexcept
static constexpr int kResumPeriod
std::atomic< T > maxLookaheadMs_
Latency kept (0: none).
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an AudioBufferView in-place.
static constexpr double kHoldTolerance
0.01 dB: crests that close restart the hold (Precision::High).
double prefixMin_
Running minimum of the current hold block.
int histMask_
Moving-average histories (lookahead).
static constexpr int kAnnexWindow
Samples one Annex 2 reading is formed from.
int alignFrame_
Frame counter modulo kAlignRing.
void setMaxLookahead(T ms) noexcept
Keeps a latency for the lookahead to move inside.
T pointHist_[kMaxChannels][2 *kPointTaps]
Mirrored interpolation history per channel.
double holdSlack_
Factor of the held reduction a crest restarts the hold within.
DSPARK_NOINLINE void restartHoldBlock(int64_t firstFrame) noexcept
T getLookahead() const noexcept
void updateHoldSamples() noexcept
std::atomic< bool > adaptiveRelease_
static constexpr int kAlignFast
Delay of the fast readings.
void syncKeptLatency() noexcept
void setHoldMode(HoldMode mode) noexcept
Selects the hold behaviour (see HoldMode). RT-Safe.
bool tpHighApplied_
High-precision reading applied (implies ispApplied_).
std::vector< typename TpEstimator::Channel > tpChannels_
Per channel history.
void seedTruePeakHistory() noexcept
int gainSpan_
Length of the gain line.
HoldMode getHoldMode() const noexcept
bool isTruePeakEnabled() const noexcept
T alignHighReadings(T samplePeak, T annex, T slow) noexcept
static constexpr T kSafetyClipCeiling
-0.3 dBFS
T pendingSlow_
The same for their analyzer readings (high precision).
std::atomic< T > publishedGain_
static constexpr int kSteps
Steps of the gain computer per sample at Precision::High.
static constexpr double kMaxLookaheadMs
void setHold(T ms) noexcept
Sets how long the reduction is held after the last peak that asked for it, before the release starts....
T getHold() const noexcept
static constexpr int kMaxChannels
void seedHighTruePeakHistory() noexcept
std::atomic< T > ceilingDb_
void setCeiling(T dB) noexcept
Sets the absolute output ceiling.
Precision getPrecision() const noexcept
DSPARK_NOINLINE void resumBoxes() noexcept
static constexpr int kTpHighDelay
Samples a high-precision reading reaches back.
std::vector< double > avgHist_
First moving-average output history.
T lastCeilingDb_
Change detector for the ceiling pow skip.
static constexpr double kMaxHoldMs
void setTruePeakPrecision(TruePeakPrecision precision) noexcept
Selects the true-peak reading (see TruePeakPrecision). RT-Safe.
int lookaheadSamplesFor(T ms, bool truePeak, bool highPrecision, bool points) const noexcept
static constexpr int kAlignRing
Power of two above kAlignFast.
int holdMask_
Required-gain history (lookahead + hold).
Power-of-two circular buffer with compile-time interpolated read access.
Zero-allocation parameter smoother for real-time audio.
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.
Running-maximum reading of the band-limited reconstruction peak, for meters.
static constexpr int getDelay() noexcept
Input samples one reading reaches back: the newest 8x grid point a call reads lies this many samples ...
static constexpr int kChunk
Most samples one processMax() call takes.
static constexpr int kTaps
Taps of the first (interval midpoint) stage.
static constexpr int getTaps() noexcept
Input samples one estimate is computed from (taps per phase).
Block-based reading of the band-limited reconstruction peak.
static constexpr int getDelay() noexcept
Input samples one reading reaches back.
void process(Channel &channel, const T *x, int n, T *peak, bool annex2Guard=false) noexcept
Appends samples to a channel and raises each peak[i] to the reading of x[i]'s position.
static constexpr int kChunk
Most samples one process() call takes.
static constexpr int kTaps
Taps per interpolation phase.
double advanceBoxAverage(double incoming, double outgoing, double &sum, double inverseLength) noexcept
float dotProduct(const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int count) noexcept
Computes the dot product of two arrays.
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.
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
double sampleRate
Sample rate in Hz.
History of one channel (each stage's kernel span plus one chunk).
History of one channel (kTaps - 1 samples plus one chunk).