forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

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