//! Background decode worker. Frames leave over a bounded channel so the caller's //! thread (the UI thread) never blocks on decode and memory stays capped. use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}; use std::thread; use ec_core::frame::VideoFrame; use ec_av1::encode::Picture as Av1Picture; use ec_av1::stream::decode_stream_with; use ec_core::registry::{CodecId, CodecParameters}; use ec_core::registry::Decoder as _; use ec_core::{Error as Av1Error, Packet, TimeBase}; use ec_h264::H264Decoder; use crate::color::ColorParams; use crate::colorspace::{ColorDescription, Matrix, Transfer}; use crate::convert::{i420_to_bgra, i420_to_bgra_with}; use crate::demux::{Codec, Demuxer, PixelAspect, Rotation, VideoMeta}; use crate::hw::HwSession; use crate::project::Speed; use crate::scale::Composer; use crate::tonemap::{self, ToneMapper}; use crate::transform::TransformParams; /// One decoded picture, ready to hand to a renderer. pub struct Frame { /// Position in display order, starting at 0. pub index: u32, pub width: u32, pub height: u32, /// BGRA8, straight alpha, tightly packed. pub bgra: Vec, } /// Which decoder a source is really running on. Read-only introspection: it /// decides nothing, it *reports* what [`DecodeSession::open_worker`] chose -- /// a hardware session that opened and then failed before its first picture /// falls back to software and this says so, because it is written where the /// fallback happens rather than where it was hoped for. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum Backend { /// The worker has not reached its decoder yet: the plugin's VA-API init is /// ~90 ms, and this is what a caller reads in that window. #[default] Opening, /// The VA-API plugin (`libengine_hw.so`). Hardware, /// This project's own software seat: `ec-h264` or `ec-av1`, in this /// process. Software, /// A still image: one `image` decode, no stream and no decoder to pick. Still, /// A gap: black frames, nothing decoded at all. Gap, /// A waveform visualizer: the picture is painted from the audio's peaks /// ([`visualizer_i420`]), no decoder seat and no stream of pictures at all. Visualizer, } impl Backend { /// Short enough for a library row and a transport line. pub fn label(self) -> &'static str { match self { Self::Opening => "opening", Self::Hardware => "HW", Self::Software => "SW", Self::Still => "still", Self::Gap => "gap", Self::Visualizer => "viz", } } fn code(self) -> u8 { match self { Self::Opening => 0, Self::Hardware => 1, Self::Software => 2, Self::Still => 3, Self::Gap => 4, Self::Visualizer => 5, } } fn from_code(code: u8) -> Self { match code { 1 => Self::Hardware, 2 => Self::Software, 3 => Self::Still, 4 => Self::Gap, 5 => Self::Visualizer, _ => Self::Opening, } } } /// Where a worker publishes the decoder it opened, for whoever holds the other /// end of its channel. One atomic byte, written once at open (and once more if /// hardware hands the range back to software), read whenever a caller repaints /// -- never per frame on either side. #[derive(Clone, Default)] pub struct BackendCell(Arc); impl BackendCell { pub(crate) fn new(backend: Backend) -> Self { Self(Arc::new(AtomicU8::new(backend.code()))) } fn set(&self, backend: Backend) { self.0.store(backend.code(), Ordering::Relaxed); } pub fn get(&self) -> Backend { Backend::from_code(self.0.load(Ordering::Relaxed)) } } /// Which decoder `path` would open, decided exactly as [`DecodeSession::open_worker`] /// decides it: the same `VE_SW` pin and the same plugin probe against this very /// file. What lets a front-end name the decoder *before* anything plays. /// /// The codec is `None` for a still image, which has no coded stream. A stream /// no decoder here can take is an `Err` naming the plugin, exactly as opening /// it would be -- the same refusal, one VA-API init earlier. /// /// Costs that one init (~90 ms) for a stream the plugin takes: ask it once per /// file, off a render thread, and keep the answer. pub fn probe(path: &Path) -> crate::Result<(Option, Backend)> { if crate::is_image(path) { return Ok((None, Backend::Still)); } let path = path.to_path_buf(); let (meta, _demuxer) = Demuxer::open(&path)?; match hw_decodes(&path, 0, meta.codec) { Ok(()) => return Ok((Some(meta.codec), Backend::Hardware)), Err(e) if !matches!(meta.codec, Codec::H264 | Codec::Av1) => return Err(e.into()), Err(_) => {} } Ok((Some(meta.codec), Backend::Software)) } /// A running decode worker: the flag that stops it, and the handle to wait on. /// /// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize` /// outlives the process otherwise, and Mesa's `atexit` handlers free the state /// it is still reading -- a SIGSEGV at exit, long after the last test passed. pub(crate) struct Worker { cancel: Arc, /// `None` once detached, and for a range with nothing to decode: either way /// there is no thread left to wait for. handle: Option>, /// How a *later* span reaches this same thread ([`Worker::reseek`]), for the /// workers that decode a file: the still, the gap and a detached worker have /// no such door and are the one-span threads they always were. reuse: Option, } /// The door a persistent decode worker is steered through: the file it has open, /// the channel its next span arrives on, and the generation counter that tells /// the span it is decoding *now* that nobody is waiting for it any more. /// /// The point of all three is that a seek onto the same file costs a demuxer /// seek and a decoder flush ([`crate::hw::HwSession::seek`]) rather than a /// thread, a container parse and a VA-API initialisation (98 ms measured). struct Reuse { path: PathBuf, spans: std::sync::mpsc::Sender, /// Bumped by every reseek and by [`Worker::abandon`]; the decode loop stops /// the moment it no longer matches the span it was handed. generation: Arc, /// The worker's decoder, published once and read across every span it /// decodes -- so a reseek onto a file already open says "hardware" from the /// first repaint instead of going back through `opening`. backend: BackendCell, /// Where the caller's playhead stands, in this file's own frames /// ([`Worker::playhead`]): the worker converts and sends nothing behind it. /// Rewritten to the target by every reseek, so it can never carry one span's /// position into the next. floor: Arc, } /// One span asked of a persistent worker: the range in the file's own frames, /// everything a picture is graded, placed and mapped by, and the channel the /// pictures go down. Carries its generation, so a command already superseded on /// its way through the queue is dropped rather than decoded. struct SpanCmd { generation: u64, start: u32, end: u32, color: ColorParams, transform: TransformParams, canvas: Composer, tone: tonemap::Preset, /// The clip's own playback speed ([`crate::project::Clip::speed`]), for /// [`skip_for_speed`]: at faster than real time several source frames in a /// row land on the same timeline frame, and only the last of a run is ever /// shown. [`Speed::NORMAL`] for a file-level open ([`DecodeSession::open`] /// and friends), which has no clip and skips nothing. speed: Speed, tx: SyncSender, } /// What stops a decode loop: the worker's terminal flag (the thread itself is /// going away) and the generation of the span it was handed (only *this* span is /// going away). One check, so every loop treats them alike. /// /// ...and where the playhead has reached ([`Abort::late`]), which is the same /// question one picture at a time: a frame due before it is a frame nobody can /// be shown any more. struct Abort<'a> { cancel: &'a AtomicBool, generation: &'a AtomicU64, mine: u64, floor: &'a AtomicU32, } impl Abort<'_> { fn hit(&self) -> bool { self.cancel.load(Ordering::Relaxed) || self.generation.load(Ordering::Acquire) != self.mine } /// Whether the picture at source frame `index` is already past due: the /// caller's playhead has gone by it, so converting it (a full BGRA pass over /// 8 MB at 1080p) and queueing it would only push a picture nobody sees in /// front of the one they are waiting for. /// /// It is still *decoded* -- the pictures after it reference it -- and the /// floor only ever moves with the playhead the session publishes, so a /// paused session (and every seek, which republishes its own target) drops /// nothing at all. fn late(&self, index: u32) -> bool { self.floor.load(Ordering::Relaxed) > index } } /// Whether the picture at source frame `due` (of a span starting at `start` and /// ending at `end`) is redundant *by construction* at `speed`, and its convert /// and send can be skipped without ever waiting on the playhead /// ([`Abort::late`]): at faster than real time several source frames in a row /// map to the same timeline frame ([`Speed::timeline_at`]), and only the last /// of such a run is ever shown -- the newest one always lands after the others /// in `try_frame`'s stamp comparison. Unlike a late drop this needs no run /// limit: the gap between two kept frames is at most `speed` source frames, so /// the picture stream this leaves is never silent, only sparser. /// /// The last frame of the whole span is never skipped by this: it is the /// picture [`crate::project::Span::source_len`] was built to land exactly on, /// and this is what proves that promise here instead of trusting it blind. /// /// corner-cut: `due` and `start` are the file's own frame numbers, so this /// is only correct when the file plays at the timeline's own rate /// ([`crate::project::Rate::is_real_time`]) -- callers pass [`Speed::NORMAL`] /// (never skip) otherwise. Upgrade path is composing `Rate` into this the way /// [`crate::project::Span::timeline_at`] does. fn skip_for_speed(speed: Speed, start: u32, due: u32, end: u32) -> bool { if speed.is_normal() || due + 1 >= end { return false; } let rel = due - start; speed.timeline_at(rel) == speed.timeline_at(rel + 1) } impl Worker { /// Stops the worker *and its thread* at their next check, without waiting. /// Callers that replace a worker should do this first and drop the receiver /// second: a worker parked in `send` only wakes on the disconnect, so the /// join below would otherwise wait for a consumer that is never coming. /// /// The command channel goes with it, which is what wakes a persistent worker /// parked between spans -- without that it would sit in `recv` forever and a /// retired worker would never be reaped (nor joined at exit in any bounded /// time, which is the Mesa `atexit` hazard this whole type exists for). pub(crate) fn cancel(&mut self) { self.cancel.store(true, Ordering::Release); self.reuse = None; } /// Stops the span the worker is decoding, keeping the *thread* -- and with /// it the open file and the open decoder -- for the span that follows. What /// a seek does, since the next thing it says is [`Worker::reseek`]. /// /// Falls back to [`cancel`](Self::cancel) for a worker with nothing to /// reuse (a still, a gap, a detached one), where the two mean the same /// thing: this worker has no next span. pub(crate) fn abandon(&mut self) { match &self.reuse { Some(reuse) => { reuse.generation.fetch_add(1, Ordering::Release); } None => self.cancel(), } } /// Tells the worker where the caller's playhead stands, in the file's own /// frames: it converts and queues nothing behind that, because a picture /// whose moment has passed cannot be shown and would only delay the one that /// can (see [`Abort::late`]). A worker with no reuse door -- a still, a gap /// -- has nothing to tell, and this costs it nothing to say. pub(crate) fn playhead(&self, source_frame: u32) { if let Some(reuse) = &self.reuse { reuse.floor.store(source_frame, Ordering::Relaxed); } } /// Points this worker at another range of the file it already has open, /// handing back the channel the new span's pictures arrive on and the cell /// that says what is decoding them. `None` when this worker cannot take the /// job -- another file, no reuse door, or a thread that has already returned /// -- and the caller then opens a worker of its own, exactly as it always /// did. /// /// The pictures of the *old* span are left in their own channel, which the /// caller drops: that disconnect is what wakes this worker if it is parked /// in `send`, and only then does it reach the command below. So the order at /// the call site is unchanged -- install the new receiver, and the old /// worker finds out by losing its consumer. #[allow(clippy::too_many_arguments)] pub(crate) fn reseek( &mut self, path: &Path, start: u32, end: u32, color: ColorParams, transform: TransformParams, canvas: Composer, tone: tonemap::Preset, speed: Speed, ) -> Option<(Receiver, BackendCell)> { let reuse = self.reuse.as_ref()?; if reuse.path != path || self.is_finished() { return None; } let (tx, rx) = sync_channel(canvas.queue_depth()); // The new span's own playhead, before its first picture is decoded: a // floor left over from where the timeline *was* would drop every // picture of a seek that went backwards. reuse.floor.store(start, Ordering::Relaxed); // Bumped before the command is queued, so the span running now stops at // its next picture whatever order the two threads are scheduled in. let generation = reuse.generation.fetch_add(1, Ordering::Release) + 1; reuse .spans .send(SpanCmd { generation, start, end, color, transform, canvas, tone, speed, tx, }) .ok()?; Some((rx, reuse.backend.clone())) } /// Whether the thread has already returned, i.e. dropping this would not /// wait. `true` for a worker that never had a thread. What lets a caller /// park cancelled workers and reap them without ever blocking. pub(crate) fn is_finished(&self) -> bool { self.handle .as_ref() .is_none_or(thread::JoinHandle::is_finished) } /// Lets the worker run on unwatched -- what the public API does, since it /// hands out the flag alone. /// /// The reuse door goes with the handle: nothing can steer a worker nobody /// holds, and dropping the command channel is what makes such a thread end /// at its span rather than park waiting for a next one it can never be /// given -- with a VA-API session open, into Mesa's `atexit`. fn detach(mut self) -> Arc { self.handle = None; self.reuse = None; Arc::clone(&self.cancel) } } impl Drop for Worker { fn drop(&mut self) { if let Some(handle) = self.handle.take() { // `cancel` drops the command channel too, so a worker parked between // spans wakes on the disconnect and this join is bounded. self.cancel(); let _ = handle.join(); } } } /// A running worker and the frames it is sending, handed out as one value /// because they must be *dropped* as one, in this order: the receiver /// disconnects first, which is the only thing that wakes a worker parked in a /// full `send`, and the join inside [`Worker::drop`] runs second. /// /// Rust drops fields in declaration order, so this struct *is* that rule, and /// it holds wherever the value goes: an early return out of a half-built /// session, an unwind, a caller not written yet. Two separate locals do not /// hold it -- they drop in reverse order of declaration, so the worker there /// joins a thread nobody will ever drain, which is a hang and not a slow path. pub(crate) struct FrameStream { pub(crate) frames: Receiver, pub(crate) worker: Worker, /// What this stream's pictures are being decoded by. Dropped last and read /// by the caller, so it outlives nothing and blocks nothing. pub(crate) backend: BackendCell, } pub struct DecodeSession; impl DecodeSession { /// Opens `path`, returning stream metadata immediately and a receiver that /// yields frames as the worker decodes them. The worker stops when the /// receiver is dropped, at end of stream, or on the first decode error. pub fn open(path: impl AsRef) -> crate::Result<(VideoMeta, Receiver)> { let (meta, rx, _cancel) = Self::open_at(path, 0)?; Ok((meta, rx)) } /// As [`DecodeSession::open`], but the first frame delivered is /// `start_frame` (0-based display index; [`Frame::index`] stays absolute). /// Setting the returned flag stops the worker at its next access unit, /// which is how a caller abandons a session it no longer wants to drain. pub fn open_at( path: impl AsRef, start_frame: u32, ) -> crate::Result<(VideoMeta, Receiver, Arc)> { // `u32::MAX` is clamped to the stream's frame count below, so this is // "to the end of the file". Self::open_range(path, start_frame, u32::MAX) } /// As [`DecodeSession::open_at`], but the worker also stops on its own /// after sending `end_frame - 1`: the range is half-open `[start, end)` in /// absolute source frames, which is what a clip of a longer file needs. /// `end_frame` is capped at the stream's frame count, and an empty range /// yields a receiver that is simply already disconnected. pub fn open_range( path: impl AsRef, start_frame: u32, end_frame: u32, ) -> crate::Result<(VideoMeta, Receiver, Arc)> { // Ungraded: the public API opens a *file*, and a colour grade belongs to // a clip of a timeline. `PlaybackSession` is what has one to pass. let (meta, stream) = Self::open_worker( path, start_frame, end_frame, ColorParams::default(), // No clip, no transform either: the file-level API hands back the // pictures the file holds, untouched. TransformParams::default(), // No project, no canvas: the file-level API hands back the // pictures the file holds, at the size it holds them. Composer::passthrough(), // ...and no project means no picked rendition either: an HDR file // opened through this door is mapped the published way. tonemap::Preset::default(), )?; // The public API hands out the flag alone, so the worker is detached and // the receiver goes to the caller: nothing here joins anything. Ok((meta, stream.frames, stream.worker.detach())) } /// A worker that decodes nothing and emits `len` black frames, indexed from /// zero -- what a *gap* in the video lane looks like. It goes down the same /// channel as decoded frames, so a gap costs the caller no branch at all /// beyond choosing this opener: same bounded channel, same backpressure, /// same cancel, same retire path. pub(crate) fn open_black(width: u32, height: u32, len: u32) -> FrameStream { let (tx, rx) = sync_channel(2); let cancel = Arc::new(AtomicBool::new(false)); if len == 0 { return FrameStream { frames: rx, worker: Worker { cancel, handle: None, reuse: None, }, backend: BackendCell::new(Backend::Gap), }; } let worker_cancel = Arc::clone(&cancel); // One buffer, cloned per frame: opaque black is a constant, and the // clone is a memcpy against a decode this replaces entirely. let black = vec![[0u8, 0, 0, 255]; (width as usize) * (height as usize)].concat(); let handle = thread::Builder::new() .name("black".into()) .spawn(move || { for index in 0..len { if worker_cancel.load(Ordering::Relaxed) { return; } let frame = Frame { index, width, height, bgra: black.clone(), }; if tx.send(frame).is_err() { return; // caller moved on } } }) .ok(); FrameStream { frames: rx, worker: Worker { cancel, handle, reuse: None, }, backend: BackendCell::new(Backend::Gap), } } /// A worker for a still image ([`crate::is_image`]): the file is decoded /// *once* and the same picture goes down the channel `len` times, indexed /// from `start_frame` exactly as a decoder's pictures are -- so a placed /// image is a clip like any other to everything downstream (`try_frame` /// rewrites those indices, `next_clip` walks off the end of the range). /// /// Graded and placed on the canvas once too, before the repeat: a still is /// the same pixels every frame, so the whole cost of one is one conversion /// plus a memcpy per frame -- what [`open_black`](Self::open_black) pays. pub(crate) fn open_still( path: &Path, start_frame: u32, len: u32, color: ColorParams, transform: TransformParams, canvas: Composer, ) -> crate::Result { let still = Still::open(path)?; let (tx, rx) = sync_channel(2); let cancel = Arc::new(AtomicBool::new(false)); if len == 0 { return Ok(FrameStream { frames: rx, worker: Worker { cancel, handle: None, reuse: None, }, backend: BackendCell::new(Backend::Still), }); } // The one conversion, on this thread: it is a few milliseconds and the // error it could raise has already been raised by `Still::open`. // BT.601 limited, because that is what `rgb_to_i420` above wrote these // planes in: a still round-trips through the pair, not through the // colour of whatever file is on the timeline beside it. // No preset argument, and none wanted: a still is decoded into BT.601 // SDR planes, so the tone map is not built at all whichever rendition // the project is watching. let first = Render::new( color, transform, // A still has no display matrix: what the file holds is what it is. Rotation::None, // ...and no sample aspect either: a still is authored square. PixelAspect::SQUARE, ColorDescription::default(), canvas, tonemap::Preset::default(), // ...and no declared peak either, for the same reason: there is no // tone map on this path to hand one to. None, ) .frame( start_frame, &still.y, &still.u, &still.v, still.width, still.height, ); let worker_cancel = Arc::clone(&cancel); let handle = thread::Builder::new() .name("still".into()) .spawn(move || { let (width, height, bgra) = (first.width, first.height, first.bgra); for index in 0..len { if worker_cancel.load(Ordering::Relaxed) { return; } let frame = Frame { index: start_frame + index, width, height, bgra: bgra.clone(), }; if tx.send(frame).is_err() { return; // caller moved on } } }) .ok(); Ok(FrameStream { frames: rx, worker: Worker { cancel, handle, reuse: None, }, backend: BackendCell::new(Backend::Still), }) } /// A worker for an audio file played as a *picture* ([`crate::is_audio`]): /// the file's peaks are decoded **once** on the worker, and every picture /// after that is painted -- a sliding visualizer /// ([`visualizer_i420`]) at the canvas's own size, then graded, placed and /// converted exactly like a decoded picture, so a grade, a transform and a /// fit policy reach it the way they reach anything else on the timeline. /// /// `start_frame` and `len` are the file's own frames at `fps` -- which for /// an audio source are also the timeline's /// ([`crate::project::Rate::REAL_TIME`]) -- so `Frame::index` runs /// `start_frame ..` like a decoder's output and a speed reaches it through /// the same rewrite as any other clip. pub(crate) fn open_visualizer( path: &Path, stream: usize, start_frame: u32, len: u32, fps: f64, color: ColorParams, transform: TransformParams, canvas: Composer, flags: u8, paint: u64, ) -> crate::Result { let (tx, rx) = sync_channel(2); let cancel = Arc::new(AtomicBool::new(false)); if len == 0 { return Ok(FrameStream { frames: rx, worker: Worker { cancel, handle: None, reuse: None, }, backend: BackendCell::new(Backend::Visualizer), }); } // 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. // // Masked to even dimensions first: 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). No floor under the mask: a canvas with no // size is asked for no picture, and the painter answers that with empty // planes ([`visualizer_window_i420`]), which the declared size now // matches. let (canvas_w, canvas_h) = canvas.dims(); let (width, height) = (canvas_w & !1, canvas_h & !1); let worker_cancel = Arc::clone(&cancel); let path = path.to_path_buf(); let handle = thread::Builder::new() .name("viz".into()) .spawn(move || { // 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; } let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 }; // One frame's painting no longer allocates per strand per // frame: this thread lives for the span. let mut scratch = VizScratch::default(); let mut render = Render::new( color, transform, // Painted here, at the canvas's own size: nothing turned it. Rotation::None, // ...and nothing drew it anamorphic: it is square by // construction. PixelAspect::SQUARE, ColorDescription::default(), canvas, tonemap::Preset::default(), None, ); for index in 0..len { if worker_cancel.load(Ordering::Relaxed) { return; } let t = f64::from(start_frame + index) / fps; // 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 } } }) .ok(); Ok(FrameStream { frames: rx, worker: Worker { cancel, handle, reuse: None, }, backend: BackendCell::new(Backend::Visualizer), }) } /// As [`DecodeSession::open_range`], but the caller gets the whole /// [`Worker`] and can therefore *wait* for it, and the range is graded by /// `color` -- the clip's own setting, folded into the conversion the frames /// go through anyway (see [`i420_to_bgra_with`]). It is captured here rather /// than read per frame because a worker *is* one clip's range: a grade /// changed while this one runs reaches the picture when the session reseeks /// onto the new one, which every edit does. /// /// In-process only: a caller that outlives its workers has to be able to /// join them at exit. /// /// `canvas` is the project's own resolution and this clip's fit policy: the /// frames come out at *that* size, whatever the file's is. A /// [`Composer::passthrough`] (or one already the source's size) leaves every /// picture exactly as it was decoded. /// /// `tone` is the project's HDR rendition ([`tonemap::Preset`]), captured /// here for the reason the grade is: it is constant across one span, and a /// preset picked while this worker runs reaches the picture when the session /// reseeks onto the new one. An SDR source ignores it entirely. pub(crate) fn open_worker( path: impl AsRef, start_frame: u32, end_frame: u32, color: ColorParams, transform: TransformParams, canvas: Composer, tone: tonemap::Preset, ) -> crate::Result<(VideoMeta, FrameStream)> { let path = path.as_ref().to_path_buf(); let (meta, demuxer) = Demuxer::open(&path)?; // No software HEVC, VP9 or VP8 decoder exists, so such a file the plugin will // not take is refused *here*, where the caller still has somewhere to // show it -- a worker that opened and then produced nothing is a black // screen with no explanation. The probe session is opened, made to // decode one picture and dropped: it costs one extra VA-API init // (~90 ms) plus that frame, and only off the two codecs with a software // seat of their own -- H.264 through `ec-h264`, AV1 through `ec-av1` -- // which fall back to it exactly where this probe would have refused. if !matches!(meta.codec, Codec::H264 | Codec::Av1) { hw_decodes(&path, start_frame, meta.codec)?; } let end_frame = end_frame.min(meta.frame_count); if end_frame <= start_frame { // Nothing to decode: a disconnected receiver and no thread at all, // so the caller sees an immediate end of stream rather than an error. let (_, rx) = sync_channel(1); return Ok(( meta, FrameStream { frames: rx, worker: Worker { cancel: Arc::new(AtomicBool::new(false)), handle: None, reuse: None, }, backend: BackendCell::default(), }, )); } Ok(( meta, span_worker( path, Some(Source::demuxed(demuxer, meta)), start_frame, end_frame, color, transform, canvas, tone, // A file-level open has no clip and no speed to skip frames // for: every picture in range is delivered, as it always was. Speed::NORMAL, ), )) } /// As [`open_worker`](Self::open_worker), but the *file* is opened on the /// worker too: nothing here touches the disk, so the caller pays a thread /// spawn and not a demux -- 550-750 ms warm on a 25 GB film, seconds cold, /// which is what a seek or a clip boundary used to cost the UI thread. /// /// The price is that there is no [`VideoMeta`] to return and no synchronous /// refusal either: a file that will not open, and a codec no decoder here /// takes (the plugin probe is skipped -- the worker's own refusal below /// covers it), simply drop the sender. The disconnected receiver is what /// carries a session on to the next span, which is exactly what a failed /// open did on this path before. Callers that must *tell* the user why -- /// an import at the door -- keep the sync opener. #[allow(clippy::too_many_arguments)] pub(crate) fn open_worker_deferred( path: impl AsRef, start_frame: u32, end_frame: u32, color: ColorParams, transform: TransformParams, canvas: Composer, tone: tonemap::Preset, speed: Speed, ) -> FrameStream { span_worker( path.as_ref().to_path_buf(), None, start_frame, end_frame, color, transform, canvas, tone, speed, ) } } /// Spawns a decode worker over `path` and gives it its first span. The thread /// **outlives that span**: it parks on its command channel afterwards, so the /// next seek onto the same file reaches it through [`Worker::reseek`] and costs /// a demuxer seek and a decoder flush instead of a thread, a container parse and /// a VA-API initialisation (98 ms measured worst case). /// /// `opened` is the file when the caller already read it (the sync opener, which /// demuxes on the caller's thread to have metadata to return); `None` is the /// deferred one, where the worker opens it and nothing here touches the disk. #[allow(clippy::too_many_arguments)] fn span_worker( path: PathBuf, opened: Option, start_frame: u32, end_frame: u32, color: ColorParams, transform: TransformParams, canvas: Composer, tone: tonemap::Preset, speed: Speed, ) -> FrameStream { // The depth is the size of the pictures this worker will *emit*, which for a // pass-through canvas is the stream's own -- and the sync opener has already // read that on the caller's thread. Asking the canvas alone is how the file // door came up with 2: every session opens pass-through (a freshly opened // file *is* the project resolution), so a whole file would play at the // decode-ahead this engine had before there was one, until the first seek // built a real canvas. let depth = match (&opened, canvas.places_nothing()) { (Some(source), true) => crate::scale::queue_depth(source.meta.width, source.meta.height), _ => canvas.queue_depth(), }; let (tx, rx) = sync_channel(depth); let cancel = Arc::new(AtomicBool::new(false)); // Written by the worker the moment it knows, so a caller reading it sees // what opened rather than what was hoped for -- and kept across the spans // that follow, since they are decoded by that very decoder. let backend = BackendCell::default(); let generation = Arc::new(AtomicU64::new(0)); // The playhead starts where the span does: nothing is behind it yet. let floor = Arc::new(AtomicU32::new(start_frame)); let (spans, commands) = std::sync::mpsc::channel(); let first = SpanCmd { generation: 0, start: start_frame, end: end_frame, color, transform, canvas, tone, speed, tx, }; let worker_cancel = Arc::clone(&cancel); let worker_backend = backend.clone(); let worker_generation = Arc::clone(&generation); let worker_floor = Arc::clone(&floor); let worker_path = path.clone(); let handle = thread::Builder::new() .name("decode".into()) .spawn(move || { let mut source = opened; let mut cmd = first; loop { let abort = Abort { cancel: &worker_cancel, generation: &worker_generation, mine: cmd.generation, floor: &worker_floor, }; // Superseded (or cancelled) before this thread was even // scheduled: do not open the file, and do not enter VA-API // initialisation, which is the one stretch a cancel cannot // interrupt. A scrub abandons spans by the dozen and this is // where all but the last of them stop. if !abort.hit() { run_span(&worker_path, &mut source, cmd, &abort, &worker_backend); } // Parked between spans. A seek and a clip boundary arrive in // milliseconds and find the decoder still open, which is the // whole point of this thread -- but a session nobody comes back // to (the timeline played out, the window was left alone) must // not sit on the driver: it would hold a live libva thread into // whatever exit path the process takes, which is the SIGSEGV in // Mesa's `atexit` the retired pool exists to prevent, and // holding it *while idle* would widen that from "quit during a // decode" to "quit any time after opening a file". // // So the wait is in two halves: the fast one keeps everything, // and past [`IDLE`] the hardware session is closed. The demuxer // stays -- it is a file handle and an index, not driver state, // and rebuilding it is what costs seconds on a big Matroska -- // so the reseek after a long pause pays one VA-API init and // nothing else. match commands.recv_timeout(IDLE) { Ok(next) => cmd = next, Err(RecvTimeoutError::Timeout) => { if let Some(source) = &mut source && source.hw.take().is_some() { eprintln!("decode worker idle: hardware session closed"); } // The session dropped the command channel: this worker // is retired (or was detached), so the file goes now. match commands.recv() { Ok(next) => cmd = next, Err(_) => return, } } Err(RecvTimeoutError::Disconnected) => return, } } }) .ok(); FrameStream { frames: rx, worker: Worker { cancel, handle, reuse: Some(Reuse { path, spans, generation, backend: backend.clone(), floor, }), }, backend, } } /// How long a parked worker keeps its hardware session before closing it. Long /// enough that a seek, a scrub step and a clip boundary all find the decoder /// where they left it -- and long enough for the think-time between two /// samples of a live slider drag (a colour or transform card nudge), which /// reseeks the very same worker and paid the *closed* half of this window /// every time a person paused a beat to look before nudging again: a session /// found the hardware gone and rebuilt it (measured seconds on a big file) /// for what should have cost one `hw.seek`. Short enough that a session left /// alone for real (the window switched away from, a scrub that stopped) is /// not holding libva when the process exits. const IDLE: std::time::Duration = std::time::Duration::from_secs(8); /// How many pictures in a row a worker may drop for being late before it hands /// one over regardless. The policy needs a floor of its own: a machine that /// cannot decode a file in real time is late on *every* picture, and dropping /// every picture is a black screen rather than a stutter -- so the slowest seat /// still gets one in nine, which is roughly what it could paint before (the /// front-end restarted the decoder once every two seconds to the same effect, /// and paid a VA-API init for each restart). const LATE_RUN: u32 = 8; /// What a decode worker keeps **between** the spans it is asked for: the /// container it read, what the stream says about itself, and the hardware /// session -- the three things a seek used to throw away and buy again. struct Source { meta: VideoMeta, /// What the film says its brightest picture is ([`Demuxer::light`]): the /// tone map's assumed peak on the reference rendition, so a 1759 cd/m^2 /// grade is converted at 1759 rather than at the 1000 a file that declared /// nothing is assumed at. A property of the stream, read once with it. peak: Option, demuxer: Demuxer, /// The plugin's session, opened on this thread (its VA-API state is not /// `Send`-safe across a hand-off) and *kept*. `None` for software: forced by /// `VE_SW`, refused by the plugin, or handed back by a session that opened /// and then decoded nothing. hw: Option, } impl Source { /// The file as the sync opener already read it. fn demuxed(demuxer: Demuxer, meta: VideoMeta) -> Self { Self { meta, peak: demuxer.light().peak(), demuxer, hw: None, } } /// ...and as the deferred opener reads it, on the worker. `None` is a file /// that would not open: the caller drops the sender, and the disconnected /// receiver is the session's "walk on to the next span". fn open(path: &Path) -> Option { match Demuxer::open(path) { Ok((meta, demuxer)) => Some(Self::demuxed(demuxer, meta)), Err(e) => { eprintln!("video open failed: {e}"); None } } } /// Puts the hardware decoder at `start`, keeping the session open where the /// plugin can reposition it. `None` when there is no hardware here at all; /// otherwise whether the session was **reused** -- which is what lets the /// caller tell a driver that cannot decode this stream from one that merely /// did not follow a reseek. fn position_hw(&mut self, path: &Path, start: u32) -> Option { if let Some(hw) = &mut self.hw { if hw.seek(start) { eprintln!("decode backend: hardware (VA-API plugin, session kept, seek to {start})"); return Some(true); } // A plugin too old to reposition, or a decoder that would not // flush: closed and opened again, which is what every seek did. self.hw = None; } self.hw = open_hw(path, start); self.hw.as_ref().map(|_| { eprintln!("decode backend: hardware (VA-API plugin)"); false }) } } /// One span on a worker's thread: position the decoder, decode /// `[start, end)`, send the pictures. Every opener ends here -- the sync one, /// which demuxed on the caller's thread, the deferred one, which demuxes on /// this one, and every reseek after them -- so there is exactly one description /// of what a decode worker does. fn run_span( path: &Path, source: &mut Option, cmd: SpanCmd, abort: &Abort, backend: &BackendCell, ) { let SpanCmd { start, end, color, transform, canvas, tone, speed, tx, .. } = cmd; let opened = match source { Some(opened) => opened, None => { let Some(fresh) = Source::open(path) else { backend.set(Backend::Gap); return; }; source.insert(fresh) } }; // The clamp the sync opener does with the metadata it read on the caller's // thread; here the metadata arrives first. let end = end.min(opened.meta.frame_count); // An empty range decodes nothing and must send nothing: `run_hw` counts a // frame *out* before it compares, so without this a zero-length span would // emit one picture. if end <= start { return; } // The stream's own colour and peak brightness: properties of the stream, so // neither can change while one range decodes -- but the grade, the canvas // and the rendition are the *span's*, so this is built per span. let mut render = Render::new( color, transform, opened.meta.rotation, opened.meta.pixel_aspect, opened.meta.color, canvas, tone, opened.peak, ); if let Some(reused) = opened.position_hw(path, start) { // Cancelled during the init (or the seek): leave without decoding. if abort.hit() { return; } backend.set(Backend::Hardware); let mut decoded = run_hw( opened.hw.as_mut().expect("positioned above"), &tx, start, end, &mut render, abort, speed, ); // A *reused* session that produced nothing may simply be one this // reseek left where the driver would not follow; a session opened fresh // at the same frame is the honest second question, and only its silence // is a software fallback. Without this a single unfollowed seek would // collapse the rest of the file to software. if !decoded && reused { eprintln!("hardware decode produced nothing after a reseek; reopening at frame {start}"); opened.hw = open_hw(path, start); if let Some(hw) = opened.hw.as_mut() { decoded = run_hw(hw, &tx, start, end, &mut render, abort, speed); } } if decoded { return; } // A driver that opens but cannot decode a single frame is still a // fallback case, not a dead session. opened.hw = None; eprintln!("hardware decode failed before any frame, falling back to software"); } // ...except where there is nothing to fall back to. Feeding HEVC, VP9 or // VP8 bytes to either software seat would be garbage, not a fallback -- // VP8's decoder is `ec-vp8`, inside the plugin. H.264 and AV1 each // have one of this project's own here: `ec-h264`, `ec-av1`. match opened.meta.codec { Codec::H264 => { eprintln!("decode backend: software (ec-h264)"); backend.set(Backend::Software); run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed); } Codec::Av1 => { eprintln!("decode backend: software (ec-av1)"); backend.set(Backend::Software); run_av1(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed); } // Nothing decodes from here -- no software seat exists for this codec. // Say so: the cell was left claiming the hardware session that opened // and then produced nothing, and it reports what happened, not what // was hoped for. other => { backend.set(Backend::Gap); eprintln!("{}", other.needs_plugin()); } } } /// One clip's pictures on their way to the renderer: graded, placed on the /// project canvas, converted. Both decode loops go through it, so hardware and /// software cannot show two different pictures. /// /// The order is grade, then place (see [`Composer`]): a grade is the clip's own, /// applied at the resolution it was shot at, and the letterbox bars around it /// are not the clip -- a brightness grade must not lift them off black. /// /// A project at the media's own resolution never reaches any of that: it takes /// the fused graded conversion, the one path this engine had before there was a /// project resolution, byte for byte and allocation for allocation. struct Render { color: ColorParams, /// This clip's placement, on top of whatever the canvas's own fit policy /// already does ([`crate::scale::Composer::place_transformed`]). transform: TransformParams, /// How far the *file* asks its picture to be turned before anything else /// happens to it ([`crate::demux::Rotation`]): the phone-portrait turn, /// made here so the grade, the canvas and the preview's own renderer all /// see the picture the way it is meant to be seen. [`Rotation::None`] for /// every file that states no turn, which is the whole of an ordinary /// library. rotation: Rotation, /// The ratio one coded pixel is drawn at ([`crate::demux::PixelAspect`]): /// the file's sample aspect ratio, applied exactly once, at this one /// conversion to the square-pixel raster -- the same place ffmpeg's swscale /// applies it, and nowhere else. Square for every file that states no /// aspect, which takes the branch by a bool and touches no byte. pixel_aspect: PixelAspect, /// What the source's samples mean -- the stream's own matrix and range, /// which is what the conversion below is done in rather than the BT.601 it /// used to assume of every file. desc: ColorDescription, canvas: Composer, /// This stream's HDR-to-SDR map, built once here because building it is /// float work over 9 537 grid nodes and the transfer is a property of the /// stream. `None` for an SDR stream, which is what keeps that path exactly /// the one it was. tone: Option, /// The working copy of the source planes, refilled per frame and kept /// across the worker's whole range. Empty unless the clip needs one: it is /// tone-mapped in place, graded in place, or both. graded: (Vec, Vec, Vec), /// The same, for the display-matrix turn above: empty for every file that /// asks for none, and resized once for one that does -- a steady-state /// buffer rather than three plane allocations per decoded frame. turned: (Vec, Vec, Vec), /// The same, for the pixel-aspect stretch: the coded picture widened to /// the displayed width, empty for every square-pixel file and sized once /// for one that is not. stretched: (Vec, Vec, Vec), /// Where [`Composer::place_transformed`]'s owned picture lands, so a /// transformed frame's planes live as long as `self` -- matching what /// [`Composer::place`] already hands back by borrowing `self.canvas`. placed: (Vec, Vec, Vec), } /// What [`Render::frame`] converts a tone-mapped picture in: the tone map's /// output contract ([`crate::tonemap`]), and no longer the HDR space the file /// declared. const TONE_MAPPED: ColorDescription = ColorDescription { matrix: Matrix::Bt709, transfer: Transfer::Sdr, full_range: false, }; impl Render { /// `peak` is what the file declared about its own brightness /// ([`Demuxer::light`]), which only an HDR stream has and only the /// reference rendition reads (see [`tonemap::Preset`]). fn new( color: ColorParams, transform: TransformParams, rotation: Rotation, pixel_aspect: PixelAspect, desc: ColorDescription, canvas: Composer, preset: tonemap::Preset, peak: Option, ) -> Self { Self { color, transform, rotation, pixel_aspect, desc, canvas, // corner-cut: the ceiling is that the map reads limited-range codes // (`tonemap`'s input contract), so a full-range PQ file -- which // no encoder writes and no camera produces -- is mapped as if it // were limited and comes out slightly crushed. The upgrade is a // range argument to `ToneMapper::new`. tone: match desc.transfer { Transfer::Sdr => None, Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, peak)), Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)), }, graded: (Vec::new(), Vec::new(), Vec::new()), turned: (Vec::new(), Vec::new(), Vec::new()), stretched: (Vec::new(), Vec::new(), Vec::new()), placed: (Vec::new(), Vec::new(), Vec::new()), } } fn frame( &mut self, index: u32, y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32, ) -> Frame { // The pixel aspect, applied exactly once -- the single conversion to // the square-pixel raster this engine makes, where ffmpeg's swscale // makes its own -- *before* the display-matrix turn. The ratio belongs // to the axis that was horizontal before the turn: the coded width is // stretched by h/v and the turn then swaps the stretched pair, which // is the composition the probe declares (a 1440x1080 SAR-4/3 file // turned 90° displays 1080x1920, DAR 9:16). Stretching after the turn // instead lands the ratio on the coded height and renders a // 1440x1440 square into a 9:16 canvas -- letterboxed, and the bars // baked into any export. Only a file whose samples are not square // reaches the resample: a square one takes the branch by a bool and // not one byte is touched, which is what keeps every existing picture // identical to the day before anamorphic sources existed. let (y, u, v, width, height) = if self.pixel_aspect.is_square() { (y, u, v, width, height) } else { // The aspect widens the *width*, always: 4:3 SAR over 1440x1080 // shows 1920x1080. `width_factor` lands on the even grid 4:2:0 // composes on, and a height is never touched by it. let display_width = self.pixel_aspect.width_factor(width); let (sy, su, sv) = &mut self.stretched; // Sized for `scale_i420`'s exact-planes assertion, once for the // worker's whole range: steady-state buffers, not per-frame // allocations ([`turned`]'s reason). let (dcw, dch) = ( display_width.div_ceil(2) as usize, height.div_ceil(2) as usize, ); sy.resize(display_width as usize * height as usize, 0); su.resize(dcw * dch, 0); sv.resize(dcw * dch, 0); crate::scale::scale_i420( y, u, v, width as usize, height as usize, sy, su, sv, display_width as usize, height as usize, ); ( &sy[..display_width as usize * height as usize], &su[..display_width.div_ceil(2) as usize * height.div_ceil(2) as usize], &sv[..display_width.div_ceil(2) as usize * height.div_ceil(2) as usize], display_width, height, ) }; // The file's own turn, after the stretch: a phone's portrait video // arrives as landscape planes, and the grade, the canvas and the // conversion below all have to see the picture the way it is meant to // be seen. Nothing here at all for the ordinary file that states no // turn -- `Rotation::None` takes the planes by reference and not one // byte is copied. let (y, u, v, width, height) = match self.rotation.is_none() { true => (y, u, v, width, height), false => { let steps = self.rotation.steps(); let (rw, rh) = crate::scale::rotate_i420_90s_into( y, u, v, width, height, steps, &mut self.turned, ); ( &self.turned.0[..], &self.turned.1[..], &self.turned.2[..], rw, rh, ) } }; let passthrough = self.canvas.is_passthrough(width, height); // A transform still has a picture to place even where the canvas // itself would hand this size back untouched -- moving, scaling, // rotating or cropping a passthrough-sized clip is still a placement, // and must not be silently dropped by the fused conversion below. let transform_active = !self.transform.is_identity(); let skip_placement = passthrough && !transform_active; // Everything that has to happen to the samples before the canvas sees // them, on one copy: the tone map (HDR streams only) and, unless the // conversion below can fuse it, the grade. An SDR stream that is either // ungraded or passing through takes neither and never allocates. // // The grade lands *after* the map on purpose: it is a look on the // picture a viewer is shown, so its brightness and saturation mean what // they say in the SDR the tone map just produced, not in the 10-stop // HDR the file was in. let (y, u, v, desc) = if self.tone.is_some() || (!skip_placement && !self.color.is_identity()) { let (gy, gu, gv) = &mut self.graded; gy.clear(); gy.extend_from_slice(y); gu.clear(); gu.extend_from_slice(u); gv.clear(); gv.extend_from_slice(v); if let Some(tone) = &self.tone { tone.map(gy, gu, gv, width as usize, height as usize); } // The same terms the branch was entered on: anywhere the fused // conversion below will not apply the grade (a placement is // happening, so the canvas conversion is plain), it lands here -- // including the passthrough-sized clip a transform moves, whose // grade used to be dropped on the floor between these two guards. if !skip_placement && !self.color.is_identity() { crate::color::apply_yuv(&self.color, gy, gu, gv); } let desc = if self.tone.is_some() { TONE_MAPPED } else { self.desc }; (&gy[..], &gu[..], &gv[..], desc) } else { (y, u, v, self.desc) }; if skip_placement { return Frame { index, width, height, bgra: i420_to_bgra_with( &desc, &self.color, y, u, v, width as usize, height as usize, ), }; } let (y, u, v, width, height) = if transform_active { let (py, pu, pv, w, h) = self .canvas .place_transformed(y, u, v, width, height, &self.transform); self.placed = (py, pu, pv); (&self.placed.0[..], &self.placed.1[..], &self.placed.2[..], w, h) } else { self.canvas.place(y, u, v, width, height) }; Frame { index, width, height, // Ungraded on purpose: the grade is already in the pixels above and // the canvas around them must stay the black it was filled with. bgra: i420_to_bgra(&desc, y, u, v, width as usize, height as usize), } } } /// One still image, decoded to tightly packed I420 -- the shape every other /// source arrives in, so a placed image goes through the same grade, the same /// canvas and the same conversion as a decoded picture and there is no second /// pixel path to keep in step. /// /// Held whole rather than streamed: an image *is* one picture, and the file is /// read once per span that plays it. pub(crate) struct Still { pub(crate) y: Vec, pub(crate) u: Vec, pub(crate) v: Vec, pub(crate) width: u32, pub(crate) height: u32, } impl Still { /// Decodes `path`. Refused by name for a picture that is not one /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project /// file are both held to cannot be walked around by a 30000-pixel-wide PNG. /// /// Alpha is *dropped*, not composited: `to_rgb8` discards the channel, so a /// transparent PNG arrives fully opaque over its own colours rather than /// over the clip beneath it. I420 has nowhere to carry it and this engine /// composes one picture per frame (topmost lane wins), so there is nothing /// for a blend to blend with. /// /// corner-cut: the ceiling is a logo with a transparent background, which /// lands as a rectangle. Upgrade path is keeping the alpha plane here and /// giving `scale::Composer` a blend over the lane below. pub(crate) fn open(path: &Path) -> crate::Result { let reader = image::ImageReader::open(path)?.with_guessed_format()?; let rgb = reader .decode() .map_err(|e| format!("{}: {e}", path.display()))? .to_rgb8(); let (width, height) = rgb.dimensions(); if !crate::is_resolution(width, height) { return Err(format!( "{} is {width}x{height}, which is not a picture this engine composes", path.display() ) .into()); } let (y, u, v) = rgb_to_i420(&rgb, width as usize, height as usize); Ok(Self { y, u, v, width, height, }) } /// The planes as an export's decoder hands them over, so a still and a /// decoded picture are the same value to `export::run`. pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) { (&self.y, &self.u, &self.v, self.width, self.height) } } /// How big the picture in `path` is, from its header alone -- what a library row /// says about a file it has not placed anywhere. The whole file is not decoded. pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> { Ok(image::ImageReader::open(path)? .with_guessed_format()? .into_dimensions() .map_err(|e| format!("{}: {e}", path.display()))?) } /// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse /// of [`crate::convert::i420_to_bgra`] *in that matrix*, which is why /// [`DecodeSession::open_still`] hands the renderer a BT.601 description and /// not the timeline's. A still has no stream to be tagged by; it round-trips to /// the colour it was authored in through this pair and nothing else sees these /// planes (`images::still_pixels_match_the_source_image` measures it). /// /// Chroma is the 2x2 box average, and an odd edge averages the samples it has -- /// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape /// [`crate::scale::Composer::place`] panics on anything else for. fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec, Vec, Vec) { let (cw, ch) = crate::scale::chroma_dims(width, height); let mut y = vec![0u8; width * height]; let mut u = vec![0u8; cw * ch]; let mut v = vec![0u8; cw * ch]; for row in 0..height { for col in 0..width { let p = (row * width + col) * 3; let (r, g, b) = (rgb[p] as i32, rgb[p + 1] as i32, rgb[p + 2] as i32); y[row * width + col] = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8; } } for crow in 0..ch { for ccol in 0..cw { let (mut sr, mut sg, mut sb, mut n) = (0i32, 0i32, 0i32, 0i32); for row in crow * 2..(crow * 2 + 2).min(height) { for col in ccol * 2..(ccol * 2 + 2).min(width) { let p = (row * width + col) * 3; sr += rgb[p] as i32; sg += rgb[p + 1] as i32; sb += rgb[p + 2] as i32; n += 1; } } let n = n.max(1); let (r, g, b) = (sr / n, sg / n, sb / n); u[crow * cw + ccol] = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8; v[crow * cw + ccol] = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8; } } (y, u, v) } /// Peak buckets per second the visualizer paints from, shared by the one /// caller that decodes them ([`DecodeSession::open_visualizer`], preview and /// export both) and the painter that reads them. pub(crate) const VIZ_BUCKETS_PER_SEC: u32 = 4000; /// Bits 1-2: which picture this visualizer paints. Mutually exclusive — /// a picker, not independent toggles. pub const VIZ_STYLE_FILL: u8 = 0; pub const VIZ_STYLE_RIBBON: u8 = 1; pub const VIZ_STYLE_RING: u8 = 2; pub const VIZ_STYLE_WAVE: u8 = 3; pub const VIZ_FAST: u8 = 1 << 3; pub fn viz_style(flags: u8) -> u8 { (flags >> 1) & 3 } pub fn with_viz_style(flags: u8, style: u8) -> u8 { (flags & !0b0110) | ((style & 3) << 1) } /// Azure + sat 160 + 8 strands + glow 2. What `viz_paint == 0` means. pub const VIZ_PAINT_AZURE: u64 = 150 | (160 << 8) | (8 << 16) | (2 << 24); /// Where the strand colour sits above the clip's own four bytes: hue at 32 /// and sat at 40, with bit 63 as the flag that says a clip chose one /// ([`viz_strand_set`]). A clear flag means the automatic complement the /// ring has always painted -- so a v22 value, whose top half is empty, is /// nothing new. const VIZ_STRAND_HUE_SHIFT: u32 = 32; const VIZ_STRAND_SAT_SHIFT: u32 = 40; const VIZ_STRAND_CHOSEN: u64 = 1 << 63; pub fn viz_materialize(paint: u64) -> u64 { if paint == 0 { VIZ_PAINT_AZURE } else { paint } } pub fn viz_ink_from_paint(paint: u64) -> (u8, u8, u8) { let p = viz_materialize(paint); let hue = (p & 0xFF) as f32 * 360.0 / 256.0; let sat = f32::from(((p >> 8) & 0xFF) as u8) / 255.0; hsv_to_rgb(hue, sat, 0.84) } pub fn viz_strands_of(paint: u64) -> u8 { (((viz_materialize(paint) >> 16) & 0xFF) as u8).clamp(1, 32) } pub fn viz_glow_of(paint: u64) -> u8 { ((viz_materialize(paint) >> 24) & 0xFF) as u8 } pub fn with_viz_paint_hue(paint: u64, hue: u8) -> u64 { (viz_materialize(paint) & !0xFF) | u64::from(hue) } pub fn with_viz_paint_sat(paint: u64, sat: u8) -> u64 { (viz_materialize(paint) & !(0xFF << 8)) | (u64::from(sat) << 8) } pub fn with_viz_paint_strands(paint: u64, n: u8) -> u64 { (viz_materialize(paint) & !(0xFF << 16)) | (u64::from(n.clamp(1, 32)) << 16) } pub fn with_viz_paint_glow(paint: u64, n: u8) -> u64 { (viz_materialize(paint) & !(0xFF << 24)) | (u64::from(n.min(16)) << 24) } pub fn viz_hue_ui(paint: u64) -> u8 { if paint == 0 { 150 } else { (paint & 0xFF) as u8 } } pub fn viz_sat_ui(paint: u64) -> u8 { if paint == 0 { 160 } else { match ((paint >> 8) & 0xFF) as u8 { 0 => 160, s => s, } } } /// Whether the clip chose a strand colour of its own (the top bit), rather /// than taking the automatic complement a ring's dual half has always /// painted. pub fn viz_strand_set(paint: u64) -> bool { paint & VIZ_STRAND_CHOSEN != 0 } /// The chosen strand hue, 0-255 on the wheel [`viz_hue_ui`] reads. pub fn viz_strand_hue_ui(paint: u64) -> u8 { ((paint >> VIZ_STRAND_HUE_SHIFT) & 0xFF) as u8 } /// The chosen strand sat, 0-255. A stored zero stays zero here, unlike /// [`viz_sat_ui`]'s: a grey strand is a colour someone picked, and the flag /// -- not the byte -- is what says whether there is one. pub fn viz_strand_sat_ui(paint: u64) -> u8 { ((paint >> VIZ_STRAND_SAT_SHIFT) & 0xFF) as u8 } /// Set the strand hue and mark the colour chosen, so a ring's dual half /// inks it instead of the automatic complement. pub fn with_viz_paint_strand_hue(paint: u64, hue: u8) -> u64 { let p = viz_materialize(paint) & !(0xFF_u64 << VIZ_STRAND_HUE_SHIFT); (p | (u64::from(hue) << VIZ_STRAND_HUE_SHIFT)) | VIZ_STRAND_CHOSEN } /// Set the strand sat and mark the colour chosen, as /// [`with_viz_paint_strand_hue`] does. pub fn with_viz_paint_strand_sat(paint: u64, sat: u8) -> u64 { let p = viz_materialize(paint) & !(0xFF_u64 << VIZ_STRAND_SAT_SHIFT); (p | (u64::from(sat) << VIZ_STRAND_SAT_SHIFT)) | VIZ_STRAND_CHOSEN } /// Drop the chosen strand colour: the dual half of a ring goes back to the /// automatic complement, and both strand bytes go with the flag. pub fn viz_strand_clear(paint: u64) -> u64 { paint & !(VIZ_STRAND_CHOSEN | (0xFF_u64 << VIZ_STRAND_HUE_SHIFT) | (0xFF_u64 << VIZ_STRAND_SAT_SHIFT)) } /// `#RRGGBB` for an ink, at the same fixed value the painter draws at, so /// the swatch a front-end shows is the colour that reaches the picture. /// The inverse of [`viz_color_from_text`] for the colours a round trip /// through bytes can carry back. pub fn viz_color_hex(hue: u8, sat: u8) -> String { let (r, g, b) = hsv_to_rgb(f32::from(hue) * 360.0 / 256.0, f32::from(sat) / 255.0, 0.84); format!("#{r:02X}{g:02X}{b:02X}") } /// A colour someone typed -- `#4F8FD6`, `4f8fd6`, `rgb(79,143,214)` or /// `rgba(79,143,214,255)`, any case, commas or `/` between the channels, /// alpha ignored -- as the `(hue, sat)` pair the sliders and the paint /// field speak. `None` for everything else rather than a guess: the wrong /// number of digits, a channel outside 0-255, parentheses missing. /// /// Brightness is dropped, not carried: the painter draws every ink at its /// own fixed value, so a typed colour is kept by its hue and saturation. pub fn viz_color_from_text(text: &str) -> Option<(u8, u8)> { let t = text.trim(); let (r, g, b) = if let Some(inner) = t.strip_suffix(')') { let body = if starts_ci(inner, b"rgb(") { &inner[4..] } else if starts_ci(inner, b"rgba(") { &inner[5..] } else { return None; }; let mut channels = body.split(['/', ',']).map(str::trim); let r = channel(channels.next()?)?; let g = channel(channels.next()?)?; let b = channel(channels.next()?)?; // Alpha, when it is spelled: read so a bad one is refused like a // channel is, and dropped -- the paint field has no room for it. if let Some(a) = channels.next() { channel(a)?; } if channels.next().is_some() { return None; } (r, g, b) } else { let hex = t.strip_prefix('#').unwrap_or(t); if hex.len() != 6 || !hex.bytes().all(|c| c.is_ascii_hexdigit()) { return None; } ( u8::from_str_radix(&hex[0..2], 16).ok()?, u8::from_str_radix(&hex[2..4], 16).ok()?, u8::from_str_radix(&hex[4..6], 16).ok()?, ) }; Some(rgb_to_hue_sat(r, g, b)) } fn starts_ci(text: &str, prefix: &[u8]) -> bool { text.len() >= prefix.len() && text.as_bytes()[..prefix.len()].eq_ignore_ascii_case(prefix) } /// One 0-255 channel of a typed colour: digits only, so neither a sign nor /// an exponent slips in the way `u8`'s own parse would take them. fn channel(text: &str) -> Option { if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { return None; } text.parse().ok() } /// What a byte RGB is on the paint field's wheel: hue on [`viz_hue_ui`]'s /// 0-255 scale, sat 0-255, brightness dropped for the same reason /// [`viz_color_from_text`] drops the typed one. fn rgb_to_hue_sat(r: u8, g: u8, b: u8) -> (u8, u8) { let (r, g, b) = (f32::from(r), f32::from(g), f32::from(b)); let (max, min) = (r.max(g).max(b), r.min(g).min(b)); let delta = max - min; let hue = if delta == 0.0 { 0.0 } else if max == r { 60.0 * ((g - b) / delta).rem_euclid(6.0) } else if max == g { 60.0 * ((b - r) / delta + 2.0) } else { 60.0 * ((r - g) / delta + 4.0) }; let hue = ((hue * 256.0 / 360.0).round() as i64).rem_euclid(256) as u8; let sat = if max == 0.0 { 0.0 } else { delta / max }; (hue, (sat * 255.0).round() as u8) } pub fn viz_hsv_rgb(h: f32, s: f32, v: f32) -> (u8, u8, u8) { hsv_to_rgb(h, s, v) } fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (u8, u8, u8) { let h = ((h % 360.0) + 360.0) % 360.0; let c = v * s; let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs()); let m = v - c; let (r, g, b) = match (h / 60.0) as i32 { 0 => (c, x, 0.0), 1 => (x, c, 0.0), 2 => (0.0, c, x), 3 => (0.0, x, c), 4 => (x, 0.0, c), _ => (c, 0.0, x), }; ( ((r + m) * 255.0).round() as u8, ((g + m) * 255.0).round() as u8, ((b + m) * 255.0).round() as u8, ) } fn rgb_yuv(r: i32, g: i32, b: i32) -> (u8, u8, u8) { let y = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8; let u = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8; let v = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8; (y, u, v) } /// How much sound one visualizer frame shows, centered on the frame's own /// time. Two seconds by default; [`VIZ_FAST`] is a fifth of a second, the /// zoom that makes an Audacity-style trace readable as a line. const VIZ_WINDOW_SECS: f64 = 2.0; const VIZ_FAST_SECS: f64 = 0.2; fn viz_stamp( y: &mut [u8], u: &mut [u8], v: &mut [u8], w: usize, h: usize, cw: usize, ch: usize, x: i32, row: i32, fall: f32, bg_y: u8, ink_y: u8, ink_u: u8, ink_v: u8, ) { if x < 0 || row < 0 || x >= w as i32 || row >= h as i32 { return; } let lum = (f32::from(bg_y) + (f32::from(ink_y) - f32::from(bg_y)) * fall.clamp(0.0, 1.0)) as u8; let idx = row as usize * w + x as usize; if lum > y[idx] { y[idx] = lum; } if fall > 0.6 { let cx = x as usize / 2; let cy = row as usize / 2; if cy < ch && cx < cw { u[cy * cw + cx] = ink_u; v[cy * cw + cx] = ink_v; } } } fn viz_span( y: &mut [u8], u: &mut [u8], v: &mut [u8], w: usize, h: usize, cw: usize, ch: usize, x: i32, top: i32, bot: i32, bg_y: u8, ink_y: u8, ink_u: u8, ink_v: u8, ) { let (a, b) = if top <= bot { (top, bot) } else { (bot, top) }; for row in a..=b { viz_stamp(y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v); } } /// What one frame's painting borrows instead of allocating, owned by whoever /// paints a *stream* of frames -- the visualizer worker's own thread, an /// export seat, a test -- and reused for every strand of every frame. Eight /// `Vec`s, against the twenty-seven a fresh set per strand cost a ring at /// eight strands. #[derive(Default)] pub(crate) struct VizScratch { /// The frame's own columns, kept across frames to the widest picture yet. lo: Vec, hi: Vec, sig: Vec, /// One strand's sampled positions, the cells its Bresenham runs cover, /// the chain's rows, the row band's candidates and their lower hull. pts: Vec<(i32, i32)>, chain: Vec<(i32, i32)>, rows: Vec<(i32, usize, usize)>, cand: Vec<(i32, i32)>, hull: Vec, } /// One segment's glow as its own disc, stamped at every Bresenham cell: what /// a chain was painted by before [`viz_chain`], and still the cheaper of the /// two when the chain is long ([`viz_discs_are_cheaper`]). #[allow(clippy::too_many_arguments)] fn viz_line( y: &mut [u8], u: &mut [u8], v: &mut [u8], w: usize, h: usize, cw: usize, ch: usize, mut x0: i32, mut y0: i32, x1: i32, y1: i32, bg_y: u8, ink_y: u8, ink_u: u8, ink_v: u8, glow: u8, ) { let dx = (x1 - x0).abs(); let dy = -(y1 - y0).abs(); let sx = if x0 < x1 { 1 } else { -1 }; let sy = if y0 < y1 { 1 } else { -1 }; let mut err = dx + dy; let g = i32::from(glow); loop { for oy in -g..=g { for ox in -g..=g { if ox * ox + oy * oy > g * g { continue; } let fall = if ox == 0 && oy == 0 { 1.0 } else { let d2 = (ox * ox + oy * oy) as f32; (-0.45 * d2 / (g * g).max(1) as f32).exp() }; viz_stamp(y, u, v, w, h, cw, ch, x0 + ox, y0 + oy, fall, bg_y, ink_y, ink_u, ink_v); } } if x0 == x1 && y0 == y1 { break; } let e2 = 2 * err; if e2 >= dy { err += dy; x0 += sx; } if e2 <= dx { err += dx; y0 += sy; } } } /// Which of the two passes paints a chain, by what each of them visits. Both /// paint the same bytes, and the tests hold them to it; they are not alike in /// what they cost. The discs visit `samples * pi * glow^2` cells whatever the /// envelope is doing, while the chain visits each of its own cells once per /// row of its band -- `cells * (2 * glow + 1)`. So a *smooth* trace (a chain /// cell per sample, near enough) is the chain's by a wide margin, and a /// *jagged* one, whose samples are Bresenham runs of dozens of cells, is the /// discs' while the glow is small. A song's own ring at 1080p crossed between /// glow 3 and 4 (31 ms against 44 ms there, and 60 against 52 at glow 4), /// which is exactly what this comparison says. fn viz_discs_are_cheaper(samples: usize, cells: usize, glow: u8) -> bool { (samples as u64) * (2 * u64::from(glow) + 1) < cells as u64 } /// How many cells [`viz_walk`] would push for these samples, without walking /// them: one per iteration of that loop, and it iterates `max(dx, dy) + 1` /// times a segment. fn chain_cells(pts: &[(i32, i32)]) -> usize { pts.windows(2) .map(|w| { let (dx, dy) = ((w[1].0 - w[0].0).abs(), (w[1].1 - w[0].1).abs()); dx.max(dy) as usize + 1 }) .sum() } /// The Bresenham cells of one segment, collected rather than stamped: the same /// walk [`viz_line`] used to rasterise, kept for [`viz_chain`] to paint the /// whole chain from. fn viz_walk(mut x0: i32, mut y0: i32, x1: i32, y1: i32, chain: &mut Vec<(i32, i32)>) { let dx = (x1 - x0).abs(); let dy = -(y1 - y0).abs(); let sx = if x0 < x1 { 1 } else { -1 }; let sy = if y0 < y1 { 1 } else { -1 }; let mut err = dx + dy; loop { chain.push((x0, y0)); if x0 == x1 && y0 == y1 { break; } let e2 = 2 * err; if e2 >= dy { err += dy; x0 += sx; } if e2 <= dx { err += dx; y0 += sy; } } } /// Paints a whole chain in one pass: every cell within `glow` of a chain cell /// takes the falloff of the **nearest** one, and the ink with it. /// /// Byte-for-byte what the per-point discs left behind, and the reason is in the /// write: luma is a `max`, so of every disc covering a cell only the closest one /// can decide it, and a glow disc's chroma is written at *every* step of it -- /// [`viz_stamp`]`s threshold (0.6) is under the falloff of the rim /// (`exp(-0.45) = 0.64`), which is what makes the whole disc the ink's own. /// What changes is the cost: discs visit `steps * pi * glow^2` cells /// (`VIZ_STYLE_RING`'s 7680 steps measured 296 ms for one 1080p frame at glow /// 16, eight strands), while this visits each covered cell once and finds its /// nearest chain cell by walking outward from it through the chain cells of its /// own row band. #[allow(clippy::too_many_arguments)] fn viz_chain( y: &mut [u8], u: &mut [u8], v: &mut [u8], w: usize, h: usize, cw: usize, ch: usize, scratch: &mut VizScratch, bg_y: u8, ink_y: u8, ink_u: u8, ink_v: u8, glow: u8, ) { let VizScratch { pts, chain, rows, cand, hull, .. } = scratch; chain.clear(); for pair in pts.windows(2) { viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, chain); } if chain.is_empty() { return; } if glow == 0 { // Nothing to decide: with no glow the cells are the chain itself, at // full ink -- which is exactly what the row/by/band machinery below // works out, one sort later. for &(x, row) in chain.iter() { viz_stamp(y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v); } return; } let g = i32::from(glow); // By (row, x) -- the tuple is (x, row) -- so a row's band is a contiguous // slice of this: a chain revisits cells (the ring is sampled several times // a pixel) and a repeat is the same candidate. chain.sort_unstable_by_key(|&(x, row)| (row, x)); chain.dedup(); rows.clear(); let mut i = 0; while i < chain.len() { let row = chain[i].1; let start = i; while i < chain.len() && chain[i].1 == row { i += 1; } rows.push((row, start, i)); } let first = (rows[0].0 - g).max(0); let last = (rows[rows.len() - 1].0 + g).min(h as i32 - 1); let mut band = 0usize; // `(x, dy^2)` -- a candidate's horizontal offset is left to the cell that // asks, its vertical one is its own. // ...and the candidates a run's cells are decided by, once the ones that // can never be nearest are off ([`viz_chain`]'s own note). for row in first..=last { while band < rows.len() && rows[band].0 < row - g { band += 1; } cand.clear(); let mut k = band; while k < rows.len() && rows[k].0 <= row + g { let dy = rows[k].0 - row; let dy2 = dy * dy; for &(x, _) in &chain[rows[k].1..rows[k].2] { cand.push((x, dy2)); } k += 1; } if cand.is_empty() { continue; } cand.sort_unstable_by_key(|&(x, _)| x); // One candidate per column: the nearest in y is the only one that can // decide a cell -- the others are further on both axes. let mut kept = 0usize; for j in 0..cand.len() { if kept > 0 && cand[kept - 1].0 == cand[j].0 { if cand[j].1 < cand[kept - 1].1 { cand[kept - 1] = cand[j]; } } else { cand[kept] = cand[j]; kept += 1; } } cand.truncate(kept); // The stretches of x the discs reach, one run at a time: the hole in // the middle of a ring is not walked at all. let mut j = 0usize; while j < cand.len() { let run_lo = cand[j].0 - g; let mut run_hi = cand[j].0 + g; let first = j; while j + 1 < cand.len() && cand[j + 1].0 - g <= run_hi + 1 { j += 1; run_hi = run_hi.max(cand[j].0 + g); } let end = j + 1; // exclusive j += 1; let x_lo = run_lo.max(0); let x_hi = run_hi.min(w as i32 - 1); if x_lo > x_hi { continue; } // What is left of a candidate at cell `x` is // `x^2 - 2*cx*x + (cx^2 + dy^2)`: the `x^2` is common to every // candidate, so the nearest one is the lowest line of the rest -- // and only the lower hull of those lines is ever the lowest, at any // x. On the hull the nearest one only ever moves forward as x // does, which is what makes this a walk over the cells instead of a // search per cell. let line = |c: usize| { let (cx, dy2) = cand[c]; let cx = i64::from(cx); (-2 * cx, cx * cx + i64::from(dy2)) }; let value = |c: usize, x: i32| { let (m, b) = line(c); m * i64::from(x) + b }; hull.clear(); for c in first..end { let (m, b) = line(c); while hull.len() >= 2 { let (m1, b1) = line(hull[hull.len() - 2]); let (m2, b2) = line(hull[hull.len() - 1]); // The middle line is never the lowest: its two crossings // are the wrong way round. if (b2 - b1) * (m2 - m) >= (b - b2) * (m1 - m2) { hull.pop(); } else { break; } } hull.push(c); } // Only the hull's last two entries can change places as x moves // forward, so this is a walk and not a search -- and `value` is // asked of those two alone. let mut hp = 0usize; for x in x_lo..=x_hi { while hp + 1 < hull.len() && value(hull[hp + 1], x) <= value(hull[hp], x) { hp += 1; } let (cx, dy2) = cand[hull[hp]]; let d = x - cx; let d2 = d * d + dy2; if d2 <= g * g { let fall = if d2 == 0 { 1.0 } else { (-0.45 * d2 as f32 / (g * g).max(1) as f32).exp() }; viz_stamp(y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v); } } } } } /// One visualizer picture in tightly packed I420. Three looks, picked by /// [`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)], t_secs: f64, width: u32, 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; // A canvas with no size asks for no picture, and must be told so: the zero // line's row is derived from the height (`h - 1`), and a height of zero has // no row to put it on -- `clamp` answers that by panicking, which on this // path is a dead worker thread and a span the export aborts on. A // `Composer::passthrough()` canvas is exactly this size and says as much // (`places_nothing`), and a 1-pixel-high canvas floors to it (planes are // even), so both take the empty picture they asked for. if width == 0 || height == 0 { return (Vec::new(), Vec::new(), Vec::new()); } let (w, h) = (width as usize, height as usize); let (cw, ch) = crate::scale::chroma_dims(w, h); let (bg_y, bg_u, bg_v) = rgb_yuv(8, 12, 22); let mut y = vec![bg_y; w * h]; let mut u = vec![bg_u; cw * ch]; let mut v = vec![bg_v; cw * ch]; let (ink_r, ink_g, ink_b) = viz_ink_from_paint(paint); let (ink_y, ink_u, ink_v) = rgb_yuv(ink_r as i32, ink_g as i32, ink_b as i32); let center = h as f32 / 2.0; let half = h as f32 * 0.42; let t_secs = if t_secs.is_finite() { t_secs } else { 0.0 }; let z = (center.round() as isize).clamp(0, h as isize - 1) as usize; for col in 0..w { y[z * w + col] = y[z * w + col].max(bg_y.saturating_add(18)); } scratch.lo.clear(); scratch.lo.resize(w, 0.0); scratch.hi.clear(); scratch.hi.resize(w, 0.0); scratch.sig.clear(); scratch.sig.resize(w, 0.0); 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 { VIZ_WINDOW_SECS }; // Fixed window length, silence outside the file: shrinking the span // to the samples that exist stretched a bump as it entered (2s) and // Fast (0.2s) rarely hit the edge. Column x always maps to // t - window/2 + x/w * window. let origin = t_secs - window / 2.0; let pair_at = |t: f64| -> (f32, f32) { if !t.is_finite() || t < 0.0 || t > duration { return (0.0, 0.0); } 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; // 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), ) }; let signed_at = |t: f64| { let (a, b) = pair_at(t); if b.abs() >= a.abs() { b } else { a } }; for col in 0..w { let t0 = origin + col as f64 / w as f64 * window; let t1 = origin + (col + 1) as f64 / w as f64 * window; let (mut mn, mut mx) = (0.0f32, 0.0f32); let samples = 4; for k in 0..samples { let t = t0 + (t1 - t0) * (k as f64 + 0.5) / samples as f64; let (l, h) = pair_at(t); mn = mn.min(l); mx = mx.max(h); } scratch.lo[col] = mn; scratch.hi[col] = mx; scratch.sig[col] = signed_at(origin + (col as f64 + 0.5) / w as f64 * window); } // 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. 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; scratch.hi[i] /= peak; scratch.sig[i] /= peak; } } } match viz_style(flags) { VIZ_STYLE_RIBBON => { let tau = std::f64::consts::TAU; let travel = t_secs * 1.35; for col in 0..w { let env = scratch.lo[col].abs().max(scratch.hi[col]).max(0.06); let x_phase = (col as f64 / w.max(1) as f64) * 2.15 * tau; for s in 0..u32::from(viz_strands_of(paint)).max(1) { let frac = s as f32 / (viz_strands_of(paint).max(2) as f32 - 1.0); let scale = 0.28 + 0.72 * frac; let wave = (x_phase + travel + s as f64 * 0.05).sin() as f32; let row = (center + half * env * scale * wave).round() as i32; let glow = i32::from(viz_glow_of(paint)); viz_stamp( &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row, 1.0, bg_y, ink_y, ink_u, ink_v, ); for dy in 1..=glow { let fall = 0.5 / dy as f32; viz_stamp( &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row - dy, fall, bg_y, ink_y, ink_u, ink_v, ); viz_stamp( &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row + dy, fall, bg_y, ink_y, ink_u, ink_v, ); } } } } VIZ_STYLE_RING => { let cx = w as f32 / 2.0; let cy = h as f32 / 2.0; let r0 = (w.min(h) as f32) * 0.28; let amp = (w.min(h) as f32) * 0.18; let tau = std::f32::consts::TAU; let steps = w.max(h) * 4; let strands = viz_strands_of(paint); let glow = viz_glow_of(paint); for strand in 0..strands { let dual = strands >= 2 && strand >= strands / 2; // The dual half takes the clip's own strand colour when it // chose one; without one it is the wheel half a turn from // the clip's hue, at the clip's own saturation, which is // the complement every earlier project paints. let (ir, ig, ib) = if dual && viz_strand_set(paint) { let hue = f32::from(viz_strand_hue_ui(paint)) * 360.0 / 256.0; let sat = f32::from(viz_strand_sat_ui(paint)) / 255.0; hsv_to_rgb(hue, sat, 0.84) } else if dual { viz_ink_from_paint(with_viz_paint_hue( paint, viz_hue_ui(paint).wrapping_add(128), )) } else { viz_ink_from_paint(paint) }; let (iy, iu, iv) = rgb_yuv(ir as i32, ig as i32, ib as i32); let scale = 0.65 + 0.35 * f32::from(strand % 4) / 3.0; let phase = f32::from(strand) * 0.35; scratch.pts.clear(); for i in 0..=steps { let t = i as f32 / steps as f32; let theta = t * tau + t_secs as f32 * 1.1 + phase; let col = ((t * w as f32) as usize).min(w.saturating_sub(1)); let env = scratch.lo[col].abs().max(scratch.hi[col]); let wobble = (theta * 3.0 + phase).sin() * 0.12 * env; let r = r0 + amp * env * scale + amp * wobble; let x = (cx + r * theta.cos()).round() as i32; let row = (cy + r * theta.sin()).round() as i32; scratch.pts.push((x, row)); } if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) { for pair in scratch.pts.windows(2) { viz_line( &mut y, &mut u, &mut v, w, h, cw, ch, pair[0].0, pair[0].1, pair[1].0, pair[1].1, bg_y, iy, iu, iv, glow, ); } } else { viz_chain( &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, iy, iu, iv, glow, ); } } } VIZ_STYLE_WAVE => { scratch.pts.clear(); for col in 0..w { scratch .pts .push((col as i32, (center - scratch.sig[col] * half).round() as i32)); } let glow = viz_glow_of(paint); if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) { for pair in scratch.pts.windows(2) { viz_line( &mut y, &mut u, &mut v, w, h, cw, ch, pair[0].0, pair[0].1, pair[1].0, pair[1].1, bg_y, ink_y, ink_u, ink_v, glow, ); } } else { viz_chain( &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, ink_y, ink_u, ink_v, glow, ); } } _ => { // Timeline envelope: one filled body, tops then bottoms, after // the fold+smooth above. Default look. let glow = i32::from(viz_glow_of(paint)); for col in 0..w { let top = (center - scratch.hi[col] * half).round() as i32; let bot = (center - scratch.lo[col] * half).round() as i32; viz_span( &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, top, bot, bg_y, ink_y, ink_u, ink_v, ); for dy in 1..=glow { let fall = 0.55 / dy as f32; viz_stamp( &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, top - dy, fall, bg_y, ink_y, ink_u, ink_v, ); viz_stamp( &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, bot + dy, fall, bg_y, ink_y, ink_u, ink_v, ); } } } } (y, u, v) } /// `None` when the software path must be used: forced by `VE_SW=1`, or the /// plugin is absent/broken/unable to open this particular file. fn open_hw(path: &Path, start_frame: u32) -> Option { if std::env::var_os("VE_SW").is_some_and(|v| v == "1") { return None; } HwSession::open_at(path, start_frame) } /// `Ok` when the plugin really decodes this file: it opens *and* hands back a /// first picture. Opening only reads the container -- a stream the vendored /// bitstream parser dies on (a 2160p wavefront HEVC did, for one) opens fine and /// then produces nothing, which reaches the user as a black picture with an /// instant `eof` unless the door asks for that first frame. Costs one decoded /// frame per probe. /// /// The `Err` says which half failed, because "there is no decoder for this /// codec" and "the decoder here would not take this stream" are different /// refusals and a user acts on them differently. fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), String> { let Some(mut hw) = open_hw(path, start_frame) else { return Err(codec.needs_plugin()); }; // End of stream counts as a refusal, not as a pass: a session that hands // back no picture at all is exactly the black-frame-and-instant-eof this // probe exists to catch, and `Ok(None)` is how the plugin says it. match hw.next_frame() { Ok(Some(_)) => Ok(()), _ => Err(codec.undecodable()), } } /// Returns whether the session was handled; `false` only when hardware decode /// failed without emitting a single frame, so software can still take over. /// /// The plugin already positioned itself at `start_frame`, so indices are /// counted from there (a stream whose very first sample is not a sync sample /// cannot be decoded from its start at all, and is not accounted for). fn run_hw( hw: &mut HwSession, tx: &SyncSender, start_frame: u32, end_frame: u32, render: &mut Render, abort: &Abort, speed: Speed, ) -> bool { let mut index = start_frame; // Pictures dropped for being late since the last one handed over; see // [`LATE_RUN`]. let mut skipped = 0; loop { if abort.hit() { return true; } match hw.next_frame() { Ok(Some((y, u, v, width, height))) => { let due = index; index += 1; if abort.late(due) { if skipped < LATE_RUN { skipped += 1; } else { skipped = 0; let frame = render.frame(due, y, u, v, width, height); if tx.send(frame).is_err() { return true; // consumer went away } } } else if skip_for_speed(speed, start_frame, due, end_frame) { // Redundant by construction, not by lateness: no run limit // needed (see `skip_for_speed`). } else { skipped = 0; let frame = render.frame(due, y, u, v, width, height); if tx.send(frame).is_err() { return true; // consumer went away } } if index >= end_frame { return true; // end of the requested range } } Ok(None) => return true, Err(e) => { if index == start_frame { return false; } eprintln!("hardware decode error at frame {index}: {e}"); return true; } } } } #[cfg(test)] mod tests { use super::*; use std::sync::mpsc::RecvTimeoutError; use std::time::{Duration, Instant}; fn asset(name: &str) -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("../../assets") .join(name) } /// Drops `path` from the page cache, so the open below really goes to disk /// -- the case the deferred opener exists for, and the one that costs /// seconds on a 25 GB film. Unprivileged (`posix_fadvise(DONTNEED)`), and a /// no-op wherever `python3` is not around: the assertions hold either way, /// the numbers printed are simply the warm ones. fn evict(path: &Path) { let _ = std::process::Command::new("python3") .arg("-c") .arg( "import os,sys\n\ fd=os.open(sys.argv[1],os.O_RDONLY)\n\ os.posix_fadvise(fd,0,0,os.POSIX_FADV_DONTNEED)\n\ os.close(fd)", ) .arg(path) .status(); } /// The whole point of [`DecodeSession::open_worker_deferred`]: the caller /// gets its stream back in the time a thread takes to spawn, and the file /// is opened behind it -- so the first frame necessarily arrives *after* /// the call returned, and the sync opener on the same cold file pays on the /// calling thread what this one does not. #[test] fn a_deferred_open_costs_the_caller_a_thread_and_not_a_demux() { let path = asset("test_baseline.mp4"); evict(&path); let start = Instant::now(); let stream = DecodeSession::open_worker_deferred( &path, 0, u32::MAX, ColorParams::default(), TransformParams::default(), Composer::passthrough(), tonemap::Preset::default(), Speed::NORMAL, ); let returned = start.elapsed(); let frame = stream .frames .recv_timeout(Duration::from_secs(10)) .expect("first frame"); let first_frame = start.elapsed(); // The same file, equally cold, through the door the import path keeps: // that one hands back metadata, and the demux it reads to do so is on // this thread. evict(&path); let sync_start = Instant::now(); let sync = DecodeSession::open_worker( &path, 0, u32::MAX, ColorParams::default(), TransformParams::default(), Composer::passthrough(), tonemap::Preset::default(), ) .expect("sync open"); let sync_returned = sync_start.elapsed(); drop(sync); eprintln!( "deferred open returned in {returned:?}, first frame at {first_frame:?}; \ sync open returned in {sync_returned:?}" ); assert_eq!(frame.index, 0, "the deferred worker starts where it is told"); assert!( returned < Duration::from_millis(10), "the caller waited {returned:?} -- something is still being read \ from the file before this returns" ); assert!( first_frame > returned, "the first frame arrived within the call ({first_frame:?} vs \ {returned:?}), which cannot happen if the open is deferred" ); // No `returned < sync_returned` here on purpose: on a loaded machine // a thread spawn (what the deferred open pays) can cost more wall // clock than a whole sync demux of a small fixture, and the race // flaked one run in three under a parallel build. The two asserts // above already pin the invariant -- the call returns in microseconds // territory and the demux happens after it, on the worker. let _ = sync_returned; } /// The late-picture policy, at the one place it is decided. A worker told /// the playhead is already at frame 20 must not spend a conversion and a /// queue slot on the twenty pictures behind it -- they can never be shown -- /// and it must not go silent either, which is what [`LATE_RUN`] bounds: a /// machine that cannot decode in real time is late on every picture, and one /// in nine still reaches the screen. /// /// Deterministic on purpose: the floor is set by hand rather than by a clock /// that would have to outrun a debug-build decoder to prove anything. #[test] fn a_worker_skips_the_pictures_the_playhead_has_gone_past() { let take = |floor: u32| { let stream = DecodeSession::open_worker_deferred( asset("test_baseline.mp4"), 0, u32::MAX, ColorParams::default(), TransformParams::default(), Composer::passthrough(), tonemap::Preset::default(), Speed::NORMAL, ); stream.worker.playhead(floor); let mut indices = Vec::new(); while indices.len() < 4 { let frame = stream .frames .recv_timeout(Duration::from_secs(10)) .expect("a picture"); indices.push(frame.index); } indices }; // Nobody has moved: every picture of the range is owed, in order. assert_eq!(take(0), vec![0, 1, 2, 3]); // The playhead is at 20, so the pictures before it are decoded (the ones // after reference them) and dropped unconverted -- all but the one in // nine [`LATE_RUN`] lets through, so the caller never goes blind. let caught_up = take(20); assert!( caught_up[0] > 0 && caught_up.windows(2).any(|w| w[1] > w[0] + 1), "nothing was skipped: {caught_up:?}" ); assert!( caught_up.iter().any(|&i| i >= 20), "the playhead was never reached: {caught_up:?}" ); assert!( caught_up.len() >= 4, "the worker went silent instead of dropping down to one in nine" ); } /// [`skip_for_speed`] on its own, with no worker or channel involved: at /// 2x every other source frame maps onto the same timeline frame /// ([`Speed::timeline_at`]), so `skip`/`keep` must alternate exactly, and /// the last frame of the span (the one [`crate::project::Span::source_len`] /// is built to land on) must never be skipped regardless of where the /// alternation lands. #[test] fn skip_for_speed_alternates_at_2x_and_never_drops_the_last_frame() { let speed = Speed::from_permille(2000); let start = 100; let end = 110; let skips: Vec = (start..end) .map(|due| skip_for_speed(speed, start, due, end)) .collect(); // Alternation holds up to (but not including) the span's last frame, // which is special-cased below. for pair in (start..end - 2).zip(skips.windows(2)) { let (due, w) = pair; assert_eq!( w[0], !w[1], "frame {due} and its successor should alternate skip/keep at 2x: {skips:?}" ); } assert!( !skip_for_speed(speed, start, end - 1, end), "the last frame of the span must never be skipped" ); } /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait. /// The channel is bounded, so such a worker is parked in `send` within a /// few frames, and the only thing that can wake it is its receiver going /// away -- which is why the receiver is the first field and the join inside /// `Worker::drop` is the second. Swap those two fields and this hangs. /// /// This is the whole basis of every teardown path in the engine, so it is /// asserted rather than commented: the drop runs on a second thread and a /// regression fails in ten seconds instead of hanging the suite forever. #[test] fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() { let (_meta, stream) = DecodeSession::open_worker( &asset("test_baseline.mp4"), 0, u32::MAX, ColorParams::default(), TransformParams::default(), Composer::passthrough(), tonemap::Preset::default(), ) .expect("open"); // Nothing is ever received: two frames fill the channel and the next // send parks the decode thread, exactly as a refused project load does. thread::sleep(Duration::from_millis(500)); let (done_tx, done_rx) = sync_channel(1); thread::spawn(move || { drop(stream); let _ = done_tx.send(()); }); assert!( done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout), "dropping a parked stream deadlocked: it joined a decode thread \ while still holding the receiver that thread is waiting on" ); } /// The empty-peaks source -- a trackless file, or any peaks decode error /// (`peaks_shared(..).ok().flatten().unwrap_or_default()`) -- must paint /// the flat line, never panic: a visualizer frame always exists. The /// `pair_at` interpolator indexes `peaks[len() - 1]`, which is only /// reachable inside the `!peaks.is_empty()` guard, so the empty vec takes /// the early flat-line path and no column ever samples a bucket. #[test] fn empty_peaks_paint_the_flat_line() { let w = 320u32; let h = 180u32; let (y, _u, _v) = visualizer_i420(&mut VizScratch::default(), &[], 0.0, w, h, 1, 0); assert_eq!((y.len(), _u.len(), _v.len()), (320 * 180, 160 * 90, 160 * 90)); // The ink's top and bottom row for a given peaks slice: one unbroken // band, and where it sits. let band = |peaks: &[(f32, f32)]| { let (y, _, _) = visualizer_i420(&mut VizScratch::default(), peaks, 0.0, w, h, 1, 0); let rows: Vec = (0..h as usize) .filter(|&row| y[row * 320..(row + 1) * 320].iter().any(|&p| p > 40)) .collect(); assert!( !rows.is_empty() && rows.len() == rows[rows.len() - 1] - rows[0] + 1, "the ink must be one unbroken band, not scattered rows: {rows:?}" ); (rows[0], rows[rows.len() - 1]) }; // Silence is the zero line and nothing else: the band is on the middle // row and a line's thickness -- five rows here, the trace's own -- not // a picture's. let (first, last) = band(&[]); let zero = h as usize / 2; assert!( first <= zero && zero <= last, "the zero line itself must be inked: {first}..={last}" ); assert!( last - first <= (h as usize) / 8, "a peaks-less source painted a {}-row band, not a line: {first}..={last}", last - first + 1 ); // ...and the same seat over full-scale peaks is a picture, which is // what makes the line above a claim about silence rather than about a // painter that never draws anything. let (loud_first, loud_last) = band(&[(-1.0, 1.0); 1200]); assert!( loud_last - loud_first > (last - first) * 3, "full-scale peaks painted {loud_first}..={loud_last}, no taller than silence's {first}..={last}" ); } /// A canvas with no size has no row to draw the zero line on. The row index /// is derived from the height (`h as isize - 1`), so a *height* of zero /// underflows into `clamp`'s `min <= max` assert and takes the worker /// thread with it. A `Composer::passthrough()` canvas is exactly this /// (`dims()` is `(0, 0)`, `places_nothing()` is true for it), and a /// one-pixel-high canvas floors to the same nothing, the planes being even. #[test] fn a_size_less_visualizer_canvas_paints_nothing() { let size_less = visualizer_i420(&mut VizScratch::default(), &[], 0.0, 0, 0, 0, 0); assert_eq!(size_less, (Vec::new(), Vec::new(), Vec::new())); let thin = visualizer_i420(&mut VizScratch::default(), &[(0.0, 1.0)], 0.0, 2, 1, 0, 0); assert!( thin.0.is_empty() && thin.1.is_empty() && thin.2.is_empty(), "a 2x1 canvas has no even-sized plane to paint on" ); } /// The same canvas, driven through the seat that really opens one: the /// worker thread is where a panic *is* the defect -- it closes the frame /// channel and the caller sees a span with no picture in it, which is what /// the export then aborts on. #[test] fn a_pass_through_canvas_visualizer_paints_nothing_and_stays_alive() { let transform = TransformParams { pos_x: 0.25, ..Default::default() }; let stream = DecodeSession::open_visualizer( &asset("test_opus_51.mka"), 0, 0, 2, 30.0, ColorParams::default(), transform, Composer::passthrough(), VIZ_STYLE_WAVE, 0, ) .expect("open the visualizer"); let frame = stream .frames .recv_timeout(Duration::from_secs(30)) .expect("a picture, not a worker that died instead of painting one"); assert_eq!((frame.width, frame.height), (0, 0)); assert!(frame.bgra.is_empty()); } /// The same seat, at the two canvas sizes whose *declared* dims used to /// disagree with the planes the painter handed back: one pixel high (the /// planes floor to nothing) and odd (they floor to the even size below). /// The worker declares the size it renders at -- masked and floored the way /// the painter masks -- so the conversion below always has the chroma plane /// it indexes, and a picture arrives at the canvas's own size. #[test] fn a_thin_and_an_odd_visualizer_canvas_paint_through_the_seat() { for (w, h) in [(1920u32, 1u32), (1921, 1081)] { let stream = DecodeSession::open_visualizer( &asset("test_opus_51.mka"), 0, 0, 2, 30.0, ColorParams::default(), TransformParams::default(), Composer::new(w, h, crate::scale::FitPolicy::Fit), VIZ_STYLE_WAVE, 0, ) .unwrap_or_else(|e| panic!("open the visualizer at {w}x{h}: {e}")); let frame = stream .frames .recv_timeout(Duration::from_secs(30)) .unwrap_or_else(|e| { panic!("a picture for a {w}x{h} canvas, not a worker that died instead: {e}") }); assert_eq!( (frame.width, frame.height), (w, h), "a {w}x{h} canvas is handed back at its own size" ); assert_eq!( frame.bgra.len(), (w * h * 4) as usize, "and converted across the whole canvas at {w}x{h}" ); } } /// The `VE_SW=1` pin, borrowed for one test and put back as it was: it is /// process-wide, and this file's unit tests share one process. struct SwPin(Option); impl SwPin { fn set() -> Self { let had = std::env::var_os("VE_SW"); unsafe { std::env::set_var("VE_SW", "1") }; Self(had) } } impl Drop for SwPin { fn drop(&mut self) { match &self.0 { Some(was) => unsafe { std::env::set_var("VE_SW", was) }, None => unsafe { std::env::remove_var("VE_SW") }, } } } /// A span whose codec has no seat at all -- the plugin never opened one and /// there is no software decoder for these bytes -- must report the *gap* it /// is. The cell used to be left claiming `Hardware`: the arm below the /// software fallback set it before the session that produced nothing, and /// the front-end then named a decoder that had decoded no frame. /// /// Driven through [`run_span`] itself, which is the only door that reaches /// the arm: every public one refuses a plugin-only codec at `hw_decodes` /// before a span exists (VP8, VP9 and HEVC all refuse on this machine), and /// the arm is for the box where the plugin was there and then was not. /// `VE_SW=1` is what makes that box-independent; see [`SwPin`]. #[test] fn a_span_with_no_seat_at_all_reports_the_gap() { let _pin = SwPin::set(); let path = asset("test_vp8.mp4"); let mut source = None; let cancel = AtomicBool::new(false); let generation = AtomicU64::new(0); let floor = AtomicU32::new(0); let abort = Abort { cancel: &cancel, generation: &generation, mine: 0, floor: &floor, }; let (tx, rx) = sync_channel(2); let cell = BackendCell::new(Backend::Opening); run_span( &path, &mut source, SpanCmd { generation: 0, start: 0, end: 2, color: ColorParams::default(), transform: TransformParams::default(), canvas: Composer::passthrough(), tone: tonemap::Preset::default(), speed: Speed::NORMAL, tx, }, &abort, &cell, ); assert_eq!( cell.get(), Backend::Gap, "a VP8 span with no hardware must report the gap, not a hardware seat" ); assert!( rx.try_recv().is_err(), "a gap decodes nothing: no picture may come down the channel" ); } #[test] fn visualizer_default_is_a_blue_envelope() { let mut peaks = vec![(0.0, 0.0); 12_000]; for (i, p) in peaks.iter_mut().enumerate() { let a = ((i as f32 / 400.0) * std::f32::consts::TAU).sin() * 0.8; *p = (-a.abs(), a.abs()); } let flags = 1u8; let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, flags, 0); let ink = y.iter().filter(|&&p| p > 40).count(); assert!(ink > 200, "envelope missing: {ink}"); assert!(ink < y.len() * 9 / 10, "solid frame, not an envelope: {ink}"); let mut blue = 0usize; for i in 0..u.len() { if u[i] > 145 && v[i] < 120 { blue += 1; } } assert!(blue > 10, "default ink was not timeline blue: {blue}"); let ring = with_viz_style(flags, VIZ_STYLE_RING); let (yr, _, _) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, 0); let ring_ink = yr.iter().filter(|&&p| p > 40).count(); assert!(ring_ink > 80, "ring missing: {ring_ink}"); assert!(ring_ink < ink, "ring should be a stroke, not a fill"); let hue_paint = with_viz_paint_hue(0, 40); let (_, u2, v2) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 64, 32, flags, hue_paint); let mut shifted = 0usize; for i in 0..u2.len() { if u2[i] < 120 && v2[i] > 130 { shifted += 1; } } assert!(shifted > 2, "hue 8 did not leave blue"); } /// The paint's byte layout: the strand colour lives above the clip's own /// four bytes and the top bit is the flag, so either strand setter marks /// the colour chosen and clearing drops both bytes with the flag. #[test] fn the_paint_packs_the_strand_colour_above_the_v22_halves() { let p = with_viz_paint_strand_sat(with_viz_paint_strand_hue(VIZ_PAINT_AZURE, 0xAB), 0xCD); assert_eq!(p & 0xFFFF_FFFF, VIZ_PAINT_AZURE, "the low half never moves"); assert_eq!((p >> 32) & 0xFF, 0xAB); assert_eq!((p >> 40) & 0xFF, 0xCD); assert!(viz_strand_set(p)); assert_eq!(viz_strand_hue_ui(p), 0xAB); assert_eq!(viz_strand_sat_ui(p), 0xCD); assert_eq!(viz_strand_clear(p), VIZ_PAINT_AZURE); assert!(!viz_strand_set(viz_strand_clear(p))); } /// The shapes a colour is typed in all mean the same ink, and everything /// else is refused rather than guessed at. #[test] fn typed_colours_read_as_hex_rgb_and_rgba() { let want = viz_color_from_text("#4F8FD6").expect("a hex colour"); assert_eq!(want, (150, 161), "hue and sat on the field's own scales"); for text in [ "#4F8FD6", "4f8fd6", " #4f8fd6 ", "rgb(79,143,214)", "rgb(79/143/214)", "RGBA(79, 143, 214, 255)", ] { assert_eq!(viz_color_from_text(text), Some(want), "{text}"); } for text in [ "#12345", "zz", "rgb(300,0,0)", "rgb(1,2)", "", "rgb 79,143,214)", "rgb(79,143,214", "#4F8FD", "#4F8FD67", "#GGGGGG", "rgb(79,143,214,255,0)", "rgb(79;143;214)", ] { assert_eq!(viz_color_from_text(text), None, "{text}"); } } /// A colour's hex is the ink the painter draws, and reading it back /// gives the sliders their own value again -- for the 47053 of the 65536 /// hues and saturations a trip through bytes can carry. The rest land on /// a neighbour: their smallest channel rounds to a byte whose ratio is /// not the one that was asked for. Full saturation is where that channel /// is the one the value sets exactly, and it survives at every hue. #[test] fn a_sampled_palette_round_trips_through_its_hex() { for hue in (0..=255u8).step_by(8) { let hex = viz_color_hex(hue, 255); assert_eq!(viz_color_from_text(&hex), Some((hue, 255)), "{hex}"); } // The achromatic end, where hue is not a colour at all. assert_eq!(viz_color_from_text(&viz_color_hex(0, 0)), Some((0, 0))); assert_eq!(viz_color_from_text(&viz_color_hex(200, 0)), Some((0, 0))); // ...and the whole grid, so a change that quietly shrinks what the // trip can carry cannot pass by leaving the sample above green. let exact = (0..=255u8) .flat_map(|hue| (0..=255u8).map(move |sat| (hue, sat))) .filter(|&(hue, sat)| viz_color_from_text(&viz_color_hex(hue, sat)) == Some((hue, sat))) .count(); assert_eq!(exact, 47_053, "the colours a hex round trip keeps"); } /// The dual half of a ring takes the clip's own strand colour when it has /// one: a choice that names the automatic complement paints the same /// frame, another repaints the dual strands in it, and a paint whose flag /// is clear is the picture it has always been -- strand bytes or no. #[test] fn a_chosen_strand_colour_repaints_only_the_dual_half_of_a_ring() { let mut peaks = vec![(0.0, 0.0); 12_000]; for (i, p) in peaks.iter_mut().enumerate() { let a = ((i as f32 / 400.0) * std::f32::consts::TAU).sin() * 0.8; *p = (-a.abs(), a.abs()); } let ring = with_viz_style(1, VIZ_STYLE_RING); let auto = VIZ_PAINT_AZURE; let (y0, u0, v0) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, auto); // The automatic dual is half a wheel from the clip's hue at the // clip's own saturation; choosing exactly that colour changes // nothing at all. let same = with_viz_paint_strand_sat( with_viz_paint_strand_hue(auto, viz_hue_ui(auto).wrapping_add(128)), viz_sat_ui(auto), ); assert!(viz_strand_set(same)); let (ys, us, vs) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, same); assert_eq!(ys, y0, "the automatic complement, spelled out, is the same frame"); assert_eq!(us, u0); assert_eq!(vs, v0); // A colour of its own repaints the dual strands in it. let red = with_viz_paint_strand_sat(with_viz_paint_strand_hue(auto, 0), 255); let (_, u1, v1) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, red); let red_px = (0..u1.len()).filter(|&i| u1[i] < 110 && v1[i] > 200).count(); let auto_px = (0..u0.len()).filter(|&i| u0[i] < 110 && v0[i] > 200).count(); assert!(red_px > 20, "the chosen colour did not reach the frame: {red_px}"); assert_eq!(auto_px, 0, "the automatic ring already painted red: {auto_px}"); // ...and the flag is what decides: strand bytes with it clear are // the unset picture, byte for byte. let stale = auto | (77u64 << 32) | (9u64 << 40); assert!(!viz_strand_set(stale)); let (yt, ut, vt) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, stale); assert_eq!(yt, y0, "an unset strand colour is the frame it always was"); assert_eq!(ut, u0); assert_eq!(vt, v0); } /// The look of a frame the glow pass was rewritten for, pinned byte for /// byte: [`viz_chain`] replaced the per-point discs under /// [`VIZ_STYLE_RING`] and [`VIZ_STYLE_WAVE`], whose glow cost `steps * pi * /// glow^2` cells per frame (295 ms of one 1080p ring frame at glow 16 /// against 18 ms after), and this is what says the pictures did not move /// with it. FNV-1a over `y`, then `u`, then `v`, taken from the disc /// implementation that shipped before the rewrite; `fill` and `ribbon` are /// in the table because their planes share the frame with a chain's, and /// the row/run walk could still have reached them through a shared helper. /// /// Scope: eight strands (what [`VIZ_PAINT_AZURE`] carries) at four gloss /// including both ends. A strand count changes a chain's scale and phase, /// not the pass over it. #[test] fn the_glow_pass_paints_the_bytes_it_always_did() { const GOLDEN: &[(&str, u8, u64)] = &[ ("fill", 0, 0xe141_5e51_fcc1_7ea1), ("fill", 2, 0x3842_fef4_d4ec_4239), ("fill", 8, 0xfaea_3e6f_9718_1d31), ("fill", 16, 0x6a09_31fe_e9f1_3069), ("ribbon", 0, 0x91fa_9b49_48d8_bcfe), ("ribbon", 2, 0xd4d2_bcce_3c32_14d8), ("ribbon", 8, 0xd23a_d502_17ac_697c), ("ribbon", 16, 0xd7de_425a_6737_11c3), ("ring", 0, 0xcfbe_55da_b222_0a1b), ("ring", 2, 0x5468_01eb_522e_21dc), ("ring", 8, 0xc08f_994e_4a19_c9f4), ("ring", 16, 0x8cee_6dcd_256c_d484), ("wave", 0, 0x2266_ba70_ab2a_06bd), ("wave", 2, 0xd05f_0a31_9264_b377), ("wave", 8, 0x2e50_7536_c5dd_6035), ("wave", 16, 0xf888_b09c_dae2_dd36), ]; let peaks = benchmark_peaks((149.6 * f64::from(VIZ_BUCKETS_PER_SEC)) as usize); for &(name, glow, want) in GOLDEN { let style = match name { "fill" => VIZ_STYLE_FILL, "ribbon" => VIZ_STYLE_RIBBON, "ring" => VIZ_STYLE_RING, _ => VIZ_STYLE_WAVE, }; let flags = with_viz_style(1, style); let paint = with_viz_paint_glow(VIZ_PAINT_AZURE, glow); let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 37.5, 1920, 1080, flags, paint); let mut hash = 0xcbf2_9ce4_8422_2325u64; for buf in [&y, &u, &v] { for &b in buf.iter() { hash ^= u64::from(b); hash = hash.wrapping_mul(0x0000_0100_0000_01b3); } } assert_eq!( hash, want, "{name} at glow {glow} paints different bytes than it always did ({hash:016x})" ); } } /// The envelope both of the tests above paint: loud enough that every /// column carries ink, and shaped so a ring's radii and a wave's trace /// differ from column to column. fn benchmark_peaks(n: usize) -> Vec<(f32, f32)> { let mut peaks = vec![(0.0f32, 0.0f32); n]; for (i, p) in peaks.iter_mut().enumerate() { let t = i as f64 / f64::from(VIZ_BUCKETS_PER_SEC); let a = ((t * 0.7).sin() * 0.6 + (t * 5.3).sin() * 0.25 + 0.1) as f32; *p = (-a.abs(), a.abs()); } peaks } } fn run( demuxer: &mut Demuxer, tx: &SyncSender, start_frame: u32, end_frame: u32, render: &mut Render, abort: &Abort, speed: Speed, ) { // A decoder per span, and cheap: it is a parameter-set map and a picture // buffer, while the *demuxer* -- whose index cost seconds to build -- is the // one this worker keeps. let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264)) .expect("ec-h264 takes its own codec id"); // Decoding has to restart at a sync sample, so pictures between it and // `start_frame` are decoded (the target frame references them) but never // converted or sent. Signed, because the landing sync sample can sit inside // what the file's edit list trims, i.e. *before* frame 0. let mut index = demuxer.seek_to_sync_at_or_before(start_frame); // Pictures leave the decoder in display order -- clause C.4.5.3 bumps the // decoded picture buffer -- and the landing index above is a display index // by the demuxer's own contract, so the two count one to one. The decode // order this loop used to emit was a corner-cut that only held for // Baseline: a stream with B pictures arrived scrambled and mislabelled, // and every reader of `index` (the transport's playhead, `skip_for_speed`, // the export's frame map) reads it as a timeline position. let mut skipped = 0; // Set once the demuxer runs dry: `flush` makes the decoder release every // picture its reorder delay still holds, and the drain below ends on // `Error::Eof` once they are out. let mut flushed = false; // Every way this span ends: abort, consumer gone, end of the requested // range, end of stream. let mut done = false; while !done { if abort.hit() { break; } // One access unit is one packet. No timestamps travel with it: the // presentation order comes out of the bitstream's own POC, and `index` // is counted off the pictures as the decoder releases them. match demuxer.next_access_unit() { Ok(Some(au)) => { let packet = Packet::new(0, TimeBase::new(1, 1), au); if let Err(e) = decoder.send_packet(&packet) { eprintln!("decode error at access unit {index}: {e}"); break; } } Ok(None) => { flushed = true; if let Err(e) = decoder.flush() { eprintln!("decode error at end of stream: {e}"); break; } } Err(e) => { eprintln!("demux error: {e}"); break; } } // Take everything the packet released; `NeedMore` is the signal to go // back for the next access unit. loop { let pic = match decoder.receive_frame() { Ok(pic) => pic, Err(e) if e.is_need_more() || e.is_eof() => break, Err(e) => { eprintln!("decode error at access unit {index}: {e}"); break; } }; let ec_core::frame::Frame::Video(pic) = pic else { continue; }; if index < i64::from(start_frame) { index += 1; continue; } let due = index as u32; index += 1; if abort.late(due) { if skipped < LATE_RUN { skipped += 1; } else { skipped = 0; if send_picture(&pic, due, render, tx) { done = true; // consumer went away break; } } } else if skip_for_speed(speed, start_frame, due, end_frame) { // Redundant by construction, not by lateness: no run limit // needed (see `skip_for_speed`). } else { skipped = 0; if send_picture(&pic, due, render, tx) { done = true; // consumer went away break; } } if index >= i64::from(end_frame) { done = true; // end of the requested range break; } } if flushed { done = true; } } } /// Whether an access unit leads with a sequence header OBU, which is how both /// containers mark a random-access point for AV1: the demuxer prepends the /// `av1C`/`CodecPrivate` record (itself one sequence header OBU) ahead of every /// sync sample, so the marker rides on the same bytes the decoder needs. Type 1 /// in bits 6..3 of the first OBU header byte. fn leads_with_sequence_header(au: &[u8]) -> bool { matches!(au.first(), Some(&first) if first >> 3 & 0xF == 1) } /// One [`Av1Picture`] down to the tightly packed 8-bit I420 every converter /// here takes. 8-bit samples arrive as `u16` in `0..=255` and narrow losslessly; /// a 10-bit stream's `0..=1023` downshifts by two, the same truncation the /// hardware seat's P010 read-back performs when it takes the high byte of each /// pair (`p010_to_i420`, engine-hw) -- so the two seats hand the renderer /// byte-identical planes off the same file. 12-bit never reaches a seat: the /// demuxer refuses it at open, where `parse_av1c` reads the depth. fn narrow_av1( picture: &Av1Picture, ten_bit: bool, y: &mut Vec, u: &mut Vec, v: &mut Vec, ) { let shift = u8::from(ten_bit) * 2; let plane = |src: &[u16], dst: &mut Vec| { dst.clear(); dst.extend(src.iter().map(|&sample| (sample >> shift) as u8)); }; plane(&picture.y, y); plane(&picture.u, u); plane(&picture.v, v); } /// Narrows one [`Av1Picture`] ([`narrow_av1`]) and queues it through the same /// [`Render`] every other seat's pictures go through. `true` when the consumer /// went away, so the span stops rather than keeps decoding into a void. fn send_av1( picture: &Av1Picture, due: u32, ten_bit: bool, render: &mut Render, tx: &SyncSender, y: &mut Vec, u: &mut Vec, v: &mut Vec, ) -> bool { narrow_av1(picture, ten_bit, y, u, v); let frame = render.frame(due, y, u, v, picture.width as u32, picture.height as u32); tx.send(frame).is_err() } /// The AV1 software seat: one span of [`ec_av1`] through the same loop /// [`run`] drives `ec-h264` through. A decoder per span, and cheap -- it is the /// reference bank and one output picture, while the *demuxer* is the one this /// worker keeps. `ec-av1` has no packet-by-packet door; it takes one whole OBU /// stream, so the span is fed as it is built: every access unit from the landing /// sync sample up to (not including) the next one is one chunk, and a chunk is /// a legal random-access stream on its own -- it leads with the sequence header /// and a key frame, which is exactly what makes the chunk boundary detectable /// here ([`leads_with_sequence_header`]). A stream whose inter frames carried /// an in-band sequence header would be cut mid-GOP and refused by name below, /// never silently misread; container storage keeps the sequence header in the /// config record precisely so that does not happen. /// /// Chunks decode to their end, so the reorder window of the chunk the span /// ends in always drains: hidden frames (`show_frame == 0`) are references /// and arrive at the sink with `shown == false`, and the frames they hold /// back in output order are the tail the sink still has to see. /// /// A refusal out of `ec-av1` -- a real-world stream hitting a shape the /// decoder does not reconstruct -- fails the span in words, mid-film, the way /// the hardware seat's errors do: named on stderr, the pictures decoded so /// far stand, and no garbage is sent. The same sentinel ends a span that has /// delivered everything asked of it without decoding the rest of its last /// chunk. fn run_av1( demuxer: &mut Demuxer, tx: &SyncSender, start_frame: u32, end_frame: u32, render: &mut Render, abort: &Abort, speed: Speed, ) { // Signed, for the same reason [`run`]'s is: the landing sync sample can // sit inside what an mp4's edit list trims, i.e. before frame 0. let mut index = demuxer.seek_to_sync_at_or_before(start_frame); // Reusable plane buffers: one allocation each for the whole span, refilled // per picture by [`narrow_av1`]. let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new()); let mut skipped = 0; // Every way this span ends: abort, consumer gone, the requested range // delivered, the demuxer dry, or a refusal out of the decoder. let mut done = false; let mut demux_dry = false; // An access unit read past a chunk boundary, waiting to head the next one. let mut pending: Option> = None; while !done && !demux_dry { if abort.hit() { break; } // One chunk: the access units from a sync sample up to the next one. let mut stream = pending.take().unwrap_or_default(); while !demux_dry && pending.is_none() { match demuxer.next_access_unit() { Ok(Some(au)) => { if !stream.is_empty() && leads_with_sequence_header(&au) { pending = Some(au); } else { stream.extend_from_slice(&au); } } Ok(None) => demux_dry = true, Err(e) => { eprintln!("demux error: {e}"); return; } } } let ten_bit = demuxer.bit_depth() == 10; let decode = decode_stream_with(&stream, |picture, _, shown| { // Hidden frames are references: they take no display slot and // are never sent, but they do hold the chunk's output order // back, which is why the chunk decodes to its end. if !shown { return Ok(()); } let due = index; index += 1; if due < i64::from(start_frame) { return Ok(()); } let due = due as u32; // The three ends [`run`] reaches per picture, in its own shape: // late for the playhead (one in [`LATE_RUN`] still goes through), // redundant by construction at speed, or a conversion and a send. let sent = if abort.late(due) { if skipped < LATE_RUN { skipped += 1; false } else { skipped = 0; send_av1(picture, due, ten_bit, render, tx, &mut y, &mut u, &mut v) } } else if skip_for_speed(speed, start_frame, due, end_frame) { // Redundant by construction, not by lateness: no run limit // needed (see `skip_for_speed`). false } else { skipped = 0; send_av1(picture, due, ten_bit, render, tx, &mut y, &mut u, &mut v) }; if sent { done = true; // consumer went away } if done || i64::from(due) + 1 >= i64::from(end_frame) { done = true; // the range is out, or nobody is left to take it // Stops the decode inside the chunk: everything the span // asked for has been sent, and the chunk's remaining coded // frames are references for pictures nobody asked for. return Err(Av1Error::Eof); } Ok(()) }); // `done` was set by the sink itself for the `Eof` it returns -- the // sentinel, not a refusal. Any other `Err` is a refusal out of the // decoder, named where the hardware seat's decode errors are named; // the pictures decoded so far stand and the span ends. if let Err(e) = decode { if !done { eprintln!("software AV1 decode failed at frame {index}: {e}"); done = true; } } } } /// Converts one decoded picture and queues it. `true` when the consumer went /// away, so the span stops rather than keeps decoding into a void. fn send_picture(pic: &VideoFrame, due: u32, render: &mut Render, tx: &SyncSender) -> bool { // The decoder crops each picture into tightly packed planes, the shape // every converter below takes. A padded plane would render skewed rather // than subtly wrong, so the assumption is pinned where it is relied on -- // free in a release build. let (y, u, v) = (&pic.planes[0], &pic.planes[1], &pic.planes[2]); debug_assert_eq!(y.stride, pic.width as usize, "padded luma plane"); debug_assert_eq!( u.stride, pic.width.div_ceil(2) as usize, "padded chroma plane" ); let frame = render.frame(due, &y.data, &u.data, &v.data, pic.width, pic.height); tx.send(frame).is_err() }