forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

loudness.rs687 lines, 31.1 KiBHistoryRawDownload
1//! EBU R128 / ITU-R BS.1770-4 loudness and true peak, streamed.
2//!
3//! [`Meter`] takes interleaved `f32` samples as they come off the decoder and
4//! keeps only what the measurement needs: the K-weighted power of every 100 ms
5//! chunk, and the peak trackers. [`Meter::finish`] turns those into a
6//! [`Loudness`]. Nothing here is hard-coded to one sample rate: the K-weighting
7//! biquads are recomputed from the BS.1770 analog prototypes for whatever rate
8//! the meter is built with.
9//!
10//! Conventions, all of them the standard's unless noted:
11//!
12//! * Momentary is 400 ms, short-term is 3 s, both measured on 100 ms chunks, so
13//! a 400 ms block is four chunks and blocks overlap by 75%.
14//! * Gating: absolute at -70 LUFS, then relative at -10 LU below the mean of
15//! what passed the absolute gate. Integrated loudness is the mean of what
16//! passes both.
17//! * Channel weights: mono and the first three channels of anything are 1.0;
18//! for six or more channels, in SMPTE order (L R C LFE Ls Rs ...), the LFE is
19//! excluded and the surrounds weigh 1.41. Anything with fewer than six
20//! channels that is not mono or stereo is weighted as if it were the first
21//! channels of that layout.
22//! * LRA follows EBU Tech 3342: short-term loudness sampled at 2 Hz, a -20 LU
23//! relative gate, and the spread between the 10th and 95th percentiles. The
24//! percentiles are nearest-rank, not interpolated.
25//! * True peak is the BS.1770-4 Annex 2 method, 8x oversampled rather than the
26//! standard's 4x: a 256-tap windowed-sinc FIR (32 taps per phase,
27//! [`TP_COEF`]), and the largest magnitude over every oversampled sample. It is the same detector the
28//! master limiter runs ([`crate::limiter`]), so a ceiling it holds reads at
29//! or under that ceiling here.
30//!
31//! Silence is reported as [`f64::NEG_INFINITY`] for every loudness and peak
32//! that has no energy to measure. A short-term figure that cannot be computed
33//! yet (under three seconds of audio) is also `-inf`. LRA needs at least two
34//! 2 Hz short-term samples to be a spread at all: with fewer, `range_lu` is
35//! `0.0` and `lra_samples` says why (see its docs).
36
37use std::f64::consts::PI;
38use std::path::Path;
39
40use crate::AudioSession;
41
42/// Absolute gate, LUFS: a block quieter than this does not count at all.
43const ABS_GATE_LUFS: f64 = -70.0;
44/// Relative gate for integrated loudness, LU below the absolute-gated mean.
45const REL_GATE_LU: f64 = -10.0;
46/// Relative gate for LRA, LU below the absolute-gated short-term mean.
47const LRA_REL_GATE_LU: f64 = -20.0;
48/// Chunks per second: 100 ms, the hop of every block in the standard.
49const CHUNKS_PER_SEC: usize = 10;
50/// Chunks in a 400 ms momentary block.
51const MOMENTARY_CHUNKS: usize = 4;
52/// Chunks in a 3 s short-term block.
53const SHORT_TERM_CHUNKS: usize = 30;
54/// Chunks between two LRA samples: 5 x 100 ms = 500 ms, i.e. 2 Hz.
55const LRA_HOP_CHUNKS: usize = 5;
56/// Taps of the true-peak interpolator per phase.
57pub(crate) const TP_TAPS: usize = 32;
58/// Oversampling factor of the true-peak detector.
59const TP_PHASES: usize = 8;
60
61/// The 8x oversampling filter, polyphase: a 256-tap Kaiser-windowed sinc (beta
62/// 8), split as `TP_COEF[p][j] = h[8j + p]` (phase `p` is the output between
63/// input samples, tap `j` multiplies the input `j` steps back), each phase
64/// normalised to unit DC gain.
65///
66/// Why 8x and 32 taps, and not the 4x 48-tap table this file used to carry:
67/// the 4x table read up to 1.6 dB under the true peak of dense high-frequency
68/// material (white noise), and a limiter that holds that reading lets the
69/// export overshoot the ceiling by the same amount. Measured against ffmpeg's
70/// `ebur128=peak=true` on the test material (white noise, pink noise, a
71/// two-tone mix, a +12 dB test tone, a speech-and-music file): this table
72/// reads within 0.1 dB of ffmpeg on all of them and never under it by more than
73/// 0.05 dB, where the 4x table was 1.6 dB under on the noise. Tones within
74/// about a tenth of the sample rate of Nyquist are the one place the two
75/// filters, and ffmpeg's resampler, disagree by a few tenths of a dB in either
76/// direction (a 15 kHz tone at 48 kHz reads 0.4 dB under ffmpeg here; a 20 kHz
77/// one reads 0.4 dB over the waveform's true crest); nothing else in the test
78/// set does that.
79pub(crate) const TP_COEF: [[f64; TP_TAPS]; TP_PHASES] = [
80 [-9.113131439975678e-06, 4.0076035670222974e-05, -0.00010621819573270595, 0.0002284040759670764, -0.0004338708206289006, 0.0007569269598663376, -0.001239982208738999, 0.0019355921973831004, -0.0029109007764240528, 0.004257373975001418, -0.006112418887724569, 0.00870982957472023, -0.012509950835799514, 0.018598441767977404, -0.030321702331554387, 0.06538702643260477, 0.9935370754684095, -0.057482007155269126, 0.02827349906597848, -0.017640066565440395, 0.011942377142413332, -0.008332275252542716, 0.005846125446777624, -0.0040647034070906305, 0.002770883608971783, -0.0018349008372697962, 0.0011691692091189859, -0.0007087508284246482, 0.00040253288581122037, -0.00020919986159042688, 9.537201341962132e-05, -3.46447644203612e-05],
81 [-3.311694388264495e-05, 0.00013113986569634532, -0.0003358453978417591, 0.0007088167627000853, -0.0013300206219824767, 0.0022998489712809, -0.0037422781404128427, 0.005811272430550032, -0.008704737233512524, 0.012695107173726997, -0.018197543923624927, 0.02593058478547953, -0.037337762954957596, 0.05591630108406594, -0.09294865839644116, 0.21555037786454243, 0.9426947295402057, -0.145858673869235, 0.07531945801178211, -0.047702981628914426, 0.032480746980827084, -0.022701723557568016, 0.015920900371157783, -0.011048146610773036, 0.007507937684653195, -0.004950613758014254, 0.0031369765747049742, -0.0018880054283359473, 0.0010620801545960844, -0.0005445803041891528, 0.0002430517421209236, -8.464122840432894e-05],
82 [-6.169787761900706e-05, 0.00022418908603070837, -0.000556455526893554, 0.0011539493624898778, -0.0021399892134944926, 0.003668916980414196, -0.005931212321661181, 0.0091640417587589, -0.013674291087551773, 0.019889092089511885, -0.02846897809283543, 0.04057719426108761, -0.05859942936943879, 0.08848148300534162, -0.1503840991546257, 0.3823053610670679, 0.8457322859905341, -0.1965949653427006, 0.10574314941958163, -0.06786563501345873, 0.04644402518288106, -0.03250685839030642, 0.02278221067211325, -0.015776461984025044, 0.0106861423046505, -0.007015178439754547, 0.004419776898118025, -0.002640349206419353, 0.0014706075069126929, -0.0007434479010369788, 0.00032434279095271655, -0.00010771945462504619],
83 [-8.888904218233107e-05, 0.00030047873971013594, -0.0007247222673508771, 0.0014781413284720366, -0.0027105491893057556, 0.004608923212425362, -0.00740395560020146, 0.011383759722552785, -0.016923835860553745, 0.02455287281769743, -0.03510086512343416, 0.05005558258074104, -0.07253382289668456, 0.11053946484280222, -0.1927372791631574, 0.552445740092612, 0.7115968219479728, -0.210662107454357, 0.11729533434259606, -0.07616916079430923, 0.052359451330621726, -0.036687218160952884, 0.0256897361931744, -0.0177499783487386, 0.011981956177112868, -0.007829952650949394, 0.004903989286442165, -0.0029071517994024823, 0.0016025392331753556, -0.0007981591599705676, 0.00033979186197556166, -0.00010693619853382159],
84 [-0.00010693619853382162, 0.0003397918619755617, -0.0007981591599705678, 0.0016025392331753558, -0.002907151799402483, 0.004903989286442166, -0.007829952650949396, 0.011981956177112871, -0.017749978348738604, 0.025689736193174405, -0.03668721816095289, 0.05235945133062174, -0.07616916079430926, 0.11729533434259608, -0.21066210745435704, 0.711596821947973, 0.5524457400926122, -0.19273727916315744, 0.11053946484280223, -0.07253382289668457, 0.05005558258074105, -0.035100865123434175, 0.024552872817697434, -0.016923835860553748, 0.011383759722552787, -0.007403955600201462, 0.004608923212425363, -0.002710549189305756, 0.001478141328472037, -0.0007247222673508772, 0.00030047873971013604, -8.88890421823311e-05],
85 [-0.00010771945462504618, 0.0003243427909527165, -0.0007434479010369787, 0.0014706075069126927, -0.0026403492064193527, 0.004419776898118025, -0.007015178439754547, 0.010686142304650498, -0.01577646198402504, 0.02278221067211325, -0.03250685839030642, 0.04644402518288106, -0.06786563501345873, 0.10574314941958161, -0.19659496534270057, 0.845732285990534, 0.38230536106706786, -0.15038409915462567, 0.0884814830053416, -0.05859942936943878, 0.0405771942610876, -0.028468978092835426, 0.01988909208951188, -0.013674291087551773, 0.009164041758758899, -0.00593121232166118, 0.0036689169804141955, -0.002139989213494492, 0.0011539493624898776, -0.0005564555268935539, 0.00022418908603070835, -6.169787761900705e-05],
86 [-8.464122840432894e-05, 0.0002430517421209236, -0.0005445803041891528, 0.0010620801545960844, -0.0018880054283359473, 0.0031369765747049742, -0.004950613758014254, 0.007507937684653195, -0.011048146610773036, 0.015920900371157783, -0.022701723557568016, 0.032480746980827084, -0.047702981628914426, 0.07531945801178211, -0.145858673869235, 0.9426947295402057, 0.21555037786454243, -0.09294865839644116, 0.05591630108406594, -0.037337762954957596, 0.02593058478547953, -0.018197543923624927, 0.012695107173726997, -0.008704737233512524, 0.005811272430550032, -0.0037422781404128427, 0.0022998489712809, -0.0013300206219824767, 0.0007088167627000853, -0.0003358453978417591, 0.00013113986569634532, -3.311694388264495e-05],
87 [-3.464476442036121e-05, 9.537201341962134e-05, -0.00020919986159042688, 0.0004025328858112204, -0.0007087508284246483, 0.0011691692091189859, -0.0018349008372697964, 0.0027708836089717836, -0.004064703407090631, 0.005846125446777624, -0.008332275252542718, 0.011942377142413333, -0.0176400665654404, 0.028273499065978484, -0.05748200715526913, 0.9935370754684096, 0.06538702643260477, -0.03032170233155439, 0.018598441767977408, -0.012509950835799515, 0.00870982957472023, -0.00611241888772457, 0.004257373975001418, -0.0029109007764240528, 0.0019355921973831006, -0.001239982208738999, 0.0007569269598663377, -0.00043387082062890065, 0.00022840407596707644, -0.00010621819573270597, 4.007603567022298e-05, -9.113131439975678e-06],
88];
89
90/// The measured loudness and peaks of one stream. Loudness in LUFS / LU, peaks
91/// in dBTP and dBFS. See the module docs for what `-inf` means here.
92#[derive(Debug, Clone, Copy, PartialEq)]
93pub struct Loudness {
94 /// Gated programme loudness, LUFS.
95 pub integrated_lufs: f64,
96 /// Loudness range, LU (EBU Tech 3342).
97 pub range_lu: f64,
98 /// Highest true peak across all channels, dBTP.
99 pub true_peak_dbtp: f64,
100 /// Highest sample magnitude across all channels, dBFS.
101 pub sample_peak_dbfs: f64,
102 /// Loudest ungated 400 ms momentary block, LUFS.
103 pub momentary_max_lufs: f64,
104 /// Loudest ungated 3 s short-term block, LUFS.
105 pub short_term_max_lufs: f64,
106 /// Seconds of audio analysed (whole 100 ms chunks).
107 pub analysed_secs: f64,
108 /// Gated 2 Hz short-term samples the loudness range was taken from. The
109 /// range is a spread only when this is at least two; with fewer, `range_lu`
110 /// is `0.0` because there is no spread to measure.
111 pub lra_samples: usize,
112}
113
114/// One second-order IIR section, direct form I, coefficients already divided by
115/// `a0`.
116#[derive(Debug, Clone, Copy)]
117struct Biquad {
118 b: [f64; 3],
119 a: [f64; 2],
120 x: [f64; 2],
121 y: [f64; 2],
122}
123
124impl Biquad {
125 fn new(b: [f64; 3], a: [f64; 2]) -> Self {
126 Self {
127 b,
128 a,
129 x: [0.0; 2],
130 y: [0.0; 2],
131 }
132 }
133
134 fn run(&mut self, x: f64) -> f64 {
135 let y = self.b[0] * x + self.b[1] * self.x[0] + self.b[2] * self.x[1]
136 - self.a[0] * self.y[0]
137 - self.a[1] * self.y[1];
138 self.x = [x, self.x[0]];
139 self.y = [y, self.y[0]];
140 y
141 }
142}
143
144/// The two K-weighting stages of BS.1770 for `rate`: the pre-filter high shelf
145/// (stage 1) and the RLB high-pass (stage 2). The corner frequencies, gain and
146/// Q are the standard's; they are pre-warped through the bilinear transform at
147/// the actual rate, the way libebur128 does it.
148fn k_weighting(rate: f64) -> (Biquad, Biquad) {
149 let f0 = 1_681.974_450_955_533;
150 let g = 3.999_843_853_973_347;
151 let q = 0.707_175_236_955_419_6;
152 let k = (PI * f0 / rate).tan();
153 let vh = 10f64.powf(g / 20.0);
154 let vb = vh.powf(0.499_666_774_154_541_4);
155 let a0 = 1.0 + k / q + k * k;
156 let shelf = Biquad::new(
157 [
158 (vh + vb * k / q + k * k) / a0,
159 2.0 * (k * k - vh) / a0,
160 (vh - vb * k / q + k * k) / a0,
161 ],
162 [2.0 * (k * k - 1.0) / a0, (1.0 - k / q + k * k) / a0],
163 );
164
165 // The RLB high-pass has a double zero at DC, so its numerator is [1, -2, 1]
166 // with no gain: BS.1770's table at 48 kHz is exactly that numerator. Dividing
167 // it by a0 as the other stages do cuts about 0.04 dB at every rate, which is
168 // what made edith read under ffmpeg's ebur128.
169 let f0 = 38.135_470_876_024_44;
170 let q = 0.500_327_037_323_877_3;
171 let k = (PI * f0 / rate).tan();
172 let a0 = 1.0 + k / q + k * k;
173 let hipass = Biquad::new(
174 [1.0, -2.0, 1.0],
175 [2.0 * (k * k - 1.0) / a0, (1.0 - k / q + k * k) / a0],
176 );
177 (shelf, hipass)
178}
179
180/// BS.1770 channel weight for channel `index` of a `channels`-wide stream.
181fn channel_weight(index: usize, channels: usize) -> f64 {
182 if channels < 6 {
183 return 1.0;
184 }
185 match index {
186 3 => 0.0, // LFE
187 4 | 5 => 1.41, // Ls, Rs
188 _ => 1.0,
189 }
190}
191
192/// One channel's true-peak detector: the last `TP_TAPS` samples, newest first,
193/// kept twice over so the window is always one contiguous slice.
194#[derive(Debug, Clone)]
195pub(crate) struct TruePeak {
196 hist: [f64; 2 * TP_TAPS],
197 pos: usize,
198}
199
200impl TruePeak {
201 pub(crate) fn new() -> Self {
202 Self {
203 hist: [0.0; 2 * TP_TAPS],
204 pos: 0,
205 }
206 }
207
208 /// Feed one sample; returns the largest magnitude of the `TP_PHASES`
209 /// oversampled points around the sample `TP_TAPS / 2` steps back, which is
210 /// the newest point whose window is complete (the interpolator's group
211 /// delay is that many samples). Nothing is flushed at the end: the last
212 /// samples have no complete window, and a made-up tail would read the
213 /// stream's cut as a step.
214 pub(crate) fn push(&mut self, x: f64) -> f64 {
215 self.pos = (self.pos + TP_TAPS - 1) % TP_TAPS;
216 self.hist[self.pos] = x;
217 self.hist[self.pos + TP_TAPS] = x;
218 let w = &self.hist[self.pos..self.pos + TP_TAPS];
219 let mut peak = 0.0f64;
220 for row in &TP_COEF {
221 let y: f64 = w.iter().zip(row.iter()).map(|(s, c)| s * c).sum();
222 peak = peak.max(y.abs());
223 }
224 peak
225 }
226}
227
228/// Streaming BS.1770 meter. Build it with the stream's own rate and channel
229/// count, feed it interleaved samples, and ask for the result at any point.
230#[derive(Debug, Clone)]
231pub struct Meter {
232 channels: usize,
233 weights: Vec<f64>,
234 shelf: Vec<Biquad>,
235 hipass: Vec<Biquad>,
236 chunk_frames: usize,
237 frames_in_chunk: usize,
238 chunk_acc: f64,
239 /// Weighted mean-square power of each completed 100 ms chunk.
240 chunks: Vec<f64>,
241 sample_peak: f64,
242 tp: Vec<TruePeak>,
243 tp_peak: f64,
244}
245
246impl Meter {
247 /// A meter for `channels` interleaved channels at `sample_rate` Hz.
248 pub fn new(sample_rate: u32, channels: u16) -> Self {
249 let channels = usize::from(channels).max(1);
250 let (shelf, hipass) = k_weighting(f64::from(sample_rate.max(1)));
251 Self {
252 channels,
253 weights: (0..channels).map(|c| channel_weight(c, channels)).collect(),
254 shelf: vec![shelf; channels],
255 hipass: vec![hipass; channels],
256 chunk_frames: (sample_rate as usize / CHUNKS_PER_SEC).max(1),
257 frames_in_chunk: 0,
258 chunk_acc: 0.0,
259 chunks: Vec::new(),
260 sample_peak: 0.0,
261 tp: vec![TruePeak::new(); channels],
262 tp_peak: 0.0,
263 }
264 }
265
266 /// Feed interleaved samples, `channels` values per frame. A trailing
267 /// partial frame is ignored.
268 pub fn push(&mut self, interleaved: &[f32]) {
269 for frame in interleaved.chunks_exact(self.channels) {
270 let mut acc = 0.0;
271 for (c, &s) in frame.iter().enumerate() {
272 let x = f64::from(s);
273 self.sample_peak = self.sample_peak.max(x.abs());
274 let y = self.hipass[c].run(self.shelf[c].run(x));
275 acc += self.weights[c] * y * y;
276 let tp = self.tp[c].push(x);
277 self.tp_peak = self.tp_peak.max(tp);
278 }
279 self.chunk_acc += acc;
280 self.frames_in_chunk += 1;
281 if self.frames_in_chunk == self.chunk_frames {
282 self.chunks.push(self.chunk_acc / self.chunk_frames as f64);
283 self.chunk_acc = 0.0;
284 self.frames_in_chunk = 0;
285 }
286 }
287 }
288
289 /// The measurement so far. Takes `&self` so a caller can read a running
290 /// figure and keep pushing. A partly filled 100 ms chunk at the end is not
291 /// counted, and the true peak covers the samples whose interpolation is complete.
292 pub fn finish(&self) -> Loudness {
293 let chunks = &self.chunks;
294
295 // No tail: see `TruePeak::push`.
296 let tp_peak = self.tp_peak;
297
298 let momentary: Vec<f64> = (MOMENTARY_CHUNKS - 1..chunks.len())
299 .map(|i| window_mean(chunks, i, MOMENTARY_CHUNKS))
300 .collect();
301 let short_term: Vec<f64> = (SHORT_TERM_CHUNKS - 1..chunks.len())
302 .map(|i| window_mean(chunks, i, SHORT_TERM_CHUNKS))
303 .collect();
304
305 let integrated = gated_blocks(&momentary, REL_GATE_LU);
306 let integrated_lufs = if integrated.is_empty() {
307 f64::NEG_INFINITY
308 } else {
309 lufs(mean(&integrated))
310 };
311
312 // LRA: 2 Hz samples of the short-term loudness, gated, then the spread
313 // between the 10th and 95th percentile.
314 let lra_blocks: Vec<f64> = short_term.iter().step_by(LRA_HOP_CHUNKS).copied().collect();
315 let mut lra_values: Vec<f64> = gated_blocks(&lra_blocks, LRA_REL_GATE_LU)
316 .into_iter()
317 .map(lufs)
318 .collect();
319 lra_values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
320 let lra_samples = lra_values.len();
321 let range_lu = if lra_samples < 2 {
322 0.0
323 } else {
324 percentile(&lra_values, 0.95) - percentile(&lra_values, 0.10)
325 };
326
327 Loudness {
328 integrated_lufs,
329 range_lu,
330 true_peak_dbtp: db(tp_peak),
331 sample_peak_dbfs: db(self.sample_peak),
332 momentary_max_lufs: momentary
333 .iter()
334 .copied()
335 .map(lufs)
336 .fold(f64::NEG_INFINITY, f64::max),
337 short_term_max_lufs: short_term
338 .iter()
339 .copied()
340 .map(lufs)
341 .fold(f64::NEG_INFINITY, f64::max),
342 analysed_secs: chunks.len() as f64 / CHUNKS_PER_SEC as f64,
343 lra_samples,
344 }
345 }
346}
347
348/// Mean power of the `n` chunks ending at index `end`.
349fn window_mean(chunks: &[f64], end: usize, n: usize) -> f64 {
350 chunks[end + 1 - n..=end].iter().sum::<f64>() / n as f64
351}
352
353fn mean(xs: &[f64]) -> f64 {
354 xs.iter().sum::<f64>() / xs.len() as f64
355}
356
357/// Block powers that survive the absolute gate and then the relative gate
358/// `rel_lu` below the absolute-gated mean.
359fn gated_blocks(blocks: &[f64], rel_lu: f64) -> Vec<f64> {
360 let above_abs: Vec<f64> = blocks
361 .iter()
362 .copied()
363 .filter(|&p| lufs(p) > ABS_GATE_LUFS)
364 .collect();
365 if above_abs.is_empty() {
366 return Vec::new();
367 }
368 let relative = lufs(mean(&above_abs)) + rel_lu;
369 above_abs
370 .into_iter()
371 .filter(|&p| lufs(p) > relative)
372 .collect()
373}
374
375/// Nearest-rank percentile of an ascending, non-empty slice.
376fn percentile(sorted: &[f64], p: f64) -> f64 {
377 let idx = ((sorted.len() - 1) as f64 * p).round() as usize;
378 sorted[idx.min(sorted.len() - 1)]
379}
380
381/// Mean power -> LUFS (BS.1770 `-0.691 + 10 log10`), `-inf` for no power.
382fn lufs(power: f64) -> f64 {
383 if power > 0.0 {
384 -0.691 + 10.0 * power.log10()
385 } else {
386 f64::NEG_INFINITY
387 }
388}
389
390/// Linear amplitude -> dB, `-inf` for zero.
391fn db(amplitude: f64) -> f64 {
392 if amplitude > 0.0 {
393 20.0 * amplitude.log10()
394 } else {
395 f64::NEG_INFINITY
396 }
397}
398
399/// Measure the first `stream` of the audio file at `path`, over `range`
400/// seconds (`None` for the whole file). Decodes through the same
401/// [`AudioSession`] path [`crate::silence::levels`] uses. `Ok(None)` when the
402/// file has no such audio stream.
403pub fn measure_file(
404 path: &Path,
405 stream: usize,
406 range: Option<(f64, f64)>,
407) -> crate::Result<Option<Loudness>> {
408 let (from, to) = range.unwrap_or((0.0, f64::INFINITY));
409 let sources = [(path.to_path_buf(), stream)];
410 let Some((meta, rx)) =
411 AudioSession::open_multi_streams(&sources, &[(Some(0), from.max(0.0), to)])?
412 else {
413 return Ok(None);
414 };
415 let mut meter = Meter::new(meta.sample_rate, meta.channels);
416 for chunk in rx {
417 meter.push(&chunk.samples);
418 }
419 Ok(Some(meter.finish()))
420}
421
422/// The dB gain that brings `measured` to `target_lufs`, cut back if needed so
423/// the true peak stays at or under `tp_ceiling` dBTP. Silence has no loudness to
424/// move, so it returns `0.0`, and so does a measurement whose integrated
425/// loudness is `-inf` for any other reason.
426pub fn gain_to_target(measured: &Loudness, target_lufs: f64, tp_ceiling: f64) -> f64 {
427 if !measured.integrated_lufs.is_finite() {
428 return 0.0;
429 }
430 let mut gain = target_lufs - measured.integrated_lufs;
431 if measured.true_peak_dbtp.is_finite() {
432 gain = gain.min(tp_ceiling - measured.true_peak_dbtp);
433 }
434 gain
435}
436
437#[cfg(test)]
438mod tests {
439 use std::path::PathBuf;
440
441 use super::{Loudness, Meter, TP_COEF, gain_to_target, measure_file};
442
443 /// Interleaved sine: `amp` at `freq` Hz in the channels listed in `live`,
444 /// digital zero in the rest.
445 fn sine(
446 rate: u32,
447 secs: f64,
448 amp: f64,
449 freq: f64,
450 phase: f64,
451 channels: usize,
452 live: &[usize],
453 ) -> Vec<f32> {
454 let frames = (f64::from(rate) * secs) as usize;
455 let mut out = Vec::with_capacity(frames * channels);
456 for n in 0..frames {
457 let v = amp
458 * (2.0 * std::f64::consts::PI * freq * n as f64 / f64::from(rate) + phase).sin();
459 for c in 0..channels {
460 out.push(if live.contains(&c) { v as f32 } else { 0.0 });
461 }
462 }
463 out
464 }
465
466 fn measure(samples: &[f32], rate: u32, channels: u16) -> Loudness {
467 let mut m = Meter::new(rate, channels);
468 // Push in uneven pieces so chunk boundaries are not what the test
469 // happens to be aligned to.
470 for piece in samples.chunks(4097 * usize::from(channels)) {
471 m.push(piece);
472 }
473 m.finish()
474 }
475
476 /// -20 dBFS 1 kHz sine in the left channel only: BS.1770 gives -3.01 LUFS
477 /// for 0 dBFS in one channel, so -23.01 here.
478 #[test]
479 fn one_channel_tone_at_minus_20_dbfs_reads_minus_23() {
480 let amp = 0.1;
481 let s = sine(48_000, 10.0, amp, 1000.0, 0.0, 2, &[0]);
482 let l = measure(&s, 48_000, 2);
483 assert!((l.integrated_lufs - -23.0).abs() < 0.02, "{l:?}");
484 }
485
486 /// The same tone in both channels adds 3.01 dB: -20.0 LUFS. (The spec's
487 /// "-20 dBFS stereo reads -23" only holds for one channel; both channels
488 /// carry the same power twice.)
489 #[test]
490 fn two_channel_tone_at_minus_20_dbfs_reads_minus_20() {
491 let s = sine(48_000, 10.0, 0.1, 1000.0, 0.0, 2, &[0, 1]);
492 let l = measure(&s, 48_000, 2);
493 assert!((l.integrated_lufs - -20.0).abs() < 0.1, "{l:?}");
494 }
495
496 #[test]
497 fn same_reading_at_44_1_khz() {
498 let s = sine(44_100, 10.0, 0.1, 1000.0, 0.0, 2, &[0]);
499 let l = measure(&s, 44_100, 2);
500 assert!((l.integrated_lufs - -23.0).abs() < 0.02, "{l:?}");
501 }
502
503 #[test]
504 fn lra_needs_two_two_hz_samples_and_says_how_many_it_had() {
505 // Short-term values start at 3 s and come every 0.5 s: 3.0 s gives one sample, 3.5 s two.
506 let three = measure(&sine(48_000, 3.0, 0.1, 440.0, 0.0, 1, &[0]), 48_000, 1);
507 assert_eq!(three.lra_samples, 1);
508 assert_eq!(three.range_lu, 0.0);
509 assert!((three.analysed_secs - 3.0).abs() < 1e-9, "{}", three.analysed_secs);
510 let four = measure(&sine(48_000, 4.0, 0.1, 440.0, 0.0, 1, &[0]), 48_000, 1);
511 assert!(four.lra_samples >= 2, "{}", four.lra_samples);
512 }
513
514 #[test]
515 fn silence_is_negative_infinity_and_has_no_range() {
516 let s = vec![0.0f32; 48_000 * 2 * 5];
517 let l = measure(&s, 48_000, 2);
518 assert_eq!(l.integrated_lufs, f64::NEG_INFINITY);
519 assert_eq!(l.true_peak_dbtp, f64::NEG_INFINITY);
520 assert_eq!(l.sample_peak_dbfs, f64::NEG_INFINITY);
521 assert_eq!(l.momentary_max_lufs, f64::NEG_INFINITY);
522 assert_eq!(l.range_lu, 0.0);
523 }
524
525 /// Ten seconds of silence after the tone is below the absolute gate, so it
526 /// must not drag the integrated figure down. The one 400 ms block that
527 /// straddles the cut keeps a fraction of the tone and moves the mean by
528 /// under 0.1 dB.
529 #[test]
530 fn gating_ignores_trailing_silence() {
531 let tone = sine(48_000, 10.0, 0.1, 1000.0, 0.0, 2, &[0]);
532 let alone = measure(&tone, 48_000, 2);
533 let mut padded = tone.clone();
534 padded.extend(std::iter::repeat_n(0.0f32, 48_000 * 2 * 10));
535 let gated = measure(&padded, 48_000, 2);
536 assert!(
537 (gated.integrated_lufs - alone.integrated_lufs).abs() < 0.1,
538 "alone {alone:?} padded {gated:?}"
539 );
540 }
541
542 #[test]
543 fn full_scale_sine_true_peak_is_about_zero_dbtp() {
544 let s = sine(48_000, 1.0, 1.0, 1000.0, 0.0, 1, &[0]);
545 let l = measure(&s, 48_000, 1);
546 assert!(l.true_peak_dbtp.abs() < 0.1, "{l:?}");
547 assert!(l.sample_peak_dbfs.abs() < 0.1, "{l:?}");
548 }
549
550 /// fs/4 sine at 45 degrees: every sample is +-0.707 (-3.01 dBFS), but the
551 /// waveform between samples reaches 1.0. The true peak has to see that.
552 #[test]
553 fn intersample_peak_is_found_above_sample_peak() {
554 let s = sine(
555 48_000,
556 1.0,
557 1.0,
558 12_000.0,
559 std::f64::consts::FRAC_PI_4,
560 1,
561 &[0],
562 );
563 let l = measure(&s, 48_000, 1);
564 assert!((l.sample_peak_dbfs - -3.01).abs() < 0.05, "{l:?}");
565 assert!(l.true_peak_dbtp.abs() < 0.2, "{l:?}");
566 assert!(l.true_peak_dbtp > l.sample_peak_dbfs + 2.5, "{l:?}");
567 }
568
569 /// fs/4 at 45 degrees with the crest at amplitude sqrt(2): the samples are
570 /// +-1.0 (0 dBFS) and the waveform between them reaches +3.01 dBTP. The 4x
571 /// grid sits 1/8 sample from the crest, which costs about 0.17 dB, so the
572 /// BS.1770 reading is close to, not exactly, the continuous crest.
573 #[test]
574 fn fs_over_4_sine_at_45_degrees_reads_about_3_dbtp() {
575 let s = sine(
576 48_000,
577 1.0,
578 std::f64::consts::SQRT_2,
579 12_000.0,
580 std::f64::consts::FRAC_PI_4,
581 1,
582 &[0],
583 );
584 let l = measure(&s, 48_000, 1);
585 assert!(l.sample_peak_dbfs.abs() < 0.05, "{l:?}");
586 assert!((l.true_peak_dbtp - 3.0).abs() < 0.2, "{l:?}");
587 }
588
589 /// Each phase of the interpolator has unit DC gain, so a flat signal reads
590 /// its own level at every oversampled point: the table is normalised as the
591 /// comment on [`TP_COEF`] says it is.
592 #[test]
593 fn every_interpolator_phase_has_unit_dc_gain() {
594 for (p, row) in TP_COEF.iter().enumerate() {
595 let sum: f64 = row.iter().sum();
596 assert!((sum - 1.0).abs() < 1e-9, "phase {p} sums to {sum}");
597 }
598 }
599
600 /// A 997 Hz sine at -6 dBFS is well inside the passband, so its true peak
601 /// reads its amplitude, -6 dBTP.
602 #[test]
603 fn a_997_hz_sine_at_minus_6_dbfs_reads_minus_6_dbtp() {
604 let amp = 10f64.powf(-6.0 / 20.0);
605 let s = sine(48_000, 1.0, amp, 997.0, 0.3, 1, &[0]);
606 let l = measure(&s, 48_000, 1);
607 assert!((l.true_peak_dbtp - -6.0).abs() < 0.1, "{l:?}");
608 }
609
610 #[test]
611 fn measure_file_reads_the_test_tone() {
612 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_tone.wav");
613 let l = measure_file(&path, 0, None)
614 .expect("decode")
615 .expect("has audio");
616 assert!(l.integrated_lufs.is_finite(), "{l:?}");
617 assert!((-60.0..0.0).contains(&l.integrated_lufs), "{l:?}");
618 assert!(
619 l.true_peak_dbtp.is_finite() && l.true_peak_dbtp <= 0.5,
620 "{l:?}"
621 );
622 assert!(l.sample_peak_dbfs <= l.true_peak_dbtp + 0.5, "{l:?}");
623 }
624
625 /// At 48 kHz the two K-weighting stages are BS.1770-4's own table, to the
626 /// digits the standard prints.
627 #[test]
628 fn k_weighting_at_48_khz_is_the_bs1770_table() {
629 let (shelf, hipass) = super::k_weighting(48_000.0);
630 let close = |got: &[f64], want: &[f64]| {
631 got.iter()
632 .zip(want)
633 .all(|(g, w)| (g - w).abs() < 1e-10)
634 };
635 assert!(close(
636 &shelf.b,
637 &[1.535_124_859_586_97, -2.691_696_189_406_38, 1.198_392_810_852_85]
638 ));
639 assert!(close(&shelf.a, &[-1.690_659_293_182_41, 0.732_480_774_215_85]));
640 assert!(close(&hipass.b, &[1.0, -2.0, 1.0]));
641 assert!(close(&hipass.a, &[-1.990_047_454_833_98, 0.990_072_250_366_21]));
642 }
643
644 /// Readings checked against ffmpeg's `ebur128` on the same files (see the
645 /// notes on each test for the values). ffmpeg is the reference, not the
646 /// standard's own text, because the standard only prints 48 kHz tables.
647 #[test]
648 fn one_channel_997_hz_at_minus_20_dbfs_matches_ffmpeg() {
649 // ffmpeg: -23.016. 0.1 amplitude is -20 dBFS; one channel reads 3 dB under -20.
650 let s = sine(48_000, 10.0, 0.1, 997.0, 0.0, 1, &[0]);
651 let l = measure(&s, 48_000, 1);
652 assert!((l.integrated_lufs - -23.016).abs() < 0.01, "{l:?}");
653 }
654
655 #[test]
656 fn stereo_997_hz_at_minus_23_dbfs_matches_ffmpeg() {
657 // ffmpeg: -23.006 for -23 dBFS in both channels.
658 let amp = 10f64.powf(-23.0 / 20.0);
659 let s = sine(48_000, 10.0, amp, 997.0, 0.0, 2, &[0, 1]);
660 let l = measure(&s, 48_000, 2);
661 assert!((l.integrated_lufs - -23.006).abs() < 0.01, "{l:?}");
662 }
663
664 #[test]
665 fn gain_is_limited_by_true_peak_ceiling() {
666 let m = Loudness {
667 integrated_lufs: -23.0,
668 range_lu: 0.0,
669 true_peak_dbtp: -3.0,
670 sample_peak_dbfs: -4.0,
671 momentary_max_lufs: -20.0,
672 short_term_max_lufs: -21.0,
673 analysed_secs: 10.0,
674 lra_samples: 0,
675 };
676 // Loudness alone would allow +7 dB; the peak allows only +2 dB.
677 assert!((gain_to_target(&m, -16.0, -1.0) - 2.0).abs() < 1e-9);
678 // Quiet material with headroom takes the full loudness gain.
679 assert!((gain_to_target(&m, -26.0, -1.0) - -3.0).abs() < 1e-9);
680 let silent = Loudness {
681 integrated_lufs: f64::NEG_INFINITY,
682 true_peak_dbtp: f64::NEG_INFINITY,
683 ..m
684 };
685 assert_eq!(gain_to_target(&silent, -16.0, -1.0), 0.0);
686 }
687}