forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBef5832fTahinli3 months ago597 commits

silence.rs549 lines, 23.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 *stretch* of a file into one loudness number per 20 ms window,
6//! [`regions`] turns those numbers plus a [`Settings`] into silent stretches of
7//! seconds from where that read began, and [`timeline_regions`] puts those on
8//! the timeline through one clip's own range and rate. A card tweaking a
9//! threshold re-runs the last two and decodes nothing.
10//!
11//! The stretch is the *clip's*, not the file's: a take cut in half is half a
12//! decode, and the half nobody is looking at is never read (which is what a
13//! person means by "scan this clip").
14//!
15//! Loudness in **dBFS**, which is the unit every tool that does this speaks
16//! (ffmpeg's `silencedetect` noise floor, auto-editor's threshold) -- and RMS
17//! rather than the peak [`crate::waveform::peaks`] draws, because a single
18//! sample spike in a breath is not speech and a peak meter cannot tell them
19//! apart.
20
21use std::path::Path;
22use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
23
24use crate::AudioSession;
25use crate::project::{Clip, Speed};
26
27/// Loudness windows per second: 50, i.e. 20 ms each -- short enough to place a
28/// cut inside one frame at any sane rate, long enough that one glottal pulse is
29/// not a silence of its own.
30pub const WINDOWS_PER_SEC: u32 = 50;
31
32/// What a window with no samples in it, or with digital nothing in it, reads
33/// as: a floor rather than `-inf`, so a level is always a number a comparison
34/// and a `Display` can take.
35pub const SILENT_DB: f32 = -120.;
36
37/// What counts as a silence worth cutting. Seconds, not frames: detection runs
38/// on the *sound*, whose sample rate is its own business, and the frame grid
39/// is applied once at the end ([`timeline_regions`]).
40#[derive(Clone, Copy, PartialEq, Debug)]
41pub struct Settings {
42 /// At or below this level a window is quiet.
43 pub threshold_db: f32,
44 /// Quiet shorter than this is forgiven -- the pause between two words is
45 /// not a cut.
46 pub min_silence: f64,
47 /// Kept at both ends of every region, so a cut never lands on the consonant
48 /// that starts the next word.
49 pub padding: f64,
50 /// A kept sliver shorter than this joins the silences either side of it:
51 /// breaths and mouth clicks between two long silences would otherwise
52 /// survive as one-frame confetti nobody can watch.
53 pub min_keep: f64,
54}
55
56impl Default for Settings {
57 /// The conservative end of what shipped tools default to (auto-editor
58 /// ~-28 dBFS / 0.2 s margin, `silencedetect` -60 dB / 2 s): a first run
59 /// that leaves a little too much is a run nobody has to undo.
60 fn default() -> Self {
61 Self {
62 threshold_db: -40.,
63 min_silence: 0.5,
64 padding: 0.15,
65 min_keep: 0.15,
66 }
67 }
68}
69
70/// One RMS level in dBFS per [`WINDOWS_PER_SEC`]th of a second of `stream` of
71/// `path`, over the half-open `range` of **source seconds** -- the same decode
72/// [`crate::waveform::peaks`] runs and with the same contract: channels folded
73/// together, `Ok(None)` for a file with **no audio track at all**, which is a
74/// source to refuse by name rather than one long silence to cut.
75///
76/// `levels[0]` is the window at `range.0`, never the window at media time 0:
77/// what is read is what is asked for, so a clip that plays a minute of a film
78/// costs a minute of decode and the rest of the file is never touched. Whole
79/// file is `(0., f64::INFINITY)`.
80///
81/// Linear in the range's length at ~1700x realtime, so a ten-minute take scans
82/// in well under a second; a caller caches it per source, stream and range,
83/// because the settings above are all applied to the result and none of them
84/// needs a second decode.
85pub fn levels(
86 path: impl AsRef<Path>,
87 stream: usize,
88 range: (f64, f64),
89) -> crate::Result<Option<Vec<f32>>> {
90 levels_with_progress(path, stream, range, &Progress::default())
91}
92
93/// What a running [`levels_with_progress`] says about itself while it runs, and
94/// the one word that stops it. Tenths of a second rather than a fraction: how
95/// far into the sound the decode has come is a fact the moment it starts, where
96/// a percentage needs a duration the header does not always carry.
97///
98/// Shared by an [`Arc`](std::sync::Arc) between the worker and whatever is
99/// drawing it, the way an export's progress is.
100#[derive(Default, Debug)]
101pub struct Progress {
102 /// Source time decoded so far, in tenths of a second. Only ever grows.
103 pub scanned: AtomicU64,
104 /// What the header claims the whole track is, in tenths of a second, or `0`
105 /// for a file that does not say -- the estimate is drawn as `~` and a `0`
106 /// is drawn as nothing rather than as a lie.
107 pub total: AtomicU64,
108 /// Set by whoever asked for the scan when nobody is waiting for it any
109 /// more. The loop below reads it once per chunk and gives up there; the
110 /// decoder behind it stops with the dropped receiver.
111 pub cancel: AtomicBool,
112}
113
114/// [`levels`] reporting where it has come to and stopping when it is told to.
115///
116/// A **cancelled scan returns what it had got to**, which is a prefix of the
117/// track and not an answer: the caller sets [`Progress::cancel`], so the caller
118/// is the one that must check it before believing the result.
119pub fn levels_with_progress(
120 path: impl AsRef<Path>,
121 stream: usize,
122 range: (f64, f64),
123 progress: &Progress,
124) -> crate::Result<Option<Vec<f32>>> {
125 let from = range.0.max(0.);
126 let sources = [(path.as_ref().to_path_buf(), stream)];
127 let Some((meta, rx)) = AudioSession::open_multi_streams(&sources, &[(Some(0), from, range.1)])?
128 else {
129 return Ok(None);
130 };
131 let rate = f64::from(meta.sample_rate).max(1.);
132 if let Some(total) = meta.total_samples {
133 // What is left to read, not what the file is: the line has to count out
134 // of the stretch the scan actually decodes or it stalls at a third.
135 let secs = (total as f64 / rate).min(range.1) - from;
136 progress.total.store((secs.max(0.) * 10.) as u64, Relaxed);
137 }
138 // Fractional for `peaks`'s reason: 44100 / 50 is whole, 44100 / 30 is not,
139 // and a rounded window drifts a bucket every few seconds over a long take.
140 let per_window = f64::from(meta.sample_rate) / f64::from(WINDOWS_PER_SEC);
141 let channels = (meta.channels as usize).max(1);
142 // Chunks are stamped in the source's own samples, counted from where the
143 // segment starts reading -- so a scan of a clip an hour in would otherwise
144 // build an hour of empty windows in front of it, and every one of those
145 // reads as digital silence and would fuse with the first real quiet of the
146 // clip. The window the range begins at is window zero here instead.
147 let base = (from * f64::from(WINDOWS_PER_SEC)) as usize;
148 // Sum of squares and how many samples went into it -- the two halves of a
149 // mean square, kept in f64 because a loud minute is millions of terms.
150 let mut sums: Vec<(f64, u64)> = Vec::new();
151 for chunk in rx {
152 // Once per chunk, not per sample: a cancelled scan may run one block
153 // longer, and a progress line moves in blocks anyway.
154 if progress.cancel.load(Relaxed) {
155 break;
156 }
157 progress.scanned.store(
158 ((chunk.start_sample as f64 / rate - from).max(0.) * 10.) as u64,
159 Relaxed,
160 );
161 for (frame, values) in chunk.samples.chunks(channels).enumerate() {
162 let at = ((chunk.start_sample + frame as u64) as f64 / per_window) as usize;
163 let window = at.saturating_sub(base);
164 if window >= sums.len() {
165 sums.resize(window + 1, (0., 0));
166 }
167 let slot = &mut sums[window];
168 for &v in values {
169 slot.0 += f64::from(v) * f64::from(v);
170 slot.1 += 1;
171 }
172 }
173 }
174 Ok(Some(sums.iter().map(|&(sq, n)| dbfs(sq, n)).collect()))
175}
176
177/// Mean square -> dBFS, floored at [`SILENT_DB`]: full scale is 1.0, so a
178/// window of digital zero is `-inf` and is reported as the floor instead.
179fn dbfs(square_sum: f64, samples: u64) -> f32 {
180 if samples == 0 {
181 return SILENT_DB;
182 }
183 let rms = (square_sum / samples as f64).sqrt();
184 if rms <= 0. {
185 return SILENT_DB;
186 }
187 (20. * rms.log10()).max(f64::from(SILENT_DB)) as f32
188}
189
190/// The silent stretches of a `levels` track, as half-open `(from, to)` seconds
191/// **from where the read began**, in order and never overlapping.
192///
193/// Pure arithmetic: this is what a card re-runs on every keystroke. The three
194/// settings are applied in the order a person means them -- quiet runs first,
195/// then the short ones forgiven ([`Settings::min_silence`]), then a
196/// [`Settings::padding`] left at both ends so the cut never touches speech, and
197/// last the slivers too short to keep ([`Settings::min_keep`]) swallowed by the
198/// silences around them. Padding before the merge on purpose: what the merge
199/// measures is what would actually survive the cut.
200pub fn regions(levels: &[f32], cfg: Settings) -> Vec<(f64, f64)> {
201 let window = 1. / f64::from(WINDOWS_PER_SEC);
202 let mut quiet: Vec<(f64, f64)> = Vec::new();
203 let mut run: Option<usize> = None;
204 for (i, &db) in levels.iter().enumerate() {
205 match (db <= cfg.threshold_db, run) {
206 (true, None) => run = Some(i),
207 (false, Some(from)) => {
208 quiet.push((from as f64 * window, i as f64 * window));
209 run = None;
210 }
211 _ => {}
212 }
213 }
214 if let Some(from) = run {
215 quiet.push((from as f64 * window, levels.len() as f64 * window));
216 }
217 let padded = quiet
218 .into_iter()
219 .filter(|&(from, to)| to - from >= cfg.min_silence)
220 .map(|(from, to)| (from + cfg.padding, to - cfg.padding))
221 .filter(|&(from, to)| to > from);
222 let mut out: Vec<(f64, f64)> = Vec::new();
223 for (from, to) in padded {
224 match out.last_mut() {
225 Some(last) if from - last.1 < cfg.min_keep => last.1 = to,
226 _ => out.push((from, to)),
227 }
228 }
229 out
230}
231
232/// Where those source stretches sit on the timeline, as `(start, len)` frame
233/// pairs of the lane `clip` is on -- what a preview marks and what
234/// [`crate::Project::cut_regions`] cuts.
235///
236/// `regions` are seconds from the clip's **in point**, which is where
237/// [`levels`] was asked to start reading; they land at `in_frame` plus that.
238/// Only the part of each region the clip actually plays survives -- a region
239/// running past `out_frame` is trimmed to it and one starting beyond it is
240/// dropped, so a short read or a rounding at the tail cannot mark a frame the
241/// clip does not have. Positions go through the clip's **own rate**
242/// ([`Speed::timeline_at`]), so a silence in a 2x clip marks the frames it is
243/// really on.
244///
245/// Both edges are rounded **inward** -- start up, end down -- so a frame that
246/// is partly speech stays outside the region at every rate. An empty remainder
247/// is dropped rather than returned as a zero-length cut.
248pub fn timeline_regions(clip: &Clip, fps: f64, regions: &[(f64, f64)]) -> Vec<(u32, u32)> {
249 if !(fps.is_finite() && fps > 0.) {
250 return Vec::new();
251 }
252 let frame = |secs: f64, round: fn(f64) -> f64| {
253 let n = round(secs * fps);
254 n.clamp(0., f64::from(u32::MAX)) as u32
255 };
256 regions
257 .iter()
258 .filter_map(|&(from, to)| {
259 let first = clip.in_frame.saturating_add(frame(from, f64::ceil));
260 let last = clip
261 .in_frame
262 .saturating_add(frame(to, f64::floor))
263 .min(clip.out_frame);
264 if last <= first {
265 return None;
266 }
267 let start = clip.start + clip.speed.timeline_at(first - clip.in_frame);
268 let end = clip.start + floor_timeline(clip.speed, last - clip.in_frame);
269 (end > start).then_some((start, end - start))
270 })
271 .collect()
272}
273
274/// [`Speed::timeline_at`] floored instead of ceiled: which timeline frame of a
275/// clip a source frame lands on, rounded the way an *end* has to be so a
276/// region never eats the frame speech starts on. The ceil is the right rounding
277/// for a start and for playback's stamps, and this is its partner.
278fn floor_timeline(speed: Speed, offset: u32) -> u32 {
279 (u64::from(offset) * 1000 / u64::from(speed.permille())).min(u64::from(u32::MAX)) as u32
280}
281
282#[cfg(test)]
283mod tests {
284 use std::path::PathBuf;
285
286 use super::{Settings, levels, regions, timeline_regions};
287 use crate::project::{Clip, Speed};
288 use crate::scale::FitPolicy;
289
290 fn asset(name: &str) -> PathBuf {
291 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
292 .join("../../assets")
293 .join(name)
294 }
295
296 fn clip(start: u32, in_frame: u32, out_frame: u32, speed: Speed) -> Clip {
297 Clip {
298 fade_in: 0,
299 fade_out: 0,
300 transition_out: 0,
301 start,
302 in_frame,
303 out_frame,
304 source: 0,
305 link: None,
306 eq: None,
307 color: None,
308 transform: None,
309 fit: FitPolicy::default(),
310 speed,
311 }
312 }
313
314 /// A level track: `db` for every window, with the named half-open window
315 /// ranges dropped to digital silence.
316 fn track(windows: usize, db: f32, quiet: &[(usize, usize)]) -> Vec<f32> {
317 let mut out = vec![db; windows];
318 for &(from, to) in quiet {
319 out[from..to].fill(super::SILENT_DB);
320 }
321 out
322 }
323
324 /// Seconds compared as seconds: a window edge is a multiple of 0.02 and a
325 /// padding is added to it, neither of which is exact in binary.
326 fn near(got: &[(f64, f64)], want: &[(f64, f64)]) {
327 assert_eq!(got.len(), want.len(), "{got:?} against {want:?}");
328 for (&(a, b), &(c, d)) in got.iter().zip(want) {
329 assert!(
330 (a - c).abs() < 1e-9 && (b - d).abs() < 1e-9,
331 "{got:?} against {want:?}"
332 );
333 }
334 }
335
336 /// The fixture's envelope is `0.5 + 0.5*sin(2*PI*t)`: full silence every
337 /// second at t = 0.75. Detection has to land on those five dips and on
338 /// nothing else -- a scan that lost the chunk positions, or that measured
339 /// peaks instead of RMS, would not line up second after second.
340 #[test]
341 fn the_dips_of_the_1hz_pulse_are_where_the_silences_are() {
342 let levels = levels(asset("test_av.mp4"), 0, (0., f64::INFINITY))
343 .expect("open")
344 .expect("test_av.mp4 has an audio track");
345 // A short forgiveness, because each dip of a sine is brief.
346 let cfg = Settings {
347 threshold_db: -40.,
348 min_silence: 0.08,
349 padding: 0.,
350 min_keep: 0.,
351 };
352 let found = regions(&levels, cfg);
353 assert_eq!(found.len(), 5, "{found:?}");
354 for (second, &(from, to)) in found.iter().enumerate() {
355 let dip = second as f64 + 0.75;
356 assert!(
357 (from..to).contains(&dip),
358 "second {second}: {from}..{to} does not cover the dip at {dip}"
359 );
360 }
361 // Nothing survives a forgiveness longer than any dip is.
362 assert!(
363 regions(
364 &levels,
365 Settings {
366 min_silence: 1.5,
367 ..cfg
368 }
369 )
370 .is_empty()
371 );
372 }
373
374 /// Reporting where a scan has got to changes nothing about what it finds,
375 /// and the word that stops one is heard: the numbers are the plain scan's
376 /// to the last window, the header's duration reaches the card, and a scan
377 /// cancelled before its first chunk comes back with a prefix instead of a
378 /// track -- which is why a cancelled scan is never cached.
379 #[test]
380 fn a_scan_that_reports_itself_finds_exactly_what_the_plain_one_does() {
381 use super::{Progress, levels_with_progress};
382 use std::sync::atomic::Ordering::Relaxed;
383 let progress = Progress::default();
384 let watched = levels_with_progress(asset("test_av.mp4"), 0, (0., f64::INFINITY), &progress)
385 .expect("open")
386 .expect("test_av.mp4 has an audio track");
387 let plain = levels(asset("test_av.mp4"), 0, (0., f64::INFINITY))
388 .expect("open")
389 .expect("audio");
390 assert_eq!(watched, plain, "a watched scan must find the same levels");
391 // Five seconds of fixture, in tenths, from the header and from the last
392 // chunk the loop saw.
393 assert_eq!(progress.total.load(Relaxed), 50);
394 assert!(progress.scanned.load(Relaxed) > 0);
395 assert!(progress.scanned.load(Relaxed) <= progress.total.load(Relaxed));
396 // Cancelled at the door: the loop gives up at its first chunk, the
397 // receiver is dropped and the decoder behind it stops with it.
398 let stopped = Progress::default();
399 stopped.cancel.store(true, Relaxed);
400 let partial = levels_with_progress(asset("test_av.mp4"), 0, (0., f64::INFINITY), &stopped)
401 .expect("open")
402 .expect("audio");
403 assert!(partial.len() < plain.len(), "{} windows", partial.len());
404 }
405
406 /// A clip cut in half costs half a decode, and the half it reads is its
407 /// own: asked for `[2, 4)` seconds the scan hands back two seconds of
408 /// windows, starting at the *second* second -- the fixture's dips at 2.75
409 /// and 3.75 land at 0.75 and 1.75 of what comes back, and the three dips
410 /// outside the range are not in it at all.
411 #[test]
412 fn a_range_is_read_from_its_own_start_and_nothing_outside_it_is() {
413 let cfg = Settings {
414 threshold_db: -40.,
415 min_silence: 0.08,
416 padding: 0.,
417 min_keep: 0.,
418 };
419 let whole = levels(asset("test_av.mp4"), 0, (0., f64::INFINITY))
420 .expect("open")
421 .expect("audio");
422 let half = levels(asset("test_av.mp4"), 0, (2., 4.))
423 .expect("open")
424 .expect("audio");
425 // Two seconds of windows for two seconds asked, give or take the one a
426 // packet boundary rounds -- not the five the file is.
427 assert!(
428 (half.len() as i64 - 100).abs() <= 2 && half.len() < whole.len(),
429 "{} windows for [2, 4) of {} for the file",
430 half.len(),
431 whole.len()
432 );
433 let found = regions(&half, cfg);
434 assert_eq!(found.len(), 2, "{found:?}");
435 for (nth, &(from, to)) in found.iter().enumerate() {
436 let dip = nth as f64 + 0.75;
437 assert!(
438 (from..to).contains(&dip),
439 "dip {nth}: {from}..{to} does not cover {dip}"
440 );
441 }
442 // ...and on the timeline they are where the clip plays them: a clip
443 // reading from source frame 60 at 30 fps, laid at frame 500.
444 let placed = clip(500, 60, 120, Speed::NORMAL);
445 let marks = timeline_regions(&placed, 30., &found);
446 assert_eq!(marks.len(), 2, "{marks:?}");
447 for (nth, &(start, len)) in marks.iter().enumerate() {
448 let dip = 500. + (nth as f64 + 0.75) * 30.;
449 assert!(
450 (f64::from(start)..f64::from(start + len)).contains(&dip),
451 "dip {nth}: [{start}, {}) is not the dip at {dip}",
452 start + len
453 );
454 }
455 }
456
457 /// The three settings, each one visible on its own: a quiet run shorter
458 /// than `min_silence` is forgiven, `padding` shrinks what is left at both
459 /// ends, and a kept sliver shorter than `min_keep` joins the silences
460 /// around it rather than surviving as one-frame confetti.
461 #[test]
462 fn forgiveness_padding_and_min_keep_each_show_up() {
463 // 10 s of speech with a 0.2 s dip, a 1 s silence and a 2 s silence.
464 let levels = track(500, -12., &[(50, 60), (100, 150), (300, 400)]);
465 let bare = Settings {
466 threshold_db: -40.,
467 min_silence: 0.5,
468 padding: 0.,
469 min_keep: 0.,
470 };
471 near(&regions(&levels, bare), &[(2., 3.), (6., 8.)]);
472 // Padding takes 0.15 s off each end of each region, and off nothing
473 // else: a region is 0.3 s shorter and starts 0.15 s later.
474 let padded = regions(
475 &levels,
476 Settings {
477 padding: 0.15,
478 ..bare
479 },
480 );
481 near(&padded, &[(2.15, 2.85), (6.15, 7.85)]);
482 // Two silences with a two-window sliver of speech between them: with
483 // nothing to keep it, the sliver joins them into one region.
484 let sliver = track(500, -12., &[(100, 150), (152, 250)]);
485 assert_eq!(
486 regions(&sliver, bare).len(),
487 2,
488 "the sliver is kept while min_keep is zero"
489 );
490 let merged = regions(
491 &sliver,
492 Settings {
493 min_keep: 0.15,
494 ..bare
495 },
496 );
497 near(&merged, &[(2., 5.)]);
498 }
499
500 /// Where a region lands on the timeline is the clip's business: seconds
501 /// counted from its in point, its placement offsets them, its end trims
502 /// them and its rate divides them. A 2x clip's silences mark half as many
503 /// frames, at the right place.
504 #[test]
505 fn regions_map_through_the_clips_range_and_rate() {
506 let secs = [(1., 2.), (3., 3.5)];
507 // Whole file, real time, placed at the start: seconds read are timeline
508 // frames at 30 fps.
509 let whole = clip(0, 0, 300, Speed::NORMAL);
510 assert_eq!(
511 timeline_regions(&whole, 30., &secs),
512 vec![(30, 30), (90, 15)]
513 );
514 // The same clip placed at frame 100 and reading from source frame 45:
515 // the scan began at 45, so a region a second in is source frame 75 --
516 // and it lands 30 frames after the clip's own start.
517 let placed = clip(100, 45, 300, Speed::NORMAL);
518 assert_eq!(
519 timeline_regions(&placed, 30., &secs),
520 vec![(130, 30), (190, 15)]
521 );
522 // At 2x every timeline frame is two source frames, so both regions are
523 // half as wide and sit half as far along.
524 let fast = clip(0, 0, 300, Speed::from_permille(2000));
525 assert_eq!(timeline_regions(&fast, 30., &secs), vec![(15, 15), (45, 7)]);
526 // A read that ran past the clip's end is trimmed to it, and a region
527 // wholly past it is not on the timeline at all.
528 let short = clip(0, 0, 45, Speed::NORMAL);
529 assert_eq!(timeline_regions(&short, 30., &[(1., 2.)]), vec![(30, 15)]);
530 assert!(timeline_regions(&short, 30., &[(2., 3.)]).is_empty());
531 }
532
533 /// Rounded inward at both ends: a region whose seconds fall between frames
534 /// gives back the frames it *fully* covers, so no frame of speech is ever
535 /// inside a cut. Half a frame of silence is dropped, never claimed.
536 #[test]
537 fn edges_round_inward_so_speech_keeps_its_frames() {
538 let whole = clip(0, 0, 300, Speed::NORMAL);
539 // [1.01, 1.99) s at 30 fps is source frames 30.3 .. 59.7: the region
540 // may only claim 31..59.
541 assert_eq!(
542 timeline_regions(&whole, 30., &[(1.01, 1.99)]),
543 vec![(31, 28)]
544 );
545 // Under a frame wide: nothing survives the rounding, and a zero-length
546 // cut is never handed back.
547 assert!(timeline_regions(&whole, 30., &[(1.01, 1.02)]).is_empty());
548 }
549}