A film's visualizer reads a window of its envelope, not the whole file
Browse files at this commit0cf7335bda931705260baf3e597203ce0cc72b6bParent: 19dcc3e- perf
- a film's visualizer reads a window of its envelope, not the whole file
2 changed files +930 -79
- crates/engine/src/decode.rs +113 -22
- crates/engine/src/waveform.rs +817 -57
crates/engine/src/decode.rsmodified+113 -22
| @@ -656,16 +656,18 @@ impl DecodeSession { | ||
| 656 | 656 | let handle = thread::Builder::new() |
| 657 | 657 | .name("viz".into()) |
| 658 | 658 | .spawn(move || { |
| 659 | - // The one decode this seat ever does: the whole envelope, | |
| 660 | - // off the render thread, and abandoned at once if the caller | |
| 661 | - // is already gone. A file that will not open -- and one with | |
| 662 | - // no track at all -- paints the flat line, which is what its | |
| 663 | - // silence looks like anyway: a visualizer frame always | |
| 664 | - // exists, and is never worth failing a span over. | |
| 665 | - let peaks = crate::waveform::peaks_shared(&path, stream, VIZ_BUCKETS_PER_SEC) | |
| 666 | - .ok() | |
| 667 | - .flatten() | |
| 668 | - .unwrap_or_default(); | |
| 659 | + // The envelope this span paints from, asked for once for the | |
| 660 | + // whole span: the memo's own handle when it holds one, and | |
| 661 | + // otherwise a *window* of the file's envelope per frame -- | |
| 662 | + // which is what makes a rebuild cheap for a source whose whole | |
| 663 | + // envelope does not fit the memo at all ([`viz_envelope`]). A | |
| 664 | + // file that will not open -- and one with no track at all -- | |
| 665 | + // paints the flat line, which is what its silence looks like | |
| 666 | + // anyway: a visualizer frame always exists, and is never worth | |
| 667 | + // failing a span over. | |
| 668 | + let mut envelope = | |
| 669 | + crate::waveform::viz_envelope(&path, stream, VIZ_BUCKETS_PER_SEC) | |
| 670 | + .unwrap_or(crate::waveform::VizEnvelope::Silent); | |
| 669 | 671 | if worker_cancel.load(Ordering::Relaxed) { |
| 670 | 672 | return; |
| 671 | 673 | } |
| @@ -688,8 +690,14 @@ impl DecodeSession { | ||
| 688 | 690 | return; |
| 689 | 691 | } |
| 690 | 692 | let t = f64::from(start_frame + index) / fps; |
| 691 | - let (y, u, v) = | |
| 692 | - visualizer_i420(&mut scratch, &peaks, t, width, height, flags, paint); | |
| 693 | + // One window of the envelope about this frame's own time: | |
| 694 | + // the same window for every frame a sliding paint asks of | |
| 695 | + // the same thirty seconds, and no decode at all for the | |
| 696 | + // rebuilds of a look edit. | |
| 697 | + let view = envelope.view_at(t); | |
| 698 | + let (y, u, v) = visualizer_window_i420( | |
| 699 | + &mut scratch, &view, t, width, height, flags, paint, | |
| 700 | + ); | |
| 693 | 701 | let frame = render.frame(start_frame + index, &y, &u, &v, width, height); |
| 694 | 702 | if tx.send(frame).is_err() { |
| 695 | 703 | return; // caller moved on |
| @@ -2102,6 +2110,10 @@ fn viz_chain( | ||
| 2102 | 2110 | /// [`viz_style`]: a bipolar sample trace (Audacity), a filled min/max |
| 2103 | 2111 | /// envelope at pixel resolution, or a multi-strand ribbon. Ink is |
| 2104 | 2112 | /// [`viz_ink_from_paint`]. A frame always exists; silence is the zero line. |
| 2113 | +/// | |
| 2114 | +/// This is the whole-envelope entry: it is handed the file's envelope and | |
| 2115 | +/// paints from it ([`VizView::whole`]). The seat paints from a *window* of one | |
| 2116 | +/// instead ([`visualizer_window_i420`], [`crate::waveform::viz_envelope`]). | |
| 2105 | 2117 | pub(crate) fn visualizer_i420( |
| 2106 | 2118 | scratch: &mut VizScratch, |
| 2107 | 2119 | peaks: &[(f32, f32)], |
| @@ -2110,6 +2122,80 @@ pub(crate) fn visualizer_i420( | ||
| 2110 | 2122 | height: u32, |
| 2111 | 2123 | flags: u8, |
| 2112 | 2124 | paint: u64, |
| 2125 | +) -> (Vec<u8>, Vec<u8>, Vec<u8>) { | |
| 2126 | + visualizer_window_i420(scratch, &VizView::whole(peaks), t_secs, width, height, flags, paint) | |
| 2127 | +} | |
| 2128 | + | |
| 2129 | +/// The envelope a visualizer frame is painted from: the whole file, or one | |
| 2130 | +/// *window* of it -- which is what the seat holds, because a film's own | |
| 2131 | +/// envelope is past the memo's ceiling ([`crate::waveform::viz_envelope`]). | |
| 2132 | +/// | |
| 2133 | +/// `peaks[i]` is the bucket at absolute index `first + i`, so the painter's | |
| 2134 | +/// index arithmetic is the same whether it was handed a slice of thirty | |
| 2135 | +/// seconds or of two hours. `total` is the *file's* own bucket count, which is | |
| 2136 | +/// what "past the end of the file" is measured against -- a window that | |
| 2137 | +/// measured it against itself would draw the file's end wherever the window | |
| 2138 | +/// ended -- and `peak` is the file's loudest bucket, which every column is | |
| 2139 | +/// scaled by: no window can derive that from itself. | |
| 2140 | +pub(crate) struct VizView<'a> { | |
| 2141 | + pub(crate) peaks: &'a [(f32, f32)], | |
| 2142 | + pub(crate) first: usize, | |
| 2143 | + pub(crate) total: usize, | |
| 2144 | + pub(crate) peak: f32, | |
| 2145 | +} | |
| 2146 | + | |
| 2147 | +impl<'a> VizView<'a> { | |
| 2148 | + /// The whole envelope, which is what every caller but the seat has. | |
| 2149 | + pub(crate) fn whole(peaks: &'a [(f32, f32)]) -> Self { | |
| 2150 | + Self { | |
| 2151 | + peaks, | |
| 2152 | + first: 0, | |
| 2153 | + total: peaks.len(), | |
| 2154 | + peak: crate::waveform::peak_of(peaks), | |
| 2155 | + } | |
| 2156 | + } | |
| 2157 | + | |
| 2158 | + /// One window of an envelope: `peaks` starts at absolute bucket `first`, | |
| 2159 | + /// `total` and `peak` are the whole file's. | |
| 2160 | + pub(crate) fn window( | |
| 2161 | + peaks: &'a [(f32, f32)], | |
| 2162 | + first: usize, | |
| 2163 | + total: usize, | |
| 2164 | + peak: f32, | |
| 2165 | + ) -> Self { | |
| 2166 | + Self { | |
| 2167 | + peaks, | |
| 2168 | + first, | |
| 2169 | + total, | |
| 2170 | + peak, | |
| 2171 | + } | |
| 2172 | + } | |
| 2173 | + | |
| 2174 | + /// The bucket at absolute index `abs`, when this view carries it: the | |
| 2175 | + /// window's own edges are not the file's, and a frame asked for one of | |
| 2176 | + /// them draws silence rather than a bucket that is only half decoded. | |
| 2177 | + pub(crate) fn at(&self, abs: usize) -> Option<(f32, f32)> { | |
| 2178 | + abs.checked_sub(self.first) | |
| 2179 | + .and_then(|i| self.peaks.get(i)) | |
| 2180 | + .copied() | |
| 2181 | + } | |
| 2182 | + | |
| 2183 | + fn is_empty(&self) -> bool { | |
| 2184 | + self.peaks.is_empty() | |
| 2185 | + } | |
| 2186 | +} | |
| 2187 | + | |
| 2188 | +/// [`visualizer_i420`] from a view, which is how the seat paints: `peaks` may | |
| 2189 | +/// be a window rather than the file's own envelope, and `t_secs` is the | |
| 2190 | +/// frame's own time either way -- the view knows where its slice starts. | |
| 2191 | +pub(crate) fn visualizer_window_i420( | |
| 2192 | + scratch: &mut VizScratch, | |
| 2193 | + view: &VizView, | |
| 2194 | + t_secs: f64, | |
| 2195 | + width: u32, | |
| 2196 | + height: u32, | |
| 2197 | + flags: u8, | |
| 2198 | + paint: u64, | |
| 2113 | 2199 | ) -> (Vec<u8>, Vec<u8>, Vec<u8>) { |
| 2114 | 2200 | let width = width & !1; |
| 2115 | 2201 | let height = height & !1; |
| @@ -2136,8 +2222,8 @@ pub(crate) fn visualizer_i420( | ||
| 2136 | 2222 | scratch.hi.resize(w, 0.0); |
| 2137 | 2223 | scratch.sig.clear(); |
| 2138 | 2224 | scratch.sig.resize(w, 0.0); |
| 2139 | - if !peaks.is_empty() { | |
| 2140 | - let duration = peaks.len() as f64 / f64::from(VIZ_BUCKETS_PER_SEC); | |
| 2225 | + if !view.is_empty() && view.total != 0 { | |
| 2226 | + let duration = view.total as f64 / f64::from(VIZ_BUCKETS_PER_SEC); | |
| 2141 | 2227 | let per_sec = f64::from(VIZ_BUCKETS_PER_SEC); |
| 2142 | 2228 | let window = if flags & VIZ_FAST != 0 { |
| 2143 | 2229 | VIZ_FAST_SECS |
| @@ -2153,11 +2239,17 @@ pub(crate) fn visualizer_i420( | ||
| 2153 | 2239 | if !t.is_finite() || t < 0.0 || t > duration { |
| 2154 | 2240 | return (0.0, 0.0); |
| 2155 | 2241 | } |
| 2156 | - let pos = (t * per_sec).clamp(0.0, (peaks.len() - 1) as f64); | |
| 2242 | + let pos = (t * per_sec).clamp(0.0, (view.total - 1) as f64); | |
| 2157 | 2243 | let i = pos.floor() as usize; |
| 2158 | 2244 | let f = (pos - i as f64) as f32; |
| 2159 | - let (lo0, hi0) = peaks[i]; | |
| 2160 | - let (lo1, hi1) = peaks[(i + 1).min(peaks.len() - 1)]; | |
| 2245 | + // Silence where the slice does not reach: a view that is a window | |
| 2246 | + // is only handed the buckets the frame can ask for, so this is the | |
| 2247 | + // file's own ends and nothing else. | |
| 2248 | + let (Some((lo0, hi0)), Some((lo1, hi1))) = | |
| 2249 | + (view.at(i), view.at((i + 1).min(view.total - 1))) | |
| 2250 | + else { | |
| 2251 | + return (0.0, 0.0); | |
| 2252 | + }; | |
| 2161 | 2253 | ( |
| 2162 | 2254 | (lo0 + (lo1 - lo0) * f).clamp(-1.0, 0.0), |
| 2163 | 2255 | (hi0 + (hi1 - hi0) * f).clamp(0.0, 1.0), |
| @@ -2184,11 +2276,10 @@ pub(crate) fn visualizer_i420( | ||
| 2184 | 2276 | } |
| 2185 | 2277 | // Whole-file peak, not the window's: a 2s window that gains or loses |
| 2186 | 2278 | // a loud hit used to rescale every column, so the same bump changed |
| 2187 | - // height as it entered and left the picture. | |
| 2188 | - let peak = peaks | |
| 2189 | - .iter() | |
| 2190 | - .map(|&(l, h)| l.abs().max(h.abs())) | |
| 2191 | - .fold(0.0f32, f32::max); | |
| 2279 | + // height as it entered and left the picture. A view carries that peak | |
| 2280 | + // with it ([`VizView`]), because a window of a film could not compute | |
| 2281 | + // it from the megabyte it holds. | |
| 2282 | + let peak = view.peak; | |
| 2192 | 2283 | if peak > 1e-4 { |
| 2193 | 2284 | for i in 0..w { |
| 2194 | 2285 | scratch.lo[i] /= peak; |
crates/engine/src/waveform.rsmodified+817 -57
| @@ -6,8 +6,8 @@ use std::path::{Path, PathBuf}; | ||
| 6 | 6 | use std::sync::mpsc::Receiver; |
| 7 | 7 | use std::thread; |
| 8 | 8 | |
| 9 | -use crate::AudioSession; | |
| 10 | 9 | use crate::audio::AudioChunk; |
| 10 | +use crate::AudioSession; | |
| 11 | 11 | |
| 12 | 12 | /// `(min, max)` of every sample in each `1 / buckets_per_sec` window of |
| 13 | 13 | /// `stream` of `path`'s audio, from media time 0 (priming already trimmed by |
| @@ -55,7 +55,7 @@ pub(crate) type SharedPeaks = std::sync::Arc<Vec<(f32, f32)>>; | ||
| 55 | 55 | /// The identity a memo entry is keyed by: what was asked for *and* the file it |
| 56 | 56 | /// was answered from, so a source replaced on disk is read again rather than |
| 57 | 57 | /// served the envelope of bytes that are gone. |
| 58 | -#[derive(PartialEq, Eq, Hash)] | |
| 58 | +#[derive(PartialEq, Eq, Hash, Clone)] | |
| 59 | 59 | struct PeaksKey { |
| 60 | 60 | path: PathBuf, |
| 61 | 61 | stream: usize, |
| @@ -65,6 +65,15 @@ struct PeaksKey { | ||
| 65 | 65 | } |
| 66 | 66 | |
| 67 | 67 | impl PeaksKey { |
| 68 | + /// The same identity for an ask that has nothing to do with a rate: the | |
| 69 | + /// scalars [`viz_summary`] reads off a file are its samples, not its | |
| 70 | + /// buckets, and one measuring is enough for every rate asked of it. `0` is | |
| 71 | + /// not a rate any ask can use ([`per_bucket_of`] floors it), so a summary | |
| 72 | + /// never collides with an envelope. | |
| 73 | + fn stream_of(path: &Path, stream: usize) -> Self { | |
| 74 | + Self::of(path, stream, 0) | |
| 75 | + } | |
| 76 | + | |
| 68 | 77 | fn of(path: &Path, stream: usize, buckets_per_sec: u32) -> Self { |
| 69 | 78 | let stat = std::fs::metadata(path).ok(); |
| 70 | 79 | Self { |
| @@ -122,36 +131,21 @@ impl MemoEntry { | ||
| 122 | 131 | MemoEntry::NoTrack => None, |
| 123 | 132 | } |
| 124 | 133 | } |
| 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 | } |
| 134 | 135 | |
| 135 | 136 | /// Every answer the process has been asked for, by identity. |
| 136 | 137 | type PeaksMemo = std::collections::HashMap<PeaksKey, MemoEntry>; |
| 137 | 138 | |
| 138 | 139 | /// [`peaks`] as a handle the caller can hold: the same envelope, shared rather |
| 139 | -/// than copied. | |
| 140 | +/// than copied, under a ceiling. | |
| 140 | 141 | /// |
| 141 | -/// The visualizer seat asks this of every picture rebuild it makes | |
| 142 | -/// ([`DecodeSession::open_visualizer`]): a rebuild happens once per look edit, | |
| 143 | -/// and a look edit is what a drag across the colour wheel is -- so an envelope | |
| 144 | -/// decoded per rebuild is a whole-file audio decode per pointer sample, for an | |
| 145 | -/// answer that has not changed. | |
| 146 | -/// | |
| 147 | -/// Keyed on the file's own stat ([`PeaksKey`]) and bounded by | |
| 148 | -/// [`PEAKS_MEMO_BUCKETS`] *of what it holds*: past the ceiling the memo lets | |
| 149 | -/// everything go rather than evicting one entry at a time, because the entries | |
| 150 | -/// are large and a re-decode is the honest cost of asking for more than the | |
| 151 | -/// ceiling. A single source whose own envelope is bigger than the ceiling is | |
| 152 | -/// not memoized at all (see [`peaks_shared`]), so the ceiling is one -- an | |
| 153 | -/// entry that no clear can bring the memo back under would be a memo that | |
| 154 | -/// clears on every other ask. | |
| 142 | +/// Keyed on the file's own stat ([`PeaksKey`]) and bounded by [`cap`] *of what | |
| 143 | +/// it holds*: past the ceiling the memo lets everything go rather than evicting | |
| 144 | +/// one entry at a time, because the entries are large and a re-decode is the | |
| 145 | +/// honest cost of asking for more than the ceiling. A single source whose own | |
| 146 | +/// envelope is bigger than the ceiling is not memoized at all (the caller still | |
| 147 | +/// gets its handle), so the ceiling is one -- an entry that no clear can bring | |
| 148 | +/// the memo back under would be a memo that clears on every other ask. | |
| 155 | 149 | /// |
| 156 | 150 | /// A trackless source's `Ok(None)` is kept too: it is an answer the file will |
| 157 | 151 | /// give again, and without it a visualizer clip on a silent source re-opens |
| @@ -159,17 +153,12 @@ type PeaksMemo = std::collections::HashMap<PeaksKey, MemoEntry>; | ||
| 159 | 153 | /// paid once per look edit. It holds no buckets, so it never counts against |
| 160 | 154 | /// the ceiling. A failed ask is *not* kept: a decode that failed once may fail |
| 161 | 155 | /// for a reason that has gone away, and caching it would make that permanent. |
| 162 | -pub(crate) fn peaks_shared( | |
| 163 | - path: &Path, | |
| 164 | - stream: usize, | |
| 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. | |
| 156 | +/// | |
| 157 | +/// The visualizer seat does not ask this directly any more -- it asks | |
| 158 | +/// [`viz_envelope`], which answers with this for a source the memo holds and | |
| 159 | +/// with windows of it for one it cannot. `cap` is [`PEAKS_MEMO_BUCKETS`] there; | |
| 160 | +/// a test drives it down to a handful of buckets so the over-the-ceiling path | |
| 161 | +/// is walked without an eight-million-bucket fixture. | |
| 173 | 162 | fn peaks_shared_capped( |
| 174 | 163 | path: &Path, |
| 175 | 164 | stream: usize, |
| @@ -200,6 +189,28 @@ fn peaks_shared_capped( | ||
| 200 | 189 | Ok(handle) |
| 201 | 190 | } |
| 202 | 191 | |
| 192 | +/// What a memo holds a bucket count of. Both memos below are ceilinged in | |
| 193 | +/// *buckets*, so every entry has to say how many it brings -- and one | |
| 194 | +/// arithmetic serves both rather than two that can drift apart. | |
| 195 | +trait Bucketed { | |
| 196 | + fn buckets(&self) -> usize; | |
| 197 | +} | |
| 198 | + | |
| 199 | +impl Bucketed for MemoEntry { | |
| 200 | + fn buckets(&self) -> usize { | |
| 201 | + match self { | |
| 202 | + MemoEntry::Envelope(shared) => shared.len(), | |
| 203 | + MemoEntry::NoTrack => 0, | |
| 204 | + } | |
| 205 | + } | |
| 206 | +} | |
| 207 | + | |
| 208 | +impl Bucketed for SharedPeaks { | |
| 209 | + fn buckets(&self) -> usize { | |
| 210 | + self.len() | |
| 211 | + } | |
| 212 | +} | |
| 213 | + | |
| 203 | 214 | /// Record `entry` under `key` in `memo`, keeping `count` equal to the buckets |
| 204 | 215 | /// the map holds. The arithmetic is what keeps the ceiling a ceiling: |
| 205 | 216 | /// |
| @@ -214,12 +225,12 @@ fn peaks_shared_capped( | ||
| 214 | 225 | /// missed one key each decode and insert it -- does not leave the count high |
| 215 | 226 | /// for good: only a clear resets it, and a high count makes later asks clear |
| 216 | 227 | /// early, dropping entries that then pay a whole-file decode to be rebuilt. |
| 217 | -fn memoize( | |
| 218 | - memo: &mut PeaksMemo, | |
| 228 | +fn memoize<K: std::hash::Hash + Eq, V: Bucketed>( | |
| 229 | + memo: &mut std::collections::HashMap<K, V>, | |
| 219 | 230 | count: &mut usize, |
| 220 | 231 | cap: usize, |
| 221 | - key: PeaksKey, | |
| 222 | - entry: MemoEntry, | |
| 232 | + key: K, | |
| 233 | + entry: V, | |
| 223 | 234 | ) { |
| 224 | 235 | let len = entry.buckets(); |
| 225 | 236 | if len > cap { |
| @@ -235,6 +246,510 @@ fn memoize( | ||
| 235 | 246 | *count += len; |
| 236 | 247 | } |
| 237 | 248 | |
| 249 | +/// How much sound one window of an over-the-ceiling source covers: 30 s at the | |
| 250 | +/// visualizer's 4000 buckets a second is 120k buckets, a megabyte, against the | |
| 251 | +/// 230 MB the whole of a two-hour film's envelope is. | |
| 252 | +const VIZ_WINDOW_SECS: f64 = 30.0; | |
| 253 | + | |
| 254 | +/// Decoded past each end of that window. A seek lands where it lands (a | |
| 255 | +/// standalone mp3's pre-roll is 8192 samples), so the first and last buckets of | |
| 256 | +/// a window's own decode can hold part of a bucket the neighbouring window | |
| 257 | +/// covers too; three seconds either side keeps those edges well clear of the | |
| 258 | +/// two-second window a frame actually asks for. | |
| 259 | +const VIZ_WINDOW_SEEK_SECS: f64 = 3.0; | |
| 260 | + | |
| 261 | +/// How many buckets the window memo holds before it gives them back: 4M | |
| 262 | +/// buckets is 32 MB, some thirty windows -- fifteen minutes of sound about the | |
| 263 | +/// playhead, for every source in the session together, against the eight | |
| 264 | +/// million a single film's envelope would want. Past it the map is emptied | |
| 265 | +/// rather than evicted one window at a time: the paint slides forward, so the | |
| 266 | +/// window it is in is the one worth losing last, and re-decoding it is a second | |
| 267 | +/// of sound rather than two hours. | |
| 268 | +const VIZ_WINDOW_MEMO_BUCKETS: usize = 4 << 20; | |
| 269 | + | |
| 270 | +/// The loudest bucket of an envelope: what a visualizer column is scaled by | |
| 271 | +/// ([`crate::decode::visualizer_i420`]), and therefore a property of the | |
| 272 | +/// *whole* file -- a window that derived it from itself would rescale every | |
| 273 | +/// column as it slid. | |
| 274 | +pub(crate) fn peak_of(peaks: &[(f32, f32)]) -> f32 { | |
| 275 | + peaks | |
| 276 | + .iter() | |
| 277 | + .map(|&(lo, hi)| lo.abs().max(hi.abs())) | |
| 278 | + .fold(0.0f32, f32::max) | |
| 279 | +} | |
| 280 | + | |
| 281 | +/// What a visualizer frame needs from the whole file, in two scalars: how many | |
| 282 | +/// samples it carries, and the loudest of them. Neither depends on the | |
| 283 | +/// bucketing -- a bucket is as loud as the loudest sample in it, and a sample | |
| 284 | +/// lands in the last bucket whatever that bucket is -- so both come off one | |
| 285 | +/// pass that keeps no buckets at all ([`viz_summary`]). A film's two hours at | |
| 286 | +/// 4000 buckets a second is 230 MB of pairs; this is sixteen bytes of it. | |
| 287 | +pub(crate) struct VizSummary { | |
| 288 | + /// One past the file's last sample, counted from its first audible one -- | |
| 289 | + /// the same arithmetic [`fold`] counts buckets with. | |
| 290 | + samples: u64, | |
| 291 | + /// The rate those samples were counted at, which is what turns an ask's | |
| 292 | + /// buckets-per-second into samples per bucket. Carried here because the | |
| 293 | + /// summary outlives the probe that read it. | |
| 294 | + sample_rate: u32, | |
| 295 | + /// The file's loudest sample, clamped to full scale like every bucket | |
| 296 | + /// value. | |
| 297 | + pub(crate) peak: f32, | |
| 298 | +} | |
| 299 | + | |
| 300 | +impl VizSummary { | |
| 301 | + /// The file's length in buckets of `per_bucket` samples: what | |
| 302 | + /// `peaks.len()` would have been. `fold` puts a sample in | |
| 303 | + /// `(sample / per_bucket)` truncated, so the last sample decides the last | |
| 304 | + /// bucket -- and a file with no samples has none. | |
| 305 | + fn buckets(&self, per_bucket: f64) -> usize { | |
| 306 | + if self.samples == 0 { | |
| 307 | + return 0; | |
| 308 | + } | |
| 309 | + ((self.samples - 1) as f64 / per_bucket) as usize + 1 | |
| 310 | + } | |
| 311 | +} | |
| 312 | + | |
| 313 | +/// The visualizer seat's envelope: what a picture of a clip is painted from. | |
| 314 | +/// | |
| 315 | +/// The seat is re-opened on every look edit and every seek, so the second ask | |
| 316 | +/// has to be a refcount. For a source whose whole envelope the memo holds -- a | |
| 317 | +/// song's, a short clip's -- [`peaks_shared_capped`] answers exactly that. A | |
| 318 | +/// film's is past the memo's ceiling and never held, and what the seat asks for | |
| 319 | +/// one is a *window* of it about the frame's own time, which is all a | |
| 320 | +/// two-second picture reads, plus the pass that reads the whole file's two | |
| 321 | +/// scalars once ([`VizSummary`]). | |
| 322 | +pub(crate) enum VizEnvelope { | |
| 323 | + /// No audio track -- and what the seat falls back to when the ask itself | |
| 324 | + /// fails: a frame always exists, and is never worth failing a span over. | |
| 325 | + Silent, | |
| 326 | + /// The memo holds the whole envelope: the same slice every frame, as it | |
| 327 | + /// always was. | |
| 328 | + Whole(SharedPeaks), | |
| 329 | + /// Past the ceiling: the file's two scalars, and one window of it at a time. | |
| 330 | + Windowed(VizWindows), | |
| 331 | +} | |
| 332 | + | |
| 333 | +impl VizEnvelope { | |
| 334 | + /// The envelope the frame at `t_secs` is painted from: the whole of it, or | |
| 335 | + /// the window `t_secs` falls in -- decoded once per window per process. | |
| 336 | + pub(crate) fn view_at(&mut self, t_secs: f64) -> crate::decode::VizView<'_> { | |
| 337 | + match self { | |
| 338 | + Self::Silent => crate::decode::VizView::whole(&[]), | |
| 339 | + Self::Whole(shared) => crate::decode::VizView::whole(shared.as_slice()), | |
| 340 | + Self::Windowed(windows) => windows.view_at(t_secs), | |
| 341 | + } | |
| 342 | + } | |
| 343 | +} | |
| 344 | + | |
| 345 | +/// One source's windows, and the window the paint is in. | |
| 346 | +pub(crate) struct VizWindows { | |
| 347 | + /// The ask: file, stream and rate, so a window of the same source asked at | |
| 348 | + /// two rates is two windows. | |
| 349 | + key: PeaksKey, | |
| 350 | + /// The rate the ask named, in buckets per second. The file's own rate is in | |
| 351 | + /// the summary; this and the two of them make samples per bucket, and the | |
| 352 | + /// ask is what turns a frame's time into buckets and back. | |
| 353 | + buckets_per_sec: u32, | |
| 354 | + summary: std::sync::Arc<VizSummary>, | |
| 355 | + /// The window the last frame was served from, and the window it is: a | |
| 356 | + /// sliding paint asks this thirty times a second, and only a look edit or a | |
| 357 | + /// seek ever moves it to another. | |
| 358 | + current: Option<(usize, SharedPeaks)>, | |
| 359 | +} | |
| 360 | + | |
| 361 | +impl VizWindows { | |
| 362 | + /// Samples per bucket, at the rate this seat asked for. | |
| 363 | + fn per_bucket(&self) -> f64 { | |
| 364 | + per_bucket_of(self.summary.sample_rate, self.buckets_per_sec) | |
| 365 | + } | |
| 366 | + | |
| 367 | + /// Buckets per second -- the ask's own rate. A bucket holds a fraction of a | |
| 368 | + /// sample at a rate above the file's, which is exactly why the file's own | |
| 369 | + /// rate has to be the one that divides. | |
| 370 | + fn per_sec(&self) -> f64 { | |
| 371 | + f64::from(self.buckets_per_sec.max(1)) | |
| 372 | + } | |
| 373 | + | |
| 374 | + /// The window `t_secs` falls in: a *window* of 30 s at a fixed grid, so the | |
| 375 | + /// same second of the same file is the same window whichever seat asks. | |
| 376 | + fn view_at(&mut self, t_secs: f64) -> crate::decode::VizView<'_> { | |
| 377 | + let per_sec = self.per_sec(); | |
| 378 | + let total = self.summary.buckets(self.per_bucket()); | |
| 379 | + let per_window = (VIZ_WINDOW_SECS * per_sec) as usize; | |
| 380 | + let seek = (VIZ_WINDOW_SEEK_SECS * per_sec) as usize; | |
| 381 | + let t_secs = if t_secs.is_finite() { | |
| 382 | + t_secs.max(0.0) | |
| 383 | + } else { | |
| 384 | + 0.0 | |
| 385 | + }; | |
| 386 | + let first = ((t_secs * per_sec) as usize / per_window) * per_window; | |
| 387 | + if first >= total { | |
| 388 | + // Past the end of the file -- which is where a source shorter than | |
| 389 | + // the clip playing it leaves the last frames. Nothing to decode: | |
| 390 | + // the painter measures "past the file" against `total` and draws | |
| 391 | + // silence there, exactly as it did when it held the whole envelope. | |
| 392 | + return crate::decode::VizView::window(&[], first, total, self.summary.peak); | |
| 393 | + } | |
| 394 | + if self.current.as_ref().map(|(at, _)| *at) != Some(first) { | |
| 395 | + // A window that will not open keeps the frame's own silence and is | |
| 396 | + // *not* remembered as the window: the next frame asks again, and a | |
| 397 | + // source that comes back (a share remounting, a file finishing its | |
| 398 | + // write) paints again. | |
| 399 | + let window = viz_window( | |
| 400 | + &self.key, | |
| 401 | + self.summary.sample_rate, | |
| 402 | + self.buckets_per_sec, | |
| 403 | + first, | |
| 404 | + per_window + 2 * seek, | |
| 405 | + ) | |
| 406 | + .unwrap_or_else(|_| SharedPeaks::new(Vec::new())); | |
| 407 | + self.current = Some((first, window)); | |
| 408 | + } | |
| 409 | + let (at, peaks) = self.current.as_ref().expect("just set"); | |
| 410 | + // The slice starts where the decode did, a seek margin below the | |
| 411 | + // window's own first bucket -- the same arithmetic [`viz_window`] was | |
| 412 | + // asked with, so the absolute positions line up. | |
| 413 | + let slice_first = at.saturating_sub(seek); | |
| 414 | + crate::decode::VizView::window(peaks.as_slice(), slice_first, total, self.summary.peak) | |
| 415 | + } | |
| 416 | +} | |
| 417 | + | |
| 418 | +/// A window's identity: the file it came from, and its own first bucket. | |
| 419 | +#[derive(PartialEq, Eq, Hash)] | |
| 420 | +struct WindowKey { | |
| 421 | + file: PeaksKey, | |
| 422 | + from: usize, | |
| 423 | +} | |
| 424 | + | |
| 425 | +impl WindowKey { | |
| 426 | + fn of(file: &PeaksKey, from: usize) -> Self { | |
| 427 | + Self { | |
| 428 | + file: file.clone(), | |
| 429 | + from, | |
| 430 | + } | |
| 431 | + } | |
| 432 | +} | |
| 433 | + | |
| 434 | +/// The windows every seat of this process has asked for, and how many buckets | |
| 435 | +/// they hold between them. | |
| 436 | +fn viz_windows( | |
| 437 | +) -> &'static std::sync::Mutex<(std::collections::HashMap<WindowKey, SharedPeaks>, usize)> { | |
| 438 | + static MEMO: std::sync::LazyLock< | |
| 439 | + std::sync::Mutex<(std::collections::HashMap<WindowKey, SharedPeaks>, usize)>, | |
| 440 | + > = std::sync::LazyLock::new(|| std::sync::Mutex::new((std::collections::HashMap::new(), 0))); | |
| 441 | + &MEMO | |
| 442 | +} | |
| 443 | + | |
| 444 | +/// The whole-file scalars every over-the-ceiling source has been measured for, | |
| 445 | +/// by the stream's own identity: [`VizSummary`] is sixteen bytes, so this map | |
| 446 | +/// is bounded by how many *streams* a session has asked about rather than by | |
| 447 | +/// how long they are. | |
| 448 | +fn viz_summaries( | |
| 449 | +) -> &'static std::sync::Mutex<std::collections::HashMap<PeaksKey, std::sync::Arc<VizSummary>>> { | |
| 450 | + static MEMO: std::sync::LazyLock< | |
| 451 | + std::sync::Mutex<std::collections::HashMap<PeaksKey, std::sync::Arc<VizSummary>>>, | |
| 452 | + > = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); | |
| 453 | + &MEMO | |
| 454 | +} | |
| 455 | + | |
| 456 | +/// Test-only: how many times the visualizer's own ask had to open the file -- | |
| 457 | +/// a window of an envelope, or one window of a [`viz_summary`] pass. The | |
| 458 | +/// second ask for the same window of the same source must not move it. | |
| 459 | +#[cfg(test)] | |
| 460 | +static VIZ_DECODES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); | |
| 461 | + | |
| 462 | +/// [`VIZ_DECODES`], for a test that measures a delta across its own asks. | |
| 463 | +#[cfg(test)] | |
| 464 | +fn viz_decodes() -> usize { | |
| 465 | + VIZ_DECODES.load(std::sync::atomic::Ordering::Relaxed) | |
| 466 | +} | |
| 467 | + | |
| 468 | +/// The visualizer seat's own ask: the whole envelope when the memo holds it, | |
| 469 | +/// and otherwise windows of it. Never decoded per frame either way -- the | |
| 470 | +/// per-frame cost of a look drag is what this exists to remove. | |
| 471 | +pub(crate) fn viz_envelope( | |
| 472 | + path: &Path, | |
| 473 | + stream: usize, | |
| 474 | + buckets_per_sec: u32, | |
| 475 | +) -> crate::Result<VizEnvelope> { | |
| 476 | + viz_envelope_capped(path, stream, buckets_per_sec, PEAKS_MEMO_BUCKETS) | |
| 477 | +} | |
| 478 | + | |
| 479 | +/// [`viz_envelope`] against a ceiling a test can drive down to a handful of | |
| 480 | +/// buckets, so the windowed route is walked on a five-second fixture. `cap` is | |
| 481 | +/// [`PEAKS_MEMO_BUCKETS`] everywhere but in a test. | |
| 482 | +pub(crate) fn viz_envelope_capped( | |
| 483 | + path: &Path, | |
| 484 | + stream: usize, | |
| 485 | + buckets_per_sec: u32, | |
| 486 | + cap: usize, | |
| 487 | +) -> crate::Result<VizEnvelope> { | |
| 488 | + let key = PeaksKey::of(path, stream, buckets_per_sec); | |
| 489 | + // An answer the memo already holds ends it, without opening anything: a | |
| 490 | + // song's whole envelope, or the stable "no audio track" a silent source | |
| 491 | + // gives. | |
| 492 | + match peaks_memo().lock().unwrap().0.get(&key) { | |
| 493 | + Some(MemoEntry::Envelope(shared)) => { | |
| 494 | + return Ok(VizEnvelope::Whole(SharedPeaks::clone(shared))) | |
| 495 | + } | |
| 496 | + Some(MemoEntry::NoTrack) => return Ok(VizEnvelope::Silent), | |
| 497 | + None => {} | |
| 498 | + } | |
| 499 | + // A source this process has already measured past the ceiling: the summary | |
| 500 | + // is the answer, and it costs an open to have asked for one. | |
| 501 | + let stream_key = PeaksKey::stream_of(path, stream); | |
| 502 | + if let Some(summary) = viz_summaries().lock().unwrap().get(&stream_key) { | |
| 503 | + let summary = std::sync::Arc::clone(summary); | |
| 504 | + return Ok(VizEnvelope::Windowed(VizWindows { | |
| 505 | + key, | |
| 506 | + buckets_per_sec, | |
| 507 | + summary, | |
| 508 | + current: None, | |
| 509 | + })); | |
| 510 | + } | |
| 511 | + // A miss, so the file has to be looked at once. The container's own word | |
| 512 | + // for its length decides which ask this is, before anything is decoded: | |
| 513 | + // what the memo can hold is asked for exactly as it always was, and only | |
| 514 | + // what it cannot is served in windows. | |
| 515 | + let Some((meta, rx)) = open_window(path, stream, 0.0, f64::INFINITY)? else { | |
| 516 | + let mut guard = peaks_memo().lock().unwrap(); | |
| 517 | + let (memo, count) = &mut *guard; | |
| 518 | + memoize(memo, count, cap, key, MemoEntry::NoTrack); | |
| 519 | + return Ok(VizEnvelope::Silent); | |
| 520 | + }; | |
| 521 | + let per_bucket = per_bucket_of(meta.sample_rate, buckets_per_sec); | |
| 522 | + let fits = match meta.total_samples { | |
| 523 | + // The stated length is the container's, which is a lower bound on what | |
| 524 | + // the decode finds (a tail past it is still drawn), so a file near the | |
| 525 | + // ceiling can turn out larger. The windowed route below catches that. | |
| 526 | + Some(samples) => (samples as f64 / per_bucket) as usize + 1 <= cap, | |
| 527 | + // A length the container does not state cannot be windowed -- neither | |
| 528 | + // by this ask nor by the split inside it. Read exactly as it always | |
| 529 | + // was, and held when it fits. | |
| 530 | + None => true, | |
| 531 | + }; | |
| 532 | + if fits { | |
| 533 | + // The receiver the probe opened is dropped here: the whole-file ask | |
| 534 | + // opens its own, which is the only ask this path has ever made. | |
| 535 | + drop(rx); | |
| 536 | + let answer = peaks_shared_capped(path, stream, buckets_per_sec, cap)?; | |
| 537 | + return Ok(match answer { | |
| 538 | + None => VizEnvelope::Silent, | |
| 539 | + Some(shared) if shared.len() > cap => { | |
| 540 | + // The container understated its length, so this ask paid for a | |
| 541 | + // whole envelope it cannot keep. Measure the file off it -- | |
| 542 | + // both scalars are exact here -- and hand the seat windows of | |
| 543 | + // it instead, so the *next* rebuild is the cheap one. | |
| 544 | + let summary = std::sync::Arc::new(VizSummary { | |
| 545 | + samples: (shared.len() as f64 * per_bucket) as u64, | |
| 546 | + sample_rate: meta.sample_rate, | |
| 547 | + peak: peak_of(&shared), | |
| 548 | + }); | |
| 549 | + viz_summaries() | |
| 550 | + .lock() | |
| 551 | + .unwrap() | |
| 552 | + .insert(stream_key, summary.clone()); | |
| 553 | + VizEnvelope::Windowed(VizWindows { | |
| 554 | + key, | |
| 555 | + buckets_per_sec, | |
| 556 | + summary, | |
| 557 | + current: None, | |
| 558 | + }) | |
| 559 | + } | |
| 560 | + Some(shared) => VizEnvelope::Whole(shared), | |
| 561 | + }); | |
| 562 | + } | |
| 563 | + // Past the ceiling: the file's two scalars off the probe's own window and | |
| 564 | + // its neighbours, then a window of it per painted frame. | |
| 565 | + let summary = viz_summary(path, stream, &meta, rx)?; | |
| 566 | + Ok(VizEnvelope::Windowed(VizWindows { | |
| 567 | + key, | |
| 568 | + buckets_per_sec, | |
| 569 | + summary, | |
| 570 | + current: None, | |
| 571 | + })) | |
| 572 | +} | |
| 573 | + | |
| 574 | +/// The two scalars of [`VizSummary`], read off one pass that keeps no buckets. | |
| 575 | +/// | |
| 576 | +/// The same windows, the same threads and the same opens [`peaks_over`] decodes | |
| 577 | +/// a whole envelope with -- `rx` is that ask's own first window, the probe's -- | |
| 578 | +/// because the peak has to be the peak of the envelope the memo would have | |
| 579 | +/// held: a frame scaled by any other number is a different picture. A stop | |
| 580 | +/// sample would be the one way to lose a bucket the envelope has (and, with it, | |
| 581 | +/// the loudest sample in the file), so there are none here: what the windows | |
| 582 | +/// fold between them is everything the file delivers. | |
| 583 | +fn viz_summary( | |
| 584 | + path: &Path, | |
| 585 | + stream: usize, | |
| 586 | + meta: &crate::AudioMeta, | |
| 587 | + rx: Receiver<AudioChunk>, | |
| 588 | +) -> crate::Result<std::sync::Arc<VizSummary>> { | |
| 589 | + let key = PeaksKey::stream_of(path, stream); | |
| 590 | + if let Some(hit) = viz_summaries().lock().unwrap().get(&key) { | |
| 591 | + return Ok(std::sync::Arc::clone(hit)); | |
| 592 | + } | |
| 593 | + let rate = f64::from(meta.sample_rate.max(1)); | |
| 594 | + let channels = (meta.channels as usize).max(1); | |
| 595 | + let secs = meta.total_samples.unwrap_or(0) as f64 / rate; | |
| 596 | + let jobs = jobs_for(secs).max(1); | |
| 597 | + let window = secs / jobs as f64; | |
| 598 | + let rest: Vec<_> = (1..jobs) | |
| 599 | + .map(|k| { | |
| 600 | + let path = path.to_path_buf(); | |
| 601 | + let start = window * k as f64; | |
| 602 | + let end = match k + 1 == jobs { | |
| 603 | + true => f64::INFINITY, | |
| 604 | + false => window * (k + 1) as f64, | |
| 605 | + }; | |
| 606 | + #[cfg(test)] | |
| 607 | + VIZ_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | |
| 608 | + thread::Builder::new().name("waveform".into()).spawn( | |
| 609 | + move || -> crate::Result<(f32, u64)> { | |
| 610 | + match open_window(&path, stream, start, end)? { | |
| 611 | + Some((window_meta, window_rx)) => Ok(fold_summary( | |
| 612 | + window_rx, | |
| 613 | + u64::MAX, | |
| 614 | + (window_meta.channels as usize).max(1), | |
| 615 | + )), | |
| 616 | + None => Ok((0.0, 0)), | |
| 617 | + } | |
| 618 | + }, | |
| 619 | + ) | |
| 620 | + }) | |
| 621 | + .collect::<Result<_, _>>()?; | |
| 622 | + #[cfg(test)] | |
| 623 | + VIZ_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | |
| 624 | + // Every window folds everything it is handed, the first one included: no | |
| 625 | + // stop sample, because a stop that dropped a window's own tail could drop | |
| 626 | + // the loudest sample in the file with it -- and the peak a visualizer frame | |
| 627 | + // is scaled by is the one thing here that has to be the envelope's own. | |
| 628 | + let (mut peak, mut samples) = fold_summary(rx, u64::MAX, channels); | |
| 629 | + for handle in rest { | |
| 630 | + let (part_peak, part_samples) = handle.join().map_err(|_| "waveform worker panicked")??; | |
| 631 | + peak = peak.max(part_peak); | |
| 632 | + samples = samples.max(part_samples); | |
| 633 | + } | |
| 634 | + let summary = std::sync::Arc::new(VizSummary { | |
| 635 | + samples, | |
| 636 | + sample_rate: meta.sample_rate, | |
| 637 | + peak, | |
| 638 | + }); | |
| 639 | + viz_summaries() | |
| 640 | + .lock() | |
| 641 | + .unwrap() | |
| 642 | + .insert(key, std::sync::Arc::clone(&summary)); | |
| 643 | + Ok(summary) | |
| 644 | +} | |
| 645 | + | |
| 646 | +/// One window of one file's envelope, decoded and kept. A window is what the | |
| 647 | +/// memo can hold of a film: thirty seconds of sound about the frame's own time, | |
| 648 | +/// so the look edit that re-opens the seat decodes a window rather than the | |
| 649 | +/// file, and the *second* edit reads the one the first left. | |
| 650 | +fn viz_window( | |
| 651 | + key: &PeaksKey, | |
| 652 | + sample_rate: u32, | |
| 653 | + buckets_per_sec: u32, | |
| 654 | + from: usize, | |
| 655 | + buckets: usize, | |
| 656 | +) -> crate::Result<SharedPeaks> { | |
| 657 | + let memo_key = WindowKey::of(key, from); | |
| 658 | + if let Some(hit) = viz_windows().lock().unwrap().0.get(&memo_key) { | |
| 659 | + return Ok(SharedPeaks::clone(hit)); | |
| 660 | + } | |
| 661 | + #[cfg(test)] | |
| 662 | + VIZ_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed); | |
| 663 | + // Both units, from the two rates: `per_bucket` is what the fold counts | |
| 664 | + // samples in, `per_sec` is what a window's own ends are named in -- and a | |
| 665 | + // bucket is a fraction of a *second* over the ask's rate, never of a sample, | |
| 666 | + // whatever either rate is. | |
| 667 | + let per_bucket = per_bucket_of(sample_rate, buckets_per_sec); | |
| 668 | + let per_sec = f64::from(buckets_per_sec.max(1)); | |
| 669 | + let start = from as f64 / per_sec; | |
| 670 | + let end = (from + buckets) as f64 / per_sec; | |
| 671 | + let Some((meta, rx)) = open_window(&key.path, key.stream, start, end)? else { | |
| 672 | + // The track the probe found is gone (the file changed under the key): | |
| 673 | + // an empty window, which paints its own stretch of the flat line. | |
| 674 | + return Ok(SharedPeaks::new(Vec::new())); | |
| 675 | + }; | |
| 676 | + let channels = (meta.channels as usize).max(1); | |
| 677 | + let peaks = SharedPeaks::new(fold_window(rx, per_bucket, channels, from)); | |
| 678 | + let mut guard = viz_windows().lock().unwrap(); | |
| 679 | + let (memo, count) = &mut *guard; | |
| 680 | + // The ceiling arithmetic is [`memoize`]'s, on a map whose entries are | |
| 681 | + // windows: an entry bigger than the ceiling is handed back but not held, | |
| 682 | + // and one that replaces another subtracts what it replaced. | |
| 683 | + memoize( | |
| 684 | + memo, | |
| 685 | + count, | |
| 686 | + VIZ_WINDOW_MEMO_BUCKETS, | |
| 687 | + memo_key, | |
| 688 | + SharedPeaks::clone(&peaks), | |
| 689 | + ); | |
| 690 | + Ok(peaks) | |
| 691 | +} | |
| 692 | + | |
| 693 | +/// Min/max per bucket of everything `rx` carries, from `from` on: the window's | |
| 694 | +/// own first bucket is `from`, and anything the decoder hands over before it -- | |
| 695 | +/// a seek lands where it lands -- is dropped rather than folded at an index the | |
| 696 | +/// window does not have. The *last* bucket is partial too, which is what the | |
| 697 | +/// seek margin in [`viz_window`] is for. | |
| 698 | +fn fold_window( | |
| 699 | + rx: Receiver<AudioChunk>, | |
| 700 | + per_bucket: f64, | |
| 701 | + channels: usize, | |
| 702 | + from: usize, | |
| 703 | +) -> Vec<(f32, f32)> { | |
| 704 | + let mut peaks: Vec<(f32, f32)> = Vec::new(); | |
| 705 | + for chunk in rx { | |
| 706 | + for (frame, values) in chunk.samples.chunks(channels).enumerate() { | |
| 707 | + let bucket = ((chunk.start_sample + frame as u64) as f64 / per_bucket) as usize; | |
| 708 | + if bucket < from { | |
| 709 | + continue; | |
| 710 | + } | |
| 711 | + let i = bucket - from; | |
| 712 | + if i >= peaks.len() { | |
| 713 | + peaks.resize(i + 1, (0.0, 0.0)); | |
| 714 | + } | |
| 715 | + let slot = &mut peaks[i]; | |
| 716 | + for &v in values { | |
| 717 | + let v = v.clamp(-1.0, 1.0); | |
| 718 | + slot.0 = slot.0.min(v); | |
| 719 | + slot.1 = slot.1.max(v); | |
| 720 | + } | |
| 721 | + } | |
| 722 | + } | |
| 723 | + peaks | |
| 724 | +} | |
| 725 | + | |
| 726 | +/// [`fold`]'s two answers without its buckets: the loudest sample the window | |
| 727 | +/// carries, and how far the file it came from runs. Clamped and counted | |
| 728 | +/// exactly as `fold` clamps and counts them, so the peak of a whole-file pass | |
| 729 | +/// is the peak of the whole-file envelope. | |
| 730 | +fn fold_summary(rx: Receiver<AudioChunk>, stop_sample: u64, channels: usize) -> (f32, u64) { | |
| 731 | + let (mut peak, mut samples) = (0.0f32, 0u64); | |
| 732 | + for chunk in rx { | |
| 733 | + if chunk.start_sample >= stop_sample { | |
| 734 | + break; | |
| 735 | + } | |
| 736 | + samples = samples.max(chunk.start_sample + (chunk.samples.len() / channels) as u64); | |
| 737 | + for &v in &chunk.samples { | |
| 738 | + peak = peak.max(v.clamp(-1.0, 1.0).abs()); | |
| 739 | + } | |
| 740 | + } | |
| 741 | + (peak, samples) | |
| 742 | +} | |
| 743 | + | |
| 744 | +/// Samples per bucket. Guarded at one both ways, because a container that does | |
| 745 | +/// not state a rate (or states a zero one) would otherwise make this zero, | |
| 746 | +/// every sample would land in bucket `usize::MAX`, and the fold's own | |
| 747 | +/// `resize(bucket + 1)` would be a length that does not exist. One keeps the | |
| 748 | +/// fold total, and `buckets_per_sec` is floored where it is asked for as well. | |
| 749 | +fn per_bucket_of(sample_rate: u32, buckets_per_sec: u32) -> f64 { | |
| 750 | + f64::from(sample_rate.max(1)) / f64::from(buckets_per_sec.max(1)) | |
| 751 | +} | |
| 752 | + | |
| 238 | 753 | /// [`peaks`] with the split forced to `jobs` windows, which is how a test asks |
| 239 | 754 | /// for the same envelope by both routes. |
| 240 | 755 | fn peaks_over( |
| @@ -248,7 +763,7 @@ fn peaks_over( | ||
| 248 | 763 | }; |
| 249 | 764 | // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a |
| 250 | 765 | // bucket every few seconds over a long source. |
| 251 | - let per_bucket = f64::from(meta.sample_rate) / f64::from(buckets_per_sec.max(1)); | |
| 766 | + let per_bucket = per_bucket_of(meta.sample_rate, buckets_per_sec); | |
| 252 | 767 | let channels = (meta.channels as usize).max(1); |
| 253 | 768 | let rate = f64::from(meta.sample_rate.max(1)); |
| 254 | 769 | // A track whose length the container does not state cannot be cut into |
| @@ -274,14 +789,14 @@ fn peaks_over( | ||
| 274 | 789 | true => f64::INFINITY, |
| 275 | 790 | false => window * (k + 1) as f64, |
| 276 | 791 | }; |
| 277 | - thread::Builder::new() | |
| 278 | - .name("waveform".into()) | |
| 279 | - .spawn(move || -> crate::Result<Vec<(f32, f32)>> { | |
| 792 | + thread::Builder::new().name("waveform".into()).spawn( | |
| 793 | + move || -> crate::Result<Vec<(f32, f32)>> { | |
| 280 | 794 | match open_window(&path, stream, start, end)? { |
| 281 | 795 | Some((_, rx)) => Ok(fold(rx, per_bucket, channels, u64::MAX)), |
| 282 | 796 | None => Ok(Vec::new()), |
| 283 | 797 | } |
| 284 | - }) | |
| 798 | + }, | |
| 799 | + ) | |
| 285 | 800 | }) |
| 286 | 801 | .collect::<Result<_, _>>()?; |
| 287 | 802 | // This window ends where the next one's decoder was told to start, by the |
| @@ -311,7 +826,10 @@ fn jobs_for(secs: f64) -> usize { | ||
| 311 | 826 | return 1; |
| 312 | 827 | } |
| 313 | 828 | let cores = thread::available_parallelism().map_or(1, |n| n.get()); |
| 314 | - ((secs / PER_JOB_SECS) as usize).min(cores).min(CEILING).max(1) | |
| 829 | + ((secs / PER_JOB_SECS) as usize) | |
| 830 | + .min(cores) | |
| 831 | + .min(CEILING) | |
| 832 | + .max(1) | |
| 315 | 833 | } |
| 316 | 834 | |
| 317 | 835 | /// `part` folded into `peaks` bucket for bucket. Both are indexed absolutely, |
| @@ -375,12 +893,23 @@ mod tests { | ||
| 375 | 893 | use std::path::PathBuf; |
| 376 | 894 | |
| 377 | 895 | use super::{ |
| 378 | - memo_decodes, memoize, peaks, peaks_over, peaks_shared, peaks_shared_capped, MemoEntry, | |
| 379 | - PeaksKey, PeaksMemo, SharedPeaks, | |
| 896 | + memo_decodes, memoize, peak_of, peaks, peaks_over, peaks_shared_capped, viz_decodes, | |
| 897 | + viz_envelope, viz_envelope_capped, MemoEntry, PeaksKey, PeaksMemo, SharedPeaks, | |
| 898 | + PEAKS_MEMO_BUCKETS, | |
| 380 | 899 | }; |
| 381 | 900 | |
| 382 | 901 | const BPS: u32 = 10; |
| 383 | 902 | |
| 903 | + /// The memo's own ask, as the seat's used to be: a ceiling a test does not | |
| 904 | + /// want to think about is the process's. | |
| 905 | + fn peaks_shared( | |
| 906 | + path: &std::path::Path, | |
| 907 | + stream: usize, | |
| 908 | + buckets_per_sec: u32, | |
| 909 | + ) -> crate::Result<Option<SharedPeaks>> { | |
| 910 | + peaks_shared_capped(path, stream, buckets_per_sec, PEAKS_MEMO_BUCKETS) | |
| 911 | + } | |
| 912 | + | |
| 384 | 913 | fn asset(name: &str) -> PathBuf { |
| 385 | 914 | PathBuf::from(env!("CARGO_MANIFEST_DIR")) |
| 386 | 915 | .join("../../assets") |
| @@ -529,11 +1058,9 @@ mod tests { | ||
| 529 | 1058 | |
| 530 | 1059 | #[test] |
| 531 | 1060 | fn video_only_source_has_no_peaks() { |
| 532 | - assert!( | |
| 533 | - peaks(asset("test_baseline.mp4"), 0, BPS) | |
| 534 | - .expect("open") | |
| 535 | - .is_none() | |
| 536 | - ); | |
| 1061 | + assert!(peaks(asset("test_baseline.mp4"), 0, BPS) | |
| 1062 | + .expect("open") | |
| 1063 | + .is_none()); | |
| 537 | 1064 | } |
| 538 | 1065 | |
| 539 | 1066 | /// Two streams of one file are two envelopes: the lane draws what the clip |
| @@ -553,7 +1080,9 @@ mod tests { | ||
| 553 | 1080 | assert_ne!(zero[0], one[0], "...and they differ from the first bucket"); |
| 554 | 1081 | // Stream 2 is AC-3, and it decodes now: it draws its own envelope like |
| 555 | 1082 | // any other stream rather than being refused. |
| 556 | - let two = peaks(&multi, 2, BPS).expect("AC-3 opens").expect("stream 2"); | |
| 1083 | + let two = peaks(&multi, 2, BPS) | |
| 1084 | + .expect("AC-3 opens") | |
| 1085 | + .expect("stream 2"); | |
| 557 | 1086 | assert!(!two.is_empty(), "the AC-3 stream drew nothing"); |
| 558 | 1087 | } |
| 559 | 1088 | |
| @@ -593,7 +1122,8 @@ mod tests { | ||
| 593 | 1122 | /// read-only for every other test in this binary. |
| 594 | 1123 | #[test] |
| 595 | 1124 | fn a_replaced_source_is_read_again() { |
| 596 | - let path = std::env::temp_dir().join(format!("edith-peaks-memo-{}.mp4", std::process::id())); | |
| 1125 | + let path = | |
| 1126 | + std::env::temp_dir().join(format!("edith-peaks-memo-{}.mp4", std::process::id())); | |
| 597 | 1127 | let short = std::fs::read(asset("test_multiaudio.mp4")).expect("read the fixture"); |
| 598 | 1128 | let long = std::fs::read(asset("test_av.mp4")).expect("read the fixture"); |
| 599 | 1129 | // The two halves below are the length half and the clock half of the |
| @@ -603,14 +1133,20 @@ mod tests { | ||
| 603 | 1133 | std::fs::write(&path, &short).expect("write the copy"); |
| 604 | 1134 | let first = peaks_shared(&path, 0, BPS).expect("open").expect("copy"); |
| 605 | 1135 | let again = peaks_shared(&path, 0, BPS).expect("open").expect("copy"); |
| 606 | - assert!(std::sync::Arc::ptr_eq(&first, &again), "the copy was not memoized"); | |
| 1136 | + assert!( | |
| 1137 | + std::sync::Arc::ptr_eq(&first, &again), | |
| 1138 | + "the copy was not memoized" | |
| 1139 | + ); | |
| 607 | 1140 | |
| 608 | 1141 | // Other bytes behind the same path. A key without the file's length |
| 609 | 1142 | // (or without any stat at all) serves `first` here -- the envelope of |
| 610 | 1143 | // bytes that are gone. |
| 611 | 1144 | std::fs::write(&path, &long).expect("rewrite the copy"); |
| 612 | 1145 | let replaced = peaks_shared(&path, 0, BPS).expect("open").expect("copy"); |
| 613 | - assert_ne!(*replaced, *first, "the memo served the replaced file's envelope"); | |
| 1146 | + assert_ne!( | |
| 1147 | + *replaced, *first, | |
| 1148 | + "the memo served the replaced file's envelope" | |
| 1149 | + ); | |
| 614 | 1150 | assert_eq!( |
| 615 | 1151 | *replaced, |
| 616 | 1152 | peaks(&path, 0, BPS).expect("open").expect("copy"), |
| @@ -747,4 +1283,228 @@ mod tests { | ||
| 747 | 1283 | assert_eq!(count, 5, "the replaced entry's buckets were not subtracted"); |
| 748 | 1284 | assert_eq!(memo.len(), 1, "the replace added a second entry"); |
| 749 | 1285 | } |
| 1286 | + | |
| 1287 | + /// A container that states no sample rate (or a zero one) must not make the | |
| 1288 | + /// samples-per-bucket arithmetic zero: `sample / 0.0` is infinite, `as | |
| 1289 | + /// usize` saturates, and the fold's own `resize(bucket + 1)` is then a | |
| 1290 | + /// length that does not exist -- a panic in debug, a wrap and an | |
| 1291 | + /// out-of-bounds index in release. Both asks that bucket samples share the | |
| 1292 | + /// guard, so this is the one arithmetic they both use. | |
| 1293 | + #[test] | |
| 1294 | + fn a_zero_sample_rate_still_buckets_samples() { | |
| 1295 | + // A rate of zero is read as one, and the rate is what divides either | |
| 1296 | + // way, so the arithmetic stays finite and positive. | |
| 1297 | + assert_eq!(super::per_bucket_of(0, 4000), 1.0 / 4000.0); | |
| 1298 | + assert_eq!(super::per_bucket_of(44100, 0), 44100.0); | |
| 1299 | + // ...and a fold over a chunk at that rate is total: one bucket per | |
| 1300 | + // sample rather than an index that does not exist. | |
| 1301 | + let per_bucket = super::per_bucket_of(0, 1); | |
| 1302 | + assert_eq!(per_bucket, 1.0); | |
| 1303 | + let (tx, rx) = std::sync::mpsc::channel(); | |
| 1304 | + tx.send(crate::audio::AudioChunk { | |
| 1305 | + start_sample: 0, | |
| 1306 | + samples: vec![0.5; 4], | |
| 1307 | + }) | |
| 1308 | + .expect("send"); | |
| 1309 | + drop(tx); | |
| 1310 | + let peaks = super::fold(rx, per_bucket, 1, u64::MAX); | |
| 1311 | + assert_eq!(peaks.len(), 4, "the fold lost or invented buckets"); | |
| 1312 | + assert_eq!(peaks[0], (0.0, 0.5), "a bucket must still straddle zero"); | |
| 1313 | + } | |
| 1314 | + | |
| 1315 | + /// The visualizer's ask for a source past the memo's ceiling: the first ask | |
| 1316 | + /// pays one pass for the file's two scalars and one window of it, and every | |
| 1317 | + /// ask after that -- the ones a look drag makes, once per pointer sample at | |
| 1318 | + /// the same playhead -- decodes nothing at all. Driven with a ceiling of ten | |
| 1319 | + /// buckets against a five-second source (fifty buckets), which is the same | |
| 1320 | + /// route the eight-million-bucket ceiling takes for a film. | |
| 1321 | + #[test] | |
| 1322 | + fn a_window_of_an_over_the_ceiling_source_is_decoded_once() { | |
| 1323 | + let file = copy_of("test_av.mp4", "window"); | |
| 1324 | + let plain = peaks(&file, 0, BPS).expect("open").expect("audio track"); | |
| 1325 | + | |
| 1326 | + let before = viz_decodes(); | |
| 1327 | + let mut first = viz_envelope_capped(&file, 0, BPS, 10).expect("open"); | |
| 1328 | + assert!( | |
| 1329 | + matches!(first, super::VizEnvelope::Windowed(_)), | |
| 1330 | + "the fixture must be past the test ceiling" | |
| 1331 | + ); | |
| 1332 | + let view = first.view_at(2.5); | |
| 1333 | + assert!(!view.peaks.is_empty(), "the window decoded nothing"); | |
| 1334 | + // The two scalars are the file's own and not an approximation of them: | |
| 1335 | + // the painter's whole-file peak and its "past the end of the file" both | |
| 1336 | + // come from here, and a frame scaled by anything else is another frame. | |
| 1337 | + assert_eq!( | |
| 1338 | + view.peak, | |
| 1339 | + peak_of(&plain), | |
| 1340 | + "the window's peak is not the file's" | |
| 1341 | + ); | |
| 1342 | + assert_eq!( | |
| 1343 | + view.total, | |
| 1344 | + plain.len(), | |
| 1345 | + "the windowed length is not the envelope's" | |
| 1346 | + ); | |
| 1347 | + let after_first = viz_decodes(); | |
| 1348 | + assert!(after_first > before, "the first ask decoded nothing"); | |
| 1349 | + | |
| 1350 | + // The same second, three more times, the way a drag asks it: a new seat | |
| 1351 | + // every time, and no decode in any of them. | |
| 1352 | + for ask in 0..3 { | |
| 1353 | + let mut again = viz_envelope_capped(&file, 0, BPS, 10).expect("open"); | |
| 1354 | + let view = again.view_at(2.5); | |
| 1355 | + assert_eq!(view.total, plain.len()); | |
| 1356 | + assert!( | |
| 1357 | + viz_decodes() == after_first, | |
| 1358 | + "ask {} re-decoded a window the memo holds", | |
| 1359 | + ask + 2 | |
| 1360 | + ); | |
| 1361 | + } | |
| 1362 | + let _ = std::fs::remove_file(&file); | |
| 1363 | + } | |
| 1364 | + | |
| 1365 | + /// A window paints the frame the whole envelope paints: the picture of a | |
| 1366 | + /// clip must not change because the seat stopped holding two hours of sound | |
| 1367 | + /// to draw thirty seconds of it. The window here is cut out of the envelope | |
| 1368 | + /// itself, so this is the painter's half of the promise -- both looks, and | |
| 1369 | + /// times from the file's first frame to past its last. | |
| 1370 | + #[test] | |
| 1371 | + fn a_window_paints_the_frame_the_whole_envelope_paints() { | |
| 1372 | + let file = asset("test_av.mp4"); | |
| 1373 | + // The painter's own rate: it indexes an envelope at | |
| 1374 | + // [`VIZ_BUCKETS_PER_SEC`], whatever rate an ask drew it at. | |
| 1375 | + let per_sec = f64::from(crate::decode::VIZ_BUCKETS_PER_SEC); | |
| 1376 | + let whole = peaks(&file, 0, crate::decode::VIZ_BUCKETS_PER_SEC) | |
| 1377 | + .expect("open") | |
| 1378 | + .expect("audio track"); | |
| 1379 | + let peak = peak_of(&whole); | |
| 1380 | + let mut scratch = crate::decode::VizScratch::default(); | |
| 1381 | + for flags in [0u8, crate::decode::VIZ_FAST] { | |
| 1382 | + for secs in [0.0, 0.4, 1.0, 2.5, 4.9, 5.2] { | |
| 1383 | + let whole_frame = | |
| 1384 | + crate::decode::visualizer_i420(&mut scratch, &whole, secs, 320, 180, flags, 7); | |
| 1385 | + // The buckets a two-second picture can reach: a second either | |
| 1386 | + // side of the frame's own time, plus the bucket the | |
| 1387 | + // interpolation reads past it. | |
| 1388 | + let from = ((secs - 1.0).max(0.0) * per_sec) as usize; | |
| 1389 | + let to = (((secs + 1.0) * per_sec) as usize + 2).min(whole.len()); | |
| 1390 | + let view = | |
| 1391 | + crate::decode::VizView::window(&whole[from..to], from, whole.len(), peak); | |
| 1392 | + let window_frame = crate::decode::visualizer_window_i420( | |
| 1393 | + &mut scratch, | |
| 1394 | + &view, | |
| 1395 | + secs, | |
| 1396 | + 320, | |
| 1397 | + 180, | |
| 1398 | + flags, | |
| 1399 | + 7, | |
| 1400 | + ); | |
| 1401 | + assert_eq!( | |
| 1402 | + whole_frame, window_frame, | |
| 1403 | + "the window painted {secs}s (flags {flags}) differently" | |
| 1404 | + ); | |
| 1405 | + } | |
| 1406 | + } | |
| 1407 | + } | |
| 1408 | + | |
| 1409 | + /// The long source the defect is about: forty minutes of sound, whose own | |
| 1410 | + /// envelope at the visualizer's 4000 buckets a second is 9.6M buckets -- | |
| 1411 | + /// past [`PEAKS_MEMO_BUCKETS`], so the memo can never hold it and the | |
| 1412 | + /// windowed route is the only one there is. What a window of it draws is | |
| 1413 | + /// what the whole envelope draws, byte for byte, and the second and third | |
| 1414 | + /// ask decode nothing. | |
| 1415 | + /// | |
| 1416 | + /// The fixture is generated here (`ffmpeg -f lavfi -i | |
| 1417 | + /// sine=frequency=440:duration=2400 -ar 8000 -ac 1 -c:a flac`) and is FLAC | |
| 1418 | + /// on purpose: a seek into a lossless frame lands on the sample, so a | |
| 1419 | + /// window of it holds exactly the buckets the whole-file decode holds -- | |
| 1420 | + /// which is the promise a caching change has to keep, and what a lossy | |
| 1421 | + /// codec's seeked filterbank cannot (a bucket lands a ten-thousandth away, | |
| 1422 | + /// as [`a_split_decode_draws_the_same_envelope`] already bounds it). The | |
| 1423 | + /// envelope's own length is asserted against the forty minutes asked for, | |
| 1424 | + /// so a fixture that came out at another scale cannot pass this vacuously. | |
| 1425 | + /// Skipped, loudly, where ffmpeg is not installed. | |
| 1426 | + #[test] | |
| 1427 | + fn a_film_length_source_paints_the_same_frame_in_windows() { | |
| 1428 | + let path = | |
| 1429 | + std::env::temp_dir().join(format!("edith-peaks-long-{}.flac", std::process::id())); | |
| 1430 | + let generated = std::process::Command::new("ffmpeg") | |
| 1431 | + .args(["-y", "-v", "error", "-f", "lavfi", "-i"]) | |
| 1432 | + .arg("sine=frequency=440:duration=2400") | |
| 1433 | + .args(["-ar", "8000", "-ac", "1", "-c:a", "flac"]) | |
| 1434 | + .arg(&path) | |
| 1435 | + .status() | |
| 1436 | + .map(|status| status.success() && path.exists()) | |
| 1437 | + .unwrap_or(false); | |
| 1438 | + if !generated { | |
| 1439 | + eprintln!("no ffmpeg: a film-length fixture cannot be generated, skipping"); | |
| 1440 | + return; | |
| 1441 | + } | |
| 1442 | + let bps = crate::decode::VIZ_BUCKETS_PER_SEC; | |
| 1443 | + let plain = peaks(&path, 0, bps) | |
| 1444 | + .expect("open") | |
| 1445 | + .expect("the tone is audio"); | |
| 1446 | + let secs = 2400 * bps as usize; | |
| 1447 | + assert!( | |
| 1448 | + plain.len().abs_diff(secs) < 100, | |
| 1449 | + "the envelope is {} buckets, not the 2400 s of sound it was generated for", | |
| 1450 | + plain.len() | |
| 1451 | + ); | |
| 1452 | + assert!( | |
| 1453 | + plain.len() > PEAKS_MEMO_BUCKETS, | |
| 1454 | + "{} buckets is not past the memo's ceiling", | |
| 1455 | + plain.len() | |
| 1456 | + ); | |
| 1457 | + | |
| 1458 | + let before = viz_decodes(); | |
| 1459 | + let mut seat = viz_envelope(&path, 0, bps).expect("open"); | |
| 1460 | + let t = 1200.0; | |
| 1461 | + let view = seat.view_at(t); | |
| 1462 | + assert!(!view.peaks.is_empty(), "the window decoded nothing"); | |
| 1463 | + assert_eq!( | |
| 1464 | + view.peak, | |
| 1465 | + peak_of(&plain), | |
| 1466 | + "the window's peak is not the file's" | |
| 1467 | + ); | |
| 1468 | + assert_eq!( | |
| 1469 | + view.total, | |
| 1470 | + plain.len(), | |
| 1471 | + "the windowed length is not the envelope's" | |
| 1472 | + ); | |
| 1473 | + // The window's own buckets are the envelope's, bucket for bucket: the | |
| 1474 | + // time the seats ask for in the middle of a film is the time a window | |
| 1475 | + // has to get exactly as right as two hours of decode did. | |
| 1476 | + let mut checked = 0; | |
| 1477 | + for abs in (t * f64::from(bps)) as usize..((t + 20.0) * f64::from(bps)) as usize { | |
| 1478 | + let (Some(window), Some(&whole)) = (view.at(abs), plain.get(abs)) else { | |
| 1479 | + continue; | |
| 1480 | + }; | |
| 1481 | + assert_eq!(window, whole, "bucket {abs} differs from the envelope's"); | |
| 1482 | + checked += 1; | |
| 1483 | + } | |
| 1484 | + assert!(checked > 10_000, "only {checked} buckets were compared"); | |
| 1485 | + | |
| 1486 | + let mut scratch = crate::decode::VizScratch::default(); | |
| 1487 | + for secs in [t - 1.0, t, t + 1.0] { | |
| 1488 | + let whole = crate::decode::visualizer_i420(&mut scratch, &plain, secs, 320, 180, 0, 3); | |
| 1489 | + let window = | |
| 1490 | + crate::decode::visualizer_window_i420(&mut scratch, &view, secs, 320, 180, 0, 3); | |
| 1491 | + assert_eq!(whole, window, "the window painted {secs}s differently"); | |
| 1492 | + } | |
| 1493 | + let after_first = viz_decodes(); | |
| 1494 | + assert!(after_first > before, "the first ask decoded nothing"); | |
| 1495 | + | |
| 1496 | + // A look drag on a film: a new seat per pointer sample, at the same | |
| 1497 | + // playhead, and not one decode between them. | |
| 1498 | + for ask in 0..3 { | |
| 1499 | + let mut again = viz_envelope(&path, 0, bps).expect("open"); | |
| 1500 | + let view = again.view_at(t); | |
| 1501 | + assert_eq!(view.total, plain.len()); | |
| 1502 | + assert!( | |
| 1503 | + viz_decodes() == after_first, | |
| 1504 | + "ask {} re-decoded a window the memo holds", | |
| 1505 | + ask + 2 | |
| 1506 | + ); | |
| 1507 | + } | |
| 1508 | + let _ = std::fs::remove_file(&path); | |
| 1509 | + } | |
| 750 | 1510 | } |