forge
Explore
Log in

Don't you dare go Hollow

The silence scan starts at import, not at the card

Browse files at this commit

99d87d41f2e4bcba2c5f04fd6c42e9935e268377Ahmet Kaan GümüşParent: 31449fc
  • perf
    • the silence scan starts at import, not at the card
Show full message
⚡ perf(app): the silence scan starts at import, not at the card

Moves the whole-source RMS decode engine::silence::levels_with_progress
was only ever asked for when the silence card opened
(Player::start_silence_scan) into Player::cache_media, the same
per-repaint "unseen sources" door the waveform, proxy and stream
probes already run through. The scan is now landed under a
whole-source sentinel key (full_scan_key, out_frame = u32::MAX) in
the very silence_levels map the card reads, so scan_silences slices a
clip's own [in, out) window out of it (slice_whole_levels) before
ever falling back to the on-demand per-clip scan the card used to
start unconditionally.

silence_bg tracks scans in flight per (path, stream): its presence is
the dedupe against a re-add of the same source, and remove_source /
close_session cancel it via the same Progress::cancel flag
start_silence_scan already used, so a source that leaves mid-decode
does not write levels into a library that no longer holds it.

Caveat: the background decode is still O(file length) -- ~1700x
realtime per engine::silence::levels' own doc comment, so a
several-hour file is still seconds of background work, just no
longer on the card's critical path, and a card opened before that
finishes still falls back to its own on-demand scan.
crates/app/src/importing.rsmodified+39 -0
@@ -361,6 +361,45 @@ pub(crate) fn source_secs(key: &ScanKey, fps: f64) -> (f64, f64) {
361361 }
362362 }
363363
364+/// The [`ScanKey`] a background scan lands its whole-file levels under: every
365+/// frame the source has, so one entry answers for every clip cut from it. A
366+/// sentinel `out_frame` rather than a fourth map, because [`ScanKey`] is
367+/// already what [`Player::silence_levels`] is keyed by -- a clip can never
368+/// itself claim `u32::MAX` as its own `out_frame`, so the two never collide.
369+pub(crate) fn full_scan_key(path: &Path, stream: usize) -> ScanKey {
370+ (path.to_path_buf(), stream, 0, u32::MAX)
371+}
372+
373+/// The clip's own stretch of a whole-source scan, in the same dBFS windows
374+/// [`engine::silence::levels`] would have decoded for it directly: window `k`
375+/// of both is the same [`engine::silence::WINDOWS_PER_SEC`]th of a second from
376+/// the start of the file, so slicing costs no decode and reads the same
377+/// numbers the on-demand scan would have. Empty past the end of what the
378+/// background read has landed so far -- a scan still running answers with
379+/// what it has, same as [`SilenceScan`]'s own cancel does.
380+pub(crate) fn slice_whole_levels(whole: &[f32], fps: f64, in_frame: u32, out_frame: u32) -> Vec<f32> {
381+ if !(fps.is_finite() && fps > 0.) {
382+ return Vec::new();
383+ }
384+ let window = f64::from(engine::silence::WINDOWS_PER_SEC);
385+ let start = ((f64::from(in_frame) / fps) * window) as usize;
386+ let end = (((f64::from(out_frame) / fps) * window).ceil() as usize).min(whole.len());
387+ match start < end {
388+ true => whole[start..end].to_vec(),
389+ false => Vec::new(),
390+ }
391+}
392+
393+/// Whether the card may draw `key`'s marks as arithmetic rather than start a
394+/// worker for it: its own exact read, or -- new since the scan moved to
395+/// import -- the whole-source background scan its file is cut from
396+/// ([`Player::cache_media`]). One function so `Player::open_silence`'s plan
397+/// and `Player::scan_silences`' lookup share the one contract for what
398+/// "cached" means, instead of two copies that could drift.
399+pub(crate) fn silence_cached(levels: &std::collections::HashMap<ScanKey, Arc<Vec<f32>>>, key: &ScanKey) -> bool {
400+ levels.contains_key(key) || levels.contains_key(&full_scan_key(&key.0, key.1))
401+}
402+
364403 /// What the silence card says while its worker reads. Unlike an import this
365404 /// one *has* a fraction -- a decode knows how far into the sound it has come --
366405 /// so the line is where it is up to, out of what the header claims the track is
crates/app/src/main.rsmodified+8 -0
@@ -520,6 +520,13 @@ struct Player {
520520 /// The scan a worker is running for the card, if one is. `None` means the
521521 /// card is drawing numbers it already has.
522522 silence_scan: Option<SilenceScan>,
523+ /// Whole-source background scans in flight, keyed the same as
524+ /// [`Self::silence_levels`]'s own whole-source entries
525+ /// ([`full_scan_key`]). Started at import ([`Player::cache_media`]) so a
526+ /// card opened later finds the levels already read; presence here is what
527+ /// stops a re-add of the same source from starting a second one, and its
528+ /// [`engine::silence::Progress::cancel`] is what a removed source is told.
529+ silence_bg: HashMap<(PathBuf, usize), Arc<engine::silence::Progress>>,
523530 /// Which of the card's four sliders the arrow keys and a drag move. The
524531 /// card's own focus, since nothing in it takes gpui's (ledger:182).
525532 color_band: usize,
@@ -756,6 +763,7 @@ fn main() {
756763 silence_marks: Vec::new(),
757764 silence_levels: HashMap::new(),
758765 silence_scan: None,
766+ silence_bg: HashMap::new(),
759767 color_open: None,
760768 color_band: 0,
761769 color_dragging: false,
crates/app/src/player/cards.rsmodified+33 -11
@@ -560,7 +560,12 @@ impl Player {
560560 clip.out_frame,
561561 );
562562 match scan_plan(
563- self.silence_levels.contains_key(&key),
563+ // The whole-source background scan counts as "cached"
564+ // too: a card opened after import finds the levels a
565+ // repaint has already been decoding since the file
566+ // arrived ([`Player::cache_media`]), and `scan_silences`
567+ // is what slices this clip's stretch out of them.
568+ silence_cached(&self.silence_levels, &key),
564569 self.silence_scan.as_ref().map(|scan| &scan.key),
565570 &key,
566571 ) {
@@ -769,16 +774,33 @@ impl Player {
769774 };
770775 // Nothing read yet: the worker is running and the card is drawing its
771776 // line. The marks arrive with the levels.
772- let Some(levels) = self
773- .silence_levels
774- .get(&(
775- source.path.clone(),
776- source.audio_stream,
777- clip.in_frame,
778- clip.out_frame,
779- ))
780- .cloned()
781- else {
777+ //
778+ // The clip's own read first -- an on-demand scan already asked for
779+ // exactly this stretch -- and failing that, this clip's slice of the
780+ // whole-source background scan ([`Player::cache_media`]), which is
781+ // what makes the card answer at once for a file that arrived a
782+ // repaint or two ago.
783+ let key = (
784+ source.path.clone(),
785+ source.audio_stream,
786+ clip.in_frame,
787+ clip.out_frame,
788+ );
789+ let levels = match self.silence_levels.get(&key).cloned() {
790+ Some(levels) => Some(levels),
791+ None => self
792+ .silence_levels
793+ .get(&full_scan_key(&source.path, source.audio_stream))
794+ .map(|whole| {
795+ Arc::new(slice_whole_levels(
796+ whole,
797+ self.fps,
798+ clip.in_frame,
799+ clip.out_frame,
800+ ))
801+ }),
802+ };
803+ let Some(levels) = levels else {
782804 return;
783805 };
784806 self.silence_marks = engine::silence::timeline_regions(
crates/app/src/player/export.rsmodified+62 -0
@@ -177,9 +177,71 @@ impl Player {
177177 })
178178 .detach();
179179 }
180+ // The silence card's own decode, started here instead of at the card
181+ // -- a whole source, off the render thread, the moment it arrives
182+ // rather than the moment somebody opens the card on it
183+ // ([`Player::start_silence_scan`] used to be the only door and cost
184+ // the card its first fifty seconds). Landed under `full_scan_key` in
185+ // the very map the card reads, so `scan_silences` finds it warm.
186+ //
187+ // A still has no sound to read, and `silence_bg`'s presence is the
188+ // dedupe: a source already scanning, already scanned, or scanned and
189+ // then removed mid-read (its entry stays until the scan notices the
190+ // cancel) is not started twice. Gathered here, off `session`, for
191+ // `starting`'s own reason: starting one below takes `self` mutably
192+ // and `session` is a borrow of it.
193+ let silence_starting: Vec<(PathBuf, usize)> = session
194+ .sources()
195+ .iter()
196+ .map(|s| (s.path.clone(), s.audio_stream))
197+ .filter(|key| {
198+ !engine::is_image(&key.0)
199+ && !self.silence_bg.contains_key(key)
200+ && !self
201+ .silence_levels
202+ .contains_key(&full_scan_key(&key.0, key.1))
203+ })
204+ .collect();
180205 for path in starting {
181206 self.start_proxy_for(&path, cx);
182207 }
208+ for key in silence_starting {
209+ let progress = Arc::new(engine::silence::Progress::default());
210+ self.silence_bg.insert(key.clone(), Arc::clone(&progress));
211+ let scan = cx.background_executor().spawn({
212+ let (path, stream, progress) = (key.0.clone(), key.1, Arc::clone(&progress));
213+ async move {
214+ engine::silence::levels_with_progress(&path, stream, (0., f64::INFINITY), &progress)
215+ }
216+ });
217+ cx.spawn(async move |this, cx| {
218+ let landed = scan.await;
219+ this.update(cx, |this, cx| {
220+ this.silence_bg.remove(&key);
221+ // Cancelled means the source was removed while this read
222+ // was running: half a file's levels answer for a source
223+ // that is not on the list any more.
224+ if progress.cancel.load(std::sync::atomic::Ordering::Relaxed) {
225+ return;
226+ }
227+ if let Ok(Some(levels)) = landed {
228+ this.silence_levels
229+ .insert(full_scan_key(&key.0, key.1), Arc::new(levels));
230+ // A card already open and waiting on this very source
231+ // draws its marks the moment they land, same as an
232+ // on-demand scan does.
233+ this.scan_silences();
234+ cx.notify();
235+ }
236+ // `Ok(None)` (no audio track) and `Err` are left unrecorded:
237+ // the card's own on-demand scan is what a person waiting on
238+ // this file actually sees, and it gives the same answer
239+ // (`unscannable`/`SCAN FAILED`) when it is opened.
240+ })
241+ .ok();
242+ })
243+ .detach();
244+ }
183245 }
184246
185247 /// Probes what an export would open, once per (settings, resolution, cuts)
crates/app/src/player/library.rsmodified+16 -0
@@ -79,6 +79,13 @@ impl Player {
7979 .map(|session| session.remove_source(path, stream));
8080 let text = match removed {
8181 Some(Ok(idx)) => {
82+ // Tells a running background scan of this source nobody wants
83+ // its levels any more, and drops the entry that was standing
84+ // in the way of a re-add starting a fresh one
85+ // ([`Player::cache_media`]'s dedupe reads presence here).
86+ if let Some(scan) = self.silence_bg.remove(&(path.to_path_buf(), stream)) {
87+ scan.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
88+ }
8289 // The picked row may be the one that just went, and the engine
8390 // reseeks, so this owes the flag reset like every other edit.
8491 if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) {
@@ -164,6 +171,15 @@ impl Player {
164171 self.syncs.clear();
165172 // Scanned off sources that are not in the library any more.
166173 self.silence_levels.clear();
174+ // ...and every background read still chasing one of them: cancelled
175+ // rather than merely dropped, so a landing closure over a gone window
176+ // does not write into a `silence_levels` the next session starts
177+ // empty (`Player::cache_media`'s spawn checks this flag before it
178+ // inserts).
179+ for scan in self.silence_bg.values() {
180+ scan.cancel.store(true, std::sync::atomic::Ordering::Relaxed);
181+ }
182+ self.silence_bg.clear();
167183 // Every gesture in flight, dropped for `reset_after_reseek`'s reason
168184 // (it drops the trim below): a drag holds a bar, a clip or a band of a
169185 // timeline that has just stopped existing.
crates/app/src/tests/media.rsmodified+60 -0
@@ -293,6 +293,66 @@ fn a_second_film_does_not_cost_the_first_one_its_levels() {
293293 assert_eq!(source_secs(&half, 0.), (0., f64::INFINITY));
294294 }
295295
296+/// The background scan started at import ([`Player::cache_media`]) lands its
297+/// whole-file levels under [`full_scan_key`], and that entry alone is what
298+/// makes the card's own cache check answer "already read" for *every* clip
299+/// cut from that source -- without the per-clip decode `start_silence_scan`
300+/// used to be the only way to get one. The whole point of moving the scan to
301+/// import: the card must find it warm.
302+#[test]
303+fn a_warm_whole_source_scan_answers_the_card_for_every_clip_cut_from_it() {
304+ use std::sync::Arc;
305+ let mut levels: std::collections::HashMap<ScanKey, Arc<Vec<f32>>> = std::collections::HashMap::new();
306+ let clip_a = (PathBuf::from("/films/a.mkv"), 0, 300, 900);
307+ let clip_b = (PathBuf::from("/films/a.mkv"), 0, 1_200, 1_800);
308+ // Nothing yet -- neither clip's own read nor a background one.
309+ assert!(!silence_cached(&levels, &clip_a));
310+ assert!(!silence_cached(&levels, &clip_b));
311+ // The background scan lands, once, before either half of the take was
312+ // ever opened on the card.
313+ levels.insert(full_scan_key(&clip_a.0, clip_a.1), Arc::new(vec![0.; 100]));
314+ assert!(
315+ silence_cached(&levels, &clip_a) && silence_cached(&levels, &clip_b),
316+ "one whole-source entry answers for both halves of the take"
317+ );
318+ // A clip cut from a *different* file is not answered by it -- the
319+ // sentinel is per (path, stream), exactly like every other scan key.
320+ let other_file = (PathBuf::from("/films/b.mkv"), 0, 300, 900);
321+ assert!(!silence_cached(&levels, &other_file));
322+ // A clip's own exact read still counts too, same as before this existed.
323+ levels.insert(clip_a.clone(), Arc::new(vec![-40.; 10]));
324+ assert!(silence_cached(&levels, &clip_a));
325+}
326+
327+/// What the card actually draws from a warm background scan: the same
328+/// dBFS-per-window numbers a direct read of the clip's own stretch would
329+/// have found, because window `k` of the whole file and window `k` of a read
330+/// that started at second 0 name the same slice of the same source
331+/// ([`slice_whole_levels`]'s whole contract). No decode in this test at
332+/// all -- the numbers are synthetic and distinct per window so a wrong
333+/// offset shows up as a wrong value, not a coincidentally-right one.
334+#[test]
335+fn a_clips_slice_of_the_whole_scan_is_the_windows_its_own_read_would_have_found() {
336+ // 50 fps: one timeline frame is exactly one silence window
337+ // (`engine::silence::WINDOWS_PER_SEC` is 50), so the arithmetic is exact
338+ // and the test does not have to fight rounding to prove the offset.
339+ let fps = 50.;
340+ let whole: Vec<f32> = (0..40).map(|i| i as f32).collect();
341+ let slice = slice_whole_levels(&whole, fps, 10, 20);
342+ assert_eq!(slice, (10..20).map(|i| i as f32).collect::<Vec<f32>>());
343+ // The clip's own in point is where its slice starts, not the file's:
344+ // a take an hour into the film reads the same as one at its head.
345+ assert_eq!(slice_whole_levels(&whole, fps, 0, 5), vec![0., 1., 2., 3., 4.]);
346+ // Past what the background scan has read so far (still running, or
347+ // cancelled) is not padded with zeroes -- the caller is told nothing is
348+ // there yet, same as [`SilenceScan`]'s own cancel leaves a prefix.
349+ assert_eq!(slice_whole_levels(&whole, fps, 35, 60), vec![35., 36., 37., 38., 39.]);
350+ assert_eq!(slice_whole_levels(&whole, fps, 45, 60), Vec::<f32>::new());
351+ // A rate that is not a rate reads nothing, the same refusal
352+ // `source_secs` makes for a background scan's own range.
353+ assert_eq!(slice_whole_levels(&whole, 0., 0, 10), Vec::<f32>::new());
354+}
355+
296356 /// The import door's split, which is what keeps the render thread out of a
297357 /// header walk: what the worker probed and what the landing registers add up
298358 /// to exactly the rows, lengths and refusals the in-place import lands.
crates/app/src/tests/mod.rsmodified+1 -1
@@ -46,7 +46,7 @@ use super::{
4646 fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution,
4747 note_progress, px_along,
4848 IMPORT_STALL, Import, ImportStage, SEEK_STALL, ScanKey, ScanPlan, SilenceScan, import_line,
49- Landing, arrival, launch_queue,
49+ Landing, arrival, launch_queue, full_scan_key, silence_cached, slice_whole_levels,
5050 read_ahead, scan_plan, seek_line, silence_line, source_secs, stash_or_write,
5151 repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label,
5252 clip_width, frames_of_us, trimmed_clip, trimmed_sub, trims, unscannable, unusable,