forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

silence.rs380 lines, 15.3 KiBHistoryRawDownload
1//! Where a clip goes quiet: RMS levels off the same read-only decode path the
2//! waveform takes, and the stretches of them nobody wants to watch.
3//!
4//! Three steps, kept apart so only the first one costs a decode: [`levels`]
5//! turns a file into one loudness number per 20 ms window, [`regions`] turns
6//! those numbers plus a [`Settings`] into silent stretches of *source* seconds,
7//! and [`timeline_regions`] puts those on the timeline through one clip's own
8//! range and rate. A card tweaking a threshold re-runs the last two and decodes
9//! nothing.
10//!
11//! Loudness in **dBFS**, which is the unit every tool that does this speaks
12//! (ffmpeg's `silencedetect` noise floor, auto-editor's threshold) -- and RMS
13//! rather than the peak [`crate::waveform::peaks`] draws, because a single
14//! sample spike in a breath is not speech and a peak meter cannot tell them
15//! apart.
16
17use std::path::Path;
18
19use crate::AudioSession;
20use crate::project::{Clip, Speed};
21
22/// Loudness windows per second: 50, i.e. 20 ms each -- short enough to place a
23/// cut inside one frame at any sane rate, long enough that one glottal pulse is
24/// not a silence of its own.
25pub const WINDOWS_PER_SEC: u32 = 50;
26
27/// What a window with no samples in it, or with digital nothing in it, reads
28/// as: a floor rather than `-inf`, so a level is always a number a comparison
29/// and a `Display` can take.
30pub const SILENT_DB: f32 = -120.;
31
32/// What counts as a silence worth cutting. Seconds, not frames: detection runs
33/// on the *source*, whose sample rate is its own business, and the frame grid
34/// is applied once at the end ([`timeline_regions`]).
35#[derive(Clone, Copy, PartialEq, Debug)]
36pub struct Settings {
37 /// At or below this level a window is quiet.
38 pub threshold_db: f32,
39 /// Quiet shorter than this is forgiven -- the pause between two words is
40 /// not a cut.
41 pub min_silence: f64,
42 /// Kept at both ends of every region, so a cut never lands on the consonant
43 /// that starts the next word.
44 pub padding: f64,
45 /// A kept sliver shorter than this joins the silences either side of it:
46 /// breaths and mouth clicks between two long silences would otherwise
47 /// survive as one-frame confetti nobody can watch.
48 pub min_keep: f64,
49}
50
51impl Default for Settings {
52 /// The conservative end of what shipped tools default to (auto-editor
53 /// ~-28 dBFS / 0.2 s margin, `silencedetect` -60 dB / 2 s): a first run
54 /// that leaves a little too much is a run nobody has to undo.
55 fn default() -> Self {
56 Self {
57 threshold_db: -40.,
58 min_silence: 0.5,
59 padding: 0.15,
60 min_keep: 0.15,
61 }
62 }
63}
64
65/// One RMS level in dBFS per [`WINDOWS_PER_SEC`]th of a second of `stream` of
66/// `path`, from media time 0 -- the same decode [`crate::waveform::peaks`] runs
67/// and with the same contract: channels folded together, `Ok(None)` for a file
68/// with **no audio track at all**, which is a source to refuse by name rather
69/// than one long silence to cut.
70///
71/// Linear in source length at ~1700x realtime, so a ten-minute take scans in
72/// well under a second; a caller caches it per source and stream, because the
73/// settings above are all applied to the result and none of them needs a second
74/// decode.
75pub fn levels(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<Vec<f32>>> {
76 let sources = [(path.as_ref().to_path_buf(), stream)];
77 let Some((meta, rx)) =
78 AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])?
79 else {
80 return Ok(None);
81 };
82 // Fractional for `peaks`'s reason: 44100 / 50 is whole, 44100 / 30 is not,
83 // and a rounded window drifts a bucket every few seconds over a long take.
84 let per_window = f64::from(meta.sample_rate) / f64::from(WINDOWS_PER_SEC);
85 let channels = (meta.channels as usize).max(1);
86 // Sum of squares and how many samples went into it -- the two halves of a
87 // mean square, kept in f64 because a loud minute is millions of terms.
88 let mut sums: Vec<(f64, u64)> = Vec::new();
89 for chunk in rx {
90 for (frame, values) in chunk.samples.chunks(channels).enumerate() {
91 let window = ((chunk.start_sample + frame as u64) as f64 / per_window) as usize;
92 if window >= sums.len() {
93 sums.resize(window + 1, (0., 0));
94 }
95 let slot = &mut sums[window];
96 for &v in values {
97 slot.0 += f64::from(v) * f64::from(v);
98 slot.1 += 1;
99 }
100 }
101 }
102 Ok(Some(sums.iter().map(|&(sq, n)| dbfs(sq, n)).collect()))
103}
104
105/// Mean square -> dBFS, floored at [`SILENT_DB`]: full scale is 1.0, so a
106/// window of digital zero is `-inf` and is reported as the floor instead.
107fn dbfs(square_sum: f64, samples: u64) -> f32 {
108 if samples == 0 {
109 return SILENT_DB;
110 }
111 let rms = (square_sum / samples as f64).sqrt();
112 if rms <= 0. {
113 return SILENT_DB;
114 }
115 (20. * rms.log10()).max(f64::from(SILENT_DB)) as f32
116}
117
118/// The silent stretches of a `levels` track, as half-open `(from, to)` *source*
119/// seconds, in order and never overlapping.
120///
121/// Pure arithmetic: this is what a card re-runs on every keystroke. The three
122/// settings are applied in the order a person means them -- quiet runs first,
123/// then the short ones forgiven ([`Settings::min_silence`]), then a
124/// [`Settings::padding`] left at both ends so the cut never touches speech, and
125/// last the slivers too short to keep ([`Settings::min_keep`]) swallowed by the
126/// silences around them. Padding before the merge on purpose: what the merge
127/// measures is what would actually survive the cut.
128pub fn regions(levels: &[f32], cfg: Settings) -> Vec<(f64, f64)> {
129 let window = 1. / f64::from(WINDOWS_PER_SEC);
130 let mut quiet: Vec<(f64, f64)> = Vec::new();
131 let mut run: Option<usize> = None;
132 for (i, &db) in levels.iter().enumerate() {
133 match (db <= cfg.threshold_db, run) {
134 (true, None) => run = Some(i),
135 (false, Some(from)) => {
136 quiet.push((from as f64 * window, i as f64 * window));
137 run = None;
138 }
139 _ => {}
140 }
141 }
142 if let Some(from) = run {
143 quiet.push((from as f64 * window, levels.len() as f64 * window));
144 }
145 let padded = quiet
146 .into_iter()
147 .filter(|&(from, to)| to - from >= cfg.min_silence)
148 .map(|(from, to)| (from + cfg.padding, to - cfg.padding))
149 .filter(|&(from, to)| to > from);
150 let mut out: Vec<(f64, f64)> = Vec::new();
151 for (from, to) in padded {
152 match out.last_mut() {
153 Some(last) if from - last.1 < cfg.min_keep => last.1 = to,
154 _ => out.push((from, to)),
155 }
156 }
157 out
158}
159
160/// Where those source stretches sit on the timeline, as `(start, len)` frame
161/// pairs of the lane `clip` is on -- what a preview marks and what
162/// [`crate::Project::cut_regions`] cuts.
163///
164/// Only the part of each region the clip actually plays: the scan reads the
165/// whole file and the clip is a range of it, so a silence outside `[in, out)`
166/// is not on the timeline at all. Positions go through the clip's **own rate**
167/// ([`Speed::timeline_at`]), so a silence in a 2x clip marks the frames it is
168/// really on.
169///
170/// Both edges are rounded **inward** -- start up, end down -- so a frame that
171/// is partly speech stays outside the region at every rate. An empty remainder
172/// is dropped rather than returned as a zero-length cut.
173pub fn timeline_regions(clip: &Clip, fps: f64, regions: &[(f64, f64)]) -> Vec<(u32, u32)> {
174 if !(fps.is_finite() && fps > 0.) {
175 return Vec::new();
176 }
177 let frame = |secs: f64, round: fn(f64) -> f64| {
178 let n = round(secs * fps);
179 n.clamp(0., f64::from(u32::MAX)) as u32
180 };
181 regions
182 .iter()
183 .filter_map(|&(from, to)| {
184 let first = frame(from, f64::ceil).max(clip.in_frame);
185 let last = frame(to, f64::floor).min(clip.out_frame);
186 if last <= first {
187 return None;
188 }
189 let start = clip.start + clip.speed.timeline_at(first - clip.in_frame);
190 let end = clip.start + floor_timeline(clip.speed, last - clip.in_frame);
191 (end > start).then_some((start, end - start))
192 })
193 .collect()
194}
195
196/// [`Speed::timeline_at`] floored instead of ceiled: which timeline frame of a
197/// clip a source frame lands on, rounded the way an *end* has to be so a
198/// region never eats the frame speech starts on. The ceil is the right rounding
199/// for a start and for playback's stamps, and this is its partner.
200fn floor_timeline(speed: Speed, offset: u32) -> u32 {
201 (u64::from(offset) * 1000 / u64::from(speed.permille())).min(u64::from(u32::MAX)) as u32
202}
203
204#[cfg(test)]
205mod tests {
206 use std::path::PathBuf;
207
208 use super::{Settings, levels, regions, timeline_regions};
209 use crate::project::{Clip, Speed};
210 use crate::scale::FitPolicy;
211
212 fn asset(name: &str) -> PathBuf {
213 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
214 .join("../../assets")
215 .join(name)
216 }
217
218 fn clip(start: u32, in_frame: u32, out_frame: u32, speed: Speed) -> Clip {
219 Clip {
220 start,
221 in_frame,
222 out_frame,
223 source: 0,
224 link: None,
225 eq: None,
226 color: None,
227 fit: FitPolicy::default(),
228 speed,
229 }
230 }
231
232 /// A level track: `db` for every window, with the named half-open window
233 /// ranges dropped to digital silence.
234 fn track(windows: usize, db: f32, quiet: &[(usize, usize)]) -> Vec<f32> {
235 let mut out = vec![db; windows];
236 for &(from, to) in quiet {
237 out[from..to].fill(super::SILENT_DB);
238 }
239 out
240 }
241
242 /// Seconds compared as seconds: a window edge is a multiple of 0.02 and a
243 /// padding is added to it, neither of which is exact in binary.
244 fn near(got: &[(f64, f64)], want: &[(f64, f64)]) {
245 assert_eq!(got.len(), want.len(), "{got:?} against {want:?}");
246 for (&(a, b), &(c, d)) in got.iter().zip(want) {
247 assert!(
248 (a - c).abs() < 1e-9 && (b - d).abs() < 1e-9,
249 "{got:?} against {want:?}"
250 );
251 }
252 }
253
254 /// The fixture's envelope is `0.5 + 0.5*sin(2*PI*t)`: full silence every
255 /// second at t = 0.75. Detection has to land on those five dips and on
256 /// nothing else -- a scan that lost the chunk positions, or that measured
257 /// peaks instead of RMS, would not line up second after second.
258 #[test]
259 fn the_dips_of_the_1hz_pulse_are_where_the_silences_are() {
260 let levels = levels(asset("test_av.mp4"), 0)
261 .expect("open")
262 .expect("test_av.mp4 has an audio track");
263 // A short forgiveness, because each dip of a sine is brief.
264 let cfg = Settings {
265 threshold_db: -40.,
266 min_silence: 0.08,
267 padding: 0.,
268 min_keep: 0.,
269 };
270 let found = regions(&levels, cfg);
271 assert_eq!(found.len(), 5, "{found:?}");
272 for (second, &(from, to)) in found.iter().enumerate() {
273 let dip = second as f64 + 0.75;
274 assert!(
275 (from..to).contains(&dip),
276 "second {second}: {from}..{to} does not cover the dip at {dip}"
277 );
278 }
279 // Nothing survives a forgiveness longer than any dip is.
280 assert!(
281 regions(
282 &levels,
283 Settings {
284 min_silence: 1.5,
285 ..cfg
286 }
287 )
288 .is_empty()
289 );
290 }
291
292 /// The three settings, each one visible on its own: a quiet run shorter
293 /// than `min_silence` is forgiven, `padding` shrinks what is left at both
294 /// ends, and a kept sliver shorter than `min_keep` joins the silences
295 /// around it rather than surviving as one-frame confetti.
296 #[test]
297 fn forgiveness_padding_and_min_keep_each_show_up() {
298 // 10 s of speech with a 0.2 s dip, a 1 s silence and a 2 s silence.
299 let levels = track(500, -12., &[(50, 60), (100, 150), (300, 400)]);
300 let bare = Settings {
301 threshold_db: -40.,
302 min_silence: 0.5,
303 padding: 0.,
304 min_keep: 0.,
305 };
306 near(&regions(&levels, bare), &[(2., 3.), (6., 8.)]);
307 // Padding takes 0.15 s off each end of each region, and off nothing
308 // else: a region is 0.3 s shorter and starts 0.15 s later.
309 let padded = regions(
310 &levels,
311 Settings {
312 padding: 0.15,
313 ..bare
314 },
315 );
316 near(&padded, &[(2.15, 2.85), (6.15, 7.85)]);
317 // Two silences with a two-window sliver of speech between them: with
318 // nothing to keep it, the sliver joins them into one region.
319 let sliver = track(500, -12., &[(100, 150), (152, 250)]);
320 assert_eq!(
321 regions(&sliver, bare).len(),
322 2,
323 "the sliver is kept while min_keep is zero"
324 );
325 let merged = regions(
326 &sliver,
327 Settings {
328 min_keep: 0.15,
329 ..bare
330 },
331 );
332 near(&merged, &[(2., 5.)]);
333 }
334
335 /// Where a region lands on the timeline is the clip's business: its range
336 /// clips what was scanned, its placement offsets it, and its rate divides
337 /// it. A 2x clip's silences mark half as many frames, at the right place.
338 #[test]
339 fn regions_map_through_the_clips_range_and_rate() {
340 let secs = [(1., 2.), (3., 3.5)];
341 // Whole file, real time, placed at the start: source seconds are
342 // timeline frames at 30 fps.
343 let whole = clip(0, 0, 300, Speed::NORMAL);
344 assert_eq!(
345 timeline_regions(&whole, 30., &secs),
346 vec![(30, 30), (90, 15)]
347 );
348 // The same clip placed at frame 100 and reading from source frame 45:
349 // the first region is only the half of it the clip still plays, and it
350 // lands at the clip's own start.
351 let placed = clip(100, 45, 300, Speed::NORMAL);
352 assert_eq!(
353 timeline_regions(&placed, 30., &secs),
354 vec![(100, 15), (145, 15)]
355 );
356 // At 2x every timeline frame is two source frames, so both regions are
357 // half as wide and sit half as far along.
358 let fast = clip(0, 0, 300, Speed::from_permille(2000));
359 assert_eq!(timeline_regions(&fast, 30., &secs), vec![(15, 15), (45, 7)]);
360 // A region entirely outside what the clip plays is not on the timeline.
361 assert!(timeline_regions(&clip(0, 200, 300, Speed::NORMAL), 30., &[(1., 2.)]).is_empty());
362 }
363
364 /// Rounded inward at both ends: a region whose seconds fall between frames
365 /// gives back the frames it *fully* covers, so no frame of speech is ever
366 /// inside a cut. Half a frame of silence is dropped, never claimed.
367 #[test]
368 fn edges_round_inward_so_speech_keeps_its_frames() {
369 let whole = clip(0, 0, 300, Speed::NORMAL);
370 // [1.01, 1.99) s at 30 fps is source frames 30.3 .. 59.7: the region
371 // may only claim 31..59.
372 assert_eq!(
373 timeline_regions(&whole, 30., &[(1.01, 1.99)]),
374 vec![(31, 28)]
375 );
376 // Under a frame wide: nothing survives the rounding, and a zero-length
377 // cut is never handed back.
378 assert!(timeline_regions(&whole, 30., &[(1.01, 1.02)]).is_empty());
379 }
380}