forge
Explore
Log in

Don't you dare go Hollow

Merge the wave lane into main

Browse files at this commit

b747d45b6b9d66bd629f00c95036841c59cda4f3Ahmet Kaan GümüşParent: 8a7835a60c5322
  • fix
    • merge the wave lane into main
Show full message
🐛 fix(engine): merge the wave lane into main

A film's visualizer reads a window of its envelope instead of the whole
file, a dead audio output is re-opened rather than ending the session's
sound, and the counter claims hold under a parallel runner. Lane:
lane-bughunt-wave.
crates/engine/src/decode.rsmodified+135 -24
@@ -649,22 +649,33 @@ impl DecodeSession {
649 // Painted at the canvas's own size, so the composite places nothing:649 // Painted at the canvas's own size, so the composite places nothing:
650 // the picture *is* the canvas, and whatever transform the clip650 // the picture *is* the canvas, and whatever transform the clip
651 // carries still reaches it through the render below.651 // carries still reaches it through the render below.
652- let (width, height) = canvas.dims();652+ //
653+ // Masked to even dimensions first, and floored at two: that is what the
654+ // painter does to the planes it hands back, so a canvas it cannot divide
655+ // evenly (an odd `resolution 1921 1081` line, or a one-pixel-high one)
656+ // used to be *declared* at a size the picture never had -- and the
657+ // conversion below then indexes a chroma plane that is not there
658+ // (`index out of bounds` on a zero-length slice, in this worker, where
659+ // no frame ever arrives and nothing catches it).
660+ let (canvas_w, canvas_h) = canvas.dims();
661+ let (width, height) = ((canvas_w & !1).max(2), (canvas_h & !1).max(2));
653 let worker_cancel = Arc::clone(&cancel);662 let worker_cancel = Arc::clone(&cancel);
654 let path = path.to_path_buf();663 let path = path.to_path_buf();
655 let handle = thread::Builder::new()664 let handle = thread::Builder::new()
656 .name("viz".into())665 .name("viz".into())
657 .spawn(move || {666 .spawn(move || {
658- // The one decode this seat ever does: the whole envelope,667+ // The envelope this span paints from, asked for once for the
659- // off the render thread, and abandoned at once if the caller668+ // whole span: the memo's own handle when it holds one, and
660- // is already gone. A file that will not open -- and one with669+ // otherwise a *window* of the file's envelope per frame --
661- // no track at all -- paints the flat line, which is what its670+ // which is what makes a rebuild cheap for a source whose whole
662- // silence looks like anyway: a visualizer frame always671+ // envelope does not fit the memo at all ([`viz_envelope`]). A
663- // exists, and is never worth failing a span over.672+ // file that will not open -- and one with no track at all --
664- let peaks = crate::waveform::peaks_shared(&path, stream, VIZ_BUCKETS_PER_SEC)673+ // paints the flat line, which is what its silence looks like
665- .ok()674+ // anyway: a visualizer frame always exists, and is never worth
666- .flatten()675+ // failing a span over.
667- .unwrap_or_default();676+ let mut envelope =
677+ crate::waveform::viz_envelope(&path, stream, VIZ_BUCKETS_PER_SEC)
678+ .unwrap_or(crate::waveform::VizEnvelope::Silent);
668 if worker_cancel.load(Ordering::Relaxed) {679 if worker_cancel.load(Ordering::Relaxed) {
669 return;680 return;
670 }681 }
@@ -687,8 +698,14 @@ impl DecodeSession {
687 return;698 return;
688 }699 }
689 let t = f64::from(start_frame + index) / fps;700 let t = f64::from(start_frame + index) / fps;
690- let (y, u, v) =701+ // One window of the envelope about this frame's own time:
691- visualizer_i420(&mut scratch, &peaks, t, width, height, flags, paint);702+ // the same window for every frame a sliding paint asks of
703+ // the same thirty seconds, and no decode at all for the
704+ // rebuilds of a look edit.
705+ let view = envelope.view_at(t);
706+ let (y, u, v) = visualizer_window_i420(
707+ &mut scratch, &view, t, width, height, flags, paint,
708+ );
692 let frame = render.frame(start_frame + index, &y, &u, &v, width, height);709 let frame = render.frame(start_frame + index, &y, &u, &v, width, height);
693 if tx.send(frame).is_err() {710 if tx.send(frame).is_err() {
694 return; // caller moved on711 return; // caller moved on
@@ -2094,6 +2111,10 @@ fn viz_chain(
2094 /// [`viz_style`]: a bipolar sample trace (Audacity), a filled min/max2111 /// [`viz_style`]: a bipolar sample trace (Audacity), a filled min/max
2095 /// envelope at pixel resolution, or a multi-strand ribbon. Ink is2112 /// envelope at pixel resolution, or a multi-strand ribbon. Ink is
2096 /// [`viz_ink_from_paint`]. A frame always exists; silence is the zero line.2113 /// [`viz_ink_from_paint`]. A frame always exists; silence is the zero line.
2114+///
2115+/// This is the whole-envelope entry: it is handed the file's envelope and
2116+/// paints from it ([`VizView::whole`]). The seat paints from a *window* of one
2117+/// instead ([`visualizer_window_i420`], [`crate::waveform::viz_envelope`]).
2097 pub(crate) fn visualizer_i420(2118 pub(crate) fn visualizer_i420(
2098 scratch: &mut VizScratch,2119 scratch: &mut VizScratch,
2099 peaks: &[(f32, f32)],2120 peaks: &[(f32, f32)],
@@ -2102,6 +2123,91 @@ pub(crate) fn visualizer_i420(
2102 height: u32,2123 height: u32,
2103 flags: u8,2124 flags: u8,
2104 paint: u64,2125 paint: u64,
2126+) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
2127+ visualizer_window_i420(scratch, &VizView::whole(peaks), t_secs, width, height, flags, paint)
2128+}
2129+
2130+/// The envelope a visualizer frame is painted from: the whole file, or one
2131+/// *window* of it -- which is what the seat holds, because a film's own
2132+/// envelope is past the memo's ceiling ([`crate::waveform::viz_envelope`]).
2133+///
2134+/// `peaks[i]` is the bucket at absolute index `first + i`, so the painter's
2135+/// index arithmetic is the same whether it was handed a slice of thirty
2136+/// seconds or of two hours. `total` is the *file's* own bucket count, which is
2137+/// what "past the end of the file" is measured against -- a window that
2138+/// measured it against itself would draw the file's end wherever the window
2139+/// ended -- and `peak` is the file's loudest bucket, which every column is
2140+/// scaled by: no window can derive that from itself.
2141+///
2142+/// `per_sec` is the rate *this* envelope was drawn at, in buckets per second,
2143+/// and it is carried rather than assumed: the slice is indexed at it, so an
2144+/// envelope drawn at another rate under a painter that hard-coded the
2145+/// visualizer's own would read a tenth of a second of sound as a second. The
2146+/// whole-file constructor is the one place the visualizer's rate is named.
2147+pub(crate) struct VizView<'a> {
2148+ pub(crate) peaks: &'a [(f32, f32)],
2149+ pub(crate) first: usize,
2150+ pub(crate) total: usize,
2151+ pub(crate) peak: f32,
2152+ pub(crate) per_sec: f64,
2153+}
2154+
2155+impl<'a> VizView<'a> {
2156+ /// The whole envelope, which is what every caller but the seat has.
2157+ pub(crate) fn whole(peaks: &'a [(f32, f32)]) -> Self {
2158+ Self {
2159+ peaks,
2160+ first: 0,
2161+ total: peaks.len(),
2162+ peak: crate::waveform::peak_of(peaks),
2163+ per_sec: f64::from(VIZ_BUCKETS_PER_SEC),
2164+ }
2165+ }
2166+
2167+ /// One window of an envelope: `peaks` starts at absolute bucket `first`,
2168+ /// `total` and `peak` are the whole file's, and `per_sec` is the rate the
2169+ /// file's envelope was drawn at.
2170+ pub(crate) fn window(
2171+ peaks: &'a [(f32, f32)],
2172+ first: usize,
2173+ total: usize,
2174+ peak: f32,
2175+ per_sec: f64,
2176+ ) -> Self {
2177+ Self {
2178+ peaks,
2179+ first,
2180+ total,
2181+ peak,
2182+ per_sec,
2183+ }
2184+ }
2185+
2186+ /// The bucket at absolute index `abs`, when this view carries it: the
2187+ /// window's own edges are not the file's, and a frame asked for one of
2188+ /// them draws silence rather than a bucket that is only half decoded.
2189+ pub(crate) fn at(&self, abs: usize) -> Option<(f32, f32)> {
2190+ abs.checked_sub(self.first)
2191+ .and_then(|i| self.peaks.get(i))
2192+ .copied()
2193+ }
2194+
2195+ fn is_empty(&self) -> bool {
2196+ self.peaks.is_empty()
2197+ }
2198+}
2199+
2200+/// [`visualizer_i420`] from a view, which is how the seat paints: `peaks` may
2201+/// be a window rather than the file's own envelope, and `t_secs` is the
2202+/// frame's own time either way -- the view knows where its slice starts.
2203+pub(crate) fn visualizer_window_i420(
2204+ scratch: &mut VizScratch,
2205+ view: &VizView,
2206+ t_secs: f64,
2207+ width: u32,
2208+ height: u32,
2209+ flags: u8,
2210+ paint: u64,
2105 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {2211 ) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
2106 let width = width & !1;2212 let width = width & !1;
2107 let height = height & !1;2213 let height = height & !1;
@@ -2138,9 +2244,9 @@ pub(crate) fn visualizer_i420(
2138 scratch.hi.resize(w, 0.0);2244 scratch.hi.resize(w, 0.0);
2139 scratch.sig.clear();2245 scratch.sig.clear();
2140 scratch.sig.resize(w, 0.0);2246 scratch.sig.resize(w, 0.0);
2141- if !peaks.is_empty() {2247+ if !view.is_empty() && view.total != 0 {
2142- let duration = peaks.len() as f64 / f64::from(VIZ_BUCKETS_PER_SEC);2248+ let duration = view.total as f64 / view.per_sec;
2143- let per_sec = f64::from(VIZ_BUCKETS_PER_SEC);2249+ let per_sec = view.per_sec;
2144 let window = if flags & VIZ_FAST != 0 {2250 let window = if flags & VIZ_FAST != 0 {
2145 VIZ_FAST_SECS2251 VIZ_FAST_SECS
2146 } else {2252 } else {
@@ -2155,11 +2261,17 @@ pub(crate) fn visualizer_i420(
2155 if !t.is_finite() || t < 0.0 || t > duration {2261 if !t.is_finite() || t < 0.0 || t > duration {
2156 return (0.0, 0.0);2262 return (0.0, 0.0);
2157 }2263 }
2158- let pos = (t * per_sec).clamp(0.0, (peaks.len() - 1) as f64);2264+ let pos = (t * per_sec).clamp(0.0, (view.total - 1) as f64);
2159 let i = pos.floor() as usize;2265 let i = pos.floor() as usize;
2160 let f = (pos - i as f64) as f32;2266 let f = (pos - i as f64) as f32;
2161- let (lo0, hi0) = peaks[i];2267+ // Silence where the slice does not reach: a view that is a window
2162- let (lo1, hi1) = peaks[(i + 1).min(peaks.len() - 1)];2268+ // is only handed the buckets the frame can ask for, so this is the
2269+ // file's own ends and nothing else.
2270+ let (Some((lo0, hi0)), Some((lo1, hi1))) =
2271+ (view.at(i), view.at((i + 1).min(view.total - 1)))
2272+ else {
2273+ return (0.0, 0.0);
2274+ };
2163 (2275 (
2164 (lo0 + (lo1 - lo0) * f).clamp(-1.0, 0.0),2276 (lo0 + (lo1 - lo0) * f).clamp(-1.0, 0.0),
2165 (hi0 + (hi1 - hi0) * f).clamp(0.0, 1.0),2277 (hi0 + (hi1 - hi0) * f).clamp(0.0, 1.0),
@@ -2186,11 +2298,10 @@ pub(crate) fn visualizer_i420(
2186 }2298 }
2187 // Whole-file peak, not the window's: a 2s window that gains or loses2299 // Whole-file peak, not the window's: a 2s window that gains or loses
2188 // a loud hit used to rescale every column, so the same bump changed2300 // a loud hit used to rescale every column, so the same bump changed
2189- // height as it entered and left the picture.2301+ // height as it entered and left the picture. A view carries that peak
2190- let peak = peaks2302+ // with it ([`VizView`]), because a window of a film could not compute
2191- .iter()2303+ // it from the megabyte it holds.
2192- .map(|&(l, h)| l.abs().max(h.abs()))2304+ let peak = view.peak;
2193- .fold(0.0f32, f32::max);
2194 if peak > 1e-4 {2305 if peak > 1e-4 {
2195 for i in 0..w {2306 for i in 0..w {
2196 scratch.lo[i] /= peak;2307 scratch.lo[i] /= peak;
crates/engine/src/playback.rsmodified+227 -9
@@ -16,7 +16,7 @@ use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering}
16 use std::sync::mpsc::{Receiver, TryRecvError};16 use std::sync::mpsc::{Receiver, TryRecvError};
17 use std::sync::{Arc, Mutex};17 use std::sync::{Arc, Mutex};
18 use std::thread;18 use std::thread;
19-use std::time::Duration;19+use std::time::{Duration, Instant};
20 20
21 use crate::ao::AoSession;21 use crate::ao::AoSession;
22 use crate::audio::{AudioChunk, AudioSession};22 use crate::audio::{AudioChunk, AudioSession};
@@ -52,6 +52,23 @@ const FLUSH_WAIT: Duration = Duration::from_millis(1);
52 /// all pays this once per span rather than freezing the preview outright.52 /// all pays this once per span rather than freezing the preview outright.
53 const DISSOLVE_B_TIMEOUT: Duration = Duration::from_millis(200);53 const DISSOLVE_B_TIMEOUT: Duration = Duration::from_millis(200);
54 54
55+/// How long a dead output is left alone before another open is attempted. A
56+/// PipeWire daemon restart takes a moment, and the ask that makes the attempt
57+/// runs once per rendered frame: a second is long enough that a restart lands
58+/// inside it, and short enough that a play pressed after one does not wait.
59+const AUDIO_REARM_AFTER: Duration = Duration::from_secs(1);
60+
61+/// The reason a session gives for having gone quiet when its output dies
62+/// ([`PlaybackSession::tick`]), through the same door a file's own refusal
63+/// reaches a front-end by ([`PlaybackSession::audio_disabled_reason`]).
64+///
65+/// That door is read where a notice is *built* -- at open and at load -- so this
66+/// is fetchable rather than announced: the engine sets the reason and clears it
67+/// again when the output comes back, and a front-end that reads the door after
68+/// the session is open (a per-frame check, or one at the next load) is what
69+/// shows it. Nothing here pushes a notice.
70+const AUDIO_LOST: &str = "output device went away -- reconnecting the timeline's sound";
71+
55 /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 --72 /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 --
56 /// nothing was shot on it, so it is the canvas a *later* import meets rather73 /// nothing was shot on it, so it is the canvas a *later* import meets rather
57 /// than a description of the song. H.264 because it is the one codec that74 /// than a description of the song. H.264 because it is the one codec that
@@ -149,6 +166,13 @@ struct Audio {
149 /// at once -- which is precisely what166 /// at once -- which is precisely what
150 /// [`live_workers`](PlaybackSession::live_workers) is asked about.167 /// [`live_workers`](PlaybackSession::live_workers) is asked about.
151 feeders: Arc<AtomicUsize>,168 feeders: Arc<AtomicUsize>,
169+ /// When this device was last opened *again* after dying
170+ /// ([`PlaybackSession::rearm_audio`]). A dead output is offered one open a
171+ /// second and no more, because the ask that makes the attempt runs once per
172+ /// rendered frame: a daemon restart takes a moment, and a device that is
173+ /// gone for good must not be opened sixty times a second for the rest of
174+ /// the session.
175+ rearm_at: Arc<Mutex<Option<Instant>>>,
152 }176 }
153 177
154 /// How much of the played signal the tap keeps. A power of two, because what178 /// How much of the played signal the tap keeps. A power of two, because what
@@ -2672,7 +2696,12 @@ impl PlaybackSession {
2672 /// ([`Self::seek`]'s own `switch_to_audio`), which is the seek a front-end2696 /// ([`Self::seek`]'s own `switch_to_audio`), which is the seek a front-end
2673 /// makes as it places the file it just imported.2697 /// makes as it places the file it just imported.
2674 fn arm_audio(&mut self) {2698 fn arm_audio(&mut self) {
2675- if self.audio.is_some() {2699+ // A device that is there but *dead* is not a device: the walk below
2700+ // opens another one, which is also what clears the notice a death put up
2701+ // ([`Self::tick`]).
2702+ if let Some(audio) = &self.audio
2703+ && !audio.died.load(Ordering::Acquire)
2704+ {
2676 return;2705 return;
2677 }2706 }
2678 for source in self2707 for source in self
@@ -2690,6 +2719,63 @@ impl PlaybackSession {
2690 }2719 }
2691 }2720 }
2692 2721
2722+ /// Opens the output again for a stream that died, at the rate and channel
2723+ /// count it carried, and clears the flag that stopped the session feeding.
2724+ ///
2725+ /// An output that goes away -- a PipeWire daemon restarting, a sink node
2726+ /// removed and put back -- leaves every stream that was open on it dead for
2727+ /// good: its position is frozen, so the clock can only fall to wall time, and
2728+ /// a session that never opens another device is silent for the rest of its
2729+ /// life, through every seek and every pause/play, with nothing said about it.
2730+ ///
2731+ /// The device *only*, never the file: the feeder is [`Self::start_audio`]'s,
2732+ /// at the seek that follows. That is what lets [`Self::tick`] call this too,
2733+ /// once a frame -- a tick is not a seek and must not reseek the timeline. The
2734+ /// clock is on wall time by then and stays there until a seek comes, which is
2735+ /// the seek whose feeder opens in step with the picture.
2736+ ///
2737+ /// `if_idle_for` is the cooldown: a tick passes [`AUDIO_REARM_AFTER`], because
2738+ /// sixty opens a second against a device that is gone for good is a spin; a
2739+ /// seek passes zero, because that one is a person asking.
2740+ ///
2741+ /// `false` when there is nothing to open, nothing came back, or the cooldown
2742+ /// has not passed -- and the flag stays standing for the next attempt.
2743+ fn rearm_audio(&mut self, if_idle_for: Duration) -> bool {
2744+ let Some(audio) = &self.audio else {
2745+ return false;
2746+ };
2747+ if !audio.died.load(Ordering::Acquire) {
2748+ return true;
2749+ }
2750+ {
2751+ let mut at = audio.rearm_at.lock().unwrap();
2752+ if at.is_some_and(|at| at.elapsed() < if_idle_for) {
2753+ return false;
2754+ }
2755+ *at = Some(Instant::now());
2756+ }
2757+ let Some(ao) = AoSession::open(audio.sample_rate, audio.channels as u32) else {
2758+ return false;
2759+ };
2760+ // A stream comes up streaming and a session starts paused: the fresh one
2761+ // is silenced until the seek that feeds it says otherwise, which is the
2762+ // same two steps [`open_audio`] takes on the way in.
2763+ ao.set_active(false);
2764+ // Replacing the session is what closes the dead stream, so it is done
2765+ // under the device lock the feeder writes through.
2766+ *audio.ao.lock().unwrap() = ao;
2767+ // The clock anchor and the played-out arithmetic both belong to the
2768+ // stream that died: the new one stamps its own first sample
2769+ // ([`Audio::content_at`]), and `start_audio` re-bases the count from the
2770+ // device's own position.
2771+ audio.content_at.store(-1, Ordering::Release);
2772+ audio.died.store(false, Ordering::Release);
2773+ if self.audio_disabled.as_deref() == Some(AUDIO_LOST) {
2774+ self.audio_disabled = None;
2775+ }
2776+ true
2777+ }
2778+
2693 /// The rate noted for whichever source plays `path`, by2779 /// The rate noted for whichever source plays `path`, by
2694 /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however2780 /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however
2695 /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session2781 /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session
@@ -3910,6 +3996,12 @@ impl PlaybackSession {
3910 let fps = self.meta.frame_rate;3996 let fps = self.meta.frame_rate;
3911 let mut audio_running = false;3997 let mut audio_running = false;
3912 let mut live = None;3998 let mut live = None;
3999+ // A dead output gets an attempt here without waiting out the cooldown: a
4000+ // seek is a person asking, and this is the one moment the sound can come
4001+ // back into step with the picture, because the feeder opened below starts
4002+ // at the target. If it does not come back the flag stands and the guard
4003+ // under it leaves the clock on wall time.
4004+ self.rearm_audio(Duration::ZERO);
3913 if let Some(audio) = &self.audio4005 if let Some(audio) = &self.audio
3914 && !audio.died.load(Ordering::Acquire)4006 && !audio.died.load(Ordering::Acquire)
3915 {4007 {
@@ -4079,19 +4171,37 @@ impl PlaybackSession {
4079 // still be moving it -- otherwise the queue fills with pictures whose4171 // still be moving it -- otherwise the queue fills with pictures whose
4080 // moment passed while nobody was taking them.4172 // moment passed while nobody was taking them.
4081 self.publish_playhead();4173 self.publish_playhead();
4174+ // Before the clock-source guard below, and not after it: a dead output is
4175+ // what *puts* the clock on wall time, so this branch has to keep running
4176+ // while it is there -- the one attempt that can bring the sound back is
4177+ // in it.
4178+ if self
4179+ .audio
4180+ .as_ref()
4181+ .is_some_and(|audio| audio.died.load(Ordering::Acquire))
4182+ {
4183+ // Output died mid-stream: its position will never reach `fed`, so the
4184+ // EOF comparison below is unreachable. Wall time takes over from
4185+ // wherever the clock last stood, and the session says so rather than
4186+ // going silent for good without a word: a front-end already has a
4187+ // line for a silent session ([`Self::audio_disabled_reason`]).
4188+ if self.audio_disabled.is_none() {
4189+ self.audio_disabled = Some(AUDIO_LOST.to_string());
4190+ }
4191+ self.clock.switch_to_wall();
4192+ // ...and the output is offered another open, once a second: a
4193+ // restarting daemon takes a moment, and this runs once a frame. A
4194+ // re-arm that takes is what clears the notice, and the next seek
4195+ // feeds it.
4196+ self.rearm_audio(AUDIO_REARM_AFTER);
4197+ return;
4198+ }
4082 let Some(audio) = &self.audio else {4199 let Some(audio) = &self.audio else {
4083 return; // wall time from the start, nothing to poll4200 return; // wall time from the start, nothing to poll
4084 };4201 };
4085 if self.clock.source() != ClockSource::Audio {4202 if self.clock.source() != ClockSource::Audio {
4086 return;4203 return;
4087 }4204 }
4088- if audio.died.load(Ordering::Acquire) {
4089- // Output died mid-stream: its position will never reach `fed`, so
4090- // the EOF comparison below is unreachable. Wall time takes over
4091- // from wherever the clock last stood.
4092- self.clock.switch_to_wall();
4093- return;
4094- }
4095 // `None` until the device's first callback: the clock holds at its4205 // `None` until the device's first callback: the clock holds at its
4096 // anchor rather than guessing, which is why playback starts on time4206 // anchor rather than guessing, which is why playback starts on time
4097 // instead of a quantum early.4207 // instead of a quantum early.
@@ -4420,6 +4530,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
4420 wants_active: Arc::new(AtomicBool::new(false)),4530 wants_active: Arc::new(AtomicBool::new(false)),
4421 tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))),4531 tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))),
4422 feeders: Arc::new(AtomicUsize::new(0)),4532 feeders: Arc::new(AtomicUsize::new(0)),
4533+ rearm_at: Arc::new(Mutex::new(None)),
4423 };4534 };
4424 (audio.spawn_feeder(rx).then_some(audio), None)4535 (audio.spawn_feeder(rx).then_some(audio), None)
4425 }4536 }
@@ -4553,8 +4664,10 @@ fn blend_bgra(a: &[u8], b: &[u8], t: f32) -> Vec<u8> {
4553 mod tests {4664 mod tests {
4554 use super::{4665 use super::{
4555 Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of, blend_bgra, secs_to_frame,4666 Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of, blend_bgra, secs_to_frame,
4667+ AUDIO_LOST,
4556 };4668 };
4557 use std::path::PathBuf;4669 use std::path::PathBuf;
4670+ use std::sync::atomic::Ordering;
4558 4671
4559 fn asset(name: &str) -> PathBuf {4672 fn asset(name: &str) -> PathBuf {
4560 PathBuf::from(env!("CARGO_MANIFEST_DIR"))4673 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
@@ -4562,6 +4675,111 @@ mod tests {
4562 .join(name)4675 .join(name)
4563 }4676 }
4564 4677
4678+ /// A dead output is not the end of a session's sound.
4679+ ///
4680+ /// The stream is stopped the way a seek stops one and then flagged the way a
4681+ /// failed write flags it ([`feed`]): nothing is feeding and nothing will. The
4682+ /// session must say so -- a dead output used to hand the clock to wall time
4683+ /// in silence, for the rest of the session's life, through every seek -- and
4684+ /// the play (and the seek after it) must put the output back, which is read
4685+ /// off the tap: the samples that actually reached the device. A session that
4686+ /// only switched the clock leaves the tap empty.
4687+ ///
4688+ /// The tick below runs with the cooldown already spent (an attempt stamped
4689+ /// just now), which is what makes the notice observable at all *and* what
4690+ /// proves the one thing a frame-rate poll must not do: open a device that is
4691+ /// gone for good sixty times a second.
4692+ #[test]
4693+ fn a_dead_output_is_rearmed_and_the_sound_comes_back() {
4694+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
4695+ assert!(
4696+ session.audio_tap().is_some(),
4697+ "test_av.mp4 carries an audio track, which is what this drives"
4698+ );
4699+
4700+ session.stop_audio();
4701+ let audio = session.audio.as_ref().expect("audio");
4702+ audio.died.store(true, Ordering::Release);
4703+ *audio.rearm_at.lock().unwrap() = Some(std::time::Instant::now());
4704+
4705+ session.tick();
4706+ assert_eq!(
4707+ session.audio_disabled_reason(),
4708+ Some(AUDIO_LOST),
4709+ "a dead output went to wall time without a word"
4710+ );
4711+ assert!(
4712+ session.audio.as_ref().expect("audio").died.load(Ordering::Acquire),
4713+ "a tick opened the output again inside the cooldown"
4714+ );
4715+ assert!(
4716+ session.audio_tap().expect("audio").0.is_empty(),
4717+ "something was still feeding the device"
4718+ );
4719+
4720+ // Playing is the ask that is not throttled: the output is opened again,
4721+ // the flag clears and a feeder fills the device -- asynchronously, so the
4722+ // tap is waited on.
4723+ session.play();
4724+ session.seek(1.0);
4725+ let mut fed = Vec::new();
4726+ for _ in 0..200 {
4727+ fed = session.audio_tap().expect("audio").0;
4728+ if !fed.is_empty() {
4729+ break;
4730+ }
4731+ std::thread::sleep(std::time::Duration::from_millis(5));
4732+ }
4733+ assert!(
4734+ !fed.is_empty(),
4735+ "playing after a dead output fed nothing: the session cannot come back"
4736+ );
4737+ assert!(
4738+ !session.audio.as_ref().expect("audio").died.load(Ordering::Acquire),
4739+ "the death flag stood after the output was replaced"
4740+ );
4741+ assert_eq!(
4742+ session.audio_disabled_reason(),
4743+ None,
4744+ "the notice was left standing over a session that is playing again"
4745+ );
4746+ }
4747+
4748+ /// The seat declares the canvas's own size; the painter masks the planes it
4749+ /// returns to even dimensions, and a canvas the two disagree about used to
4750+ /// take the picture down between them. On the revision before the seat masked
4751+ /// what it declares, a 1920x1 canvas died *in the painter* -- `decode.rs`
4752+ /// clamped the zero line of an h of 0: `max = -1`, `min > max` -- and a
4753+ /// 321x181 one died in the conversion on the *canvas's* chroma plane, one row
4754+ /// past the masked source's: `index out of bounds: the len is 14400 but the
4755+ /// index is 14400`, a full plane and not an empty one.
4756+ ///
4757+ /// This drives the same path a front-end does (`set_resolution`, then frames
4758+ /// out of the session). It is a guard against the shape coming back rather
4759+ /// than a reproduction: a frame does still arrive on the parent revision
4760+ /// (which is why the masking, not this test, is the fix).
4761+ #[test]
4762+ fn a_visualizer_seat_paints_a_canvas_it_cannot_evenly_divide() {
4763+ for (w, h) in [(1920, 1), (1921, 1081), (320, 1), (321, 181)] {
4764+ let mut session =
4765+ PlaybackSession::open(asset("test_tone.mp3")).expect("open the audio fixture");
4766+ assert!(
4767+ session.set_resolution(w, h),
4768+ "{w}x{h} should be a resolution this session takes"
4769+ );
4770+ let mut frame = None;
4771+ for _ in 0..400 {
4772+ if let Some(f) = session.try_frame() {
4773+ frame = Some(f);
4774+ break;
4775+ }
4776+ std::thread::sleep(std::time::Duration::from_millis(5));
4777+ }
4778+ let frame = frame.unwrap_or_else(|| panic!("no frame from a {w}x{h} canvas"));
4779+ assert_eq!((frame.width, frame.height), (w, h), "a frame at the canvas's own size");
4780+ }
4781+ }
4782+
4565 /// `blend_bgra` at the two ends and the midpoint of its weight -- `t=0` is4783 /// `blend_bgra` at the two ends and the midpoint of its weight -- `t=0` is
4566 /// pure A, `t=1` is pure B, `t=0.5` rounds each byte to its own midpoint.4784 /// pure A, `t=1` is pure B, `t=0.5` rounds each byte to its own midpoint.
4567 /// Straight alpha (255 in both) survives every weight, which is the one4785 /// Straight alpha (255 in both) survives every weight, which is the one
crates/engine/src/waveform.rsmodified+1073 -71
@@ -6,8 +6,8 @@ use std::path::{Path, PathBuf};
6 use std::sync::mpsc::Receiver;6 use std::sync::mpsc::Receiver;
7 use std::thread;7 use std::thread;
8 8
9-use crate::AudioSession;
10 use crate::audio::AudioChunk;9 use crate::audio::AudioChunk;
10+use crate::AudioSession;
11 11
12 /// `(min, max)` of every sample in each `1 / buckets_per_sec` window of12 /// `(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 by13 /// `stream` of `path`'s audio, from media time 0 (priming already trimmed by
@@ -55,7 +55,7 @@ pub(crate) type SharedPeaks = std::sync::Arc<Vec<(f32, f32)>>;
55 /// The identity a memo entry is keyed by: what was asked for *and* the file it55 /// 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 than56 /// was answered from, so a source replaced on disk is read again rather than
57 /// served the envelope of bytes that are gone.57 /// served the envelope of bytes that are gone.
58-#[derive(PartialEq, Eq, Hash)]58+#[derive(PartialEq, Eq, Hash, Clone)]
59 struct PeaksKey {59 struct PeaksKey {
60 path: PathBuf,60 path: PathBuf,
61 stream: usize,61 stream: usize,
@@ -65,6 +65,15 @@ struct PeaksKey {
65 }65 }
66 66
67 impl PeaksKey {67 impl PeaksKey {
68+ /// The same identity for an ask that has nothing to do with a rate: the
69+ /// scalars [`viz_summary`] reads off a file are its samples, not its
70+ /// buckets, and one measuring is enough for every rate asked of it. `0` is
71+ /// not a rate any ask can use ([`per_bucket_of`] floors it), so a summary
72+ /// never collides with an envelope.
73+ fn stream_of(path: &Path, stream: usize) -> Self {
74+ Self::of(path, stream, 0)
75+ }
76+
68 fn of(path: &Path, stream: usize, buckets_per_sec: u32) -> Self {77 fn of(path: &Path, stream: usize, buckets_per_sec: u32) -> Self {
69 let stat = std::fs::metadata(path).ok();78 let stat = std::fs::metadata(path).ok();
70 Self {79 Self {
@@ -89,16 +98,30 @@ fn peaks_memo() -> &'static std::sync::Mutex<(PeaksMemo, usize)> {
89 &MEMO98 &MEMO
90 }99 }
91 100
92-/// Test-only: how many times an ask had to decode rather than answer from what101+/// Test-only: how many times an ask *for one key* had to decode rather than
93-/// the memo already held. A second ask for the same source -- trackless or not102+/// answer from what the memo already held. A second ask of the same source --
94-/// -- must not move it, which is what makes "the memo answered" observable.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.
95 #[cfg(test)]111 #[cfg(test)]
96-static MEMO_DECODES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);112+static 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()));
97 115
98-/// [`MEMO_DECODES`], for a test that measures a delta across its own asks.116+/// [`MEMO_DECODES`] for one ask, for a test that measures a delta across its own.
99 #[cfg(test)]117 #[cfg(test)]
100-fn memo_decodes() -> usize {118+fn memo_decodes(path: &Path, stream: usize, buckets_per_sec: u32) -> usize {
101- MEMO_DECODES.load(std::sync::atomic::Ordering::Relaxed)119+ MEMO_DECODES
120+ .lock()
121+ .unwrap()
122+ .get(&PeaksKey::of(path, stream, buckets_per_sec))
123+ .copied()
124+ .unwrap_or(0)
102 }125 }
103 126
104 /// What the memo holds for one key: an envelope, or the stable answer that the127 /// What the memo holds for one key: an envelope, or the stable answer that the
@@ -122,36 +145,21 @@ impl MemoEntry {
122 MemoEntry::NoTrack => None,145 MemoEntry::NoTrack => None,
123 }146 }
124 }147 }
125-
126- /// How many buckets this entry adds to the counter.
127- fn buckets(&self) -> usize {
128- match self {
129- MemoEntry::Envelope(shared) => shared.len(),
130- MemoEntry::NoTrack => 0,
131- }
132- }
133 }148 }
134 149
135 /// Every answer the process has been asked for, by identity.150 /// Every answer the process has been asked for, by identity.
136 type PeaksMemo = std::collections::HashMap<PeaksKey, MemoEntry>;151 type PeaksMemo = std::collections::HashMap<PeaksKey, MemoEntry>;
137 152
138 /// [`peaks`] as a handle the caller can hold: the same envelope, shared rather153 /// [`peaks`] as a handle the caller can hold: the same envelope, shared rather
139-/// than copied.154+/// than copied, under a ceiling.
140-///
141-/// The visualizer seat asks this of every picture rebuild it makes
142-/// ([`DecodeSession::open_visualizer`]): a rebuild happens once per look edit,
143-/// and a look edit is what a drag across the colour wheel is -- so an envelope
144-/// decoded per rebuild is a whole-file audio decode per pointer sample, for an
145-/// answer that has not changed.
146 ///155 ///
147-/// Keyed on the file's own stat ([`PeaksKey`]) and bounded by156+/// Keyed on the file's own stat ([`PeaksKey`]) and bounded by [`cap`] *of what
148-/// [`PEAKS_MEMO_BUCKETS`] *of what it holds*: past the ceiling the memo lets157+/// it holds*: past the ceiling the memo lets everything go rather than evicting
149-/// everything go rather than evicting one entry at a time, because the entries158+/// one entry at a time, because the entries are large and a re-decode is the
150-/// are large and a re-decode is the honest cost of asking for more than the159+/// honest cost of asking for more than the ceiling. A single source whose own
151-/// ceiling. A single source whose own envelope is bigger than the ceiling is160+/// envelope is bigger than the ceiling is not memoized at all (the caller still
152-/// not memoized at all (see [`peaks_shared`]), so the ceiling is one -- an161+/// gets its handle), so the ceiling is one -- an entry that no clear can bring
153-/// entry that no clear can bring the memo back under would be a memo that162+/// the memo back under would be a memo that clears on every other ask.
154-/// clears on every other ask.
155 ///163 ///
156 /// A trackless source's `Ok(None)` is kept too: it is an answer the file will164 /// A trackless source's `Ok(None)` is kept too: it is an answer the file will
157 /// give again, and without it a visualizer clip on a silent source re-opens165 /// give again, and without it a visualizer clip on a silent source re-opens
@@ -159,17 +167,12 @@ type PeaksMemo = std::collections::HashMap<PeaksKey, MemoEntry>;
159 /// paid once per look edit. It holds no buckets, so it never counts against167 /// paid once per look edit. It holds no buckets, so it never counts against
160 /// the ceiling. A failed ask is *not* kept: a decode that failed once may fail168 /// the ceiling. A failed ask is *not* kept: a decode that failed once may fail
161 /// for a reason that has gone away, and caching it would make that permanent.169 /// for a reason that has gone away, and caching it would make that permanent.
162-pub(crate) fn peaks_shared(170+///
163- path: &Path,171+/// The visualizer seat does not ask this directly any more -- it asks
164- stream: usize,172+/// [`viz_envelope`], which answers with this for a source the memo holds and
165- buckets_per_sec: u32,173+/// with windows of it for one it cannot. `cap` is [`PEAKS_MEMO_BUCKETS`] there;
166-) -> crate::Result<Option<SharedPeaks>> {174+/// a test drives it down to a handful of buckets so the over-the-ceiling path
167- peaks_shared_capped(path, stream, buckets_per_sec, PEAKS_MEMO_BUCKETS)175+/// is walked without an eight-million-bucket fixture.
168-}
169-
170-/// [`peaks_shared`] against a ceiling a test can drive down to a handful of
171-/// buckets, so the over-the-ceiling path is walked without an eight-million-
172-/// bucket fixture. `cap` is [`PEAKS_MEMO_BUCKETS`] everywhere but in a test.
173 fn peaks_shared_capped(176 fn peaks_shared_capped(
174 path: &Path,177 path: &Path,
175 stream: usize,178 stream: usize,
@@ -181,7 +184,9 @@ fn peaks_shared_capped(
181 return Ok(hit.envelope());184 return Ok(hit.envelope());
182 }185 }
183 #[cfg(test)]186 #[cfg(test)]
184- MEMO_DECODES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);187+ {
188+ *MEMO_DECODES.lock().unwrap().entry(key.clone()).or_insert(0) += 1;
189+ }
185 // A failure is *not* memoized: `?` leaves the map untouched, so a decode190 // A failure is *not* memoized: `?` leaves the map untouched, so a decode
186 // that failed once -- a file caught mid-write, a busy device -- is retried191 // that failed once -- a file caught mid-write, a busy device -- is retried
187 // rather than frozen for the process's life. Only the two successful192 // rather than frozen for the process's life. Only the two successful
@@ -200,6 +205,28 @@ fn peaks_shared_capped(
200 Ok(handle)205 Ok(handle)
201 }206 }
202 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.
211+trait Bucketed {
212+ fn buckets(&self) -> usize;
213+}
214+
215+impl 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+
224+impl Bucketed for SharedPeaks {
225+ fn buckets(&self) -> usize {
226+ self.len()
227+ }
228+}
229+
203 /// Record `entry` under `key` in `memo`, keeping `count` equal to the buckets230 /// Record `entry` under `key` in `memo`, keeping `count` equal to the buckets
204 /// the map holds. The arithmetic is what keeps the ceiling a ceiling:231 /// the map holds. The arithmetic is what keeps the ceiling a ceiling:
205 ///232 ///
@@ -214,12 +241,12 @@ fn peaks_shared_capped(
214 /// missed one key each decode and insert it -- does not leave the count high241 /// missed one key each decode and insert it -- does not leave the count high
215 /// for good: only a clear resets it, and a high count makes later asks clear242 /// for good: only a clear resets it, and a high count makes later asks clear
216 /// early, dropping entries that then pay a whole-file decode to be rebuilt.243 /// early, dropping entries that then pay a whole-file decode to be rebuilt.
217-fn memoize(244+fn memoize<K: std::hash::Hash + Eq, V: Bucketed>(
218- memo: &mut PeaksMemo,245+ memo: &mut std::collections::HashMap<K, V>,
219 count: &mut usize,246 count: &mut usize,
220 cap: usize,247 cap: usize,
221- key: PeaksKey,248+ key: K,
222- entry: MemoEntry,249+ entry: V,
223 ) {250 ) {
224 let len = entry.buckets();251 let len = entry.buckets();
225 if len > cap {252 if len > cap {
@@ -235,6 +262,550 @@ fn memoize(
235 *count += len;262 *count += len;
236 }263 }
237 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.
268+const 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.
275+const 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.
284+const 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.
290+pub(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.
303+pub(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+
316+impl 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`]).
338+pub(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+
349+impl 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.
362+pub(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+
377+impl 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)]
448+struct WindowKey {
449+ file: PeaksKey,
450+ from: usize,
451+}
452+
453+impl 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.
464+fn 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.
476+fn 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)]
488+static 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)]
492+fn 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)]
502+static 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)]
506+fn 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.
513+pub(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.
524+pub(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.
625+fn 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.
701+fn 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.
749+fn 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.
781+fn 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.
805+fn 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+
238 /// [`peaks`] with the split forced to `jobs` windows, which is how a test asks809 /// [`peaks`] with the split forced to `jobs` windows, which is how a test asks
239 /// for the same envelope by both routes.810 /// for the same envelope by both routes.
240 fn peaks_over(811 fn peaks_over(
@@ -248,7 +819,7 @@ fn peaks_over(
248 };819 };
249 // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a820 // Kept fractional: 44100 / 30 is not whole, and rounding it would drift a
250 // bucket every few seconds over a long source.821 // bucket every few seconds over a long source.
251- let per_bucket = f64::from(meta.sample_rate) / f64::from(buckets_per_sec.max(1));822+ let per_bucket = per_bucket_of(meta.sample_rate, buckets_per_sec);
252 let channels = (meta.channels as usize).max(1);823 let channels = (meta.channels as usize).max(1);
253 let rate = f64::from(meta.sample_rate.max(1));824 let rate = f64::from(meta.sample_rate.max(1));
254 // A track whose length the container does not state cannot be cut into825 // A track whose length the container does not state cannot be cut into
@@ -274,14 +845,14 @@ fn peaks_over(
274 true => f64::INFINITY,845 true => f64::INFINITY,
275 false => window * (k + 1) as f64,846 false => window * (k + 1) as f64,
276 };847 };
277- thread::Builder::new()848+ thread::Builder::new().name("waveform".into()).spawn(
278- .name("waveform".into())849+ move || -> crate::Result<Vec<(f32, f32)>> {
279- .spawn(move || -> crate::Result<Vec<(f32, f32)>> {
280 match open_window(&path, stream, start, end)? {850 match open_window(&path, stream, start, end)? {
281 Some((_, rx)) => Ok(fold(rx, per_bucket, channels, u64::MAX)),851 Some((_, rx)) => Ok(fold(rx, per_bucket, channels, u64::MAX)),
282 None => Ok(Vec::new()),852 None => Ok(Vec::new()),
283 }853 }
284- })854+ },
855+ )
285 })856 })
286 .collect::<Result<_, _>>()?;857 .collect::<Result<_, _>>()?;
287 // This window ends where the next one's decoder was told to start, by the858 // This window ends where the next one's decoder was told to start, by the
@@ -311,7 +882,10 @@ fn jobs_for(secs: f64) -> usize {
311 return 1;882 return 1;
312 }883 }
313 let cores = thread::available_parallelism().map_or(1, |n| n.get());884 let cores = thread::available_parallelism().map_or(1, |n| n.get());
314- ((secs / PER_JOB_SECS) as usize).min(cores).min(CEILING).max(1)885+ ((secs / PER_JOB_SECS) as usize)
886+ .min(cores)
887+ .min(CEILING)
888+ .max(1)
315 }889 }
316 890
317 /// `part` folded into `peaks` bucket for bucket. Both are indexed absolutely,891 /// `part` folded into `peaks` bucket for bucket. Both are indexed absolutely,
@@ -375,12 +949,23 @@ mod tests {
375 use std::path::PathBuf;949 use std::path::PathBuf;
376 950
377 use super::{951 use super::{
378- memo_decodes, memoize, peaks, peaks_over, peaks_shared, peaks_shared_capped, MemoEntry,952+ memo_decodes, memoize, peak_of, peaks, peaks_over, peaks_shared_capped, viz_decodes,
379- PeaksKey, PeaksMemo, SharedPeaks,953+ viz_envelope, viz_envelope_capped, viz_folded, MemoEntry, PeaksKey, PeaksMemo, SharedPeaks,
954+ PEAKS_MEMO_BUCKETS,
380 };955 };
381 956
382 const BPS: u32 = 10;957 const BPS: u32 = 10;
383 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+
384 fn asset(name: &str) -> PathBuf {969 fn asset(name: &str) -> PathBuf {
385 PathBuf::from(env!("CARGO_MANIFEST_DIR"))970 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
386 .join("../../assets")971 .join("../../assets")
@@ -397,8 +982,34 @@ mod tests {
397 path982 path
398 }983 }
399 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+
400 #[test]1010 #[test]
401 fn peaks_follow_the_1hz_volume_pulse() {1011 fn peaks_follow_the_1hz_volume_pulse() {
1012+ let _serial = counters_serial();
402 let peaks = peaks(asset("test_av.mp4"), 0, BPS)1013 let peaks = peaks(asset("test_av.mp4"), 0, BPS)
403 .expect("open")1014 .expect("open")
404 .expect("test_av.mp4 has an audio track");1015 .expect("test_av.mp4 has an audio track");
@@ -451,6 +1062,7 @@ mod tests {
451 /// audio file on stream 0 as readily as an mp4's AAC track.1062 /// audio file on stream 0 as readily as an mp4's AAC track.
452 #[test]1063 #[test]
453 fn a_standalone_audio_file_has_peaks_too() {1064 fn a_standalone_audio_file_has_peaks_too() {
1065+ let _serial = counters_serial();
454 let peaks = peaks(asset("test_tone.mp3"), 0, BPS)1066 let peaks = peaks(asset("test_tone.mp3"), 0, BPS)
455 .expect("open")1067 .expect("open")
456 .expect("test_tone.mp3 is audio");1068 .expect("test_tone.mp3 is audio");
@@ -478,6 +1090,7 @@ mod tests {
478 /// flat -- rather than the empty band a silent file makes.1090 /// flat -- rather than the empty band a silent file makes.
479 #[test]1091 #[test]
480 fn a_five_one_aac_mkv_draws_an_envelope() {1092 fn a_five_one_aac_mkv_draws_an_envelope() {
1093+ let _serial = counters_serial();
481 let peaks = peaks(asset("test_hevc10.mkv"), 0, BPS)1094 let peaks = peaks(asset("test_hevc10.mkv"), 0, BPS)
482 .expect("the 5.1 AAC track decodes")1095 .expect("the 5.1 AAC track decodes")
483 .expect("test_hevc10.mkv has an audio track");1096 .expect("test_hevc10.mkv has an audio track");
@@ -505,6 +1118,7 @@ mod tests {
505 /// waveform is still the film's.1118 /// waveform is still the film's.
506 #[test]1119 #[test]
507 fn a_split_decode_draws_the_same_envelope() {1120 fn a_split_decode_draws_the_same_envelope() {
1121+ let _serial = counters_serial();
508 let file = asset("test_av.mp4");1122 let file = asset("test_av.mp4");
509 let whole = peaks_over(&file, 0, BPS, Some(1))1123 let whole = peaks_over(&file, 0, BPS, Some(1))
510 .expect("open")1124 .expect("open")
@@ -529,11 +1143,10 @@ mod tests {
529 1143
530 #[test]1144 #[test]
531 fn video_only_source_has_no_peaks() {1145 fn video_only_source_has_no_peaks() {
532- assert!(1146+ let _serial = counters_serial();
533- peaks(asset("test_baseline.mp4"), 0, BPS)1147+ assert!(peaks(asset("test_baseline.mp4"), 0, BPS)
534- .expect("open")1148+ .expect("open")
535- .is_none()1149+ .is_none());
536- );
537 }1150 }
538 1151
539 /// Two streams of one file are two envelopes: the lane draws what the clip1152 /// Two streams of one file are two envelopes: the lane draws what the clip
@@ -542,6 +1155,7 @@ mod tests {
542 /// stream 0's 4-second-long pulsed stereo pair.1155 /// stream 0's 4-second-long pulsed stereo pair.
543 #[test]1156 #[test]
544 fn each_stream_of_a_file_has_its_own_envelope() {1157 fn each_stream_of_a_file_has_its_own_envelope() {
1158+ let _serial = counters_serial();
545 let multi = asset("test_multiaudio.mp4");1159 let multi = asset("test_multiaudio.mp4");
546 let zero = peaks(&multi, 0, BPS).expect("open").expect("stream 0");1160 let zero = peaks(&multi, 0, BPS).expect("open").expect("stream 0");
547 let one = peaks(&multi, 1, BPS).expect("open").expect("stream 1");1161 let one = peaks(&multi, 1, BPS).expect("open").expect("stream 1");
@@ -553,7 +1167,9 @@ mod tests {
553 assert_ne!(zero[0], one[0], "...and they differ from the first bucket");1167 assert_ne!(zero[0], one[0], "...and they differ from the first bucket");
554 // Stream 2 is AC-3, and it decodes now: it draws its own envelope like1168 // Stream 2 is AC-3, and it decodes now: it draws its own envelope like
555 // any other stream rather than being refused.1169 // any other stream rather than being refused.
556- let two = peaks(&multi, 2, BPS).expect("AC-3 opens").expect("stream 2");1170+ let two = peaks(&multi, 2, BPS)
1171+ .expect("AC-3 opens")
1172+ .expect("stream 2");
557 assert!(!two.is_empty(), "the AC-3 stream drew nothing");1173 assert!(!two.is_empty(), "the AC-3 stream drew nothing");
558 }1174 }
559 1175
@@ -564,6 +1180,7 @@ mod tests {
564 /// down, where the visualizer seat reads it.1180 /// down, where the visualizer seat reads it.
565 #[test]1181 #[test]
566 fn the_shared_memo_answers_per_stream() {1182 fn the_shared_memo_answers_per_stream() {
1183+ let _serial = counters_serial();
567 let multi = asset("test_multiaudio.mp4");1184 let multi = asset("test_multiaudio.mp4");
568 let zero = peaks_shared(&multi, 0, BPS)1185 let zero = peaks_shared(&multi, 0, BPS)
569 .expect("open")1186 .expect("open")
@@ -593,7 +1210,9 @@ mod tests {
593 /// read-only for every other test in this binary.1210 /// read-only for every other test in this binary.
594 #[test]1211 #[test]
595 fn a_replaced_source_is_read_again() {1212 fn a_replaced_source_is_read_again() {
596- let path = std::env::temp_dir().join(format!("edith-peaks-memo-{}.mp4", std::process::id()));1213+ let _serial = counters_serial();
1214+ let path =
1215+ std::env::temp_dir().join(format!("edith-peaks-memo-{}.mp4", std::process::id()));
597 let short = std::fs::read(asset("test_multiaudio.mp4")).expect("read the fixture");1216 let short = std::fs::read(asset("test_multiaudio.mp4")).expect("read the fixture");
598 let long = std::fs::read(asset("test_av.mp4")).expect("read the fixture");1217 let long = std::fs::read(asset("test_av.mp4")).expect("read the fixture");
599 // The two halves below are the length half and the clock half of the1218 // The two halves below are the length half and the clock half of the
@@ -603,14 +1222,20 @@ mod tests {
603 std::fs::write(&path, &short).expect("write the copy");1222 std::fs::write(&path, &short).expect("write the copy");
604 let first = peaks_shared(&path, 0, BPS).expect("open").expect("copy");1223 let first = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
605 let again = peaks_shared(&path, 0, BPS).expect("open").expect("copy");1224 let again = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
606- assert!(std::sync::Arc::ptr_eq(&first, &again), "the copy was not memoized");1225+ assert!(
1226+ std::sync::Arc::ptr_eq(&first, &again),
1227+ "the copy was not memoized"
1228+ );
607 1229
608 // Other bytes behind the same path. A key without the file's length1230 // Other bytes behind the same path. A key without the file's length
609 // (or without any stat at all) serves `first` here -- the envelope of1231 // (or without any stat at all) serves `first` here -- the envelope of
610 // bytes that are gone.1232 // bytes that are gone.
611 std::fs::write(&path, &long).expect("rewrite the copy");1233 std::fs::write(&path, &long).expect("rewrite the copy");
612 let replaced = peaks_shared(&path, 0, BPS).expect("open").expect("copy");1234 let replaced = peaks_shared(&path, 0, BPS).expect("open").expect("copy");
613- assert_ne!(*replaced, *first, "the memo served the replaced file's envelope");1235+ assert_ne!(
1236+ *replaced, *first,
1237+ "the memo served the replaced file's envelope"
1238+ );
614 assert_eq!(1239 assert_eq!(
615 *replaced,1240 *replaced,
616 peaks(&path, 0, BPS).expect("open").expect("copy"),1241 peaks(&path, 0, BPS).expect("open").expect("copy"),
@@ -640,18 +1265,19 @@ mod tests {
640 /// one. A copy is used so the key is this test's alone.1265 /// one. A copy is used so the key is this test's alone.
641 #[test]1266 #[test]
642 fn a_trackless_source_is_memoized_too() {1267 fn a_trackless_source_is_memoized_too() {
1268+ let _serial = counters_serial();
643 let path = copy_of("test_baseline.mp4", "none");1269 let path = copy_of("test_baseline.mp4", "none");
644 1270
645- let before = memo_decodes();1271+ let before = memo_decodes(&path, 0, BPS);
646 let first = peaks_shared(&path, 0, BPS).expect("open");1272 let first = peaks_shared(&path, 0, BPS).expect("open");
647 assert!(first.is_none(), "test_baseline.mp4 has no audio track");1273 assert!(first.is_none(), "test_baseline.mp4 has no audio track");
648- let after_first = memo_decodes();1274+ let after_first = memo_decodes(&path, 0, BPS);
649 assert_eq!(after_first - before, 1, "the first ask did not decode");1275 assert_eq!(after_first - before, 1, "the first ask did not decode");
650 1276
651 let second = peaks_shared(&path, 0, BPS).expect("open");1277 let second = peaks_shared(&path, 0, BPS).expect("open");
652 assert!(second.is_none());1278 assert!(second.is_none());
653 assert_eq!(1279 assert_eq!(
654- memo_decodes(),1280+ memo_decodes(&path, 0, BPS),
655 after_first,1281 after_first,
656 "the second ask re-opened a trackless source"1282 "the second ask re-opened a trackless source"
657 );1283 );
@@ -664,6 +1290,7 @@ mod tests {
664 /// the `NoTrack` entry for an envelope without stranding the old count.1290 /// the `NoTrack` entry for an envelope without stranding the old count.
665 #[test]1291 #[test]
666 fn a_trackless_answer_holds_no_buckets() {1292 fn a_trackless_answer_holds_no_buckets() {
1293+ let _serial = counters_serial();
667 let mut memo = PeaksMemo::new();1294 let mut memo = PeaksMemo::new();
668 let mut count = 0;1295 let mut count = 0;
669 let key = || PeaksKey::of(std::path::Path::new("edith-peaks-none-key"), 0, BPS);1296 let key = || PeaksKey::of(std::path::Path::new("edith-peaks-none-key"), 0, BPS);
@@ -691,13 +1318,14 @@ mod tests {
691 /// Does not cover: an end-to-end decode past eight million buckets.1318 /// Does not cover: an end-to-end decode past eight million buckets.
692 #[test]1319 #[test]
693 fn an_envelope_over_the_ceiling_is_not_held() {1320 fn an_envelope_over_the_ceiling_is_not_held() {
1321+ let _serial = counters_serial();
694 let file = copy_of("test_av.mp4", "over");1322 let file = copy_of("test_av.mp4", "over");
695- let before = memo_decodes();1323+ let before = memo_decodes(&file, 0, BPS);
696 let first = peaks_shared_capped(&file, 0, BPS, 10)1324 let first = peaks_shared_capped(&file, 0, BPS, 10)
697 .expect("open")1325 .expect("open")
698 .expect("test_av.mp4 has an audio track");1326 .expect("test_av.mp4 has an audio track");
699 assert!(first.len() > 10, "the fixture must exceed the test ceiling");1327 assert!(first.len() > 10, "the fixture must exceed the test ceiling");
700- let mid = memo_decodes();1328+ let mid = memo_decodes(&file, 0, BPS);
701 assert_eq!(mid - before, 1, "the first ask did not decode");1329 assert_eq!(mid - before, 1, "the first ask did not decode");
702 1330
703 let second = peaks_shared_capped(&file, 0, BPS, 10)1331 let second = peaks_shared_capped(&file, 0, BPS, 10)
@@ -705,7 +1333,7 @@ mod tests {
705 .expect("test_av.mp4 has an audio track");1333 .expect("test_av.mp4 has an audio track");
706 assert_eq!(*first, *second, "the caller did not get its envelope");1334 assert_eq!(*first, *second, "the caller did not get its envelope");
707 assert_eq!(1335 assert_eq!(
708- memo_decodes() - mid,1336+ memo_decodes(&file, 0, BPS) - mid,
709 1,1337 1,
710 "an envelope over the ceiling was held"1338 "an envelope over the ceiling was held"
711 );1339 );
@@ -724,6 +1352,7 @@ mod tests {
724 /// 3 + 5 = 8.1352 /// 3 + 5 = 8.
725 #[test]1353 #[test]
726 fn replacing_an_entry_subtracts_the_old_buckets() {1354 fn replacing_an_entry_subtracts_the_old_buckets() {
1355+ let _serial = counters_serial();
727 let mut memo = PeaksMemo::new();1356 let mut memo = PeaksMemo::new();
728 let mut count = 0;1357 let mut count = 0;
729 let key = || PeaksKey::of(std::path::Path::new("edith-peaks-replace-key"), 0, BPS);1358 let key = || PeaksKey::of(std::path::Path::new("edith-peaks-replace-key"), 0, BPS);
@@ -747,4 +1376,377 @@ mod tests {
747 assert_eq!(count, 5, "the replaced entry's buckets were not subtracted");1376 assert_eq!(count, 5, "the replaced entry's buckets were not subtracted");
748 assert_eq!(memo.len(), 1, "the replace added a second entry");1377 assert_eq!(memo.len(), 1, "the replace added a second entry");
749 }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+ }
750 }1752 }