forge
Explore
Log in

Don't you dare go Hollow

The visualizer reads its envelope from a process memo

Browse files at this commit

dc551d7d3b8f96849c62c9a5890aa774b06a1901Ahmet Kaan GümüşParent: 880e8a0
  • perf
    • the visualizer reads its envelope from a process memo
Show full message
⚡ perf(audio): the visualizer reads its envelope from a process memo

A picture rebuild called `open_visualizer`, which decoded the whole file's
audio envelope again -- ~51 ms of CPU, 598k buckets for a 150 s song -- so
every look edit, and every sample of a wheel drag, paid a whole-file decode
for an answer that had not changed. `waveform::peaks_shared` memoises it by
the file's own stat (path, stream, buckets, length, mtime), bounded in
buckets; the envelope fed to the painter is the same value as before.

The user's "dragging causes frame drop" was that decode on the frame path:
rebuild latency p50 68 -> 6-18 ms, playing frame interval p95 80 -> 48 ms,
frames over 50 ms 32/438 -> 1/496. The wheel's own 720-polygon repaint
measured ~0.9 ms and the engine write's UI-thread share ~42 us, so neither
was touched.
crates/engine/src/decode.rsmodified+1 -1
@@ -660,7 +660,7 @@ impl DecodeSession {
660 // no track at all -- paints the flat line, which is what its660 // no track at all -- paints the flat line, which is what its
661 // silence looks like anyway: a visualizer frame always661 // silence looks like anyway: a visualizer frame always
662 // exists, and is never worth failing a span over.662 // exists, and is never worth failing a span over.
663- let peaks = crate::waveform::peaks(&path, stream, VIZ_BUCKETS_PER_SEC)663+ let peaks = crate::waveform::peaks_shared(&path, stream, VIZ_BUCKETS_PER_SEC)
664 .ok()664 .ok()
665 .flatten()665 .flatten()
666 .unwrap_or_default();666 .unwrap_or_default();
crates/engine/src/waveform.rsmodified+183 -1
@@ -42,6 +42,112 @@ pub fn peaks(
42 peaks_over(path.as_ref(), stream, buckets_per_sec, None)42 peaks_over(path.as_ref(), stream, buckets_per_sec, None)
43 }43 }
44 44
45+/// How many buckets the process-wide envelope memo may hold before it gives
46+/// them back. A bucket is a pair of `f32`s, so this is a ~64 MB ceiling over
47+/// every *source* a session has asked for -- not over the asks themselves --
48+/// and a single source larger than it is not held at all.
49+const PEAKS_MEMO_BUCKETS: usize = 8 << 20;
50+
51+/// One file's envelope as the memo holds it: shared, so the second ask for the
52+/// same source is a refcount rather than a decode of the whole file.
53+pub(crate) type SharedPeaks = std::sync::Arc<Vec<(f32, f32)>>;
54+
55+/// The identity a memo entry is keyed by: what was asked for *and* the file it
56+/// was answered from, so a source replaced on disk is read again rather than
57+/// served the envelope of bytes that are gone.
58+#[derive(PartialEq, Eq, Hash)]
59+struct PeaksKey {
60+ path: PathBuf,
61+ stream: usize,
62+ buckets_per_sec: u32,
63+ bytes: u64,
64+ mtime: Option<std::time::SystemTime>,
65+}
66+
67+impl PeaksKey {
68+ fn of(path: &Path, stream: usize, buckets_per_sec: u32) -> Self {
69+ let stat = std::fs::metadata(path).ok();
70+ Self {
71+ path: path.to_path_buf(),
72+ stream,
73+ buckets_per_sec,
74+ bytes: stat.as_ref().map_or(0, std::fs::Metadata::len),
75+ mtime: stat.and_then(|m| m.modified().ok()),
76+ }
77+ }
78+}
79+
80+/// The memo and how many buckets it is holding. One lock for both: a hit is a
81+/// lookup and a refcount, which is the whole of what the caller saves.
82+///
83+/// `std::sync::Mutex`, not `parking_lot`'s: edith's workspace has no
84+/// `parking_lot` of its own and this crate locks `std`'s everywhere (the audio
85+/// device, the tap), so a new dependency is not what a memo is worth.
86+fn peaks_memo() -> &'static std::sync::Mutex<(PeaksMemo, usize)> {
87+ static MEMO: std::sync::LazyLock<std::sync::Mutex<(PeaksMemo, usize)>> =
88+ std::sync::LazyLock::new(|| std::sync::Mutex::new((PeaksMemo::new(), 0)));
89+ &MEMO
90+}
91+
92+/// Every envelope the process has been asked for, by identity.
93+type PeaksMemo = std::collections::HashMap<PeaksKey, SharedPeaks>;
94+
95+/// [`peaks`] as a handle the caller can hold: the same envelope, shared rather
96+/// than copied.
97+///
98+/// The visualizer seat asks this of every picture rebuild it makes
99+/// ([`DecodeSession::open_visualizer`]): a rebuild happens once per look edit,
100+/// and a look edit is what a drag across the colour wheel is -- so an envelope
101+/// decoded per rebuild is a whole-file audio decode per pointer sample, for an
102+/// answer that has not changed.
103+///
104+/// Keyed on the file's own stat ([`PeaksKey`]) and bounded by
105+/// [`PEAKS_MEMO_BUCKETS`] *of what it holds*: past the ceiling the memo lets
106+/// everything go rather than evicting one entry at a time, because the entries
107+/// are large and a re-decode is the honest cost of asking for more than the
108+/// ceiling. A single source whose own envelope is bigger than the ceiling is
109+/// not memoized at all (see [`peaks_shared`]), so the ceiling is one -- an
110+/// entry that no clear can bring the memo back under would be a memo that
111+/// clears on every other ask.
112+pub(crate) fn peaks_shared(
113+ path: &Path,
114+ stream: usize,
115+ buckets_per_sec: u32,
116+) -> crate::Result<Option<SharedPeaks>> {
117+ let key = PeaksKey::of(path, stream, buckets_per_sec);
118+ if let Some(hit) = peaks_memo().lock().unwrap().0.get(&key) {
119+ return Ok(Some(SharedPeaks::clone(hit)));
120+ }
121+ let Some(peaks) = peaks_over(path, stream, buckets_per_sec, None)? else {
122+ return Ok(None);
123+ };
124+ let shared = SharedPeaks::new(peaks);
125+ let mut memo = peaks_memo().lock().unwrap();
126+ // An entry bigger than the ceiling is never memoized at all: keeping it
127+ // would put the count permanently over the ceiling, so the next ask of any
128+ // *other* key would clear the map and drop it -- and this source would pay
129+ // a whole-file decode per rebuild anyway, which is the stall the memo is
130+ // here to remove. The caller gets its envelope either way.
131+ if shared.len() <= PEAKS_MEMO_BUCKETS {
132+ if memo.1 + shared.len() > PEAKS_MEMO_BUCKETS {
133+ memo.0.clear();
134+ memo.1 = 0;
135+ }
136+ // The map may already hold this very key: two workers that missed
137+ // together both decode, and the slower one inserts after the faster
138+ // one. The count follows what the map *holds*, so the replaced entry's
139+ // buckets come off before the new one's go on -- otherwise every such
140+ // race leaves the count high for good (only a clear resets it) and
141+ // later asks clear the memo early, dropping entries that then pay a
142+ // whole-file decode to be rebuilt.
143+ if let Some(previous) = memo.0.insert(key, SharedPeaks::clone(&shared)) {
144+ memo.1 -= previous.len();
145+ }
146+ memo.1 += shared.len();
147+ }
148+ Ok(Some(shared))
149+}
150+
45 /// [`peaks`] with the split forced to `jobs` windows, which is how a test asks151 /// [`peaks`] with the split forced to `jobs` windows, which is how a test asks
46 /// for the same envelope by both routes.152 /// for the same envelope by both routes.
47 fn peaks_over(153 fn peaks_over(
@@ -181,7 +287,7 @@ fn fold(
181 mod tests {287 mod tests {
182 use std::path::PathBuf;288 use std::path::PathBuf;
183 289
184- use super::{peaks, peaks_over};290+ use super::{peaks, peaks_over, peaks_shared};
185 291
186 const BPS: u32 = 10;292 const BPS: u32 = 10;
187 293
@@ -350,4 +456,80 @@ mod tests {
350 let two = peaks(&multi, 2, BPS).expect("AC-3 opens").expect("stream 2");456 let two = peaks(&multi, 2, BPS).expect("AC-3 opens").expect("stream 2");
351 assert!(!two.is_empty(), "the AC-3 stream drew nothing");457 assert!(!two.is_empty(), "the AC-3 stream drew nothing");
352 }458 }
459+
460+ /// The memo is keyed on the *ask*, not on the file: a second visualizer
461+ /// rebuild of one source reuses the envelope, and one of another stream is
462+ /// decoded rather than handed the first one's -- the lie
463+ /// [`each_stream_of_a_file_has_its_own_envelope`] refuses, one cache layer
464+ /// down, where the visualizer seat reads it.
465+ #[test]
466+ fn the_shared_memo_answers_per_stream() {
467+ let multi = asset("test_multiaudio.mp4");
468+ let zero = peaks_shared(&multi, 0, BPS)
469+ .expect("open")
470+ .expect("stream 0");
471+ let again = peaks_shared(&multi, 0, BPS)
472+ .expect("open")
473+ .expect("stream 0, second ask");
474+ // Shared, not decoded again -- which is the whole of what the second
475+ // visualizer rebuild saves.
476+ assert!(
477+ std::sync::Arc::ptr_eq(&zero, &again),
478+ "the second ask decoded the file again"
479+ );
480+ // ...and the very envelope a plain ask draws, so nothing is served
481+ // through the memo that the decoder would not have said.
482+ let plain = peaks(&multi, 0, BPS).expect("open").expect("stream 0");
483+ assert_eq!(*zero, plain);
484+ let one = peaks_shared(&multi, 1, BPS)
485+ .expect("open")
486+ .expect("stream 1");
487+ assert_ne!(*zero, *one, "a stream took another's memo entry");
488+ }
489+
490+ /// A source replaced on disk is read again: the key carries the file's own
491+ /// stat, so the memo cannot paint the old file's envelope for a clip that
492+ /// no longer plays it. Asked of a *copy*, because the fixtures are
493+ /// read-only for every other test in this binary.
494+ #[test]
495+ fn a_replaced_source_is_read_again() {
496+ let path = std::env::temp_dir().join(format!("edith-peaks-memo-{}.mp4", std::process::id()));
497+ let short = std::fs::read(asset("test_multiaudio.mp4")).expect("read the fixture");
498+ let long = std::fs::read(asset("test_av.mp4")).expect("read the fixture");
499+ // The two halves below are the length half and the clock half of the
500+ // key, so their sizes have to differ for the first of them to be it.
501+ assert_ne!(short.len(), long.len(), "fixtures must differ in length");
502+
503+ std::fs::write(&path, &short).expect("write the copy");
504+ let first = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
505+ let again = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
506+ assert!(std::sync::Arc::ptr_eq(&first, &again), "the copy was not memoized");
507+
508+ // Other bytes behind the same path. A key without the file's length
509+ // (or without any stat at all) serves `first` here -- the envelope of
510+ // bytes that are gone.
511+ std::fs::write(&path, &long).expect("rewrite the copy");
512+ let replaced = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
513+ assert_ne!(*replaced, *first, "the memo served the replaced file's envelope");
514+ assert_eq!(
515+ *replaced,
516+ peaks(&path, 0, BPS).expect("open").expect("copy"),
517+ "the memo's answer is not what a plain ask draws"
518+ );
519+
520+ // The *same* bytes written again: same length, a newer clock. Resolution
521+ // is the filesystem's, so give it a moment to move.
522+ std::thread::sleep(std::time::Duration::from_millis(20));
523+ std::fs::write(&path, &long).expect("touch the copy");
524+ let touched = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
525+ assert_eq!(*touched, *replaced);
526+ // A key with length but no mtime hands the old handle back -- for a file
527+ // that changed under it, which is the serve the mtime is in the key for.
528+ assert!(
529+ !std::sync::Arc::ptr_eq(&replaced, &touched),
530+ "the mtime is not part of the key"
531+ );
532+
533+ let _ = std::fs::remove_file(&path);
534+ }
353 }535 }