DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
TruePeakDetector.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
52#include "DspMath.h"
53#include "SimdOps.h"
54
55#include <algorithm>
56#include <array>
57#include <cassert>
58#include <cmath>
59#include <limits>
60#include <numbers>
61#include <type_traits>
62
63namespace dspark {
64
80template <FloatType T, int MaxChannels = 16>
82{
83public:
85 void reset() noexcept
86 {
87 for (auto& s : states_)
88 s = {};
89 }
90
102 [[nodiscard]] T processSample(T sample, int channel) noexcept
103 {
104 assert(channel >= 0 && channel < MaxChannels);
105 // Release-safe clamp to the nearest valid channel. (Redirecting an
106 // out-of-range index to channel 0 would corrupt that channel's
107 // history with a foreign stream.)
108 channel = std::clamp(channel, 0, MaxChannels - 1);
109 return processState(sample, states_[static_cast<size_t>(channel)]);
110 }
111
118 [[nodiscard]] T getTailPeak(int channel) const noexcept
119 {
120 assert(channel >= 0 && channel < MaxChannels);
121 channel = std::clamp(channel, 0, MaxChannels - 1);
122 auto state = states_[static_cast<size_t>(channel)];
123 T peak = T(0);
124 for (int i = 0; i < kTaps - 1; ++i)
125 peak = std::max(peak, processState(T(0), state));
126 return peak;
127 }
128
130 [[nodiscard]] static constexpr int getLatency() noexcept { return kTaps / 2; }
131
140 [[nodiscard]] static constexpr int getTaps() noexcept { return kTaps; }
141
143 [[nodiscard]] static constexpr int getPhases() noexcept { return kPhases; }
144
156 [[nodiscard]] static constexpr const T* getReversedPhase(int phase) noexcept
157 {
158 return kReversedCoeffs[static_cast<size_t>(std::clamp(phase, 0, kPhases - 1))].data();
159 }
160
161private:
162 static constexpr int kTaps = 12;
163 static constexpr int kPhases = 4;
164 static constexpr int kHistSize = 16;
165 static constexpr int kHistMask = kHistSize - 1;
166
167 struct State
168 {
171 T history[kHistSize * 2] = {};
172 int writePos = 0;
173 };
174
175 [[nodiscard]] static T processState(T sample, State& tp) noexcept
176 {
177 // Mirroring makes the latest FIR window contiguous for the shared dot product.
178 tp.history[static_cast<size_t>(tp.writePos)] = sample;
179 tp.history[static_cast<size_t>(tp.writePos + kHistSize)] = sample;
180 const int newest = tp.writePos;
181 tp.writePos = (tp.writePos + 1) & kHistMask;
182 const T* window = &tp.history[static_cast<size_t>(newest + kHistSize - (kTaps - 1))];
183 T peak = std::abs(sample);
184#if defined(DSPARK_SIMD_SSE2) || defined(DSPARK_SIMD_NEON)
185 if constexpr (std::is_same_v<T, float>)
186 {
187 // The four phases are four lanes: one pass over the 12 taps with
188 // the transposed table, then one horizontal max (3.6x faster than
189 // four horizontal dot products). The sums run in tap order, so the
190 // reading differs from the scalar path only by rounding (< 2e-7).
191#if defined(DSPARK_SIMD_SSE2)
192 __m128 acc = _mm_setzero_ps();
193 for (int j = 0; j < kTaps; ++j)
194 acc = _mm_add_ps(acc, _mm_mul_ps(_mm_load_ps(kVertical.c[j]), _mm_set1_ps(window[j])));
195 acc = _mm_andnot_ps(_mm_set1_ps(-0.0f), acc);
196 __m128 m = _mm_max_ps(acc, _mm_movehl_ps(acc, acc));
197 m = _mm_max_ss(m, _mm_shuffle_ps(m, m, 1));
198 const float a = _mm_cvtss_f32(m);
199#else
200 float32x4_t acc = vdupq_n_f32(0.0f);
201 for (int j = 0; j < kTaps; ++j)
202 acc = vaddq_f32(acc, vmulq_f32(vld1q_f32(kVertical.c[j]), vdupq_n_f32(window[j])));
203 acc = vabsq_f32(acc);
204 float32x2_t m = vpmax_f32(vget_low_f32(acc), vget_high_f32(acc));
205 m = vpmax_f32(m, m);
206 const float a = vget_lane_f32(m, 0);
207#endif
208 return (a > peak) ? a : peak;
209 }
210#endif
211 for (int phase = 0; phase < kPhases; ++phase)
212 {
213 const T interp = simd::dotProduct(
214 kReversedCoeffs[static_cast<size_t>(phase)].data(), window, kTaps);
215 const T a = std::abs(interp);
216 if (a > peak) peak = a;
217 }
218 return peak;
219 }
220
231 [[nodiscard]] static constexpr std::array<std::array<T, kTaps>, kPhases>
232 buildReversedPhaseTable() noexcept
233 {
234 constexpr double kAnnex2[kPhases][kTaps] = {
235 { 0.0017089843750, 0.0109863281250, -0.0196533203125,
236 0.0332031250000, -0.0594482421875, 0.1373291015625,
237 0.9721679687500, -0.1022949218750, 0.0476074218750,
238 -0.0266113281250, 0.0148925781250, -0.0083007812500 },
239 { -0.0291748046875, 0.0292968750000, -0.0517578125000,
240 0.0891113281250, -0.1665039062500, 0.4650878906250,
241 0.7797851562500, -0.2003173828125, 0.1015625000000,
242 -0.0582275390625, 0.0330810546875, -0.0189208984375 },
243 { -0.0189208984375, 0.0330810546875, -0.0582275390625,
244 0.1015625000000, -0.2003173828125, 0.7797851562500,
245 0.4650878906250, -0.1665039062500, 0.0891113281250,
246 -0.0517578125000, 0.0292968750000, -0.0291748046875 },
247 { -0.0083007812500, 0.0148925781250, -0.0266113281250,
248 0.0476074218750, -0.1022949218750, 0.9721679687500,
249 0.1373291015625, -0.0594482421875, 0.0332031250000,
250 -0.0196533203125, 0.0109863281250, 0.0017089843750 },
251 };
252
253 std::array<std::array<T, kTaps>, kPhases> result {};
254 for (int phase = 0; phase < kPhases; ++phase)
255 for (int k = 0; k < kTaps; ++k)
256 result[static_cast<size_t>(phase)][static_cast<size_t>(kTaps - 1 - k)]
257 = static_cast<T>(kAnnex2[phase][k]);
258 return result;
259 }
260
263 static constexpr std::array<std::array<T, kTaps>, kPhases> kReversedCoeffs =
264 buildReversedPhaseTable();
265
268 struct VerticalTable { alignas(16) float c[kTaps][kPhases]; };
269 [[nodiscard]] static constexpr VerticalTable buildVerticalTable() noexcept
270 {
271 VerticalTable v {};
272 for (int j = 0; j < kTaps; ++j)
273 for (int p = 0; p < kPhases; ++p)
274 v.c[j][p] = static_cast<float>(kReversedCoeffs[static_cast<size_t>(p)][static_cast<size_t>(j)]);
275 return v;
276 }
277 static constexpr VerticalTable kVertical = buildVerticalTable();
278
279 std::array<State, MaxChannels> states_ {};
280};
281
282namespace detail {
283
284// Kaiser-windowed sinc interpolation phase (beta `beta`, cut at Nyquist),
285// normalised to unity at DC: `out[j]` multiplies window sample j of a
286// `Count`-sample window and the phase reads the point `frac` (0 < frac < 1)
287// past window sample Count / 2 - 1. Designed in double.
288template <int Count, typename T>
289inline void designSincPhase(T* out, double beta, double frac) noexcept
290{
291 constexpr double kPi = std::numbers::pi_v<double>;
292 const auto besselI0 = [](double x) noexcept {
293 double sum = 1.0, term = 1.0;
294 for (int k = 1; k < 64; ++k)
295 {
296 const double h = x / (2.0 * k);
297 term *= h * h;
298 sum += term;
299 if (term < 1e-17 * sum) break;
300 }
301 return sum;
302 };
303 const double norm = besselI0(beta);
304 constexpr double halfTaps = Count / 2;
305 double taps[Count];
306 double sum = 0.0;
307 for (int j = 0; j < Count; ++j)
308 {
309 // Distance from tap j to the interpolation point.
310 const double d = static_cast<double>(j) - (halfTaps - 1.0) - frac;
311 const double sinc = std::sin(kPi * d) / (kPi * d);
312 const double u = d / halfTaps;
313 const double w = besselI0(beta * std::sqrt(std::max(0.0, 1.0 - u * u))) / norm;
314 taps[j] = sinc * w;
315 sum += taps[j];
316 }
317 for (int j = 0; j < Count; ++j)
318 out[j] = static_cast<T>(taps[j] / sum);
319}
320
321// Raises m to the vertex of the parabola through (a, b, c) when b is a
322// local maximum of the magnitude there (never by more than a quarter of
323// |b|). No multiply feeds an add, so the result does not depend on
324// floating-point contraction.
325template <typename T>
326[[nodiscard]] inline T refineVertex(T a, T b, T c, T m) noexcept
327{
328 const T ab = std::abs(b);
329 const T d = (a + c) - (b + b);
330 if (ab >= std::abs(a) && ab >= std::abs(c) && b * d < T(0))
331 {
332 const T q = c - a;
333 const T v = std::abs(b - (q * q) / (T(8) * d));
334 if (v > m) m = v;
335 }
336 return m;
337}
338
339// The reading of position i of a 4x grid: the largest magnitude among the
340// five grid points of the interval from sample s[i] to s[i + 1] (its quarter,
341// half and three-quarter points at q[i], h[i] and t[i + 1]) and among the
342// crests refined around the four inner ones, the first with the
343// three-quarter point before the interval, t[i].
344template <typename T>
345[[nodiscard]] inline T gridReading(const T* s, const T* q, const T* h, const T* t, int i) noexcept
346{
347 const T a0 = s[i], a4 = s[i + 1];
348 const T y0 = t[i], y1 = q[i], y2 = h[i], y3 = t[i + 1];
349 T m = std::max(std::max(std::abs(a0), std::abs(a4)),
350 std::max(std::abs(y2), std::max(std::abs(y1), std::abs(y3))));
351 m = refineVertex(y0, a0, y1, m);
352 m = refineVertex(a0, y1, y2, m);
353 m = refineVertex(y1, y2, y3, m);
354 m = refineVertex(y2, y3, a4, m);
355 return m;
356}
357
358// Raises m to the two crests that point u of an 8x grid completes. The grid
359// alternates the points a[u] and e[u + 1] (e[0] is the point before a[0], and
360// a[-1] the one before that): the crests are refined around e[u], between
361// a[u - 1] and a[u], and around a[u], between e[u] and e[u + 1].
362template <typename T>
363[[nodiscard]] inline T eighthCrests(const T* a, const T* e, int u, T m) noexcept
364{
365 m = refineVertex(a[u - 1], e[u], a[u], m);
366 return refineVertex(e[u], a[u], e[u + 1], m);
367}
368
369// Raises peak[i] to the reading of sample i of an 8x grid, for i in
370// [first, n): the largest magnitude among the sample's four pairs of points
371// (4 i .. 4 i + 3) and the crests they complete (eighthCrests()), the two
372// points before each pair carried from one to the next. Magnitudes that are
373// not numbers are ignored.
374template <typename T>
375inline void raiseToEighthSamples(const T* a, const T* e, T* peak, int first, int n) noexcept
376{
377 if (first >= n) return;
378 T p0 = a[4 * first - 1], p1 = e[4 * first];
379 for (int i = first; i < n; ++i)
380 {
381 T m = T(0);
382 for (int k = 0; k < 4; ++k)
383 {
384 const T x = a[4 * i + k];
385 const T y = e[4 * i + k + 1];
386 m = std::max(m, std::abs(x));
387 m = std::max(m, std::abs(y));
388 m = refineVertex(p0, p1, x, m);
389 m = refineVertex(p1, x, y, m);
390 p0 = x;
391 p1 = y;
392 }
393 peak[i] = std::max(peak[i], m);
394 }
395}
396
397// The reading loops on vectors, compiled for the build's baseline
398// (detail/TruePeakKernels.inl). A compiler vectorises the scalar loop only
399// when it may run the vertex's division and comparisons for positions the
400// source skips, which those that honour floating-point traps do not.
401namespace truepeak {
402template <typename T, int W> using Vec = simd::Vec<T, W>;
403template <typename T> inline constexpr int kWide = simd::kVecWidth<T>;
404template <typename T> inline constexpr int kNarrow = simd::kVecNarrowWidth<T>;
405#include "detail/TruePeakKernels.inl"
406} // namespace truepeak
407
408} // namespace detail
409} // namespace dspark
410
411#if defined(DSPARK_SIMD_DISPATCH_AVX2)
412// The same loops compiled for AVX2+FMA, run when isRuntimeDispatchActive().
413DSPARK_SIMD_AVX2_BEGIN
414namespace dspark {
415namespace detail {
416namespace truepeak {
417namespace avx2 {
418template <typename T, int W> using Vec = simd::avx2::Vec<T, W>;
419template <typename T> inline constexpr int kWide = simd::avx2::kVecWidth<T>;
420template <typename T> inline constexpr int kNarrow = simd::avx2::kVecNarrowWidth<T>;
421#include "detail/TruePeakKernels.inl"
422} // namespace avx2
423} // namespace truepeak
424} // namespace detail
425} // namespace dspark
426DSPARK_SIMD_AVX2_END
427#endif
428
429namespace dspark {
430namespace detail {
431
432// The reading loops (detail/TruePeakKernels.inl) on the kernel copy in use:
433// the AVX2+FMA one when the run-time dispatch is active. Every copy returns
434// the same values, bit for bit, so a stream may change copy between calls.
435template <typename T>
437{
439 static void raiseToReadings(const T* s, const T* q, const T* h, const T* t, T* peak, int n) noexcept
440 {
441#if defined(DSPARK_SIMD_DISPATCH_AVX2)
443 {
444 truepeak::avx2::raiseToReadings(s, q, h, t, peak, n);
445 return;
446 }
447#endif
448 truepeak::raiseToReadings(s, q, h, t, peak, n);
449 }
450
452 [[nodiscard]] static T largestFiniteReading(const T* s, const T* q, const T* h, const T* t, int n,
453 T start) noexcept
454 {
455#if defined(DSPARK_SIMD_DISPATCH_AVX2)
457 return truepeak::avx2::largestFiniteReading(s, q, h, t, n, start);
458#endif
459 return truepeak::largestFiniteReading(s, q, h, t, n, start);
460 }
461
463 static void raiseToMagnitudes(T* dst, const T* src, int n) noexcept
464 {
465#if defined(DSPARK_SIMD_DISPATCH_AVX2)
467 {
468 truepeak::avx2::raiseToMagnitudes(dst, src, n);
469 return;
470 }
471#endif
472 truepeak::raiseToMagnitudes(dst, src, n);
473 }
474
476 [[nodiscard]] static T largestFiniteMagnitude(const T* v, int count, T start) noexcept
477 {
478#if defined(DSPARK_SIMD_DISPATCH_AVX2)
480 return truepeak::avx2::largestFiniteMagnitude(v, count, start);
481#endif
482 return truepeak::largestFiniteMagnitude(v, count, start);
483 }
484
487 static void raiseToEighthReadings(const T* a, const T* e, T* peak, int n) noexcept
488 {
489#if defined(DSPARK_SIMD_DISPATCH_AVX2)
491 {
492 truepeak::avx2::raiseToEighthReadings(a, e, peak, n);
493 return;
494 }
495#endif
496 truepeak::raiseToEighthReadings(a, e, peak, n);
497 }
498
501 [[nodiscard]] static T largestFiniteEighthCrest(const T* a, const T* e, int points, T start) noexcept
502 {
503#if defined(DSPARK_SIMD_DISPATCH_AVX2)
505 return truepeak::avx2::largestFiniteEighthCrest(a, e, points, start);
506#endif
507 return truepeak::largestFiniteEighthCrest(a, e, points, start);
508 }
509};
510
511} // namespace detail
512
557template <FloatType T>
559{
560public:
561 static constexpr int kTaps = 64;
562 static constexpr int kPhases = 3;
563 static constexpr int kChunk = 128;
564
566 struct Channel
567 {
568 T history[kTaps - 1 + kChunk] = {};
569 int fill = 0;
570 T last = T(0);
571 };
572
575 {
576 for (int p = 0; p < kPhases; ++p)
577 detail::designSincPhase<kTaps>(coeffs_[p], 8.0, static_cast<double>(p + 1) / 4.0);
578 }
579
581 [[nodiscard]] static constexpr int getDelay() noexcept { return kTaps / 2 + 1; }
582
597 void process(Channel& channel, const T* x, int n, T* peak, bool annex2Guard = false) noexcept
598 {
599 assert(n >= 1 && n <= kChunk);
600 n = std::clamp(n, 0, kChunk);
601 const T* base = appendAndInterpolate(channel, x, n);
602
603 if (annex2Guard)
604 {
605 // BS.1770 Annex 2 phases over the newest kAnnexTaps samples.
606 const T* annexBase = base + (kTaps - kAnnexTaps);
607 for (int p = 0; p < kAnnexPhases; ++p)
608 {
609 simd::firCorrelate(annexBase, Annex::getReversedPhase(p), kAnnexTaps, annex_, n, T(1));
610 Loops::raiseToMagnitudes(peak, annex_, n); // NaN is ignored
611 }
612 }
613 Loops::raiseToReadings(base + (kTaps / 2 - 1), quarter_, half_, threeQuarter(), peak, n); // NaN is ignored
614 channel.fill += n;
615 }
616
634 [[nodiscard]] T processMax(Channel& channel, const T* x, int n, T atLeast) noexcept
635 {
636 assert(n >= 1 && n <= kChunk);
637 n = std::clamp(n, 0, kChunk);
638 const T* base = appendAndInterpolate(channel, x, n);
639 channel.fill += n;
640 // Grid points of the chunk: the samples x[i - 32] .. x[i - 31] and the
641 // three interpolated points between them.
642 const T* const samples = base + (kTaps / 2 - 1);
643 T gridMax = Loops::largestFiniteMagnitude(samples, n + 1, T(0));
644 gridMax = Loops::largestFiniteMagnitude(quarter_, n, gridMax);
645 gridMax = Loops::largestFiniteMagnitude(half_, n, gridMax);
646 gridMax = Loops::largestFiniteMagnitude(threeQuarter() + 1, n, gridMax);
647 if (!(gridMax * T(1.25) > atLeast))
648 return gridMax;
649 return Loops::largestFiniteReading(samples, quarter_, half_, threeQuarter(), n, gridMax);
650 }
651
662 [[nodiscard]] T getTailPeak(const Channel& channel) noexcept
663 {
664 Channel copy = channel;
665 T zeros[kTaps] = {};
666 T peak[kTaps] = {};
667 process(copy, zeros, kTaps, peak);
668 T result = T(0);
669 for (const T v : peak) result = std::max(result, v);
670 return result;
671 }
672
673private:
674 using Annex = TruePeakDetector<T, 1>;
675 using Loops = detail::TruePeakLoops<T>;
676 static constexpr int kAnnexTaps = Annex::getTaps();
677 static constexpr int kAnnexPhases = Annex::getPhases();
678 static_assert(kAnnexTaps <= kTaps, "the BS.1770 window must fit the estimator history");
679 static_assert(kTaps <= kChunk, "the tail is measured in one call");
680
684 const T* appendAndInterpolate(Channel& channel, const T* x, int n) noexcept
685 {
686 T* h = channel.history;
687 if (channel.fill + n > kChunk)
688 {
689 std::copy(h + channel.fill, h + channel.fill + (kTaps - 1), h); // keep the last kTaps - 1 samples
690 channel.fill = 0;
691 }
692 std::copy(x, x + n, h + (kTaps - 1) + channel.fill);
693 const T* base = h + channel.fill;
694 simd::firCorrelate(base, coeffs_[0], kTaps, quarter_, n, T(1));
695 simd::firCorrelate(base, coeffs_[1], kTaps, half_, n, T(1));
696 // The three-quarter point before the chunk sits ahead of the chunk's,
697 // so every interval reads the one before it from the same array.
698 T* const t = threeQuarter();
699 t[0] = channel.last;
700 simd::firCorrelate(base, coeffs_[2], kTaps, t + 1, n, T(1));
701 channel.last = t[n];
702 return base;
703 }
704
709 static constexpr int kLead = 32 / static_cast<int>(sizeof(T));
710 [[nodiscard]] T* threeQuarter() noexcept { return threeQuarter_ + (kLead - 1); }
711
712 T coeffs_[kPhases][kTaps] = {};
713 T quarter_[kChunk] = {};
714 T half_[kChunk] = {};
715 T threeQuarter_[kLead + kChunk] = {};
716 T annex_[kChunk] = {};
717};
718
763template <FloatType T>
765{
766 static constexpr int kTaps2 = 16;
767 static constexpr int kTaps3 = 8;
768
769public:
770 static constexpr int kTaps = 512;
771 static constexpr int kChunk = 128;
772
774 struct Channel
775 {
776 T input[kTaps - 1 + kChunk] = {};
777 T twice[kTaps2 - 1 + 2 * kChunk] = {};
778 T fourTimes[kTaps3 - 1 + 4 * kChunk] = {};
779 int fill = 0;
780 T previous[2] = {};
781 };
782
785 {
786 detail::designSincPhase<kTaps>(coeffs1_, 7.0, 0.5);
787 detail::designSincPhase<kTaps2>(coeffs2_, 9.0, 0.5);
788 detail::designSincPhase<kTaps3>(coeffs3_, 9.0, 0.5);
789 }
790
794 [[nodiscard]] static constexpr int getDelay() noexcept
795 {
796 return kDelay;
797 }
798
818 [[nodiscard]] T processMax(Channel& channel, const T* x, int n, T atLeast) noexcept
819 {
820 assert(n >= 1 && n <= kChunk);
821 n = std::clamp(n, 0, kChunk);
822 if (n == 0) return T(0);
823 const T* fourth = advance(channel, x, n); // 4n points of the 4x stream
824 const int points = 4 * n;
825 constexpr T kFinite = std::numeric_limits<T>::max();
826 T gridMax = Loops::largestFiniteMagnitude(fourth, points, T(0));
827 gridMax = Loops::largestFiniteMagnitude(eighth() + 1, points, gridMax);
828 // The first crest of the call is centred on the point carried over.
829 const T carried = std::abs(eighth()[0]);
830 const T centres = carried <= kFinite ? std::max(gridMax, carried) : gridMax;
831 if (!(centres * T(1.25) > atLeast))
832 return gridMax;
833 return Loops::largestFiniteEighthCrest(fourth, eighth(), points, gridMax);
834 }
835
859 void process(Channel& channel, const T* x, int n, T* peak, T* annex2 = nullptr) noexcept
860 {
861 assert(n >= 1 && n <= kChunk);
862 n = std::clamp(n, 0, kChunk);
863 if (n == 0) return;
864 const T* fourth = advance(channel, x, n); // 4n points of the 4x stream
865
866 if (annex2 != nullptr)
867 {
868 // BS.1770 Annex 2 phases over the newest kAnnexTaps input samples.
869 const T* annexBase = channel.input + (channel.fill - n) + (kTaps - kAnnexTaps);
870 for (int p = 0; p < kAnnexPhases; ++p)
871 {
872 simd::firCorrelate(annexBase, Annex::getReversedPhase(p), kAnnexTaps, scratch_, n, T(1));
873 Loops::raiseToMagnitudes(annex2, scratch_, n); // NaN is ignored
874 }
875 }
876 Loops::raiseToEighthReadings(fourth, eighth(), peak, n); // NaN is ignored
877 }
878
889 [[nodiscard]] T getTailPeak(const Channel& channel) noexcept
890 {
891 Channel copy = channel;
892 constexpr T zeros[kChunk] = {};
893 T result = T(0);
894 for (int left = kTailSamples; left > 0; left -= kChunk)
895 {
896 const T peak = processMax(copy, zeros, std::min(left, kChunk), result);
897 if (peak > result) result = peak;
898 }
899 return result;
900 }
901
902private:
903 using Annex = TruePeakDetector<T, 1>;
904 using Loops = detail::TruePeakLoops<T>;
905 static constexpr int kAnnexTaps = Annex::getTaps();
906 static constexpr int kAnnexPhases = Annex::getPhases();
907 static_assert(kAnnexTaps <= kTaps, "the BS.1770 window must fit the first stage history");
908
910 static constexpr int kDelay = kTaps / 2 + kTaps2 / 4 + kTaps3 / 8;
913 static constexpr int kTailSamples = kTaps / 2 + kDelay + 1;
914 static_assert(kTaps % 2 == 0 && kTaps2 % 2 == 0 && kTaps3 % 2 == 0, "midpoint kernels are even");
915
920 const T* advance(Channel& channel, const T* x, int n) noexcept
921 {
922 if (channel.fill + n > kChunk)
923 {
924 // Keep the last kernel span of each stage.
925 const int f = channel.fill;
926 std::copy(channel.input + f, channel.input + f + (kTaps - 1), channel.input);
927 std::copy(channel.twice + 2 * f, channel.twice + 2 * f + (kTaps2 - 1), channel.twice);
928 std::copy(channel.fourTimes + 4 * f, channel.fourTimes + 4 * f + (kTaps3 - 1), channel.fourTimes);
929 channel.fill = 0;
930 }
931 const int f = channel.fill;
932
933 // Stage 1: the midpoint of every interval, from the input.
934 std::copy(x, x + n, channel.input + (kTaps - 1) + f);
935 const T* in = channel.input + f;
936 simd::firCorrelate(in, coeffs1_, kTaps, scratch_, n, T(1));
937 T* twice = channel.twice + (kTaps2 - 1) + 2 * f;
938 for (int i = 0; i < n; ++i)
939 {
940 twice[2 * i] = in[i + kTaps / 2 - 1];
941 twice[2 * i + 1] = scratch_[i];
942 }
943
944 // Stage 2: the midpoints of the 2x stream.
945 const T* two = channel.twice + 2 * f;
946 simd::firCorrelate(two, coeffs2_, kTaps2, scratch_, 2 * n, T(1));
947 T* four = channel.fourTimes + (kTaps3 - 1) + 4 * f;
948 for (int t = 0; t < 2 * n; ++t)
949 {
950 four[2 * t] = two[t + kTaps2 / 2 - 1];
951 four[2 * t + 1] = scratch_[t];
952 }
953
954 // Stage 3: the midpoints of the 4x stream. The eighth point before
955 // the chunk sits ahead of the chunk's, so every crest reads the
956 // points before it from the same arrays (the 4x point before the
957 // chunk is in the history).
958 const T* base = channel.fourTimes + 4 * f;
959 T* const e = eighth();
960 e[0] = channel.previous[1];
961 simd::firCorrelate(base, coeffs3_, kTaps3, e + 1, 4 * n, T(1));
962 const T* fourth = base + (kTaps3 / 2 - 1);
963 channel.previous[0] = fourth[4 * n - 1];
964 channel.previous[1] = e[4 * n];
965 channel.fill += n;
966 return fourth;
967 }
968
973 static constexpr int kLead = 32 / static_cast<int>(sizeof(T));
974 [[nodiscard]] T* eighth() noexcept { return eighth_ + (kLead - 1); }
975
976 T coeffs1_[kTaps] = {};
977 T coeffs2_[kTaps2] = {};
978 T coeffs3_[kTaps3] = {};
979 T scratch_[2 * kChunk] = {};
980 T eighth_[kLead + 4 * kChunk] = {};
981};
982
983} // namespace dspark
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.
void process(Channel &channel, const T *x, int n, T *peak, T *annex2=nullptr) noexcept
Appends samples to a channel and raises each peak[i] to the reading of the 8x grid points x[i] comple...
TruePeakAnalyzer() noexcept
Designs the three interpolation stages.
T getTailPeak(const Channel &channel) noexcept
Peak of the zero-extended tail of a finite programme.
T processMax(Channel &channel, const T *x, int n, T atLeast) noexcept
Appends samples to a channel and returns the largest finite reading among the 8x grid points they com...
Per-channel 4x-oversampled inter-sample peak estimator.
static constexpr int getTaps() noexcept
Input samples one estimate is computed from (taps per phase).
static constexpr int getLatency() noexcept
Group delay of the interpolation FIR in samples (per phase).
static constexpr int getPhases() noexcept
Number of interpolation phases (4x over-sampling).
T getTailPeak(int channel) const noexcept
Measures the zero-extended interpolation tail of one channel. Evaluates getTaps()-1 zero frames on a ...
T processSample(T sample, int channel) noexcept
Feeds one sample and returns the local true-peak estimate.
static constexpr const T * getReversedPhase(int phase) noexcept
One official interpolation phase, row reversed, for callers that run the interpolator as a block FIR.
void reset() noexcept
Clears all channel histories. Safe on the audio thread.
Block-based reading of the band-limited reconstruction peak.
static constexpr int getDelay() noexcept
Input samples one reading reaches back.
T getTailPeak(const Channel &channel) noexcept
Peak of the zero-extended tail of a finite programme.
static constexpr int kPhases
Quarter, half and three-quarter points.
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.
TruePeakEstimator() noexcept
Designs the interpolation phases.
T processMax(Channel &channel, const T *x, int n, T atLeast) noexcept
Appends samples to a channel and returns the largest finite reading among them (0 if none),...
T gridReading(const T *s, const T *q, const T *h, const T *t, int i) noexcept
T eighthCrests(const T *a, const T *e, int u, T m) noexcept
T refineVertex(T a, T b, T c, T m) noexcept
void designSincPhase(T *out, double beta, double frac) noexcept
void raiseToEighthSamples(const T *a, const T *e, T *peak, int first, int n) noexcept
bool isRuntimeDispatchActive() noexcept
Whether the AVX2+FMA kernels are selected now (see setRuntimeDispatch()).
Definition SimdOps.h:262
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
void firCorrelate(const T *x, const T *h, int taps, T *DSPARK_RESTRICT y, int n, T gain) noexcept
Block FIR as a valid correlation: y[i] = gain * sum_j h[j] * x[i + j] for i in [0,...
Definition SimdOps.h:1496
Main namespace for the DSPark framework.
History of one channel (each stage's kernel span plus one chunk).
T twice[kTaps2 - 1+2 *kChunk]
2x stream, oldest first.
int fill
Input samples past the history prefix.
T input[kTaps - 1+kChunk]
Input samples, oldest first.
T fourTimes[kTaps3 - 1+4 *kChunk]
4x stream, oldest first.
T previous[2]
Last two points of the 8x grid.
History of one channel (kTaps - 1 samples plus one chunk).
T history[kTaps - 1+kChunk]
Oldest first; see process().
int fill
Samples past the history prefix.
T last
Last three-quarter point.
static T largestFiniteEighthCrest(const T *a, const T *e, int points, T start) noexcept
static void raiseToReadings(const T *s, const T *q, const T *h, const T *t, T *peak, int n) noexcept
Raises peak[i] to gridReading(s, q, h, t, i) for i in [0, n).
static void raiseToMagnitudes(T *dst, const T *src, int n) noexcept
Raises dst[i] to |src[i]| for i in [0, n).
static T largestFiniteMagnitude(const T *v, int count, T start) noexcept
The largest finite magnitude among count values and start.
static void raiseToEighthReadings(const T *a, const T *e, T *peak, int n) noexcept
static T largestFiniteReading(const T *s, const T *q, const T *h, const T *t, int n, T start) noexcept
The largest finite gridReading() of the positions [0, n) and start.