forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

silence.rs621 lines, 26.0 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;
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/// The stretches of `[0, duration)` that `regions` did not cover, same
233/// half-open `(from, to)` seconds, in order, never overlapping.
234pub fn invert(duration: f64, regions: &[(f64, f64)]) -> Vec<(f64, f64)> {
235 if !(duration.is_finite() && duration > 0.) {
236 return Vec::new();
237 }
238 let mut out: Vec<(f64, f64)> = Vec::new();
239 let mut cursor = 0.;
240 for &(from, to) in regions {
241 let (from, to) = (from.clamp(0., duration), to.clamp(0., duration));
242 if to <= from {
243 continue;
244 }
245 if from > cursor {
246 out.push((cursor, from));
247 }
248 cursor = cursor.max(to);
249 }
250 if cursor < duration {
251 out.push((cursor, duration));
252 }
253 out
254}
255
256/// Where those source stretches sit on the timeline, as `(start, len)` frame
257/// pairs of the lane `clip` is on -- what a preview marks and what
258/// [`crate::Project::cut_regions`] cuts.
259///
260/// `regions` are seconds from the clip's **in point**, which is where
261/// [`levels`] was asked to start reading; they land at `in_frame` plus that.
262/// Only the part of each region the clip actually plays survives -- a region
263/// running past `out_frame` is trimmed to it and one starting beyond it is
264/// dropped, so a short read or a rounding at the tail cannot mark a frame the
265/// clip does not have. Positions go through the clip's **own rate**
266/// ([`Speed::timeline_at`]), so a silence in a 2x clip marks the frames it is
267/// really on.
268///
269/// Both edges are rounded **inward** -- start up, end down -- so a frame that
270/// is partly speech stays outside the region at every rate. An empty remainder
271/// is dropped rather than returned as a zero-length cut.
272pub fn timeline_regions(clip: &Clip, fps: f64, regions: &[(f64, f64)]) -> Vec<(u32, u32)> {
273 if !(fps.is_finite() && fps > 0.) {
274 return Vec::new();
275 }
276 let frame = |secs: f64, round: fn(f64) -> f64| {
277 let n = round(secs * fps);
278 n.clamp(0., f64::from(u32::MAX)) as u32
279 };
280 regions
281 .iter()
282 .filter_map(|&(from, to)| {
283 let first = clip.in_frame.saturating_add(frame(from, f64::ceil));
284 let last = clip
285 .in_frame
286 .saturating_add(frame(to, f64::floor))
287 .min(clip.out_frame);
288 if last <= first {
289 return None;
290 }
291 let start = clip.start + clip.timeline_offset(first - clip.in_frame);
292 let end = clip.start + clip.timeline_offset_floor(last - clip.in_frame);
293 (end > start).then_some((start, end - start))
294 })
295 .collect()
296}
297
298#[cfg(test)]
299mod tests {
300 use std::path::PathBuf;
301
302 use super::{Settings, invert, levels, regions, timeline_regions};
303 use crate::project::{Clip, Speed, SpeedKey};
304 use crate::scale::FitPolicy;
305
306 fn asset(name: &str) -> PathBuf {
307 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
308 .join("../../assets")
309 .join(name)
310 }
311
312 fn clip(start: u32, in_frame: u32, out_frame: u32, speed: Speed) -> Clip {
313 Clip {
314 speed_keys: Vec::new(),
315 reversed: false,
316 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
317 angle: Default::default(),
318 fade_in: 0,
319 fade_out: 0,
320 transition_out: 0,
321 transition_kind: Default::default(),
322 visualizer: 0,
323 viz_paint: 0,
324 gain_db: 0.0,
325 gain_keys: Vec::new(),
326 pan: 0,
327 transform_keys: Vec::new(),
328 opacity_keys: Vec::new(),
329 color_keys: Vec::new(),
330 effects: Vec::new(),
331 start,
332 in_frame,
333 out_frame,
334 source: 0,
335 link: None,
336 eq: None,
337 color: None,
338 transform: None,
339 fit: FitPolicy::default(),
340 speed,
341 pitch: 0.0,
342 }
343 }
344
345 /// A level track: `db` for every window, with the named half-open window
346 /// ranges dropped to digital silence.
347 fn track(windows: usize, db: f32, quiet: &[(usize, usize)]) -> Vec<f32> {
348 let mut out = vec![db; windows];
349 for &(from, to) in quiet {
350 out[from..to].fill(super::SILENT_DB);
351 }
352 out
353 }
354
355 /// Seconds compared as seconds: a window edge is a multiple of 0.02 and a
356 /// padding is added to it, neither of which is exact in binary.
357 fn near(got: &[(f64, f64)], want: &[(f64, f64)]) {
358 assert_eq!(got.len(), want.len(), "{got:?} against {want:?}");
359 for (&(a, b), &(c, d)) in got.iter().zip(want) {
360 assert!(
361 (a - c).abs() < 1e-9 && (b - d).abs() < 1e-9,
362 "{got:?} against {want:?}"
363 );
364 }
365 }
366
367 /// The fixture's envelope is `0.5 + 0.5*sin(2*PI*t)`: full silence every
368 /// second at t = 0.75. Detection has to land on those five dips and on
369 /// nothing else -- a scan that lost the chunk positions, or that measured
370 /// peaks instead of RMS, would not line up second after second.
371 #[test]
372 fn the_dips_of_the_1hz_pulse_are_where_the_silences_are() {
373 let levels = levels(asset("test_av.mp4"), 0, (0., f64::INFINITY))
374 .expect("open")
375 .expect("test_av.mp4 has an audio track");
376 // A short forgiveness, because each dip of a sine is brief.
377 let cfg = Settings {
378 threshold_db: -40.,
379 min_silence: 0.08,
380 padding: 0.,
381 min_keep: 0.,
382 };
383 let found = regions(&levels, cfg);
384 assert_eq!(found.len(), 5, "{found:?}");
385 for (second, &(from, to)) in found.iter().enumerate() {
386 let dip = second as f64 + 0.75;
387 assert!(
388 (from..to).contains(&dip),
389 "second {second}: {from}..{to} does not cover the dip at {dip}"
390 );
391 }
392 // Nothing survives a forgiveness longer than any dip is.
393 assert!(
394 regions(
395 &levels,
396 Settings {
397 min_silence: 1.5,
398 ..cfg
399 }
400 )
401 .is_empty()
402 );
403 }
404
405 /// Reporting where a scan has got to changes nothing about what it finds,
406 /// and the word that stops one is heard: the numbers are the plain scan's
407 /// to the last window, the header's duration reaches the card, and a scan
408 /// cancelled before its first chunk comes back with a prefix instead of a
409 /// track -- which is why a cancelled scan is never cached.
410 #[test]
411 fn a_scan_that_reports_itself_finds_exactly_what_the_plain_one_does() {
412 use super::{Progress, levels_with_progress};
413 use std::sync::atomic::Ordering::Relaxed;
414 let progress = Progress::default();
415 let watched = levels_with_progress(asset("test_av.mp4"), 0, (0., f64::INFINITY), &progress)
416 .expect("open")
417 .expect("test_av.mp4 has an audio track");
418 let plain = levels(asset("test_av.mp4"), 0, (0., f64::INFINITY))
419 .expect("open")
420 .expect("audio");
421 assert_eq!(watched, plain, "a watched scan must find the same levels");
422 // Five seconds of fixture, in tenths, from the header and from the last
423 // chunk the loop saw.
424 assert_eq!(progress.total.load(Relaxed), 50);
425 assert!(progress.scanned.load(Relaxed) > 0);
426 assert!(progress.scanned.load(Relaxed) <= progress.total.load(Relaxed));
427 // Cancelled at the door: the loop gives up at its first chunk, the
428 // receiver is dropped and the decoder behind it stops with it.
429 let stopped = Progress::default();
430 stopped.cancel.store(true, Relaxed);
431 let partial = levels_with_progress(asset("test_av.mp4"), 0, (0., f64::INFINITY), &stopped)
432 .expect("open")
433 .expect("audio");
434 assert!(partial.len() < plain.len(), "{} windows", partial.len());
435 }
436
437 /// A clip cut in half costs half a decode, and the half it reads is its
438 /// own: asked for `[2, 4)` seconds the scan hands back two seconds of
439 /// windows, starting at the *second* second -- the fixture's dips at 2.75
440 /// and 3.75 land at 0.75 and 1.75 of what comes back, and the three dips
441 /// outside the range are not in it at all.
442 #[test]
443 fn a_range_is_read_from_its_own_start_and_nothing_outside_it_is() {
444 let cfg = Settings {
445 threshold_db: -40.,
446 min_silence: 0.08,
447 padding: 0.,
448 min_keep: 0.,
449 };
450 let whole = levels(asset("test_av.mp4"), 0, (0., f64::INFINITY))
451 .expect("open")
452 .expect("audio");
453 let half = levels(asset("test_av.mp4"), 0, (2., 4.))
454 .expect("open")
455 .expect("audio");
456 // Two seconds of windows for two seconds asked, give or take the one a
457 // packet boundary rounds -- not the five the file is.
458 assert!(
459 (half.len() as i64 - 100).abs() <= 2 && half.len() < whole.len(),
460 "{} windows for [2, 4) of {} for the file",
461 half.len(),
462 whole.len()
463 );
464 let found = regions(&half, cfg);
465 assert_eq!(found.len(), 2, "{found:?}");
466 for (nth, &(from, to)) in found.iter().enumerate() {
467 let dip = nth as f64 + 0.75;
468 assert!(
469 (from..to).contains(&dip),
470 "dip {nth}: {from}..{to} does not cover {dip}"
471 );
472 }
473 // ...and on the timeline they are where the clip plays them: a clip
474 // reading from source frame 60 at 30 fps, laid at frame 500.
475 let placed = clip(500, 60, 120, Speed::NORMAL);
476 let marks = timeline_regions(&placed, 30., &found);
477 assert_eq!(marks.len(), 2, "{marks:?}");
478 for (nth, &(start, len)) in marks.iter().enumerate() {
479 let dip = 500. + (nth as f64 + 0.75) * 30.;
480 assert!(
481 (f64::from(start)..f64::from(start + len)).contains(&dip),
482 "dip {nth}: [{start}, {}) is not the dip at {dip}",
483 start + len
484 );
485 }
486 }
487
488 /// The three settings, each one visible on its own: a quiet run shorter
489 /// than `min_silence` is forgiven, `padding` shrinks what is left at both
490 /// ends, and a kept sliver shorter than `min_keep` joins the silences
491 /// around it rather than surviving as one-frame confetti.
492 #[test]
493 fn forgiveness_padding_and_min_keep_each_show_up() {
494 // 10 s of speech with a 0.2 s dip, a 1 s silence and a 2 s silence.
495 let levels = track(500, -12., &[(50, 60), (100, 150), (300, 400)]);
496 let bare = Settings {
497 threshold_db: -40.,
498 min_silence: 0.5,
499 padding: 0.,
500 min_keep: 0.,
501 };
502 near(&regions(&levels, bare), &[(2., 3.), (6., 8.)]);
503 // Padding takes 0.15 s off each end of each region, and off nothing
504 // else: a region is 0.3 s shorter and starts 0.15 s later.
505 let padded = regions(
506 &levels,
507 Settings {
508 padding: 0.15,
509 ..bare
510 },
511 );
512 near(&padded, &[(2.15, 2.85), (6.15, 7.85)]);
513 // Two silences with a two-window sliver of speech between them: with
514 // nothing to keep it, the sliver joins them into one region.
515 let sliver = track(500, -12., &[(100, 150), (152, 250)]);
516 assert_eq!(
517 regions(&sliver, bare).len(),
518 2,
519 "the sliver is kept while min_keep is zero"
520 );
521 let merged = regions(
522 &sliver,
523 Settings {
524 min_keep: 0.15,
525 ..bare
526 },
527 );
528 near(&merged, &[(2., 5.)]);
529 }
530
531 /// Where a region lands on the timeline is the clip's business: seconds
532 /// counted from its in point, its placement offsets them, its end trims
533 /// them and its rate divides them. A 2x clip's silences mark half as many
534 /// frames, at the right place.
535 #[test]
536 fn regions_map_through_the_clips_range_and_rate() {
537 let secs = [(1., 2.), (3., 3.5)];
538 // Whole file, real time, placed at the start: seconds read are timeline
539 // frames at 30 fps.
540 let whole = clip(0, 0, 300, Speed::NORMAL);
541 assert_eq!(
542 timeline_regions(&whole, 30., &secs),
543 vec![(30, 30), (90, 15)]
544 );
545 // The same clip placed at frame 100 and reading from source frame 45:
546 // the scan began at 45, so a region a second in is source frame 75 --
547 // and it lands 30 frames after the clip's own start.
548 let placed = clip(100, 45, 300, Speed::NORMAL);
549 assert_eq!(
550 timeline_regions(&placed, 30., &secs),
551 vec![(130, 30), (190, 15)]
552 );
553 // At 2x every timeline frame is two source frames, so both regions are
554 // half as wide and sit half as far along.
555 let fast = clip(0, 0, 300, Speed::from_permille(2000));
556 assert_eq!(timeline_regions(&fast, 30., &secs), vec![(15, 15), (45, 7)]);
557 // A read that ran past the clip's end is trimmed to it, and a region
558 // wholly past it is not on the timeline at all.
559 let short = clip(0, 0, 45, Speed::NORMAL);
560 assert_eq!(timeline_regions(&short, 30., &[(1., 2.)]), vec![(30, 15)]);
561 assert!(timeline_regions(&short, 30., &[(2., 3.)]).is_empty());
562 }
563
564 /// A ramped clip maps a region through the ramp's integral, not one rate: 1x to 2x
565 /// over 60 frames reads source frame `t + t^2/120` at timeline frame `t`, so the
566 /// second of source from frame 30 to 60 starts at timeline 25 (the first frame
567 /// whose source frame is 30 or more) and its end rounds down to 43.
568 #[test]
569 fn regions_map_through_a_ramp_not_a_single_rate() {
570 let ramped = Clip {
571 speed_keys: vec![
572 SpeedKey { at: 0, speed: Speed::NORMAL },
573 SpeedKey { at: 60, speed: Speed::from_permille(2000) },
574 ],
575 ..clip(0, 0, 300, Speed::NORMAL)
576 };
577 assert_eq!(timeline_regions(&ramped, 30., &[(1., 2.)]), vec![(25, 18)]);
578 // Placed at 100 and read from source frame 30: the region is the same 30 source
579 // frames in, so it lands the same 25 frames in.
580 let placed = Clip { start: 100, in_frame: 30, ..ramped };
581 assert_eq!(timeline_regions(&placed, 30., &[(1., 2.)]), vec![(125, 18)]);
582 }
583
584 /// Rounded inward at both ends: a region whose seconds fall between frames
585 /// gives back the frames it *fully* covers, so no frame of speech is ever
586 /// inside a cut. Half a frame of silence is dropped, never claimed.
587 #[test]
588 fn edges_round_inward_so_speech_keeps_its_frames() {
589 let whole = clip(0, 0, 300, Speed::NORMAL);
590 // [1.01, 1.99) s at 30 fps is source frames 30.3 .. 59.7: the region
591 // may only claim 31..59.
592 assert_eq!(
593 timeline_regions(&whole, 30., &[(1.01, 1.99)]),
594 vec![(31, 28)]
595 );
596 // Under a frame wide: nothing survives the rounding, and a zero-length
597 // cut is never handed back.
598 assert!(timeline_regions(&whole, 30., &[(1.01, 1.02)]).is_empty());
599 }
600
601 /// The complement, taken literally: what `regions` kept out is exactly
602 /// what `invert` hands back, an empty scan inverts to the whole span, a
603 /// scan of everything inverts to nothing, and a region hanging past the
604 /// end is clamped to it rather than dragging the answer past `duration`.
605 #[test]
606 fn invert_is_the_complement_of_the_regions_it_is_given() {
607 near(
608 &invert(10., &[(2., 3.), (6., 8.)]),
609 &[(0., 2.), (3., 6.), (8., 10.)],
610 );
611 near(&invert(10., &[]), &[(0., 10.)]);
612 assert!(invert(10., &[(0., 10.)]).is_empty());
613 near(&invert(10., &[(8., 20.)]), &[(0., 8.)]);
614 // No span to invert *of*: zero, negative and nonsense durations
615 // refuse rather than inventing one.
616 assert!(invert(0., &[]).is_empty());
617 assert!(invert(-1., &[]).is_empty());
618 assert!(invert(f64::NAN, &[]).is_empty());
619 assert!(invert(f64::INFINITY, &[]).is_empty());
620 }
621}