forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

waveform.rs1760 lines, 77.3 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) < 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).clamp(1, cores.min(CEILING))
886}
887
888/// `part` folded into `peaks` bucket for bucket. Both are indexed absolutely,
889/// so this is a straight min/max: an empty bucket is `(0.0, 0.0)` and every
890/// value is clamped to `[-1.0, 1.0]`, which makes the empty pair the identity.
891fn merge(peaks: &mut Vec<(f32, f32)>, part: &[(f32, f32)]) {
892 if part.len() > peaks.len() {
893 peaks.resize(part.len(), (0.0, 0.0));
894 }
895 for (slot, &(lo, hi)) in peaks.iter_mut().zip(part) {
896 slot.0 = slot.0.min(lo);
897 slot.1 = slot.1.max(hi);
898 }
899}
900
901/// One window of one stream, opened the way playback opens it.
902fn open_window(
903 path: &Path,
904 stream: usize,
905 start_secs: f64,
906 end_secs: f64,
907) -> crate::Result<Option<(crate::AudioMeta, Receiver<AudioChunk>)>> {
908 let sources = [(PathBuf::from(path), stream)];
909 // A waveform draws the file, so it is read at the file's own rate: the
910 // mix rule would read an 8 kHz source at 48 kHz, which is the wrong
911 // number of buckets per second for the picture it is drawn beside.
912 let file_rate = AudioSession::probe_streams(path)?
913 .into_iter()
914 .find(|s| s.index == stream)
915 .map(|s| s.sample_rate)
916 .filter(|rate| *rate > 0);
917 AudioSession::open_multi_streams_speed_at(
918 &sources,
919 &[(Some(0), start_secs, end_secs)],
920 &[],
921 &[],
922 file_rate,
923 )
924}
925
926/// Min/max per bucket of everything `rx` carries, at absolute bucket positions:
927/// `start_sample` counts from the source's own first audible sample whatever
928/// window the session was opened at. Stops at the first chunk beginning at or
929/// past `stop_sample`, and dropping the receiver there is what stops that
930/// window's decoder.
931fn fold(
932 rx: Receiver<AudioChunk>,
933 per_bucket: f64,
934 channels: usize,
935 stop_sample: u64,
936) -> Vec<(f32, f32)> {
937 let mut peaks: Vec<(f32, f32)> = Vec::new();
938 for chunk in rx {
939 if chunk.start_sample >= stop_sample {
940 break;
941 }
942 for (frame, values) in chunk.samples.chunks(channels).enumerate() {
943 let bucket = ((chunk.start_sample + frame as u64) as f64 / per_bucket) as usize;
944 if bucket >= peaks.len() {
945 peaks.resize(bucket + 1, (0.0, 0.0));
946 }
947 let slot = &mut peaks[bucket];
948 for &v in values {
949 let v = v.clamp(-1.0, 1.0);
950 slot.0 = slot.0.min(v);
951 slot.1 = slot.1.max(v);
952 }
953 }
954 }
955 peaks
956}
957
958#[cfg(test)]
959mod tests {
960 use std::path::PathBuf;
961
962 use super::{
963 memo_decodes, memoize, peak_of, peaks, peaks_over, peaks_shared_capped, viz_decodes,
964 viz_envelope, viz_envelope_capped, viz_folded, MemoEntry, PeaksKey, PeaksMemo, SharedPeaks,
965 PEAKS_MEMO_BUCKETS,
966 };
967
968 const BPS: u32 = 10;
969
970 /// The memo's own ask, as the seat's used to be: a ceiling a test does not
971 /// want to think about is the process's.
972 fn peaks_shared(
973 path: &std::path::Path,
974 stream: usize,
975 buckets_per_sec: u32,
976 ) -> crate::Result<Option<SharedPeaks>> {
977 peaks_shared_capped(path, stream, buckets_per_sec, PEAKS_MEMO_BUCKETS)
978 }
979
980 fn asset(name: &str) -> PathBuf {
981 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
982 .join("../../assets")
983 .join(name)
984 }
985
986 /// A private copy of a fixture, so the memo key a test drives is not one
987 /// another test in this binary may already hold.
988 fn copy_of(name: &str, tag: &str) -> crate::scratch::Scratch {
989 let path = crate::scratch::Scratch::file(&format!("ve_peaks_{tag}"), "mp4");
990 std::fs::write(&path, std::fs::read(asset(name)).expect("read the fixture"))
991 .expect("write the copy");
992 path
993 }
994
995 /// One test at a time, for the whole module.
996 ///
997 /// Three of the seams these tests read -- [`MEMO_DECODES`], [`VIZ_DECODES`]
998 /// and [`VIZ_FOLDED`] -- are process-wide, so "the second ask decoded
999 /// nothing" is a claim about every test in this binary at once. Without this
1000 /// lock it holds only when the suite is run the way it is documented to be
1001 /// run (`--test-threads=1`); under `cargo test`'s own parallel default a
1002 /// pass belonging to a test running beside this one lands inside the delta,
1003 /// and the claim fails for a reason that has nothing to do with the code
1004 /// ([`a_summary_pass_folds_the_file_once`] and the parent revision's
1005 /// [`an_envelope_over_the_ceiling_is_not_held`] are both red that way).
1006 ///
1007 /// Every test in the module takes it, not only the readers: a test that
1008 /// *decodes* moves the counters the readers are measuring. The cost is that
1009 /// this module's tests do not run in parallel with each other -- they are the
1010 /// fixture-heavy ones, and the suite runs them serially anyway. Keying each
1011 /// counter by the file it was for would buy the parallelism back, and is the
1012 /// upgrade path if this lock ever shows up in a profile.
1013 fn counters_serial() -> std::sync::MutexGuard<'static, ()> {
1014 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1015 // A poisoned lock is another test's panic, not this one's failure: the
1016 // counters are still readable and mutual exclusion is the whole point.
1017 LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
1018 }
1019
1020 #[test]
1021 fn peaks_follow_the_1hz_volume_pulse() {
1022 let _serial = counters_serial();
1023 let peaks = peaks(asset("test_av.mp4"), 0, BPS)
1024 .expect("open")
1025 .expect("test_av.mp4 has an audio track");
1026 // 5 s of source; the container's tail padding may spill one bucket.
1027 let want = 5 * BPS as usize;
1028 assert!(
1029 peaks.len().abs_diff(want) <= 1,
1030 "{} buckets, want {want} +/-1",
1031 peaks.len()
1032 );
1033
1034 for (i, &(lo, hi)) in peaks.iter().enumerate() {
1035 assert!(
1036 (-1.0..=0.0).contains(&lo) && (0.0..=1.0).contains(&hi),
1037 "bucket {i} is ({lo}, {hi})"
1038 );
1039 }
1040
1041 // The fixture's envelope is 0.5 + 0.5*sin(2*PI*t): a full silence every
1042 // second at t = 0.75, a full-scale peak at t = 0.25. So every second's
1043 // quietest bucket must be the 8th (t in [0.7, 0.8)) — a bucketing that
1044 // was off by a scale factor or dropped chunk positions would not line
1045 // the dips up second after second.
1046 for second in 0..5 {
1047 let band = &peaks[second * BPS as usize..][..BPS as usize];
1048 let level = |&(lo, hi): &(f32, f32)| hi - lo;
1049 let quietest = (0..band.len())
1050 .min_by(|&a, &b| level(&band[a]).total_cmp(&level(&band[b])))
1051 .expect("non-empty band");
1052 assert!(
1053 (6..=8).contains(&quietest),
1054 "second {second}: dip at bucket {quietest}, want 7 +/-1"
1055 );
1056 // Depth as a ratio, not an absolute: the fixture's sines sit around
1057 // an eighth of full scale, and that is the encoder's business.
1058 let (dip, loudest) = (
1059 level(&band[quietest]),
1060 band.iter().map(level).fold(0.0, f32::max),
1061 );
1062 assert!(loudest > 0.05, "second {second}: peak level only {loudest}");
1063 assert!(
1064 dip < 0.1 * loudest,
1065 "second {second}: dip {dip} against peak {loudest}, want near silence"
1066 );
1067 }
1068 }
1069
1070 /// A song's clip draws like any other: this goes through the same
1071 /// `open_multi_streams` the timeline plays with, which reads a standalone
1072 /// audio file on stream 0 as readily as an mp4's AAC track.
1073 #[test]
1074 fn a_standalone_audio_file_has_peaks_too() {
1075 let _serial = counters_serial();
1076 let peaks = peaks(asset("test_tone.mp3"), 0, BPS)
1077 .expect("open")
1078 .expect("test_tone.mp3 is audio");
1079 let want = 3 * BPS as usize; // 3 s of tone, mp3 padding may spill one
1080 assert!(
1081 peaks.len().abs_diff(want) <= 2,
1082 "{} buckets, want {want} +/-2",
1083 peaks.len()
1084 );
1085 // The fixture carries the A/V one's 1 Hz envelope, so the middle second
1086 // has a dip and a peak. As a ratio, and a looser one: the tone sits
1087 // around an eighth of full scale and mp3 does not preserve a true zero.
1088 let level = |&(lo, hi): &(f32, f32)| hi - lo;
1089 let band = &peaks[BPS as usize..][..BPS as usize];
1090 let dip = band.iter().map(level).fold(f32::MAX, f32::min);
1091 let loudest = band.iter().map(level).fold(0.0, f32::max);
1092 assert!(loudest > 0.05, "peak level only {loudest}");
1093 assert!(dip < 0.2 * loudest, "dip {dip} against peak {loudest}");
1094 }
1095
1096 /// The shape the ask came from: a film in an mkv with a 5.1 AAC track,
1097 /// which no symphonia decoder takes (`aac: aac too complex`) and which
1098 /// therefore reaches the lane through `ec-aac` and the stereo fold. A
1099 /// clip of one draws a waveform like any other -- an envelope that is not
1100 /// flat -- rather than the empty band a silent file makes.
1101 #[test]
1102 fn a_five_one_aac_mkv_draws_an_envelope() {
1103 let _serial = counters_serial();
1104 let peaks = peaks(asset("test_hevc10.mkv"), 0, BPS)
1105 .expect("the 5.1 AAC track decodes")
1106 .expect("test_hevc10.mkv has an audio track");
1107 let want = 2 * BPS as usize; // 2 s of tones
1108 assert!(
1109 peaks.len().abs_diff(want) <= 2,
1110 "{} buckets, want {want} +/-2",
1111 peaks.len()
1112 );
1113 // Six tones, one per channel, folded to stereo: every bucket carries
1114 // signal, and a decode that came out silent (or clipped to a rail) is
1115 // exactly what this refuses.
1116 for (i, &(lo, hi)) in peaks.iter().enumerate() {
1117 assert!(
1118 (0.02..2.0).contains(&(hi - lo)),
1119 "bucket {i} is ({lo}, {hi})"
1120 );
1121 }
1122 }
1123
1124 /// The split is an optimisation and nothing else: four windows decoded side
1125 /// by side draw the very envelope the single-threaded walk draws, bucket for
1126 /// bucket. The joints are where a window that started a sample late or
1127 /// stopped a chunk early would show, so this is the check that a film's
1128 /// waveform is still the film's.
1129 #[test]
1130 fn a_split_decode_draws_the_same_envelope() {
1131 let _serial = counters_serial();
1132 let file = asset("test_av.mp4");
1133 let whole = peaks_over(&file, 0, BPS, Some(1))
1134 .expect("open")
1135 .expect("test_av.mp4 has an audio track");
1136 let split = peaks_over(&file, 0, BPS, Some(4))
1137 .expect("open")
1138 .expect("test_av.mp4 has an audio track");
1139 assert_eq!(whole.len(), split.len(), "the split lost or grew buckets");
1140 // Not bit-equality: a window seeks into the middle of an AAC stream and
1141 // its filterbank is primed from a preceding packet rather than carried
1142 // over, so a bucket can land a ten-thousandth away. A lane is drawn a
1143 // hundred pixels tall, where that is a thousandth of a pixel; a window
1144 // that started late or stopped early is off by whole tenths and is what
1145 // this catches.
1146 for (i, (w, s)) in whole.iter().zip(&split).enumerate() {
1147 assert!(
1148 (w.0 - s.0).abs() < 1e-3 && (w.1 - s.1).abs() < 1e-3,
1149 "bucket {i}: whole {w:?}, split {s:?}"
1150 );
1151 }
1152 }
1153
1154 #[test]
1155 fn video_only_source_has_no_peaks() {
1156 let _serial = counters_serial();
1157 assert!(peaks(asset("test_baseline.mp4"), 0, BPS)
1158 .expect("open")
1159 .is_none());
1160 }
1161
1162 /// Two streams of one file are two envelopes: the lane draws what the clip
1163 /// actually plays, so a cache keyed on the path alone would be a lie the
1164 /// user can see. Stream 1 of the fixture is 2 s of 220 Hz mono against
1165 /// stream 0's 4-second-long pulsed stereo pair.
1166 #[test]
1167 fn each_stream_of_a_file_has_its_own_envelope() {
1168 let _serial = counters_serial();
1169 let multi = asset("test_multiaudio.mp4");
1170 let zero = peaks(&multi, 0, BPS).expect("open").expect("stream 0");
1171 let one = peaks(&multi, 1, BPS).expect("open").expect("stream 1");
1172 assert!(!zero.is_empty() && !one.is_empty());
1173 // Bucket for bucket, not merely somewhere: a cache keyed on the path
1174 // alone would hand the lane the *first* stream's shape for both, and
1175 // that is what this refuses.
1176 assert_ne!(zero, one, "both streams drew the same envelope");
1177 assert_ne!(zero[0], one[0], "...and they differ from the first bucket");
1178 // Stream 2 is AC-3, and it decodes now: it draws its own envelope like
1179 // any other stream rather than being refused.
1180 let two = peaks(&multi, 2, BPS)
1181 .expect("AC-3 opens")
1182 .expect("stream 2");
1183 assert!(!two.is_empty(), "the AC-3 stream drew nothing");
1184 }
1185
1186 /// The memo is keyed on the *ask*, not on the file: a second visualizer
1187 /// rebuild of one source reuses the envelope, and one of another stream is
1188 /// decoded rather than handed the first one's -- the lie
1189 /// [`each_stream_of_a_file_has_its_own_envelope`] refuses, one cache layer
1190 /// down, where the visualizer seat reads it.
1191 #[test]
1192 fn the_shared_memo_answers_per_stream() {
1193 let _serial = counters_serial();
1194 let multi = asset("test_multiaudio.mp4");
1195 let zero = peaks_shared(&multi, 0, BPS)
1196 .expect("open")
1197 .expect("stream 0");
1198 let again = peaks_shared(&multi, 0, BPS)
1199 .expect("open")
1200 .expect("stream 0, second ask");
1201 // Shared, not decoded again -- which is the whole of what the second
1202 // visualizer rebuild saves.
1203 assert!(
1204 std::sync::Arc::ptr_eq(&zero, &again),
1205 "the second ask decoded the file again"
1206 );
1207 // ...and the very envelope a plain ask draws, so nothing is served
1208 // through the memo that the decoder would not have said.
1209 let plain = peaks(&multi, 0, BPS).expect("open").expect("stream 0");
1210 assert_eq!(*zero, plain);
1211 let one = peaks_shared(&multi, 1, BPS)
1212 .expect("open")
1213 .expect("stream 1");
1214 assert_ne!(*zero, *one, "a stream took another's memo entry");
1215 }
1216
1217 /// A source replaced on disk is read again: the key carries the file's own
1218 /// stat, so the memo cannot paint the old file's envelope for a clip that
1219 /// no longer plays it. Asked of a *copy*, because the fixtures are
1220 /// read-only for every other test in this binary.
1221 #[test]
1222 fn a_replaced_source_is_read_again() {
1223 let _serial = counters_serial();
1224 let path = crate::scratch::Scratch::file("ve_peaks_memo", "mp4");
1225 let short = std::fs::read(asset("test_multiaudio.mp4")).expect("read the fixture");
1226 let long = std::fs::read(asset("test_av.mp4")).expect("read the fixture");
1227 // The two halves below are the length half and the clock half of the
1228 // key, so their sizes have to differ for the first of them to be it.
1229 assert_ne!(short.len(), long.len(), "fixtures must differ in length");
1230
1231 std::fs::write(&path, &short).expect("write the copy");
1232 let first = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
1233 let again = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
1234 assert!(
1235 std::sync::Arc::ptr_eq(&first, &again),
1236 "the copy was not memoized"
1237 );
1238
1239 // Other bytes behind the same path. A key without the file's length
1240 // (or without any stat at all) serves `first` here -- the envelope of
1241 // bytes that are gone.
1242 std::fs::write(&path, &long).expect("rewrite the copy");
1243 let replaced = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
1244 assert_ne!(
1245 *replaced, *first,
1246 "the memo served the replaced file's envelope"
1247 );
1248 assert_eq!(
1249 *replaced,
1250 peaks(&path, 0, BPS).expect("open").expect("copy"),
1251 "the memo's answer is not what a plain ask draws"
1252 );
1253
1254 // The *same* bytes written again: same length, a newer clock. Resolution
1255 // is the filesystem's, so give it a moment to move.
1256 std::thread::sleep(std::time::Duration::from_millis(20));
1257 std::fs::write(&path, &long).expect("touch the copy");
1258 let touched = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
1259 assert_eq!(*touched, *replaced);
1260 // A key with length but no mtime hands the old handle back -- for a file
1261 // that changed under it, which is the serve the mtime is in the key for.
1262 assert!(
1263 !std::sync::Arc::ptr_eq(&replaced, &touched),
1264 "the mtime is not part of the key"
1265 );
1266 }
1267
1268 /// A trackless source is an answer too, and the memo keeps it: without that
1269 /// a visualizer clip on a silent source re-opens the container on every
1270 /// picture rebuild -- the whole cost the memo exists to remove, paid once
1271 /// per look edit. Proved by counting decodes: the second ask must not take
1272 /// one. A copy is used so the key is this test's alone.
1273 #[test]
1274 fn a_trackless_source_is_memoized_too() {
1275 let _serial = counters_serial();
1276 let path = copy_of("test_baseline.mp4", "none");
1277
1278 let before = memo_decodes(&path, 0, BPS);
1279 let first = peaks_shared(&path, 0, BPS).expect("open");
1280 assert!(first.is_none(), "test_baseline.mp4 has no audio track");
1281 let after_first = memo_decodes(&path, 0, BPS);
1282 assert_eq!(after_first - before, 1, "the first ask did not decode");
1283
1284 let second = peaks_shared(&path, 0, BPS).expect("open");
1285 assert!(second.is_none());
1286 assert_eq!(
1287 memo_decodes(&path, 0, BPS),
1288 after_first,
1289 "the second ask re-opened a trackless source"
1290 );
1291 }
1292
1293 /// A trackless answer holds no buckets, so the ceiling counts only
1294 /// envelopes -- and a source that gains an audio track (a re-encode) swaps
1295 /// the `NoTrack` entry for an envelope without stranding the old count.
1296 #[test]
1297 fn a_trackless_answer_holds_no_buckets() {
1298 let _serial = counters_serial();
1299 let mut memo = PeaksMemo::new();
1300 let mut count = 0;
1301 let key = || PeaksKey::of(std::path::Path::new("edith-peaks-none-key"), 0, BPS);
1302
1303 memoize(&mut memo, &mut count, 100, key(), MemoEntry::NoTrack);
1304 assert_eq!(count, 0, "a trackless answer counted buckets");
1305 assert!(memo.contains_key(&key()));
1306
1307 memoize(
1308 &mut memo,
1309 &mut count,
1310 100,
1311 key(),
1312 MemoEntry::Envelope(SharedPeaks::new(vec![(0.0, 0.0); 4])),
1313 );
1314 assert_eq!(count, 4, "the envelope did not replace the trackless count");
1315 }
1316
1317 /// An envelope larger than the ceiling is handed to the caller but never
1318 /// held, so a clear can always bring the memo back under the ceiling. The
1319 /// real ceiling is 8M buckets (~35 min at 10/s), unreachable from a
1320 /// fixture, so this drives the same code through a ceiling of ten buckets
1321 /// against a five-second source (about fifty buckets). Covers: the
1322 /// over-the-ceiling *decision* and the caller-still-gets-its-handle half.
1323 /// Does not cover: an end-to-end decode past eight million buckets.
1324 #[test]
1325 fn an_envelope_over_the_ceiling_is_not_held() {
1326 let _serial = counters_serial();
1327 let file = copy_of("test_av.mp4", "over");
1328 let before = memo_decodes(&file, 0, BPS);
1329 let first = peaks_shared_capped(&file, 0, BPS, 10)
1330 .expect("open")
1331 .expect("test_av.mp4 has an audio track");
1332 assert!(first.len() > 10, "the fixture must exceed the test ceiling");
1333 let mid = memo_decodes(&file, 0, BPS);
1334 assert_eq!(mid - before, 1, "the first ask did not decode");
1335
1336 let second = peaks_shared_capped(&file, 0, BPS, 10)
1337 .expect("open")
1338 .expect("test_av.mp4 has an audio track");
1339 assert_eq!(*first, *second, "the caller did not get its envelope");
1340 assert_eq!(
1341 memo_decodes(&file, 0, BPS) - mid,
1342 1,
1343 "an envelope over the ceiling was held"
1344 );
1345 }
1346
1347 /// An insert that replaces an entry the counter already includes subtracts
1348 /// the replaced length: the racing-workers case, where two workers that
1349 /// missed one key each decode and insert it. The count follows what the map
1350 /// *holds*, so a missing subtraction leaves it high for good -- only a
1351 /// clear resets it, and later asks then clear early, dropping entries that
1352 /// pay a whole-file decode to be rebuilt. Driven through the same [`memoize`]
1353 /// the ask path uses (a second *ask* on one key hits the memo, so it cannot
1354 /// reach the insert): without the subtraction the second insert would read
1355 /// 3 + 5 = 8.
1356 #[test]
1357 fn replacing_an_entry_subtracts_the_old_buckets() {
1358 let _serial = counters_serial();
1359 let mut memo = PeaksMemo::new();
1360 let mut count = 0;
1361 let key = || PeaksKey::of(std::path::Path::new("edith-peaks-replace-key"), 0, BPS);
1362
1363 memoize(
1364 &mut memo,
1365 &mut count,
1366 100,
1367 key(),
1368 MemoEntry::Envelope(SharedPeaks::new(vec![(0.0, 0.0); 3])),
1369 );
1370 assert_eq!(count, 3, "the first insert was not counted");
1371
1372 memoize(
1373 &mut memo,
1374 &mut count,
1375 100,
1376 key(),
1377 MemoEntry::Envelope(SharedPeaks::new(vec![(0.0, 0.0); 5])),
1378 );
1379 assert_eq!(count, 5, "the replaced entry's buckets were not subtracted");
1380 assert_eq!(memo.len(), 1, "the replace added a second entry");
1381 }
1382
1383 /// A window is where it says it is: on a fixture whose envelope is *not*
1384 /// periodic, so a slice labelled a margin below where it starts cannot hide.
1385 /// A sine hides it -- a shift by a whole number of periods leaves every
1386 /// bucket identical, which is exactly how a +3 s mislabel survived a 440 Hz
1387 /// fixture at 8 kHz (3 s is 1320 whole periods) -- so this is noise, in
1388 /// FLAC (a seek lands on the sample, so the buckets must be *equal*, not
1389 /// merely close).
1390 ///
1391 /// Every place a window can go wrong: the file's head, its middle, both
1392 /// sides of a 30 s grid line, and the last window it has. At each: every
1393 /// bucket a two-second picture can reach is the envelope's, and the frame is
1394 /// byte for byte the one the *export* path paints from the whole envelope
1395 /// ([`crate::decode::visualizer_i420`]).
1396 #[test]
1397 fn a_window_of_a_non_periodic_file_is_where_it_says_it_is() {
1398 let _serial = counters_serial();
1399 let path = crate::scratch::Scratch::file("ve_peaks_noise", "flac");
1400 let generated = std::process::Command::new("ffmpeg")
1401 .args(["-y", "-v", "error", "-f", "lavfi", "-i"])
1402 .arg("anoisesrc=color=white:amplitude=0.5:sample_rate=8000:duration=120")
1403 .args(["-c:a", "flac"])
1404 .arg(&path)
1405 .status()
1406 .map(|status| status.success() && path.exists())
1407 .unwrap_or(false);
1408 if !generated {
1409 eprintln!("no ffmpeg: a non-periodic fixture cannot be generated, skipping");
1410 return;
1411 }
1412 let bps = crate::decode::VIZ_BUCKETS_PER_SEC;
1413 let per_sec = f64::from(bps);
1414 let plain = peaks(&path, 0, bps)
1415 .expect("open")
1416 .expect("the noise is audio");
1417 assert!(
1418 plain.len().abs_diff(120 * bps as usize) < 100,
1419 "the envelope is {} buckets, not the 120 s it was generated for",
1420 plain.len()
1421 );
1422 let peak = peak_of(&plain);
1423 let mut scratch = crate::decode::VizScratch::default();
1424 for secs in [0.0, 15.0, 29.5, 30.5, 60.0, 89.5, 119.0] {
1425 // A ceiling of a thousand buckets, so the windowed route is the one
1426 // walked (the route is what the real ceiling takes for a film).
1427 let mut seat = viz_envelope_capped(&path, 0, bps, 1000).expect("open");
1428 let view = seat.view_at(secs);
1429 assert!(
1430 !view.peaks.is_empty(),
1431 "t={secs}: the window decoded nothing"
1432 );
1433 assert_eq!(
1434 view.peak, peak,
1435 "t={secs}: the window's peak is not the file's"
1436 );
1437 assert_eq!(
1438 view.total,
1439 plain.len(),
1440 "t={secs}: the length is not the file's"
1441 );
1442 // The buckets the frame at `secs` can reach: a second either way,
1443 // plus the bucket the interpolation reads past the end.
1444 let from = ((secs - 1.0).max(0.0) * per_sec) as usize;
1445 let to = (((secs + 1.0) * per_sec) as usize + 2).min(plain.len());
1446 let (mut compared, mut wrong, mut out_of_reach) = (0, 0, 0);
1447 for abs in from..to {
1448 match (view.at(abs), plain.get(abs)) {
1449 (Some(window), Some(&whole)) => {
1450 compared += 1;
1451 if window != whole {
1452 wrong += 1;
1453 }
1454 }
1455 _ => out_of_reach += 1,
1456 }
1457 }
1458 assert!(
1459 compared > 1000,
1460 "t={secs}: only {compared} buckets were comparable ({out_of_reach} out of reach)"
1461 );
1462 assert_eq!(
1463 (wrong, out_of_reach),
1464 (0, 0),
1465 "t={secs}: {wrong} of {compared} windowed buckets are not the envelope's, \
1466 {out_of_reach} out of reach"
1467 );
1468 let whole = crate::decode::visualizer_i420(&mut scratch, &plain, secs, 320, 180, 0, 5);
1469 let window =
1470 crate::decode::visualizer_window_i420(&mut scratch, &view, secs, 320, 180, 0, 5);
1471 assert_eq!(
1472 whole, window,
1473 "t={secs}: the window painted a frame the whole envelope does not"
1474 );
1475 }
1476 }
1477
1478 /// The summary pass reads the file *once*. Its windows partition it -- the
1479 /// first one stops at the joint the next was told to start at -- so the
1480 /// frames it folds are the file's own, and folding the ask's whole-file
1481 /// probe on top of them (which is what it used to do) is up to twice a file
1482 /// for nothing, on the critical path of the first look edit.
1483 #[test]
1484 fn a_summary_pass_folds_the_file_once() {
1485 let _serial = counters_serial();
1486 let path = crate::scratch::Scratch::file("ve_peaks_once", "flac");
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 }
1516
1517 /// A container that states no sample rate (or a zero one) must not make the
1518 /// samples-per-bucket arithmetic zero: `sample / 0.0` is infinite, `as
1519 /// usize` saturates, and the fold's own `resize(bucket + 1)` is then a
1520 /// length that does not exist -- a panic in debug, a wrap and an
1521 /// out-of-bounds index in release. Both asks that bucket samples share the
1522 /// guard, so this is the one arithmetic they both use.
1523 #[test]
1524 fn a_zero_sample_rate_still_buckets_samples() {
1525 let _serial = counters_serial();
1526 // A rate of zero is read as one, and the rate is what divides either
1527 // way, so the arithmetic stays finite and positive.
1528 assert_eq!(super::per_bucket_of(0, 4000), 1.0 / 4000.0);
1529 assert_eq!(super::per_bucket_of(44100, 0), 44100.0);
1530 // ...and a fold over a chunk at that rate is total: one bucket per
1531 // sample rather than an index that does not exist.
1532 let per_bucket = super::per_bucket_of(0, 1);
1533 assert_eq!(per_bucket, 1.0);
1534 let (tx, rx) = std::sync::mpsc::channel();
1535 tx.send(crate::audio::AudioChunk {
1536 start_sample: 0,
1537 samples: vec![0.5; 4],
1538 })
1539 .expect("send");
1540 drop(tx);
1541 let peaks = super::fold(rx, per_bucket, 1, u64::MAX);
1542 assert_eq!(peaks.len(), 4, "the fold lost or invented buckets");
1543 assert_eq!(peaks[0], (0.0, 0.5), "a bucket must still straddle zero");
1544 }
1545
1546 /// The visualizer's ask for a source past the memo's ceiling: the first ask
1547 /// pays one pass for the file's two scalars and one window of it, and every
1548 /// ask after that -- the ones a look drag makes, once per pointer sample at
1549 /// the same playhead -- decodes nothing at all. Driven with a ceiling of ten
1550 /// buckets against a five-second source (fifty buckets), which is the same
1551 /// route the eight-million-bucket ceiling takes for a film.
1552 #[test]
1553 fn a_window_of_an_over_the_ceiling_source_is_decoded_once() {
1554 let _serial = counters_serial();
1555 let file = copy_of("test_av.mp4", "window");
1556 let plain = peaks(&file, 0, BPS).expect("open").expect("audio track");
1557
1558 let before = viz_decodes();
1559 let mut first = viz_envelope_capped(&file, 0, BPS, 10).expect("open");
1560 assert!(
1561 matches!(first, super::VizEnvelope::Windowed(_)),
1562 "the fixture must be past the test ceiling"
1563 );
1564 let view = first.view_at(2.5);
1565 assert!(!view.peaks.is_empty(), "the window decoded nothing");
1566 // The two scalars are the file's own and not an approximation of them:
1567 // the painter's whole-file peak and its "past the end of the file" both
1568 // come from here, and a frame scaled by anything else is another frame.
1569 assert_eq!(
1570 view.peak,
1571 peak_of(&plain),
1572 "the window's peak is not the file's"
1573 );
1574 assert_eq!(
1575 view.total,
1576 plain.len(),
1577 "the windowed length is not the envelope's"
1578 );
1579 let after_first = viz_decodes();
1580 assert!(after_first > before, "the first ask decoded nothing");
1581
1582 // The same second, three more times, the way a drag asks it: a new seat
1583 // every time, and no decode in any of them.
1584 for ask in 0..3 {
1585 let mut again = viz_envelope_capped(&file, 0, BPS, 10).expect("open");
1586 let view = again.view_at(2.5);
1587 assert_eq!(view.total, plain.len());
1588 assert!(
1589 viz_decodes() == after_first,
1590 "ask {} re-decoded a window the memo holds",
1591 ask + 2
1592 );
1593 }
1594 }
1595
1596 /// A window paints the frame the whole envelope paints: the picture of a
1597 /// clip must not change because the seat stopped holding two hours of sound
1598 /// to draw thirty seconds of it. The window here is cut out of the envelope
1599 /// itself, so this is the painter's half of the promise -- both looks, and
1600 /// times from the file's first frame to past its last.
1601 #[test]
1602 fn a_window_paints_the_frame_the_whole_envelope_paints() {
1603 let _serial = counters_serial();
1604 let file = asset("test_av.mp4");
1605 // The painter's own rate: a view carries the rate its envelope
1606 // was drawn at and indexes the slice by it, so this envelope is
1607 // drawn at exactly the rate the painter reads it at -- the
1608 // visualizer's own ([`crate::decode::VIZ_BUCKETS_PER_SEC`]).
1609 let per_sec = f64::from(crate::decode::VIZ_BUCKETS_PER_SEC);
1610 let whole = peaks(&file, 0, crate::decode::VIZ_BUCKETS_PER_SEC)
1611 .expect("open")
1612 .expect("audio track");
1613 let peak = peak_of(&whole);
1614 let mut scratch = crate::decode::VizScratch::default();
1615 for flags in [0u8, crate::decode::VIZ_FAST] {
1616 for secs in [0.0, 0.4, 1.0, 2.5, 4.9, 5.2] {
1617 let whole_frame =
1618 crate::decode::visualizer_i420(&mut scratch, &whole, secs, 320, 180, flags, 7);
1619 // The buckets a two-second picture can reach: a second either
1620 // side of the frame's own time, plus the bucket the
1621 // interpolation reads past it.
1622 let from = ((secs - 1.0).max(0.0) * per_sec) as usize;
1623 let to = (((secs + 1.0) * per_sec) as usize + 2).min(whole.len());
1624 let view = crate::decode::VizView::window(
1625 &whole[from..to],
1626 from,
1627 whole.len(),
1628 peak,
1629 per_sec,
1630 );
1631 let window_frame = crate::decode::visualizer_window_i420(
1632 &mut scratch,
1633 &view,
1634 secs,
1635 320,
1636 180,
1637 flags,
1638 7,
1639 );
1640 assert_eq!(
1641 whole_frame, window_frame,
1642 "the window painted {secs}s (flags {flags}) differently"
1643 );
1644 }
1645 }
1646 }
1647
1648 /// The long source the defect is about: forty minutes of sound, whose own
1649 /// envelope at the visualizer's 4000 buckets a second is 9.6M buckets --
1650 /// past [`PEAKS_MEMO_BUCKETS`], so the memo can never hold it and the
1651 /// windowed route is the only one there is. What a window of it draws is
1652 /// what the whole envelope draws, byte for byte, and the second and third
1653 /// ask decode nothing.
1654 ///
1655 /// The fixture is generated here (`ffmpeg -f lavfi -i
1656 /// sine=frequency=440:duration=2400 -ar 8000 -ac 1 -c:a flac`) and is FLAC
1657 /// on purpose: a seek into a lossless frame lands on the sample, so a
1658 /// window of it holds exactly the buckets the whole-file decode holds --
1659 /// which is the promise a caching change has to keep, and what a lossy
1660 /// codec's seeked filterbank cannot (a bucket lands a ten-thousandth away,
1661 /// as [`a_split_decode_draws_the_same_envelope`] already bounds it). The
1662 /// envelope's own length is asserted against the forty minutes asked for,
1663 /// so a fixture that came out at another scale cannot pass this vacuously.
1664 /// Skipped, loudly, where ffmpeg is not installed.
1665 #[test]
1666 fn a_film_length_source_paints_the_same_frame_in_windows() {
1667 let _serial = counters_serial();
1668 let path = crate::scratch::Scratch::file("ve_peaks_long", "flac");
1669 let generated = std::process::Command::new("ffmpeg")
1670 .args(["-y", "-v", "error", "-f", "lavfi", "-i"])
1671 .arg("sine=frequency=440:duration=2400")
1672 .args(["-ar", "8000", "-ac", "1", "-c:a", "flac"])
1673 .arg(&path)
1674 .status()
1675 .map(|status| status.success() && path.exists())
1676 .unwrap_or(false);
1677 if !generated {
1678 eprintln!("no ffmpeg: a film-length fixture cannot be generated, skipping");
1679 return;
1680 }
1681 let bps = crate::decode::VIZ_BUCKETS_PER_SEC;
1682 let plain = peaks(&path, 0, bps)
1683 .expect("open")
1684 .expect("the tone is audio");
1685 let secs = 2400 * bps as usize;
1686 assert!(
1687 plain.len().abs_diff(secs) < 100,
1688 "the envelope is {} buckets, not the 2400 s of sound it was generated for",
1689 plain.len()
1690 );
1691 assert!(
1692 plain.len() > PEAKS_MEMO_BUCKETS,
1693 "{} buckets is not past the memo's ceiling",
1694 plain.len()
1695 );
1696
1697 let before = viz_decodes();
1698 let mut seat = viz_envelope(&path, 0, bps).expect("open");
1699 let t = 1200.0;
1700 let view = seat.view_at(t);
1701 assert!(!view.peaks.is_empty(), "the window decoded nothing");
1702 assert_eq!(
1703 view.peak,
1704 peak_of(&plain),
1705 "the window's peak is not the file's"
1706 );
1707 assert_eq!(
1708 view.total,
1709 plain.len(),
1710 "the windowed length is not the envelope's"
1711 );
1712 // The window's own buckets are the envelope's, bucket for bucket: the
1713 // time the seats ask for in the middle of a film is the time a window
1714 // has to get exactly as right as two hours of decode did.
1715 let mut checked = 0;
1716 for abs in (t * f64::from(bps)) as usize..((t + 20.0) * f64::from(bps)) as usize {
1717 let (Some(window), Some(&whole)) = (view.at(abs), plain.get(abs)) else {
1718 continue;
1719 };
1720 assert_eq!(window, whole, "bucket {abs} differs from the envelope's");
1721 checked += 1;
1722 }
1723 assert!(checked > 10_000, "only {checked} buckets were compared");
1724
1725 let mut scratch = crate::decode::VizScratch::default();
1726 for secs in [t - 1.0, t, t + 1.0] {
1727 let whole = crate::decode::visualizer_i420(&mut scratch, &plain, secs, 320, 180, 0, 3);
1728 let window =
1729 crate::decode::visualizer_window_i420(&mut scratch, &view, secs, 320, 180, 0, 3);
1730 assert_eq!(whole, window, "the window painted {secs}s differently");
1731 }
1732 let after_first = viz_decodes();
1733 assert!(after_first > before, "the first ask decoded nothing");
1734
1735 // A look drag on a film: a new seat per pointer sample, at the same
1736 // playhead, and not one decode between them.
1737 for ask in 0..3 {
1738 let mut again = viz_envelope(&path, 0, bps).expect("open");
1739 let view = again.view_at(t);
1740 assert_eq!(view.total, plain.len());
1741 assert!(
1742 viz_decodes() == after_first,
1743 "ask {} re-decoded a window the memo holds",
1744 ask + 2
1745 );
1746 }
1747 }
1748
1749 /// The copies these tests write leave nothing in the temporary directory
1750 /// once the test is over, and that holds on a panic too: the guard is what
1751 /// removes them, not the last line of each test.
1752 #[test]
1753 fn a_copy_leaves_no_file_behind_when_its_test_is_over() {
1754 let path = copy_of("test_av.mp4", "gone");
1755 let dir = path.parent().expect("a copy has a directory").to_path_buf();
1756 assert!(path.exists(), "the copy was not written");
1757 drop(path);
1758 assert!(!dir.exists(), "the copy's directory outlived its guard");
1759 }
1760}