diff --git a/crates/app/src/importing.rs b/crates/app/src/importing.rs index bdbca7b..a87639b 100644 --- a/crates/app/src/importing.rs +++ b/crates/app/src/importing.rs @@ -361,6 +361,45 @@ pub(crate) fn source_secs(key: &ScanKey, fps: f64) -> (f64, f64) { } } +/// The [`ScanKey`] a background scan lands its whole-file levels under: every +/// frame the source has, so one entry answers for every clip cut from it. A +/// sentinel `out_frame` rather than a fourth map, because [`ScanKey`] is +/// already what [`Player::silence_levels`] is keyed by -- a clip can never +/// itself claim `u32::MAX` as its own `out_frame`, so the two never collide. +pub(crate) fn full_scan_key(path: &Path, stream: usize) -> ScanKey { + (path.to_path_buf(), stream, 0, u32::MAX) +} + +/// The clip's own stretch of a whole-source scan, in the same dBFS windows +/// [`engine::silence::levels`] would have decoded for it directly: window `k` +/// of both is the same [`engine::silence::WINDOWS_PER_SEC`]th of a second from +/// the start of the file, so slicing costs no decode and reads the same +/// numbers the on-demand scan would have. Empty past the end of what the +/// background read has landed so far -- a scan still running answers with +/// what it has, same as [`SilenceScan`]'s own cancel does. +pub(crate) fn slice_whole_levels(whole: &[f32], fps: f64, in_frame: u32, out_frame: u32) -> Vec { + if !(fps.is_finite() && fps > 0.) { + return Vec::new(); + } + let window = f64::from(engine::silence::WINDOWS_PER_SEC); + let start = ((f64::from(in_frame) / fps) * window) as usize; + let end = (((f64::from(out_frame) / fps) * window).ceil() as usize).min(whole.len()); + match start < end { + true => whole[start..end].to_vec(), + false => Vec::new(), + } +} + +/// Whether the card may draw `key`'s marks as arithmetic rather than start a +/// worker for it: its own exact read, or -- new since the scan moved to +/// import -- the whole-source background scan its file is cut from +/// ([`Player::cache_media`]). One function so `Player::open_silence`'s plan +/// and `Player::scan_silences`' lookup share the one contract for what +/// "cached" means, instead of two copies that could drift. +pub(crate) fn silence_cached(levels: &std::collections::HashMap>>, key: &ScanKey) -> bool { + levels.contains_key(key) || levels.contains_key(&full_scan_key(&key.0, key.1)) +} + /// What the silence card says while its worker reads. Unlike an import this /// one *has* a fraction -- a decode knows how far into the sound it has come -- /// so the line is where it is up to, out of what the header claims the track is diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 111eeb6..c260273 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -520,6 +520,13 @@ struct Player { /// The scan a worker is running for the card, if one is. `None` means the /// card is drawing numbers it already has. silence_scan: Option, + /// Whole-source background scans in flight, keyed the same as + /// [`Self::silence_levels`]'s own whole-source entries + /// ([`full_scan_key`]). Started at import ([`Player::cache_media`]) so a + /// card opened later finds the levels already read; presence here is what + /// stops a re-add of the same source from starting a second one, and its + /// [`engine::silence::Progress::cancel`] is what a removed source is told. + silence_bg: HashMap<(PathBuf, usize), Arc>, /// Which of the card's four sliders the arrow keys and a drag move. The /// card's own focus, since nothing in it takes gpui's (ledger:182). color_band: usize, @@ -756,6 +763,7 @@ fn main() { silence_marks: Vec::new(), silence_levels: HashMap::new(), silence_scan: None, + silence_bg: HashMap::new(), color_open: None, color_band: 0, color_dragging: false, diff --git a/crates/app/src/player/cards.rs b/crates/app/src/player/cards.rs index 071d4f6..8d858d1 100644 --- a/crates/app/src/player/cards.rs +++ b/crates/app/src/player/cards.rs @@ -560,7 +560,12 @@ impl Player { clip.out_frame, ); match scan_plan( - self.silence_levels.contains_key(&key), + // The whole-source background scan counts as "cached" + // too: a card opened after import finds the levels a + // repaint has already been decoding since the file + // arrived ([`Player::cache_media`]), and `scan_silences` + // is what slices this clip's stretch out of them. + silence_cached(&self.silence_levels, &key), self.silence_scan.as_ref().map(|scan| &scan.key), &key, ) { @@ -769,16 +774,33 @@ impl Player { }; // Nothing read yet: the worker is running and the card is drawing its // line. The marks arrive with the levels. - let Some(levels) = self - .silence_levels - .get(&( - source.path.clone(), - source.audio_stream, - clip.in_frame, - clip.out_frame, - )) - .cloned() - else { + // + // The clip's own read first -- an on-demand scan already asked for + // exactly this stretch -- and failing that, this clip's slice of the + // whole-source background scan ([`Player::cache_media`]), which is + // what makes the card answer at once for a file that arrived a + // repaint or two ago. + let key = ( + source.path.clone(), + source.audio_stream, + clip.in_frame, + clip.out_frame, + ); + let levels = match self.silence_levels.get(&key).cloned() { + Some(levels) => Some(levels), + None => self + .silence_levels + .get(&full_scan_key(&source.path, source.audio_stream)) + .map(|whole| { + Arc::new(slice_whole_levels( + whole, + self.fps, + clip.in_frame, + clip.out_frame, + )) + }), + }; + let Some(levels) = levels else { return; }; self.silence_marks = engine::silence::timeline_regions( diff --git a/crates/app/src/player/export.rs b/crates/app/src/player/export.rs index 2305026..d7be444 100644 --- a/crates/app/src/player/export.rs +++ b/crates/app/src/player/export.rs @@ -177,9 +177,71 @@ impl Player { }) .detach(); } + // The silence card's own decode, started here instead of at the card + // -- a whole source, off the render thread, the moment it arrives + // rather than the moment somebody opens the card on it + // ([`Player::start_silence_scan`] used to be the only door and cost + // the card its first fifty seconds). Landed under `full_scan_key` in + // the very map the card reads, so `scan_silences` finds it warm. + // + // A still has no sound to read, and `silence_bg`'s presence is the + // dedupe: a source already scanning, already scanned, or scanned and + // then removed mid-read (its entry stays until the scan notices the + // cancel) is not started twice. Gathered here, off `session`, for + // `starting`'s own reason: starting one below takes `self` mutably + // and `session` is a borrow of it. + let silence_starting: Vec<(PathBuf, usize)> = session + .sources() + .iter() + .map(|s| (s.path.clone(), s.audio_stream)) + .filter(|key| { + !engine::is_image(&key.0) + && !self.silence_bg.contains_key(key) + && !self + .silence_levels + .contains_key(&full_scan_key(&key.0, key.1)) + }) + .collect(); for path in starting { self.start_proxy_for(&path, cx); } + for key in silence_starting { + let progress = Arc::new(engine::silence::Progress::default()); + self.silence_bg.insert(key.clone(), Arc::clone(&progress)); + let scan = cx.background_executor().spawn({ + let (path, stream, progress) = (key.0.clone(), key.1, Arc::clone(&progress)); + async move { + engine::silence::levels_with_progress(&path, stream, (0., f64::INFINITY), &progress) + } + }); + cx.spawn(async move |this, cx| { + let landed = scan.await; + this.update(cx, |this, cx| { + this.silence_bg.remove(&key); + // Cancelled means the source was removed while this read + // was running: half a file's levels answer for a source + // that is not on the list any more. + if progress.cancel.load(std::sync::atomic::Ordering::Relaxed) { + return; + } + if let Ok(Some(levels)) = landed { + this.silence_levels + .insert(full_scan_key(&key.0, key.1), Arc::new(levels)); + // A card already open and waiting on this very source + // draws its marks the moment they land, same as an + // on-demand scan does. + this.scan_silences(); + cx.notify(); + } + // `Ok(None)` (no audio track) and `Err` are left unrecorded: + // the card's own on-demand scan is what a person waiting on + // this file actually sees, and it gives the same answer + // (`unscannable`/`SCAN FAILED`) when it is opened. + }) + .ok(); + }) + .detach(); + } } /// Probes what an export would open, once per (settings, resolution, cuts) diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 82b6332..d83bc9e 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -79,6 +79,13 @@ impl Player { .map(|session| session.remove_source(path, stream)); let text = match removed { Some(Ok(idx)) => { + // Tells a running background scan of this source nobody wants + // its levels any more, and drops the entry that was standing + // in the way of a re-add starting a fresh one + // ([`Player::cache_media`]'s dedupe reads presence here). + if let Some(scan) = self.silence_bg.remove(&(path.to_path_buf(), stream)) { + scan.cancel.store(true, std::sync::atomic::Ordering::Relaxed); + } // The picked row may be the one that just went, and the engine // reseeks, so this owes the flag reset like every other edit. if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) { @@ -164,6 +171,15 @@ impl Player { self.syncs.clear(); // Scanned off sources that are not in the library any more. self.silence_levels.clear(); + // ...and every background read still chasing one of them: cancelled + // rather than merely dropped, so a landing closure over a gone window + // does not write into a `silence_levels` the next session starts + // empty (`Player::cache_media`'s spawn checks this flag before it + // inserts). + for scan in self.silence_bg.values() { + scan.cancel.store(true, std::sync::atomic::Ordering::Relaxed); + } + self.silence_bg.clear(); // Every gesture in flight, dropped for `reset_after_reseek`'s reason // (it drops the trim below): a drag holds a bar, a clip or a band of a // timeline that has just stopped existing. diff --git a/crates/app/src/tests/media.rs b/crates/app/src/tests/media.rs index cc700ba..087690d 100644 --- a/crates/app/src/tests/media.rs +++ b/crates/app/src/tests/media.rs @@ -293,6 +293,66 @@ fn a_second_film_does_not_cost_the_first_one_its_levels() { assert_eq!(source_secs(&half, 0.), (0., f64::INFINITY)); } +/// The background scan started at import ([`Player::cache_media`]) lands its +/// whole-file levels under [`full_scan_key`], and that entry alone is what +/// makes the card's own cache check answer "already read" for *every* clip +/// cut from that source -- without the per-clip decode `start_silence_scan` +/// used to be the only way to get one. The whole point of moving the scan to +/// import: the card must find it warm. +#[test] +fn a_warm_whole_source_scan_answers_the_card_for_every_clip_cut_from_it() { + use std::sync::Arc; + let mut levels: std::collections::HashMap>> = std::collections::HashMap::new(); + let clip_a = (PathBuf::from("/films/a.mkv"), 0, 300, 900); + let clip_b = (PathBuf::from("/films/a.mkv"), 0, 1_200, 1_800); + // Nothing yet -- neither clip's own read nor a background one. + assert!(!silence_cached(&levels, &clip_a)); + assert!(!silence_cached(&levels, &clip_b)); + // The background scan lands, once, before either half of the take was + // ever opened on the card. + levels.insert(full_scan_key(&clip_a.0, clip_a.1), Arc::new(vec![0.; 100])); + assert!( + silence_cached(&levels, &clip_a) && silence_cached(&levels, &clip_b), + "one whole-source entry answers for both halves of the take" + ); + // A clip cut from a *different* file is not answered by it -- the + // sentinel is per (path, stream), exactly like every other scan key. + let other_file = (PathBuf::from("/films/b.mkv"), 0, 300, 900); + assert!(!silence_cached(&levels, &other_file)); + // A clip's own exact read still counts too, same as before this existed. + levels.insert(clip_a.clone(), Arc::new(vec![-40.; 10])); + assert!(silence_cached(&levels, &clip_a)); +} + +/// What the card actually draws from a warm background scan: the same +/// dBFS-per-window numbers a direct read of the clip's own stretch would +/// have found, because window `k` of the whole file and window `k` of a read +/// that started at second 0 name the same slice of the same source +/// ([`slice_whole_levels`]'s whole contract). No decode in this test at +/// all -- the numbers are synthetic and distinct per window so a wrong +/// offset shows up as a wrong value, not a coincidentally-right one. +#[test] +fn a_clips_slice_of_the_whole_scan_is_the_windows_its_own_read_would_have_found() { + // 50 fps: one timeline frame is exactly one silence window + // (`engine::silence::WINDOWS_PER_SEC` is 50), so the arithmetic is exact + // and the test does not have to fight rounding to prove the offset. + let fps = 50.; + let whole: Vec = (0..40).map(|i| i as f32).collect(); + let slice = slice_whole_levels(&whole, fps, 10, 20); + assert_eq!(slice, (10..20).map(|i| i as f32).collect::>()); + // The clip's own in point is where its slice starts, not the file's: + // a take an hour into the film reads the same as one at its head. + assert_eq!(slice_whole_levels(&whole, fps, 0, 5), vec![0., 1., 2., 3., 4.]); + // Past what the background scan has read so far (still running, or + // cancelled) is not padded with zeroes -- the caller is told nothing is + // there yet, same as [`SilenceScan`]'s own cancel leaves a prefix. + assert_eq!(slice_whole_levels(&whole, fps, 35, 60), vec![35., 36., 37., 38., 39.]); + assert_eq!(slice_whole_levels(&whole, fps, 45, 60), Vec::::new()); + // A rate that is not a rate reads nothing, the same refusal + // `source_secs` makes for a background scan's own range. + assert_eq!(slice_whole_levels(&whole, 0., 0, 10), Vec::::new()); +} + /// The import door's split, which is what keeps the render thread out of a /// header walk: what the worker probed and what the landing registers add up /// to exactly the rows, lengths and refusals the in-place import lands. diff --git a/crates/app/src/tests/mod.rs b/crates/app/src/tests/mod.rs index cef1de3..70586df 100644 --- a/crates/app/src/tests/mod.rs +++ b/crates/app/src/tests/mod.rs @@ -46,7 +46,7 @@ use super::{ fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution, note_progress, px_along, IMPORT_STALL, Import, ImportStage, SEEK_STALL, ScanKey, ScanPlan, SilenceScan, import_line, - Landing, arrival, launch_queue, + Landing, arrival, launch_queue, full_scan_key, silence_cached, slice_whole_levels, read_ahead, scan_plan, seek_line, silence_line, source_secs, stash_or_write, repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label, clip_width, frames_of_us, trimmed_clip, trimmed_sub, trims, unscannable, unusable,