forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7cb30bfTahinli2 months ago908 commits

waveform.rs1513 lines, 65.5 KiBHistoryRawDownload
1//! Waveform peaks for drawing a clip's audio: min/max per time bucket, taken
2//! off the same read-only decode path playback uses. Path in, peaks out — no
3//! project model, so a lane rework cannot reach it.
4
5use std::path::{Path, PathBuf};
6use std::sync::mpsc::Receiver;
7use std::thread;
8
9use crate::audio::AudioChunk;
10use crate::AudioSession;
11
12/// `(min, max)` of every sample in each `1 / buckets_per_sec` window of
13/// `stream` of `path`'s audio, from media time 0 (priming already trimmed by
14/// the decoder). Channels are folded together: one envelope per clip, not per
15/// channel.
16///
17/// `Ok(None)` for a file with no audio track — a silent source is valid, not a
18/// failure. Values are clamped to `[-1.0, 1.0]`, and a bucket's pair always
19/// straddles zero, so silence draws as a flat line.
20///
21/// Decoding the whole file runs at ~1700x realtime for an mp4's stereo AAC and
22/// ~260x for a film's 5.1 AAC in an mkv (six channels through `ec-aac`), but
23/// it is linear in source length either way: callers cache the result per source
24/// *and stream* — two streams of one file are two different envelopes, and a
25/// cache keyed on the path alone would draw the first one under both. Memory is
26/// flat in it, though: chunks are consumed as they arrive and only the buckets
27/// are kept (2 hours at 10/s is 70k pairs).
28///
29/// A source long enough for it is decoded in **windows on several threads** and
30/// the buckets stitched, which is what that linear cost is divided by:
31/// `open_multi_streams` takes a window per call and seeks to it, and the fold to
32/// one envelope is what makes the join safe — a bucket two windows straddle is
33/// folded from both, and min/max cannot double-count. A film that cost 23 s of
34/// one core costs about a quarter of that; a clip short enough that the extra
35/// opens would outweigh the decode they save ([`jobs_for`]) is read exactly as
36/// it always was, on this thread.
37pub fn peaks(
38 path: impl AsRef<Path>,
39 stream: usize,
40 buckets_per_sec: u32,
41) -> crate::Result<Option<Vec<(f32, f32)>>> {
42 peaks_over(path.as_ref(), stream, buckets_per_sec, None)
43}
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.
49const 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.
53pub(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, Clone)]
59struct PeaksKey {
60 path: PathBuf,
61 stream: usize,
62 buckets_per_sec: u32,
63 bytes: u64,
64 mtime: Option<std::time::SystemTime>,
65}
66
67impl 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
77 fn of(path: &Path, stream: usize, buckets_per_sec: u32) -> Self {
78 let stat = std::fs::metadata(path).ok();
79 Self {
80 path: path.to_path_buf(),
81 stream,
82 buckets_per_sec,
83 bytes: stat.as_ref().map_or(0, std::fs::Metadata::len),
84 mtime: stat.and_then(|m| m.modified().ok()),
85 }
86 }
87}
88
89/// The memo and how many buckets it is holding. One lock for both: a hit is a
90/// lookup and a refcount, which is the whole of what the caller saves.
91///
92/// `std::sync::Mutex`, not `parking_lot`'s: edith's workspace has no
93/// `parking_lot` of its own and this crate locks `std`'s everywhere (the audio
94/// device, the tap), so a new dependency is not what a memo is worth.
95fn peaks_memo() -> &'static std::sync::Mutex<(PeaksMemo, usize)> {
96 static MEMO: std::sync::LazyLock<std::sync::Mutex<(PeaksMemo, usize)>> =
97 std::sync::LazyLock::new(|| std::sync::Mutex::new((PeaksMemo::new(), 0)));
98 &MEMO
99}
100
101/// Test-only: how many times an ask had to decode rather than answer from what
102/// the memo already held. A second ask for the same source -- trackless or not
103/// -- must not move it, which is what makes "the memo answered" observable.
104#[cfg(test)]
105static MEMO_DECODES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
106
107/// [`MEMO_DECODES`], for a test that measures a delta across its own asks.
108#[cfg(test)]
109fn memo_decodes() -> usize {
110 MEMO_DECODES.load(std::sync::atomic::Ordering::Relaxed)
111}
112
113/// What the memo holds for one key: an envelope, or the stable answer that the
114/// source carries no audio track at all. The second is worth keeping too -- a
115/// trackless source re-opens its container on every ask otherwise, the same
116/// per-rebuild cost the envelope memo exists to remove -- and it holds no
117/// buckets, so the counter stays honest about what the map holds.
118enum MemoEntry {
119 /// A source with an audio track, shared so a second ask is a refcount.
120 Envelope(SharedPeaks),
121 /// A source with no audio track: a valid, empty answer ([`peaks`]'s
122 /// `Ok(None)`), kept rather than re-derived from the file each time.
123 NoTrack,
124}
125
126impl MemoEntry {
127 /// The answer this entry stands for, as [`peaks_shared`] returns it.
128 fn envelope(&self) -> Option<SharedPeaks> {
129 match self {
130 MemoEntry::Envelope(shared) => Some(SharedPeaks::clone(shared)),
131 MemoEntry::NoTrack => None,
132 }
133 }
134}
135
136/// Every answer the process has been asked for, by identity.
137type PeaksMemo = std::collections::HashMap<PeaksKey, MemoEntry>;
138
139/// [`peaks`] as a handle the caller can hold: the same envelope, shared rather
140/// than copied, under a ceiling.
141///
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.
149///
150/// A trackless source's `Ok(None)` is kept too: it is an answer the file will
151/// give again, and without it a visualizer clip on a silent source re-opens
152/// the container on every picture rebuild -- the whole cost the memo removes,
153/// paid once per look edit. It holds no buckets, so it never counts against
154/// the ceiling. A failed ask is *not* kept: a decode that failed once may fail
155/// for a reason that has gone away, and caching it would make that permanent.
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.
162fn peaks_shared_capped(
163 path: &Path,
164 stream: usize,
165 buckets_per_sec: u32,
166 cap: usize,
167) -> crate::Result<Option<SharedPeaks>> {
168 let key = PeaksKey::of(path, stream, buckets_per_sec);
169 if let Some(hit) = peaks_memo().lock().unwrap().0.get(&key) {
170 return Ok(hit.envelope());
171 }
172 #[cfg(test)]
173 MEMO_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
174 // A failure is *not* memoized: `?` leaves the map untouched, so a decode
175 // that failed once -- a file caught mid-write, a busy device -- is retried
176 // rather than frozen for the process's life. Only the two successful
177 // answers are kept: the envelope, and the trackless `None`.
178 let answer = peaks_over(path, stream, buckets_per_sec, None)?;
179 let entry = match answer {
180 None => MemoEntry::NoTrack,
181 Some(peaks) => MemoEntry::Envelope(SharedPeaks::new(peaks)),
182 };
183 // The handle the caller gets is the answer itself, whether or not the memo
184 // keeps a copy: an over-the-ceiling envelope is still returned below.
185 let handle = entry.envelope();
186 let mut guard = peaks_memo().lock().unwrap();
187 let (memo, count) = &mut *guard;
188 memoize(memo, count, cap, key, entry);
189 Ok(handle)
190}
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.
195trait Bucketed {
196 fn buckets(&self) -> usize;
197}
198
199impl 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
208impl Bucketed for SharedPeaks {
209 fn buckets(&self) -> usize {
210 self.len()
211 }
212}
213
214/// Record `entry` under `key` in `memo`, keeping `count` equal to the buckets
215/// the map holds. The arithmetic is what keeps the ceiling a ceiling:
216///
217/// - an entry bigger than `cap` is not held at all -- keeping it would put the
218/// count permanently over the ceiling, so the next ask of any *other* key
219/// would clear the map and drop it, and this source would pay a whole-file
220/// decode per rebuild anyway. The caller keeps the handle it was handed;
221/// - when the new entry would take the count past `cap`, the map is emptied
222/// rather than evicted one entry at a time (the entries are large);
223/// - an insert that replaces an entry the count already includes subtracts the
224/// replaced length first, so the racing-workers case -- two workers that
225/// missed one key each decode and insert it -- does not leave the count high
226/// for good: only a clear resets it, and a high count makes later asks clear
227/// early, dropping entries that then pay a whole-file decode to be rebuilt.
228fn memoize<K: std::hash::Hash + Eq, V: Bucketed>(
229 memo: &mut std::collections::HashMap<K, V>,
230 count: &mut usize,
231 cap: usize,
232 key: K,
233 entry: V,
234) {
235 let len = entry.buckets();
236 if len > cap {
237 return;
238 }
239 if *count + len > cap {
240 memo.clear();
241 *count = 0;
242 }
243 if let Some(previous) = memo.insert(key, entry) {
244 *count -= previous.buckets();
245 }
246 *count += len;
247}
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.
252const 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.
259const 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.
268const 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.
274pub(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.
287pub(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
300impl 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`]).
322pub(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
333impl 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.
346pub(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
361impl 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 for the
396 // rest of it: the seat is what remembers that, and only while it is
397 // painting in this window -- the memo keeps successes only, so the
398 // next seek (and the next window) asks the file again, and a source
399 // that comes back (a share remounting, a file finishing its write)
400 // paints again. Re-asking every frame instead would hammer a file
401 // that is not there thirty times a second.
402 let window = viz_window(
403 &self.key,
404 self.summary.sample_rate,
405 self.buckets_per_sec,
406 first,
407 per_window + 2 * seek,
408 )
409 .unwrap_or_else(|_| SharedPeaks::new(Vec::new()));
410 self.current = Some((first, window));
411 }
412 let (at, peaks) = self.current.as_ref().expect("just set");
413 // The slice starts where the decode did, a seek margin below the
414 // window's own first bucket -- the same arithmetic [`viz_window`] was
415 // asked with, so the absolute positions line up.
416 let slice_first = at.saturating_sub(seek);
417 crate::decode::VizView::window(peaks.as_slice(), slice_first, total, self.summary.peak)
418 }
419}
420
421/// A window's identity: the file it came from, and its own first bucket.
422#[derive(PartialEq, Eq, Hash)]
423struct WindowKey {
424 file: PeaksKey,
425 from: usize,
426}
427
428impl WindowKey {
429 fn of(file: &PeaksKey, from: usize) -> Self {
430 Self {
431 file: file.clone(),
432 from,
433 }
434 }
435}
436
437/// The windows every seat of this process has asked for, and how many buckets
438/// they hold between them.
439fn viz_windows(
440) -> &'static std::sync::Mutex<(std::collections::HashMap<WindowKey, SharedPeaks>, usize)> {
441 static MEMO: std::sync::LazyLock<
442 std::sync::Mutex<(std::collections::HashMap<WindowKey, SharedPeaks>, usize)>,
443 > = std::sync::LazyLock::new(|| std::sync::Mutex::new((std::collections::HashMap::new(), 0)));
444 &MEMO
445}
446
447/// The whole-file scalars every over-the-ceiling source has been measured for,
448/// by the stream's own identity: [`VizSummary`] is sixteen bytes, so this map
449/// is bounded by how many *streams* a session has asked about rather than by
450/// how long they are.
451fn viz_summaries(
452) -> &'static std::sync::Mutex<std::collections::HashMap<PeaksKey, std::sync::Arc<VizSummary>>> {
453 static MEMO: std::sync::LazyLock<
454 std::sync::Mutex<std::collections::HashMap<PeaksKey, std::sync::Arc<VizSummary>>>,
455 > = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
456 &MEMO
457}
458
459/// Test-only: how many times the visualizer's own ask had to open the file --
460/// a window of an envelope, or one window of a [`viz_summary`] pass. The
461/// second ask for the same window of the same source must not move it.
462#[cfg(test)]
463static VIZ_DECODES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
464
465/// [`VIZ_DECODES`], for a test that measures a delta across its own asks.
466#[cfg(test)]
467fn viz_decodes() -> usize {
468 VIZ_DECODES.load(std::sync::atomic::Ordering::Relaxed)
469}
470
471/// The visualizer seat's own ask: the whole envelope when the memo holds it,
472/// and otherwise windows of it. Never decoded per frame either way -- the
473/// per-frame cost of a look drag is what this exists to remove.
474pub(crate) fn viz_envelope(
475 path: &Path,
476 stream: usize,
477 buckets_per_sec: u32,
478) -> crate::Result<VizEnvelope> {
479 viz_envelope_capped(path, stream, buckets_per_sec, PEAKS_MEMO_BUCKETS)
480}
481
482/// [`viz_envelope`] against a ceiling a test can drive down to a handful of
483/// buckets, so the windowed route is walked on a five-second fixture. `cap` is
484/// [`PEAKS_MEMO_BUCKETS`] everywhere but in a test.
485pub(crate) fn viz_envelope_capped(
486 path: &Path,
487 stream: usize,
488 buckets_per_sec: u32,
489 cap: usize,
490) -> crate::Result<VizEnvelope> {
491 let key = PeaksKey::of(path, stream, buckets_per_sec);
492 // An answer the memo already holds ends it, without opening anything: a
493 // song's whole envelope, or the stable "no audio track" a silent source
494 // gives.
495 match peaks_memo().lock().unwrap().0.get(&key) {
496 Some(MemoEntry::Envelope(shared)) => {
497 return Ok(VizEnvelope::Whole(SharedPeaks::clone(shared)))
498 }
499 Some(MemoEntry::NoTrack) => return Ok(VizEnvelope::Silent),
500 None => {}
501 }
502 // A source this process has already measured past the ceiling: the summary
503 // is the answer, and it costs an open to have asked for one.
504 let stream_key = PeaksKey::stream_of(path, stream);
505 if let Some(summary) = viz_summaries().lock().unwrap().get(&stream_key) {
506 let summary = std::sync::Arc::clone(summary);
507 return Ok(VizEnvelope::Windowed(VizWindows {
508 key,
509 buckets_per_sec,
510 summary,
511 current: None,
512 }));
513 }
514 // A miss, so the file has to be looked at once. The container's own word
515 // for its length decides which ask this is, before anything is decoded:
516 // what the memo can hold is asked for exactly as it always was, and only
517 // what it cannot is served in windows.
518 let Some((meta, rx)) = open_window(path, stream, 0.0, f64::INFINITY)? else {
519 let mut guard = peaks_memo().lock().unwrap();
520 let (memo, count) = &mut *guard;
521 memoize(memo, count, cap, key, MemoEntry::NoTrack);
522 return Ok(VizEnvelope::Silent);
523 };
524 let per_bucket = per_bucket_of(meta.sample_rate, buckets_per_sec);
525 let fits = match meta.total_samples {
526 // The stated length is the container's, which is a lower bound on what
527 // the decode finds (a tail past it is still drawn), so a file near the
528 // ceiling can turn out larger. The windowed route below catches that.
529 Some(samples) => (samples as f64 / per_bucket) as usize + 1 <= cap,
530 // A length the container does not state cannot be windowed -- neither
531 // by this ask nor by the split inside it. Read exactly as it always
532 // was, and held when it fits.
533 None => true,
534 };
535 if fits {
536 // The receiver the probe opened is dropped here: the whole-file ask
537 // opens its own, which is the only ask this path has ever made.
538 drop(rx);
539 let answer = peaks_shared_capped(path, stream, buckets_per_sec, cap)?;
540 return Ok(match answer {
541 None => VizEnvelope::Silent,
542 Some(shared) if shared.len() > cap => {
543 // The container understated its length, so this ask paid for a
544 // whole envelope it cannot keep. Measure the file off it --
545 // both scalars are exact here -- and hand the seat windows of
546 // it instead, so the *next* rebuild is the cheap one.
547 let summary = std::sync::Arc::new(VizSummary {
548 samples: (shared.len() as f64 * per_bucket) as u64,
549 sample_rate: meta.sample_rate,
550 peak: peak_of(&shared),
551 });
552 viz_summaries()
553 .lock()
554 .unwrap()
555 .insert(stream_key, summary.clone());
556 VizEnvelope::Windowed(VizWindows {
557 key,
558 buckets_per_sec,
559 summary,
560 current: None,
561 })
562 }
563 Some(shared) => VizEnvelope::Whole(shared),
564 });
565 }
566 // Past the ceiling: the file's two scalars off the probe's own window and
567 // its neighbours, then a window of it per painted frame.
568 let summary = viz_summary(path, stream, &meta, rx)?;
569 Ok(VizEnvelope::Windowed(VizWindows {
570 key,
571 buckets_per_sec,
572 summary,
573 current: None,
574 }))
575}
576
577/// The two scalars of [`VizSummary`], read off one pass that keeps no buckets.
578///
579/// The same windows, the same threads and the same opens [`peaks_over`] decodes
580/// a whole envelope with -- `rx` is that ask's own first window, the probe's --
581/// because the peak has to be the peak of the envelope the memo would have
582/// held: a frame scaled by any other number is a different picture. A stop
583/// sample would be the one way to lose a bucket the envelope has (and, with it,
584/// the loudest sample in the file), so there are none here: what the windows
585/// fold between them is everything the file delivers.
586fn viz_summary(
587 path: &Path,
588 stream: usize,
589 meta: &crate::AudioMeta,
590 rx: Receiver<AudioChunk>,
591) -> crate::Result<std::sync::Arc<VizSummary>> {
592 let key = PeaksKey::stream_of(path, stream);
593 if let Some(hit) = viz_summaries().lock().unwrap().get(&key) {
594 return Ok(std::sync::Arc::clone(hit));
595 }
596 let rate = f64::from(meta.sample_rate.max(1));
597 let channels = (meta.channels as usize).max(1);
598 let secs = meta.total_samples.unwrap_or(0) as f64 / rate;
599 let jobs = jobs_for(secs).max(1);
600 let window = secs / jobs as f64;
601 let rest: Vec<_> = (1..jobs)
602 .map(|k| {
603 let path = path.to_path_buf();
604 let start = window * k as f64;
605 let end = match k + 1 == jobs {
606 true => f64::INFINITY,
607 false => window * (k + 1) as f64,
608 };
609 #[cfg(test)]
610 VIZ_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
611 thread::Builder::new().name("waveform".into()).spawn(
612 move || -> crate::Result<(f32, u64)> {
613 match open_window(&path, stream, start, end)? {
614 Some((window_meta, window_rx)) => Ok(fold_summary(
615 window_rx,
616 u64::MAX,
617 (window_meta.channels as usize).max(1),
618 )),
619 None => Ok((0.0, 0)),
620 }
621 },
622 )
623 })
624 .collect::<Result<_, _>>()?;
625 #[cfg(test)]
626 VIZ_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
627 // Every window folds everything it is handed, the first one included: no
628 // stop sample, because a stop that dropped a window's own tail could drop
629 // the loudest sample in the file with it -- and the peak a visualizer frame
630 // is scaled by is the one thing here that has to be the envelope's own.
631 let (mut peak, mut samples) = fold_summary(rx, u64::MAX, channels);
632 for handle in rest {
633 let (part_peak, part_samples) = handle.join().map_err(|_| "waveform worker panicked")??;
634 peak = peak.max(part_peak);
635 samples = samples.max(part_samples);
636 }
637 let summary = std::sync::Arc::new(VizSummary {
638 samples,
639 sample_rate: meta.sample_rate,
640 peak,
641 });
642 viz_summaries()
643 .lock()
644 .unwrap()
645 .insert(key, std::sync::Arc::clone(&summary));
646 Ok(summary)
647}
648
649/// One window of one file's envelope, decoded and kept. A window is what the
650/// memo can hold of a film: thirty seconds of sound about the frame's own time,
651/// so the look edit that re-opens the seat decodes a window rather than the
652/// file, and the *second* edit reads the one the first left.
653fn viz_window(
654 key: &PeaksKey,
655 sample_rate: u32,
656 buckets_per_sec: u32,
657 from: usize,
658 buckets: usize,
659) -> crate::Result<SharedPeaks> {
660 let memo_key = WindowKey::of(key, from);
661 if let Some(hit) = viz_windows().lock().unwrap().0.get(&memo_key) {
662 return Ok(SharedPeaks::clone(hit));
663 }
664 #[cfg(test)]
665 VIZ_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
666 // Both units, from the two rates: `per_bucket` is what the fold counts
667 // samples in, `per_sec` is what a window's own ends are named in -- and a
668 // bucket is a fraction of a *second* over the ask's rate, never of a sample,
669 // whatever either rate is.
670 let per_bucket = per_bucket_of(sample_rate, buckets_per_sec);
671 let per_sec = f64::from(buckets_per_sec.max(1));
672 let start = from as f64 / per_sec;
673 let end = (from + buckets) as f64 / per_sec;
674 let Some((meta, rx)) = open_window(&key.path, key.stream, start, end)? else {
675 // The track the probe found is gone (the file changed under the key):
676 // an empty window, which paints its own stretch of the flat line.
677 return Ok(SharedPeaks::new(Vec::new()));
678 };
679 let channels = (meta.channels as usize).max(1);
680 let peaks = SharedPeaks::new(fold_window(rx, per_bucket, channels, from));
681 let mut guard = viz_windows().lock().unwrap();
682 let (memo, count) = &mut *guard;
683 // The ceiling arithmetic is [`memoize`]'s, on a map whose entries are
684 // windows: an entry bigger than the ceiling is handed back but not held,
685 // and one that replaces another subtracts what it replaced.
686 memoize(
687 memo,
688 count,
689 VIZ_WINDOW_MEMO_BUCKETS,
690 memo_key,
691 SharedPeaks::clone(&peaks),
692 );
693 Ok(peaks)
694}
695
696/// Min/max per bucket of everything `rx` carries, from `from` on: the window's
697/// own first bucket is `from`, and anything the decoder hands over before it --
698/// a seek lands where it lands -- is dropped rather than folded at an index the
699/// window does not have. The *last* bucket is partial too, which is what the
700/// seek margin in [`viz_window`] is for.
701fn fold_window(
702 rx: Receiver<AudioChunk>,
703 per_bucket: f64,
704 channels: usize,
705 from: usize,
706) -> Vec<(f32, f32)> {
707 let mut peaks: Vec<(f32, f32)> = Vec::new();
708 for chunk in rx {
709 for (frame, values) in chunk.samples.chunks(channels).enumerate() {
710 let bucket = ((chunk.start_sample + frame as u64) as f64 / per_bucket) as usize;
711 if bucket < from {
712 continue;
713 }
714 let i = bucket - from;
715 if i >= peaks.len() {
716 peaks.resize(i + 1, (0.0, 0.0));
717 }
718 let slot = &mut peaks[i];
719 for &v in values {
720 let v = v.clamp(-1.0, 1.0);
721 slot.0 = slot.0.min(v);
722 slot.1 = slot.1.max(v);
723 }
724 }
725 }
726 peaks
727}
728
729/// [`fold`]'s two answers without its buckets: the loudest sample the window
730/// carries, and how far the file it came from runs. Clamped and counted
731/// exactly as `fold` clamps and counts them, so the peak of a whole-file pass
732/// is the peak of the whole-file envelope.
733fn fold_summary(rx: Receiver<AudioChunk>, stop_sample: u64, channels: usize) -> (f32, u64) {
734 let (mut peak, mut samples) = (0.0f32, 0u64);
735 for chunk in rx {
736 if chunk.start_sample >= stop_sample {
737 break;
738 }
739 samples = samples.max(chunk.start_sample + (chunk.samples.len() / channels) as u64);
740 for &v in &chunk.samples {
741 peak = peak.max(v.clamp(-1.0, 1.0).abs());
742 }
743 }
744 (peak, samples)
745}
746
747/// Samples per bucket. Guarded at one both ways, because a container that does
748/// not state a rate (or states a zero one) would otherwise make this zero,
749/// every sample would land in bucket `usize::MAX`, and the fold's own
750/// `resize(bucket + 1)` would be a length that does not exist. One keeps the
751/// fold total, and `buckets_per_sec` is floored where it is asked for as well.
752fn per_bucket_of(sample_rate: u32, buckets_per_sec: u32) -> f64 {
753 f64::from(sample_rate.max(1)) / f64::from(buckets_per_sec.max(1))
754}
755
756/// [`peaks`] with the split forced to `jobs` windows, which is how a test asks
757/// for the same envelope by both routes.
758fn peaks_over(
759 path: &Path,
760 stream: usize,
761 buckets_per_sec: u32,
762 jobs: Option<usize>,
763) -> crate::Result<Option<Vec<(f32, f32)>>> {
764 let Some((meta, rx)) = open_window(path, stream, 0.0, f64::INFINITY)? else {
765 return Ok(None);
766 };
767 // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a
768 // bucket every few seconds over a long source.
769 let per_bucket = per_bucket_of(meta.sample_rate, buckets_per_sec);
770 let channels = (meta.channels as usize).max(1);
771 let rate = f64::from(meta.sample_rate.max(1));
772 // A track whose length the container does not state cannot be cut into
773 // windows at all: `secs` is 0 and the whole of it is read on this thread,
774 // exactly as it was before there was a split.
775 let secs = meta.total_samples.unwrap_or(0) as f64 / rate;
776 let jobs = jobs.unwrap_or_else(|| jobs_for(secs)).max(1);
777 if jobs == 1 {
778 return Ok(Some(fold(rx, per_bucket, channels, u64::MAX)));
779 }
780 let window = secs / jobs as f64;
781 // Every other window is spawned before this thread folds its own, so they
782 // all decode side by side; each carries its own error home rather than
783 // taking a worker down.
784 let rest: Vec<_> = (1..jobs)
785 .map(|k| {
786 let path = path.to_path_buf();
787 let start = window * k as f64;
788 // The last window runs to the end of the file: `total_samples` is
789 // the container's word for a length, and a tail past it must still
790 // be drawn.
791 let end = match k + 1 == jobs {
792 true => f64::INFINITY,
793 false => window * (k + 1) as f64,
794 };
795 thread::Builder::new().name("waveform".into()).spawn(
796 move || -> crate::Result<Vec<(f32, f32)>> {
797 match open_window(&path, stream, start, end)? {
798 Some((_, rx)) => Ok(fold(rx, per_bucket, channels, u64::MAX)),
799 None => Ok(Vec::new()),
800 }
801 },
802 )
803 })
804 .collect::<Result<_, _>>()?;
805 // This window ends where the next one's decoder was told to start, by the
806 // same arithmetic, so the two meet with no gap; the chunk that straddles the
807 // joint is folded into both and min/max does not double-count.
808 let mut peaks = fold(rx, per_bucket, channels, (window * rate) as u64);
809 for handle in rest {
810 let part = handle.join().map_err(|_| "waveform worker panicked")??;
811 merge(&mut peaks, &part);
812 }
813 Ok(Some(peaks))
814}
815
816/// How many threads a source of `secs` is worth splitting across: one below two
817/// minutes of sound, where the extra opens (a Matroska's is a cluster walk) cost
818/// more than the decode they would save, and never more than the machine has —
819/// nor more than a handful, since an import asks this of every source at once.
820///
821/// corner-cut: that last clause is a ceiling and not a bound — a library import of
822/// twenty films runs as many of these as the background executor has threads,
823/// each with eight of its own. The upgrade path is one pool the waveforms share,
824/// which is also where a "visible range first" order would live.
825fn jobs_for(secs: f64) -> usize {
826 const PER_JOB_SECS: f64 = 60.0;
827 const CEILING: usize = 8;
828 if !secs.is_finite() || secs < 2.0 * PER_JOB_SECS {
829 return 1;
830 }
831 let cores = thread::available_parallelism().map_or(1, |n| n.get());
832 ((secs / PER_JOB_SECS) as usize)
833 .min(cores)
834 .min(CEILING)
835 .max(1)
836}
837
838/// `part` folded into `peaks` bucket for bucket. Both are indexed absolutely,
839/// so this is a straight min/max: an empty bucket is `(0.0, 0.0)` and every
840/// value is clamped to `[-1.0, 1.0]`, which makes the empty pair the identity.
841fn merge(peaks: &mut Vec<(f32, f32)>, part: &[(f32, f32)]) {
842 if part.len() > peaks.len() {
843 peaks.resize(part.len(), (0.0, 0.0));
844 }
845 for (slot, &(lo, hi)) in peaks.iter_mut().zip(part) {
846 slot.0 = slot.0.min(lo);
847 slot.1 = slot.1.max(hi);
848 }
849}
850
851/// One window of one stream, opened the way playback opens it.
852fn open_window(
853 path: &Path,
854 stream: usize,
855 start_secs: f64,
856 end_secs: f64,
857) -> crate::Result<Option<(crate::AudioMeta, Receiver<AudioChunk>)>> {
858 let sources = [(PathBuf::from(path), stream)];
859 AudioSession::open_multi_streams(&sources, &[(Some(0), start_secs, end_secs)])
860}
861
862/// Min/max per bucket of everything `rx` carries, at absolute bucket positions:
863/// `start_sample` counts from the source's own first audible sample whatever
864/// window the session was opened at. Stops at the first chunk beginning at or
865/// past `stop_sample`, and dropping the receiver there is what stops that
866/// window's decoder.
867fn fold(
868 rx: Receiver<AudioChunk>,
869 per_bucket: f64,
870 channels: usize,
871 stop_sample: u64,
872) -> Vec<(f32, f32)> {
873 let mut peaks: Vec<(f32, f32)> = Vec::new();
874 for chunk in rx {
875 if chunk.start_sample >= stop_sample {
876 break;
877 }
878 for (frame, values) in chunk.samples.chunks(channels).enumerate() {
879 let bucket = ((chunk.start_sample + frame as u64) as f64 / per_bucket) as usize;
880 if bucket >= peaks.len() {
881 peaks.resize(bucket + 1, (0.0, 0.0));
882 }
883 let slot = &mut peaks[bucket];
884 for &v in values {
885 let v = v.clamp(-1.0, 1.0);
886 slot.0 = slot.0.min(v);
887 slot.1 = slot.1.max(v);
888 }
889 }
890 }
891 peaks
892}
893
894#[cfg(test)]
895mod tests {
896 use std::path::PathBuf;
897
898 use super::{
899 memo_decodes, memoize, peak_of, peaks, peaks_over, peaks_shared_capped, viz_decodes,
900 viz_envelope, viz_envelope_capped, MemoEntry, PeaksKey, PeaksMemo, SharedPeaks,
901 PEAKS_MEMO_BUCKETS,
902 };
903
904 const BPS: u32 = 10;
905
906 /// The memo's own ask, as the seat's used to be: a ceiling a test does not
907 /// want to think about is the process's.
908 fn peaks_shared(
909 path: &std::path::Path,
910 stream: usize,
911 buckets_per_sec: u32,
912 ) -> crate::Result<Option<SharedPeaks>> {
913 peaks_shared_capped(path, stream, buckets_per_sec, PEAKS_MEMO_BUCKETS)
914 }
915
916 fn asset(name: &str) -> PathBuf {
917 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
918 .join("../../assets")
919 .join(name)
920 }
921
922 /// A private copy of a fixture, so the memo key a test drives is not one
923 /// another test in this binary may already hold.
924 fn copy_of(name: &str, tag: &str) -> PathBuf {
925 let path =
926 std::env::temp_dir().join(format!("edith-peaks-{tag}-{}.mp4", std::process::id()));
927 std::fs::write(&path, std::fs::read(asset(name)).expect("read the fixture"))
928 .expect("write the copy");
929 path
930 }
931
932 #[test]
933 fn peaks_follow_the_1hz_volume_pulse() {
934 let peaks = peaks(asset("test_av.mp4"), 0, BPS)
935 .expect("open")
936 .expect("test_av.mp4 has an audio track");
937 // 5 s of source; the container's tail padding may spill one bucket.
938 let want = 5 * BPS as usize;
939 assert!(
940 peaks.len().abs_diff(want) <= 1,
941 "{} buckets, want {want} +/-1",
942 peaks.len()
943 );
944
945 for (i, &(lo, hi)) in peaks.iter().enumerate() {
946 assert!(
947 (-1.0..=0.0).contains(&lo) && (0.0..=1.0).contains(&hi),
948 "bucket {i} is ({lo}, {hi})"
949 );
950 }
951
952 // The fixture's envelope is 0.5 + 0.5*sin(2*PI*t): a full silence every
953 // second at t = 0.75, a full-scale peak at t = 0.25. So every second's
954 // quietest bucket must be the 8th (t in [0.7, 0.8)) — a bucketing that
955 // was off by a scale factor or dropped chunk positions would not line
956 // the dips up second after second.
957 for second in 0..5 {
958 let band = &peaks[second * BPS as usize..][..BPS as usize];
959 let level = |&(lo, hi): &(f32, f32)| hi - lo;
960 let quietest = (0..band.len())
961 .min_by(|&a, &b| level(&band[a]).total_cmp(&level(&band[b])))
962 .expect("non-empty band");
963 assert!(
964 (6..=8).contains(&quietest),
965 "second {second}: dip at bucket {quietest}, want 7 +/-1"
966 );
967 // Depth as a ratio, not an absolute: the fixture's sines sit around
968 // an eighth of full scale, and that is the encoder's business.
969 let (dip, loudest) = (
970 level(&band[quietest]),
971 band.iter().map(level).fold(0.0, f32::max),
972 );
973 assert!(loudest > 0.05, "second {second}: peak level only {loudest}");
974 assert!(
975 dip < 0.1 * loudest,
976 "second {second}: dip {dip} against peak {loudest}, want near silence"
977 );
978 }
979 }
980
981 /// A song's clip draws like any other: this goes through the same
982 /// `open_multi_streams` the timeline plays with, which reads a standalone
983 /// audio file on stream 0 as readily as an mp4's AAC track.
984 #[test]
985 fn a_standalone_audio_file_has_peaks_too() {
986 let peaks = peaks(asset("test_tone.mp3"), 0, BPS)
987 .expect("open")
988 .expect("test_tone.mp3 is audio");
989 let want = 3 * BPS as usize; // 3 s of tone, mp3 padding may spill one
990 assert!(
991 peaks.len().abs_diff(want) <= 2,
992 "{} buckets, want {want} +/-2",
993 peaks.len()
994 );
995 // The fixture carries the A/V one's 1 Hz envelope, so the middle second
996 // has a dip and a peak. As a ratio, and a looser one: the tone sits
997 // around an eighth of full scale and mp3 does not preserve a true zero.
998 let level = |&(lo, hi): &(f32, f32)| hi - lo;
999 let band = &peaks[BPS as usize..][..BPS as usize];
1000 let dip = band.iter().map(level).fold(f32::MAX, f32::min);
1001 let loudest = band.iter().map(level).fold(0.0, f32::max);
1002 assert!(loudest > 0.05, "peak level only {loudest}");
1003 assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}");
1004 }
1005
1006 /// The shape the ask came from: a film in an mkv with a 5.1 AAC track,
1007 /// which no symphonia decoder takes (`aac: aac too complex`) and which
1008 /// therefore reaches the lane through `ec-aac` and the stereo fold. A
1009 /// clip of one draws a waveform like any other -- an envelope that is not
1010 /// flat -- rather than the empty band a silent file makes.
1011 #[test]
1012 fn a_five_one_aac_mkv_draws_an_envelope() {
1013 let peaks = peaks(asset("test_hevc10.mkv"), 0, BPS)
1014 .expect("the 5.1 AAC track decodes")
1015 .expect("test_hevc10.mkv has an audio track");
1016 let want = 2 * BPS as usize; // 2 s of tones
1017 assert!(
1018 peaks.len().abs_diff(want) <= 2,
1019 "{} buckets, want {want} +/-2",
1020 peaks.len()
1021 );
1022 // Six tones, one per channel, folded to stereo: every bucket carries
1023 // signal, and a decode that came out silent (or clipped to a rail) is
1024 // exactly what this refuses.
1025 for (i, &(lo, hi)) in peaks.iter().enumerate() {
1026 assert!(
1027 (0.02..2.0).contains(&(hi - lo)),
1028 "bucket {i} is ({lo}, {hi})"
1029 );
1030 }
1031 }
1032
1033 /// The split is an optimisation and nothing else: four windows decoded side
1034 /// by side draw the very envelope the single-threaded walk draws, bucket for
1035 /// bucket. The joints are where a window that started a sample late or
1036 /// stopped a chunk early would show, so this is the check that a film's
1037 /// waveform is still the film's.
1038 #[test]
1039 fn a_split_decode_draws_the_same_envelope() {
1040 let file = asset("test_av.mp4");
1041 let whole = peaks_over(&file, 0, BPS, Some(1))
1042 .expect("open")
1043 .expect("test_av.mp4 has an audio track");
1044 let split = peaks_over(&file, 0, BPS, Some(4))
1045 .expect("open")
1046 .expect("test_av.mp4 has an audio track");
1047 assert_eq!(whole.len(), split.len(), "the split lost or grew buckets");
1048 // Not bit-equality: a window seeks into the middle of an AAC stream and
1049 // its filterbank is primed from a preceding packet rather than carried
1050 // over, so a bucket can land a ten-thousandth away. A lane is drawn a
1051 // hundred pixels tall, where that is a thousandth of a pixel; a window
1052 // that started late or stopped early is off by whole tenths and is what
1053 // this catches.
1054 for (i, (w, s)) in whole.iter().zip(&split).enumerate() {
1055 assert!(
1056 (w.0 - s.0).abs() < 1e-3 && (w.1 - s.1).abs() < 1e-3,
1057 "bucket {i}: whole {w:?}, split {s:?}"
1058 );
1059 }
1060 }
1061
1062 #[test]
1063 fn video_only_source_has_no_peaks() {
1064 assert!(peaks(asset("test_baseline.mp4"), 0, BPS)
1065 .expect("open")
1066 .is_none());
1067 }
1068
1069 /// Two streams of one file are two envelopes: the lane draws what the clip
1070 /// actually plays, so a cache keyed on the path alone would be a lie the
1071 /// user can see. Stream 1 of the fixture is 2 s of 220 Hz mono against
1072 /// stream 0's 4-second-long pulsed stereo pair.
1073 #[test]
1074 fn each_stream_of_a_file_has_its_own_envelope() {
1075 let multi = asset("test_multiaudio.mp4");
1076 let zero = peaks(&multi, 0, BPS).expect("open").expect("stream 0");
1077 let one = peaks(&multi, 1, BPS).expect("open").expect("stream 1");
1078 assert!(!zero.is_empty() && !one.is_empty());
1079 // Bucket for bucket, not merely somewhere: a cache keyed on the path
1080 // alone would hand the lane the *first* stream's shape for both, and
1081 // that is what this refuses.
1082 assert_ne!(zero, one, "both streams drew the same envelope");
1083 assert_ne!(zero[0], one[0], "...and they differ from the first bucket");
1084 // Stream 2 is AC-3, and it decodes now: it draws its own envelope like
1085 // any other stream rather than being refused.
1086 let two = peaks(&multi, 2, BPS)
1087 .expect("AC-3 opens")
1088 .expect("stream 2");
1089 assert!(!two.is_empty(), "the AC-3 stream drew nothing");
1090 }
1091
1092 /// The memo is keyed on the *ask*, not on the file: a second visualizer
1093 /// rebuild of one source reuses the envelope, and one of another stream is
1094 /// decoded rather than handed the first one's -- the lie
1095 /// [`each_stream_of_a_file_has_its_own_envelope`] refuses, one cache layer
1096 /// down, where the visualizer seat reads it.
1097 #[test]
1098 fn the_shared_memo_answers_per_stream() {
1099 let multi = asset("test_multiaudio.mp4");
1100 let zero = peaks_shared(&multi, 0, BPS)
1101 .expect("open")
1102 .expect("stream 0");
1103 let again = peaks_shared(&multi, 0, BPS)
1104 .expect("open")
1105 .expect("stream 0, second ask");
1106 // Shared, not decoded again -- which is the whole of what the second
1107 // visualizer rebuild saves.
1108 assert!(
1109 std::sync::Arc::ptr_eq(&zero, &again),
1110 "the second ask decoded the file again"
1111 );
1112 // ...and the very envelope a plain ask draws, so nothing is served
1113 // through the memo that the decoder would not have said.
1114 let plain = peaks(&multi, 0, BPS).expect("open").expect("stream 0");
1115 assert_eq!(*zero, plain);
1116 let one = peaks_shared(&multi, 1, BPS)
1117 .expect("open")
1118 .expect("stream 1");
1119 assert_ne!(*zero, *one, "a stream took another's memo entry");
1120 }
1121
1122 /// A source replaced on disk is read again: the key carries the file's own
1123 /// stat, so the memo cannot paint the old file's envelope for a clip that
1124 /// no longer plays it. Asked of a *copy*, because the fixtures are
1125 /// read-only for every other test in this binary.
1126 #[test]
1127 fn a_replaced_source_is_read_again() {
1128 let path =
1129 std::env::temp_dir().join(format!("edith-peaks-memo-{}.mp4", std::process::id()));
1130 let short = std::fs::read(asset("test_multiaudio.mp4")).expect("read the fixture");
1131 let long = std::fs::read(asset("test_av.mp4")).expect("read the fixture");
1132 // The two halves below are the length half and the clock half of the
1133 // key, so their sizes have to differ for the first of them to be it.
1134 assert_ne!(short.len(), long.len(), "fixtures must differ in length");
1135
1136 std::fs::write(&path, &short).expect("write the copy");
1137 let first = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
1138 let again = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
1139 assert!(
1140 std::sync::Arc::ptr_eq(&first, &again),
1141 "the copy was not memoized"
1142 );
1143
1144 // Other bytes behind the same path. A key without the file's length
1145 // (or without any stat at all) serves `first` here -- the envelope of
1146 // bytes that are gone.
1147 std::fs::write(&path, &long).expect("rewrite the copy");
1148 let replaced = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
1149 assert_ne!(
1150 *replaced, *first,
1151 "the memo served the replaced file's envelope"
1152 );
1153 assert_eq!(
1154 *replaced,
1155 peaks(&path, 0, BPS).expect("open").expect("copy"),
1156 "the memo's answer is not what a plain ask draws"
1157 );
1158
1159 // The *same* bytes written again: same length, a newer clock. Resolution
1160 // is the filesystem's, so give it a moment to move.
1161 std::thread::sleep(std::time::Duration::from_millis(20));
1162 std::fs::write(&path, &long).expect("touch the copy");
1163 let touched = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
1164 assert_eq!(*touched, *replaced);
1165 // A key with length but no mtime hands the old handle back -- for a file
1166 // that changed under it, which is the serve the mtime is in the key for.
1167 assert!(
1168 !std::sync::Arc::ptr_eq(&replaced, &touched),
1169 "the mtime is not part of the key"
1170 );
1171
1172 let _ = std::fs::remove_file(&path);
1173 }
1174
1175 /// A trackless source is an answer too, and the memo keeps it: without that
1176 /// a visualizer clip on a silent source re-opens the container on every
1177 /// picture rebuild -- the whole cost the memo exists to remove, paid once
1178 /// per look edit. Proved by counting decodes: the second ask must not take
1179 /// one. A copy is used so the key is this test's alone.
1180 #[test]
1181 fn a_trackless_source_is_memoized_too() {
1182 let path = copy_of("test_baseline.mp4", "none");
1183
1184 let before = memo_decodes();
1185 let first = peaks_shared(&path, 0, BPS).expect("open");
1186 assert!(first.is_none(), "test_baseline.mp4 has no audio track");
1187 let after_first = memo_decodes();
1188 assert_eq!(after_first - before, 1, "the first ask did not decode");
1189
1190 let second = peaks_shared(&path, 0, BPS).expect("open");
1191 assert!(second.is_none());
1192 assert_eq!(
1193 memo_decodes(),
1194 after_first,
1195 "the second ask re-opened a trackless source"
1196 );
1197
1198 let _ = std::fs::remove_file(&path);
1199 }
1200
1201 /// A trackless answer holds no buckets, so the ceiling counts only
1202 /// envelopes -- and a source that gains an audio track (a re-encode) swaps
1203 /// the `NoTrack` entry for an envelope without stranding the old count.
1204 #[test]
1205 fn a_trackless_answer_holds_no_buckets() {
1206 let mut memo = PeaksMemo::new();
1207 let mut count = 0;
1208 let key = || PeaksKey::of(std::path::Path::new("edith-peaks-none-key"), 0, BPS);
1209
1210 memoize(&mut memo, &mut count, 100, key(), MemoEntry::NoTrack);
1211 assert_eq!(count, 0, "a trackless answer counted buckets");
1212 assert!(memo.contains_key(&key()));
1213
1214 memoize(
1215 &mut memo,
1216 &mut count,
1217 100,
1218 key(),
1219 MemoEntry::Envelope(SharedPeaks::new(vec![(0.0, 0.0); 4])),
1220 );
1221 assert_eq!(count, 4, "the envelope did not replace the trackless count");
1222 }
1223
1224 /// An envelope larger than the ceiling is handed to the caller but never
1225 /// held, so a clear can always bring the memo back under the ceiling. The
1226 /// real ceiling is 8M buckets (~35 min at 10/s), unreachable from a
1227 /// fixture, so this drives the same code through a ceiling of ten buckets
1228 /// against a five-second source (about fifty buckets). Covers: the
1229 /// over-the-ceiling *decision* and the caller-still-gets-its-handle half.
1230 /// Does not cover: an end-to-end decode past eight million buckets.
1231 #[test]
1232 fn an_envelope_over_the_ceiling_is_not_held() {
1233 let file = copy_of("test_av.mp4", "over");
1234 let before = memo_decodes();
1235 let first = peaks_shared_capped(&file, 0, BPS, 10)
1236 .expect("open")
1237 .expect("test_av.mp4 has an audio track");
1238 assert!(first.len() > 10, "the fixture must exceed the test ceiling");
1239 let mid = memo_decodes();
1240 assert_eq!(mid - before, 1, "the first ask did not decode");
1241
1242 let second = peaks_shared_capped(&file, 0, BPS, 10)
1243 .expect("open")
1244 .expect("test_av.mp4 has an audio track");
1245 assert_eq!(*first, *second, "the caller did not get its envelope");
1246 assert_eq!(
1247 memo_decodes() - mid,
1248 1,
1249 "an envelope over the ceiling was held"
1250 );
1251
1252 let _ = std::fs::remove_file(&file);
1253 }
1254
1255 /// An insert that replaces an entry the counter already includes subtracts
1256 /// the replaced length: the racing-workers case, where two workers that
1257 /// missed one key each decode and insert it. The count follows what the map
1258 /// *holds*, so a missing subtraction leaves it high for good -- only a
1259 /// clear resets it, and later asks then clear early, dropping entries that
1260 /// pay a whole-file decode to be rebuilt. Driven through the same [`memoize`]
1261 /// the ask path uses (a second *ask* on one key hits the memo, so it cannot
1262 /// reach the insert): without the subtraction the second insert would read
1263 /// 3 + 5 = 8.
1264 #[test]
1265 fn replacing_an_entry_subtracts_the_old_buckets() {
1266 let mut memo = PeaksMemo::new();
1267 let mut count = 0;
1268 let key = || PeaksKey::of(std::path::Path::new("edith-peaks-replace-key"), 0, BPS);
1269
1270 memoize(
1271 &mut memo,
1272 &mut count,
1273 100,
1274 key(),
1275 MemoEntry::Envelope(SharedPeaks::new(vec![(0.0, 0.0); 3])),
1276 );
1277 assert_eq!(count, 3, "the first insert was not counted");
1278
1279 memoize(
1280 &mut memo,
1281 &mut count,
1282 100,
1283 key(),
1284 MemoEntry::Envelope(SharedPeaks::new(vec![(0.0, 0.0); 5])),
1285 );
1286 assert_eq!(count, 5, "the replaced entry's buckets were not subtracted");
1287 assert_eq!(memo.len(), 1, "the replace added a second entry");
1288 }
1289
1290 /// A container that states no sample rate (or a zero one) must not make the
1291 /// samples-per-bucket arithmetic zero: `sample / 0.0` is infinite, `as
1292 /// usize` saturates, and the fold's own `resize(bucket + 1)` is then a
1293 /// length that does not exist -- a panic in debug, a wrap and an
1294 /// out-of-bounds index in release. Both asks that bucket samples share the
1295 /// guard, so this is the one arithmetic they both use.
1296 #[test]
1297 fn a_zero_sample_rate_still_buckets_samples() {
1298 // A rate of zero is read as one, and the rate is what divides either
1299 // way, so the arithmetic stays finite and positive.
1300 assert_eq!(super::per_bucket_of(0, 4000), 1.0 / 4000.0);
1301 assert_eq!(super::per_bucket_of(44100, 0), 44100.0);
1302 // ...and a fold over a chunk at that rate is total: one bucket per
1303 // sample rather than an index that does not exist.
1304 let per_bucket = super::per_bucket_of(0, 1);
1305 assert_eq!(per_bucket, 1.0);
1306 let (tx, rx) = std::sync::mpsc::channel();
1307 tx.send(crate::audio::AudioChunk {
1308 start_sample: 0,
1309 samples: vec![0.5; 4],
1310 })
1311 .expect("send");
1312 drop(tx);
1313 let peaks = super::fold(rx, per_bucket, 1, u64::MAX);
1314 assert_eq!(peaks.len(), 4, "the fold lost or invented buckets");
1315 assert_eq!(peaks[0], (0.0, 0.5), "a bucket must still straddle zero");
1316 }
1317
1318 /// The visualizer's ask for a source past the memo's ceiling: the first ask
1319 /// pays one pass for the file's two scalars and one window of it, and every
1320 /// ask after that -- the ones a look drag makes, once per pointer sample at
1321 /// the same playhead -- decodes nothing at all. Driven with a ceiling of ten
1322 /// buckets against a five-second source (fifty buckets), which is the same
1323 /// route the eight-million-bucket ceiling takes for a film.
1324 #[test]
1325 fn a_window_of_an_over_the_ceiling_source_is_decoded_once() {
1326 let file = copy_of("test_av.mp4", "window");
1327 let plain = peaks(&file, 0, BPS).expect("open").expect("audio track");
1328
1329 let before = viz_decodes();
1330 let mut first = viz_envelope_capped(&file, 0, BPS, 10).expect("open");
1331 assert!(
1332 matches!(first, super::VizEnvelope::Windowed(_)),
1333 "the fixture must be past the test ceiling"
1334 );
1335 let view = first.view_at(2.5);
1336 assert!(!view.peaks.is_empty(), "the window decoded nothing");
1337 // The two scalars are the file's own and not an approximation of them:
1338 // the painter's whole-file peak and its "past the end of the file" both
1339 // come from here, and a frame scaled by anything else is another frame.
1340 assert_eq!(
1341 view.peak,
1342 peak_of(&plain),
1343 "the window's peak is not the file's"
1344 );
1345 assert_eq!(
1346 view.total,
1347 plain.len(),
1348 "the windowed length is not the envelope's"
1349 );
1350 let after_first = viz_decodes();
1351 assert!(after_first > before, "the first ask decoded nothing");
1352
1353 // The same second, three more times, the way a drag asks it: a new seat
1354 // every time, and no decode in any of them.
1355 for ask in 0..3 {
1356 let mut again = viz_envelope_capped(&file, 0, BPS, 10).expect("open");
1357 let view = again.view_at(2.5);
1358 assert_eq!(view.total, plain.len());
1359 assert!(
1360 viz_decodes() == after_first,
1361 "ask {} re-decoded a window the memo holds",
1362 ask + 2
1363 );
1364 }
1365 let _ = std::fs::remove_file(&file);
1366 }
1367
1368 /// A window paints the frame the whole envelope paints: the picture of a
1369 /// clip must not change because the seat stopped holding two hours of sound
1370 /// to draw thirty seconds of it. The window here is cut out of the envelope
1371 /// itself, so this is the painter's half of the promise -- both looks, and
1372 /// times from the file's first frame to past its last.
1373 #[test]
1374 fn a_window_paints_the_frame_the_whole_envelope_paints() {
1375 let file = asset("test_av.mp4");
1376 // The painter's own rate: it indexes an envelope at
1377 // [`VIZ_BUCKETS_PER_SEC`], whatever rate an ask drew it at.
1378 let per_sec = f64::from(crate::decode::VIZ_BUCKETS_PER_SEC);
1379 let whole = peaks(&file, 0, crate::decode::VIZ_BUCKETS_PER_SEC)
1380 .expect("open")
1381 .expect("audio track");
1382 let peak = peak_of(&whole);
1383 let mut scratch = crate::decode::VizScratch::default();
1384 for flags in [0u8, crate::decode::VIZ_FAST] {
1385 for secs in [0.0, 0.4, 1.0, 2.5, 4.9, 5.2] {
1386 let whole_frame =
1387 crate::decode::visualizer_i420(&mut scratch, &whole, secs, 320, 180, flags, 7);
1388 // The buckets a two-second picture can reach: a second either
1389 // side of the frame's own time, plus the bucket the
1390 // interpolation reads past it.
1391 let from = ((secs - 1.0).max(0.0) * per_sec) as usize;
1392 let to = (((secs + 1.0) * per_sec) as usize + 2).min(whole.len());
1393 let view =
1394 crate::decode::VizView::window(&whole[from..to], from, whole.len(), peak);
1395 let window_frame = crate::decode::visualizer_window_i420(
1396 &mut scratch,
1397 &view,
1398 secs,
1399 320,
1400 180,
1401 flags,
1402 7,
1403 );
1404 assert_eq!(
1405 whole_frame, window_frame,
1406 "the window painted {secs}s (flags {flags}) differently"
1407 );
1408 }
1409 }
1410 }
1411
1412 /// The long source the defect is about: forty minutes of sound, whose own
1413 /// envelope at the visualizer's 4000 buckets a second is 9.6M buckets --
1414 /// past [`PEAKS_MEMO_BUCKETS`], so the memo can never hold it and the
1415 /// windowed route is the only one there is. What a window of it draws is
1416 /// what the whole envelope draws, byte for byte, and the second and third
1417 /// ask decode nothing.
1418 ///
1419 /// The fixture is generated here (`ffmpeg -f lavfi -i
1420 /// sine=frequency=440:duration=2400 -ar 8000 -ac 1 -c:a flac`) and is FLAC
1421 /// on purpose: a seek into a lossless frame lands on the sample, so a
1422 /// window of it holds exactly the buckets the whole-file decode holds --
1423 /// which is the promise a caching change has to keep, and what a lossy
1424 /// codec's seeked filterbank cannot (a bucket lands a ten-thousandth away,
1425 /// as [`a_split_decode_draws_the_same_envelope`] already bounds it). The
1426 /// envelope's own length is asserted against the forty minutes asked for,
1427 /// so a fixture that came out at another scale cannot pass this vacuously.
1428 /// Skipped, loudly, where ffmpeg is not installed.
1429 #[test]
1430 fn a_film_length_source_paints_the_same_frame_in_windows() {
1431 let path =
1432 std::env::temp_dir().join(format!("edith-peaks-long-{}.flac", std::process::id()));
1433 let generated = std::process::Command::new("ffmpeg")
1434 .args(["-y", "-v", "error", "-f", "lavfi", "-i"])
1435 .arg("sine=frequency=440:duration=2400")
1436 .args(["-ar", "8000", "-ac", "1", "-c:a", "flac"])
1437 .arg(&path)
1438 .status()
1439 .map(|status| status.success() && path.exists())
1440 .unwrap_or(false);
1441 if !generated {
1442 eprintln!("no ffmpeg: a film-length fixture cannot be generated, skipping");
1443 return;
1444 }
1445 let bps = crate::decode::VIZ_BUCKETS_PER_SEC;
1446 let plain = peaks(&path, 0, bps)
1447 .expect("open")
1448 .expect("the tone is audio");
1449 let secs = 2400 * bps as usize;
1450 assert!(
1451 plain.len().abs_diff(secs) < 100,
1452 "the envelope is {} buckets, not the 2400 s of sound it was generated for",
1453 plain.len()
1454 );
1455 assert!(
1456 plain.len() > PEAKS_MEMO_BUCKETS,
1457 "{} buckets is not past the memo's ceiling",
1458 plain.len()
1459 );
1460
1461 let before = viz_decodes();
1462 let mut seat = viz_envelope(&path, 0, bps).expect("open");
1463 let t = 1200.0;
1464 let view = seat.view_at(t);
1465 assert!(!view.peaks.is_empty(), "the window decoded nothing");
1466 assert_eq!(
1467 view.peak,
1468 peak_of(&plain),
1469 "the window's peak is not the file's"
1470 );
1471 assert_eq!(
1472 view.total,
1473 plain.len(),
1474 "the windowed length is not the envelope's"
1475 );
1476 // The window's own buckets are the envelope's, bucket for bucket: the
1477 // time the seats ask for in the middle of a film is the time a window
1478 // has to get exactly as right as two hours of decode did.
1479 let mut checked = 0;
1480 for abs in (t * f64::from(bps)) as usize..((t + 20.0) * f64::from(bps)) as usize {
1481 let (Some(window), Some(&whole)) = (view.at(abs), plain.get(abs)) else {
1482 continue;
1483 };
1484 assert_eq!(window, whole, "bucket {abs} differs from the envelope's");
1485 checked += 1;
1486 }
1487 assert!(checked > 10_000, "only {checked} buckets were compared");
1488
1489 let mut scratch = crate::decode::VizScratch::default();
1490 for secs in [t - 1.0, t, t + 1.0] {
1491 let whole = crate::decode::visualizer_i420(&mut scratch, &plain, secs, 320, 180, 0, 3);
1492 let window =
1493 crate::decode::visualizer_window_i420(&mut scratch, &view, secs, 320, 180, 0, 3);
1494 assert_eq!(whole, window, "the window painted {secs}s differently");
1495 }
1496 let after_first = viz_decodes();
1497 assert!(after_first > before, "the first ask decoded nothing");
1498
1499 // A look drag on a film: a new seat per pointer sample, at the same
1500 // playhead, and not one decode between them.
1501 for ask in 0..3 {
1502 let mut again = viz_envelope(&path, 0, bps).expect("open");
1503 let view = again.view_at(t);
1504 assert_eq!(view.total, plain.len());
1505 assert!(
1506 viz_decodes() == after_first,
1507 "ask {} re-decoded a window the memo holds",
1508 ask + 2
1509 );
1510 }
1511 let _ = std::fs::remove_file(&path);
1512 }
1513}