forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb8aec29Tahinli2 months ago966 commits

waveform.rs1752 lines, 76.7 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 *for one key* had to decode rather than
102/// answer from what the memo already held. A second ask of the same source --
103/// trackless or not -- must not move it, which is what makes "the memo
104/// answered" observable.
105///
106/// Keyed by the ask rather than counted process-wide: a test's claim is about
107/// *its* source, the suite runs in parallel by default, and a decode another
108/// test made would otherwise land inside the delta -- failing the claim for a
109/// reason that has nothing to do with the code. Every reader's source is a
110/// private copy of a fixture, so its key is that test's alone.
111#[cfg(test)]
112static MEMO_DECODES: std::sync::LazyLock<
113 std::sync::Mutex<std::collections::HashMap<PeaksKey, usize>>,
114> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
115
116/// [`MEMO_DECODES`] for one ask, for a test that measures a delta across its own.
117#[cfg(test)]
118fn memo_decodes(path: &Path, stream: usize, buckets_per_sec: u32) -> usize {
119 MEMO_DECODES
120 .lock()
121 .unwrap()
122 .get(&PeaksKey::of(path, stream, buckets_per_sec))
123 .copied()
124 .unwrap_or(0)
125}
126
127/// What the memo holds for one key: an envelope, or the stable answer that the
128/// source carries no audio track at all. The second is worth keeping too -- a
129/// trackless source re-opens its container on every ask otherwise, the same
130/// per-rebuild cost the envelope memo exists to remove -- and it holds no
131/// buckets, so the counter stays honest about what the map holds.
132enum MemoEntry {
133 /// A source with an audio track, shared so a second ask is a refcount.
134 Envelope(SharedPeaks),
135 /// A source with no audio track: a valid, empty answer ([`peaks`]'s
136 /// `Ok(None)`), kept rather than re-derived from the file each time.
137 NoTrack,
138}
139
140impl MemoEntry {
141 /// The answer this entry stands for, as [`peaks_shared`] returns it.
142 fn envelope(&self) -> Option<SharedPeaks> {
143 match self {
144 MemoEntry::Envelope(shared) => Some(SharedPeaks::clone(shared)),
145 MemoEntry::NoTrack => None,
146 }
147 }
148}
149
150/// Every answer the process has been asked for, by identity.
151type PeaksMemo = std::collections::HashMap<PeaksKey, MemoEntry>;
152
153/// [`peaks`] as a handle the caller can hold: the same envelope, shared rather
154/// than copied, under a ceiling.
155///
156/// Keyed on the file's own stat ([`PeaksKey`]) and bounded by [`cap`] *of what
157/// it holds*: past the ceiling the memo lets everything go rather than evicting
158/// one entry at a time, because the entries are large and a re-decode is the
159/// honest cost of asking for more than the ceiling. A single source whose own
160/// envelope is bigger than the ceiling is not memoized at all (the caller still
161/// gets its handle), so the ceiling is one -- an entry that no clear can bring
162/// the memo back under would be a memo that clears on every other ask.
163///
164/// A trackless source's `Ok(None)` is kept too: it is an answer the file will
165/// give again, and without it a visualizer clip on a silent source re-opens
166/// the container on every picture rebuild -- the whole cost the memo removes,
167/// paid once per look edit. It holds no buckets, so it never counts against
168/// the ceiling. A failed ask is *not* kept: a decode that failed once may fail
169/// for a reason that has gone away, and caching it would make that permanent.
170///
171/// The visualizer seat does not ask this directly any more -- it asks
172/// [`viz_envelope`], which answers with this for a source the memo holds and
173/// with windows of it for one it cannot. `cap` is [`PEAKS_MEMO_BUCKETS`] there;
174/// a test drives it down to a handful of buckets so the over-the-ceiling path
175/// is walked without an eight-million-bucket fixture.
176fn peaks_shared_capped(
177 path: &Path,
178 stream: usize,
179 buckets_per_sec: u32,
180 cap: usize,
181) -> crate::Result<Option<SharedPeaks>> {
182 let key = PeaksKey::of(path, stream, buckets_per_sec);
183 if let Some(hit) = peaks_memo().lock().unwrap().0.get(&key) {
184 return Ok(hit.envelope());
185 }
186 #[cfg(test)]
187 {
188 *MEMO_DECODES.lock().unwrap().entry(key.clone()).or_insert(0) += 1;
189 }
190 // A failure is *not* memoized: `?` leaves the map untouched, so a decode
191 // that failed once -- a file caught mid-write, a busy device -- is retried
192 // rather than frozen for the process's life. Only the two successful
193 // answers are kept: the envelope, and the trackless `None`.
194 let answer = peaks_over(path, stream, buckets_per_sec, None)?;
195 let entry = match answer {
196 None => MemoEntry::NoTrack,
197 Some(peaks) => MemoEntry::Envelope(SharedPeaks::new(peaks)),
198 };
199 // The handle the caller gets is the answer itself, whether or not the memo
200 // keeps a copy: an over-the-ceiling envelope is still returned below.
201 let handle = entry.envelope();
202 let mut guard = peaks_memo().lock().unwrap();
203 let (memo, count) = &mut *guard;
204 memoize(memo, count, cap, key, entry);
205 Ok(handle)
206}
207
208/// What a memo holds a bucket count of. Both memos below are ceilinged in
209/// *buckets*, so every entry has to say how many it brings -- and one
210/// arithmetic serves both rather than two that can drift apart.
211trait Bucketed {
212 fn buckets(&self) -> usize;
213}
214
215impl Bucketed for MemoEntry {
216 fn buckets(&self) -> usize {
217 match self {
218 MemoEntry::Envelope(shared) => shared.len(),
219 MemoEntry::NoTrack => 0,
220 }
221 }
222}
223
224impl Bucketed for SharedPeaks {
225 fn buckets(&self) -> usize {
226 self.len()
227 }
228}
229
230/// Record `entry` under `key` in `memo`, keeping `count` equal to the buckets
231/// the map holds. The arithmetic is what keeps the ceiling a ceiling:
232///
233/// - an entry bigger than `cap` is not held at all -- keeping it would put the
234/// count permanently over the ceiling, so the next ask of any *other* key
235/// would clear the map and drop it, and this source would pay a whole-file
236/// decode per rebuild anyway. The caller keeps the handle it was handed;
237/// - when the new entry would take the count past `cap`, the map is emptied
238/// rather than evicted one entry at a time (the entries are large);
239/// - an insert that replaces an entry the count already includes subtracts the
240/// replaced length first, so the racing-workers case -- two workers that
241/// missed one key each decode and insert it -- does not leave the count high
242/// for good: only a clear resets it, and a high count makes later asks clear
243/// early, dropping entries that then pay a whole-file decode to be rebuilt.
244fn memoize<K: std::hash::Hash + Eq, V: Bucketed>(
245 memo: &mut std::collections::HashMap<K, V>,
246 count: &mut usize,
247 cap: usize,
248 key: K,
249 entry: V,
250) {
251 let len = entry.buckets();
252 if len > cap {
253 return;
254 }
255 if *count + len > cap {
256 memo.clear();
257 *count = 0;
258 }
259 if let Some(previous) = memo.insert(key, entry) {
260 *count -= previous.buckets();
261 }
262 *count += len;
263}
264
265/// How much sound one window of an over-the-ceiling source covers: 30 s at the
266/// visualizer's 4000 buckets a second is 120k buckets, a megabyte, against the
267/// 230 MB the whole of a two-hour film's envelope is.
268const VIZ_WINDOW_SECS: f64 = 30.0;
269
270/// Decoded past each end of that window. A seek lands where it lands (a
271/// standalone mp3's pre-roll is 8192 samples), so the first and last buckets of
272/// a window's own decode can hold part of a bucket the neighbouring window
273/// covers too; three seconds either side keeps those edges well clear of the
274/// two-second window a frame actually asks for.
275const VIZ_WINDOW_SEEK_SECS: f64 = 3.0;
276
277/// How many buckets the window memo holds before it gives them back: 4M
278/// buckets is 32 MB, some thirty windows -- fifteen minutes of sound about the
279/// playhead, for every source in the session together, against the eight
280/// million a single film's envelope would want. Past it the map is emptied
281/// rather than evicted one window at a time: the paint slides forward, so the
282/// window it is in is the one worth losing last, and re-decoding it is a second
283/// of sound rather than two hours.
284const VIZ_WINDOW_MEMO_BUCKETS: usize = 4 << 20;
285
286/// The loudest bucket of an envelope: what a visualizer column is scaled by
287/// ([`crate::decode::visualizer_i420`]), and therefore a property of the
288/// *whole* file -- a window that derived it from itself would rescale every
289/// column as it slid.
290pub(crate) fn peak_of(peaks: &[(f32, f32)]) -> f32 {
291 peaks
292 .iter()
293 .map(|&(lo, hi)| lo.abs().max(hi.abs()))
294 .fold(0.0f32, f32::max)
295}
296
297/// What a visualizer frame needs from the whole file, in two scalars: how many
298/// samples it carries, and the loudest of them. Neither depends on the
299/// bucketing -- a bucket is as loud as the loudest sample in it, and a sample
300/// lands in the last bucket whatever that bucket is -- so both come off one
301/// pass that keeps no buckets at all ([`viz_summary`]). A film's two hours at
302/// 4000 buckets a second is 230 MB of pairs; this is sixteen bytes of it.
303pub(crate) struct VizSummary {
304 /// One past the file's last sample, counted from its first audible one --
305 /// the same arithmetic [`fold`] counts buckets with.
306 samples: u64,
307 /// The rate those samples were counted at, which is what turns an ask's
308 /// buckets-per-second into samples per bucket. Carried here because the
309 /// summary outlives the probe that read it.
310 sample_rate: u32,
311 /// The file's loudest sample, clamped to full scale like every bucket
312 /// value.
313 pub(crate) peak: f32,
314}
315
316impl VizSummary {
317 /// The file's length in buckets of `per_bucket` samples: what
318 /// `peaks.len()` would have been. `fold` puts a sample in
319 /// `(sample / per_bucket)` truncated, so the last sample decides the last
320 /// bucket -- and a file with no samples has none.
321 fn buckets(&self, per_bucket: f64) -> usize {
322 if self.samples == 0 {
323 return 0;
324 }
325 ((self.samples - 1) as f64 / per_bucket) as usize + 1
326 }
327}
328
329/// The visualizer seat's envelope: what a picture of a clip is painted from.
330///
331/// The seat is re-opened on every look edit and every seek, so the second ask
332/// has to be a refcount. For a source whose whole envelope the memo holds -- a
333/// song's, a short clip's -- [`peaks_shared_capped`] answers exactly that. A
334/// film's is past the memo's ceiling and never held, and what the seat asks for
335/// one is a *window* of it about the frame's own time, which is all a
336/// two-second picture reads, plus the pass that reads the whole file's two
337/// scalars once ([`VizSummary`]).
338pub(crate) enum VizEnvelope {
339 /// No audio track -- and what the seat falls back to when the ask itself
340 /// fails: a frame always exists, and is never worth failing a span over.
341 Silent,
342 /// The memo holds the whole envelope: the same slice every frame, as it
343 /// always was.
344 Whole(SharedPeaks),
345 /// Past the ceiling: the file's two scalars, and one window of it at a time.
346 Windowed(VizWindows),
347}
348
349impl VizEnvelope {
350 /// The envelope the frame at `t_secs` is painted from: the whole of it, or
351 /// the window `t_secs` falls in -- decoded once per window per process.
352 pub(crate) fn view_at(&mut self, t_secs: f64) -> crate::decode::VizView<'_> {
353 match self {
354 Self::Silent => crate::decode::VizView::whole(&[]),
355 Self::Whole(shared) => crate::decode::VizView::whole(shared.as_slice()),
356 Self::Windowed(windows) => windows.view_at(t_secs),
357 }
358 }
359}
360
361/// One source's windows, and the window the paint is in.
362pub(crate) struct VizWindows {
363 /// The ask: file, stream and rate, so a window of the same source asked at
364 /// two rates is two windows.
365 key: PeaksKey,
366 /// The rate the ask named, in buckets per second. The file's own rate is in
367 /// the summary; this and the two of them make samples per bucket, and the
368 /// ask is what turns a frame's time into buckets and back.
369 buckets_per_sec: u32,
370 summary: std::sync::Arc<VizSummary>,
371 /// The window the last frame was served from, and the window it is: a
372 /// sliding paint asks this thirty times a second, and only a look edit or a
373 /// seek ever moves it to another.
374 current: Option<(usize, SharedPeaks)>,
375}
376
377impl VizWindows {
378 /// Samples per bucket, at the rate this seat asked for.
379 fn per_bucket(&self) -> f64 {
380 per_bucket_of(self.summary.sample_rate, self.buckets_per_sec)
381 }
382
383 /// Buckets per second -- the ask's own rate. A bucket holds a fraction of a
384 /// sample at a rate above the file's, which is exactly why the file's own
385 /// rate has to be the one that divides.
386 fn per_sec(&self) -> f64 {
387 f64::from(self.buckets_per_sec.max(1))
388 }
389
390 /// The window `t_secs` falls in: a *window* of 30 s at a fixed grid, so the
391 /// same second of the same file is the same window whichever seat asks.
392 fn view_at(&mut self, t_secs: f64) -> crate::decode::VizView<'_> {
393 let per_sec = self.per_sec();
394 let total = self.summary.buckets(self.per_bucket());
395 let per_window = (VIZ_WINDOW_SECS * per_sec) as usize;
396 let seek = (VIZ_WINDOW_SEEK_SECS * per_sec) as usize;
397 let t_secs = if t_secs.is_finite() {
398 t_secs.max(0.0)
399 } else {
400 0.0
401 };
402 let first = ((t_secs * per_sec) as usize / per_window) * per_window;
403 // The decode is asked for from the seek margin *below* the window's own
404 // first bucket, and the whole of what it returns is served: `from` is
405 // where the slice starts, absolutely, which is the one thing a caller
406 // cannot recover from the slice itself. The margin is what the frames at
407 // the window's own edges read -- the painter's window is two seconds
408 // wide and centred on the frame -- and it is a *seek* margin rather than
409 // a served one, because a decode's own first and last buckets can hold
410 // part of a bucket the neighbouring window covers too.
411 let from = first.saturating_sub(seek);
412 if first >= total {
413 // Past the end of the file -- which is where a source shorter than
414 // the clip playing it leaves the last frames. Nothing to decode:
415 // the painter measures "past the file" against `total` and draws
416 // silence there, exactly as it did when it held the whole envelope.
417 return crate::decode::VizView::window(&[], first, total, self.summary.peak, per_sec);
418 }
419 if self.current.as_ref().map(|(at, _)| *at) != Some(first) {
420 // A window that will not open keeps the frame's own silence for the
421 // rest of it: the seat is what remembers that, and only while it is
422 // painting in this window -- the memo keeps successes only, so the
423 // next seek (and the next window) asks the file again, and a source
424 // that comes back (a share remounting, a file finishing its write)
425 // paints again. Re-asking every frame instead would hammer a file
426 // that is not there thirty times a second.
427 let window = viz_window(
428 &self.key,
429 self.summary.sample_rate,
430 self.buckets_per_sec,
431 from,
432 per_window + 2 * seek,
433 )
434 .unwrap_or_else(|_| SharedPeaks::new(Vec::new()));
435 self.current = Some((first, window));
436 }
437 let (at, peaks) = self.current.as_ref().expect("just set");
438 debug_assert_eq!(
439 *at, first,
440 "the seat kept a window other than the one it asked for"
441 );
442 crate::decode::VizView::window(peaks.as_slice(), from, total, self.summary.peak, per_sec)
443 }
444}
445
446/// A window's identity: the file it came from, and its own first bucket.
447#[derive(PartialEq, Eq, Hash)]
448struct WindowKey {
449 file: PeaksKey,
450 from: usize,
451}
452
453impl WindowKey {
454 fn of(file: &PeaksKey, from: usize) -> Self {
455 Self {
456 file: file.clone(),
457 from,
458 }
459 }
460}
461
462/// The windows every seat of this process has asked for, and how many buckets
463/// they hold between them.
464fn viz_windows(
465) -> &'static std::sync::Mutex<(std::collections::HashMap<WindowKey, SharedPeaks>, usize)> {
466 static MEMO: std::sync::LazyLock<
467 std::sync::Mutex<(std::collections::HashMap<WindowKey, SharedPeaks>, usize)>,
468 > = std::sync::LazyLock::new(|| std::sync::Mutex::new((std::collections::HashMap::new(), 0)));
469 &MEMO
470}
471
472/// The whole-file scalars every over-the-ceiling source has been measured for,
473/// by the stream's own identity: [`VizSummary`] is sixteen bytes, so this map
474/// is bounded by how many *streams* a session has asked about rather than by
475/// how long they are.
476fn viz_summaries(
477) -> &'static std::sync::Mutex<std::collections::HashMap<PeaksKey, std::sync::Arc<VizSummary>>> {
478 static MEMO: std::sync::LazyLock<
479 std::sync::Mutex<std::collections::HashMap<PeaksKey, std::sync::Arc<VizSummary>>>,
480 > = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));
481 &MEMO
482}
483
484/// Test-only: how many times the visualizer's own ask had to open the file --
485/// a window of an envelope, or one window of a [`viz_summary`] pass. The
486/// second ask for the same window of the same source must not move it.
487#[cfg(test)]
488static VIZ_DECODES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
489
490/// [`VIZ_DECODES`], for a test that measures a delta across its own asks.
491#[cfg(test)]
492fn viz_decodes() -> usize {
493 VIZ_DECODES.load(std::sync::atomic::Ordering::Relaxed)
494}
495
496/// Test-only: how many frames of *sound* the summary pass folded
497/// ([`fold_summary`]); not the window decodes, so a delta across one ask is how
498/// many times over the file's own length that pass read. The windows partition
499/// the file, so a pass is one file's worth -- and a pass that also folded the
500/// ask's whole-file probe would be up to twice that.
501#[cfg(test)]
502static VIZ_FOLDED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
503
504/// [`VIZ_FOLDED`], for a test that measures a delta across its own ask.
505#[cfg(test)]
506fn viz_folded() -> u64 {
507 VIZ_FOLDED.load(std::sync::atomic::Ordering::Relaxed)
508}
509
510/// The visualizer seat's own ask: the whole envelope when the memo holds it,
511/// and otherwise windows of it. Never decoded per frame either way -- the
512/// per-frame cost of a look drag is what this exists to remove.
513pub(crate) fn viz_envelope(
514 path: &Path,
515 stream: usize,
516 buckets_per_sec: u32,
517) -> crate::Result<VizEnvelope> {
518 viz_envelope_capped(path, stream, buckets_per_sec, PEAKS_MEMO_BUCKETS)
519}
520
521/// [`viz_envelope`] against a ceiling a test can drive down to a handful of
522/// buckets, so the windowed route is walked on a five-second fixture. `cap` is
523/// [`PEAKS_MEMO_BUCKETS`] everywhere but in a test.
524pub(crate) fn viz_envelope_capped(
525 path: &Path,
526 stream: usize,
527 buckets_per_sec: u32,
528 cap: usize,
529) -> crate::Result<VizEnvelope> {
530 let key = PeaksKey::of(path, stream, buckets_per_sec);
531 // An answer the memo already holds ends it, without opening anything: a
532 // song's whole envelope, or the stable "no audio track" a silent source
533 // gives.
534 match peaks_memo().lock().unwrap().0.get(&key) {
535 Some(MemoEntry::Envelope(shared)) => {
536 return Ok(VizEnvelope::Whole(SharedPeaks::clone(shared)))
537 }
538 Some(MemoEntry::NoTrack) => return Ok(VizEnvelope::Silent),
539 None => {}
540 }
541 // A source this process has already measured past the ceiling: the summary
542 // is the answer, and it costs an open to have asked for one.
543 let stream_key = PeaksKey::stream_of(path, stream);
544 if let Some(summary) = viz_summaries().lock().unwrap().get(&stream_key) {
545 let summary = std::sync::Arc::clone(summary);
546 return Ok(VizEnvelope::Windowed(VizWindows {
547 key,
548 buckets_per_sec,
549 summary,
550 current: None,
551 }));
552 }
553 // A miss, so the file has to be looked at once. The container's own word
554 // for its length decides which ask this is, before anything is decoded:
555 // what the memo can hold is asked for exactly as it always was, and only
556 // what it cannot is served in windows.
557 let Some((meta, rx)) = open_window(path, stream, 0.0, f64::INFINITY)? else {
558 let mut guard = peaks_memo().lock().unwrap();
559 let (memo, count) = &mut *guard;
560 memoize(memo, count, cap, key, MemoEntry::NoTrack);
561 return Ok(VizEnvelope::Silent);
562 };
563 let per_bucket = per_bucket_of(meta.sample_rate, buckets_per_sec);
564 let fits = match meta.total_samples {
565 // The stated length is the container's, which is a lower bound on what
566 // the decode finds (a tail past it is still drawn), so a file near the
567 // ceiling can turn out larger. The windowed route below catches that.
568 Some(samples) => (samples as f64 / per_bucket) as usize + 1 <= cap,
569 // A length the container does not state cannot be windowed -- neither
570 // by this ask nor by the split inside it. Read exactly as it always
571 // was, and held when it fits.
572 None => true,
573 };
574 if fits {
575 // The receiver the probe opened is dropped here: the whole-file ask
576 // opens its own, which is the only ask this path has ever made.
577 drop(rx);
578 let answer = peaks_shared_capped(path, stream, buckets_per_sec, cap)?;
579 return Ok(match answer {
580 None => VizEnvelope::Silent,
581 Some(shared) if shared.len() > cap => {
582 // The container understated its length, so this ask paid for a
583 // whole envelope it cannot keep. Measure the file off it --
584 // both scalars are exact here -- and hand the seat windows of
585 // it instead, so the *next* rebuild is the cheap one.
586 let summary = std::sync::Arc::new(VizSummary {
587 samples: (shared.len() as f64 * per_bucket) as u64,
588 sample_rate: meta.sample_rate,
589 peak: peak_of(&shared),
590 });
591 viz_summaries()
592 .lock()
593 .unwrap()
594 .insert(stream_key, summary.clone());
595 VizEnvelope::Windowed(VizWindows {
596 key,
597 buckets_per_sec,
598 summary,
599 current: None,
600 })
601 }
602 Some(shared) => VizEnvelope::Whole(shared),
603 });
604 }
605 // Past the ceiling: the file's two scalars off the probe's own window and
606 // its neighbours, then a window of it per painted frame.
607 let summary = viz_summary(path, stream, &meta, rx)?;
608 Ok(VizEnvelope::Windowed(VizWindows {
609 key,
610 buckets_per_sec,
611 summary,
612 current: None,
613 }))
614}
615
616/// The two scalars of [`VizSummary`], read off one pass that keeps no buckets.
617///
618/// The same windows, the same threads and the same opens [`peaks_over`] decodes
619/// a whole envelope with -- `rx` is that ask's own first window, the probe's --
620/// because the peak has to be the peak of the envelope the memo would have
621/// held: a frame scaled by any other number is a different picture. A stop
622/// sample would be the one way to lose a bucket the envelope has (and, with it,
623/// the loudest sample in the file), so there are none here: what the windows
624/// fold between them is everything the file delivers.
625fn viz_summary(
626 path: &Path,
627 stream: usize,
628 meta: &crate::AudioMeta,
629 rx: Receiver<AudioChunk>,
630) -> crate::Result<std::sync::Arc<VizSummary>> {
631 let key = PeaksKey::stream_of(path, stream);
632 if let Some(hit) = viz_summaries().lock().unwrap().get(&key) {
633 return Ok(std::sync::Arc::clone(hit));
634 }
635 let rate = f64::from(meta.sample_rate.max(1));
636 let channels = (meta.channels as usize).max(1);
637 let secs = meta.total_samples.unwrap_or(0) as f64 / rate;
638 let jobs = jobs_for(secs).max(1);
639 let window = secs / jobs as f64;
640 let rest: Vec<_> = (1..jobs)
641 .map(|k| {
642 let path = path.to_path_buf();
643 let start = window * k as f64;
644 let end = match k + 1 == jobs {
645 true => f64::INFINITY,
646 false => window * (k + 1) as f64,
647 };
648 #[cfg(test)]
649 VIZ_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
650 thread::Builder::new().name("waveform".into()).spawn(
651 move || -> crate::Result<(f32, u64)> {
652 match open_window(&path, stream, start, end)? {
653 Some((window_meta, window_rx)) => Ok(fold_summary(
654 window_rx,
655 u64::MAX,
656 (window_meta.channels as usize).max(1),
657 )),
658 None => Ok((0.0, 0)),
659 }
660 },
661 )
662 })
663 .collect::<Result<_, _>>()?;
664 #[cfg(test)]
665 VIZ_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
666 // The first window stops at the joint the second one was told to start at,
667 // exactly as the envelope's own split stops it -- and the windows between
668 // them are the file, so a pass reads it once. Folding this receiver whole
669 // (it is the ask's probe, opened at the file's end) would have every later
670 // window decode the same sound again: measured at 1.5x the file on a
671 // two-window split and 1.875x at the eight-window ceiling, on the critical
672 // path of the first look edit. A window with no joint to stop at -- the only
673 // window there is -- folds everything it is handed, which is what the
674 // single-threaded envelope ask does with it.
675 let stop = match jobs {
676 1 => u64::MAX,
677 _ => (window * rate) as u64,
678 };
679 let (mut peak, mut samples) = fold_summary(rx, stop, channels);
680 for handle in rest {
681 let (part_peak, part_samples) = handle.join().map_err(|_| "waveform worker panicked")??;
682 peak = peak.max(part_peak);
683 samples = samples.max(part_samples);
684 }
685 let summary = std::sync::Arc::new(VizSummary {
686 samples,
687 sample_rate: meta.sample_rate,
688 peak,
689 });
690 viz_summaries()
691 .lock()
692 .unwrap()
693 .insert(key, std::sync::Arc::clone(&summary));
694 Ok(summary)
695}
696
697/// One window of one file's envelope, decoded and kept. A window is what the
698/// memo can hold of a film: thirty seconds of sound about the frame's own time,
699/// so the look edit that re-opens the seat decodes a window rather than the
700/// file, and the *second* edit reads the one the first left.
701fn viz_window(
702 key: &PeaksKey,
703 sample_rate: u32,
704 buckets_per_sec: u32,
705 from: usize,
706 buckets: usize,
707) -> crate::Result<SharedPeaks> {
708 let memo_key = WindowKey::of(key, from);
709 if let Some(hit) = viz_windows().lock().unwrap().0.get(&memo_key) {
710 return Ok(SharedPeaks::clone(hit));
711 }
712 #[cfg(test)]
713 VIZ_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
714 // Both units, from the two rates: `per_bucket` is what the fold counts
715 // samples in, `per_sec` is what a window's own ends are named in -- and a
716 // bucket is a fraction of a *second* over the ask's rate, never of a sample,
717 // whatever either rate is.
718 let per_bucket = per_bucket_of(sample_rate, buckets_per_sec);
719 let per_sec = f64::from(buckets_per_sec.max(1));
720 let start = from as f64 / per_sec;
721 let end = (from + buckets) as f64 / per_sec;
722 let Some((meta, rx)) = open_window(&key.path, key.stream, start, end)? else {
723 // The track the probe found is gone (the file changed under the key):
724 // an empty window, which paints its own stretch of the flat line.
725 return Ok(SharedPeaks::new(Vec::new()));
726 };
727 let channels = (meta.channels as usize).max(1);
728 let peaks = SharedPeaks::new(fold_window(rx, per_bucket, channels, from));
729 let mut guard = viz_windows().lock().unwrap();
730 let (memo, count) = &mut *guard;
731 // The ceiling arithmetic is [`memoize`]'s, on a map whose entries are
732 // windows: an entry bigger than the ceiling is handed back but not held,
733 // and one that replaces another subtracts what it replaced.
734 memoize(
735 memo,
736 count,
737 VIZ_WINDOW_MEMO_BUCKETS,
738 memo_key,
739 SharedPeaks::clone(&peaks),
740 );
741 Ok(peaks)
742}
743
744/// Min/max per bucket of everything `rx` carries, from `from` on: the window's
745/// own first bucket is `from`, and anything the decoder hands over before it --
746/// a seek lands where it lands -- is dropped rather than folded at an index the
747/// window does not have. The *last* bucket is partial too, which is what the
748/// seek margin in [`viz_window`] is for.
749fn fold_window(
750 rx: Receiver<AudioChunk>,
751 per_bucket: f64,
752 channels: usize,
753 from: usize,
754) -> Vec<(f32, f32)> {
755 let mut peaks: Vec<(f32, f32)> = Vec::new();
756 for chunk in rx {
757 for (frame, values) in chunk.samples.chunks(channels).enumerate() {
758 let bucket = ((chunk.start_sample + frame as u64) as f64 / per_bucket) as usize;
759 if bucket < from {
760 continue;
761 }
762 let i = bucket - from;
763 if i >= peaks.len() {
764 peaks.resize(i + 1, (0.0, 0.0));
765 }
766 let slot = &mut peaks[i];
767 for &v in values {
768 let v = v.clamp(-1.0, 1.0);
769 slot.0 = slot.0.min(v);
770 slot.1 = slot.1.max(v);
771 }
772 }
773 }
774 peaks
775}
776
777/// [`fold`]'s two answers without its buckets: the loudest sample the window
778/// carries, and how far the file it came from runs. Clamped and counted
779/// exactly as `fold` clamps and counts them, so the peak of a whole-file pass
780/// is the peak of the whole-file envelope.
781fn fold_summary(rx: Receiver<AudioChunk>, stop_sample: u64, channels: usize) -> (f32, u64) {
782 let (mut peak, mut samples) = (0.0f32, 0u64);
783 for chunk in rx {
784 if chunk.start_sample >= stop_sample {
785 break;
786 }
787 #[cfg(test)]
788 VIZ_FOLDED.fetch_add(
789 (chunk.samples.len() / channels) as u64,
790 std::sync::atomic::Ordering::Relaxed,
791 );
792 samples = samples.max(chunk.start_sample + (chunk.samples.len() / channels) as u64);
793 for &v in &chunk.samples {
794 peak = peak.max(v.clamp(-1.0, 1.0).abs());
795 }
796 }
797 (peak, samples)
798}
799
800/// Samples per bucket. Guarded at one both ways, because a container that does
801/// not state a rate (or states a zero one) would otherwise make this zero,
802/// every sample would land in bucket `usize::MAX`, and the fold's own
803/// `resize(bucket + 1)` would be a length that does not exist. One keeps the
804/// fold total, and `buckets_per_sec` is floored where it is asked for as well.
805fn per_bucket_of(sample_rate: u32, buckets_per_sec: u32) -> f64 {
806 f64::from(sample_rate.max(1)) / f64::from(buckets_per_sec.max(1))
807}
808
809/// [`peaks`] with the split forced to `jobs` windows, which is how a test asks
810/// for the same envelope by both routes.
811fn peaks_over(
812 path: &Path,
813 stream: usize,
814 buckets_per_sec: u32,
815 jobs: Option<usize>,
816) -> crate::Result<Option<Vec<(f32, f32)>>> {
817 let Some((meta, rx)) = open_window(path, stream, 0.0, f64::INFINITY)? else {
818 return Ok(None);
819 };
820 // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a
821 // bucket every few seconds over a long source.
822 let per_bucket = per_bucket_of(meta.sample_rate, buckets_per_sec);
823 let channels = (meta.channels as usize).max(1);
824 let rate = f64::from(meta.sample_rate.max(1));
825 // A track whose length the container does not state cannot be cut into
826 // windows at all: `secs` is 0 and the whole of it is read on this thread,
827 // exactly as it was before there was a split.
828 let secs = meta.total_samples.unwrap_or(0) as f64 / rate;
829 let jobs = jobs.unwrap_or_else(|| jobs_for(secs)).max(1);
830 if jobs == 1 {
831 return Ok(Some(fold(rx, per_bucket, channels, u64::MAX)));
832 }
833 let window = secs / jobs as f64;
834 // Every other window is spawned before this thread folds its own, so they
835 // all decode side by side; each carries its own error home rather than
836 // taking a worker down.
837 let rest: Vec<_> = (1..jobs)
838 .map(|k| {
839 let path = path.to_path_buf();
840 let start = window * k as f64;
841 // The last window runs to the end of the file: `total_samples` is
842 // the container's word for a length, and a tail past it must still
843 // be drawn.
844 let end = match k + 1 == jobs {
845 true => f64::INFINITY,
846 false => window * (k + 1) as f64,
847 };
848 thread::Builder::new().name("waveform".into()).spawn(
849 move || -> crate::Result<Vec<(f32, f32)>> {
850 match open_window(&path, stream, start, end)? {
851 Some((_, rx)) => Ok(fold(rx, per_bucket, channels, u64::MAX)),
852 None => Ok(Vec::new()),
853 }
854 },
855 )
856 })
857 .collect::<Result<_, _>>()?;
858 // This window ends where the next one's decoder was told to start, by the
859 // same arithmetic, so the two meet with no gap; the chunk that straddles the
860 // joint is folded into both and min/max does not double-count.
861 let mut peaks = fold(rx, per_bucket, channels, (window * rate) as u64);
862 for handle in rest {
863 let part = handle.join().map_err(|_| "waveform worker panicked")??;
864 merge(&mut peaks, &part);
865 }
866 Ok(Some(peaks))
867}
868
869/// How many threads a source of `secs` is worth splitting across: one below two
870/// minutes of sound, where the extra opens (a Matroska's is a cluster walk) cost
871/// more than the decode they would save, and never more than the machine has —
872/// nor more than a handful, since an import asks this of every source at once.
873///
874/// corner-cut: that last clause is a ceiling and not a bound — a library import of
875/// twenty films runs as many of these as the background executor has threads,
876/// each with eight of its own. The upgrade path is one pool the waveforms share,
877/// which is also where a "visible range first" order would live.
878fn jobs_for(secs: f64) -> usize {
879 const PER_JOB_SECS: f64 = 60.0;
880 const CEILING: usize = 8;
881 if !secs.is_finite() || secs < 2.0 * PER_JOB_SECS {
882 return 1;
883 }
884 let cores = thread::available_parallelism().map_or(1, |n| n.get());
885 ((secs / PER_JOB_SECS) as usize)
886 .min(cores)
887 .min(CEILING)
888 .max(1)
889}
890
891/// `part` folded into `peaks` bucket for bucket. Both are indexed absolutely,
892/// so this is a straight min/max: an empty bucket is `(0.0, 0.0)` and every
893/// value is clamped to `[-1.0, 1.0]`, which makes the empty pair the identity.
894fn merge(peaks: &mut Vec<(f32, f32)>, part: &[(f32, f32)]) {
895 if part.len() > peaks.len() {
896 peaks.resize(part.len(), (0.0, 0.0));
897 }
898 for (slot, &(lo, hi)) in peaks.iter_mut().zip(part) {
899 slot.0 = slot.0.min(lo);
900 slot.1 = slot.1.max(hi);
901 }
902}
903
904/// One window of one stream, opened the way playback opens it.
905fn open_window(
906 path: &Path,
907 stream: usize,
908 start_secs: f64,
909 end_secs: f64,
910) -> crate::Result<Option<(crate::AudioMeta, Receiver<AudioChunk>)>> {
911 let sources = [(PathBuf::from(path), stream)];
912 AudioSession::open_multi_streams(&sources, &[(Some(0), start_secs, end_secs)])
913}
914
915/// Min/max per bucket of everything `rx` carries, at absolute bucket positions:
916/// `start_sample` counts from the source's own first audible sample whatever
917/// window the session was opened at. Stops at the first chunk beginning at or
918/// past `stop_sample`, and dropping the receiver there is what stops that
919/// window's decoder.
920fn fold(
921 rx: Receiver<AudioChunk>,
922 per_bucket: f64,
923 channels: usize,
924 stop_sample: u64,
925) -> Vec<(f32, f32)> {
926 let mut peaks: Vec<(f32, f32)> = Vec::new();
927 for chunk in rx {
928 if chunk.start_sample >= stop_sample {
929 break;
930 }
931 for (frame, values) in chunk.samples.chunks(channels).enumerate() {
932 let bucket = ((chunk.start_sample + frame as u64) as f64 / per_bucket) as usize;
933 if bucket >= peaks.len() {
934 peaks.resize(bucket + 1, (0.0, 0.0));
935 }
936 let slot = &mut peaks[bucket];
937 for &v in values {
938 let v = v.clamp(-1.0, 1.0);
939 slot.0 = slot.0.min(v);
940 slot.1 = slot.1.max(v);
941 }
942 }
943 }
944 peaks
945}
946
947#[cfg(test)]
948mod tests {
949 use std::path::PathBuf;
950
951 use super::{
952 memo_decodes, memoize, peak_of, peaks, peaks_over, peaks_shared_capped, viz_decodes,
953 viz_envelope, viz_envelope_capped, viz_folded, MemoEntry, PeaksKey, PeaksMemo, SharedPeaks,
954 PEAKS_MEMO_BUCKETS,
955 };
956
957 const BPS: u32 = 10;
958
959 /// The memo's own ask, as the seat's used to be: a ceiling a test does not
960 /// want to think about is the process's.
961 fn peaks_shared(
962 path: &std::path::Path,
963 stream: usize,
964 buckets_per_sec: u32,
965 ) -> crate::Result<Option<SharedPeaks>> {
966 peaks_shared_capped(path, stream, buckets_per_sec, PEAKS_MEMO_BUCKETS)
967 }
968
969 fn asset(name: &str) -> PathBuf {
970 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
971 .join("../../assets")
972 .join(name)
973 }
974
975 /// A private copy of a fixture, so the memo key a test drives is not one
976 /// another test in this binary may already hold.
977 fn copy_of(name: &str, tag: &str) -> PathBuf {
978 let path =
979 std::env::temp_dir().join(format!("edith-peaks-{tag}-{}.mp4", std::process::id()));
980 std::fs::write(&path, std::fs::read(asset(name)).expect("read the fixture"))
981 .expect("write the copy");
982 path
983 }
984
985 /// One test at a time, for the whole module.
986 ///
987 /// Three of the seams these tests read -- [`MEMO_DECODES`], [`VIZ_DECODES`]
988 /// and [`VIZ_FOLDED`] -- are process-wide, so "the second ask decoded
989 /// nothing" is a claim about every test in this binary at once. Without this
990 /// lock it holds only when the suite is run the way it is documented to be
991 /// run (`--test-threads=1`); under `cargo test`'s own parallel default a
992 /// pass belonging to a test running beside this one lands inside the delta,
993 /// and the claim fails for a reason that has nothing to do with the code
994 /// ([`a_summary_pass_folds_the_file_once`] and the parent revision's
995 /// [`an_envelope_over_the_ceiling_is_not_held`] are both red that way).
996 ///
997 /// Every test in the module takes it, not only the readers: a test that
998 /// *decodes* moves the counters the readers are measuring. The cost is that
999 /// this module's tests do not run in parallel with each other -- they are the
1000 /// fixture-heavy ones, and the suite runs them serially anyway. Keying each
1001 /// counter by the file it was for would buy the parallelism back, and is the
1002 /// upgrade path if this lock ever shows up in a profile.
1003 fn counters_serial() -> std::sync::MutexGuard<'static, ()> {
1004 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1005 // A poisoned lock is another test's panic, not this one's failure: the
1006 // counters are still readable and mutual exclusion is the whole point.
1007 LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
1008 }
1009
1010 #[test]
1011 fn peaks_follow_the_1hz_volume_pulse() {
1012 let _serial = counters_serial();
1013 let peaks = peaks(asset("test_av.mp4"), 0, BPS)
1014 .expect("open")
1015 .expect("test_av.mp4 has an audio track");
1016 // 5 s of source; the container's tail padding may spill one bucket.
1017 let want = 5 * BPS as usize;
1018 assert!(
1019 peaks.len().abs_diff(want) <= 1,
1020 "{} buckets, want {want} +/-1",
1021 peaks.len()
1022 );
1023
1024 for (i, &(lo, hi)) in peaks.iter().enumerate() {
1025 assert!(
1026 (-1.0..=0.0).contains(&lo) && (0.0..=1.0).contains(&hi),
1027 "bucket {i} is ({lo}, {hi})"
1028 );
1029 }
1030
1031 // The fixture's envelope is 0.5 + 0.5*sin(2*PI*t): a full silence every
1032 // second at t = 0.75, a full-scale peak at t = 0.25. So every second's
1033 // quietest bucket must be the 8th (t in [0.7, 0.8)) — a bucketing that
1034 // was off by a scale factor or dropped chunk positions would not line
1035 // the dips up second after second.
1036 for second in 0..5 {
1037 let band = &peaks[second * BPS as usize..][..BPS as usize];
1038 let level = |&(lo, hi): &(f32, f32)| hi - lo;
1039 let quietest = (0..band.len())
1040 .min_by(|&a, &b| level(&band[a]).total_cmp(&level(&band[b])))
1041 .expect("non-empty band");
1042 assert!(
1043 (6..=8).contains(&quietest),
1044 "second {second}: dip at bucket {quietest}, want 7 +/-1"
1045 );
1046 // Depth as a ratio, not an absolute: the fixture's sines sit around
1047 // an eighth of full scale, and that is the encoder's business.
1048 let (dip, loudest) = (
1049 level(&band[quietest]),
1050 band.iter().map(level).fold(0.0, f32::max),
1051 );
1052 assert!(loudest > 0.05, "second {second}: peak level only {loudest}");
1053 assert!(
1054 dip < 0.1 * loudest,
1055 "second {second}: dip {dip} against peak {loudest}, want near silence"
1056 );
1057 }
1058 }
1059
1060 /// A song's clip draws like any other: this goes through the same
1061 /// `open_multi_streams` the timeline plays with, which reads a standalone
1062 /// audio file on stream 0 as readily as an mp4's AAC track.
1063 #[test]
1064 fn a_standalone_audio_file_has_peaks_too() {
1065 let _serial = counters_serial();
1066 let peaks = peaks(asset("test_tone.mp3"), 0, BPS)
1067 .expect("open")
1068 .expect("test_tone.mp3 is audio");
1069 let want = 3 * BPS as usize; // 3 s of tone, mp3 padding may spill one
1070 assert!(
1071 peaks.len().abs_diff(want) <= 2,
1072 "{} buckets, want {want} +/-2",
1073 peaks.len()
1074 );
1075 // The fixture carries the A/V one's 1 Hz envelope, so the middle second
1076 // has a dip and a peak. As a ratio, and a looser one: the tone sits
1077 // around an eighth of full scale and mp3 does not preserve a true zero.
1078 let level = |&(lo, hi): &(f32, f32)| hi - lo;
1079 let band = &peaks[BPS as usize..][..BPS as usize];
1080 let dip = band.iter().map(level).fold(f32::MAX, f32::min);
1081 let loudest = band.iter().map(level).fold(0.0, f32::max);
1082 assert!(loudest > 0.05, "peak level only {loudest}");
1083 assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}");
1084 }
1085
1086 /// The shape the ask came from: a film in an mkv with a 5.1 AAC track,
1087 /// which no symphonia decoder takes (`aac: aac too complex`) and which
1088 /// therefore reaches the lane through `ec-aac` and the stereo fold. A
1089 /// clip of one draws a waveform like any other -- an envelope that is not
1090 /// flat -- rather than the empty band a silent file makes.
1091 #[test]
1092 fn a_five_one_aac_mkv_draws_an_envelope() {
1093 let _serial = counters_serial();
1094 let peaks = peaks(asset("test_hevc10.mkv"), 0, BPS)
1095 .expect("the 5.1 AAC track decodes")
1096 .expect("test_hevc10.mkv has an audio track");
1097 let want = 2 * BPS as usize; // 2 s of tones
1098 assert!(
1099 peaks.len().abs_diff(want) <= 2,
1100 "{} buckets, want {want} +/-2",
1101 peaks.len()
1102 );
1103 // Six tones, one per channel, folded to stereo: every bucket carries
1104 // signal, and a decode that came out silent (or clipped to a rail) is
1105 // exactly what this refuses.
1106 for (i, &(lo, hi)) in peaks.iter().enumerate() {
1107 assert!(
1108 (0.02..2.0).contains(&(hi - lo)),
1109 "bucket {i} is ({lo}, {hi})"
1110 );
1111 }
1112 }
1113
1114 /// The split is an optimisation and nothing else: four windows decoded side
1115 /// by side draw the very envelope the single-threaded walk draws, bucket for
1116 /// bucket. The joints are where a window that started a sample late or
1117 /// stopped a chunk early would show, so this is the check that a film's
1118 /// waveform is still the film's.
1119 #[test]
1120 fn a_split_decode_draws_the_same_envelope() {
1121 let _serial = counters_serial();
1122 let file = asset("test_av.mp4");
1123 let whole = peaks_over(&file, 0, BPS, Some(1))
1124 .expect("open")
1125 .expect("test_av.mp4 has an audio track");
1126 let split = peaks_over(&file, 0, BPS, Some(4))
1127 .expect("open")
1128 .expect("test_av.mp4 has an audio track");
1129 assert_eq!(whole.len(), split.len(), "the split lost or grew buckets");
1130 // Not bit-equality: a window seeks into the middle of an AAC stream and
1131 // its filterbank is primed from a preceding packet rather than carried
1132 // over, so a bucket can land a ten-thousandth away. A lane is drawn a
1133 // hundred pixels tall, where that is a thousandth of a pixel; a window
1134 // that started late or stopped early is off by whole tenths and is what
1135 // this catches.
1136 for (i, (w, s)) in whole.iter().zip(&split).enumerate() {
1137 assert!(
1138 (w.0 - s.0).abs() < 1e-3 && (w.1 - s.1).abs() < 1e-3,
1139 "bucket {i}: whole {w:?}, split {s:?}"
1140 );
1141 }
1142 }
1143
1144 #[test]
1145 fn video_only_source_has_no_peaks() {
1146 let _serial = counters_serial();
1147 assert!(peaks(asset("test_baseline.mp4"), 0, BPS)
1148 .expect("open")
1149 .is_none());
1150 }
1151
1152 /// Two streams of one file are two envelopes: the lane draws what the clip
1153 /// actually plays, so a cache keyed on the path alone would be a lie the
1154 /// user can see. Stream 1 of the fixture is 2 s of 220 Hz mono against
1155 /// stream 0's 4-second-long pulsed stereo pair.
1156 #[test]
1157 fn each_stream_of_a_file_has_its_own_envelope() {
1158 let _serial = counters_serial();
1159 let multi = asset("test_multiaudio.mp4");
1160 let zero = peaks(&multi, 0, BPS).expect("open").expect("stream 0");
1161 let one = peaks(&multi, 1, BPS).expect("open").expect("stream 1");
1162 assert!(!zero.is_empty() && !one.is_empty());
1163 // Bucket for bucket, not merely somewhere: a cache keyed on the path
1164 // alone would hand the lane the *first* stream's shape for both, and
1165 // that is what this refuses.
1166 assert_ne!(zero, one, "both streams drew the same envelope");
1167 assert_ne!(zero[0], one[0], "...and they differ from the first bucket");
1168 // Stream 2 is AC-3, and it decodes now: it draws its own envelope like
1169 // any other stream rather than being refused.
1170 let two = peaks(&multi, 2, BPS)
1171 .expect("AC-3 opens")
1172 .expect("stream 2");
1173 assert!(!two.is_empty(), "the AC-3 stream drew nothing");
1174 }
1175
1176 /// The memo is keyed on the *ask*, not on the file: a second visualizer
1177 /// rebuild of one source reuses the envelope, and one of another stream is
1178 /// decoded rather than handed the first one's -- the lie
1179 /// [`each_stream_of_a_file_has_its_own_envelope`] refuses, one cache layer
1180 /// down, where the visualizer seat reads it.
1181 #[test]
1182 fn the_shared_memo_answers_per_stream() {
1183 let _serial = counters_serial();
1184 let multi = asset("test_multiaudio.mp4");
1185 let zero = peaks_shared(&multi, 0, BPS)
1186 .expect("open")
1187 .expect("stream 0");
1188 let again = peaks_shared(&multi, 0, BPS)
1189 .expect("open")
1190 .expect("stream 0, second ask");
1191 // Shared, not decoded again -- which is the whole of what the second
1192 // visualizer rebuild saves.
1193 assert!(
1194 std::sync::Arc::ptr_eq(&zero, &again),
1195 "the second ask decoded the file again"
1196 );
1197 // ...and the very envelope a plain ask draws, so nothing is served
1198 // through the memo that the decoder would not have said.
1199 let plain = peaks(&multi, 0, BPS).expect("open").expect("stream 0");
1200 assert_eq!(*zero, plain);
1201 let one = peaks_shared(&multi, 1, BPS)
1202 .expect("open")
1203 .expect("stream 1");
1204 assert_ne!(*zero, *one, "a stream took another's memo entry");
1205 }
1206
1207 /// A source replaced on disk is read again: the key carries the file's own
1208 /// stat, so the memo cannot paint the old file's envelope for a clip that
1209 /// no longer plays it. Asked of a *copy*, because the fixtures are
1210 /// read-only for every other test in this binary.
1211 #[test]
1212 fn a_replaced_source_is_read_again() {
1213 let _serial = counters_serial();
1214 let path =
1215 std::env::temp_dir().join(format!("edith-peaks-memo-{}.mp4", std::process::id()));
1216 let short = std::fs::read(asset("test_multiaudio.mp4")).expect("read the fixture");
1217 let long = std::fs::read(asset("test_av.mp4")).expect("read the fixture");
1218 // The two halves below are the length half and the clock half of the
1219 // key, so their sizes have to differ for the first of them to be it.
1220 assert_ne!(short.len(), long.len(), "fixtures must differ in length");
1221
1222 std::fs::write(&path, &short).expect("write the copy");
1223 let first = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
1224 let again = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
1225 assert!(
1226 std::sync::Arc::ptr_eq(&first, &again),
1227 "the copy was not memoized"
1228 );
1229
1230 // Other bytes behind the same path. A key without the file's length
1231 // (or without any stat at all) serves `first` here -- the envelope of
1232 // bytes that are gone.
1233 std::fs::write(&path, &long).expect("rewrite the copy");
1234 let replaced = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
1235 assert_ne!(
1236 *replaced, *first,
1237 "the memo served the replaced file's envelope"
1238 );
1239 assert_eq!(
1240 *replaced,
1241 peaks(&path, 0, BPS).expect("open").expect("copy"),
1242 "the memo's answer is not what a plain ask draws"
1243 );
1244
1245 // The *same* bytes written again: same length, a newer clock. Resolution
1246 // is the filesystem's, so give it a moment to move.
1247 std::thread::sleep(std::time::Duration::from_millis(20));
1248 std::fs::write(&path, &long).expect("touch the copy");
1249 let touched = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
1250 assert_eq!(*touched, *replaced);
1251 // A key with length but no mtime hands the old handle back -- for a file
1252 // that changed under it, which is the serve the mtime is in the key for.
1253 assert!(
1254 !std::sync::Arc::ptr_eq(&replaced, &touched),
1255 "the mtime is not part of the key"
1256 );
1257
1258 let _ = std::fs::remove_file(&path);
1259 }
1260
1261 /// A trackless source is an answer too, and the memo keeps it: without that
1262 /// a visualizer clip on a silent source re-opens the container on every
1263 /// picture rebuild -- the whole cost the memo exists to remove, paid once
1264 /// per look edit. Proved by counting decodes: the second ask must not take
1265 /// one. A copy is used so the key is this test's alone.
1266 #[test]
1267 fn a_trackless_source_is_memoized_too() {
1268 let _serial = counters_serial();
1269 let path = copy_of("test_baseline.mp4", "none");
1270
1271 let before = memo_decodes(&path, 0, BPS);
1272 let first = peaks_shared(&path, 0, BPS).expect("open");
1273 assert!(first.is_none(), "test_baseline.mp4 has no audio track");
1274 let after_first = memo_decodes(&path, 0, BPS);
1275 assert_eq!(after_first - before, 1, "the first ask did not decode");
1276
1277 let second = peaks_shared(&path, 0, BPS).expect("open");
1278 assert!(second.is_none());
1279 assert_eq!(
1280 memo_decodes(&path, 0, BPS),
1281 after_first,
1282 "the second ask re-opened a trackless source"
1283 );
1284
1285 let _ = std::fs::remove_file(&path);
1286 }
1287
1288 /// A trackless answer holds no buckets, so the ceiling counts only
1289 /// envelopes -- and a source that gains an audio track (a re-encode) swaps
1290 /// the `NoTrack` entry for an envelope without stranding the old count.
1291 #[test]
1292 fn a_trackless_answer_holds_no_buckets() {
1293 let _serial = counters_serial();
1294 let mut memo = PeaksMemo::new();
1295 let mut count = 0;
1296 let key = || PeaksKey::of(std::path::Path::new("edith-peaks-none-key"), 0, BPS);
1297
1298 memoize(&mut memo, &mut count, 100, key(), MemoEntry::NoTrack);
1299 assert_eq!(count, 0, "a trackless answer counted buckets");
1300 assert!(memo.contains_key(&key()));
1301
1302 memoize(
1303 &mut memo,
1304 &mut count,
1305 100,
1306 key(),
1307 MemoEntry::Envelope(SharedPeaks::new(vec![(0.0, 0.0); 4])),
1308 );
1309 assert_eq!(count, 4, "the envelope did not replace the trackless count");
1310 }
1311
1312 /// An envelope larger than the ceiling is handed to the caller but never
1313 /// held, so a clear can always bring the memo back under the ceiling. The
1314 /// real ceiling is 8M buckets (~35 min at 10/s), unreachable from a
1315 /// fixture, so this drives the same code through a ceiling of ten buckets
1316 /// against a five-second source (about fifty buckets). Covers: the
1317 /// over-the-ceiling *decision* and the caller-still-gets-its-handle half.
1318 /// Does not cover: an end-to-end decode past eight million buckets.
1319 #[test]
1320 fn an_envelope_over_the_ceiling_is_not_held() {
1321 let _serial = counters_serial();
1322 let file = copy_of("test_av.mp4", "over");
1323 let before = memo_decodes(&file, 0, BPS);
1324 let first = peaks_shared_capped(&file, 0, BPS, 10)
1325 .expect("open")
1326 .expect("test_av.mp4 has an audio track");
1327 assert!(first.len() > 10, "the fixture must exceed the test ceiling");
1328 let mid = memo_decodes(&file, 0, BPS);
1329 assert_eq!(mid - before, 1, "the first ask did not decode");
1330
1331 let second = peaks_shared_capped(&file, 0, BPS, 10)
1332 .expect("open")
1333 .expect("test_av.mp4 has an audio track");
1334 assert_eq!(*first, *second, "the caller did not get its envelope");
1335 assert_eq!(
1336 memo_decodes(&file, 0, BPS) - mid,
1337 1,
1338 "an envelope over the ceiling was held"
1339 );
1340
1341 let _ = std::fs::remove_file(&file);
1342 }
1343
1344 /// An insert that replaces an entry the counter already includes subtracts
1345 /// the replaced length: the racing-workers case, where two workers that
1346 /// missed one key each decode and insert it. The count follows what the map
1347 /// *holds*, so a missing subtraction leaves it high for good -- only a
1348 /// clear resets it, and later asks then clear early, dropping entries that
1349 /// pay a whole-file decode to be rebuilt. Driven through the same [`memoize`]
1350 /// the ask path uses (a second *ask* on one key hits the memo, so it cannot
1351 /// reach the insert): without the subtraction the second insert would read
1352 /// 3 + 5 = 8.
1353 #[test]
1354 fn replacing_an_entry_subtracts_the_old_buckets() {
1355 let _serial = counters_serial();
1356 let mut memo = PeaksMemo::new();
1357 let mut count = 0;
1358 let key = || PeaksKey::of(std::path::Path::new("edith-peaks-replace-key"), 0, BPS);
1359
1360 memoize(
1361 &mut memo,
1362 &mut count,
1363 100,
1364 key(),
1365 MemoEntry::Envelope(SharedPeaks::new(vec![(0.0, 0.0); 3])),
1366 );
1367 assert_eq!(count, 3, "the first insert was not counted");
1368
1369 memoize(
1370 &mut memo,
1371 &mut count,
1372 100,
1373 key(),
1374 MemoEntry::Envelope(SharedPeaks::new(vec![(0.0, 0.0); 5])),
1375 );
1376 assert_eq!(count, 5, "the replaced entry's buckets were not subtracted");
1377 assert_eq!(memo.len(), 1, "the replace added a second entry");
1378 }
1379
1380 /// A window is where it says it is: on a fixture whose envelope is *not*
1381 /// periodic, so a slice labelled a margin below where it starts cannot hide.
1382 /// A sine hides it -- a shift by a whole number of periods leaves every
1383 /// bucket identical, which is exactly how a +3 s mislabel survived a 440 Hz
1384 /// fixture at 8 kHz (3 s is 1320 whole periods) -- so this is noise, in
1385 /// FLAC (a seek lands on the sample, so the buckets must be *equal*, not
1386 /// merely close).
1387 ///
1388 /// Every place a window can go wrong: the file's head, its middle, both
1389 /// sides of a 30 s grid line, and the last window it has. At each: every
1390 /// bucket a two-second picture can reach is the envelope's, and the frame is
1391 /// byte for byte the one the *export* path paints from the whole envelope
1392 /// ([`crate::decode::visualizer_i420`]).
1393 #[test]
1394 fn a_window_of_a_non_periodic_file_is_where_it_says_it_is() {
1395 let _serial = counters_serial();
1396 let path =
1397 std::env::temp_dir().join(format!("edith-peaks-noise-{}.flac", std::process::id()));
1398 let generated = std::process::Command::new("ffmpeg")
1399 .args(["-y", "-v", "error", "-f", "lavfi", "-i"])
1400 .arg("anoisesrc=color=white:amplitude=0.5:sample_rate=8000:duration=120")
1401 .args(["-c:a", "flac"])
1402 .arg(&path)
1403 .status()
1404 .map(|status| status.success() && path.exists())
1405 .unwrap_or(false);
1406 if !generated {
1407 eprintln!("no ffmpeg: a non-periodic fixture cannot be generated, skipping");
1408 return;
1409 }
1410 let bps = crate::decode::VIZ_BUCKETS_PER_SEC;
1411 let per_sec = f64::from(bps);
1412 let plain = peaks(&path, 0, bps)
1413 .expect("open")
1414 .expect("the noise is audio");
1415 assert!(
1416 plain.len().abs_diff(120 * bps as usize) < 100,
1417 "the envelope is {} buckets, not the 120 s it was generated for",
1418 plain.len()
1419 );
1420 let peak = peak_of(&plain);
1421 let mut scratch = crate::decode::VizScratch::default();
1422 for secs in [0.0, 15.0, 29.5, 30.5, 60.0, 89.5, 119.0] {
1423 // A ceiling of a thousand buckets, so the windowed route is the one
1424 // walked (the route is what the real ceiling takes for a film).
1425 let mut seat = viz_envelope_capped(&path, 0, bps, 1000).expect("open");
1426 let view = seat.view_at(secs);
1427 assert!(
1428 !view.peaks.is_empty(),
1429 "t={secs}: the window decoded nothing"
1430 );
1431 assert_eq!(
1432 view.peak, peak,
1433 "t={secs}: the window's peak is not the file's"
1434 );
1435 assert_eq!(
1436 view.total,
1437 plain.len(),
1438 "t={secs}: the length is not the file's"
1439 );
1440 // The buckets the frame at `secs` can reach: a second either way,
1441 // plus the bucket the interpolation reads past the end.
1442 let from = ((secs - 1.0).max(0.0) * per_sec) as usize;
1443 let to = (((secs + 1.0) * per_sec) as usize + 2).min(plain.len());
1444 let (mut compared, mut wrong, mut out_of_reach) = (0, 0, 0);
1445 for abs in from..to {
1446 match (view.at(abs), plain.get(abs)) {
1447 (Some(window), Some(&whole)) => {
1448 compared += 1;
1449 if window != whole {
1450 wrong += 1;
1451 }
1452 }
1453 _ => out_of_reach += 1,
1454 }
1455 }
1456 assert!(
1457 compared > 1000,
1458 "t={secs}: only {compared} buckets were comparable ({out_of_reach} out of reach)"
1459 );
1460 assert_eq!(
1461 (wrong, out_of_reach),
1462 (0, 0),
1463 "t={secs}: {wrong} of {compared} windowed buckets are not the envelope's, \
1464 {out_of_reach} out of reach"
1465 );
1466 let whole = crate::decode::visualizer_i420(&mut scratch, &plain, secs, 320, 180, 0, 5);
1467 let window =
1468 crate::decode::visualizer_window_i420(&mut scratch, &view, secs, 320, 180, 0, 5);
1469 assert_eq!(
1470 whole, window,
1471 "t={secs}: the window painted a frame the whole envelope does not"
1472 );
1473 }
1474 let _ = std::fs::remove_file(&path);
1475 }
1476
1477 /// The summary pass reads the file *once*. Its windows partition it -- the
1478 /// first one stops at the joint the next was told to start at -- so the
1479 /// frames it folds are the file's own, and folding the ask's whole-file
1480 /// probe on top of them (which is what it used to do) is up to twice a file
1481 /// for nothing, on the critical path of the first look edit.
1482 #[test]
1483 fn a_summary_pass_folds_the_file_once() {
1484 let _serial = counters_serial();
1485 let path =
1486 std::env::temp_dir().join(format!("edith-peaks-once-{}.flac", std::process::id()));
1487 let generated = std::process::Command::new("ffmpeg")
1488 .args(["-y", "-v", "error", "-f", "lavfi", "-i"])
1489 .arg("anoisesrc=color=white:amplitude=0.5:sample_rate=8000:duration=120")
1490 .args(["-c:a", "flac"])
1491 .arg(&path)
1492 .status()
1493 .map(|status| status.success() && path.exists())
1494 .unwrap_or(false);
1495 if !generated {
1496 eprintln!("no ffmpeg: a film-length fixture cannot be generated, skipping");
1497 return;
1498 }
1499 let bps = crate::decode::VIZ_BUCKETS_PER_SEC;
1500 let frames = 120 * 8000;
1501 let before = viz_folded();
1502 let mut seat = viz_envelope_capped(&path, 0, bps, 1000).expect("open");
1503 let view = seat.view_at(60.0);
1504 assert!(!view.peaks.is_empty(), "the window decoded nothing");
1505 let folded = viz_folded() - before;
1506 assert!(
1507 folded >= frames - frames / 10,
1508 "the summary pass folded {folded} frames of a {frames}-frame file: it lost a window"
1509 );
1510 assert!(
1511 folded <= frames + frames / 20,
1512 "the summary pass folded {folded} frames of a {frames}-frame file, {:.2}x over",
1513 folded as f64 / frames as f64
1514 );
1515 let _ = std::fs::remove_file(&path);
1516 }
1517
1518 /// A container that states no sample rate (or a zero one) must not make the
1519 /// samples-per-bucket arithmetic zero: `sample / 0.0` is infinite, `as
1520 /// usize` saturates, and the fold's own `resize(bucket + 1)` is then a
1521 /// length that does not exist -- a panic in debug, a wrap and an
1522 /// out-of-bounds index in release. Both asks that bucket samples share the
1523 /// guard, so this is the one arithmetic they both use.
1524 #[test]
1525 fn a_zero_sample_rate_still_buckets_samples() {
1526 let _serial = counters_serial();
1527 // A rate of zero is read as one, and the rate is what divides either
1528 // way, so the arithmetic stays finite and positive.
1529 assert_eq!(super::per_bucket_of(0, 4000), 1.0 / 4000.0);
1530 assert_eq!(super::per_bucket_of(44100, 0), 44100.0);
1531 // ...and a fold over a chunk at that rate is total: one bucket per
1532 // sample rather than an index that does not exist.
1533 let per_bucket = super::per_bucket_of(0, 1);
1534 assert_eq!(per_bucket, 1.0);
1535 let (tx, rx) = std::sync::mpsc::channel();
1536 tx.send(crate::audio::AudioChunk {
1537 start_sample: 0,
1538 samples: vec![0.5; 4],
1539 })
1540 .expect("send");
1541 drop(tx);
1542 let peaks = super::fold(rx, per_bucket, 1, u64::MAX);
1543 assert_eq!(peaks.len(), 4, "the fold lost or invented buckets");
1544 assert_eq!(peaks[0], (0.0, 0.5), "a bucket must still straddle zero");
1545 }
1546
1547 /// The visualizer's ask for a source past the memo's ceiling: the first ask
1548 /// pays one pass for the file's two scalars and one window of it, and every
1549 /// ask after that -- the ones a look drag makes, once per pointer sample at
1550 /// the same playhead -- decodes nothing at all. Driven with a ceiling of ten
1551 /// buckets against a five-second source (fifty buckets), which is the same
1552 /// route the eight-million-bucket ceiling takes for a film.
1553 #[test]
1554 fn a_window_of_an_over_the_ceiling_source_is_decoded_once() {
1555 let _serial = counters_serial();
1556 let file = copy_of("test_av.mp4", "window");
1557 let plain = peaks(&file, 0, BPS).expect("open").expect("audio track");
1558
1559 let before = viz_decodes();
1560 let mut first = viz_envelope_capped(&file, 0, BPS, 10).expect("open");
1561 assert!(
1562 matches!(first, super::VizEnvelope::Windowed(_)),
1563 "the fixture must be past the test ceiling"
1564 );
1565 let view = first.view_at(2.5);
1566 assert!(!view.peaks.is_empty(), "the window decoded nothing");
1567 // The two scalars are the file's own and not an approximation of them:
1568 // the painter's whole-file peak and its "past the end of the file" both
1569 // come from here, and a frame scaled by anything else is another frame.
1570 assert_eq!(
1571 view.peak,
1572 peak_of(&plain),
1573 "the window's peak is not the file's"
1574 );
1575 assert_eq!(
1576 view.total,
1577 plain.len(),
1578 "the windowed length is not the envelope's"
1579 );
1580 let after_first = viz_decodes();
1581 assert!(after_first > before, "the first ask decoded nothing");
1582
1583 // The same second, three more times, the way a drag asks it: a new seat
1584 // every time, and no decode in any of them.
1585 for ask in 0..3 {
1586 let mut again = viz_envelope_capped(&file, 0, BPS, 10).expect("open");
1587 let view = again.view_at(2.5);
1588 assert_eq!(view.total, plain.len());
1589 assert!(
1590 viz_decodes() == after_first,
1591 "ask {} re-decoded a window the memo holds",
1592 ask + 2
1593 );
1594 }
1595 let _ = std::fs::remove_file(&file);
1596 }
1597
1598 /// A window paints the frame the whole envelope paints: the picture of a
1599 /// clip must not change because the seat stopped holding two hours of sound
1600 /// to draw thirty seconds of it. The window here is cut out of the envelope
1601 /// itself, so this is the painter's half of the promise -- both looks, and
1602 /// times from the file's first frame to past its last.
1603 #[test]
1604 fn a_window_paints_the_frame_the_whole_envelope_paints() {
1605 let _serial = counters_serial();
1606 let file = asset("test_av.mp4");
1607 // The painter's own rate: a view carries the rate its envelope
1608 // was drawn at and indexes the slice by it, so this envelope is
1609 // drawn at exactly the rate the painter reads it at -- the
1610 // visualizer's own ([`crate::decode::VIZ_BUCKETS_PER_SEC`]).
1611 let per_sec = f64::from(crate::decode::VIZ_BUCKETS_PER_SEC);
1612 let whole = peaks(&file, 0, crate::decode::VIZ_BUCKETS_PER_SEC)
1613 .expect("open")
1614 .expect("audio track");
1615 let peak = peak_of(&whole);
1616 let mut scratch = crate::decode::VizScratch::default();
1617 for flags in [0u8, crate::decode::VIZ_FAST] {
1618 for secs in [0.0, 0.4, 1.0, 2.5, 4.9, 5.2] {
1619 let whole_frame =
1620 crate::decode::visualizer_i420(&mut scratch, &whole, secs, 320, 180, flags, 7);
1621 // The buckets a two-second picture can reach: a second either
1622 // side of the frame's own time, plus the bucket the
1623 // interpolation reads past it.
1624 let from = ((secs - 1.0).max(0.0) * per_sec) as usize;
1625 let to = (((secs + 1.0) * per_sec) as usize + 2).min(whole.len());
1626 let view = crate::decode::VizView::window(
1627 &whole[from..to],
1628 from,
1629 whole.len(),
1630 peak,
1631 per_sec,
1632 );
1633 let window_frame = crate::decode::visualizer_window_i420(
1634 &mut scratch,
1635 &view,
1636 secs,
1637 320,
1638 180,
1639 flags,
1640 7,
1641 );
1642 assert_eq!(
1643 whole_frame, window_frame,
1644 "the window painted {secs}s (flags {flags}) differently"
1645 );
1646 }
1647 }
1648 }
1649
1650 /// The long source the defect is about: forty minutes of sound, whose own
1651 /// envelope at the visualizer's 4000 buckets a second is 9.6M buckets --
1652 /// past [`PEAKS_MEMO_BUCKETS`], so the memo can never hold it and the
1653 /// windowed route is the only one there is. What a window of it draws is
1654 /// what the whole envelope draws, byte for byte, and the second and third
1655 /// ask decode nothing.
1656 ///
1657 /// The fixture is generated here (`ffmpeg -f lavfi -i
1658 /// sine=frequency=440:duration=2400 -ar 8000 -ac 1 -c:a flac`) and is FLAC
1659 /// on purpose: a seek into a lossless frame lands on the sample, so a
1660 /// window of it holds exactly the buckets the whole-file decode holds --
1661 /// which is the promise a caching change has to keep, and what a lossy
1662 /// codec's seeked filterbank cannot (a bucket lands a ten-thousandth away,
1663 /// as [`a_split_decode_draws_the_same_envelope`] already bounds it). The
1664 /// envelope's own length is asserted against the forty minutes asked for,
1665 /// so a fixture that came out at another scale cannot pass this vacuously.
1666 /// Skipped, loudly, where ffmpeg is not installed.
1667 #[test]
1668 fn a_film_length_source_paints_the_same_frame_in_windows() {
1669 let _serial = counters_serial();
1670 let path =
1671 std::env::temp_dir().join(format!("edith-peaks-long-{}.flac", std::process::id()));
1672 let generated = std::process::Command::new("ffmpeg")
1673 .args(["-y", "-v", "error", "-f", "lavfi", "-i"])
1674 .arg("sine=frequency=440:duration=2400")
1675 .args(["-ar", "8000", "-ac", "1", "-c:a", "flac"])
1676 .arg(&path)
1677 .status()
1678 .map(|status| status.success() && path.exists())
1679 .unwrap_or(false);
1680 if !generated {
1681 eprintln!("no ffmpeg: a film-length fixture cannot be generated, skipping");
1682 return;
1683 }
1684 let bps = crate::decode::VIZ_BUCKETS_PER_SEC;
1685 let plain = peaks(&path, 0, bps)
1686 .expect("open")
1687 .expect("the tone is audio");
1688 let secs = 2400 * bps as usize;
1689 assert!(
1690 plain.len().abs_diff(secs) < 100,
1691 "the envelope is {} buckets, not the 2400 s of sound it was generated for",
1692 plain.len()
1693 );
1694 assert!(
1695 plain.len() > PEAKS_MEMO_BUCKETS,
1696 "{} buckets is not past the memo's ceiling",
1697 plain.len()
1698 );
1699
1700 let before = viz_decodes();
1701 let mut seat = viz_envelope(&path, 0, bps).expect("open");
1702 let t = 1200.0;
1703 let view = seat.view_at(t);
1704 assert!(!view.peaks.is_empty(), "the window decoded nothing");
1705 assert_eq!(
1706 view.peak,
1707 peak_of(&plain),
1708 "the window's peak is not the file's"
1709 );
1710 assert_eq!(
1711 view.total,
1712 plain.len(),
1713 "the windowed length is not the envelope's"
1714 );
1715 // The window's own buckets are the envelope's, bucket for bucket: the
1716 // time the seats ask for in the middle of a film is the time a window
1717 // has to get exactly as right as two hours of decode did.
1718 let mut checked = 0;
1719 for abs in (t * f64::from(bps)) as usize..((t + 20.0) * f64::from(bps)) as usize {
1720 let (Some(window), Some(&whole)) = (view.at(abs), plain.get(abs)) else {
1721 continue;
1722 };
1723 assert_eq!(window, whole, "bucket {abs} differs from the envelope's");
1724 checked += 1;
1725 }
1726 assert!(checked > 10_000, "only {checked} buckets were compared");
1727
1728 let mut scratch = crate::decode::VizScratch::default();
1729 for secs in [t - 1.0, t, t + 1.0] {
1730 let whole = crate::decode::visualizer_i420(&mut scratch, &plain, secs, 320, 180, 0, 3);
1731 let window =
1732 crate::decode::visualizer_window_i420(&mut scratch, &view, secs, 320, 180, 0, 3);
1733 assert_eq!(whole, window, "the window painted {secs}s differently");
1734 }
1735 let after_first = viz_decodes();
1736 assert!(after_first > before, "the first ask decoded nothing");
1737
1738 // A look drag on a film: a new seat per pointer sample, at the same
1739 // playhead, and not one decode between them.
1740 for ask in 0..3 {
1741 let mut again = viz_envelope(&path, 0, bps).expect("open");
1742 let view = again.view_at(t);
1743 assert_eq!(view.total, plain.len());
1744 assert!(
1745 viz_decodes() == after_first,
1746 "ask {} re-decoded a window the memo holds",
1747 ask + 2
1748 );
1749 }
1750 let _ = std::fs::remove_file(&path);
1751 }
1752}