forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

duck.rs309 lines, 12.1 KiBHistoryRawDownload
1//! Auto-ducking: one audio lane drops in level while another lane (the key,
2//! usually dialogue) is loud, so a music bed sits under speech.
3//!
4//! The shared DSP. [`Ducker`] is one target lane's gain reduction and is run by
5//! the mixer ([`crate::audio`]) once per block, on the post-gain signal of the
6//! key lane. Playback and export both sum through that mixer, so the two cannot
7//! disagree about where a duck lands.
8//!
9//! The detector is the key's RMS over a 10 ms window (the channels are averaged
10//! into one power per frame first). The reduction is a *linear ramp in dB*:
11//! while the key is at or above the threshold the gain falls towards
12//! `depth_db` at `|depth_db| / attack_ms` per millisecond, so it has reached
13//! the full depth exactly `attack_ms` after the key arrives; once the key drops
14//! away it climbs back to 0 dB over `release_ms` the same way. A linear-in-dB
15//! ramp keeps those two times literal, which a one-pole would not.
16
17/// The deepest a duck may cut, in dB.
18pub const MIN_DEPTH_DB: f32 = -40.0;
19/// The shallowest: 0 dB, which is a duck that does nothing.
20pub const MAX_DEPTH_DB: f32 = 0.0;
21/// The quietest key level a threshold may name, in dBFS.
22pub const MIN_THRESHOLD_DB: f32 = -90.0;
23/// The loudest: a key at full scale is always above it, so the duck never fires.
24pub const MAX_THRESHOLD_DB: f32 = 0.0;
25/// The slowest attack, in ms. The fastest is [`MIN_TIME_MS`].
26pub const MAX_ATTACK_MS: f32 = 2000.0;
27/// The slowest release, in ms.
28pub const MAX_RELEASE_MS: f32 = 10000.0;
29/// The shortest attack or release a ramp is made of, in ms: a zero would be a
30/// step, which divides by nothing and clicks.
31pub const MIN_TIME_MS: f32 = 1.0;
32/// The window the key's level is measured over, in ms.
33pub const DETECT_MS: f32 = 10.0;
34
35/// One audio lane's duck, as the project holds it ([`crate::Project::set_lane_duck`]).
36#[derive(Clone, Copy, Debug, PartialEq)]
37pub struct Duck {
38 /// The key lane: the 0-based position of an audio lane in the order
39 /// [`crate::Project::audio_lanes`] lists them, which is the order the mix
40 /// sums them in. Never the duck's own lane.
41 pub under: usize,
42 /// How far the lane drops while the key is loud, in dB (`-40..=0`).
43 pub depth_db: f32,
44 /// The key level, in dBFS, that triggers the duck (`-90..=0`).
45 pub threshold_db: f32,
46 /// How long the drop takes to reach full depth, in ms.
47 pub attack_ms: f32,
48 /// How long the recovery to 0 dB takes, in ms.
49 pub release_ms: f32,
50}
51
52impl Duck {
53 /// The threshold a duck starts at, in dBFS.
54 pub const DEFAULT_THRESHOLD_DB: f32 = -40.0;
55 /// The attack a duck starts at, in ms.
56 pub const DEFAULT_ATTACK_MS: f32 = 80.0;
57 /// The release a duck starts at, in ms.
58 pub const DEFAULT_RELEASE_MS: f32 = 400.0;
59
60 /// A duck under `under` at `depth_db`, with the default threshold and times.
61 pub fn new(under: usize, depth_db: f32) -> Self {
62 Self {
63 under,
64 depth_db,
65 threshold_db: Self::DEFAULT_THRESHOLD_DB,
66 attack_ms: Self::DEFAULT_ATTACK_MS,
67 release_ms: Self::DEFAULT_RELEASE_MS,
68 }
69 }
70
71 /// The same duck with every number clamped into its range. `None` when a
72 /// number is not finite: there is no clamp for a NaN that means something.
73 pub fn clamped(self) -> Option<Self> {
74 let finite = [
75 self.depth_db,
76 self.threshold_db,
77 self.attack_ms,
78 self.release_ms,
79 ]
80 .iter()
81 .all(|v| v.is_finite());
82 finite.then_some(Self {
83 under: self.under,
84 depth_db: self.depth_db.clamp(MIN_DEPTH_DB, MAX_DEPTH_DB),
85 threshold_db: self.threshold_db.clamp(MIN_THRESHOLD_DB, MAX_THRESHOLD_DB),
86 attack_ms: self.attack_ms.clamp(MIN_TIME_MS, MAX_ATTACK_MS),
87 release_ms: self.release_ms.clamp(MIN_TIME_MS, MAX_RELEASE_MS),
88 })
89 }
90}
91
92/// One target lane's duck while the mix runs: the key's detector and the
93/// reduction it has reached. State carries from block to block, so a block
94/// boundary is not a step in the gain.
95#[derive(Clone, Debug)]
96pub struct Ducker {
97 duck: Duck,
98 /// The key's per-frame power (channel mean of the squares) over the last
99 /// [`DETECT_MS`], kept as a ring so the window is exact.
100 window: Vec<f64>,
101 pos: usize,
102 /// The sum of `window`, in f64 so that a long run does not drift.
103 sum: f64,
104 /// The reduction now, in dB: `0.0` at rest, down to `depth_db` at most.
105 gain_db: f32,
106 /// How far the reduction may move per frame, in dB.
107 step_attack: f32,
108 step_release: f32,
109}
110
111impl Ducker {
112 /// A ducker at rest (0 dB) for `duck`, at `rate` Hz.
113 pub fn new(duck: &Duck, rate: u32) -> Self {
114 let frames = ((DETECT_MS * 0.001 * rate as f32).round() as usize).max(1);
115 let mut ducker = Self {
116 duck: *duck,
117 window: vec![0.0; frames],
118 pos: 0,
119 sum: 0.0,
120 gain_db: 0.0,
121 step_attack: 0.0,
122 step_release: 0.0,
123 };
124 ducker.retune(duck, rate);
125 ducker
126 }
127
128 /// Takes a new duck's numbers, keeping the detector and the reduction where
129 /// they are: a fader moved under the mix is a change of slope, not a click.
130 pub fn retune(&mut self, duck: &Duck, rate: u32) {
131 self.duck = *duck;
132 let rate = rate.max(1) as f32;
133 let depth = self.duck.depth_db.abs();
134 self.step_attack = depth / (self.duck.attack_ms.max(MIN_TIME_MS) * 0.001 * rate);
135 self.step_release = depth / (self.duck.release_ms.max(MIN_TIME_MS) * 0.001 * rate);
136 }
137
138 /// The reduction now, in dB (`0.0` or negative).
139 pub fn gain_db(&self) -> f32 {
140 self.gain_db
141 }
142
143 /// Ducks `target` by the key's level. `key` and `target` are interleaved
144 /// with `channels` channels and are read frame by frame over the shorter of
145 /// the two. The key is only read: the caller passes the key's signal as it
146 /// was before any duck touched it.
147 pub fn process(&mut self, key: &[f32], target: &mut [f32], channels: usize) {
148 if channels == 0 {
149 return;
150 }
151 let frames = key.len().min(target.len()) / channels;
152 let threshold = self.duck.threshold_db;
153 let depth = self.duck.depth_db;
154 for f in 0..frames {
155 let base = f * channels;
156 let frame = &key[base..base + channels];
157 let power = frame.iter().map(|&s| f64::from(s) * f64::from(s)).sum::<f64>()
158 / channels as f64;
159 // The window's oldest frame leaves and this one takes its place.
160 self.sum += power - self.window[self.pos];
161 self.window[self.pos] = power;
162 self.pos = (self.pos + 1) % self.window.len();
163 let mean = (self.sum.max(0.0)) / self.window.len() as f64;
164 let level_db = (10.0 * (mean + 1e-12).log10()) as f32;
165
166 let want = if level_db >= threshold { depth } else { 0.0 };
167 if want < self.gain_db {
168 self.gain_db = (self.gain_db - self.step_attack).max(want);
169 } else if want > self.gain_db {
170 self.gain_db = (self.gain_db + self.step_release).min(want);
171 }
172 // At rest the samples are left exactly as they were.
173 if self.gain_db != 0.0 {
174 let g = 10f32.powf(self.gain_db / 20.0);
175 for s in &mut target[base..base + channels] {
176 *s *= g;
177 }
178 }
179 }
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 const RATE: u32 = 48_000;
188
189 /// `ms` of a stereo tone at `amp`, interleaved.
190 fn tone(amp: f32, ms: f32) -> Vec<f32> {
191 let frames = (ms * 0.001 * RATE as f32) as usize;
192 (0..frames)
193 .flat_map(|i| {
194 let s = amp * (i as f32 * 0.05).sin();
195 [s, s]
196 })
197 .collect()
198 }
199
200 fn silence(ms: f32) -> Vec<f32> {
201 vec![0.0; (ms * 0.001 * RATE as f32) as usize * 2]
202 }
203
204 fn db(lin: f32) -> f32 {
205 20.0 * lin.log10()
206 }
207
208 /// The gain the target's first frame of `[at_ms..]` carries, in dB, read off
209 /// a constant-amplitude target so the ratio is the gain.
210 fn gain_at(ducker: &mut Ducker, key: &[f32], ms: f32) -> f32 {
211 let ones = vec![1.0f32; key.len()];
212 let mut out = ones.clone();
213 ducker.process(key, &mut out, 2);
214 let frame = ((ms * 0.001 * RATE as f32) as usize).min(out.len() / 2 - 1) * 2;
215 db(out[frame])
216 }
217
218 #[test]
219 fn silence_under_the_key_never_reduces() {
220 let duck = Duck::new(0, -12.0);
221 let mut ducker = Ducker::new(&duck, RATE);
222 let key = silence(500.0);
223 let mut target = tone(0.5, 500.0);
224 let before = target.clone();
225 ducker.process(&key, &mut target, 2);
226 assert_eq!(target, before, "a silent key leaves the lane bit-exact");
227 assert_eq!(ducker.gain_db(), 0.0);
228 }
229
230 #[test]
231 fn a_key_below_threshold_never_reduces() {
232 let duck = Duck::new(0, -12.0);
233 let mut ducker = Ducker::new(&duck, RATE);
234 // -60 dBFS, under the -40 dBFS default threshold.
235 let key = tone(0.001, 300.0);
236 let mut target = tone(0.5, 300.0);
237 let before = target.clone();
238 ducker.process(&key, &mut target, 2);
239 assert_eq!(target, before);
240 }
241
242 #[test]
243 fn a_loud_key_reaches_the_depth_within_the_attack_time() {
244 let duck = Duck::new(0, -12.0); // attack 80 ms by default
245 let mut ducker = Ducker::new(&duck, RATE);
246 let key = tone(0.5, 300.0); // -6 dBFS, well over the threshold at once
247 // Halfway through the attack the reduction is half the depth...
248 let mid = gain_at(&mut ducker, &key, 40.0);
249 assert!((mid + 6.0).abs() < 0.3, "half way is half the depth, got {mid}");
250 // ...and at the end of it, the full depth, which it stays at.
251 let mut ducker = Ducker::new(&duck, RATE);
252 let end = gain_at(&mut ducker, &key, 80.0);
253 assert!((end + 12.0).abs() < 0.3, "the depth within attack_ms, got {end}");
254 assert!((ducker.gain_db() + 12.0).abs() < 1e-3, "and it holds there");
255 }
256
257 #[test]
258 fn the_reduction_releases_back_to_unity() {
259 let duck = Duck::new(0, -12.0); // release 400 ms
260 let mut ducker = Ducker::new(&duck, RATE);
261 let loud = tone(0.5, 300.0);
262 let mut target = vec![1.0f32; loud.len()];
263 ducker.process(&loud, &mut target, 2);
264 assert!((ducker.gain_db() + 12.0).abs() < 1e-3, "down first");
265 // Silence for the detector's 10 ms to let go, then half the release.
266 let quiet = silence(10.0 + 200.0);
267 let mut target = vec![1.0f32; quiet.len()];
268 ducker.process(&quiet, &mut target, 2);
269 assert!(
270 (ducker.gain_db() + 6.0).abs() < 0.3,
271 "half way back after half the release, got {}",
272 ducker.gain_db()
273 );
274 let rest = silence(220.0);
275 let mut target = vec![1.0f32; rest.len()];
276 ducker.process(&rest, &mut target, 2);
277 assert_eq!(ducker.gain_db(), 0.0, "back at unity after the release");
278 assert_eq!(target.last().copied(), Some(1.0), "and the samples are untouched again");
279 }
280
281 #[test]
282 fn retune_keeps_the_reduction_it_has_reached() {
283 let duck = Duck::new(0, -12.0);
284 let mut ducker = Ducker::new(&duck, RATE);
285 let loud = tone(0.5, 200.0);
286 let mut target = vec![1.0f32; loud.len()];
287 ducker.process(&loud, &mut target, 2);
288 let reached = ducker.gain_db();
289 ducker.retune(&Duck::new(0, -6.0), RATE);
290 assert_eq!(ducker.gain_db(), reached, "a change of depth is not a click");
291 }
292
293 #[test]
294 fn clamped_bounds_every_number_and_refuses_nan() {
295 let wild = Duck {
296 under: 1,
297 depth_db: -90.0,
298 threshold_db: 20.0,
299 attack_ms: 0.0,
300 release_ms: 1e9,
301 };
302 let tame = wild.clamped().expect("finite");
303 assert_eq!(tame.depth_db, MIN_DEPTH_DB);
304 assert_eq!(tame.threshold_db, MAX_THRESHOLD_DB);
305 assert_eq!(tame.attack_ms, MIN_TIME_MS);
306 assert_eq!(tame.release_ms, MAX_RELEASE_MS);
307 assert!(Duck { depth_db: f32::NAN, ..wild }.clamped().is_none());
308 }
309}