DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
LoudnessMeter.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
42#include "../Core/DspMath.h"
43#include "../Core/AudioSpec.h"
44#include "../Core/AudioBuffer.h"
45#include "../Core/Biquad.h"
46#include "../Core/SimdOps.h"
47#include "../Core/TruePeakDetector.h"
48
49#include <algorithm>
50#include <atomic>
51#include <cmath>
52#include <cstdint>
53#include <limits>
54#include <numbers>
55#include <array>
56#include <type_traits>
57
58namespace dspark {
59
74template <FloatType T>
76{
77public:
85 {
86 std::int64_t committedFrames = 0;
88 int hopFrames = 0;
89 std::uint64_t integratedBlocks = 0;
90 std::uint64_t rangeBlocks = 0;
91 };
92
99 [[nodiscard]] MeasurementInfo getMeasurementInfo() const noexcept
100 {
101 MeasurementInfo info;
102 if (!prepared_.load(std::memory_order_relaxed)) return info;
103 info.committedFrames = totalCommittedBlocks_ * blockSamples_;
104 info.pendingFrames = currentBlockSamples_;
105 info.hopFrames = blockSamples_;
106 for (int i = 0; i < kNumBins; ++i)
107 {
108 info.integratedBlocks += histogram_[i].load(std::memory_order_relaxed);
109 info.rangeBlocks += lraHistogram_[i].load(std::memory_order_relaxed);
110 }
111 return info;
112 }
113
125 void prepare(double sampleRate, int numChannels = 2) noexcept
126 {
127 (void)numChannels;
128 if (!std::isfinite(sampleRate) || sampleRate <= 0.0) return;
129
130 sampleRate_ = sampleRate;
131
132 computeKWeighting(sampleRate);
133
134 // 100 ms block length (clamped in double before the cast: an absurd
135 // finite rate must not overflow the int conversion)
136 blockSamples_ = static_cast<int>(std::clamp(sampleRate * 0.1, 1.0, 1.0e9));
137
138 reset();
139 prepared_.store(true, std::memory_order_relaxed);
140 }
141
143 void prepare(const AudioSpec& spec) noexcept
144 {
145 prepare(spec.sampleRate, spec.numChannels);
146 }
147
157 {
158 const int nCh = buffer.getNumChannels();
159 const int nS = buffer.getNumSamples();
160 if (nCh >= 2)
161 process(buffer.getChannel(0), buffer.getChannel(1), nS);
162 else if (nCh == 1)
163 process(buffer.getChannel(0), nS);
164 }
165
171 void process(const T* data, int numSamples) noexcept
172 {
173 if (!prepared_.load(std::memory_order_relaxed) || data == nullptr || numSamples <= 0)
174 return;
175
176 truePeakMax_.store(measureTruePeak(data, 0, numSamples,
177 truePeakMax_.load(std::memory_order_relaxed)),
178 std::memory_order_relaxed);
179 // One register holds stage 1 of frame i (lane 0) and stage 2 of frame
180 // i - 1 (lane 1). The first frame's stage 1 and the last frame's
181 // stage 2 run through the same step with the other lane on a copy
182 // that is thrown away, so every frame rounds the same way wherever
183 // a call starts or ends.
184 using L = KLane;
185 using V = typename L::V;
186 const V b0 = L::set(pre_.b0, rlb_.b0), b1 = L::set(pre_.b1, rlb_.b1);
187 const V b2 = L::set(pre_.b2, rlb_.b2), a1 = L::set(pre_.a1, rlb_.a1);
188 const V a2 = L::set(pre_.a2, rlb_.a2);
189 V z1 = L::set(preState_[0].z1, rlbState_[0].z1);
190 V z2 = L::set(preState_[0].z2, rlbState_[0].z2);
191 const auto stageOne = [&](double x) noexcept
192 {
193 V t1 = z1, t2 = z2;
194 const V y = L::step(b0, b1, b2, a1, a2, L::set(x, 0.0), t1, t2);
195 z1 = L::set(L::first(t1), L::second(z1));
196 z2 = L::set(L::first(t2), L::second(z2));
197 return L::first(y);
198 };
199 double pre = stageOne(static_cast<double>(data[0]));
200 // The last pass closes the pipeline: its lane 0 runs on a copy, and
201 // every frame's power is added at this one place.
202 for (int i = 1; i <= numSamples; ++i)
203 {
204 const bool more = i < numSamples;
205 const V kept1 = z1, kept2 = z2;
206 const V y = L::step(b0, b1, b2, a1, a2,
207 L::set(more ? static_cast<double>(data[i]) : 0.0, pre), z1, z2);
208 pre = L::first(y);
209 const double filtered = L::second(y);
210 if (accumulate(filtered * filtered))
211 {
212 // A non-finite block cleared the states: frame i restarts
213 // from them, as it would one stage after the other.
214 z1 = L::set(0.0, 0.0);
215 z2 = L::set(0.0, 0.0);
216 if (more)
217 pre = stageOne(static_cast<double>(data[i]));
218 }
219 else if (!more)
220 {
221 z1 = L::set(L::first(kept1), L::second(z1));
222 z2 = L::set(L::first(kept2), L::second(z2));
223 }
224 }
225 preState_[0] = { L::first(z1), L::first(z2) };
226 rlbState_[0] = { L::second(z1), L::second(z2) };
227 }
228
235 void process(const T* left, const T* right, int numSamples) noexcept
236 {
237 if (!prepared_.load(std::memory_order_relaxed)
238 || left == nullptr || right == nullptr || numSamples <= 0)
239 return;
240
241 const T peakLeft = measureTruePeak(left, 0, numSamples,
242 truePeakMax_.load(std::memory_order_relaxed));
243 truePeakMax_.store(measureTruePeak(right, 1, numSamples, peakLeft), std::memory_order_relaxed);
244 // Two registers, both channels in each: stage 1 of frame i next to
245 // stage 2 of frame i - 1, which has no wait on it. The first frame's
246 // stage 1 and the last frame's stage 2 run through the same steps,
247 // so every frame rounds the same way wherever a call starts or ends.
248 using L = KLane;
249 using V = typename L::V;
250 const V pb0 = L::set(pre_.b0, pre_.b0), pb1 = L::set(pre_.b1, pre_.b1);
251 const V pb2 = L::set(pre_.b2, pre_.b2), pa1 = L::set(pre_.a1, pre_.a1);
252 const V pa2 = L::set(pre_.a2, pre_.a2);
253 const V rb0 = L::set(rlb_.b0, rlb_.b0), rb1 = L::set(rlb_.b1, rlb_.b1);
254 const V rb2 = L::set(rlb_.b2, rlb_.b2), ra1 = L::set(rlb_.a1, rlb_.a1);
255 const V ra2 = L::set(rlb_.a2, rlb_.a2);
256 V pz1 = L::set(preState_[0].z1, preState_[1].z1);
257 V pz2 = L::set(preState_[0].z2, preState_[1].z2);
258 V rz1 = L::set(rlbState_[0].z1, rlbState_[1].z1);
259 V rz2 = L::set(rlbState_[0].z2, rlbState_[1].z2);
260 V pending = L::step(pb0, pb1, pb2, pa1, pa2,
261 L::set(static_cast<double>(left[0]), static_cast<double>(right[0])),
262 pz1, pz2);
263 // The last pass closes the pipeline with stage 2 alone, and every
264 // frame's power is added at this one place.
265 for (int i = 1; i <= numSamples; ++i)
266 {
267 const bool more = i < numSamples;
268 const V k = L::step(rb0, rb1, rb2, ra1, ra2, pending, rz1, rz2);
269 V x {};
270 if (more)
271 {
272 x = L::set(static_cast<double>(left[i]), static_cast<double>(right[i]));
273 pending = L::step(pb0, pb1, pb2, pa1, pa2, x, pz1, pz2);
274 }
275 const double filtL = L::first(k);
276 const double filtR = L::second(k);
277 if (accumulate(filtL * filtL + filtR * filtR))
278 {
279 // A non-finite block cleared the states: frame i restarts
280 // from them, as it would one stage after the other.
281 pz1 = L::set(0.0, 0.0);
282 pz2 = L::set(0.0, 0.0);
283 rz1 = L::set(0.0, 0.0);
284 rz2 = L::set(0.0, 0.0);
285 if (more)
286 pending = L::step(pb0, pb1, pb2, pa1, pa2, x, pz1, pz2);
287 }
288 }
289 preState_[0] = { L::first(pz1), L::first(pz2) };
290 preState_[1] = { L::second(pz1), L::second(pz2) };
291 rlbState_[0] = { L::first(rz1), L::first(rz2) };
292 rlbState_[1] = { L::second(rz1), L::second(rz2) };
293 }
294
299 [[nodiscard]] T getMomentaryLUFS() const noexcept
300 {
301 return calculateLUFSFromBlocks(4);
302 }
303
308 [[nodiscard]] T getShortTermLUFS() const noexcept
309 {
310 return calculateLUFSFromBlocks(30);
311 }
312
319 [[nodiscard]] T getIntegratedLUFS() const noexcept
320 {
321 // Pass 1: Absolute Gate (-70 LUFS)
322 double sumPowerUngated = 0.0;
323 uint64_t countUngated = 0;
324
325 for (int i = 0; i < kNumBins; ++i)
326 {
327 sumPowerUngated += histogramPower_[i].load(std::memory_order_relaxed);
328 countUngated += histogram_[i].load(std::memory_order_relaxed);
329 }
330
331 if (countUngated == 0) return T(-100);
332
333 double meanPowerUngated = sumPowerUngated / countUngated;
334 double ungatedLUFS = powerToLUFS(meanPowerUngated);
335
336 // Pass 2: Relative Gate (-10 LU below ungated mean)
337 double relativeGateLUFS = ungatedLUFS - 10.0;
338 const int relativeGateBin = firstBinAtOrAbove(relativeGateLUFS);
339
340 double sumPowerGated = 0.0;
341 uint64_t countGated = 0;
342
343 for (int i = relativeGateBin; i < kNumBins; ++i)
344 {
345 sumPowerGated += histogramPower_[i].load(std::memory_order_relaxed);
346 countGated += histogram_[i].load(std::memory_order_relaxed);
347 }
348
349 if (countGated == 0) return T(-100);
350
351 return static_cast<T>(powerToLUFS(sumPowerGated / countGated));
352 }
353
363 [[nodiscard]] bool isMeasurementValid() const noexcept
364 {
365 return measurementValid_.load(std::memory_order_relaxed);
366 }
367
384 [[nodiscard]] T getTruePeakDb() const noexcept
385 {
386 return gainToDecibels(truePeakMax_.load(std::memory_order_relaxed));
387 }
388
398 void finalizeTruePeak() noexcept
399 {
400 if (!prepared_.load(std::memory_order_relaxed)) return;
401 T peak = truePeakMax_.load(std::memory_order_relaxed);
402 for (int channel = 0; channel < kMaxChannels; ++channel)
403 {
404 const T tail = static_cast<T>(truePeak_.getTailPeak(tpChannels_[static_cast<size_t>(channel)]));
405 if (std::isfinite(tail))
406 peak = std::max(peak, tail);
407 else
408 invalidateMeasurement();
409 }
410 truePeakMax_.store(peak, std::memory_order_relaxed);
411 }
412
436 [[nodiscard]] T getLoudnessRange() const noexcept
437 {
438 // Pass 1: relative gate from the exact mean energy of the
439 // absolute-gated short-term values.
440 double sumPower = 0.0;
441 uint64_t count = 0;
442 for (int i = 0; i < kNumBins; ++i)
443 {
444 const uint32_t c = lraHistogram_[i].load(std::memory_order_relaxed);
445 if (c > 0)
446 {
447 sumPower += lraEnergy_[i].load(std::memory_order_relaxed);
448 count += c;
449 }
450 }
451 if (count == 0) return T(0);
452
453 // A value takes part when the centre of its 0.005 LU cell clears the
454 // gate (as a block does for the integrated gate).
455 const double relGateLUFS = powerToLUFS(sumPower / static_cast<double>(count)) - 20.0;
456 const int gateCell = firstRangeCellAtOrAbove(relGateLUFS);
457 const int gateBin = gateCell / kRangeCells;
458
459 uint64_t gateCells[kRangeCells];
460 rangeCellCounts(gateBin, gateCells);
461 uint64_t gateBinCount = 0;
462 for (int s = gateCell % kRangeCells; s < kRangeCells; ++s)
463 gateBinCount += gateCells[s];
464
465 // Pass 2: 10th / 95th percentiles above the relative gate.
466 uint64_t gatedCount = gateBinCount;
467 for (int i = gateBin + 1; i < kNumBins; ++i)
468 gatedCount += lraHistogram_[i].load(std::memory_order_relaxed);
469 if (gatedCount == 0) return T(0);
470
471 // Percentiles by the Tech 3342 reference rule: the value of 0-based rank
472 // round((n - 1) * p) among the n gated values. Both ranks are always
473 // measured values - never the gate threshold - and every n is
474 // covered: with one value, or with n equal values, the range is 0.
475 const auto rank10 = static_cast<uint64_t>(std::llround(0.10 * static_cast<double>(gatedCount - 1)));
476 const auto rank95 = static_cast<uint64_t>(std::llround(0.95 * static_cast<double>(gatedCount - 1)));
477
478 // The 0.1 LU bins locate each rank; the bin's 0.005 LU cells place it.
479 auto valueAt = [&](int bin, uint64_t rankInBin) noexcept {
480 uint64_t cells[kRangeCells];
481 const int first = bin == gateBin ? gateCell % kRangeCells : 0;
482 if (bin == gateBin)
483 std::copy(gateCells, gateCells + kRangeCells, cells);
484 else
485 rangeCellCounts(bin, cells);
486 uint64_t seen = 0;
487 int lastFilled = -1;
488 for (int s = first; s < kRangeCells; ++s)
489 {
490 if (cells[s] == 0) continue;
491 lastFilled = s;
492 seen += cells[s];
493 if (seen > rankInBin) break;
494 }
495 // A reader that raced the writer may find the bin count ahead of
496 // its cells: the last filled cell then stands in.
497 const int cell = lastFilled >= 0 ? lastFilled : kRangeCells / 2;
498 return rangeCellCentre(bin * kRangeCells + cell);
499 };
500
501 double p10 = 0.0, p95 = 0.0;
502 uint64_t running = 0;
503 bool have10 = false;
504 for (int i = gateBin; i < kNumBins; ++i)
505 {
506 const uint64_t c = i == gateBin ? gateBinCount
507 : lraHistogram_[i].load(std::memory_order_relaxed);
508 if (c == 0) continue;
509 // `running` values sit below this bin: ranks running .. running+c-1 here.
510 if (!have10 && running + c > rank10)
511 {
512 p10 = valueAt(i, rank10 - running);
513 have10 = true;
514 }
515 if (running + c > rank95)
516 {
517 p95 = valueAt(i, rank95 - running);
518 break;
519 }
520 running += c;
521 }
522 return static_cast<T>(std::max(0.0, p95 - p10));
523 }
524
532 void reset() noexcept
533 {
534 for (int ch = 0; ch < kMaxChannels; ++ch)
535 {
536 preState_[ch] = {};
537 rlbState_[ch] = {};
538 }
539
540 for (auto& power : blockPowers_)
541 power.store(0.0, std::memory_order_relaxed);
542
543 for (auto& bin : histogram_)
544 bin.store(0, std::memory_order_relaxed);
545 for (auto& energy : histogramPower_)
546 energy.store(0.0, std::memory_order_relaxed);
547 for (auto& bin : lraHistogram_)
548 bin.store(0, std::memory_order_relaxed);
549 for (auto& energy : lraEnergy_)
550 energy.store(0.0, std::memory_order_relaxed);
551 for (auto& cell : lraCells_)
552 cell.store(0, std::memory_order_relaxed);
553
554 for (auto& state : tpChannels_)
555 state = {};
556 truePeakMax_.store(T(0), std::memory_order_relaxed);
557
558 blockWritePos_.store(0, std::memory_order_relaxed);
559 totalCommittedBlocks_ = 0;
560 currentBlockPower_ = 0.0;
561 currentBlockSamples_ = 0;
562 measurementValid_.store(true, std::memory_order_relaxed);
563 }
564
565private:
566 static constexpr int kMaxChannels = 2; // Expandable to 8 with proper spatial weighting
567
568 // Histogram specs: -70 LUFS to +30 LUFS with 0.1 resolution = 1000 bins
569 static constexpr double kMinHistogramLUFS = -70.0;
570 static constexpr double kMaxHistogramLUFS = 30.0;
571 static constexpr double kBinWidth = 0.1;
572 static constexpr int kNumBins = 1000;
573
574 // Loudness range cells: each 0.1 LU bin split in 20 cells of 0.005 LU
575 // (16-bit counts; the bin's 32-bit count stays authoritative).
576 static constexpr int kRangeCells = 20;
577 static constexpr double kRangeCellWidth = kBinWidth / kRangeCells;
578 static constexpr int kNumRangeCells = kNumBins * kRangeCells;
579 static constexpr uint16_t kRangeCellMax = std::numeric_limits<uint16_t>::max();
580
581 // True-peak analysis runs in single precision whatever T is: the reading's
582 // own error (0.004 dB on steady tones) is three orders above float
583 // rounding, and a double kernel costs twice as much.
584 using TruePeakReader = TruePeakAnalyzer<float>;
585 // The most samples one reader call takes.
586 static constexpr int kTruePeakChunk = TruePeakReader::kChunk;
587
588 // Filters state (Forced to double to prevent DF2T precision issues)
589 struct BiquadState { double z1 = 0.0, z2 = 0.0; };
590 struct BiquadCoeff { double b0 = 1.0, b1 = 0.0, b2 = 0.0, a1 = 0.0, a2 = 0.0; };
591
592 void computeKWeighting(double sr)
593 {
594 // Pre-warped analog parameterization that reproduces the official
595 // ITU-R BS.1770-5 table 1/2 coefficients at 48 kHz to machine
596 // precision (verified: max error 8.9e-16). This is an exact 48 kHz
597 // parameterization, not a claim of an identical response at every
598 // rate: the retained 997 Hz cascade gains are +0.691014 dB at 48 kHz,
599 // +0.693776 dB at 44.1 kHz and +0.663943 dB at 192 kHz. Residual
600 // full-band deviation stays below 0.05 dB through 384 kHz and inside
601 // the standard tolerance. The -0.691 constant in powerToLUFS remains
602 // tied to this cascade; an RBJ shelf or a gain-normalized RLB high-pass
603 // reads ~0.26 LU low on the EBU conformance vectors. The design lives
604 // in BiquadCoeffs so every K-weighted measurement shares it.
605 const auto shelf = BiquadCoeffs::makeKWeightingShelf(sr);
606 pre_ = { shelf.b0, shelf.b1, shelf.b2, shelf.a1, shelf.a2 };
607 const auto rlb = BiquadCoeffs::makeKWeightingHighPass(sr);
608 rlb_ = { rlb.b0, rlb.b1, rlb.b2, rlb.a1, rlb.a2 };
609 }
610
616 template <int W, typename D = double> struct KPair
617 {
618 struct V { D a, b; };
619 static V set(D a, D b) noexcept { return { a, b }; }
620 static D first(V v) noexcept { return v.a; }
621 static D second(V v) noexcept { return v.b; }
622 static V step(V b0, V b1, V b2, V a1, V a2, V x, V& z1, V& z2) noexcept
623 {
624 const V y { b0.a * x.a + z1.a, b0.b * x.b + z1.b };
625 z1 = { b1.a * x.a - a1.a * y.a + z2.a, b1.b * x.b - a1.b * y.b + z2.b };
626 z2 = { b2.a * x.a - a2.a * y.a + D(1e-18), b2.b * x.b - a2.b * y.b + D(1e-18) };
627 return y;
628 }
629 };
630 template <typename D> struct KPair<2, D>
631 {
632 using O = simd::Vec<D, 2>;
633 using V = typename O::V;
634 static V set(D a, D b) noexcept { return O::set2(a, b); }
635 static D first(V v) noexcept { return O::lane0(v); }
636 static D second(V v) noexcept { return O::lane1(v); }
637 // No product here feeds a plain addition: where the target fuses
638 // multiply-adds these are fused explicitly, so the compiler has none
639 // left to fuse, and a step whose other lane it drops rounds the same.
640 static V step(V b0, V b1, V b2, V a1, V a2, V x, V& z1, V& z2) noexcept
641 {
642 const V y = O::madd(b0, x, z1);
643 z1 = O::add(O::mulSub(b1, x, a1, y), z2);
644 z2 = O::add(O::mulSub(b2, x, a2, y), O::set1(D(1e-18)));
645 return y;
646 }
647 };
648 using KLane = KPair<simd::kVecDoubleNarrow>;
649
652 [[nodiscard]] bool accumulate(double power) noexcept
653 {
654 currentBlockPower_ += power;
655 if (!std::isfinite(currentBlockPower_))
656 invalidateMeasurement();
657 if (++currentBlockSamples_ >= blockSamples_)
658 return commitBlock();
659 return false;
660 }
661
664 bool commitBlock() noexcept
665 {
666 const double meanPower = currentBlockPower_ / currentBlockSamples_;
667 currentBlockPower_ = 0.0;
668 currentBlockSamples_ = 0;
669
670 // A non-finite block (NaN/Inf fed by the caller) would poison the
671 // sliding window and freeze the histograms forever: the K-filter
672 // recursion never drains a NaN. A meter must report the signal as it
673 // is NOW, so drop the block, clear the filter states and resume
674 // measuring clean on the next one.
675 if (!std::isfinite(meanPower))
676 {
677 invalidateMeasurement();
678 for (int ch = 0; ch < kMaxChannels; ++ch)
679 {
680 preState_[ch] = {};
681 rlbState_[ch] = {};
682 }
683 return true;
684 }
685
686 // Update sliding window ring buffer
687 int currentPos = blockWritePos_.load(std::memory_order_relaxed);
688 blockPowers_[currentPos].store(meanPower, std::memory_order_relaxed);
689
690 int nextPos = (currentPos + 1) % 30; // 30 blocks = 3s max window
691 blockWritePos_.store(nextPos, std::memory_order_release);
692 ++totalCommittedBlocks_;
693
694 // BS.1770-4 integrated gating uses 400 ms blocks with 75% overlap.
695 // With a 100 ms sub-block hop, that is EXACTLY the mean of the last
696 // four sub-blocks committed at every 100 ms step. (Gating raw 100 ms
697 // blocks has higher variance and fails the EBU conformance vectors.)
698 if (totalCommittedBlocks_ >= 4)
699 {
700 double gating400 = meanPower;
701 for (int back = 1; back < 4; ++back)
702 {
703 int idx = (currentPos - back + 30) % 30;
704 gating400 += blockPowers_[idx].load(std::memory_order_relaxed);
705 }
706 gating400 *= 0.25;
707
708 const double lufs = powerToLUFS(gating400);
709 if (!std::isfinite(gating400) || !std::isfinite(lufs))
710 {
711 invalidateMeasurement();
712 }
713 else if (lufs >= kMinHistogramLUFS)
714 {
715 int binIndex = static_cast<int>(std::round((lufs - kMinHistogramLUFS) / kBinWidth));
716 if (binIndex >= kNumBins)
717 invalidateMeasurement();
718 binIndex = std::clamp(binIndex, 0, kNumBins - 1);
719 incrementHistogram(histogram_[binIndex]);
720 auto& energy = histogramPower_[static_cast<size_t>(binIndex)];
721 energy.store(energy.load(std::memory_order_relaxed) + gating400,
722 std::memory_order_relaxed);
723 }
724 }
725
726 // EBU Tech 3342 loudness range: short-term (3 s) values sampled at
727 // 10 Hz - every 100 ms sub-block, the 2.9 s minimum window overlap
728 // Tech 3342 has required since V3 (2016) - absolute-gated at -70 LUFS
729 // into a histogram of 0.005 LU cells, with the exact energy per bin.
730 if (totalCommittedBlocks_ >= 30)
731 {
732 const double stPower = meanPowerOfBlocks(30);
733 const double stLufs = powerToLUFS(stPower);
734 if (!std::isfinite(stPower) || !std::isfinite(stLufs))
735 {
736 invalidateMeasurement();
737 }
738 else if (stLufs >= kMinHistogramLUFS)
739 {
740 const double position = std::floor((stLufs - kMinHistogramLUFS + 0.5 * kBinWidth)
741 / kRangeCellWidth);
742 if (position >= static_cast<double>(kNumRangeCells))
743 invalidateMeasurement();
744 const int cell = static_cast<int>(std::clamp(position, 0.0,
745 static_cast<double>(kNumRangeCells - 1)));
746 const int bin = cell / kRangeCells;
747 if (lraHistogram_[bin].load(std::memory_order_relaxed)
748 == std::numeric_limits<uint32_t>::max())
749 {
750 invalidateMeasurement();
751 }
752 else
753 {
754 auto& cellCount = lraCells_[static_cast<size_t>(cell)];
755 const uint16_t c = cellCount.load(std::memory_order_relaxed);
756 if (c < kRangeCellMax) // a full cell hands the rest to its bin count
757 cellCount.store(static_cast<uint16_t>(c + 1), std::memory_order_relaxed);
758 auto& energy = lraEnergy_[static_cast<size_t>(bin)];
759 energy.store(energy.load(std::memory_order_relaxed) + stPower,
760 std::memory_order_relaxed);
761 lraHistogram_[bin].fetch_add(1, std::memory_order_relaxed);
762 }
763 }
764 }
765 return false;
766 }
767
769 [[nodiscard]] double meanPowerOfBlocks(int numBlocks) const noexcept
770 {
771 double sum = 0.0;
772 const int currentPos = blockWritePos_.load(std::memory_order_acquire);
773 for (int i = 0; i < numBlocks; ++i)
774 {
775 const int idx = (currentPos - 1 - i + 30) % 30;
776 sum += blockPowers_[idx].load(std::memory_order_relaxed);
777 }
778 return sum / numBlocks;
779 }
780
784 void rangeCellCounts(int bin, uint64_t (&out)[kRangeCells]) const noexcept
785 {
786 uint64_t sum = 0;
787 int full = -1;
788 for (int s = 0; s < kRangeCells; ++s)
789 {
790 const uint16_t v = lraCells_[static_cast<size_t>(bin * kRangeCells + s)]
791 .load(std::memory_order_relaxed);
792 out[s] = v;
793 sum += v;
794 if (v == kRangeCellMax && full < 0) full = s;
795 }
796 const uint64_t total = lraHistogram_[static_cast<size_t>(bin)].load(std::memory_order_relaxed);
797 if (full >= 0 && total > sum)
798 out[full] += total - sum;
799 }
800
802 [[nodiscard]] static int firstRangeCellAtOrAbove(double lufs) noexcept
803 {
804 const double position
805 = std::ceil((lufs - kMinHistogramLUFS + 0.5 * kBinWidth) / kRangeCellWidth - 0.5);
806 return static_cast<int>(std::clamp(position, 0.0, static_cast<double>(kNumRangeCells - 1)));
807 }
808
810 [[nodiscard]] static double rangeCellCentre(int cell) noexcept
811 {
812 return kMinHistogramLUFS - 0.5 * kBinWidth + (static_cast<double>(cell) + 0.5) * kRangeCellWidth;
813 }
814
818 [[nodiscard]] T measureTruePeak(const T* x, int channel, int numSamples, T peak) noexcept
819 {
820 auto& state = tpChannels_[static_cast<size_t>(channel)];
821 for (int start = 0; start < numSamples; start += kTruePeakChunk)
822 {
823 const int n = std::min(kTruePeakChunk, numSamples - start);
824 // Only FINITE values join the max-hold: one Inf/NaN sample would
825 // otherwise pin it at +Inf until reset() (the K-filter / histogram
826 // path already self-recovers, so the true peak must too).
827 for (int i = 0; i < n; ++i)
828 {
829 const T a = std::abs(x[start + i]);
830 if (!std::isfinite(a))
831 invalidateMeasurement();
832 else if (a > peak)
833 peak = a;
834 }
835 const T chunkPeak = static_cast<T>(truePeak_.processMax(state, narrow(x + start, n), n, readerFloor(peak)));
836 if (chunkPeak > peak)
837 peak = chunkPeak;
838 }
839 return peak;
840 }
841
844 [[nodiscard]] static float readerFloor(T peak) noexcept
845 {
846 if constexpr (std::is_same_v<T, float>)
847 {
848 return peak;
849 }
850 else
851 {
852 constexpr T kFloatMax = static_cast<T>(std::numeric_limits<float>::max());
853 // Two float steps down: one for the conversion, one for the product.
854 constexpr float kDown = 1.0f - 2.0f * std::numeric_limits<float>::epsilon();
855 return static_cast<float>(std::min(peak, kFloatMax)) * kDown;
856 }
857 }
858
863 [[nodiscard]] const float* narrow(const T* x, int n) noexcept
864 {
865 if constexpr (std::is_same_v<T, float>)
866 {
867 static_cast<void>(n);
868 return x;
869 }
870 else
871 {
872 constexpr T kFloatMax = static_cast<T>(std::numeric_limits<float>::max());
873 for (int i = 0; i < n; ++i)
874 {
875 const T v = x[i];
876 // NaN stays NaN; everything else lands inside float's range.
877 tpNarrow_[i] = static_cast<float>(v > kFloatMax ? kFloatMax : (v < -kFloatMax ? -kFloatMax : v));
878 }
879 return tpNarrow_;
880 }
881 }
882
883 void invalidateMeasurement() noexcept
884 {
885 measurementValid_.store(false, std::memory_order_relaxed);
886 }
887
888 void incrementHistogram(std::atomic<uint32_t>& bin) noexcept
889 {
890 if (bin.load(std::memory_order_relaxed)
891 == std::numeric_limits<uint32_t>::max())
892 {
893 invalidateMeasurement();
894 return;
895 }
896 bin.fetch_add(1, std::memory_order_relaxed);
897 }
898
899 T calculateLUFSFromBlocks(int numBlocks) const noexcept
900 {
901 double sum = 0.0;
902 int currentPos = blockWritePos_.load(std::memory_order_acquire);
903
904 for (int i = 0; i < numBlocks; ++i)
905 {
906 int idx = (currentPos - 1 - i + 30) % 30;
907 sum += blockPowers_[idx].load(std::memory_order_relaxed);
908 }
909
910 return static_cast<T>(powerToLUFS(sum / numBlocks));
911 }
912
915 [[nodiscard]] static int firstBinAtOrAbove(double lufs) noexcept
916 {
917 const double position = std::ceil((lufs - kMinHistogramLUFS) / kBinWidth);
918 return static_cast<int>(std::clamp(position, 0.0, static_cast<double>(kNumBins - 1)));
919 }
920
921 [[nodiscard]] static double powerToLUFS(double meanPower) noexcept
922 {
923 if (meanPower <= 1e-10) return -100.0; // Prevent log10(0)
924 return std::max(-100.0, -0.691 + 10.0 * std::log10(meanPower));
925 }
926
927 double sampleRate_ = 48000.0;
928 std::atomic<bool> prepared_{ false };
929
930 BiquadCoeff pre_, rlb_;
931 BiquadState preState_[kMaxChannels], rlbState_[kMaxChannels];
932
933 int blockSamples_ = 4800;
934 double currentBlockPower_ = 0.0;
935 int currentBlockSamples_ = 0;
936
937 // Concurrency-safe components
938 std::array<std::atomic<double>, 30> blockPowers_;
939 std::atomic<int> blockWritePos_{0};
940 int64_t totalCommittedBlocks_ = 0;
941
942 // Constant-memory histogram for integrated loudness. The count decides the
943 // gates; the energy beside it is the exact sum of the blocks in that bin.
944 std::array<std::atomic<uint32_t>, kNumBins> histogram_;
945 std::array<std::atomic<double>, kNumBins> histogramPower_;
946
947 // EBU Tech 3342 loudness-range histogram (short-term values, 100 ms hop):
948 // per 0.1 LU bin the count, the exact energy and the 0.005 LU cells.
949 std::array<std::atomic<uint32_t>, kNumBins> lraHistogram_;
950 std::array<std::atomic<double>, kNumBins> lraEnergy_;
951 std::array<std::atomic<uint16_t>, kNumRangeCells> lraCells_;
952
953 // Sticky for one reset-to-reset measurement transaction.
954 std::atomic<bool> measurementValid_ { true };
955
956 // BS.1770 true-peak (dBTP) tracking
957 TruePeakReader truePeak_;
958 std::array<TruePeakReader::Channel, kMaxChannels> tpChannels_ {};
960 float tpNarrow_[std::is_same_v<T, float> ? 1 : kTruePeakChunk] = {};
961 std::atomic<T> truePeakMax_ { T(0) };
962};
963
964} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Real-time safe EBU R128 loudness meter.
void prepare(const AudioSpec &spec) noexcept
Unified API preparation.
T getIntegratedLUFS() const noexcept
Computes the Integrated loudness using standard two-pass gating.
T getLoudnessRange() const noexcept
Computes the EBU R128 Loudness Range (EBU Tech 3342).
void process(const T *data, int numSamples) noexcept
Processes a mono block of samples.
void reset() noexcept
Clears all measurements and resets filters.
void process(const T *left, const T *right, int numSamples) noexcept
Processes a stereo block of samples.
T getMomentaryLUFS() const noexcept
Reads the Momentary loudness (400 ms window).
MeasurementInfo getMeasurementInfo() const noexcept
Returns window coverage without modifying any state. Call from the stream owner, or after processing ...
void prepare(double sampleRate, int numChannels=2) noexcept
Prepares the meter and pre-calculates filter coefficients.
T getTruePeakDb() const noexcept
Returns the maximum true peak observed since the last reset.
void finalizeTruePeak() noexcept
Includes the final interpolation tail of a finite programme. Call after the last input block,...
T getShortTermLUFS() const noexcept
Reads the Short-term loudness (3 second window).
bool isMeasurementValid() const noexcept
Reports whether every measurement since reset was representable.
void processBlock(AudioBufferView< const T > buffer) noexcept
Processes a non-interleaved buffer view (read-only).
Running-maximum reading of the band-limited reconstruction peak, for meters.
static constexpr int kChunk
Most samples one processMax() call takes.
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...
Main namespace for the DSPark framework.
T gainToDecibels(T gain, T minusInfinityDb=T(-100)) noexcept
Converts a linear gain value to decibels.
Definition DspMath.h:92
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
static BiquadCoeffs makeKWeightingHighPass(double sampleRate) noexcept
ITU-R BS.1770 K-weighting, stage 2: the RLB high-pass.
Definition Biquad.h:632
static BiquadCoeffs makeKWeightingShelf(double sampleRate) noexcept
ITU-R BS.1770 K-weighting, stage 1: the head-related high shelf.
Definition Biquad.h:607
Window/gate coverage for a stopped or stream-owner measurement. Durations use the existing floor(samp...