forge
Explore
Log in

Don't you dare go Hollow

The scan reads the clip that was asked about, not the film it came from

Browse files at this commit

dec2ced478c844bb94157a80ca3a5ce51b84a557Ahmet Kaan GümüşParent: 0e324ec
  • feat
    • the scan reads the clip that was asked about, not the film it came from
Show full message
✨ feat(silence): the scan reads the clip that was asked about, not the film it came from

A take cut in half was still decoding the whole source and then throwing
most of the answer away: the levels were read from media time 0 to the
end of the file, and only `timeline_regions` remembered the clip had a
range at all. Now the range *is* the read.

`silence::levels` takes the half-open source seconds to scan and hands
back windows counted from its own start; `timeline_regions` lands those
at `in_frame` plus that and trims to `out_frame`. The card names a scan
by source, stream **and** the clip's frames (`ScanKey`), so a trimmed
clip is a read of its own and a re-trim is not answered from the cache.

Half a take is half a wait, and what it finds is what is still on the
timeline.
crates/app/src/main.rsmodified+83 -31
@@ -410,14 +410,21 @@ impl Import {
410410 }
411411 }
412412
413+/// What a scan is *of*: the source, which of its audio streams, and the clip's
414+/// own `[in, out)` source frames. The range is part of the name because it is
415+/// part of the read -- a clip cut in half is a different, shorter decode than
416+/// the whole take was, and levels read for one are not the other's.
417+type ScanKey = (PathBuf, usize, u32, u32);
418+
413419 /// The silence scan a worker is running, as the card shows it. Same two clocks
414420 /// as an [`Import`] and for the same reason -- one proves the window answers,
415421 /// one says the read has stopped moving -- over a progress that *can* move:
416422 /// a decode knows how far into the sound it has come, so the card says so.
417423 struct SilenceScan {
418- /// Source and stream being scanned, which is the cache key the levels land
419- /// under and what tells a second open of the same clip from a new one.
420- key: (PathBuf, usize),
424+ /// Source, stream and source range being scanned, which is the cache key
425+ /// the levels land under and what tells a second open of the same clip from
426+ /// a new one.
427+ key: ScanKey,
421428 /// When the worker started, for the elapsed clock.
422429 started: Instant,
423430 /// Written by the worker, read here every repaint. The cancel flag in it is
@@ -1490,12 +1497,12 @@ struct Player {
14901497 /// over and what an apply acts on -- *exactly* the previewed set, never a
14911498 /// second scan at the moment of the press.
14921499 silence_marks: Vec<(u32, u32)>,
1493- /// The levels of every source scanned this session, kept so moving a
1494- /// threshold is arithmetic rather than another decode. Keyed by source and
1495- /// stream, and not one entry: two films on one timeline would otherwise
1496- /// evict each other, and the decode being paid twice is the fifty seconds
1497- /// this card exists to not spend.
1498- silence_levels: HashMap<(PathBuf, usize), Arc<Vec<f32>>>,
1500+ /// The levels of every stretch scanned this session, kept so moving a
1501+ /// threshold is arithmetic rather than another decode. Keyed by
1502+ /// [`ScanKey`], and not one entry: two films on one timeline would
1503+ /// otherwise evict each other, and the decode being paid twice is the fifty
1504+ /// seconds this card exists to not spend.
1505+ silence_levels: HashMap<ScanKey, Arc<Vec<f32>>>,
14991506 /// The scan a worker is running for the card, if one is. `None` means the
15001507 /// card is drawing numbers it already has.
15011508 silence_scan: Option<SilenceScan>,
@@ -2560,8 +2567,9 @@ impl Player {
25602567 /// Opens the silence card on the clip to be scanned: the selected one, or
25612568 /// -- with nothing selected -- the clip the picture is coming from, which is
25622569 /// the rule the speed card follows and what a person means by "this shot".
2563- /// Either half of a take will do: the scan reads the *source*, and both
2564- /// halves of an A/V take name the same file.
2570+ /// Either half of a take will do: both halves of an A/V take name the same
2571+ /// file and play the same source frames, which is the whole of what a scan
2572+ /// is of ([`ScanKey`]).
25652573 ///
25662574 /// The card is up on the next frame whatever the file is: a still is
25672575 /// refused by name here, where the answer costs a look at the path, and
@@ -2584,16 +2592,16 @@ impl Player {
25842592 .map(|clip| audio_half(session, clip))
25852593 {
25862594 Some((lane, idx)) => {
2587- let source = self.session.as_ref().and_then(|session| {
2588- let clip = session.lane_clips(lane).get(idx)?;
2589- session.sources().get(clip.source).cloned()
2595+ let found = self.session.as_ref().and_then(|session| {
2596+ let clip = *session.lane_clips(lane).get(idx)?;
2597+ Some((session.sources().get(clip.source)?.clone(), clip))
25902598 });
25912599 // A still is asked *before* the decoder is: handing a png to the
25922600 // mp4 demuxer answers "a box with a larger size than it", which
25932601 // is a true sentence about a container and nothing a person can
25942602 // act on. A picture has no sound for the same reason a silent
25952603 // video has none, so it is refused in the same words.
2596- let Some(source) = source else {
2604+ let Some((source, clip)) = found else {
25972605 cx.notify();
25982606 return;
25992607 };
@@ -2611,7 +2619,15 @@ impl Player {
26112619 self.color_open = None;
26122620 self.speed_open = None;
26132621 self.context_menu = None;
2614- let key = (source.path.clone(), source.audio_stream);
2622+ // The clip's own range, not the file's: the scan reads what this
2623+ // clip plays and nothing else, so a take cut in half costs half
2624+ // the decode and finds only what is still on the timeline.
2625+ let key = (
2626+ source.path.clone(),
2627+ source.audio_stream,
2628+ clip.in_frame,
2629+ clip.out_frame,
2630+ );
26152631 match scan_plan(
26162632 self.silence_levels.contains_key(&key),
26172633 self.silence_scan.as_ref().map(|scan| &scan.key),
@@ -2733,13 +2749,18 @@ impl Player {
27332749 ///
27342750 /// Whatever was scanning is cancelled first: one card, one scan, and the
27352751 /// clip that has just been asked about is the one worth the disk.
2736- fn start_silence_scan(&mut self, key: (PathBuf, usize), cx: &mut Context<Self>) {
2752+ ///
2753+ /// Only the clip's own `[in, out)` is read -- source frames over the
2754+ /// project's rate, the same seconds [`engine::Project`] hands the decoder
2755+ /// for playback -- so half a take is half a wait.
2756+ fn start_silence_scan(&mut self, key: ScanKey, cx: &mut Context<Self>) {
27372757 self.cancel_silence_scan();
27382758 self.silence_marks.clear();
27392759 let progress = Arc::new(engine::silence::Progress::default());
2760+ let range = source_secs(&key, self.fps);
27402761 let scan = cx.background_executor().spawn({
27412762 let (key, progress) = (key.clone(), Arc::clone(&progress));
2742- async move { engine::silence::levels_with_progress(&key.0, key.1, &progress) }
2763+ async move { engine::silence::levels_with_progress(&key.0, key.1, range, &progress) }
27432764 });
27442765 let now = Instant::now();
27452766 self.silence_scan = Some(SilenceScan {
@@ -2819,7 +2840,12 @@ impl Player {
28192840 // line. The marks arrive with the levels.
28202841 let Some(levels) = self
28212842 .silence_levels
2822- .get(&(source.path.clone(), source.audio_stream))
2843+ .get(&(
2844+ source.path.clone(),
2845+ source.audio_stream,
2846+ clip.in_frame,
2847+ clip.out_frame,
2848+ ))
28232849 .cloned()
28242850 else {
28252851 return;
@@ -9948,7 +9974,7 @@ enum ScanPlan {
99489974 /// Which of the three [`ScanPlan`]s opening the card on `key` means. The whole
99499975 /// of the cache policy, and the reason a second film does not cost the first
99509976 /// one its levels: what is cached is asked per source, never "the last one".
9951-fn scan_plan(cached: bool, running: Option<&(PathBuf, usize)>, key: &(PathBuf, usize)) -> ScanPlan {
9977+fn scan_plan(cached: bool, running: Option<&ScanKey>, key: &ScanKey) -> ScanPlan {
99529978 match (cached, running) {
99539979 (true, _) => ScanPlan::Marks,
99549980 (false, Some(at)) if at == key => ScanPlan::Wait,
@@ -9956,6 +9982,18 @@ fn scan_plan(cached: bool, running: Option<&(PathBuf, usize)>, key: &(PathBuf, u
99569982 }
99579983 }
99589984
9985+/// The half-open source seconds a [`ScanKey`]'s frames name, at the project's
9986+/// rate -- what [`engine::silence::levels`] is asked to read, and the same
9987+/// arithmetic playback puts a clip's `in_frame` through. A rate that is not a
9988+/// rate reads the whole file rather than an empty window: a scan of nothing is
9989+/// worse than a scan of too much.
9990+fn source_secs(key: &ScanKey, fps: f64) -> (f64, f64) {
9991+ match fps.is_finite() && fps > 0. {
9992+ true => (f64::from(key.2) / fps, f64::from(key.3) / fps),
9993+ false => (0., f64::INFINITY),
9994+ }
9995+}
9996+
99599997 /// What the silence card says while its worker reads. Unlike an import this
99609998 /// one *has* a fraction -- a decode knows how far into the sound it has come --
99619999 /// so the line is where it is up to, out of what the header claims the track is
@@ -10059,9 +10097,9 @@ mod tests {
1005910097 ZOOM_MIN_FRAMES, ZOOM_OUT_MARGIN, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri,
1006010098 fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution,
1006110099 note_progress, px_along,
10062- IMPORT_STALL, Import, ImportStage, SEEK_STALL, ScanPlan, SilenceScan, import_line,
10100+ IMPORT_STALL, Import, ImportStage, SEEK_STALL, ScanKey, ScanPlan, SilenceScan, import_line,
1006310101 Landing, arrival, launch_queue,
10064- read_ahead, scan_plan, seek_line, silence_line, stash_or_write,
10102+ read_ahead, scan_plan, seek_line, silence_line, source_secs, stash_or_write,
1006510103 repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label,
1006610104 clip_width, trimmed_clip, trims, unscannable, unusable,
1006710105 visible_slice,
@@ -14043,7 +14081,7 @@ mod tests {
1404314081 progress.total.store(7680, Relaxed);
1404414082 let started = Instant::now() - Duration::from_secs(9);
1404514083 let mut scan = SilenceScan {
14046- key: (PathBuf::from("/films/A Film.mkv"), 0),
14084+ key: (PathBuf::from("/films/A Film.mkv"), 0, 0, 192_000),
1404714085 started,
1404814086 progress: Arc::clone(&progress),
1404914087 seen: 0,
@@ -14082,18 +14120,20 @@ mod tests {
1408214120 assert_eq!(scan.since, held, "an unchanged mark must not reset it");
1408314121 }
1408414122
14085- /// The cache is per source, which is what stops two films thrashing each
14086- /// other's fifty seconds: A, then B, then A again is *one* decode of A.
14087- /// And a source already being read is waited for rather than read twice --
14088- /// both halves of an A/V take name the same file.
14123+ /// The cache is per scanned stretch, which is what stops two films
14124+ /// thrashing each other's fifty seconds: A, then B, then A again is *one*
14125+ /// decode of A. And a stretch already being read is waited for rather than
14126+ /// read twice -- both halves of an A/V take name the same file and the same
14127+ /// frames. A *trimmed* A is not A: it is a shorter read of its own, which
14128+ /// is the whole point of scanning the clip instead of the file.
1408914129 #[test]
1409014130 fn a_second_film_does_not_cost_the_first_one_its_levels() {
1409114131 let (a, b) = (
14092- (PathBuf::from("/films/a.mkv"), 0),
14093- (PathBuf::from("/films/b.mkv"), 0),
14132+ (PathBuf::from("/films/a.mkv"), 0, 0, 3000),
14133+ (PathBuf::from("/films/b.mkv"), 0, 0, 3000),
1409414134 );
14095- let mut cache: std::collections::HashMap<(PathBuf, usize), ()> =
14096- std::collections::HashMap::new();
14135+ let half = (PathBuf::from("/films/a.mkv"), 0, 0, 1500);
14136+ let mut cache: std::collections::HashMap<ScanKey, ()> = std::collections::HashMap::new();
1409714137 let mut started = Vec::new();
1409814138 // What a card open does, three times over, with the worker landing
1409914139 // between each: plan, and start what the plan says to start.
@@ -14117,6 +14157,18 @@ mod tests {
1411714157 assert_eq!(scan_plan(false, Some(&b), &a), ScanPlan::Start);
1411814158 // Levels in hand beat a worker either way: the marks are arithmetic.
1411914159 assert_eq!(scan_plan(true, Some(&a), &a), ScanPlan::Marks);
14160+ // The same file cut in half is a read of its own: neither A's levels
14161+ // nor A's worker answers for it.
14162+ assert_eq!(
14163+ scan_plan(cache.contains_key(&half), None, &half),
14164+ ScanPlan::Start
14165+ );
14166+ assert_eq!(scan_plan(false, Some(&a), &half), ScanPlan::Start);
14167+ // ...and the seconds asked for are the clip's, at the project's rate.
14168+ assert_eq!(source_secs(&half, 30.), (0., 50.));
14169+ assert_eq!(source_secs(&(half.0.clone(), 0, 900, 1500), 30.), (30., 50.));
14170+ // A rate that is not one reads the file rather than nothing.
14171+ assert_eq!(source_secs(&half, 0.), (0., f64::INFINITY));
1412014172 }
1412114173
1412214174 /// The two halves a worker hands back for an import, unwrapped: every import
crates/engine/src/silence.rsmodified+132 -44
@@ -2,11 +2,15 @@
22 //! waveform takes, and the stretches of them nobody wants to watch.
33 //!
44 //! 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.
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").
1014 //!
1115 //! Loudness in **dBFS**, which is the unit every tool that does this speaks
1216 //! (ffmpeg's `silencedetect` noise floor, auto-editor's threshold) -- and RMS
@@ -31,7 +35,7 @@ pub const WINDOWS_PER_SEC: u32 = 50;
3135 pub const SILENT_DB: f32 = -120.;
3236
3337 /// What counts as a silence worth cutting. Seconds, not frames: detection runs
34-/// on the *source*, whose sample rate is its own business, and the frame grid
38+/// on the *sound*, whose sample rate is its own business, and the frame grid
3539 /// is applied once at the end ([`timeline_regions`]).
3640 #[derive(Clone, Copy, PartialEq, Debug)]
3741 pub struct Settings {
@@ -64,17 +68,26 @@ impl Default for Settings {
6468 }
6569
6670 /// One RMS level in dBFS per [`WINDOWS_PER_SEC`]th of a second of `stream` of
67-/// `path`, from media time 0 -- the same decode [`crate::waveform::peaks`] runs
68-/// and with the same contract: channels folded together, `Ok(None)` for a file
69-/// with **no audio track at all**, which is a source to refuse by name rather
70-/// than one long silence to cut.
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)`.
7180 ///
72-/// Linear in source length at ~1700x realtime, so a ten-minute take scans in
73-/// well under a second; a caller caches it per source and stream, because the
74-/// settings above are all applied to the result and none of them needs a second
75-/// decode.
76-pub fn levels(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<Vec<f32>>> {
77- levels_with_progress(path, stream, &Progress::default())
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.
85+pub 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())
7891 }
7992
8093 /// What a running [`levels_with_progress`] says about itself while it runs, and
@@ -106,22 +119,32 @@ pub struct Progress {
106119 pub fn levels_with_progress(
107120 path: impl AsRef<Path>,
108121 stream: usize,
122+ range: (f64, f64),
109123 progress: &Progress,
110124 ) -> crate::Result<Option<Vec<f32>>> {
125+ let from = range.0.max(0.);
111126 let sources = [(path.as_ref().to_path_buf(), stream)];
112- let Some((meta, rx)) =
113- AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])?
127+ let Some((meta, rx)) = AudioSession::open_multi_streams(&sources, &[(Some(0), from, range.1)])?
114128 else {
115129 return Ok(None);
116130 };
117131 let rate = f64::from(meta.sample_rate).max(1.);
118132 if let Some(total) = meta.total_samples {
119- progress.total.store((total as f64 / rate * 10.) as u64, Relaxed);
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);
120137 }
121138 // Fractional for `peaks`'s reason: 44100 / 50 is whole, 44100 / 30 is not,
122139 // and a rounded window drifts a bucket every few seconds over a long take.
123140 let per_window = f64::from(meta.sample_rate) / f64::from(WINDOWS_PER_SEC);
124141 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;
125148 // Sum of squares and how many samples went into it -- the two halves of a
126149 // mean square, kept in f64 because a loud minute is millions of terms.
127150 let mut sums: Vec<(f64, u64)> = Vec::new();
@@ -131,11 +154,13 @@ pub fn levels_with_progress(
131154 if progress.cancel.load(Relaxed) {
132155 break;
133156 }
134- progress
135- .scanned
136- .store((chunk.start_sample as f64 / rate * 10.) as u64, Relaxed);
157+ progress.scanned.store(
158+ ((chunk.start_sample as f64 / rate - from).max(0.) * 10.) as u64,
159+ Relaxed,
160+ );
137161 for (frame, values) in chunk.samples.chunks(channels).enumerate() {
138- let window = ((chunk.start_sample + frame as u64) as f64 / per_window) as usize;
162+ let at = ((chunk.start_sample + frame as u64) as f64 / per_window) as usize;
163+ let window = at.saturating_sub(base);
139164 if window >= sums.len() {
140165 sums.resize(window + 1, (0., 0));
141166 }
@@ -162,8 +187,8 @@ fn dbfs(square_sum: f64, samples: u64) -> f32 {
162187 (20. * rms.log10()).max(f64::from(SILENT_DB)) as f32
163188 }
164189
165-/// The silent stretches of a `levels` track, as half-open `(from, to)` *source*
166-/// seconds, in order and never overlapping.
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.
167192 ///
168193 /// Pure arithmetic: this is what a card re-runs on every keystroke. The three
169194 /// settings are applied in the order a person means them -- quiet runs first,
@@ -208,9 +233,12 @@ pub fn regions(levels: &[f32], cfg: Settings) -> Vec<(f64, f64)> {
208233 /// pairs of the lane `clip` is on -- what a preview marks and what
209234 /// [`crate::Project::cut_regions`] cuts.
210235 ///
211-/// Only the part of each region the clip actually plays: the scan reads the
212-/// whole file and the clip is a range of it, so a silence outside `[in, out)`
213-/// is not on the timeline at all. Positions go through the clip's **own rate**
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**
214242 /// ([`Speed::timeline_at`]), so a silence in a 2x clip marks the frames it is
215243 /// really on.
216244 ///
@@ -228,8 +256,11 @@ pub fn timeline_regions(clip: &Clip, fps: f64, regions: &[(f64, f64)]) -> Vec<(u
228256 regions
229257 .iter()
230258 .filter_map(|&(from, to)| {
231- let first = frame(from, f64::ceil).max(clip.in_frame);
232- let last = frame(to, f64::floor).min(clip.out_frame);
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);
233264 if last <= first {
234265 return None;
235266 }
@@ -304,7 +335,7 @@ mod tests {
304335 /// peaks instead of RMS, would not line up second after second.
305336 #[test]
306337 fn the_dips_of_the_1hz_pulse_are_where_the_silences_are() {
307- let levels = levels(asset("test_av.mp4"), 0)
338+ let levels = levels(asset("test_av.mp4"), 0, (0., f64::INFINITY))
308339 .expect("open")
309340 .expect("test_av.mp4 has an audio track");
310341 // A short forgiveness, because each dip of a sine is brief.
@@ -346,10 +377,12 @@ mod tests {
346377 use super::{Progress, levels_with_progress};
347378 use std::sync::atomic::Ordering::Relaxed;
348379 let progress = Progress::default();
349- let watched = levels_with_progress(asset("test_av.mp4"), 0, &progress)
380+ let watched = levels_with_progress(asset("test_av.mp4"), 0, (0., f64::INFINITY), &progress)
350381 .expect("open")
351382 .expect("test_av.mp4 has an audio track");
352- let plain = levels(asset("test_av.mp4"), 0).expect("open").expect("audio");
383+ let plain = levels(asset("test_av.mp4"), 0, (0., f64::INFINITY))
384+ .expect("open")
385+ .expect("audio");
353386 assert_eq!(watched, plain, "a watched scan must find the same levels");
354387 // Five seconds of fixture, in tenths, from the header and from the last
355388 // chunk the loop saw.
@@ -360,12 +393,63 @@ mod tests {
360393 // receiver is dropped and the decoder behind it stops with it.
361394 let stopped = Progress::default();
362395 stopped.cancel.store(true, Relaxed);
363- let partial = levels_with_progress(asset("test_av.mp4"), 0, &stopped)
396+ let partial = levels_with_progress(asset("test_av.mp4"), 0, (0., f64::INFINITY), &stopped)
364397 .expect("open")
365398 .expect("audio");
366399 assert!(partial.len() < plain.len(), "{} windows", partial.len());
367400 }
368401
402+ /// A clip cut in half costs half a decode, and the half it reads is its
403+ /// own: asked for `[2, 4)` seconds the scan hands back two seconds of
404+ /// windows, starting at the *second* second -- the fixture's dips at 2.75
405+ /// and 3.75 land at 0.75 and 1.75 of what comes back, and the three dips
406+ /// outside the range are not in it at all.
407+ #[test]
408+ fn a_range_is_read_from_its_own_start_and_nothing_outside_it_is() {
409+ let cfg = Settings {
410+ threshold_db: -40.,
411+ min_silence: 0.08,
412+ padding: 0.,
413+ min_keep: 0.,
414+ };
415+ let whole = levels(asset("test_av.mp4"), 0, (0., f64::INFINITY))
416+ .expect("open")
417+ .expect("audio");
418+ let half = levels(asset("test_av.mp4"), 0, (2., 4.))
419+ .expect("open")
420+ .expect("audio");
421+ // Two seconds of windows for two seconds asked, give or take the one a
422+ // packet boundary rounds -- not the five the file is.
423+ assert!(
424+ (half.len() as i64 - 100).abs() <= 2 && half.len() < whole.len(),
425+ "{} windows for [2, 4) of {} for the file",
426+ half.len(),
427+ whole.len()
428+ );
429+ let found = regions(&half, cfg);
430+ assert_eq!(found.len(), 2, "{found:?}");
431+ for (nth, &(from, to)) in found.iter().enumerate() {
432+ let dip = nth as f64 + 0.75;
433+ assert!(
434+ (from..to).contains(&dip),
435+ "dip {nth}: {from}..{to} does not cover {dip}"
436+ );
437+ }
438+ // ...and on the timeline they are where the clip plays them: a clip
439+ // reading from source frame 60 at 30 fps, laid at frame 500.
440+ let placed = clip(500, 60, 120, Speed::NORMAL);
441+ let marks = timeline_regions(&placed, 30., &found);
442+ assert_eq!(marks.len(), 2, "{marks:?}");
443+ for (nth, &(start, len)) in marks.iter().enumerate() {
444+ let dip = 500. + (nth as f64 + 0.75) * 30.;
445+ assert!(
446+ (f64::from(start)..f64::from(start + len)).contains(&dip),
447+ "dip {nth}: [{start}, {}) is not the dip at {dip}",
448+ start + len
449+ );
450+ }
451+ }
452+
369453 /// The three settings, each one visible on its own: a quiet run shorter
370454 /// than `min_silence` is forgiven, `padding` shrinks what is left at both
371455 /// ends, and a kept sliver shorter than `min_keep` joins the silences
@@ -409,33 +493,37 @@ mod tests {
409493 near(&merged, &[(2., 5.)]);
410494 }
411495
412- /// Where a region lands on the timeline is the clip's business: its range
413- /// clips what was scanned, its placement offsets it, and its rate divides
414- /// it. A 2x clip's silences mark half as many frames, at the right place.
496+ /// Where a region lands on the timeline is the clip's business: seconds
497+ /// counted from its in point, its placement offsets them, its end trims
498+ /// them and its rate divides them. A 2x clip's silences mark half as many
499+ /// frames, at the right place.
415500 #[test]
416501 fn regions_map_through_the_clips_range_and_rate() {
417502 let secs = [(1., 2.), (3., 3.5)];
418- // Whole file, real time, placed at the start: source seconds are
419- // timeline frames at 30 fps.
503+ // Whole file, real time, placed at the start: seconds read are timeline
504+ // frames at 30 fps.
420505 let whole = clip(0, 0, 300, Speed::NORMAL);
421506 assert_eq!(
422507 timeline_regions(&whole, 30., &secs),
423508 vec![(30, 30), (90, 15)]
424509 );
425510 // The same clip placed at frame 100 and reading from source frame 45:
426- // the first region is only the half of it the clip still plays, and it
427- // lands at the clip's own start.
511+ // the scan began at 45, so a region a second in is source frame 75 --
512+ // and it lands 30 frames after the clip's own start.
428513 let placed = clip(100, 45, 300, Speed::NORMAL);
429514 assert_eq!(
430515 timeline_regions(&placed, 30., &secs),
431- vec![(100, 15), (145, 15)]
516+ vec![(130, 30), (190, 15)]
432517 );
433518 // At 2x every timeline frame is two source frames, so both regions are
434519 // half as wide and sit half as far along.
435520 let fast = clip(0, 0, 300, Speed::from_permille(2000));
436521 assert_eq!(timeline_regions(&fast, 30., &secs), vec![(15, 15), (45, 7)]);
437- // A region entirely outside what the clip plays is not on the timeline.
438- assert!(timeline_regions(&clip(0, 200, 300, Speed::NORMAL), 30., &[(1., 2.)]).is_empty());
522+ // A read that ran past the clip's end is trimmed to it, and a region
523+ // wholly past it is not on the timeline at all.
524+ let short = clip(0, 0, 45, Speed::NORMAL);
525+ assert_eq!(timeline_regions(&short, 30., &[(1., 2.)]), vec![(30, 15)]);
526+ assert!(timeline_regions(&short, 30., &[(2., 3.)]).is_empty());
439527 }
440528
441529 /// Rounded inward at both ends: a region whose seconds fall between frames
crates/engine/tests/silence.rsmodified+8 -3
@@ -323,7 +323,14 @@ fn scanning_a_clip_and_cutting_what_it_finds() {
323323 // is not an edit.
324324 assert!(!p.undo());
325325
326- let levels = silence::levels(asset("test_av.mp4"), 0)
326+ let audio = Lane::new(LaneKind::Audio, 0);
327+ let clip = p.lane(audio)[0];
328+ // The clip's own stretch of the file, which is what the card asks for.
329+ let range = (
330+ f64::from(clip.in_frame) / FPS,
331+ f64::from(clip.out_frame) / FPS,
332+ );
333+ let levels = silence::levels(asset("test_av.mp4"), 0, range)
327334 .expect("scan")
328335 .expect("the fixture has audio");
329336 let cfg = Settings {
@@ -332,8 +339,6 @@ fn scanning_a_clip_and_cutting_what_it_finds() {
332339 padding: 0.02,
333340 min_keep: 0.,
334341 };
335- let audio = Lane::new(LaneKind::Audio, 0);
336- let clip = p.lane(audio)[0];
337342 let regions = silence::timeline_regions(&clip, FPS, &silence::regions(&levels, cfg));
338343 assert_eq!(regions.len(), 5, "{regions:?}");
339344 for (second, &(start, len)) in regions.iter().enumerate() {