DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Limiter.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
6#include "../Core/detail/BoxAverage.h"
7
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"
95
96#include <algorithm>
97#include <atomic>
98#include <cmath>
99#include <cstddef>
100#include <cstdint>
101#include <memory>
102#include <vector>
103
104// Keeps the gain computer's rare paths (once per hold block, once per 2^16
105// frames) out of the per-sample loop, so the hot part inlines. Guarded the same
106// way as in Core/Biquad.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))
112 #else
113 #define DSPARK_NOINLINE
114 #endif
115#endif
116
117namespace dspark {
118
125template <FloatType T>
127{
128public:
129 ~Limiter() = default; // non-virtual: leaf class (no virtual dispatch)
130
131 // -- Lifecycle --------------------------------------------------------------
132
149 void prepare(double sampleRate, int numChannels = 2, double initialLookaheadMs = -1.0)
150 {
151 if (!(sampleRate > 0.0)) return; // NaN-safe validity gate: keep previous state
152 prepared_ = false; // basic guarantee while (re)allocating
153
154 sampleRate_ = sampleRate;
155 // The true-peak detector state is a fixed kMaxChannels array; clamp so
156 // detection can never index it out of bounds for high channel counts.
157 numChannels_ = std::clamp(numChannels, 1, kMaxChannels);
158
159 // Caching inverse sample rate for fast math in hot paths
160 invSampleRate_ = T(1) / static_cast<T>(sampleRate_);
161
162 // Allocate for maximum possible lookahead to prevent RT-allocations
163 // later. The sample count is capped in double before the cast (a cast
164 // of an out-of-int-range double is undefined behaviour).
165 const double maxLaExact = sampleRate_ * kMaxLookaheadMs / 1000.0;
166 // True-peak mode raises the lookahead to at least kTpMinLookahead; its
167 // high-precision reading adds kTpHighDelay samples to the lookahead
168 // instead (always more than that minimum).
169 const int maxLookaheadSamples = static_cast<int>(std::min(maxLaExact, 1.0e7)) + 1 + kTpHighDelay;
170 static_assert(kTpHighDelay > kTpMinLookahead, "the high-precision lookahead covers the standard minimum");
171
172 // Use the clamped count: a degenerate numChannels (<= 0, or negative cast
173 // to size_t, or > kMaxChannels) must neither under-allocate (which would
174 // make processBlock index delayLines_ out of bounds) nor over-allocate.
175 delayLines_.resize(static_cast<size_t>(numChannels_));
176 for (auto& dl : delayLines_)
177 dl.prepare(maxLookaheadSamples * 2 + kChunk); // lookahead glide + one processBlock() chunk
178 gainSpan_ = maxLookaheadSamples * 2 + kChunk;
179 gainLine_.prepare(gainSpan_);
180
181 // Gain-computer histories: power-of-two rings, in steps (kSteps per
182 // sample at Precision::High, sized for it whatever the precision so
183 // it can be switched during playback). The moving averages look back
184 // at most the lookahead; the sliding minimum covers the lookahead
185 // plus the longest hold.
186 int hist = 4;
187 while (hist < kSteps * (maxLookaheadSamples + 4)) hist <<= 1;
188 histSize_ = hist;
189 histMask_ = hist - 1;
190 maxHoldSamples_ = static_cast<int>(std::min(std::ceil(sampleRate_ * kMaxHoldMs / 1000.0), 1.0e7));
191 int holdHist = 4;
192 while (holdHist < kSteps * (maxLookaheadSamples + maxHoldSamples_ + 4)) holdHist <<= 1;
193 holdHistSize_ = holdHist;
194 holdMask_ = holdHist - 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);
199
200 // Long-kernel true-peak estimator: per-channel histories (the kernel
201 // is designed by the estimator itself).
202 tpChannels_.assign(static_cast<size_t>(numChannels_), typename TpEstimator::Channel {});
203 // High-precision reading: the analyzer (kernels and scratch) and its
204 // per-channel histories, allocated whether or not the mode is on so
205 // setTruePeakPrecision() can switch it during playback.
206 if (!tpAnalyzer_) tpAnalyzer_ = std::make_unique<TpAnalyzer>();
207 tpHighChannels_.assign(static_cast<size_t>(numChannels_), typename TpAnalyzer::Channel {});
208 // The seven interpolation phases of the eight points per sample.
209 for (int p = 0; p < kSteps - 1; ++p)
210 detail::designSincPhase<kPointTaps>(pointPhase_[p], kPointBeta, static_cast<double>(p + 1) / kSteps);
211
212 if (std::isfinite(initialLookaheadMs) && initialLookaheadMs > 0.0)
213 lookaheadMs_.store(std::clamp(static_cast<T>(initialLookaheadMs),
214 T(0.5), static_cast<T>(kMaxLookaheadMs)),
215 std::memory_order_relaxed);
216 // The hold length is part of the sliding-minimum window that
217 // applyLookaheadTarget() sizes, so it is consumed first.
218 lastHoldMs_ = holdMs_.load(std::memory_order_relaxed);
219 lastHoldMode_ = holdMode_.load(std::memory_order_relaxed);
221 (void)lookaheadDirty_.exchange(false, std::memory_order_acquire);
223 lookaheadCurrent_ = static_cast<T>(lookaheadSamples_);
224
225 // Duration cap for the adaptive-release counter (2 seconds).
226 maxLimitSamples_ = static_cast<int>(std::min(sampleRate_ * 2.0, 2.5e8)); // times kSteps stays in int range
227
228 // Ceiling smoother setup
229 const T ceilDb = ceilingDb_.load(std::memory_order_relaxed);
230 lastCeilingDb_ = ceilDb;
231 const T ceilLinear = decibelsToGain(ceilDb);
232 ceilingSmooth_.prepare(sampleRate, 30.0);
233 ceilingSmooth_.reset(ceilLinear);
234
235 lastReleaseMs_ = std::max(releaseMs_.load(std::memory_order_relaxed), T(1));
237
238 reset();
239 prepared_ = true;
240 }
241
249 void prepare(const AudioSpec& spec)
250 {
251 prepare(spec.sampleRate, spec.numChannels);
252 }
253
265 void processBlock(AudioBufferView<T> buffer) noexcept
266 {
267 if (!prepared_) return;
268 DenormalGuard guard;
269
270 const int nCh = std::min(buffer.getNumChannels(), numChannels_);
271 const int nS = buffer.getNumSamples();
272
273 if (lookaheadDirty_.exchange(false, std::memory_order_acquire))
277
278 const bool isp = ispApplied_;
279 const bool adaptive = adaptiveRelease_.load(std::memory_order_relaxed);
280 const bool safetyClip = safetyClipEnabled_.load(std::memory_order_relaxed);
281 const T relMs = std::max(releaseMs_.load(std::memory_order_relaxed), T(1));
282 const T lookTarget = static_cast<T>(lookaheadSamples_);
283
284 T* chData[kMaxChannels] = {};
285 for (int ch = 0; ch < nCh; ++ch)
286 chData[ch] = buffer.getChannel(ch);
287
288 // Three passes per chunk: detection (the true-peak FIR, throughput
289 // bound), the serial gain computer (latency bound) and the gain
290 // application. Kept apart, the out-of-order core no longer stalls the
291 // FIR work behind the gain recursion. The per-sample arithmetic is
292 // unchanged, so processSample() stays bit-identical for mono.
293 for (int start = 0; start < nS; start += kChunk)
294 {
295 const int n = std::min(kChunk, nS - start);
296
297 // Pass 1: linked peak detection (loudest channel per frame).
298 const bool aligned = isp && tpHighApplied_;
299 const bool points = pointsApplied_;
300 std::fill(chunkPeak_, chunkPeak_ + n, T(0));
301 if (aligned)
302 {
303 std::fill(chunkAnnex_, chunkAnnex_ + n, T(0));
304 std::fill(chunkSlow_, chunkSlow_ + n, T(0));
305 }
306 if (points)
307 for (int i = 0; i < n; ++i) std::fill(chunkPoints_[i], chunkPoints_[i] + kSteps, T(0));
308 for (int ch = 0; ch < nCh; ++ch)
309 {
310 const T* x = chData[ch] + start;
311 for (int i = 0; i < n; ++i)
312 chunkPeak_[i] = std::max(chunkPeak_[i], std::abs(x[i])); // NaN is ignored
313 if (isp)
315 if (points)
316 for (int i = 0; i < n; ++i) readPoints(x[i], ch, chunkPoints_[i]);
317 }
318 if (aligned)
319 for (int i = 0; i < n; ++i)
321
322 // Pass 2: ceiling smoother, lookahead glide and gain computer.
323 for (int i = 0; i < n; ++i)
324 {
325 const T ceiling = ceilingSmooth_.getNextValue();
326 chunkCeiling_[i] = ceiling;
327
328 // Live-change smoothing of the lookahead read offset: at most
329 // one sample of change per sample, so a setLookahead() during
330 // playback glides (brief micro pitch-shift) instead of clicking.
331 if (lookaheadCurrent_ < lookTarget) lookaheadCurrent_ += T(1);
332 else if (lookaheadCurrent_ > lookTarget) lookaheadCurrent_ -= T(1);
333 chunkLook_[i] = static_cast<int>(lookaheadCurrent_);
334
335 if (points) advanceGainPoints(chunkPoints_[i], ceiling, adaptive, relMs);
336 else advanceGain(chunkPeak_[i], ceiling, adaptive, relMs);
338 chunkDelay_[i] = chunkLook_[i];
339 // With a latency kept for the lookahead the audio waits that
340 // long and the gain waits the difference.
342 }
343
344 // Pass 3: delay, apply the gain, optional safety clip.
345 for (int ch = 0; ch < nCh; ++ch)
346 {
347 T* x = chData[ch] + start;
348 auto& line = delayLines_[static_cast<size_t>(ch)];
349 line.pushBlock(x, n); // frame i now sits (n - 1 - i) samples back
350 for (int i = 0; i < n; ++i)
351 {
352 const T ceiling = chunkCeiling_[i];
353 T out = line.read(chunkDelay_[i] + (n - 1 - i)) * chunkGain_[i];
354
355 // Rounding backstop: the gain computer already meets the
356 // ceiling; the clamp only trims float rounding and the
357 // brief transition after a live ceiling or lookahead change.
358 out = std::clamp(out, -ceiling, ceiling);
359
360 if (safetyClip)
361 {
362 const T clipCeil = std::min(kSafetyClipCeiling, ceiling);
363 if (std::abs(out) > clipCeil)
364 out = applySafetyClipper(out, clipCeil);
365 }
366
367 x[i] = out;
368 }
369 }
370 }
371
372 // One relaxed store per block, outside the per-sample loop.
373 publishedGain_.store(currentGain_, std::memory_order_relaxed);
374 }
375
389 [[nodiscard]] T processSample(T input, int channel) noexcept
390 {
391 if (!prepared_) return input;
392 // Release-safe channel bound (delayLines_ is sized to numChannels_):
393 // out-of-range channels are an exact pass-through, no state touched.
394 if (channel < 0 || channel >= numChannels_) return input;
395
396 const bool adaptive = adaptiveRelease_.load(std::memory_order_relaxed);
397 const bool safetyClip = safetyClipEnabled_.load(std::memory_order_relaxed);
398
399 if (channel == 0)
400 {
401 if (lookaheadDirty_.exchange(false, std::memory_order_acquire))
404 sampleCeiling_ = ceilingSmooth_.getNextValue();
405
406 const T lookTarget = static_cast<T>(lookaheadSamples_);
407 if (lookaheadCurrent_ < lookTarget) lookaheadCurrent_ += T(1);
408 else if (lookaheadCurrent_ > lookTarget) lookaheadCurrent_ -= T(1);
409 sampleLookNow_ = static_cast<int>(lookaheadCurrent_);
411 }
412 const bool isp = ispApplied_;
413 const T ceiling = sampleCeiling_;
414
415 delayLines_[channel].push(input);
416 T chPeak = std::abs(input);
417 T chAnnex = T(0), chSlow = T(0);
418 if (isp)
419 detectTruePeak(&input, 1, channel, &chPeak, &chAnnex, &chSlow);
420 T chPoints[kSteps] = {};
421 if (pointsApplied_) readPoints(input, channel, chPoints);
422
423 // The gain computer advances on channel 0. Peaks of the other channels
424 // reach it on the next frame (they are processed after channel 0), so
425 // they are one sample late: prefer processBlock() for linked
426 // multi-channel limiting. Mono is bit-identical to processBlock().
427 if (channel == 0)
428 {
429 const T relMs = std::max(releaseMs_.load(std::memory_order_relaxed), T(1));
430 T peak = std::max(chPeak, pendingPeak_);
431 if (isp && tpHighApplied_)
432 peak = alignHighReadings(peak, std::max(chAnnex, pendingAnnex_), std::max(chSlow, pendingSlow_));
433 if (pointsApplied_)
434 {
435 for (int s = 0; s < kSteps; ++s) chPoints[s] = std::max(chPoints[s], pendingPoints_[s]);
436 advanceGainPoints(chPoints, ceiling, adaptive, relMs);
437 std::fill(std::begin(pendingPoints_), std::end(pendingPoints_), T(0));
438 }
439 else
440 {
441 advanceGain(peak, ceiling, adaptive, relMs);
442 }
443 pendingPeak_ = T(0);
444 pendingAnnex_ = T(0);
445 pendingSlow_ = T(0);
446 publishedGain_.store(currentGain_, std::memory_order_relaxed);
450 }
451 else
452 {
453 if (chPeak > pendingPeak_) pendingPeak_ = chPeak;
454 if (chAnnex > pendingAnnex_) pendingAnnex_ = chAnnex;
455 if (chSlow > pendingSlow_) pendingSlow_ = chSlow;
456 for (int s = 0; s < kSteps; ++s)
457 if (chPoints[s] > pendingPoints_[s]) pendingPoints_[s] = chPoints[s];
458 }
459
460 T out = delayLines_[channel].read(sampleDelayNow_) * sampleGainNow_;
461 out = std::clamp(out, -ceiling, ceiling); // exact brickwall contract
462
463 if (safetyClip)
464 {
465 const T clipCeil = std::min(kSafetyClipCeiling, ceiling);
466 if (std::abs(out) > clipCeil)
467 out = applySafetyClipper(out, clipCeil);
468 }
469 return out;
470 }
471
473 void reset() noexcept
474 {
475 for (auto& dl : delayLines_) dl.reset();
476 for (auto& state : tpChannels_) state = {};
477 for (auto& state : tpHighChannels_) state = {};
479 seedPointHistory(false);
480 currentGain_ = T(1);
481 publishedGain_.store(T(1), std::memory_order_relaxed);
483 pendingPeak_ = T(0);
484 pendingAnnex_ = T(0);
485 pendingSlow_ = T(0);
487 lookaheadCurrent_ = static_cast<T>(lookaheadSamples_);
488 ceilingSmooth_.skip();
489 sampleCeiling_ = ceilingSmooth_.getCurrentValue();
491 // A latency kept for the lookahead is in place from the first sample.
494 gainLine_.reset();
495 if (kept_)
496 for (int i = 0; i < gainSpan_; ++i) gainLine_.push(T(1));
497 sampleDelayNow_ = static_cast<int>(latencyCurrent_);
498 sampleGainNow_ = T(1);
499 }
500
501 // -- Level 1: Simple API ----------------------------------------------------
502
508 void setCeiling(T dB) noexcept
509 {
510 if (!std::isfinite(dB)) return;
511 ceilingDb_.store(dB, std::memory_order_relaxed);
512 }
513
514 // -- Level 2: Intermediate API ----------------------------------------------
515
521 void setRelease(T ms) noexcept
522 {
523 if (!std::isfinite(ms)) return;
524 releaseMs_.store(std::max(T(1), ms), std::memory_order_relaxed);
525 }
526
539 void setLookahead(T ms) noexcept
540 {
541 if (!std::isfinite(ms)) return;
542 lookaheadMs_.store(std::clamp(ms, T(0.5), static_cast<T>(kMaxLookaheadMs)),
543 std::memory_order_relaxed);
544 lookaheadDirty_.store(true, std::memory_order_release);
545 }
546
564 void setMaxLookahead(T ms) noexcept
565 {
566 if (!std::isfinite(ms)) return;
567 maxLookaheadMs_.store(std::clamp(ms, T(0), static_cast<T>(kMaxLookaheadMs)),
568 std::memory_order_relaxed);
569 lookaheadDirty_.store(true, std::memory_order_release);
570 }
571
573 [[nodiscard]] T getMaxLookahead() const noexcept { return maxLookaheadMs_.load(std::memory_order_relaxed); }
574
575 // -- Level 3: Expert API ----------------------------------------------------
576
596 void setTruePeak(bool enabled) noexcept
597 {
598 truePeakEnabled_.store(enabled, std::memory_order_relaxed);
599 lookaheadDirty_.store(true, std::memory_order_release);
600 }
601
604 {
608 Standard,
614 High
615 };
616
642 {
643 truePeakPrecision_.store(precision == TruePeakPrecision::High ? 1 : 0, std::memory_order_relaxed);
644 lookaheadDirty_.store(true, std::memory_order_release);
645 }
646
648 [[nodiscard]] TruePeakPrecision getTruePeakPrecision() const noexcept
649 {
650 return truePeakPrecision_.load(std::memory_order_relaxed) == 1 ? TruePeakPrecision::High
652 }
653
655 enum class Precision
656 {
659 Standard,
663 High
664 };
665
701 void setPrecision(Precision precision) noexcept
702 {
703 precision_.store(precision == Precision::High ? 1 : 0, std::memory_order_relaxed);
704 lookaheadDirty_.store(true, std::memory_order_release);
705 }
706
708 [[nodiscard]] Precision getPrecision() const noexcept
709 {
710 return precision_.load(std::memory_order_relaxed) == 1 ? Precision::High : Precision::Standard;
711 }
712
716 void setAdaptiveRelease(bool enabled) noexcept { adaptiveRelease_.store(enabled, std::memory_order_relaxed); }
717
735 void setHold(T ms) noexcept
736 {
737 if (!std::isfinite(ms)) return;
738 holdMs_.store(std::clamp(ms, T(0), T(50)), std::memory_order_relaxed);
739 }
740
742 [[nodiscard]] T getHold() const noexcept { return holdMs_.load(std::memory_order_relaxed); }
743
746 enum class HoldMode
747 {
752 Deepest,
764 };
765
768 void setHoldMode(HoldMode mode) noexcept
769 {
770 holdMode_.store(mode == HoldMode::EveryPeak ? 1 : 0, std::memory_order_relaxed);
771 }
772
774 [[nodiscard]] HoldMode getHoldMode() const noexcept
775 {
776 return holdMode_.load(std::memory_order_relaxed) == 1 ? HoldMode::EveryPeak : HoldMode::Deepest;
777 }
778
786 void setSafetyClip(bool enabled) noexcept { safetyClipEnabled_.store(enabled, std::memory_order_relaxed); }
787
788 // Getters
789 [[nodiscard]] bool isTruePeakEnabled() const noexcept { return truePeakEnabled_.load(std::memory_order_relaxed); }
790 [[nodiscard]] bool isAdaptiveReleaseEnabled() const noexcept { return adaptiveRelease_.load(std::memory_order_relaxed); }
791 [[nodiscard]] bool isSafetyClipEnabled() const noexcept { return safetyClipEnabled_.load(std::memory_order_relaxed); }
792 [[nodiscard]] T getLookahead() const noexcept { return lookaheadMs_.load(std::memory_order_relaxed); }
793
806 [[nodiscard]] int getLatency() const noexcept
807 {
808 const bool truePeak = truePeakEnabled_.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;
811 return latencyFor(lookaheadSamplesFor(lookaheadMs_.load(std::memory_order_relaxed), truePeak, high, points),
812 truePeak, high, points);
813 }
814
822 [[nodiscard]] T getGainReductionDb() const noexcept
823 {
824 return gainToDecibels(publishedGain_.load(std::memory_order_relaxed));
825 }
826
827
829 [[nodiscard]] std::vector<uint8_t> getState() const
830 {
831 StateWriter w(stateId("LIMT"), 1);
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)));
835 w.write("truePeak", truePeakEnabled_.load(std::memory_order_relaxed));
836 w.write("adaptive", adaptiveRelease_.load(std::memory_order_relaxed));
837 w.write("safetyClip", safetyClipEnabled_.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)));
840 w.write("truePeakPrecision", static_cast<int32_t>(truePeakPrecision_.load(std::memory_order_relaxed)));
841 w.write("maxLookahead", static_cast<float>(maxLookaheadMs_.load(std::memory_order_relaxed)));
842 w.write("precision", static_cast<int32_t>(precision_.load(std::memory_order_relaxed)));
843 return w.blob();
844 }
845
847 bool setState(const uint8_t* data, size_t size)
848 {
849 StateReader r(data, size);
850 if (!r.isValid() || r.processorId() != stateId("LIMT")) return false;
851 setCeiling(static_cast<T>(r.read("ceiling", -0.3f)));
852 setRelease(static_cast<T>(r.read("release", 100.0f)));
853 setLookahead(static_cast<T>(r.read("lookahead", 2.0f)));
854 setTruePeak(r.read("truePeak", false));
855 setAdaptiveRelease(r.read("adaptive", false));
856 setSafetyClip(r.read("safetyClip", false));
857 // A blob written before the hold existed was rendered without one.
858 setHold(static_cast<T>(r.read("hold", 0.0f)));
859 setHoldMode(r.read("holdMode", int32_t(0)) == 1 ? HoldMode::EveryPeak : HoldMode::Deepest);
860 setTruePeakPrecision(r.read("truePeakPrecision", int32_t(0)) == 1 ? TruePeakPrecision::High
862 setMaxLookahead(static_cast<T>(r.read("maxLookahead", 0.0f)));
863 setPrecision(r.read("precision", int32_t(0)) == 1 ? Precision::High : Precision::Standard);
864 return true;
865 }
866
867protected:
868 static constexpr int kMaxChannels = 16;
869 static constexpr double kMaxLookaheadMs = 10.0;
870 static constexpr double kMaxHoldMs = 50.0;
871 static constexpr T kSafetyClipCeiling = T(0.96605);
872
873 // processBlock() chunk length (see its three passes).
874 static constexpr int kChunk = 128;
875
876 // ---- Long-kernel true-peak estimator ------------------------------------
877 //
878 // The BS.1770 Annex 2 example interpolator has 12 taps per phase; its pass
879 // band ends well below Nyquist, so it under-reads peaks formed by content
880 // near the top of the band (measured up to 0.8 dB on a hard-clipped 5 kHz
881 // tone and on dense mixes once the limiter has flattened the low end).
882 // The shared TruePeakEstimator (Core/TruePeakDetector.h) evaluates the
883 // reconstruction with 64-tap phases and refines every crest of its 4x
884 // grid; its Annex 2 guard also holds the table's own reading at or below
885 // the ceiling, so an Annex 2 meter reads the output there too. The reading
886 // at sample n describes the interval x[n - 32] .. x[n - 31] and the half
887 // grid step before it.
889 static constexpr int kTpDelay = TpEstimator::getDelay();
890 static constexpr int kTpMinLookahead = kTpDelay + 16;
891 static_assert(kChunk <= TpEstimator::kChunk, "one processBlock() chunk per estimator call");
892
893 // ---- High-precision true-peak reading ------------------------------------
894 //
895 // TruePeakAnalyzer's per-sample readings: a 512-tap first stage follows
896 // the content between 0.45 fs and Nyquist that the 64-tap estimate cannot.
897 // The reading at frame n covers the reconstruction around
898 // x[n - 261] .. x[n - 260] and the crest centred an eighth of a sample
899 // before it, so it concerns the samples n - 262 .. n - 260. That reach
900 // goes to the latency (the lookahead parameter stays all ramp, as in
901 // sample-peak mode), and the readings that arrive sooner (the sample
902 // peak, the BS.1770 Annex 2 estimate) wait for it in alignHighReadings():
903 // the gain computer receives, kTpHighDelay frames late, one peak per
904 // sample that holds everything known about that sample, so no reading
905 // turns the gain down before its own sample.
907 static constexpr int kTpHighDelay = TpAnalyzer::getDelay() + 1;
909 static constexpr int kAlignFast = kTpHighDelay - (kAnnexWindow - 1);
910 static constexpr int kAlignRing = 256;
911 static constexpr int kAlignRecent = 16;
912 static_assert(kChunk <= TpAnalyzer::kChunk, "one processBlock() chunk per analyzer call");
913 static_assert(kAlignFast > 0 && kAlignFast < kAlignRing && kAnnexWindow <= kAlignRecent
914 && kAlignRing % kAlignRecent == 0,
915 "alignment rings hold the fast readings");
916
923 void detectTruePeak(const T* x, int n, int ch, T* peak, T* annex, T* slow) noexcept
924 {
925 if (tpHighApplied_)
926 tpAnalyzer_->process(tpHighChannels_[static_cast<size_t>(ch)], x, n, slow, annex);
927 else
928 tpEstimator_.process(tpChannels_[static_cast<size_t>(ch)], x, n, peak, true);
929 }
930
936 [[nodiscard]] inline T alignHighReadings(T samplePeak, T annex, T slow) noexcept
937 {
938 // w counts frames modulo the larger ring (a multiple of the smaller).
939 const int w = alignFrame_;
940 alignFrame_ = (alignFrame_ + 1) & (kAlignRing - 1);
941 alignSample_[w & (kAlignRecent - 1)] = samplePeak;
942 alignAnnex_[w & (kAlignRecent - 1)] = annex;
943 // Everything the fast readings know about the sample kAnnexWindow - 1
944 // frames back.
945 T fast = alignSample_[(w + kAlignRecent - (kAnnexWindow - 1)) & (kAlignRecent - 1)];
946 for (int j = 0; j < kAnnexWindow; ++j)
947 fast = std::max(fast, alignAnnex_[(w + kAlignRecent - j) & (kAlignRecent - 1)]); // NaN is ignored
948 alignFast_[w] = fast;
949 T peak = alignFast_[(w + kAlignRing - kAlignFast) & (kAlignRing - 1)];
950 peak = std::max(peak, std::max(slow, std::max(alignSlow_[0], alignSlow_[1])));
951 alignSlow_[1] = alignSlow_[0];
952 alignSlow_[0] = slow;
953 return peak;
954 }
955
957 void resetHighAlignment() noexcept
958 {
959 std::fill(std::begin(alignSample_), std::end(alignSample_), T(0));
960 std::fill(std::begin(alignAnnex_), std::end(alignAnnex_), T(0));
961 std::fill(std::begin(alignFast_), std::end(alignFast_), T(0));
962 alignSlow_[0] = alignSlow_[1] = T(0);
963 alignFrame_ = 0;
964 }
965
972 {
973 const int nCh = std::min(numChannels_, static_cast<int>(delayLines_.size()));
974 if (!tpAnalyzer_ || tpHighChannels_.size() < static_cast<size_t>(nCh)) return;
975 for (int ch = 0; ch < nCh; ++ch)
976 tpHighChannels_[static_cast<size_t>(ch)] = {};
978 // Covers the first-stage kernel and the two short stages behind it.
979 constexpr int kChunks = (TpAnalyzer::kTaps + 2 * kChunk - 1) / kChunk;
980 T block[kChunk];
981 for (int c = kChunks; c > 0; --c)
982 {
983 std::fill(chunkPeak_, chunkPeak_ + kChunk, T(0));
984 std::fill(chunkAnnex_, chunkAnnex_ + kChunk, T(0));
985 std::fill(chunkSlow_, chunkSlow_ + kChunk, T(0));
986 for (int ch = 0; ch < nCh; ++ch)
987 {
988 const auto& line = delayLines_[static_cast<size_t>(ch)];
989 for (int i = 0; i < kChunk; ++i)
990 {
991 block[i] = line.read(c * kChunk - 1 - i); // oldest first
992 chunkPeak_[i] = std::max(chunkPeak_[i], std::abs(block[i])); // NaN is ignored
993 }
994 tpAnalyzer_->process(tpHighChannels_[static_cast<size_t>(ch)], block, kChunk, chunkSlow_, chunkAnnex_);
995 }
996 for (int i = 0; i < kChunk; ++i)
998 }
999 }
1000
1004 void seedTruePeakHistory() noexcept
1005 {
1006 const int nCh = std::min(numChannels_, static_cast<int>(delayLines_.size()));
1007 if (tpChannels_.size() < static_cast<size_t>(nCh)) return;
1008 constexpr int kHistory = TpEstimator::kTaps - 1;
1009 for (int ch = 0; ch < nCh; ++ch)
1010 {
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);
1014 state.fill = 0;
1015 state.last = T(0);
1016 }
1017 }
1018
1020 std::vector<typename TpEstimator::Channel> tpChannels_;
1021 std::unique_ptr<TpAnalyzer> tpAnalyzer_;
1022 std::vector<typename TpAnalyzer::Channel> tpHighChannels_;
1023
1031 [[nodiscard]] int lookaheadSamplesFor(T ms, bool truePeak, bool highPrecision, bool points) const noexcept
1032 {
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)));
1036 // Readings at eight points per sample concern the sample kPointDelay
1037 // frames back: that reach goes to the latency, as the high-precision
1038 // true-peak reading's does, and the parameter stays all ramp.
1039 if (!truePeak) return points ? samples + kPointDelay : samples;
1040 return highPrecision ? samples + kTpHighDelay : std::max(samples, kTpMinLookahead);
1041 }
1042
1043 // ---- Readings at eight points per sample (Precision::High) ----------------
1044 //
1045 // A 16-tap Kaiser-windowed sinc per eighth of a sample reads the signal
1046 // between window samples 7 and 8 of the last 16; window sample 8 is the
1047 // sample kPointDelay frames back. The eight points of frame n are, in time
1048 // order, x(n - 8 + s / 8) for s = 1 .. 8, the last being that sample.
1049 static constexpr int kSteps = 8;
1050 static constexpr int kPointTaps = 16;
1051 static constexpr int kPointDelay = 7;
1052 static constexpr double kPointBeta = 9.0;
1053 static constexpr double kHoldTolerance = 1.0011520;
1054 static_assert(kPointDelay < kTpHighDelay, "the prepared delay covers the points' reach");
1055
1058 inline void readPoints(T x, int ch, T* points) noexcept
1059 {
1060 T* h = pointHist_[ch];
1061 int& at = pointAt_[ch];
1062 h[at] = x;
1063 h[at + kPointTaps] = x;
1064 const T* window = &h[at + 1];
1065 at = (at + 1) & (kPointTaps - 1);
1066 for (int p = 0; p < kSteps - 1; ++p)
1067 points[p] = std::max(points[p], std::abs(simd::dotProduct(pointPhase_[p], window, kPointTaps))); // NaN is ignored
1068 points[kSteps - 1] = std::max(points[kSteps - 1], std::abs(window[kPointTaps / 2]));
1069 }
1070
1074 void seedPointHistory(bool fromDelayLines) noexcept
1075 {
1076 const int nCh = std::min(numChannels_, static_cast<int>(delayLines_.size()));
1077 for (int ch = 0; ch < kMaxChannels; ++ch)
1078 {
1079 std::fill(std::begin(pointHist_[ch]), std::end(pointHist_[ch]), T(0));
1080 pointAt_[ch] = 0;
1081 if (!fromDelayLines || ch >= nCh) continue;
1082 T scratch[kSteps] = {};
1083 for (int k = kPointTaps - 1; k >= 0; --k)
1084 readPoints(delayLines_[static_cast<size_t>(ch)].read(k), ch, scratch);
1085 }
1086 std::fill(std::begin(pendingPoints_), std::end(pendingPoints_), T(0));
1087 }
1088
1092 inline void applyLookaheadTarget() noexcept
1093 {
1094 const bool isp = truePeakEnabled_.load(std::memory_order_relaxed);
1095 const bool high = isp && truePeakPrecision_.load(std::memory_order_relaxed) == 1;
1096 // A reading that was not running holds stale history: refill it from
1097 // the delay lines before it is used.
1098 if (isp && high && !(ispApplied_ && tpHighApplied_))
1100 else if (isp && !high && !(ispApplied_ && !tpHighApplied_))
1102 ispApplied_ = isp;
1103 tpHighApplied_ = high;
1104 const bool points = !isp && precision_.load(std::memory_order_relaxed) == 1;
1105 if (points != pointsApplied_)
1106 {
1107 // The histories hold steps of the other precision: the gain
1108 // computer continues from the gain in effect.
1109 if (points) seedPointHistory(true);
1110 pointsApplied_ = points;
1112 }
1113 lookaheadSamples_ = lookaheadSamplesFor(lookaheadMs_.load(std::memory_order_relaxed), isp, high, points);
1114 latencySamples_ = latencyFor(lookaheadSamples_, isp, high, points);
1116 }
1117
1121 [[nodiscard]] int latencyFor(int lookahead, bool truePeak, bool highPrecision, bool points) const noexcept
1122 {
1123 const T maxMs = maxLookaheadMs_.load(std::memory_order_relaxed);
1124 return (maxMs > T(0)) ? std::max(lookahead, lookaheadSamplesFor(maxMs, truePeak, highPrecision, points))
1125 : lookahead;
1126 }
1127
1132 inline void syncKeptLatency() noexcept
1133 {
1134 const bool want = latencySamples_ > lookaheadSamples_;
1135 if (want && !kept_)
1136 {
1137 for (int i = 0; i < gainSpan_; ++i) gainLine_.push(currentGain_);
1139 kept_ = true;
1140 }
1141 else if (!want && kept_ && latencyCurrent_ <= lookaheadCurrent_)
1142 {
1143 kept_ = false;
1144 }
1145 }
1146
1152 [[nodiscard]] inline T heldGain(int look, int& delay) noexcept
1153 {
1154 const T target = static_cast<T>(latencySamples_);
1155 if (latencyCurrent_ < target) latencyCurrent_ += T(1);
1156 else if (latencyCurrent_ > target) latencyCurrent_ -= T(1);
1157 delay = std::max(static_cast<int>(latencyCurrent_), look);
1158 gainLine_.push(currentGain_);
1159 return gainLine_.read(delay - look);
1160 }
1161
1162 // ---- Gain computer ------------------------------------------------------
1163 //
1164 // r[n] = min(1, ceiling / peak[n]) is the gain sample n requires. With a
1165 // lookahead of L samples the audio sample x[p] leaves the delay line at
1166 // p + L, and the applied gain there is the double moving average of the
1167 // released envelope e over [p + L - span, p + L]. e never exceeds the
1168 // sliding minimum h[n] = min(r[n - W + 1 .. n]) with W = L + 1 + hold,
1169 // so every e in that window is at or below r[p] whenever span <= L: the
1170 // ceiling holds by construction, and each peak's reduction is held for
1171 // the hold time after it has passed. In ISP mode a reading at n covers
1172 // x[n - kTpDelay .. n] (the long estimator's interval sits kTpDelay - 1
1173 // samples back, the BS.1770 estimate inside that range), so the span
1174 // shrinks by kTpDelay to cover the earliest of them. With the
1175 // high-precision reading the peak of frame n concerns x[n - kTpHighDelay]
1176 // alone (alignHighReadings()), so the span shrinks by kTpHighDelay, the
1177 // lookahead is longer by as much and W spans the ramp only: e in
1178 // [p + kTpHighDelay, p + L] is at or below what x[p] requires.
1179
1183 {
1184 if (histSize_ == 0) return;
1185 // Everything below counts steps: one per sample, or kSteps with the
1186 // readings at eight points per sample (all lengths in samples times
1187 // kSteps, the gain heard being the one at each sample's last step).
1188 const int S = pointsApplied_ ? kSteps : 1;
1189 stepsPerSample_ = S;
1190 const int L = std::clamp(lookaheadSamples_, 1, histSize_ / kSteps - 3);
1191 const int isp = ispApplied_ ? (tpHighApplied_ ? kTpHighDelay : kTpDelay)
1192 : (pointsApplied_ ? kPointDelay : 0);
1193 const int span = std::max(0, L - isp); // (a - 1) + (b - 1), in samples
1194 // EveryPeak: the hold is part of the sliding minimum. Deepest: the
1195 // minimum spans the lookahead and the hold counter does the rest.
1196 // The high-precision peaks arrive aligned, kTpHighDelay frames after
1197 // the sample each concerns, and the points kPointDelay frames after
1198 // theirs, so their minimum only spans the ramp.
1199 const bool everyPeak = lastHoldMode_ == 1;
1200 const int window = (tpHighApplied_ || pointsApplied_) ? span : L;
1201 holdLen_ = std::min(S * window + 1 + (everyPeak ? S * holdSamples_ : 0), holdHistSize_ - 1);
1202 counterHold_ = everyPeak ? 0 : S * holdSamples_;
1203 const int spanSteps = S * span;
1204 boxA_ = spanSteps / 2 + 1;
1205 boxB_ = spanSteps - (boxA_ - 1) + 1;
1206 invBoxA_ = 1.0 / static_cast<double>(boxA_);
1207 invBoxB_ = 1.0 / static_cast<double>(boxB_);
1210
1211 // Rebuild the running sums and the hold from the stored history
1212 // (O(L), only on a configuration change), so the new windows are
1213 // exact from the next frame on.
1214 resumBoxes();
1216 }
1217
1219 DSPARK_NOINLINE void resumBoxes() noexcept
1220 {
1221 sum1_ = 0.0;
1222 for (int k = 0; k < boxA_; ++k)
1223 sum1_ += eHist_[static_cast<size_t>((frame_ - 1 - k) & histMask_)];
1224 sum2_ = 0.0;
1225 for (int k = 0; k < boxB_; ++k)
1226 sum2_ += avgHist_[static_cast<size_t>((frame_ - 1 - k) & histMask_)];
1227 }
1228
1236 DSPARK_NOINLINE void restartHoldBlock(int64_t firstFrame) noexcept
1237 {
1238 double m = 1.0;
1239 sufMin_[static_cast<size_t>(holdLen_)] = 1.0; // empty suffix
1240 for (int j = holdLen_ - 1; j >= 0; --j)
1241 {
1242 m = std::min(m, rHist_[static_cast<size_t>((firstFrame + j) & holdMask_)]);
1243 sufMin_[static_cast<size_t>(j)] = m;
1244 }
1245 blockPos_ = 0;
1246 prefixMin_ = 1.0;
1247 }
1248
1250 void resetGainComputer() noexcept
1251 {
1252 std::fill(eHist_.begin(), eHist_.end(), 1.0);
1253 std::fill(avgHist_.begin(), avgHist_.end(), 1.0);
1254 std::fill(rHist_.begin(), rHist_.end(), 1.0);
1255 std::fill(sufMin_.begin(), sufMin_.end(), 1.0);
1256 blockPos_ = 0;
1257 prefixMin_ = 1.0;
1258 frame_ = 0;
1259 envelope_ = 1.0;
1260 holdLeft_ = 0;
1261 sum1_ = static_cast<double>(boxA_);
1262 sum2_ = static_cast<double>(boxB_);
1263 sinceResum_ = 0;
1264 currentGain_ = T(1);
1265 }
1266
1269 void restartGainComputerAt(double g) noexcept
1270 {
1271 if (!(g >= 0.0 && g <= 1.0)) g = 1.0;
1272 std::fill(eHist_.begin(), eHist_.end(), g);
1273 std::fill(avgHist_.begin(), avgHist_.end(), g);
1274 std::fill(rHist_.begin(), rHist_.end(), g);
1275 std::fill(sufMin_.begin(), sufMin_.end(), g);
1276 blockPos_ = 0;
1277 prefixMin_ = g;
1278 envelope_ = g;
1279 holdLeft_ = 0;
1281 }
1282
1284 inline void advanceGain(T peak, T ceiling, bool adaptive, T relMs) noexcept
1285 {
1286 // min(1, ceiling / peak) written as the ratio against the larger of
1287 // the two: the same value bit for bit (the quotient when the peak is
1288 // over the ceiling, exactly 1 otherwise, and 1 for a NaN peak), with
1289 // no minimum left for a compiler to turn into a branch on
1290 // peak > ceiling, which is data-dependent and mispredicts constantly
1291 // under limiting. A zero ceiling over silence gives 0 / 0; the minima
1292 // below ignore a NaN, which is what a required gain of 1 does.
1293 stepGain(static_cast<double>(ceiling / std::max(ceiling, peak)), adaptive, relMs);
1294 }
1295
1298 inline void advanceGainPoints(const T* points, T ceiling, bool adaptive, T relMs) noexcept
1299 {
1300 for (int s = 0; s < kSteps; ++s)
1301 stepGain(static_cast<double>(ceiling / std::max(ceiling, points[s])), adaptive, relMs);
1302 }
1303
1305 inline void stepGain(double required, bool adaptive, T relMs) noexcept
1306 {
1307
1308 // Exact minimum of r over the last holdLen_ frames (see restartHoldBlock()).
1309 rHist_[static_cast<size_t>(frame_ & holdMask_)] = required;
1310 prefixMin_ = std::min(prefixMin_, required);
1311 const double held = std::min(sufMin_[static_cast<size_t>(blockPos_ + 1)], prefixMin_);
1312 if (++blockPos_ == holdLen_)
1314
1315 // Release: the envelope follows reductions at once (the moving
1316 // averages below shape the attack) and recovers with the one-pole.
1317 // min() selects between the two without a data-dependent branch.
1318 double coeff = static_cast<double>(releaseCoeff_);
1319 if (adaptive)
1320 {
1321 // Program-dependent release: up to 3x slower after sustained
1322 // limiting. 1 / (1 + fs * tau) avoids std::exp per sample.
1323 T baseFactor = T(1);
1324 if (limitingDuration_ > 0)
1325 {
1326 const T durationMs = static_cast<T>(limitingDuration_) * T(1000) * invSampleRate_
1327 / static_cast<T>(stepsPerSample_);
1328 baseFactor = T(1) + std::min(durationMs / T(100), T(2));
1329 }
1330 coeff = 1.0 / (1.0 + sampleRate_ * stepsPerSample_ * static_cast<double>(relMs * baseFactor) / 1000.0);
1331 }
1332 // Hold (Deepest mode): a frame that pushes the envelope down (or keeps
1333 // it down) restarts the count; until it runs out the envelope does not
1334 // rise. In EveryPeak mode counterHold_ is 0 and the sliding minimum
1335 // above already holds every peak.
1336 // At Precision::High a crest within kHoldTolerance of the reduction
1337 // held counts as keeping it down: readings of equal crests differ by
1338 // their interpolation error, and which of them restarted the hold
1339 // would decide when the gain rises (Standard compares exactly).
1340 if (held <= envelope_ * holdSlack_) holdLeft_ = counterHold_;
1341 else if (holdLeft_ > 0) { --holdLeft_; coeff = 0.0; }
1342 envelope_ = std::min(held, envelope_ + coeff * (held - envelope_));
1343 // Program memory: count every frame on which a peak in the hold
1344 // window asks for reduction (counting only frames where the envelope
1345 // was still falling missed sustained limiting, which barely ever pushes
1346 // the envelope lower, so the release never slowed).
1347 limitingDuration_ = (held < 0.999) ? std::min(limitingDuration_ + 1, maxLimitSamples_ * stepsPerSample_)
1348 : (envelope_ > 0.999 ? 0 : limitingDuration_);
1349
1350 // Two cascaded moving averages (lengths boxA_, boxB_): an S-shaped,
1351 // click-free ramp spanning exactly the window the hold covers.
1352 const size_t w = static_cast<size_t>(frame_ & histMask_);
1353 eHist_[w] = envelope_;
1354 const double avg1 = detail::advanceBoxAverage(envelope_,
1355 eHist_[static_cast<size_t>((frame_ - boxA_) & histMask_)], sum1_, invBoxA_);
1356 avgHist_[w] = avg1;
1357 (void)detail::advanceBoxAverage(avg1,
1358 avgHist_[static_cast<size_t>((frame_ - boxB_) & histMask_)], sum2_, invBoxB_);
1359 ++frame_;
1360
1361 // Periodic exact re-summation keeps the running sums drift-free.
1362 if (++sinceResum_ >= kResumPeriod)
1363 {
1364 sinceResum_ = 0;
1365 resumBoxes();
1366 }
1367
1368 currentGain_ = static_cast<T>(std::min(sum2_ * invBoxB_, 1.0));
1369 }
1370
1371 // Fast-path synchronization for atomic variables. The linear ceiling is
1372 // only recomputed when the dB parameter actually changed (skips the pow).
1373 inline void syncParameters() noexcept
1374 {
1375 const T ceilDb = ceilingDb_.load(std::memory_order_relaxed);
1376 if (ceilDb != lastCeilingDb_)
1377 {
1378 lastCeilingDb_ = ceilDb;
1379 ceilingSmooth_.setTargetValue(decibelsToGain(ceilDb));
1380 }
1381
1382 const T relMs = std::max(releaseMs_.load(std::memory_order_relaxed), T(1));
1383 if (relMs != lastReleaseMs_)
1384 {
1385 lastReleaseMs_ = relMs;
1387 }
1388
1389 const T holdMs = holdMs_.load(std::memory_order_relaxed);
1390 const int holdMode = holdMode_.load(std::memory_order_relaxed);
1391 if (holdMs != lastHoldMs_ || holdMode != lastHoldMode_)
1392 {
1393 const bool resize = holdMode != lastHoldMode_ || holdMode == 1;
1394 lastHoldMs_ = holdMs;
1395 lastHoldMode_ = holdMode;
1397 if (resize) configureGainComputer(); // the window holds the hold (EveryPeak)
1399 }
1400 }
1401
1402 inline void updateHoldSamples() noexcept
1403 {
1404 holdSamples_ = std::clamp(static_cast<int>(std::lround(std::min(sampleRate_ * static_cast<double>(lastHoldMs_) / 1000.0, 1.0e8))),
1405 0, maxHoldSamples_);
1406 }
1407
1408 inline void updateReleaseCoefficient() noexcept
1409 {
1410 if (sampleRate_ > 0 && lastReleaseMs_ > T(0))
1411 releaseCoeff_ = T(1) - std::exp(T(-1) / (static_cast<T>(sampleRate_ * stepsPerSample_)
1412 * lastReleaseMs_ / T(1000)));
1413 }
1414
1417 [[nodiscard]] inline T applySafetyClipper(T out, T clipCeil) const noexcept
1418 {
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));
1423
1424 const T hardCeil = clipCeil * T(1.05);
1425 if (std::abs(out) > hardCeil)
1426 out = std::clamp(out, -hardCeil, hardCeil);
1427
1428 return out;
1429 }
1430
1431 bool prepared_ = false;
1432 double sampleRate_ = 48000.0;
1433 T invSampleRate_ = T(1.0 / 48000.0);
1436 int maxLimitSamples_ = 96000;
1437
1438 std::atomic<T> ceilingDb_ { T(-0.3) };
1439 std::atomic<T> releaseMs_ { T(100) };
1440 std::atomic<T> holdMs_ { T(10) };
1441 std::atomic<T> lookaheadMs_ { T(2) };
1442 std::atomic<bool> lookaheadDirty_ { false };
1443 std::atomic<bool> truePeakEnabled_ { false };
1444 std::atomic<bool> adaptiveRelease_ { false };
1445 std::atomic<bool> safetyClipEnabled_ { false };
1446
1448 T lastCeilingDb_ = T(-0.3);
1449
1452 T lastHoldMs_ = T(-1);
1454 int maxHoldSamples_ = 2400;
1456 int holdLeft_ = 0;
1458 std::atomic<int> holdMode_ { 0 };
1459 std::atomic<int> truePeakPrecision_ { 0 };
1460 bool ispApplied_ = false;
1461 bool tpHighApplied_ = false;
1462 std::atomic<int> precision_ { 0 };
1463 bool pointsApplied_ = false;
1465 double holdSlack_ = 1.0;
1471
1477 std::atomic<T> publishedGain_ { T(1) };
1480
1481 // Gain computer (see advanceGain()): sliding minimum, released envelope
1482 // and the two moving averages, all in double (recursive state).
1483 static constexpr int kResumPeriod = 1 << 16;
1484 int histSize_ = 0;
1485 int histMask_ = 0;
1487 int holdMask_ = 0;
1488 std::vector<double> eHist_;
1489 std::vector<double> avgHist_;
1490 std::vector<double> rHist_;
1491 std::vector<double> sufMin_;
1492 int blockPos_ = 0;
1493 double prefixMin_ = 1.0;
1494 int64_t frame_ = 0;
1495 double envelope_ = 1.0;
1496 double sum1_ = 1.0;
1497 double sum2_ = 1.0;
1498 int boxA_ = 1;
1499 int boxB_ = 1;
1500 double invBoxA_ = 1.0;
1501 double invBoxB_ = 1.0;
1502 int holdLen_ = 97;
1504 T pendingPeak_ = T(0);
1505 T pendingAnnex_ = T(0);
1506 T pendingSlow_ = T(0);
1507
1508 // High-precision alignment (see alignHighReadings()).
1512 T alignSlow_[2] = {};
1513 int alignFrame_ = 0;
1514
1515 // processBlock() chunk scratch (see its three passes).
1522
1524
1525 // Per-sample path caches (advanced on channel 0, reused by later channels).
1526 T sampleCeiling_ = T(0.96605);
1530
1531 // A latency kept for the lookahead (setMaxLookahead()).
1532 std::atomic<T> maxLookaheadMs_ { T(0) };
1535 bool kept_ = false;
1536 int gainSpan_ = 0;
1538
1539 std::vector<RingBuffer<T>> delayLines_;
1540};
1541
1542} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
High-performance brickwall lookahead limiter.
Definition Limiter.h:127
void setLookahead(T ms) noexcept
Sets the lookahead time dynamically.
Definition Limiter.h:539
void prepare(double sampleRate, int numChannels=2, double initialLookaheadMs=-1.0)
Allocates memory and prepares the limiter for processing.
Definition Limiter.h:149
void setRelease(T ms) noexcept
Sets the base release time.
Definition Limiter.h:521
T latencyCurrent_
Its smoothed value while kept.
Definition Limiter.h:1534
T alignSlow_[2]
Last two analyzer readings.
Definition Limiter.h:1512
int latencySamples_
Delay the audio is asked to have (audio thread).
Definition Limiter.h:1533
std::vector< double > rHist_
Required-gain history.
Definition Limiter.h:1490
T chunkPoints_[kChunk][kSteps]
processBlock() points per frame (loudest channel).
Definition Limiter.h:1469
bool isAdaptiveReleaseEnabled() const noexcept
Definition Limiter.h:790
double envelope_
Definition Limiter.h:1495
std::atomic< T > lookaheadMs_
Definition Limiter.h:1441
T processSample(T input, int channel) noexcept
Processes a single sample of one channel.
Definition Limiter.h:389
T getGainReductionDb() const noexcept
Current gain reduction in dB (metering).
Definition Limiter.h:822
T lookaheadCurrent_
Smoothed read offset (glides on live changes).
Definition Limiter.h:1479
int64_t frame_
Definition Limiter.h:1494
void stepGain(double required, bool adaptive, T relMs) noexcept
Definition Limiter.h:1305
int chunkLook_[kChunk]
Definition Limiter.h:1521
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
Definition Limiter.h:847
~Limiter()=default
static constexpr int kTpMinLookahead
Leaves at least a 16-sample ramp.
Definition Limiter.h:890
int maxHoldSamples_
Hold length of kMaxHoldMs.
Definition Limiter.h:1454
void prepare(const AudioSpec &spec)
Prepares from AudioSpec (unified API).
Definition Limiter.h:249
T getMaxLookahead() const noexcept
Latency kept for the lookahead in milliseconds (0: none; see setMaxLookahead()).
Definition Limiter.h:573
std::vector< typename TpAnalyzer::Channel > tpHighChannels_
Per channel history of the high-precision reading.
Definition Limiter.h:1022
T alignAnnex_[kAlignRecent]
Recent Annex 2 readings.
Definition Limiter.h:1510
T sampleGainNow_
Gain heard in the frame.
Definition Limiter.h:1529
bool kept_
The gain is being held back.
Definition Limiter.h:1535
static constexpr int kAlignRecent
Power of two holding kAnnexWindow frames.
Definition Limiter.h:911
RingBuffer< T > gainLine_
Gains waiting for the audio they belong to.
Definition Limiter.h:1537
T pointPhase_[kSteps - 1][kPointTaps]
Interpolation phases (prepare()).
Definition Limiter.h:1466
static constexpr int kTpDelay
Samples a reading reaches back.
Definition Limiter.h:889
int maxLimitSamples_
Adaptive-release duration cap (2 s).
Definition Limiter.h:1436
static constexpr int kPointDelay
Samples the points reach back.
Definition Limiter.h:1051
void configureGainComputer() noexcept
Definition Limiter.h:1182
void setSafetyClip(bool enabled) noexcept
Enables the post-limiter soft-knee safety clipper. RT-Safe.
Definition Limiter.h:786
std::atomic< int > holdMode_
Definition Limiter.h:1458
void resetGainComputer() noexcept
Definition Limiter.h:1250
bool ispApplied_
Detection mode the gain computer is sized for.
Definition Limiter.h:1460
int lastHoldMode_
Applied HoldMode (0 Deepest, 1 EveryPeak).
Definition Limiter.h:1457
std::atomic< bool > lookaheadDirty_
Definition Limiter.h:1442
void advanceGain(T peak, T ceiling, bool adaptive, T relMs) noexcept
Definition Limiter.h:1284
T chunkCeiling_[kChunk]
Definition Limiter.h:1519
void syncParameters() noexcept
Definition Limiter.h:1373
void setPrecision(Precision precision) noexcept
Selects how finely the gain computer works (see Precision). RT-Safe.
Definition Limiter.h:701
std::atomic< bool > truePeakEnabled_
Definition Limiter.h:1443
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
Definition Limiter.h:829
int getLatency() const noexcept
Reports the processing latency (the lookahead) in samples.
Definition Limiter.h:806
T alignFast_[kAlignRing]
Fast readings per sample, waiting for the analyzer.
Definition Limiter.h:1511
bool pointsApplied_
Readings at eight points per sample applied (sample-peak mode).
Definition Limiter.h:1463
int blockPos_
Position inside the current hold block.
Definition Limiter.h:1492
void seedPointHistory(bool fromDelayLines) noexcept
Definition Limiter.h:1074
T pendingPeak_
Other channels' peaks for the next processSample() frame.
Definition Limiter.h:1504
void advanceGainPoints(const T *points, T ceiling, bool adaptive, T relMs) noexcept
Definition Limiter.h:1298
T alignSample_[kAlignRecent]
Recent sample peaks.
Definition Limiter.h:1509
std::atomic< bool > safetyClipEnabled_
Definition Limiter.h:1445
std::unique_ptr< TpAnalyzer > tpAnalyzer_
High-precision kernels and scratch (prepare()).
Definition Limiter.h:1021
void reset() noexcept
Resets the internal state (delays, gain reduction). RT-Safe.
Definition Limiter.h:473
void updateReleaseCoefficient() noexcept
Definition Limiter.h:1408
SmoothedValue< T > ceilingSmooth_
Definition Limiter.h:1447
double invBoxB_
Definition Limiter.h:1501
int lookaheadSamples_
Audio-side lookahead (consumed from lookaheadMs_).
Definition Limiter.h:1435
static constexpr int kPointTaps
Taps of the interpolation.
Definition Limiter.h:1050
TruePeakPrecision getTruePeakPrecision() const noexcept
Definition Limiter.h:648
std::atomic< int > precision_
Published Precision (0 Standard, 1 High).
Definition Limiter.h:1462
T applySafetyClipper(T out, T clipCeil) const noexcept
Definition Limiter.h:1417
std::atomic< int > truePeakPrecision_
Published TruePeakPrecision (0 Standard, 1 High).
Definition Limiter.h:1459
int chunkDelay_[kChunk]
Delay of the audio per frame (the lookahead, or the latency kept).
Definition Limiter.h:1523
T chunkAnnex_[kChunk]
Definition Limiter.h:1516
int holdLeft_
Hold samples left before the release may act.
Definition Limiter.h:1456
T pendingPoints_[kSteps]
Other channels' points for the next processSample() frame.
Definition Limiter.h:1470
int latencyFor(int lookahead, bool truePeak, bool highPrecision, bool points) const noexcept
Definition Limiter.h:1121
std::vector< double > eHist_
Released envelope history.
Definition Limiter.h:1488
void applyLookaheadTarget() noexcept
Definition Limiter.h:1092
void setTruePeak(bool enabled) noexcept
Enables ISP true-peak detection. RT-Safe.
Definition Limiter.h:596
int counterHold_
Hold-counter restart value (Deepest mode).
Definition Limiter.h:1455
T pendingAnnex_
The same for their Annex 2 readings (high precision).
Definition Limiter.h:1505
std::vector< double > sufMin_
Suffix minima of the last complete hold block (+1 empty).
Definition Limiter.h:1491
bool isSafetyClipEnabled() const noexcept
Definition Limiter.h:791
void detectTruePeak(const T *x, int n, int ch, T *peak, T *annex, T *slow) noexcept
Definition Limiter.h:923
static constexpr double kPointBeta
Kaiser beta of the interpolation.
Definition Limiter.h:1052
int holdSamples_
Hold length in samples.
Definition Limiter.h:1453
TpEstimator tpEstimator_
Kernel and phase scratch.
Definition Limiter.h:1019
std::vector< RingBuffer< T > > delayLines_
Definition Limiter.h:1539
std::atomic< T > releaseMs_
Definition Limiter.h:1439
void setAdaptiveRelease(bool enabled) noexcept
Enables program-dependent adaptive release. RT-Safe. The release time grows with how long peaks have ...
Definition Limiter.h:716
static constexpr int kChunk
Definition Limiter.h:874
int pointAt_[kMaxChannels]
Next write position in it.
Definition Limiter.h:1468
void restartGainComputerAt(double g) noexcept
Definition Limiter.h:1269
int sampleDelayNow_
Delay of the audio for the frame.
Definition Limiter.h:1528
void readPoints(T x, int ch, T *points) noexcept
Definition Limiter.h:1058
T heldGain(int look, int &delay) noexcept
Definition Limiter.h:1152
int stepsPerSample_
Steps of the gain computer per sample (1 or kSteps).
Definition Limiter.h:1464
void resetHighAlignment() noexcept
Definition Limiter.h:957
static constexpr int kResumPeriod
Definition Limiter.h:1483
std::atomic< T > maxLookaheadMs_
Latency kept (0: none).
Definition Limiter.h:1532
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an AudioBufferView in-place.
Definition Limiter.h:265
static constexpr double kHoldTolerance
0.01 dB: crests that close restart the hold (Precision::High).
Definition Limiter.h:1053
double prefixMin_
Running minimum of the current hold block.
Definition Limiter.h:1493
int histMask_
Moving-average histories (lookahead).
Definition Limiter.h:1485
static constexpr int kAnnexWindow
Samples one Annex 2 reading is formed from.
Definition Limiter.h:908
int alignFrame_
Frame counter modulo kAlignRing.
Definition Limiter.h:1513
void setMaxLookahead(T ms) noexcept
Keeps a latency for the lookahead to move inside.
Definition Limiter.h:564
T pointHist_[kMaxChannels][2 *kPointTaps]
Mirrored interpolation history per channel.
Definition Limiter.h:1467
T chunkSlow_[kChunk]
Definition Limiter.h:1517
double holdSlack_
Factor of the held reduction a crest restarts the hold within.
Definition Limiter.h:1465
DSPARK_NOINLINE void restartHoldBlock(int64_t firstFrame) noexcept
Definition Limiter.h:1236
T getLookahead() const noexcept
Definition Limiter.h:792
void updateHoldSamples() noexcept
Definition Limiter.h:1402
std::atomic< bool > adaptiveRelease_
Definition Limiter.h:1444
static constexpr int kAlignFast
Delay of the fast readings.
Definition Limiter.h:909
void syncKeptLatency() noexcept
Definition Limiter.h:1132
void setHoldMode(HoldMode mode) noexcept
Selects the hold behaviour (see HoldMode). RT-Safe.
Definition Limiter.h:768
bool tpHighApplied_
High-precision reading applied (implies ispApplied_).
Definition Limiter.h:1461
std::vector< typename TpEstimator::Channel > tpChannels_
Per channel history.
Definition Limiter.h:1020
void seedTruePeakHistory() noexcept
Definition Limiter.h:1004
int gainSpan_
Length of the gain line.
Definition Limiter.h:1536
HoldMode getHoldMode() const noexcept
Definition Limiter.h:774
bool isTruePeakEnabled() const noexcept
Definition Limiter.h:789
T alignHighReadings(T samplePeak, T annex, T slow) noexcept
Definition Limiter.h:936
static constexpr T kSafetyClipCeiling
-0.3 dBFS
Definition Limiter.h:871
T pendingSlow_
The same for their analyzer readings (high precision).
Definition Limiter.h:1506
std::atomic< T > publishedGain_
Definition Limiter.h:1477
static constexpr int kSteps
Steps of the gain computer per sample at Precision::High.
Definition Limiter.h:1049
std::atomic< T > holdMs_
Definition Limiter.h:1440
static constexpr double kMaxLookaheadMs
Definition Limiter.h:869
void setHold(T ms) noexcept
Sets how long the reduction is held after the last peak that asked for it, before the release starts....
Definition Limiter.h:735
T getHold() const noexcept
Definition Limiter.h:742
static constexpr int kMaxChannels
Definition Limiter.h:868
void seedHighTruePeakHistory() noexcept
Definition Limiter.h:971
std::atomic< T > ceilingDb_
Definition Limiter.h:1438
void setCeiling(T dB) noexcept
Sets the absolute output ceiling.
Definition Limiter.h:508
Precision getPrecision() const noexcept
Definition Limiter.h:708
DSPARK_NOINLINE void resumBoxes() noexcept
Definition Limiter.h:1219
T chunkGain_[kChunk]
Definition Limiter.h:1520
static constexpr int kTpHighDelay
Samples a high-precision reading reaches back.
Definition Limiter.h:907
double sampleRate_
Definition Limiter.h:1432
double invBoxA_
Definition Limiter.h:1500
T chunkPeak_[kChunk]
Definition Limiter.h:1518
std::vector< double > avgHist_
First moving-average output history.
Definition Limiter.h:1489
T lastCeilingDb_
Change detector for the ceiling pow skip.
Definition Limiter.h:1448
static constexpr double kMaxHoldMs
Definition Limiter.h:870
void setTruePeakPrecision(TruePeakPrecision precision) noexcept
Selects the true-peak reading (see TruePeakPrecision). RT-Safe.
Definition Limiter.h:641
int lookaheadSamplesFor(T ms, bool truePeak, bool highPrecision, bool points) const noexcept
Definition Limiter.h:1031
static constexpr int kAlignRing
Power of two above kAlignFast.
Definition Limiter.h:910
int holdMask_
Required-gain history (lookahead + hold).
Definition Limiter.h:1487
int limitingDuration_
Definition Limiter.h:1478
Power-of-two circular buffer with compile-time interpolated read access.
Definition RingBuffer.h:64
Zero-allocation parameter smoother for real-time audio.
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
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
Definition BoxAverage.h:12
float dotProduct(const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int count) noexcept
Computes the dot product of two arrays.
Definition SimdOps.h:644
Main namespace for the DSPark framework.
T decibelsToGain(T dB, T minusInfinityDb=T(-100)) noexcept
Converts a value in decibels to linear gain.
Definition DspMath.h:77
T gainToDecibels(T gain, T minusInfinityDb=T(-100)) noexcept
Converts a linear gain value to decibels.
Definition DspMath.h:92
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
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
History of one channel (each stage's kernel span plus one chunk).
History of one channel (kTaps - 1 samples plus one chunk).