forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

limiter.rs595 lines, 26.7 KiBHistoryRawDownload
1//! The master limiter: one ceiling the whole mix is held under, applied where
2//! the lanes are summed and nowhere else ([`crate::audio::mix`]).
3//!
4//! A mix is an add, and two lanes at full scale add past full scale: what used
5//! to happen there was a hard `clamp`, which is a squared-off waveform and the
6//! worst-sounding thing an editor can do to a hot timeline. This holds the sum
7//! down *before* it reaches the clamp instead, and the clamp stays behind it as
8//! the backstop it always was.
9//!
10//! Per sample, no FFT, no allocation while it runs:
11//!
12//! * **True peak.** The ceiling is a true-peak ceiling (dBTP), so the peak
13//! detector is the one the meter measures with ([`crate::loudness::TruePeak`],
14//! the same filter), 8x oversampled rather than the standard's 4x: a 4x grid
15//! read up to 1.6 dB under the waveform on dense high-frequency material, and
16//! the export then overshot the ceiling by that much. A sample peak limiter
17//! lets a waveform overshoot between its samples; this one holds the
18//! reconstructed waveform instead.
19//! * **Lookahead.** The mix is written into a delay line [`LOOKAHEAD_MS`] long
20//! and read out of it that much later, so the gain a peak needs is already in
21//! force by the time the peak itself is emitted. No attack overshoot -- the
22//! first sample over the ceiling is the first sample held under it, which is
23//! what makes the peak of an exported file a *measurement* and not a hope.
24//! The detector sees its peak `TP_TAPS / 2` frames before the samples it
25//! describes, so the lookahead is what lets it act in time.
26//! * **Linked channels.** One gain for the frame, off the loudest channel in
27//! it: a per-channel gain would move the stereo image every time one side
28//! peaked.
29//! * **Soft knee.** [`KNEE_DB`] wide and centred on the ceiling, so the gain
30//! comes in gradually instead of switching on at one sample and off at the
31//! next. The knee's own curve never lets the output past the ceiling (at the
32//! centre it is already `KNEE_DB/8` under it), which is what keeps the
33//! guarantee a hard knee would give.
34//! * **Release**, not a per-sample snap back: `RELEASE_MS` of exponential
35//! recovery, so one loud transient does not pump the whole bar around it.
36//!
37//! The latency is *taken out again*, not paid: the first `lookahead` frames of
38//! output -- the empty delay line -- are dropped, so what comes out is sample
39//! aligned with what went in and the sound stays locked to the picture. The
40//! last `lookahead` frames are still in the line when the mix runs out; [`drain`]
41//! plays them out, so the tail is kept and the cut at the end of the stream is
42//! limited like everything before it.
43
44use crate::loudness::{TP_TAPS, TruePeak};
45
46/// How far ahead the gain looks. 2 ms is ~96 frames at 48 kHz: long enough to
47/// ride a transient in smoothly, short enough that the tail it eats is nothing.
48/// Never less than the detector's window ([`TP_TAPS`] frames), whatever the rate.
49const LOOKAHEAD_MS: f32 = 2.0;
50/// How wide the knee is, centred on the ceiling.
51const KNEE_DB: f32 = 6.0;
52/// How fast the gain comes back once the loud part is over.
53const RELEASE_MS: f32 = 120.0;
54/// How far under its ceiling the limiter holds the sound, in dB. The 8x detector
55/// agrees with ffmpeg's `ebur128=peak=true` to a few hundredths of a dB on the
56/// test material (white noise, pink noise, speech and music, a test tone), but
57/// ffmpeg's own resampler reads a little higher on some of it: a speech-and-music
58/// file held exactly at -1 dBTP read -0.974 there. The margin is that difference,
59/// taken from the ceiling the limiter holds to and not from the setting a user
60/// names, so the reply reads the measured level and the setting stays what was asked.
61const SAFETY_DB: f32 = 0.1;
62
63/// What a project's master limiter is set to: a ceiling in dBFS and whether it
64/// is in circuit at all. Off by default -- a timeline nobody has asked to limit
65/// mixes exactly as it always did, down to the bit.
66#[derive(Clone, Copy, Debug, PartialEq)]
67pub struct Limiter {
68 /// The level nothing may pass, in dBFS (0 dBFS is full scale).
69 pub ceiling_db: f32,
70 pub on: bool,
71}
72
73impl Default for Limiter {
74 fn default() -> Self {
75 Self {
76 ceiling_db: -1.0,
77 on: false,
78 }
79 }
80}
81
82impl Limiter {
83 /// The ceilings a front-end may set, and what a file may name: a limiter
84 /// above full scale would limit nothing, and one 24 dB down is already a
85 /// fader.
86 pub const MIN_DB: f32 = -24.0;
87 pub const MAX_DB: f32 = 0.0;
88
89 /// The setting with `ceiling_db` put inside the range above, which is what
90 /// a nudge and a parsed line both go through. Not finite means the default.
91 pub fn with_ceiling(self, ceiling_db: f32) -> Self {
92 Self {
93 ceiling_db: match ceiling_db.is_finite() {
94 true => ceiling_db.clamp(Self::MIN_DB, Self::MAX_DB),
95 false => Self::default().ceiling_db,
96 },
97 ..self
98 }
99 }
100
101 /// Whether it is doing anything to the sound -- what an export asks before
102 /// it decides a packet copy would be a lie.
103 pub fn is_active(self) -> bool {
104 self.on
105 }
106}
107
108/// dBFS as an amplitude. `db_to_linear(0.0)` is exactly 1.0, which is what
109/// keeps a flat setting a bit-exact passthrough.
110pub fn db_to_linear(db: f32) -> f32 {
111 match db == 0.0 {
112 true => 1.0,
113 false => 10f32.powf(db / 20.0),
114 }
115}
116
117/// One running limiter: the delay line, the peak window and the gain.
118pub struct LimiterState {
119 channels: usize,
120 /// The delayed mix, one frame per slot, `lookahead + 1` frames round.
121 line: Vec<f32>,
122 /// The true peak of the loudest channel at each frame as the detector saw
123 /// it, same indexing. The detector runs ahead of the line by six frames
124 /// frames, so a slot's value describes the samples around the one six
125 /// slots behind it; the window below covers those samples either way.
126 peaks: Vec<f32>,
127 /// One true-peak detector per channel, fed the mix as it arrives.
128 detect: Vec<TruePeak>,
129 /// Where the next frame is written; the frame read out is the one after it.
130 at: usize,
131 /// Frames still to be swallowed before anything is emitted -- the empty
132 /// delay line, which is how the latency is paid back (module docs).
133 warm: usize,
134 gain: f32,
135 /// Switched out while the mix runs ([`LimiterState::retune`]): the line
136 /// still delays and still emits a frame per frame, only nothing is held
137 /// down. Dropping the state instead would drop the frames still inside the
138 /// line, and those frames are what the master clock counts.
139 bypass: bool,
140 ceiling: f32,
141 /// Where the knee starts, as an amplitude: under this the fast path runs
142 /// and no logarithm is taken.
143 knee_floor: f32,
144 release: f32,
145}
146
147impl LimiterState {
148 pub fn new(params: &Limiter, sample_rate: u32, channels: usize) -> Self {
149 let channels = channels.max(1);
150 let frames = ((LOOKAHEAD_MS / 1000.0 * sample_rate as f32) as usize).max(TP_TAPS) + 1;
151 let ceiling_db = params.with_ceiling(params.ceiling_db).ceiling_db;
152 Self {
153 channels,
154 line: vec![0.0; frames * channels],
155 peaks: vec![0.0; frames],
156 detect: vec![TruePeak::new(); channels],
157 at: 0,
158 warm: frames - 1,
159 gain: 1.0,
160 bypass: !params.on,
161 ceiling: db_to_linear(ceiling_db - SAFETY_DB),
162 knee_floor: db_to_linear(ceiling_db - SAFETY_DB - KNEE_DB / 2.0),
163 // One time constant per sample: the gain covers 63% of the way back
164 // in `RELEASE_MS`.
165 release: 1.0 - (-1000.0 / (RELEASE_MS * sample_rate as f32)).exp(),
166 }
167 }
168
169 /// One switched in **while the mix is already running**: the same limiter,
170 /// except that it swallows nothing to fill its delay line -- the line is
171 /// zeroed and emitting from the first frame, where [`new`] would have eaten
172 /// that much of the mix at the front instead.
173 ///
174 /// Which matters because the count *is* the clock: a mixer that emitted
175 /// fewer samples than the timeline asked for would slide the picture off
176 /// the sound by the lookahead, once per switch-on.
177 ///
178 /// The price, stated as it measures rather than as it was hoped: not a
179 /// momentary hair of silence the stream grows back from, but a **permanent**
180 /// shift of [`LOOKAHEAD_MS`] for the rest of the stream -- the output is
181 /// the input delayed by the whole line, every block, because nothing ever
182 /// re-aligns it. That is at most 2 ms, which is under the perceptual
183 /// threshold, and it is paid once per stream rather than growing; it is
184 /// pinned by
185 /// `tests::an_engaged_limiter_shifts_the_stream_by_the_lookahead_for_good`.
186 /// Changing it is a design call about the export's A/V alignment, not a
187 /// bug fix.
188 pub fn engaged(params: &Limiter, sample_rate: u32, channels: usize) -> Self {
189 Self {
190 warm: 0,
191 ..Self::new(params, sample_rate, channels)
192 }
193 }
194
195 /// Points a running limiter at another setting -- a ceiling dragged, the
196 /// switch flipped -- without touching the delay line, the peak window or
197 /// the gain it is holding. That is what makes the ceiling a live control:
198 /// rebuilding the state would restart the window (a pump) and lose the
199 /// frames inside the line (a slip against the picture).
200 pub fn retune(&mut self, params: &Limiter) {
201 let ceiling_db = params.with_ceiling(params.ceiling_db).ceiling_db;
202 self.bypass = !params.on;
203 self.ceiling = db_to_linear(ceiling_db - SAFETY_DB);
204 self.knee_floor = db_to_linear(ceiling_db - SAFETY_DB - KNEE_DB / 2.0);
205 }
206
207 /// Rewrites `buf` -- interleaved frames -- as the limited mix. Shorter than
208 /// what came in by the delay line's length, once, at the first call.
209 pub fn process(&mut self, buf: &mut Vec<f32>) {
210 let channels = self.channels;
211 let frames = buf.len() / channels;
212 let mut out: Vec<f32> = Vec::with_capacity(buf.len());
213 for f in 0..frames {
214 let frame = &buf[f * channels..(f + 1) * channels];
215 // The raw sample counts too: the interpolated peak can read a hair under a
216 // sample that sits exactly on the ceiling, and the samples are what is held.
217 let mut peak = 0.0f64;
218 for (c, &s) in frame.iter().enumerate() {
219 let x = f64::from(s);
220 peak = peak.max(self.detect[c].push(x)).max(x.abs());
221 }
222 self.line[self.at * channels..(self.at + 1) * channels].copy_from_slice(frame);
223 self.peaks[self.at] = peak as f32;
224 self.at = (self.at + 1) % self.peaks.len();
225
226 // Every frame still in the line, the one about to leave included:
227 // the gain below is therefore never larger than what the *emitted*
228 // frame needs, which is the whole no-overshoot guarantee.
229 let window = self.peaks.iter().fold(0.0f32, |m, &p| m.max(p));
230 let want = match window <= self.knee_floor {
231 true => 1.0,
232 false => self.reduction(window),
233 };
234 // Up is the release, down is instant -- and instant is safe here
235 // only because the frame it is for has not been emitted yet.
236 self.gain += (want - self.gain).max(0.0) * self.release;
237 self.gain = self.gain.min(want);
238
239 if self.warm > 0 {
240 self.warm -= 1;
241 continue;
242 }
243 // Bypassed, the line is a delay and nothing else: the frames come
244 // out as they went in, one for one.
245 let gain = match self.bypass {
246 true => 1.0,
247 false => self.gain,
248 };
249 for c in 0..channels {
250 out.push(self.line[self.at * channels + c] * gain);
251 }
252 }
253 *buf = out;
254 }
255
256 /// The frames still in the line once the mix has run out, limited: silence is
257 /// fed through and what it pushes out is returned, which is the last
258 /// `lookahead` frames of the stream. Those frames are the tail the mix would
259 /// otherwise drop, and the silence behind them is what the detector needs --
260 /// a waveform that stops mid-cycle is a step to zero, and a meter reads that
261 /// step as an overshoot, so the gain that holds it is taken here, while the
262 /// samples are still in the line. Call it once, at the end.
263 pub fn drain(&mut self) -> Vec<f32> {
264 let mut silence = vec![0.0f32; (self.peaks.len() - 1) * self.channels];
265 self.process(&mut silence);
266 silence
267 }
268
269 /// The gain the loudest frame in the window needs: 1.0 under the knee, the
270 /// knee's own curve across it, `ceiling/peak` above it.
271 fn reduction(&self, peak: f32) -> f32 {
272 let level = 20.0 * peak.log10();
273 let ceiling = 20.0 * self.ceiling.log10();
274 let over = level - ceiling;
275 let out = match over >= KNEE_DB / 2.0 {
276 true => ceiling,
277 // The cookbook's quadratic knee. At `over == 0` this is already
278 // `KNEE_DB/8` under the ceiling and it never crosses it, so nothing
279 // the knee passes needs a clamp behind it.
280 false => level - (over + KNEE_DB / 2.0).powi(2) / (2.0 * KNEE_DB),
281 };
282 10f32.powf((out - level) / 20.0)
283 }
284}
285
286#[cfg(test)]
287mod tests {
288 use super::*;
289 use crate::loudness::Meter;
290 use std::f64::consts::TAU;
291
292 /// The promise the whole file exists for: a sum well past full scale comes
293 /// out under the ceiling, sample for sample, and the quiet part of the same
294 /// stream is left where it was.
295 #[test]
296 fn a_hot_mix_comes_out_under_the_ceiling() {
297 let rate = 48_000;
298 let params = Limiter {
299 ceiling_db: -3.0,
300 on: true,
301 };
302 let mut state = LimiterState::new(&params, rate, 2);
303 // Half a second of quiet, then half a second at 4x full scale: the
304 // join is where an attack overshoot would show.
305 let mut buf: Vec<f32> = (0..rate)
306 .flat_map(|i| {
307 let t = i as f32 / rate as f32;
308 let amp = match i < rate / 2 {
309 true => 0.05,
310 false => 4.0,
311 };
312 let s = amp * (t * 440.0 * std::f32::consts::TAU).sin();
313 [s, s]
314 })
315 .collect();
316 let quiet_in = buf[..rate as usize / 2].to_vec();
317 state.process(&mut buf);
318 let ceiling = db_to_linear(-3.0);
319 let peak = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
320 assert!(
321 peak <= ceiling + 1e-6,
322 "peak {peak} passed the {ceiling} ceiling"
323 );
324 // ...and it is not simply silence: the loud half is right at the wall,
325 // which is the ceiling less the safety margin.
326 assert!(
327 peak > db_to_linear(-3.0 - SAFETY_DB) * 0.99,
328 "peak {peak} is nowhere near the wall"
329 );
330 // The quiet half is untouched, bar the frames the lookahead eats and
331 // the ones where the gain has already started coming down for the loud
332 // part that is about to arrive.
333 let head = quiet_in.len() / 2;
334 for (a, b) in buf[..head].iter().zip(&quiet_in[..head]) {
335 assert!((a - b).abs() < 1e-6, "{a} != {b} under the knee");
336 }
337 // The delay line is paid back, not carried: the output is shorter by
338 // exactly the lookahead and nothing else.
339 assert_eq!(buf.len(), rate as usize * 2 - (state.peaks.len() - 1) * 2);
340 }
341
342 /// A ceiling dragged while the mix runs: the new one is honoured from the
343 /// next block, the delay line keeps running -- so the block is as long as
344 /// it would have been, which is what the master clock counts -- and
345 /// switching the limiter out leaves the samples alone rather than dropping
346 /// the ones still inside the line.
347 #[test]
348 fn a_retune_moves_the_ceiling_and_costs_no_samples() {
349 let rate = 48_000;
350 let mut state = LimiterState::engaged(
351 &Limiter {
352 ceiling_db: -3.0,
353 on: true,
354 },
355 rate,
356 2,
357 );
358 let block: Vec<f32> = (0..2_000).map(|i| 2.0 * ((i % 7) as f32 - 3.0)).collect();
359
360 // Engaged mid-stream: nothing is swallowed, so the count is the count.
361 let mut buf = block.clone();
362 state.process(&mut buf);
363 assert_eq!(buf.len(), block.len(), "an engaged limiter ate samples");
364 let hot = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
365 assert!(hot <= db_to_linear(-3.0) + 1e-6, "peak {hot} passed -3 dB");
366
367 // Down to -12: the same length again, and quieter.
368 state.retune(&Limiter {
369 ceiling_db: -12.0,
370 on: true,
371 });
372 let mut buf = block.clone();
373 state.process(&mut buf);
374 assert_eq!(buf.len(), block.len(), "a retune ate samples");
375 let quiet = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
376 assert!(
377 quiet <= db_to_linear(-12.0) + 1e-6,
378 "peak {quiet} passed -12 dB"
379 );
380 assert!(quiet < hot, "the ceiling did not move: {hot} -> {quiet}");
381
382 // Switched out: the line still delays, so the count still holds, and
383 // what comes out is the mix as it was written.
384 state.retune(&Limiter {
385 ceiling_db: -12.0,
386 on: false,
387 });
388 let mut buf = block.clone();
389 state.process(&mut buf);
390 assert_eq!(buf.len(), block.len(), "a bypass ate samples");
391 let raw = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
392 assert!(raw > 1.0, "bypassed, the mix is untouched: peak {raw}");
393 }
394
395 /// What engaging a limiter mid-stream actually costs, measured rather than
396 /// described: not a momentary hair of silence that the stream then grows
397 /// back from, but a **permanent** shift. `engaged` starts its delay line
398 /// empty and swallows nothing, so from the first block onward the output is
399 /// the input delayed by the whole lookahead -- for the rest of the stream.
400 /// `new` is head-aligned instead: it swallows the lookahead once, at the
401 /// front, and is a block shorter for it.
402 ///
403 /// The two are measured against each other because the difference is the
404 /// whole claim: same tone, same settings, one index offset and one block
405 /// length apart. A permanent offset of at most [`LOOKAHEAD_MS`] is below
406 /// the perceptual threshold, so this pins the *measured* behaviour the doc
407 /// comment on [`LimiterState::engaged`] describes rather than ruling on
408 /// whether it should be changed -- that is a design call, not a bug fix.
409 #[test]
410 fn an_engaged_limiter_shifts_the_stream_by_the_lookahead_for_good() {
411 let rate = 48_000;
412 let params = Limiter {
413 ceiling_db: -3.0,
414 on: true,
415 };
416 let lookahead = ((LOOKAHEAD_MS / 1000.0 * rate as f32) as usize).max(1);
417 // Under the knee throughout, so what comes out is the input and the
418 // only thing being measured is *when* each frame appears.
419 let tone: Vec<f32> = (0..4_000)
420 .flat_map(|i| {
421 let s = 0.1 * (i as f32 / rate as f32 * 440.0 * std::f32::consts::TAU).sin();
422 [s, s]
423 })
424 .collect();
425
426 // `new`: head-aligned, and a block shorter by exactly the lookahead.
427 let mut fresh = LimiterState::new(&params, rate, 2);
428 let mut head = tone.clone();
429 fresh.process(&mut head);
430 assert_eq!(
431 head.len(),
432 tone.len() - lookahead * 2,
433 "a fresh limiter is not head-aligned by exactly the lookahead"
434 );
435
436 // `engaged`: the same count, the same samples -- one lookahead later.
437 let mut live = LimiterState::engaged(&params, rate, 2);
438 let mut shifted = tone.clone();
439 live.process(&mut shifted);
440 assert_eq!(
441 shifted.len(),
442 tone.len(),
443 "an engaged limiter ate samples, which is the thing it exists not to do"
444 );
445 assert_eq!(
446 &shifted[lookahead * 2..],
447 &head[..],
448 "an engaged limiter is not the fresh one delayed by exactly the \
449 lookahead, so what it costs mid-stream is not what the doc claims"
450 );
451 // And the shift is the *stream's*, not one block's. A second block of a
452 // marker the first did not contain comes out *still* delayed by the
453 // lookahead: the head of it is still the tail of the tone, and the
454 // marker itself only appears from the lookahead on. Nothing re-aligns
455 // the line, which is what makes the cost permanent rather than a one-off
456 // at the moment of engaging.
457 // Well under the knee: a marker at the knee would be ringing-limited
458 // by its own step, which is the detector working, not the shift.
459 let marker = vec![0.25; tone.len()];
460 let mut next = marker.clone();
461 live.process(&mut next);
462 assert!(
463 next[..lookahead * 2].iter().any(|s| *s != 0.25),
464 "the second block is aligned where the first was not, so the cost is \
465 a one-off rather than a permanent shift"
466 );
467 assert!(
468 next[lookahead * 2..]
469 .iter()
470 .all(|s| (*s - 0.25).abs() < 1e-6),
471 "the marker is not behind by exactly the lookahead: the stream is not \
472 delayed by a fixed amount from here on"
473 );
474 }
475
476 /// The ceiling is a true-peak ceiling: the samples of a waveform can sit
477 /// under it while the waveform between them does not, and the export is
478 /// measured on the waveform. Held at -1 dBTP, the meter that measures the
479 /// export reads it at or under -1 dBTP, for a crest the samples hide (fs/4
480 /// at 45 degrees, amplitude 1.3, so the samples are +-0.92) and for a dense
481 /// high-frequency mix.
482 #[test]
483 fn a_true_peak_ceiling_holds_on_the_waveform_the_meter_reads() {
484 let rate = 48_000;
485 let params = Limiter {
486 ceiling_db: -1.0,
487 on: true,
488 };
489 let n = rate as usize;
490 let crest: Vec<f32> = (0..n)
491 .flat_map(|i| {
492 let ph = i as f64 * std::f64::consts::FRAC_PI_2 + std::f64::consts::FRAC_PI_4;
493 let s = (1.3 * ph.sin()) as f32;
494 [s, s]
495 })
496 .collect();
497 let dense: Vec<f32> = (0..n)
498 .flat_map(|i| {
499 let t = i as f64 / f64::from(rate);
500 let s = 0.5 * (TAU * 13_000.0 * t + 1.3).sin()
501 + 0.4 * (TAU * 17_500.0 * t + 0.7).sin()
502 + 0.3 * (TAU * 9_000.0 * t + 2.1).sin();
503 [s as f32, (0.5 * (TAU * 13_100.0 * t + 0.2).sin() + 0.4 * (TAU * 17_400.0 * t + 2.9).sin()) as f32]
504 })
505 .collect();
506 // 20 ms of digital silence after each: the meter flushes with zeros, so
507 // a signal cut off mid-wave would read the cut itself as an overshoot.
508 let tail = vec![0.0f32; rate as usize / 50 * 2];
509 for mix in [crest, dense] {
510 let mut state = LimiterState::new(&params, rate, 2);
511 let mut buf = [mix.as_slice(), tail.as_slice()].concat();
512 state.process(&mut buf);
513 let tp = Meter::new(rate, 2);
514 let mut meter = tp.clone();
515 meter.push(&buf);
516 let read = meter.finish().true_peak_dbtp;
517 // The hold is to a thousandth of a dB: the gain moves within the
518 // filter's support, which costs a few ten-thousandths at most.
519 assert!(read <= -0.999, "the meter reads {read} dBTP past the -1 ceiling");
520 }
521 }
522
523 /// The end of the stream. `process` alone keeps the last `lookahead` frames
524 /// in the line, and the export pads what it does not have with silence: a
525 /// step at the cut, which the meter reads as an overshoot. `drain` plays the
526 /// line out, so the whole stream comes out and the stop is held as well.
527 #[test]
528 fn the_tail_drains_and_the_stop_at_the_end_is_held() {
529 let rate = 44_100;
530 let params = Limiter {
531 ceiling_db: -1.0,
532 on: true,
533 };
534 let n = rate as usize / 2;
535 // 900 Hz at 4x full scale, stopped at a sample near its crest.
536 let input: Vec<f32> = (0..n)
537 .flat_map(|i| {
538 let s = 4.0 * (i as f32 * std::f32::consts::TAU * 900.0 / rate as f32).sin();
539 [s, s]
540 })
541 .collect();
542 let mut state = LimiterState::new(&params, rate, 2);
543 let mut out = input.clone();
544 state.process(&mut out);
545 let mut tail = state.drain();
546 out.append(&mut tail);
547 assert_eq!(out.len(), input.len(), "the drained stream is not the whole stream");
548 // The meter, fed the stream and then the silence that follows it.
549 let mut meter = Meter::new(rate, 2);
550 meter.push(&out);
551 meter.push(&vec![0.0f32; rate as usize / 50 * 2]);
552 let read = meter.finish().true_peak_dbtp;
553 assert!(read <= -0.999, "the stop reads {read} dBTP past the -1 ceiling");
554 }
555
556 /// The held level sits [`SAFETY_DB`] under the ceiling named, not at it: a
557 /// hot tone comes out at the named ceiling less the margin, on the sample
558 /// peak, and the setting itself is not moved.
559 #[test]
560 fn the_limiter_holds_a_safety_margin_under_the_ceiling_named() {
561 let rate = 48_000;
562 let named = Limiter {
563 ceiling_db: -1.0,
564 on: true,
565 };
566 let mut state = LimiterState::new(&named, rate, 1);
567 let mut buf: Vec<f32> = (0..rate)
568 .map(|i| 3.0 * (i as f32 * std::f32::consts::TAU * 1_000.0 / rate as f32).sin())
569 .collect();
570 state.process(&mut buf);
571 let peak = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
572 let held = db_to_linear(-1.0 - SAFETY_DB);
573 assert!(peak <= held + 1e-6, "peak {peak} passed the margin {held}");
574 assert!(peak > held * 0.99, "peak {peak} is nowhere near the margin {held}");
575 assert_eq!(named.ceiling_db, -1.0, "the setting itself moved");
576 }
577
578 /// Flat settings are a passthrough, which is what the export invariant
579 /// rests on: 0 dB is exactly 1.0, never 0.9999999.
580 #[test]
581 fn zero_db_is_exactly_unity() {
582 assert_eq!(db_to_linear(0.0), 1.0);
583 assert!((db_to_linear(-6.0) - 0.5011872).abs() < 1e-6);
584 assert!(!Limiter::default().is_active(), "off until asked for");
585 assert_eq!(
586 Limiter::default().with_ceiling(-99.0).ceiling_db,
587 Limiter::MIN_DB
588 );
589 assert_eq!(
590 Limiter::default().with_ceiling(f32::NAN).ceiling_db,
591 Limiter::default().ceiling_db
592 );
593 }
594}
595