🔀 merge(memo): the envelope memo answers a trackless source too
Browse files at this commit1 changed file +245 -30
- crates/engine/src/waveform.rs +245 -30
crates/engine/src/waveform.rsmodified+245 -30
| @@ -89,8 +89,51 @@ fn peaks_memo() -> &'static std::sync::Mutex<(PeaksMemo, usize)> { | |||
| 89 | &MEMO | 89 | &MEMO |
| 90 | } | 90 | } |
| 91 | 91 | ||
| 92 | -/// Every envelope the process has been asked for, by identity. | 92 | +/// Test-only: how many times an ask had to decode rather than answer from what |
| 93 | -type PeaksMemo = std::collections::HashMap<PeaksKey, SharedPeaks>; | 93 | +/// the memo already held. A second ask for the same source -- trackless or not |
| 94 | +/// -- must not move it, which is what makes "the memo answered" observable. | ||
| 95 | +#[cfg(test)] | ||
| 96 | +static MEMO_DECODES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); | ||
| 97 | + | ||
| 98 | +/// [`MEMO_DECODES`], for a test that measures a delta across its own asks. | ||
| 99 | +#[cfg(test)] | ||
| 100 | +fn memo_decodes() -> usize { | ||
| 101 | + MEMO_DECODES.load(std::sync::atomic::Ordering::Relaxed) | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/// What the memo holds for one key: an envelope, or the stable answer that the | ||
| 105 | +/// source carries no audio track at all. The second is worth keeping too -- a | ||
| 106 | +/// trackless source re-opens its container on every ask otherwise, the same | ||
| 107 | +/// per-rebuild cost the envelope memo exists to remove -- and it holds no | ||
| 108 | +/// buckets, so the counter stays honest about what the map holds. | ||
| 109 | +enum MemoEntry { | ||
| 110 | + /// A source with an audio track, shared so a second ask is a refcount. | ||
| 111 | + Envelope(SharedPeaks), | ||
| 112 | + /// A source with no audio track: a valid, empty answer ([`peaks`]'s | ||
| 113 | + /// `Ok(None)`), kept rather than re-derived from the file each time. | ||
| 114 | + NoTrack, | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +impl MemoEntry { | ||
| 118 | + /// The answer this entry stands for, as [`peaks_shared`] returns it. | ||
| 119 | + fn envelope(&self) -> Option<SharedPeaks> { | ||
| 120 | + match self { | ||
| 121 | + MemoEntry::Envelope(shared) => Some(SharedPeaks::clone(shared)), | ||
| 122 | + MemoEntry::NoTrack => None, | ||
| 123 | + } | ||
| 124 | + } | ||
| 125 | + | ||
| 126 | + /// How many buckets this entry adds to the counter. | ||
| 127 | + fn buckets(&self) -> usize { | ||
| 128 | + match self { | ||
| 129 | + MemoEntry::Envelope(shared) => shared.len(), | ||
| 130 | + MemoEntry::NoTrack => 0, | ||
| 131 | + } | ||
| 132 | + } | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +/// Every answer the process has been asked for, by identity. | ||
| 136 | +type PeaksMemo = std::collections::HashMap<PeaksKey, MemoEntry>; | ||
| 94 | 137 | ||
| 95 | /// [`peaks`] as a handle the caller can hold: the same envelope, shared rather | 138 | /// [`peaks`] as a handle the caller can hold: the same envelope, shared rather |
| 96 | /// than copied. | 139 | /// than copied. |
| @@ -109,43 +152,87 @@ type PeaksMemo = std::collections::HashMap<PeaksKey, SharedPeaks>; | |||
| 109 | /// not memoized at all (see [`peaks_shared`]), so the ceiling is one -- an | 152 | /// 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 | 153 | /// entry that no clear can bring the memo back under would be a memo that |
| 111 | /// clears on every other ask. | 154 | /// clears on every other ask. |
| 155 | +/// | ||
| 156 | +/// A trackless source's `Ok(None)` is kept too: it is an answer the file will | ||
| 157 | +/// give again, and without it a visualizer clip on a silent source re-opens | ||
| 158 | +/// the container on every picture rebuild -- the whole cost the memo removes, | ||
| 159 | +/// paid once per look edit. It holds no buckets, so it never counts against | ||
| 160 | +/// the ceiling. A failed ask is *not* kept: a decode that failed once may fail | ||
| 161 | +/// for a reason that has gone away, and caching it would make that permanent. | ||
| 112 | pub(crate) fn peaks_shared( | 162 | pub(crate) fn peaks_shared( |
| 113 | path: &Path, | 163 | path: &Path, |
| 114 | stream: usize, | 164 | stream: usize, |
| 115 | buckets_per_sec: u32, | 165 | buckets_per_sec: u32, |
| 166 | +) -> crate::Result<Option<SharedPeaks>> { | ||
| 167 | + peaks_shared_capped(path, stream, buckets_per_sec, PEAKS_MEMO_BUCKETS) | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +/// [`peaks_shared`] against a ceiling a test can drive down to a handful of | ||
| 171 | +/// buckets, so the over-the-ceiling path is walked without an eight-million- | ||
| 172 | +/// bucket fixture. `cap` is [`PEAKS_MEMO_BUCKETS`] everywhere but in a test. | ||
| 173 | +fn peaks_shared_capped( | ||
| 174 | + path: &Path, | ||
| 175 | + stream: usize, | ||
| 176 | + buckets_per_sec: u32, | ||
| 177 | + cap: usize, | ||
| 116 | ) -> crate::Result<Option<SharedPeaks>> { | 178 | ) -> crate::Result<Option<SharedPeaks>> { |
| 117 | let key = PeaksKey::of(path, stream, buckets_per_sec); | 179 | let key = PeaksKey::of(path, stream, buckets_per_sec); |
| 118 | if let Some(hit) = peaks_memo().lock().unwrap().0.get(&key) { | 180 | if let Some(hit) = peaks_memo().lock().unwrap().0.get(&key) { |
| 119 | - return Ok(Some(SharedPeaks::clone(hit))); | 181 | + return Ok(hit.envelope()); |
| 120 | } | 182 | } |
| 121 | - let Some(peaks) = peaks_over(path, stream, buckets_per_sec, None)? else { | 183 | + #[cfg(test)] |
| 122 | - return Ok(None); | 184 | + MEMO_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 185 | + // A failure is *not* memoized: `?` leaves the map untouched, so a decode | ||
| 186 | + // that failed once -- a file caught mid-write, a busy device -- is retried | ||
| 187 | + // rather than frozen for the process's life. Only the two successful | ||
| 188 | + // answers are kept: the envelope, and the trackless `None`. | ||
| 189 | + let answer = peaks_over(path, stream, buckets_per_sec, None)?; | ||
| 190 | + let entry = match answer { | ||
| 191 | + None => MemoEntry::NoTrack, | ||
| 192 | + Some(peaks) => MemoEntry::Envelope(SharedPeaks::new(peaks)), | ||
| 123 | }; | 193 | }; |
| 124 | - let shared = SharedPeaks::new(peaks); | 194 | + // The handle the caller gets is the answer itself, whether or not the memo |
| 125 | - let mut memo = peaks_memo().lock().unwrap(); | 195 | + // keeps a copy: an over-the-ceiling envelope is still returned below. |
| 126 | - // An entry bigger than the ceiling is never memoized at all: keeping it | 196 | + let handle = entry.envelope(); |
| 127 | - // would put the count permanently over the ceiling, so the next ask of any | 197 | + let mut guard = peaks_memo().lock().unwrap(); |
| 128 | - // *other* key would clear the map and drop it -- and this source would pay | 198 | + let (memo, count) = &mut *guard; |
| 129 | - // a whole-file decode per rebuild anyway, which is the stall the memo is | 199 | + memoize(memo, count, cap, key, entry); |
| 130 | - // here to remove. The caller gets its envelope either way. | 200 | + Ok(handle) |
| 131 | - if shared.len() <= PEAKS_MEMO_BUCKETS { | 201 | +} |
| 132 | - if memo.1 + shared.len() > PEAKS_MEMO_BUCKETS { | 202 | + |
| 133 | - memo.0.clear(); | 203 | +/// Record `entry` under `key` in `memo`, keeping `count` equal to the buckets |
| 134 | - memo.1 = 0; | 204 | +/// the map holds. The arithmetic is what keeps the ceiling a ceiling: |
| 135 | - } | 205 | +/// |
| 136 | - // The map may already hold this very key: two workers that missed | 206 | +/// - an entry bigger than `cap` is not held at all -- keeping it would put the |
| 137 | - // together both decode, and the slower one inserts after the faster | 207 | +/// count permanently over the ceiling, so the next ask of any *other* key |
| 138 | - // one. The count follows what the map *holds*, so the replaced entry's | 208 | +/// would clear the map and drop it, and this source would pay a whole-file |
| 139 | - // buckets come off before the new one's go on -- otherwise every such | 209 | +/// decode per rebuild anyway. The caller keeps the handle it was handed; |
| 140 | - // race leaves the count high for good (only a clear resets it) and | 210 | +/// - when the new entry would take the count past `cap`, the map is emptied |
| 141 | - // later asks clear the memo early, dropping entries that then pay a | 211 | +/// rather than evicted one entry at a time (the entries are large); |
| 142 | - // whole-file decode to be rebuilt. | 212 | +/// - an insert that replaces an entry the count already includes subtracts the |
| 143 | - if let Some(previous) = memo.0.insert(key, SharedPeaks::clone(&shared)) { | 213 | +/// replaced length first, so the racing-workers case -- two workers that |
| 144 | - memo.1 -= previous.len(); | 214 | +/// missed one key each decode and insert it -- does not leave the count high |
| 145 | - } | 215 | +/// for good: only a clear resets it, and a high count makes later asks clear |
| 146 | - memo.1 += shared.len(); | 216 | +/// early, dropping entries that then pay a whole-file decode to be rebuilt. |
| 217 | +fn memoize( | ||
| 218 | + memo: &mut PeaksMemo, | ||
| 219 | + count: &mut usize, | ||
| 220 | + cap: usize, | ||
| 221 | + key: PeaksKey, | ||
| 222 | + entry: MemoEntry, | ||
| 223 | +) { | ||
| 224 | + let len = entry.buckets(); | ||
| 225 | + if len > cap { | ||
| 226 | + return; | ||
| 227 | + } | ||
| 228 | + if *count + len > cap { | ||
| 229 | + memo.clear(); | ||
| 230 | + *count = 0; | ||
| 147 | } | 231 | } |
| 148 | - Ok(Some(shared)) | 232 | + if let Some(previous) = memo.insert(key, entry) { |
| 233 | + *count -= previous.buckets(); | ||
| 234 | + } | ||
| 235 | + *count += len; | ||
| 149 | } | 236 | } |
| 150 | 237 | ||
| 151 | /// [`peaks`] with the split forced to `jobs` windows, which is how a test asks | 238 | /// [`peaks`] with the split forced to `jobs` windows, which is how a test asks |
| @@ -287,7 +374,10 @@ fn fold( | |||
| 287 | mod tests { | 374 | mod tests { |
| 288 | use std::path::PathBuf; | 375 | use std::path::PathBuf; |
| 289 | 376 | ||
| 290 | - use super::{peaks, peaks_over, peaks_shared}; | 377 | + use super::{ |
| 378 | + memo_decodes, memoize, peaks, peaks_over, peaks_shared, peaks_shared_capped, MemoEntry, | ||
| 379 | + PeaksKey, PeaksMemo, SharedPeaks, | ||
| 380 | + }; | ||
| 291 | 381 | ||
| 292 | const BPS: u32 = 10; | 382 | const BPS: u32 = 10; |
| 293 | 383 | ||
| @@ -297,6 +387,16 @@ mod tests { | |||
| 297 | .join(name) | 387 | .join(name) |
| 298 | } | 388 | } |
| 299 | 389 | ||
| 390 | + /// A private copy of a fixture, so the memo key a test drives is not one | ||
| 391 | + /// another test in this binary may already hold. | ||
| 392 | + fn copy_of(name: &str, tag: &str) -> PathBuf { | ||
| 393 | + let path = | ||
| 394 | + std::env::temp_dir().join(format!("edith-peaks-{tag}-{}.mp4", std::process::id())); | ||
| 395 | + std::fs::write(&path, std::fs::read(asset(name)).expect("read the fixture")) | ||
| 396 | + .expect("write the copy"); | ||
| 397 | + path | ||
| 398 | + } | ||
| 399 | + | ||
| 300 | #[test] | 400 | #[test] |
| 301 | fn peaks_follow_the_1hz_volume_pulse() { | 401 | fn peaks_follow_the_1hz_volume_pulse() { |
| 302 | let peaks = peaks(asset("test_av.mp4"), 0, BPS) | 402 | let peaks = peaks(asset("test_av.mp4"), 0, BPS) |
| @@ -532,4 +632,119 @@ mod tests { | |||
| 532 | 632 | ||
| 533 | let _ = std::fs::remove_file(&path); | 633 | let _ = std::fs::remove_file(&path); |
| 534 | } | 634 | } |
| 635 | + | ||
| 636 | + /// A trackless source is an answer too, and the memo keeps it: without that | ||
| 637 | + /// a visualizer clip on a silent source re-opens the container on every | ||
| 638 | + /// picture rebuild -- the whole cost the memo exists to remove, paid once | ||
| 639 | + /// per look edit. Proved by counting decodes: the second ask must not take | ||
| 640 | + /// one. A copy is used so the key is this test's alone. | ||
| 641 | + #[test] | ||
| 642 | + fn a_trackless_source_is_memoized_too() { | ||
| 643 | + let path = copy_of("test_baseline.mp4", "none"); | ||
| 644 | + | ||
| 645 | + let before = memo_decodes(); | ||
| 646 | + let first = peaks_shared(&path, 0, BPS).expect("open"); | ||
| 647 | + assert!(first.is_none(), "test_baseline.mp4 has no audio track"); | ||
| 648 | + let after_first = memo_decodes(); | ||
| 649 | + assert_eq!(after_first - before, 1, "the first ask did not decode"); | ||
| 650 | + | ||
| 651 | + let second = peaks_shared(&path, 0, BPS).expect("open"); | ||
| 652 | + assert!(second.is_none()); | ||
| 653 | + assert_eq!( | ||
| 654 | + memo_decodes(), | ||
| 655 | + after_first, | ||
| 656 | + "the second ask re-opened a trackless source" | ||
| 657 | + ); | ||
| 658 | + | ||
| 659 | + let _ = std::fs::remove_file(&path); | ||
| 660 | + } | ||
| 661 | + | ||
| 662 | + /// A trackless answer holds no buckets, so the ceiling counts only | ||
| 663 | + /// envelopes -- and a source that gains an audio track (a re-encode) swaps | ||
| 664 | + /// the `NoTrack` entry for an envelope without stranding the old count. | ||
| 665 | + #[test] | ||
| 666 | + fn a_trackless_answer_holds_no_buckets() { | ||
| 667 | + let mut memo = PeaksMemo::new(); | ||
| 668 | + let mut count = 0; | ||
| 669 | + let key = || PeaksKey::of(std::path::Path::new("edith-peaks-none-key"), 0, BPS); | ||
| 670 | + | ||
| 671 | + memoize(&mut memo, &mut count, 100, key(), MemoEntry::NoTrack); | ||
| 672 | + assert_eq!(count, 0, "a trackless answer counted buckets"); | ||
| 673 | + assert!(memo.contains_key(&key())); | ||
| 674 | + | ||
| 675 | + memoize( | ||
| 676 | + &mut memo, | ||
| 677 | + &mut count, | ||
| 678 | + 100, | ||
| 679 | + key(), | ||
| 680 | + MemoEntry::Envelope(SharedPeaks::new(vec![(0.0, 0.0); 4])), | ||
| 681 | + ); | ||
| 682 | + assert_eq!(count, 4, "the envelope did not replace the trackless count"); | ||
| 683 | + } | ||
| 684 | + | ||
| 685 | + /// An envelope larger than the ceiling is handed to the caller but never | ||
| 686 | + /// held, so a clear can always bring the memo back under the ceiling. The | ||
| 687 | + /// real ceiling is 8M buckets (~35 min at 10/s), unreachable from a | ||
| 688 | + /// fixture, so this drives the same code through a ceiling of ten buckets | ||
| 689 | + /// against a five-second source (about fifty buckets). Covers: the | ||
| 690 | + /// over-the-ceiling *decision* and the caller-still-gets-its-handle half. | ||
| 691 | + /// Does not cover: an end-to-end decode past eight million buckets. | ||
| 692 | + #[test] | ||
| 693 | + fn an_envelope_over_the_ceiling_is_not_held() { | ||
| 694 | + let file = copy_of("test_av.mp4", "over"); | ||
| 695 | + let before = memo_decodes(); | ||
| 696 | + let first = peaks_shared_capped(&file, 0, BPS, 10) | ||
| 697 | + .expect("open") | ||
| 698 | + .expect("test_av.mp4 has an audio track"); | ||
| 699 | + assert!(first.len() > 10, "the fixture must exceed the test ceiling"); | ||
| 700 | + let mid = memo_decodes(); | ||
| 701 | + assert_eq!(mid - before, 1, "the first ask did not decode"); | ||
| 702 | + | ||
| 703 | + let second = peaks_shared_capped(&file, 0, BPS, 10) | ||
| 704 | + .expect("open") | ||
| 705 | + .expect("test_av.mp4 has an audio track"); | ||
| 706 | + assert_eq!(*first, *second, "the caller did not get its envelope"); | ||
| 707 | + assert_eq!( | ||
| 708 | + memo_decodes() - mid, | ||
| 709 | + 1, | ||
| 710 | + "an envelope over the ceiling was held" | ||
| 711 | + ); | ||
| 712 | + | ||
| 713 | + let _ = std::fs::remove_file(&file); | ||
| 714 | + } | ||
| 715 | + | ||
| 716 | + /// An insert that replaces an entry the counter already includes subtracts | ||
| 717 | + /// the replaced length: the racing-workers case, where two workers that | ||
| 718 | + /// missed one key each decode and insert it. The count follows what the map | ||
| 719 | + /// *holds*, so a missing subtraction leaves it high for good -- only a | ||
| 720 | + /// clear resets it, and later asks then clear early, dropping entries that | ||
| 721 | + /// pay a whole-file decode to be rebuilt. Driven through the same [`memoize`] | ||
| 722 | + /// the ask path uses (a second *ask* on one key hits the memo, so it cannot | ||
| 723 | + /// reach the insert): without the subtraction the second insert would read | ||
| 724 | + /// 3 + 5 = 8. | ||
| 725 | + #[test] | ||
| 726 | + fn replacing_an_entry_subtracts_the_old_buckets() { | ||
| 727 | + let mut memo = PeaksMemo::new(); | ||
| 728 | + let mut count = 0; | ||
| 729 | + let key = || PeaksKey::of(std::path::Path::new("edith-peaks-replace-key"), 0, BPS); | ||
| 730 | + | ||
| 731 | + memoize( | ||
| 732 | + &mut memo, | ||
| 733 | + &mut count, | ||
| 734 | + 100, | ||
| 735 | + key(), | ||
| 736 | + MemoEntry::Envelope(SharedPeaks::new(vec![(0.0, 0.0); 3])), | ||
| 737 | + ); | ||
| 738 | + assert_eq!(count, 3, "the first insert was not counted"); | ||
| 739 | + | ||
| 740 | + memoize( | ||
| 741 | + &mut memo, | ||
| 742 | + &mut count, | ||
| 743 | + 100, | ||
| 744 | + key(), | ||
| 745 | + MemoEntry::Envelope(SharedPeaks::new(vec![(0.0, 0.0); 5])), | ||
| 746 | + ); | ||
| 747 | + assert_eq!(count, 5, "the replaced entry's buckets were not subtracted"); | ||
| 748 | + assert_eq!(memo.len(), 1, "the replace added a second entry"); | ||
| 749 | + } | ||
| 535 | } | 750 | } |