diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index c716fb2..a5a755f 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -649,22 +649,33 @@ impl DecodeSession { // Painted at the canvas's own size, so the composite places nothing: // the picture *is* the canvas, and whatever transform the clip // carries still reaches it through the render below. - let (width, height) = canvas.dims(); + // + // Masked to even dimensions first, and floored at two: that is what the + // painter does to the planes it hands back, so a canvas it cannot divide + // evenly (an odd `resolution 1921 1081` line, or a one-pixel-high one) + // used to be *declared* at a size the picture never had -- and the + // conversion below then indexes a chroma plane that is not there + // (`index out of bounds` on a zero-length slice, in this worker, where + // no frame ever arrives and nothing catches it). + let (canvas_w, canvas_h) = canvas.dims(); + let (width, height) = ((canvas_w & !1).max(2), (canvas_h & !1).max(2)); let worker_cancel = Arc::clone(&cancel); let path = path.to_path_buf(); let handle = thread::Builder::new() .name("viz".into()) .spawn(move || { - // The one decode this seat ever does: the whole envelope, - // off the render thread, and abandoned at once if the caller - // is already gone. A file that will not open -- and one with - // no track at all -- paints the flat line, which is what its - // silence looks like anyway: a visualizer frame always - // exists, and is never worth failing a span over. - let peaks = crate::waveform::peaks_shared(&path, stream, VIZ_BUCKETS_PER_SEC) - .ok() - .flatten() - .unwrap_or_default(); + // The envelope this span paints from, asked for once for the + // whole span: the memo's own handle when it holds one, and + // otherwise a *window* of the file's envelope per frame -- + // which is what makes a rebuild cheap for a source whose whole + // envelope does not fit the memo at all ([`viz_envelope`]). A + // file that will not open -- and one with no track at all -- + // paints the flat line, which is what its silence looks like + // anyway: a visualizer frame always exists, and is never worth + // failing a span over. + let mut envelope = + crate::waveform::viz_envelope(&path, stream, VIZ_BUCKETS_PER_SEC) + .unwrap_or(crate::waveform::VizEnvelope::Silent); if worker_cancel.load(Ordering::Relaxed) { return; } @@ -687,8 +698,14 @@ impl DecodeSession { return; } let t = f64::from(start_frame + index) / fps; - let (y, u, v) = - visualizer_i420(&mut scratch, &peaks, t, width, height, flags, paint); + // One window of the envelope about this frame's own time: + // the same window for every frame a sliding paint asks of + // the same thirty seconds, and no decode at all for the + // rebuilds of a look edit. + let view = envelope.view_at(t); + let (y, u, v) = visualizer_window_i420( + &mut scratch, &view, t, width, height, flags, paint, + ); let frame = render.frame(start_frame + index, &y, &u, &v, width, height); if tx.send(frame).is_err() { return; // caller moved on @@ -2094,6 +2111,10 @@ fn viz_chain( /// [`viz_style`]: a bipolar sample trace (Audacity), a filled min/max /// envelope at pixel resolution, or a multi-strand ribbon. Ink is /// [`viz_ink_from_paint`]. A frame always exists; silence is the zero line. +/// +/// This is the whole-envelope entry: it is handed the file's envelope and +/// paints from it ([`VizView::whole`]). The seat paints from a *window* of one +/// instead ([`visualizer_window_i420`], [`crate::waveform::viz_envelope`]). pub(crate) fn visualizer_i420( scratch: &mut VizScratch, peaks: &[(f32, f32)], @@ -2102,6 +2123,91 @@ pub(crate) fn visualizer_i420( height: u32, flags: u8, paint: u64, +) -> (Vec, Vec, Vec) { + visualizer_window_i420(scratch, &VizView::whole(peaks), t_secs, width, height, flags, paint) +} + +/// The envelope a visualizer frame is painted from: the whole file, or one +/// *window* of it -- which is what the seat holds, because a film's own +/// envelope is past the memo's ceiling ([`crate::waveform::viz_envelope`]). +/// +/// `peaks[i]` is the bucket at absolute index `first + i`, so the painter's +/// index arithmetic is the same whether it was handed a slice of thirty +/// seconds or of two hours. `total` is the *file's* own bucket count, which is +/// what "past the end of the file" is measured against -- a window that +/// measured it against itself would draw the file's end wherever the window +/// ended -- and `peak` is the file's loudest bucket, which every column is +/// scaled by: no window can derive that from itself. +/// +/// `per_sec` is the rate *this* envelope was drawn at, in buckets per second, +/// and it is carried rather than assumed: the slice is indexed at it, so an +/// envelope drawn at another rate under a painter that hard-coded the +/// visualizer's own would read a tenth of a second of sound as a second. The +/// whole-file constructor is the one place the visualizer's rate is named. +pub(crate) struct VizView<'a> { + pub(crate) peaks: &'a [(f32, f32)], + pub(crate) first: usize, + pub(crate) total: usize, + pub(crate) peak: f32, + pub(crate) per_sec: f64, +} + +impl<'a> VizView<'a> { + /// The whole envelope, which is what every caller but the seat has. + pub(crate) fn whole(peaks: &'a [(f32, f32)]) -> Self { + Self { + peaks, + first: 0, + total: peaks.len(), + peak: crate::waveform::peak_of(peaks), + per_sec: f64::from(VIZ_BUCKETS_PER_SEC), + } + } + + /// One window of an envelope: `peaks` starts at absolute bucket `first`, + /// `total` and `peak` are the whole file's, and `per_sec` is the rate the + /// file's envelope was drawn at. + pub(crate) fn window( + peaks: &'a [(f32, f32)], + first: usize, + total: usize, + peak: f32, + per_sec: f64, + ) -> Self { + Self { + peaks, + first, + total, + peak, + per_sec, + } + } + + /// The bucket at absolute index `abs`, when this view carries it: the + /// window's own edges are not the file's, and a frame asked for one of + /// them draws silence rather than a bucket that is only half decoded. + pub(crate) fn at(&self, abs: usize) -> Option<(f32, f32)> { + abs.checked_sub(self.first) + .and_then(|i| self.peaks.get(i)) + .copied() + } + + fn is_empty(&self) -> bool { + self.peaks.is_empty() + } +} + +/// [`visualizer_i420`] from a view, which is how the seat paints: `peaks` may +/// be a window rather than the file's own envelope, and `t_secs` is the +/// frame's own time either way -- the view knows where its slice starts. +pub(crate) fn visualizer_window_i420( + scratch: &mut VizScratch, + view: &VizView, + t_secs: f64, + width: u32, + height: u32, + flags: u8, + paint: u64, ) -> (Vec, Vec, Vec) { let width = width & !1; let height = height & !1; @@ -2138,9 +2244,9 @@ pub(crate) fn visualizer_i420( scratch.hi.resize(w, 0.0); scratch.sig.clear(); scratch.sig.resize(w, 0.0); - if !peaks.is_empty() { - let duration = peaks.len() as f64 / f64::from(VIZ_BUCKETS_PER_SEC); - let per_sec = f64::from(VIZ_BUCKETS_PER_SEC); + if !view.is_empty() && view.total != 0 { + let duration = view.total as f64 / view.per_sec; + let per_sec = view.per_sec; let window = if flags & VIZ_FAST != 0 { VIZ_FAST_SECS } else { @@ -2155,11 +2261,17 @@ pub(crate) fn visualizer_i420( if !t.is_finite() || t < 0.0 || t > duration { return (0.0, 0.0); } - let pos = (t * per_sec).clamp(0.0, (peaks.len() - 1) as f64); + let pos = (t * per_sec).clamp(0.0, (view.total - 1) as f64); let i = pos.floor() as usize; let f = (pos - i as f64) as f32; - let (lo0, hi0) = peaks[i]; - let (lo1, hi1) = peaks[(i + 1).min(peaks.len() - 1)]; + // Silence where the slice does not reach: a view that is a window + // is only handed the buckets the frame can ask for, so this is the + // file's own ends and nothing else. + let (Some((lo0, hi0)), Some((lo1, hi1))) = + (view.at(i), view.at((i + 1).min(view.total - 1))) + else { + return (0.0, 0.0); + }; ( (lo0 + (lo1 - lo0) * f).clamp(-1.0, 0.0), (hi0 + (hi1 - hi0) * f).clamp(0.0, 1.0), @@ -2186,11 +2298,10 @@ pub(crate) fn visualizer_i420( } // Whole-file peak, not the window's: a 2s window that gains or loses // a loud hit used to rescale every column, so the same bump changed - // height as it entered and left the picture. - let peak = peaks - .iter() - .map(|&(l, h)| l.abs().max(h.abs())) - .fold(0.0f32, f32::max); + // height as it entered and left the picture. A view carries that peak + // with it ([`VizView`]), because a window of a film could not compute + // it from the megabyte it holds. + let peak = view.peak; if peak > 1e-4 { for i in 0..w { scratch.lo[i] /= peak; diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index be6c899..1ef55ad 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -16,7 +16,7 @@ use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering} use std::sync::mpsc::{Receiver, TryRecvError}; use std::sync::{Arc, Mutex}; use std::thread; -use std::time::Duration; +use std::time::{Duration, Instant}; use crate::ao::AoSession; use crate::audio::{AudioChunk, AudioSession}; @@ -52,6 +52,23 @@ const FLUSH_WAIT: Duration = Duration::from_millis(1); /// all pays this once per span rather than freezing the preview outright. const DISSOLVE_B_TIMEOUT: Duration = Duration::from_millis(200); +/// How long a dead output is left alone before another open is attempted. A +/// PipeWire daemon restart takes a moment, and the ask that makes the attempt +/// runs once per rendered frame: a second is long enough that a restart lands +/// inside it, and short enough that a play pressed after one does not wait. +const AUDIO_REARM_AFTER: Duration = Duration::from_secs(1); + +/// The reason a session gives for having gone quiet when its output dies +/// ([`PlaybackSession::tick`]), through the same door a file's own refusal +/// reaches a front-end by ([`PlaybackSession::audio_disabled_reason`]). +/// +/// That door is read where a notice is *built* -- at open and at load -- so this +/// is fetchable rather than announced: the engine sets the reason and clears it +/// again when the output comes back, and a front-end that reads the door after +/// the session is open (a per-frame check, or one at the next load) is what +/// shows it. Nothing here pushes a notice. +const AUDIO_LOST: &str = "output device went away -- reconnecting the timeline's sound"; + /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 -- /// nothing was shot on it, so it is the canvas a *later* import meets rather /// than a description of the song. H.264 because it is the one codec that @@ -149,6 +166,13 @@ struct Audio { /// at once -- which is precisely what /// [`live_workers`](PlaybackSession::live_workers) is asked about. feeders: Arc, + /// When this device was last opened *again* after dying + /// ([`PlaybackSession::rearm_audio`]). A dead output is offered one open a + /// second and no more, because the ask that makes the attempt runs once per + /// rendered frame: a daemon restart takes a moment, and a device that is + /// gone for good must not be opened sixty times a second for the rest of + /// the session. + rearm_at: Arc>>, } /// How much of the played signal the tap keeps. A power of two, because what @@ -2672,7 +2696,12 @@ impl PlaybackSession { /// ([`Self::seek`]'s own `switch_to_audio`), which is the seek a front-end /// makes as it places the file it just imported. fn arm_audio(&mut self) { - if self.audio.is_some() { + // A device that is there but *dead* is not a device: the walk below + // opens another one, which is also what clears the notice a death put up + // ([`Self::tick`]). + if let Some(audio) = &self.audio + && !audio.died.load(Ordering::Acquire) + { return; } for source in self @@ -2690,6 +2719,63 @@ impl PlaybackSession { } } + /// Opens the output again for a stream that died, at the rate and channel + /// count it carried, and clears the flag that stopped the session feeding. + /// + /// An output that goes away -- a PipeWire daemon restarting, a sink node + /// removed and put back -- leaves every stream that was open on it dead for + /// good: its position is frozen, so the clock can only fall to wall time, and + /// a session that never opens another device is silent for the rest of its + /// life, through every seek and every pause/play, with nothing said about it. + /// + /// The device *only*, never the file: the feeder is [`Self::start_audio`]'s, + /// at the seek that follows. That is what lets [`Self::tick`] call this too, + /// once a frame -- a tick is not a seek and must not reseek the timeline. The + /// clock is on wall time by then and stays there until a seek comes, which is + /// the seek whose feeder opens in step with the picture. + /// + /// `if_idle_for` is the cooldown: a tick passes [`AUDIO_REARM_AFTER`], because + /// sixty opens a second against a device that is gone for good is a spin; a + /// seek passes zero, because that one is a person asking. + /// + /// `false` when there is nothing to open, nothing came back, or the cooldown + /// has not passed -- and the flag stays standing for the next attempt. + fn rearm_audio(&mut self, if_idle_for: Duration) -> bool { + let Some(audio) = &self.audio else { + return false; + }; + if !audio.died.load(Ordering::Acquire) { + return true; + } + { + let mut at = audio.rearm_at.lock().unwrap(); + if at.is_some_and(|at| at.elapsed() < if_idle_for) { + return false; + } + *at = Some(Instant::now()); + } + let Some(ao) = AoSession::open(audio.sample_rate, audio.channels as u32) else { + return false; + }; + // A stream comes up streaming and a session starts paused: the fresh one + // is silenced until the seek that feeds it says otherwise, which is the + // same two steps [`open_audio`] takes on the way in. + ao.set_active(false); + // Replacing the session is what closes the dead stream, so it is done + // under the device lock the feeder writes through. + *audio.ao.lock().unwrap() = ao; + // The clock anchor and the played-out arithmetic both belong to the + // stream that died: the new one stamps its own first sample + // ([`Audio::content_at`]), and `start_audio` re-bases the count from the + // device's own position. + audio.content_at.store(-1, Ordering::Release); + audio.died.store(false, Ordering::Release); + if self.audio_disabled.as_deref() == Some(AUDIO_LOST) { + self.audio_disabled = None; + } + true + } + /// The rate noted for whichever source plays `path`, by /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session @@ -3910,6 +3996,12 @@ impl PlaybackSession { let fps = self.meta.frame_rate; let mut audio_running = false; let mut live = None; + // A dead output gets an attempt here without waiting out the cooldown: a + // seek is a person asking, and this is the one moment the sound can come + // back into step with the picture, because the feeder opened below starts + // at the target. If it does not come back the flag stands and the guard + // under it leaves the clock on wall time. + self.rearm_audio(Duration::ZERO); if let Some(audio) = &self.audio && !audio.died.load(Ordering::Acquire) { @@ -4079,19 +4171,37 @@ impl PlaybackSession { // still be moving it -- otherwise the queue fills with pictures whose // moment passed while nobody was taking them. self.publish_playhead(); + // Before the clock-source guard below, and not after it: a dead output is + // what *puts* the clock on wall time, so this branch has to keep running + // while it is there -- the one attempt that can bring the sound back is + // in it. + if self + .audio + .as_ref() + .is_some_and(|audio| audio.died.load(Ordering::Acquire)) + { + // Output died mid-stream: its position will never reach `fed`, so the + // EOF comparison below is unreachable. Wall time takes over from + // wherever the clock last stood, and the session says so rather than + // going silent for good without a word: a front-end already has a + // line for a silent session ([`Self::audio_disabled_reason`]). + if self.audio_disabled.is_none() { + self.audio_disabled = Some(AUDIO_LOST.to_string()); + } + self.clock.switch_to_wall(); + // ...and the output is offered another open, once a second: a + // restarting daemon takes a moment, and this runs once a frame. A + // re-arm that takes is what clears the notice, and the next seek + // feeds it. + self.rearm_audio(AUDIO_REARM_AFTER); + return; + } let Some(audio) = &self.audio else { return; // wall time from the start, nothing to poll }; if self.clock.source() != ClockSource::Audio { return; } - if audio.died.load(Ordering::Acquire) { - // Output died mid-stream: its position will never reach `fed`, so - // the EOF comparison below is unreachable. Wall time takes over - // from wherever the clock last stood. - self.clock.switch_to_wall(); - return; - } // `None` until the device's first callback: the clock holds at its // anchor rather than guessing, which is why playback starts on time // instead of a quantum early. @@ -4420,6 +4530,7 @@ fn open_audio(path: &Path, stream: usize) -> (Option