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 {
410 }410 }
411 }411 }
412 412
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+
413 /// The silence scan a worker is running, as the card shows it. Same two clocks419 /// The silence scan a worker is running, as the card shows it. Same two clocks
414 /// as an [`Import`] and for the same reason -- one proves the window answers,420 /// as an [`Import`] and for the same reason -- one proves the window answers,
415 /// one says the read has stopped moving -- over a progress that *can* move:421 /// one says the read has stopped moving -- over a progress that *can* move:
416 /// a decode knows how far into the sound it has come, so the card says so.422 /// a decode knows how far into the sound it has come, so the card says so.
417 struct SilenceScan {423 struct SilenceScan {
418- /// Source and stream being scanned, which is the cache key the levels land424+ /// Source, stream and source range being scanned, which is the cache key
419- /// under and what tells a second open of the same clip from a new one.425+ /// the levels land under and what tells a second open of the same clip from
420- key: (PathBuf, usize),426+ /// a new one.
427+ key: ScanKey,
421 /// When the worker started, for the elapsed clock.428 /// When the worker started, for the elapsed clock.
422 started: Instant,429 started: Instant,
423 /// Written by the worker, read here every repaint. The cancel flag in it is430 /// Written by the worker, read here every repaint. The cancel flag in it is
@@ -1490,12 +1497,12 @@ struct Player {
1490 /// over and what an apply acts on -- *exactly* the previewed set, never a1497 /// over and what an apply acts on -- *exactly* the previewed set, never a
1491 /// second scan at the moment of the press.1498 /// second scan at the moment of the press.
1492 silence_marks: Vec<(u32, u32)>,1499 silence_marks: Vec<(u32, u32)>,
1493- /// The levels of every source scanned this session, kept so moving a1500+ /// The levels of every stretch scanned this session, kept so moving a
1494- /// threshold is arithmetic rather than another decode. Keyed by source and1501+ /// threshold is arithmetic rather than another decode. Keyed by
1495- /// stream, and not one entry: two films on one timeline would otherwise1502+ /// [`ScanKey`], and not one entry: two films on one timeline would
1496- /// evict each other, and the decode being paid twice is the fifty seconds1503+ /// otherwise evict each other, and the decode being paid twice is the fifty
1497- /// this card exists to not spend.1504+ /// seconds this card exists to not spend.
1498- silence_levels: HashMap<(PathBuf, usize), Arc<Vec<f32>>>,1505+ silence_levels: HashMap<ScanKey, Arc<Vec<f32>>>,
1499 /// The scan a worker is running for the card, if one is. `None` means the1506 /// The scan a worker is running for the card, if one is. `None` means the
1500 /// card is drawing numbers it already has.1507 /// card is drawing numbers it already has.
1501 silence_scan: Option<SilenceScan>,1508 silence_scan: Option<SilenceScan>,
@@ -2560,8 +2567,9 @@ impl Player {
2560 /// Opens the silence card on the clip to be scanned: the selected one, or2567 /// Opens the silence card on the clip to be scanned: the selected one, or
2561 /// -- with nothing selected -- the clip the picture is coming from, which is2568 /// -- with nothing selected -- the clip the picture is coming from, which is
2562 /// the rule the speed card follows and what a person means by "this shot".2569 /// 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 both2570+ /// Either half of a take will do: both halves of an A/V take name the same
2564- /// halves of an A/V take name the same file.2571+ /// file and play the same source frames, which is the whole of what a scan
2572+ /// is of ([`ScanKey`]).
2565 ///2573 ///
2566 /// The card is up on the next frame whatever the file is: a still is2574 /// The card is up on the next frame whatever the file is: a still is
2567 /// refused by name here, where the answer costs a look at the path, and2575 /// refused by name here, where the answer costs a look at the path, and
@@ -2584,16 +2592,16 @@ impl Player {
2584 .map(|clip| audio_half(session, clip))2592 .map(|clip| audio_half(session, clip))
2585 {2593 {
2586 Some((lane, idx)) => {2594 Some((lane, idx)) => {
2587- let source = self.session.as_ref().and_then(|session| {2595+ let found = self.session.as_ref().and_then(|session| {
2588- let clip = session.lane_clips(lane).get(idx)?;2596+ let clip = *session.lane_clips(lane).get(idx)?;
2589- session.sources().get(clip.source).cloned()2597+ Some((session.sources().get(clip.source)?.clone(), clip))
2590 });2598 });
2591 // A still is asked *before* the decoder is: handing a png to the2599 // A still is asked *before* the decoder is: handing a png to the
2592 // mp4 demuxer answers "a box with a larger size than it", which2600 // mp4 demuxer answers "a box with a larger size than it", which
2593 // is a true sentence about a container and nothing a person can2601 // is a true sentence about a container and nothing a person can
2594 // act on. A picture has no sound for the same reason a silent2602 // act on. A picture has no sound for the same reason a silent
2595 // video has none, so it is refused in the same words.2603 // video has none, so it is refused in the same words.
2596- let Some(source) = source else {2604+ let Some((source, clip)) = found else {
2597 cx.notify();2605 cx.notify();
2598 return;2606 return;
2599 };2607 };
@@ -2611,7 +2619,15 @@ impl Player {
2611 self.color_open = None;2619 self.color_open = None;
2612 self.speed_open = None;2620 self.speed_open = None;
2613 self.context_menu = None;2621 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+ );
2615 match scan_plan(2631 match scan_plan(
2616 self.silence_levels.contains_key(&key),2632 self.silence_levels.contains_key(&key),
2617 self.silence_scan.as_ref().map(|scan| &scan.key),2633 self.silence_scan.as_ref().map(|scan| &scan.key),
@@ -2733,13 +2749,18 @@ impl Player {
2733 ///2749 ///
2734 /// Whatever was scanning is cancelled first: one card, one scan, and the2750 /// Whatever was scanning is cancelled first: one card, one scan, and the
2735 /// clip that has just been asked about is the one worth the disk.2751 /// 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>) {
2737 self.cancel_silence_scan();2757 self.cancel_silence_scan();
2738 self.silence_marks.clear();2758 self.silence_marks.clear();
2739 let progress = Arc::new(engine::silence::Progress::default());2759 let progress = Arc::new(engine::silence::Progress::default());
2760+ let range = source_secs(&key, self.fps);
2740 let scan = cx.background_executor().spawn({2761 let scan = cx.background_executor().spawn({
2741 let (key, progress) = (key.clone(), Arc::clone(&progress));2762 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) }
2743 });2764 });
2744 let now = Instant::now();2765 let now = Instant::now();
2745 self.silence_scan = Some(SilenceScan {2766 self.silence_scan = Some(SilenceScan {
@@ -2819,7 +2840,12 @@ impl Player {
2819 // line. The marks arrive with the levels.2840 // line. The marks arrive with the levels.
2820 let Some(levels) = self2841 let Some(levels) = self
2821 .silence_levels2842 .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+ ))
2823 .cloned()2849 .cloned()
2824 else {2850 else {
2825 return;2851 return;
@@ -9948,7 +9974,7 @@ enum ScanPlan {
9948 /// Which of the three [`ScanPlan`]s opening the card on `key` means. The whole9974 /// Which of the three [`ScanPlan`]s opening the card on `key` means. The whole
9949 /// of the cache policy, and the reason a second film does not cost the first9975 /// of the cache policy, and the reason a second film does not cost the first
9950 /// one its levels: what is cached is asked per source, never "the last one".9976 /// 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 {
9952 match (cached, running) {9978 match (cached, running) {
9953 (true, _) => ScanPlan::Marks,9979 (true, _) => ScanPlan::Marks,
9954 (false, Some(at)) if at == key => ScanPlan::Wait,9980 (false, Some(at)) if at == key => ScanPlan::Wait,
@@ -9956,6 +9982,18 @@ fn scan_plan(cached: bool, running: Option<&(PathBuf, usize)>, key: &(PathBuf, u
9956 }9982 }
9957 }9983 }
9958 9984
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+
9959 /// What the silence card says while its worker reads. Unlike an import this9997 /// What the silence card says while its worker reads. Unlike an import this
9960 /// one *has* a fraction -- a decode knows how far into the sound it has come --9998 /// one *has* a fraction -- a decode knows how far into the sound it has come --
9961 /// so the line is where it is up to, out of what the header claims the track is9999 /// so the line is where it is up to, out of what the header claims the track is
@@ -10059,9 +10097,9 @@ mod tests {
10059 ZOOM_MIN_FRAMES, ZOOM_OUT_MARGIN, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri,10097 ZOOM_MIN_FRAMES, ZOOM_OUT_MARGIN, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri,
10060 fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution,10098 fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution,
10061 note_progress, px_along,10099 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,
10063 Landing, arrival, launch_queue,10101 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,
10065 repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label,10103 repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label,
10066 clip_width, trimmed_clip, trims, unscannable, unusable,10104 clip_width, trimmed_clip, trims, unscannable, unusable,
10067 visible_slice,10105 visible_slice,
@@ -14043,7 +14081,7 @@ mod tests {
14043 progress.total.store(7680, Relaxed);14081 progress.total.store(7680, Relaxed);
14044 let started = Instant::now() - Duration::from_secs(9);14082 let started = Instant::now() - Duration::from_secs(9);
14045 let mut scan = SilenceScan {14083 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),
14047 started,14085 started,
14048 progress: Arc::clone(&progress),14086 progress: Arc::clone(&progress),
14049 seen: 0,14087 seen: 0,
@@ -14082,18 +14120,20 @@ mod tests {
14082 assert_eq!(scan.since, held, "an unchanged mark must not reset it");14120 assert_eq!(scan.since, held, "an unchanged mark must not reset it");
14083 }14121 }
14084 14122
14085- /// The cache is per source, which is what stops two films thrashing each14123+ /// The cache is per scanned stretch, which is what stops two films
14086- /// other's fifty seconds: A, then B, then A again is *one* decode of A.14124+ /// thrashing each other's fifty seconds: A, then B, then A again is *one*
14087- /// And a source already being read is waited for rather than read twice --14125+ /// decode of A. And a stretch already being read is waited for rather than
14088- /// both halves of an A/V take name the same file.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.
14089 #[test]14129 #[test]
14090 fn a_second_film_does_not_cost_the_first_one_its_levels() {14130 fn a_second_film_does_not_cost_the_first_one_its_levels() {
14091 let (a, b) = (14131 let (a, b) = (
14092- (PathBuf::from("/films/a.mkv"), 0),14132+ (PathBuf::from("/films/a.mkv"), 0, 0, 3000),
14093- (PathBuf::from("/films/b.mkv"), 0),14133+ (PathBuf::from("/films/b.mkv"), 0, 0, 3000),
14094 );14134 );
14095- let mut cache: std::collections::HashMap<(PathBuf, usize), ()> =14135+ let half = (PathBuf::from("/films/a.mkv"), 0, 0, 1500);
14096- std::collections::HashMap::new();14136+ let mut cache: std::collections::HashMap<ScanKey, ()> = std::collections::HashMap::new();
14097 let mut started = Vec::new();14137 let mut started = Vec::new();
14098 // What a card open does, three times over, with the worker landing14138 // What a card open does, three times over, with the worker landing
14099 // between each: plan, and start what the plan says to start.14139 // between each: plan, and start what the plan says to start.
@@ -14117,6 +14157,18 @@ mod tests {
14117 assert_eq!(scan_plan(false, Some(&b), &a), ScanPlan::Start);14157 assert_eq!(scan_plan(false, Some(&b), &a), ScanPlan::Start);
14118 // Levels in hand beat a worker either way: the marks are arithmetic.14158 // Levels in hand beat a worker either way: the marks are arithmetic.
14119 assert_eq!(scan_plan(true, Some(&a), &a), ScanPlan::Marks);14159 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));
14120 }14172 }
14121 14173
14122 /// The two halves a worker hands back for an import, unwrapped: every import14174 /// The two halves a worker hands back for an import, unwrapped: every import
crates/engine/src/silence.rsmodified+132 -44
@@ -2,11 +2,15 @@
2 //! waveform takes, and the stretches of them nobody wants to watch.2 //! waveform takes, and the stretches of them nobody wants to watch.
3 //!3 //!
4 //! Three steps, kept apart so only the first one costs a decode: [`levels`]4 //! Three steps, kept apart so only the first one costs a decode: [`levels`]
5-//! turns a file into one loudness number per 20 ms window, [`regions`] turns5+//! turns a *stretch* of a file into one loudness number per 20 ms window,
6-//! those numbers plus a [`Settings`] into silent stretches of *source* seconds,6+//! [`regions`] turns those numbers plus a [`Settings`] into silent stretches of
7-//! and [`timeline_regions`] puts those on the timeline through one clip's own7+//! seconds from where that read began, and [`timeline_regions`] puts those on
8-//! range and rate. A card tweaking a threshold re-runs the last two and decodes8+//! the timeline through one clip's own range and rate. A card tweaking a
9-//! nothing.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").
10 //!14 //!
11 //! Loudness in **dBFS**, which is the unit every tool that does this speaks15 //! Loudness in **dBFS**, which is the unit every tool that does this speaks
12 //! (ffmpeg's `silencedetect` noise floor, auto-editor's threshold) -- and RMS16 //! (ffmpeg's `silencedetect` noise floor, auto-editor's threshold) -- and RMS
@@ -31,7 +35,7 @@ pub const WINDOWS_PER_SEC: u32 = 50;
31 pub const SILENT_DB: f32 = -120.;35 pub const SILENT_DB: f32 = -120.;
32 36
33 /// What counts as a silence worth cutting. Seconds, not frames: detection runs37 /// 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 grid38+/// on the *sound*, whose sample rate is its own business, and the frame grid
35 /// is applied once at the end ([`timeline_regions`]).39 /// is applied once at the end ([`timeline_regions`]).
36 #[derive(Clone, Copy, PartialEq, Debug)]40 #[derive(Clone, Copy, PartialEq, Debug)]
37 pub struct Settings {41 pub struct Settings {
@@ -64,17 +68,26 @@ impl Default for Settings {
64 }68 }
65 69
66 /// One RMS level in dBFS per [`WINDOWS_PER_SEC`]th of a second of `stream` of70 /// 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`] runs71+/// `path`, over the half-open `range` of **source seconds** -- the same decode
68-/// and with the same contract: channels folded together, `Ok(None)` for a file72+/// [`crate::waveform::peaks`] runs and with the same contract: channels folded
69-/// with **no audio track at all**, which is a source to refuse by name rather73+/// together, `Ok(None)` for a file with **no audio track at all**, which is a
70-/// than one long silence to cut.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)`.
71 ///80 ///
72-/// Linear in source length at ~1700x realtime, so a ten-minute take scans in81+/// Linear in the range's length at ~1700x realtime, so a ten-minute take scans
73-/// well under a second; a caller caches it per source and stream, because the82+/// in well under a second; a caller caches it per source, stream and range,
74-/// settings above are all applied to the result and none of them needs a second83+/// because the settings above are all applied to the result and none of them
75-/// decode.84+/// needs a second decode.
76-pub fn levels(path: impl AsRef<Path>, stream: usize) -> crate::Result<Option<Vec<f32>>> {85+pub fn levels(
77- levels_with_progress(path, stream, &Progress::default())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())
78 }91 }
79 92
80 /// What a running [`levels_with_progress`] says about itself while it runs, and93 /// What a running [`levels_with_progress`] says about itself while it runs, and
@@ -106,22 +119,32 @@ pub struct Progress {
106 pub fn levels_with_progress(119 pub fn levels_with_progress(
107 path: impl AsRef<Path>,120 path: impl AsRef<Path>,
108 stream: usize,121 stream: usize,
122+ range: (f64, f64),
109 progress: &Progress,123 progress: &Progress,
110 ) -> crate::Result<Option<Vec<f32>>> {124 ) -> crate::Result<Option<Vec<f32>>> {
125+ let from = range.0.max(0.);
111 let sources = [(path.as_ref().to_path_buf(), stream)];126 let sources = [(path.as_ref().to_path_buf(), stream)];
112- let Some((meta, rx)) =127+ let Some((meta, rx)) = AudioSession::open_multi_streams(&sources, &[(Some(0), from, range.1)])?
113- AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])?
114 else {128 else {
115 return Ok(None);129 return Ok(None);
116 };130 };
117 let rate = f64::from(meta.sample_rate).max(1.);131 let rate = f64::from(meta.sample_rate).max(1.);
118 if let Some(total) = meta.total_samples {132 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);
120 }137 }
121 // Fractional for `peaks`'s reason: 44100 / 50 is whole, 44100 / 30 is not,138 // Fractional for `peaks`'s reason: 44100 / 50 is whole, 44100 / 30 is not,
122 // and a rounded window drifts a bucket every few seconds over a long take.139 // and a rounded window drifts a bucket every few seconds over a long take.
123 let per_window = f64::from(meta.sample_rate) / f64::from(WINDOWS_PER_SEC);140 let per_window = f64::from(meta.sample_rate) / f64::from(WINDOWS_PER_SEC);
124 let channels = (meta.channels as usize).max(1);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;
125 // Sum of squares and how many samples went into it -- the two halves of a148 // Sum of squares and how many samples went into it -- the two halves of a
126 // mean square, kept in f64 because a loud minute is millions of terms.149 // mean square, kept in f64 because a loud minute is millions of terms.
127 let mut sums: Vec<(f64, u64)> = Vec::new();150 let mut sums: Vec<(f64, u64)> = Vec::new();
@@ -131,11 +154,13 @@ pub fn levels_with_progress(
131 if progress.cancel.load(Relaxed) {154 if progress.cancel.load(Relaxed) {
132 break;155 break;
133 }156 }
134- progress157+ progress.scanned.store(
135- .scanned158+ ((chunk.start_sample as f64 / rate - from).max(0.) * 10.) as u64,
136- .store((chunk.start_sample as f64 / rate * 10.) as u64, Relaxed);159+ Relaxed,
160+ );
137 for (frame, values) in chunk.samples.chunks(channels).enumerate() {161 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);
139 if window >= sums.len() {164 if window >= sums.len() {
140 sums.resize(window + 1, (0., 0));165 sums.resize(window + 1, (0., 0));
141 }166 }
@@ -162,8 +187,8 @@ fn dbfs(square_sum: f64, samples: u64) -> f32 {
162 (20. * rms.log10()).max(f64::from(SILENT_DB)) as f32187 (20. * rms.log10()).max(f64::from(SILENT_DB)) as f32
163 }188 }
164 189
165-/// The silent stretches of a `levels` track, as half-open `(from, to)` *source*190+/// The silent stretches of a `levels` track, as half-open `(from, to)` seconds
166-/// seconds, in order and never overlapping.191+/// **from where the read began**, in order and never overlapping.
167 ///192 ///
168 /// Pure arithmetic: this is what a card re-runs on every keystroke. The three193 /// Pure arithmetic: this is what a card re-runs on every keystroke. The three
169 /// settings are applied in the order a person means them -- quiet runs first,194 /// 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)> {
208 /// pairs of the lane `clip` is on -- what a preview marks and what233 /// pairs of the lane `clip` is on -- what a preview marks and what
209 /// [`crate::Project::cut_regions`] cuts.234 /// [`crate::Project::cut_regions`] cuts.
210 ///235 ///
211-/// Only the part of each region the clip actually plays: the scan reads the236+/// `regions` are seconds from the clip's **in point**, which is where
212-/// whole file and the clip is a range of it, so a silence outside `[in, out)`237+/// [`levels`] was asked to start reading; they land at `in_frame` plus that.
213-/// is not on the timeline at all. Positions go through the clip's **own rate**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**
214 /// ([`Speed::timeline_at`]), so a silence in a 2x clip marks the frames it is242 /// ([`Speed::timeline_at`]), so a silence in a 2x clip marks the frames it is
215 /// really on.243 /// really on.
216 ///244 ///
@@ -228,8 +256,11 @@ pub fn timeline_regions(clip: &Clip, fps: f64, regions: &[(f64, f64)]) -> Vec<(u
228 regions256 regions
229 .iter()257 .iter()
230 .filter_map(|&(from, to)| {258 .filter_map(|&(from, to)| {
231- let first = frame(from, f64::ceil).max(clip.in_frame);259+ let first = clip.in_frame.saturating_add(frame(from, f64::ceil));
232- let last = frame(to, f64::floor).min(clip.out_frame);260+ let last = clip
261+ .in_frame
262+ .saturating_add(frame(to, f64::floor))
263+ .min(clip.out_frame);
233 if last <= first {264 if last <= first {
234 return None;265 return None;
235 }266 }
@@ -304,7 +335,7 @@ mod tests {
304 /// peaks instead of RMS, would not line up second after second.335 /// peaks instead of RMS, would not line up second after second.
305 #[test]336 #[test]
306 fn the_dips_of_the_1hz_pulse_are_where_the_silences_are() {337 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))
308 .expect("open")339 .expect("open")
309 .expect("test_av.mp4 has an audio track");340 .expect("test_av.mp4 has an audio track");
310 // A short forgiveness, because each dip of a sine is brief.341 // A short forgiveness, because each dip of a sine is brief.
@@ -346,10 +377,12 @@ mod tests {
346 use super::{Progress, levels_with_progress};377 use super::{Progress, levels_with_progress};
347 use std::sync::atomic::Ordering::Relaxed;378 use std::sync::atomic::Ordering::Relaxed;
348 let progress = Progress::default();379 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)
350 .expect("open")381 .expect("open")
351 .expect("test_av.mp4 has an audio track");382 .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");
353 assert_eq!(watched, plain, "a watched scan must find the same levels");386 assert_eq!(watched, plain, "a watched scan must find the same levels");
354 // Five seconds of fixture, in tenths, from the header and from the last387 // Five seconds of fixture, in tenths, from the header and from the last
355 // chunk the loop saw.388 // chunk the loop saw.
@@ -360,12 +393,63 @@ mod tests {
360 // receiver is dropped and the decoder behind it stops with it.393 // receiver is dropped and the decoder behind it stops with it.
361 let stopped = Progress::default();394 let stopped = Progress::default();
362 stopped.cancel.store(true, Relaxed);395 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)
364 .expect("open")397 .expect("open")
365 .expect("audio");398 .expect("audio");
366 assert!(partial.len() < plain.len(), "{} windows", partial.len());399 assert!(partial.len() < plain.len(), "{} windows", partial.len());
367 }400 }
368 401
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+
369 /// The three settings, each one visible on its own: a quiet run shorter453 /// The three settings, each one visible on its own: a quiet run shorter
370 /// than `min_silence` is forgiven, `padding` shrinks what is left at both454 /// than `min_silence` is forgiven, `padding` shrinks what is left at both
371 /// ends, and a kept sliver shorter than `min_keep` joins the silences455 /// ends, and a kept sliver shorter than `min_keep` joins the silences
@@ -409,33 +493,37 @@ mod tests {
409 near(&merged, &[(2., 5.)]);493 near(&merged, &[(2., 5.)]);
410 }494 }
411 495
412- /// Where a region lands on the timeline is the clip's business: its range496+ /// Where a region lands on the timeline is the clip's business: seconds
413- /// clips what was scanned, its placement offsets it, and its rate divides497+ /// counted from its in point, its placement offsets them, its end trims
414- /// it. A 2x clip's silences mark half as many frames, at the right place.498+ /// them and its rate divides them. A 2x clip's silences mark half as many
499+ /// frames, at the right place.
415 #[test]500 #[test]
416 fn regions_map_through_the_clips_range_and_rate() {501 fn regions_map_through_the_clips_range_and_rate() {
417 let secs = [(1., 2.), (3., 3.5)];502 let secs = [(1., 2.), (3., 3.5)];
418- // Whole file, real time, placed at the start: source seconds are503+ // Whole file, real time, placed at the start: seconds read are timeline
419- // timeline frames at 30 fps.504+ // frames at 30 fps.
420 let whole = clip(0, 0, 300, Speed::NORMAL);505 let whole = clip(0, 0, 300, Speed::NORMAL);
421 assert_eq!(506 assert_eq!(
422 timeline_regions(&whole, 30., &secs),507 timeline_regions(&whole, 30., &secs),
423 vec![(30, 30), (90, 15)]508 vec![(30, 30), (90, 15)]
424 );509 );
425 // The same clip placed at frame 100 and reading from source frame 45:510 // 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 it511+ // the scan began at 45, so a region a second in is source frame 75 --
427- // lands at the clip's own start.512+ // and it lands 30 frames after the clip's own start.
428 let placed = clip(100, 45, 300, Speed::NORMAL);513 let placed = clip(100, 45, 300, Speed::NORMAL);
429 assert_eq!(514 assert_eq!(
430 timeline_regions(&placed, 30., &secs),515 timeline_regions(&placed, 30., &secs),
431- vec![(100, 15), (145, 15)]516+ vec![(130, 30), (190, 15)]
432 );517 );
433 // At 2x every timeline frame is two source frames, so both regions are518 // At 2x every timeline frame is two source frames, so both regions are
434 // half as wide and sit half as far along.519 // half as wide and sit half as far along.
435 let fast = clip(0, 0, 300, Speed::from_permille(2000));520 let fast = clip(0, 0, 300, Speed::from_permille(2000));
436 assert_eq!(timeline_regions(&fast, 30., &secs), vec![(15, 15), (45, 7)]);521 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.522+ // A read that ran past the clip's end is trimmed to it, and a region
438- assert!(timeline_regions(&clip(0, 200, 300, Speed::NORMAL), 30., &[(1., 2.)]).is_empty());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());
439 }527 }
440 528
441 /// Rounded inward at both ends: a region whose seconds fall between frames529 /// 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() {
323 // is not an edit.323 // is not an edit.
324 assert!(!p.undo());324 assert!(!p.undo());
325 325
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)
327 .expect("scan")334 .expect("scan")
328 .expect("the fixture has audio");335 .expect("the fixture has audio");
329 let cfg = Settings {336 let cfg = Settings {
@@ -332,8 +339,6 @@ fn scanning_a_clip_and_cutting_what_it_finds() {
332 padding: 0.02,339 padding: 0.02,
333 min_keep: 0.,340 min_keep: 0.,
334 };341 };
335- let audio = Lane::new(LaneKind::Audio, 0);
336- let clip = p.lane(audio)[0];
337 let regions = silence::timeline_regions(&clip, FPS, &silence::regions(&levels, cfg));342 let regions = silence::timeline_regions(&clip, FPS, &silence::regions(&levels, cfg));
338 assert_eq!(regions.len(), 5, "{regions:?}");343 assert_eq!(regions.len(), 5, "{regions:?}");
339 for (second, &(start, len)) in regions.iter().enumerate() {344 for (second, &(start, len)) in regions.iter().enumerate() {