forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2c8e3aaTahinli3 months ago335 commits

limiter.rs349 lines, 14.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//! * **Lookahead.** The mix is written into a delay line [`LOOKAHEAD_MS`] long
13//! and read out of it that much later, so the gain a peak needs is already in
14//! force by the time the peak itself is emitted. No attack overshoot -- the
15//! first sample over the ceiling is the first sample held under it, which is
16//! what makes the peak of an exported file a *measurement* and not a hope.
17//! * **Linked channels.** One gain for the frame, off the loudest channel in
18//! it: a per-channel gain would move the stereo image every time one side
19//! peaked.
20//! * **Soft knee.** [`KNEE_DB`] wide and centred on the ceiling, so the gain
21//! comes in gradually instead of switching on at one sample and off at the
22//! next. The knee's own curve never lets the output past the ceiling (at the
23//! centre it is already `KNEE_DB/8` under it), which is what keeps the
24//! guarantee a hard knee would give.
25//! * **Release**, not a per-sample snap back: `RELEASE_MS` of exponential
26//! recovery, so one loud transient does not pump the whole bar around it.
27//!
28//! The latency is *taken out again*, not paid: the first `lookahead` frames of
29//! output -- the empty delay line -- are dropped, so what comes out is sample
30//! aligned with what went in and the sound stays locked to the picture. What
31//! that costs is the last couple of milliseconds of the timeline's tail, which
32//! is the trade every lookahead limiter makes.
33
34/// How far ahead the gain looks. 2 ms is ~96 frames at 48 kHz: long enough to
35/// ride a transient in smoothly, short enough that the tail it eats is nothing.
36const LOOKAHEAD_MS: f32 = 2.0;
37/// How wide the knee is, centred on the ceiling.
38const KNEE_DB: f32 = 6.0;
39/// How fast the gain comes back once the loud part is over.
40const RELEASE_MS: f32 = 120.0;
41
42/// What a project's master limiter is set to: a ceiling in dBFS and whether it
43/// is in circuit at all. Off by default -- a timeline nobody has asked to limit
44/// mixes exactly as it always did, down to the bit.
45#[derive(Clone, Copy, Debug, PartialEq)]
46pub struct Limiter {
47 /// The level nothing may pass, in dBFS (0 dBFS is full scale).
48 pub ceiling_db: f32,
49 pub on: bool,
50}
51
52impl Default for Limiter {
53 fn default() -> Self {
54 Self {
55 ceiling_db: -1.0,
56 on: false,
57 }
58 }
59}
60
61impl Limiter {
62 /// The ceilings a front-end may set, and what a file may name: a limiter
63 /// above full scale would limit nothing, and one 24 dB down is already a
64 /// fader.
65 pub const MIN_DB: f32 = -24.0;
66 pub const MAX_DB: f32 = 0.0;
67
68 /// The setting with `ceiling_db` put inside the range above, which is what
69 /// a nudge and a parsed line both go through. Not finite means the default.
70 pub fn with_ceiling(self, ceiling_db: f32) -> Self {
71 Self {
72 ceiling_db: match ceiling_db.is_finite() {
73 true => ceiling_db.clamp(Self::MIN_DB, Self::MAX_DB),
74 false => Self::default().ceiling_db,
75 },
76 ..self
77 }
78 }
79
80 /// Whether it is doing anything to the sound -- what an export asks before
81 /// it decides a packet copy would be a lie.
82 pub fn is_active(self) -> bool {
83 self.on
84 }
85}
86
87/// dBFS as an amplitude. `db_to_linear(0.0)` is exactly 1.0, which is what
88/// keeps a flat setting a bit-exact passthrough.
89pub fn db_to_linear(db: f32) -> f32 {
90 match db == 0.0 {
91 true => 1.0,
92 false => 10f32.powf(db / 20.0),
93 }
94}
95
96/// One running limiter: the delay line, the peak window and the gain.
97pub struct LimiterState {
98 channels: usize,
99 /// The delayed mix, one frame per slot, `lookahead + 1` frames round.
100 line: Vec<f32>,
101 /// The loudest channel of each frame in `line`, same indexing.
102 peaks: Vec<f32>,
103 /// Where the next frame is written; the frame read out is the one after it.
104 at: usize,
105 /// Frames still to be swallowed before anything is emitted -- the empty
106 /// delay line, which is how the latency is paid back (module docs).
107 warm: usize,
108 gain: f32,
109 /// Switched out while the mix runs ([`LimiterState::retune`]): the line
110 /// still delays and still emits a frame per frame, only nothing is held
111 /// down. Dropping the state instead would drop the frames still inside the
112 /// line, and those frames are what the master clock counts.
113 bypass: bool,
114 ceiling: f32,
115 /// Where the knee starts, as an amplitude: under this the fast path runs
116 /// and no logarithm is taken.
117 knee_floor: f32,
118 release: f32,
119}
120
121impl LimiterState {
122 pub fn new(params: &Limiter, sample_rate: u32, channels: usize) -> Self {
123 let channels = channels.max(1);
124 let frames = ((LOOKAHEAD_MS / 1000.0 * sample_rate as f32) as usize).max(1) + 1;
125 let ceiling_db = params.with_ceiling(params.ceiling_db).ceiling_db;
126 Self {
127 channels,
128 line: vec![0.0; frames * channels],
129 peaks: vec![0.0; frames],
130 at: 0,
131 warm: frames - 1,
132 gain: 1.0,
133 bypass: !params.on,
134 ceiling: db_to_linear(ceiling_db),
135 knee_floor: db_to_linear(ceiling_db - KNEE_DB / 2.0),
136 // One time constant per sample: the gain covers 63% of the way back
137 // in `RELEASE_MS`.
138 release: 1.0 - (-1000.0 / (RELEASE_MS * sample_rate as f32)).exp(),
139 }
140 }
141
142 /// One switched in **while the mix is already running**: the same limiter,
143 /// except that it swallows nothing to fill its delay line -- what comes out
144 /// first is the line's own [`LOOKAHEAD_MS`] of silence and the mix behind
145 /// it, where a fresh state would have eaten that much of the mix instead.
146 ///
147 /// Which matters because the count *is* the clock: a mixer that emitted
148 /// fewer samples than the timeline asked for would slide the picture off
149 /// the sound by the lookahead, once per switch-on. A hair of silence at the
150 /// moment somebody engages a limiter is the honest price.
151 pub fn engaged(params: &Limiter, sample_rate: u32, channels: usize) -> Self {
152 Self {
153 warm: 0,
154 ..Self::new(params, sample_rate, channels)
155 }
156 }
157
158 /// Points a running limiter at another setting -- a ceiling dragged, the
159 /// switch flipped -- without touching the delay line, the peak window or
160 /// the gain it is holding. That is what makes the ceiling a live control:
161 /// rebuilding the state would restart the window (a pump) and lose the
162 /// frames inside the line (a slip against the picture).
163 pub fn retune(&mut self, params: &Limiter) {
164 let ceiling_db = params.with_ceiling(params.ceiling_db).ceiling_db;
165 self.bypass = !params.on;
166 self.ceiling = db_to_linear(ceiling_db);
167 self.knee_floor = db_to_linear(ceiling_db - KNEE_DB / 2.0);
168 }
169
170 /// Rewrites `buf` -- interleaved frames -- as the limited mix. Shorter than
171 /// what came in by the delay line's length, once, at the first call.
172 pub fn process(&mut self, buf: &mut Vec<f32>) {
173 let channels = self.channels;
174 let frames = buf.len() / channels;
175 let mut out: Vec<f32> = Vec::with_capacity(buf.len());
176 for f in 0..frames {
177 let frame = &buf[f * channels..(f + 1) * channels];
178 let peak = frame.iter().fold(0.0f32, |m, s| m.max(s.abs()));
179 self.line[self.at * channels..(self.at + 1) * channels].copy_from_slice(frame);
180 self.peaks[self.at] = peak;
181 self.at = (self.at + 1) % self.peaks.len();
182
183 // Every frame still in the line, the one about to leave included:
184 // the gain below is therefore never larger than what the *emitted*
185 // frame needs, which is the whole no-overshoot guarantee.
186 let window = self.peaks.iter().fold(0.0f32, |m, &p| m.max(p));
187 let want = match window <= self.knee_floor {
188 true => 1.0,
189 false => self.reduction(window),
190 };
191 // Up is the release, down is instant -- and instant is safe here
192 // only because the frame it is for has not been emitted yet.
193 self.gain += (want - self.gain).max(0.0) * self.release;
194 self.gain = self.gain.min(want);
195
196 if self.warm > 0 {
197 self.warm -= 1;
198 continue;
199 }
200 // Bypassed, the line is a delay and nothing else: the frames come
201 // out as they went in, one for one.
202 let gain = match self.bypass {
203 true => 1.0,
204 false => self.gain,
205 };
206 for c in 0..channels {
207 out.push(self.line[self.at * channels + c] * gain);
208 }
209 }
210 *buf = out;
211 }
212
213 /// The gain the loudest frame in the window needs: 1.0 under the knee, the
214 /// knee's own curve across it, `ceiling/peak` above it.
215 fn reduction(&self, peak: f32) -> f32 {
216 let level = 20.0 * peak.log10();
217 let ceiling = 20.0 * self.ceiling.log10();
218 let over = level - ceiling;
219 let out = match over >= KNEE_DB / 2.0 {
220 true => ceiling,
221 // The cookbook's quadratic knee. At `over == 0` this is already
222 // `KNEE_DB/8` under the ceiling and it never crosses it, so nothing
223 // the knee passes needs a clamp behind it.
224 false => level - (over + KNEE_DB / 2.0).powi(2) / (2.0 * KNEE_DB),
225 };
226 10f32.powf((out - level) / 20.0)
227 }
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233
234 /// The promise the whole file exists for: a sum well past full scale comes
235 /// out under the ceiling, sample for sample, and the quiet part of the same
236 /// stream is left where it was.
237 #[test]
238 fn a_hot_mix_comes_out_under_the_ceiling() {
239 let rate = 48_000;
240 let params = Limiter {
241 ceiling_db: -3.0,
242 on: true,
243 };
244 let mut state = LimiterState::new(&params, rate, 2);
245 // Half a second of quiet, then half a second at 4x full scale: the
246 // join is where an attack overshoot would show.
247 let mut buf: Vec<f32> = (0..rate)
248 .flat_map(|i| {
249 let t = i as f32 / rate as f32;
250 let amp = match i < rate / 2 {
251 true => 0.05,
252 false => 4.0,
253 };
254 let s = amp * (t * 440.0 * std::f32::consts::TAU).sin();
255 [s, s]
256 })
257 .collect();
258 let quiet_in = buf[..rate as usize / 2].to_vec();
259 state.process(&mut buf);
260 let ceiling = db_to_linear(-3.0);
261 let peak = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
262 assert!(
263 peak <= ceiling + 1e-6,
264 "peak {peak} passed the {ceiling} ceiling"
265 );
266 // ...and it is not simply silence: the loud half is right at the wall.
267 assert!(
268 peak > ceiling * 0.99,
269 "peak {peak} is nowhere near the wall"
270 );
271 // The quiet half is untouched, bar the frames the lookahead eats and
272 // the ones where the gain has already started coming down for the loud
273 // part that is about to arrive.
274 let head = quiet_in.len() / 2;
275 for (a, b) in buf[..head].iter().zip(&quiet_in[..head]) {
276 assert!((a - b).abs() < 1e-6, "{a} != {b} under the knee");
277 }
278 // The delay line is paid back, not carried: the output is shorter by
279 // exactly the lookahead and nothing else.
280 assert_eq!(buf.len(), rate as usize * 2 - (state.peaks.len() - 1) * 2);
281 }
282
283 /// A ceiling dragged while the mix runs: the new one is honoured from the
284 /// next block, the delay line keeps running -- so the block is as long as
285 /// it would have been, which is what the master clock counts -- and
286 /// switching the limiter out leaves the samples alone rather than dropping
287 /// the ones still inside the line.
288 #[test]
289 fn a_retune_moves_the_ceiling_and_costs_no_samples() {
290 let rate = 48_000;
291 let mut state = LimiterState::engaged(
292 &Limiter {
293 ceiling_db: -3.0,
294 on: true,
295 },
296 rate,
297 2,
298 );
299 let block: Vec<f32> = (0..2_000).map(|i| 2.0 * ((i % 7) as f32 - 3.0)).collect();
300
301 // Engaged mid-stream: nothing is swallowed, so the count is the count.
302 let mut buf = block.clone();
303 state.process(&mut buf);
304 assert_eq!(buf.len(), block.len(), "an engaged limiter ate samples");
305 let hot = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
306 assert!(hot <= db_to_linear(-3.0) + 1e-6, "peak {hot} passed -3 dB");
307
308 // Down to -12: the same length again, and quieter.
309 state.retune(&Limiter {
310 ceiling_db: -12.0,
311 on: true,
312 });
313 let mut buf = block.clone();
314 state.process(&mut buf);
315 assert_eq!(buf.len(), block.len(), "a retune ate samples");
316 let quiet = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
317 assert!(quiet <= db_to_linear(-12.0) + 1e-6, "peak {quiet} passed -12 dB");
318 assert!(quiet < hot, "the ceiling did not move: {hot} -> {quiet}");
319
320 // Switched out: the line still delays, so the count still holds, and
321 // what comes out is the mix as it was written.
322 state.retune(&Limiter {
323 ceiling_db: -12.0,
324 on: false,
325 });
326 let mut buf = block.clone();
327 state.process(&mut buf);
328 assert_eq!(buf.len(), block.len(), "a bypass ate samples");
329 let raw = buf.iter().fold(0.0f32, |m, s| m.max(s.abs()));
330 assert!(raw > 1.0, "bypassed, the mix is untouched: peak {raw}");
331 }
332
333 /// Flat settings are a passthrough, which is what the export invariant
334 /// rests on: 0 dB is exactly 1.0, never 0.9999999.
335 #[test]
336 fn zero_db_is_exactly_unity() {
337 assert_eq!(db_to_linear(0.0), 1.0);
338 assert!((db_to_linear(-6.0) - 0.5011872).abs() < 1e-6);
339 assert!(!Limiter::default().is_active(), "off until asked for");
340 assert_eq!(
341 Limiter::default().with_ceiling(-99.0).ceiling_db,
342 Limiter::MIN_DB
343 );
344 assert_eq!(
345 Limiter::default().with_ceiling(f32::NAN).ceiling_db,
346 Limiter::default().ceiling_db
347 );
348 }
349}