//! 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::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}; use std::sync::{Arc, Mutex}; use std::thread; use ec_av1::encode::Picture as Av1Picture; use ec_av1::stream::decode_stream_with; use ec_core::frame::VideoFrame; use ec_core::registry::Decoder as _; use ec_core::registry::{CodecId, CodecParameters}; use ec_core::{Error as Av1Error, Packet, TimeBase}; use ec_h264::H264Decoder; use crate::color::ColorParams; use crate::colorspace::{Chroma, 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; mod dnxhd; mod dv; mod hevc; pub(crate) mod intra; mod mjpeg; mod raw; mod prores; use hevc::run_hevc; mod mpeg2; use mpeg2::run_mpeg2; mod mpeg4; use mpeg4::run_mpeg4; mod vp8; use vp8::run_vp8; mod vp9; use vp9::run_vp9; /// One software picture as the tightly packed 8-bit I420 every converter takes: /// the buffers a pulled decoder fills, reused for every picture of a stream. #[derive(Default)] pub(crate) struct I420 { pub(crate) width: u32, pub(crate) height: u32, pub(crate) y: Vec, pub(crate) u: Vec, pub(crate) v: Vec, } /// The 10-bit planes of a picture an export's 10-bit seat encodes: the same /// shape as [`I420`], at 16 bits a sample and 10 bits of depth. #[derive(Default)] pub(crate) struct Wide { pub(crate) width: u32, pub(crate) height: u32, pub(crate) y: Vec, pub(crate) u: Vec, pub(crate) v: Vec, } /// What `ec-h264` hands over for a High 10 stream (`I010`: 16-bit little-endian /// samples, 10 bits of depth, a 9-bit stream left-aligned), taken into the two /// shapes the engine reads: [`Wide`] for a 10-bit export, and the truncated /// 8-bit [`I420`] playback and an 8-bit export use (`>> 2`, the same /// truncation `ec-h265`'s narrowing and the P010 read-back make). Buffers are /// reused for every picture of a stream. #[derive(Default)] pub(crate) struct Deep { pub(crate) wide: Wide, pub(crate) narrow: I420, /// Whether the last picture loaded was `I010`. pub(crate) on: bool, /// Whether it went into `wide` (else into `narrow`). pub(crate) in_wide: bool, } impl Deep { /// Takes `pic` when it is anything but plain 8-bit 4:2:0: `I010` (High 10), /// the 4:2:2 shapes `I422` and `I210`, whose chroma is full height and is /// averaged down a pair of rows to 4:2:0 as HEVC 4:2:2 is /// (`(a + b + 1) >> 1`), and the 4:4:4 shapes `I444` and `I410`, averaged /// down over 2x2 the same way. Into `wide` when `want_wide` and the picture is /// above 8 bits, into `narrow` otherwise (`>> 2` for 10-bit); a plain /// picture just clears [`Deep::on`]. pub(crate) fn load(&mut self, pic: &VideoFrame, want_wide: bool) { use ec_core::frame::PixelFormat as F; // (bytes per sample, chroma is full height, chroma is full width) let (bytes, full_height, full_width) = match pic.format { F::I010 => (2usize, false, false), F::I210 => (2, true, false), F::I422 => (1, true, false), F::I410 => (2, true, true), F::I444 => (1, true, true), _ => { self.on = false; self.in_wide = false; return; } }; self.on = true; self.in_wide = want_wide && bytes == 2; let (w, h) = (pic.width as usize, pic.height as usize); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); let src_ch = if full_height { h } else { ch }; let src_cw = if full_width { w } else { cw }; let dims = [(w, h, h, w), (cw, ch, src_ch, src_cw), (cw, ch, src_ch, src_cw)]; let sample = |line: &[u8], x: usize| -> u32 { if bytes == 2 { u32::from(u16::from_le_bytes([line[2 * x], line[2 * x + 1]])) } else { u32::from(line[x]) } }; // One output sample (r, x): the sample itself, or the rounded average of // the 2x1 / 1x2 / 2x2 source samples under it for chroma stored at full // height and/or width (`(a + b + 1) >> 1`, applied per axis). let row_value = |plane: &ec_core::Plane, r: usize, rows_in: usize, cols_in: usize, x: usize, avg_v: bool, avg_h: bool| -> u32 { let line = |row: usize| &plane.data[row * plane.stride..row * plane.stride + cols_in * bytes]; let at = |row: usize| -> u32 { if avg_h { let (a, b) = (2 * x, (2 * x + 1).min(cols_in - 1)); (sample(line(row), a) + sample(line(row), b) + 1) >> 1 } else { sample(line(row), x) } }; if avg_v { let (a, b) = (2 * r, (2 * r + 1).min(rows_in - 1)); (at(a) + at(b) + 1) >> 1 } else { at(r) } }; if self.in_wide { self.wide.width = pic.width; self.wide.height = pic.height; let out = [&mut self.wide.y, &mut self.wide.u, &mut self.wide.v]; for (i, ((plane, (pw, ph, rows_in, cols_in)), out)) in pic.planes.iter().zip(dims).zip(out).enumerate() { out.clear(); for r in 0..ph { out.extend((0..pw).map(|x| row_value(plane, r, rows_in, cols_in, x, full_height && i > 0, full_width && i > 0) as u16)); } } } else { self.narrow.width = pic.width; self.narrow.height = pic.height; let shift = if bytes == 2 { 2 } else { 0 }; let out = [&mut self.narrow.y, &mut self.narrow.u, &mut self.narrow.v]; for (i, ((plane, (pw, ph, rows_in, cols_in)), out)) in pic.planes.iter().zip(dims).zip(out).enumerate() { out.clear(); for r in 0..ph { out.extend((0..pw).map(|x| (row_value(plane, r, rows_in, cols_in, x, full_height && i > 0, full_width && i > 0) >> shift) as u8)); } } } } } /// The software seats whose pictures come one at a time: `ec-h265`, `ec-vp9`, /// `ec-vp8`, `ec-mpeg2`, `ec-mpeg4` and the intra-only `ec-prores`, `ec-dnxhd`, `ec-mjpeg` and `ec-dv`. Export decodes its sources through here, and playback's span /// loops read the same streams, so each codec's decode is written once. pub(crate) enum Pulled { Hevc(Box), Vp9(Box), Vp8(Box), Mpeg2(Box), ProRes(Box), Dnxhd(Box), Mjpeg(Box), Dv(Box), Mpeg4(Box), Raw(Box), } impl Pulled { /// A stream positioned at the sync sample at or before `start_frame`. `None` /// for a codec with no pulled seat: H.264 and AV1 keep their own loops. pub(crate) fn open( codec: Codec, demuxer: &mut Demuxer, start_frame: u32, deint: crate::project::Deinterlace, ) -> Option { Some(match codec { Codec::Hevc => Self::Hevc(Box::new(hevc::Stream::open(demuxer, start_frame))), Codec::Vp9 => Self::Vp9(Box::new(vp9::Stream::open(demuxer, start_frame))), Codec::Vp8 => Self::Vp8(Box::new(vp8::Stream::open(demuxer, start_frame))), Codec::Mpeg2 => Self::Mpeg2(Box::new(mpeg2::Stream::open(demuxer, start_frame, deint))), Codec::ProRes => Self::ProRes(Box::new(prores::Stream::open(demuxer, start_frame))), Codec::Dnxhd => Self::Dnxhd(Box::new(dnxhd::Stream::open(demuxer, start_frame))), Codec::Mjpeg => Self::Mjpeg(Box::new(mjpeg::Stream::open(demuxer, start_frame))), Codec::Dv => Self::Dv(Box::new(dv::Stream::open(demuxer, start_frame))), Codec::Mpeg4 | Codec::MsMpeg4 => Self::Mpeg4(Box::new(mpeg4::Stream::open(demuxer, start_frame))), Codec::Raw => Self::Raw(Box::new(raw::Stream::open(demuxer, start_frame))), Codec::H264 | Codec::Av1 => return None, }) } /// The next picture in display order at 10-bit scale, into `out`, with its /// display index. HEVC and the intra-only seats (ProRes, DNxHD, MJPEG) have such /// a seat; the others are an error here, and the export asks for it only of those. pub(crate) fn next_wide( &mut self, demuxer: &mut Demuxer, out: &mut Wide, ) -> Result, String> { match self { Self::Hevc(stream) => stream.next_wide(demuxer, out), Self::ProRes(stream) => stream.next_wide(demuxer, out), Self::Dnxhd(stream) => stream.next_wide(demuxer, out), Self::Mjpeg(stream) => stream.next_wide(demuxer, out), Self::Raw(stream) => stream.next_wide(demuxer, out), Self::Vp9(_) | Self::Vp8(_) | Self::Mpeg2(_) | Self::Dv(_) | Self::Mpeg4(_) => Err("no 10-bit seat for this codec".into()), } } /// The next picture in display order, narrowed into `out`, with its display /// index. `None` at end of stream; `Err` names a refusal. pub(crate) fn next( &mut self, demuxer: &mut Demuxer, out: &mut I420, ) -> Result, String> { match self { Self::Hevc(stream) => stream.next(demuxer, out), Self::Vp9(stream) => stream.next(demuxer, out), Self::Vp8(stream) => stream.next(demuxer, out), Self::Mpeg2(stream) => stream.next(demuxer, out), Self::ProRes(stream) => stream.next(demuxer, out), Self::Dnxhd(stream) => stream.next(demuxer, out), Self::Mjpeg(stream) => stream.next(demuxer, out), Self::Dv(stream) => stream.next(demuxer, out), Self::Mpeg4(stream) => stream.next(demuxer, out), Self::Raw(stream) => stream.next(demuxer, out), } } } /// 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, } /// `frame` as a PNG file at `path` (RGBA, colours swizzled from BGRA). pub fn to_png(frame: &Frame, path: &Path) -> crate::Result<()> { std::fs::write(path, to_png_bytes(frame)?)?; Ok(()) } /// `frame` as PNG-encoded bytes (RGBA, colours swizzled from BGRA). pub fn to_png_bytes(frame: &Frame) -> crate::Result> { let pixels = frame.width as usize * frame.height as usize; if frame.bgra.len() != pixels * 4 { return Err(format!( "frame is {}x{} but carries {} bytes", frame.width, frame.height, frame.bgra.len() ) .into()); } let mut rgba = Vec::with_capacity(pixels * 4); for px in frame.bgra.as_chunks::<4>().0 { rgba.extend_from_slice(&[px[2], px[1], px[0], px[3]]); } Ok(ec_image::png_encode::encode_rgba8(frame.width, frame.height, &rgba)?) } /// 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`, `ec-h265`, `ec-av1`, `ec-vp9` /// or `ec-vp8`, 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 and for a sound-only file, which have no /// coded stream (both answer [`Backend::Still`]). Every codec /// here has a software seat, so a plugin that will not take the file is not a /// refusal: the file plays in software, and the only `Err` is the container's. /// /// 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)> { // A still, and a sound-only file ([`crate::is_audio`]): neither has a picture // stream, so there is no coded stream to open and no container to read as a // movie. Asking the mp4 reader of a wav would refuse it with the mp4 reader's // words, which the media panel would show beside a file that plays. if crate::is_image(path) || crate::is_audio(path) { return Ok((None, Backend::Still)); } let path = path.to_path_buf(); let (meta, _demuxer) = Demuxer::open(&path)?; if hw_decodes(&path, 0, meta.codec).is_ok() { return Ok((Some(meta.codec), Backend::Hardware)); } 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, /// The clip's deinterlace setting ([`crate::project::Clip::deinterlace`]). With /// `Field` on an interlaced source the file's frame numbers in `start`, `end` /// and every [`Frame::index`] are **field** numbers, `2 * frame + 0 or 1`. deint: crate::project::Deinterlace, 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, dead_code, reason = "the playback session calls reseek_with once the lane's playback.rs hunk is in")] 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)> { self.reseek_with(path, start, end, color, transform, canvas, tone, speed, Default::default()) } /// [`reseek`](Self::reseek) for a clip with a deinterlace setting: `start` and /// `end` are field numbers when `deint` is `Field` and the file is interlaced. #[allow(clippy::too_many_arguments)] pub(crate) fn reseek_with( &mut self, path: &Path, start: u32, end: u32, color: ColorParams, transform: TransformParams, canvas: Composer, tone: tonemap::Preset, speed: Speed, deint: crate::project::Deinterlace, ) -> 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, deint, 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, /// Why this stream stopped early, if it did -- the answer a closed channel /// cannot give. Cloned into the worker, so it outlives the span that set it. pub(crate) failure: DecodeFailure, } /// Why a decode worker stopped **before** the end of its stream, if it did. /// /// The reason channel the sound path already has ([`crate::playback::Audio`]'s /// `died` flag, read back as `audio_disabled_reason`), for the picture side. It /// exists because a closed channel is not an answer: a worker that ran to the end /// of the file and a worker that gave up on a corrupt packet both drop the /// sender, and to a caller reading [`std::sync::mpsc::Receiver::try_recv`] /// those are one event. The app read that as `Transport::Ended`, so a file with /// a broken middle froze on its last good picture and said nothing -- identical /// to the film finishing, with no notice and no banner. /// /// The **first** reason wins: a span that fails and is then reseeked keeps the /// failure that stopped it until a span succeeds, which is what makes this a /// statement about the file rather than about the last attempt. A clean /// end-of-stream sets nothing at all -- silence is not a fault, and a notice /// that fires on every film would be a notice nobody reads. #[derive(Clone, Default)] pub struct DecodeFailure(Arc>>); impl DecodeFailure { /// The reason the last span failed, if one did. pub fn reason(&self) -> Option { self.0.lock().ok().and_then(|reason| reason.clone()) } /// Records a failure and says so on stderr, which is where these used to go /// and where they still belong: the stderr line is for whoever is reading a /// log, and this cell is for whoever is looking at a window. pub(crate) fn set(&self, reason: String) { eprintln!("{reason}"); let Ok(mut slot) = self.0.lock() else { return; // poisoned by a panic elsewhere: the stderr line still stands }; if slot.is_none() { *slot = Some(reason); } } /// Takes the reason back, for a caller that has read it: a fresh span that /// gets all the way through its range has answered the question. pub(crate) fn clear(&self) { if let Ok(mut slot) = self.0.lock() { slot.take(); } } } 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), failure: DecodeFailure::default(), }; } 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), failure: DecodeFailure::default(), } } /// A stream whose frames `body` produces on a thread of its own, sent down /// the same bounded channel, with the same cancel and the same retire path, /// as a decoder's. What a layered picture's composed frames come down. pub(crate) fn spawn_stream( name: &'static str, backend: Backend, body: impl FnOnce(&std::sync::mpsc::SyncSender, &AtomicBool) + Send + 'static, ) -> FrameStream { let (tx, rx) = sync_channel(2); let cancel = Arc::new(AtomicBool::new(false)); let worker_cancel = Arc::clone(&cancel); let handle = thread::Builder::new() .name(name.into()) .spawn(move || body(&tx, &worker_cancel)) .ok(); FrameStream { frames: rx, worker: Worker { cancel, handle, reuse: None, }, backend: BackendCell::new(backend), failure: DecodeFailure::default(), } } /// A worker that plays `count` frames of `path` **backwards**, from file frame /// `top` down: the picture of a reversed clip. Frame `d` of the stream is file /// frame `top - d`, numbered `top + d` -- the clip's *own* frame numbers, counted /// as if the file ran backwards from `top`, so everything downstream that stamps, /// skips and drops by a frame's number (and every span mapping in /// [`crate::project::Span`]) treats it as the forward stream it looks like. /// /// The frames are decoded by a forward worker a block at a time and served last /// to first ([`crate::reverse`]), which is what bounds the memory: one block of /// finished canvases, never the clip. The picture is graded and placed exactly as /// a forward span's is -- the same inner worker does it -- so a reversed frame is /// a forward frame, bit for bit, in another order. A block that ends early (a file /// shorter than the window) ends the stream there. #[allow(clippy::too_many_arguments)] #[allow(dead_code, reason = "the playback session calls open_reversed_with once the lane's playback.rs hunk is in")] pub(crate) fn open_reversed( path: &Path, top: u32, count: u32, color: ColorParams, transform: TransformParams, canvas: Composer, tone: tonemap::Preset, ) -> FrameStream { Self::open_reversed_with(path, top, count, color, transform, canvas, tone, Default::default()) } /// [`open_reversed`](Self::open_reversed) for a clip with a deinterlace /// setting. In field mode `top` and `count` are field numbers: the fields of /// an interlaced file play last to first, so each frame's second field comes /// before its first. #[allow(clippy::too_many_arguments)] pub(crate) fn open_reversed_with( path: &Path, top: u32, count: u32, color: ColorParams, transform: TransformParams, canvas: Composer, tone: tonemap::Preset, deint: crate::project::Deinterlace, ) -> FrameStream { let path = path.to_path_buf(); let deint = crate::deinterlace::effective(deint, &path); let (cw, ch) = canvas.dims(); // A pass-through canvas has no size of its own: plan for the biggest picture // the engine decodes so that the block stays inside its budget whatever it is. let (cw, ch) = if cw == 0 || ch == 0 { (3840, 2160) } else { (cw, ch) }; Self::spawn_stream("decode-reverse", Backend::Software, move |tx, cancel| { let lo = (top + 1).saturating_sub(count); let mut sync = crate::reverse::sync_frames(&path); if deint == crate::project::Deinterlace::Field { // Sync frames are frame numbers; a field-mode block starts at a // frame's first field. sync.iter_mut().for_each(|f| *f *= 2); } if deint == crate::project::Deinterlace::Ivtc { // ...and a film-frame block at the first film frame that starts at or // after the sync frame. sync.iter_mut().for_each(|f| *f = crate::deinterlace::counted_frames(deint, &path, *f)); } let cap = crate::reverse::block_cap(cw as usize * ch as usize * 4); let mut walk = crate::reverse::Walk::new(sync, lo, top + 1, cap); let mut inner: Option = None; let mut rx: Option> = None; while let Some((start, end)) = walk.next() { if cancel.load(Ordering::Relaxed) { return; } match inner.as_mut() { None => { let stream = span_worker( path.clone(), None, start, end, color, transform, canvas.fresh(), tone, Speed::NORMAL, deint, ); inner = Some(stream); } Some(stream) => { match stream.worker.reseek_with( &path, start, end, color, transform, canvas.fresh(), tone, Speed::NORMAL, deint, ) { Some((next, _)) => rx = Some(next), // The worker is gone (the file would not open, or it died): // nothing more to serve. None => return, } } } let stream = inner.as_ref().expect("opened above"); let frames = rx.as_ref().unwrap_or(&stream.frames); let mut block: Vec = Vec::with_capacity((end - start) as usize); loop { match frames.recv_timeout(std::time::Duration::from_millis(50)) { Ok(frame) => block.push(frame), Err(RecvTimeoutError::Timeout) => { if cancel.load(Ordering::Relaxed) { return; } } Err(RecvTimeoutError::Disconnected) => break, } } if block.is_empty() { return; // the inner worker found nothing: the file ended or failed } for mut frame in block.into_iter().rev() { if cancel.load(Ordering::Relaxed) { return; } frame.index = 2 * top - frame.index; if tx.send(frame).is_err() { return; // caller moved on } } } }) } /// 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 { // A numbered run opens on the frame the stream starts at; a file opens as it always did. let still = match crate::sequence::Run::parse(path) { Some(_) => Still::open_at(path, start_frame)?, None => Still::open(path)?, }; if still.seq.is_some() { return Self::open_run(still, start_frame, len, color, transform, canvas); } 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), // A still has no stream to fail in: `Still::open` raised // anything that was wrong with the file at the door, before a // worker existed. failure: DecodeFailure::default(), }); } // 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's own turn is already in these planes: `Still::open` made // it before the conversion above, exactly where the video door // makes a display matrix, so the render must not make it twice. 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), failure: DecodeFailure::default(), }) } /// A numbered run ([`crate::sequence`]) as a stream: one picture per frame of the clip, each /// frame of the run read on the worker when its turn comes, so a long run never sits decoded /// in memory. The same stream shape [`open_still`](Self::open_still) gives a single picture. fn open_run( mut still: Still, start_frame: u32, len: u32, color: ColorParams, transform: TransformParams, canvas: Composer, ) -> crate::Result { let (tx, rx) = sync_channel(2); let cancel = Arc::new(AtomicBool::new(false)); let mut render = Render::new( color, transform, // A frame's own turn is already in its planes, made by `Still::open_at`. Rotation::None, PixelAspect::SQUARE, ColorDescription::default(), canvas, tonemap::Preset::default(), None, ); let worker_cancel = Arc::clone(&cancel); let handle = thread::Builder::new() .name("still-run".into()) .spawn(move || { for index in 0..len { if worker_cancel.load(Ordering::Relaxed) { return; } // The first call hands out the frame the stream opened on; each later one reads the next. let (y, u, v, width, height) = still.picture(); 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::Still), failure: DecodeFailure::default(), }) } /// 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. #[allow( clippy::too_many_arguments, reason = "playback.rs calls this seat positionally; bundling its arguments is a change to that caller too" )] 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), // A painted picture has no decoder to fail: an unreadable audio // file is `VizEnvelope::Silent`, which is what silence looks like. failure: DecodeFailure::default(), }); } // 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), // ...and nothing in the paint loop can fail either, for the same // reason. failure: DecodeFailure::default(), }) } /// 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)> { Self::open_worker_with(path, start_frame, end_frame, color, transform, canvas, tone, Default::default()) } /// [`open_worker`](Self::open_worker) for a clip with a deinterlace setting: /// with `Field` over an interlaced file `start_frame` and `end_frame` are field /// numbers, and the range is capped at twice the file's frame count. #[allow(clippy::too_many_arguments)] pub(crate) fn open_worker_with( path: impl AsRef, start_frame: u32, end_frame: u32, color: ColorParams, transform: TransformParams, canvas: Composer, tone: tonemap::Preset, deint: crate::project::Deinterlace, ) -> crate::Result<(VideoMeta, FrameStream)> { let path = path.as_ref().to_path_buf(); // A still is not a stream: handing one to the mp4 demuxer answers "a // box with a larger size than it", which is a true sentence about a // container and nothing a person can act on -- and it made this door, // the one a front-end opens a file through, refuse every picture // outright. The still door answers with a meta of its own, so a poster // thumbnail and a preview window get the same picture the timeline // does, at the same size. No `tone` argument is passed on and none is // wanted: a still is decoded into BT.601 SDR planes, so there is no // map to build whichever rendition the project is watching. if crate::is_image(&path) { let still = Still::open(&path)?; let meta = VideoMeta { width: still.width, height: still.height, frame_rate: 1.0, frame_count: 1, codec: Codec::H264, color: ColorDescription::default(), matrix_assumed: false, // A still's own turn was made in `Still::open`, before these // planes were written, so there is nothing left to state here. rotation: Rotation::None, coded_width: still.width, coded_height: still.height, pixel_aspect: PixelAspect::SQUARE, }; return Self::open_still(&path, start_frame, 1, color, transform, canvas) .map(|stream| (meta, stream)); } let (meta, mut demuxer) = Demuxer::open(&path)?; // Before any decoder is chosen: a stream whose parameter sets the parser // refuses is refused here, for hardware and software alike, because the // driver would otherwise open it and hand back no picture. if meta.codec == Codec::Hevc && !demuxer.hevc_parameter_sets_parse() { return Err(Codec::Hevc.undecodable().into()); } let deint = effective_deint(deint, &meta, &demuxer); let end_frame = end_frame.min(crate::deinterlace::counted_frames(deint, &path, 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(), failure: DecodeFailure::default(), }, )); } Ok(( meta, span_worker( path, Some((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, deint, ), )) } /// 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)] #[allow(dead_code, reason = "the playback session calls open_worker_deferred_with once the lane's playback.rs hunk is in")] 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 { Self::open_worker_deferred_with(path, start_frame, end_frame, color, transform, canvas, tone, speed, Default::default()) } /// [`open_worker_deferred`](Self::open_worker_deferred) for a clip with a /// deinterlace setting (see [`open_worker_with`](Self::open_worker_with)). #[allow(clippy::too_many_arguments)] pub(crate) fn open_worker_deferred_with( path: impl AsRef, start_frame: u32, end_frame: u32, color: ColorParams, transform: TransformParams, canvas: Composer, tone: tonemap::Preset, speed: Speed, deint: crate::project::Deinterlace, ) -> FrameStream { span_worker( path.as_ref().to_path_buf(), None, start_frame, end_frame, color, transform, canvas, tone, speed, deint, ) } } /// 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 demuxer when the caller already read the file (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. /// The [`Source`] itself is built on the worker, so the hardware session it may /// hold never crosses a thread boundary. #[allow(clippy::too_many_arguments)] fn span_worker( path: PathBuf, opened: Option<(Demuxer, VideoMeta)>, start_frame: u32, end_frame: u32, color: ColorParams, transform: TransformParams, canvas: Composer, tone: tonemap::Preset, speed: Speed, deint: crate::project::Deinterlace, ) -> 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((_, meta)), true) => crate::scale::queue_depth(meta.width, 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(); // One cell for the whole worker, not one per span: the thread outlives its // spans (that is what a reseek costs nothing for), so the reason a span // failed has to outlive the span too, and be visible to whoever opened this // stream. let failure = DecodeFailure::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, deint, tx, }; let worker_cancel = Arc::clone(&cancel); let worker_backend = backend.clone(); let worker_failure = failure.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.map(|(demuxer, meta)| Source::demuxed(demuxer, meta)); 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, &worker_failure, ); } // 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() && std::env::var_os("EDITH_DEBUG").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, failure, } } /// 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) { if std::env::var_os("EDITH_DEBUG").is_some() { 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(|_| { if std::env::var_os("EDITH_DEBUG").is_some() { 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, worker_failure: &DecodeFailure, ) { let SpanCmd { start, end, color, transform, canvas, tone, speed, deint, tx, .. } = cmd; // Where the software seat starts: `start`, unless hardware dies mid-span and // hands the rest over from the picture it failed on. let mut start = start; // A span is a fresh question, so it starts from a clean answer: the // failure that stopped the span before this one was already reported, and // carrying it would keep saying a fault that this range may not have. Only // a span that is actually going to run clears it -- a span superseded on its // way through the queue decoded nothing and has nothing to say. worker_failure.clear(); let opened = match source { Some(opened) => opened, None => { let Some(fresh) = Source::open(path) else { backend.set(Backend::Gap); worker_failure.set(format!( "{}: could not be opened for decoding", path.display() )); 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 deint = effective_deint(deint, &opened.meta, &opened.demuxer); let end = match opened.demuxer.path() { Some(path) => end.min(crate::deinterlace::counted_frames(deint, path, opened.meta.frame_count)), None => end.min(opened.meta.frame_count * deint_units(deint)), }; // 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 ended = run_hw( opened.hw.as_mut().expect("positioned above"), Pass { tx: &tx, start_frame: start, end_frame: end, render: &mut render, abort, speed, failure: worker_failure, deint, }, ); // 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 ended == HwEnd::Refused && 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() { ended = run_hw( hw, Pass { tx: &tx, start_frame: start, end_frame: end, render: &mut render, abort, speed, failure: worker_failure, deint, }, ); } } match ended { HwEnd::Done => return, // A driver that opens but cannot decode a single frame is still a // fallback case, not a dead session. HwEnd::Refused => { opened.hw = None; if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("hardware decode failed before any frame, falling back to software"); } } // The GPU failed part-way (a hung ring, a reset context): the // pictures before `index` are out, and the software seat is put at // `index` below, so the span carries on as a software decode would // have. The session is dropped -- its context is gone. HwEnd::FellBackAt(index) => { opened.hw = None; start = index; } } } // ...and every codec has one to fall back to: H.264, HEVC, AV1, VP9 and VP8 // each have one of this project's own here (`ec-h264`, `ec-h265`, `ec-av1`, // `ec-vp9`, `ec-vp8`), so no stream reaches a seat it cannot decode. match opened.meta.codec { Codec::H264 => { if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("decode backend: software (ec-h264)"); } backend.set(Backend::Software); run( &mut opened.demuxer, Pass { tx: &tx, start_frame: start, end_frame: end, render: &mut render, abort, speed, failure: worker_failure, deint, }, ); } Codec::Av1 => { if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("decode backend: software (ec-av1)"); } backend.set(Backend::Software); run_av1( &mut opened.demuxer, Pass { tx: &tx, start_frame: start, end_frame: end, render: &mut render, abort, speed, failure: worker_failure, deint, }, ); } Codec::Vp9 => { eprintln!("decode backend: software (ec-vp9)"); backend.set(Backend::Software); run_vp9( &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure, ); } Codec::Vp8 => { eprintln!("decode backend: software (ec-vp8)"); backend.set(Backend::Software); run_vp8( &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure, ); } Codec::ProRes => { eprintln!("decode backend: software (ec-prores)"); backend.set(Backend::Software); intra::run::( &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure, ); } Codec::Dnxhd => { eprintln!("decode backend: software (ec-dnxhd)"); backend.set(Backend::Software); intra::run::( &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure, ); } Codec::Mjpeg => { eprintln!("decode backend: software (ec-mjpeg)"); backend.set(Backend::Software); intra::run::( &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure, ); } Codec::Dv => { eprintln!("decode backend: software (ec-dv)"); backend.set(Backend::Software); intra::run::( &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure, ); } Codec::Raw => { eprintln!("decode backend: software (raw video)"); backend.set(Backend::Software); intra::run::( &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure, ); } Codec::Mpeg4 | Codec::MsMpeg4 => { eprintln!("decode backend: software (ec-mpeg4)"); backend.set(Backend::Software); run_mpeg4( &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure, ); } Codec::Mpeg2 => { eprintln!("decode backend: software (ec-mpeg2)"); backend.set(Backend::Software); run_mpeg2( &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure, deint, ); } Codec::Hevc => { eprintln!("decode backend: software (ec-h265)"); backend.set(Backend::Software); run_hevc( &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure, ); } } } /// 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. pub(crate) 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`]). #[allow( clippy::too_many_arguments, reason = "one argument per field, passed straight through at its three construction sites" )] 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()), } } pub(crate) 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, width as usize, self.tone.is_none() && self.desc.full_range); } 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, /// The picture as it is *shown*, which for a phone's portrait photo is not /// the picture as it was stored: the turn its EXIF block asks for was made /// in [`Still::open`] before these planes were written, exactly where the /// video doors make a display matrix, so the pair every reader takes is /// the displayed one ([`crate::demux::Rotation`]'s own contract). pub(crate) width: u32, pub(crate) height: u32, /// An animated generator ([`crate::generate`]) and the source frame its next picture is. /// `None` for a file and for a generator that is the same on every frame. anim: Option<(crate::generate::Gen, u32)>, /// A numbered run ([`crate::sequence`]): the frame the planes hold, read again for each /// picture that follows. `None` for a file and for a generator. seq: Option, } /// Where a [`Still`] read from a numbered run is: the run, and which of its frames the planes /// hold. `handed` is set once the planes have been handed out, so the next call moves on. #[derive(Debug, Clone)] pub(crate) struct SeqCursor { run: crate::sequence::Run, at: u32, handed: bool, } /// A still whose EXIF orientation is not a quarter turn: values 2, 4, 5 and 7 /// are mirrorings, and this engine has no flip anywhere in its pipeline -- not /// in [`crate::scale::rotate_i420_90s`], not in [`Render`], not in an export's /// `place_picture`. Refused **by name** at the door, for /// [`crate::demux::UnsupportedRotation`]'s reason: showing a mirrored photo the /// wrong way round is a wrong picture rather than a missing feature, and /// quietly treating a mirror as a turn is exactly the bug this door exists to /// stop. The `Display` is what a user is refused by. #[derive(Debug)] pub struct UnsupportedStillOrientation { /// The EXIF value the file states, which is what the sentence names: the /// eight legal values are 1 (upright) through 8, and the four mirrorings /// are the even-odd pairs. pub exif: u8, } impl std::fmt::Display for UnsupportedStillOrientation { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "this picture's EXIF orientation is {}, which is a mirror and not a turn; only \ upright, 90°, 180° and 270° can be straightened here", self.exif ) } } impl std::error::Error for UnsupportedStillOrientation {} impl UnsupportedStillOrientation { /// Whether `error` is one of these, however deep in a `Box` it is -- /// [`crate::demux::UnsupportedRotation::is_it`]'s twin. pub fn is_it(error: &crate::Error) -> bool { error.downcast_ref::().is_some() } } /// The quarter turns an EXIF orientation asks for, as the one /// [`Rotation`] every other door in this engine already uses -- no second /// shape mechanism for a still, so the same turn is made by the same code /// that makes a video's display matrix turn. /// /// EXIF 1, 6, 8 and 3 are the four quarter turns; **2, 4, 5 and 7 are /// mirrorings** and are refused ([`UnsupportedStillOrientation`]) rather than /// approximated by the nearest rotation. Any other value (0, or above 8) is /// not a legal orientation and reads as upright, as `ec_image` reports it. fn rotation_of_exif(orientation: u8) -> crate::Result { Ok(match orientation { 6 => Rotation::Cw90, 3 => Rotation::Cw180, 8 => Rotation::Cw270, // A mirror is refused by its own EXIF number, so the sentence names // what the file says rather than a guess at the nearest turn. 2 | 4 | 5 | 7 => { return Err(UnsupportedStillOrientation { exif: orientation }.into()); } _ => Rotation::None, }) } /// The header of the picture at `path`, read through the first /// [`ec_image::PROBE_LIMIT`] bytes and no further: no pixel is decoded, and /// the file is never read whole. Shared by [`image_orientation`] and /// [`image_size`] so a library row costs one bounded read. fn probe_header(path: &Path) -> crate::Result { // A numbered run's spelling is not a file: its size and turn are its first frame's. let path = crate::sequence::first_frame(path); let file = std::fs::File::open(&path)?; ec_image::probe_reader(file).map_err(|e| format!("{}: {e}", path.display()).into()) } /// What turn `path` asks for, read off its **header** alone -- what a library /// row says about a file it has not placed anywhere, and what /// [`image_size`] needs to report the size the picture is shown at. /// /// Header-only on purpose: the whole file is not decoded, exactly as /// [`image_size`] has always been. The probe reads the container's header /// and EXIF block and stops; the pixels are never touched. pub fn image_orientation(path: &Path) -> crate::Result { if crate::generate::is_generated(path) { return Ok(Rotation::None); } // The refusal is handed on **unchanged**, not folded into a sentence with // the file's name: a `String` is not an error a caller can downcast, and // `is_it` is how a front-end tells this refusal from any other failure. // The path is not lost -- every caller that has one puts it in front. rotation_of_exif(probe_header(path)?.orientation) } 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 { Self::open_at(path, 0) } /// [`Still::open`] for a span that starts at source frame `start`: only an animated /// generator ([`crate::generate::Gen::animated`]) cares, and then each [`Still::picture`] /// is the next frame of it. pub(crate) fn open_at(path: &Path, start: u32) -> crate::Result { if let Some(g) = crate::generate::Gen::parse(path) { let (y, u, v) = rgb_to_i420(&g.rgb(start), g.width as usize, g.height as usize); return Ok(Self { y, u, v, width: g.width, height: g.height, anim: g.animated().then_some((g, start)), seq: None }); } // A numbered run opens at its frame `start`, and each later picture is the frame after it. let run = crate::sequence::Run::parse(path); let file = match &run { Some(run) => run.frame(start), None => path.to_path_buf(), }; let path = file.as_path(); // The turn is read and made **here**, once, before a single pair of // numbers leaves this function: `image`'s decoder keeps an EXIF // orientation in its own field and applies nothing, so a portrait // phone photo arrived as landscape planes and every consumer below -- // the `Render`, the `VideoMeta`, `image_size` -- reported the shape the // camera stored rather than the one it was shot at. This is the same // step the video doors make, at the same place in the pipeline // (before the grade, the canvas and the conversion all see the // picture), and it uses the same [`Rotation`]. // The turn comes from the same probe `image_size` makes, so a library // row and a placed still agree on what a picture's turn is. let rotation = image_orientation(path)?; let decoded = ec_image::open(path).map_err(|e| format!("{}: {e}", path.display()))?; let (coded_width, coded_height) = decoded.dimensions(); // Turned here rather than left to each consumer, so there is exactly // one place the turn is made and no consumer can be forgotten: the // planes handed out below are the *shown* picture, so the `Render`, the // `VideoMeta`, an export's `place_picture` and `image_size` all agree // without any of them re-deriving it. A file that states no turn takes // the branch by a bool and not one byte is copied. let (width, height, rgb) = match rotation.is_none() { true => (coded_width, coded_height, decoded.to_rgb8()), false => turn_rgb( &decoded.to_rgb8(), coded_width, coded_height, rotation.steps(), ) .map_err(|e| format!("{}: {e}", path.display()))?, }; 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, anim: None, seq: run.map(|run| SeqCursor { run, at: start, handed: false }), }) } /// The planes as an export's decoder hands them over, so a still and a /// decoded picture are the same value to `export::run` -- and, for a /// turned still, the same value in the only sense that matters: the turn /// is already in them, so an export places what the preview showed without /// being told a second time. pub(crate) fn picture(&mut self) -> (&[u8], &[u8], &[u8], u32, u32) { // A numbered run hands out its frames in turn, each one read now: a frame that will // not decode keeps the picture before it, so a run deleted under a playing clip holds // its last good frame instead of tearing the timeline down. if let Some(cur) = &mut self.seq { if cur.handed { let next = (cur.at + 1).min(cur.run.count - 1); if next != cur.at && let Ok(still) = Still::open_at(&cur.run.frame(next), 0) { (self.y, self.u, self.v, self.width, self.height) = (still.y, still.u, still.v, still.width, still.height); cur.at = next; } } cur.handed = true; } // An animated generator hands out its frames in turn: the one drawn at open first. if let Some((g, next)) = &mut self.anim { if *next > 0 || self.y.is_empty() { (self.y, self.u, self.v) = rgb_to_i420(&g.rgb(*next), self.width as usize, self.height as usize); } *next += 1; } (&self.y, &self.u, &self.v, self.width, self.height) } } /// `steps` quarter turns clockwise over a packed RGB8 picture of `width` by /// `height` -- the same direction and the same count /// [`crate::scale::rotate_i420_90s`] takes, on the still's own buffer rather /// than on its planes: a still is turned exactly once in its whole life, so /// there is no steady-state cost to make the allocating call the one that /// happens. Returns the turned picture's `(width, height, pixels)`. fn turn_rgb( rgb: &[u8], width: u32, height: u32, steps: u8, ) -> Result<(u32, u32, Vec), ec_core::Error> { use ec_image::transform::{Layout, rotate90, rotate180, rotate270}; let layout = Layout::Rgb8; Ok(match steps % 4 { 1 => (height, width, rotate90(layout, width, height, rgb)?), 2 => (width, height, rotate180(layout, width, height, rgb)?), 3 => (height, width, rotate270(layout, width, height, rgb)?), _ => (width, height, rgb.to_vec()), }) } /// How big the picture in `path` is as it is **shown**, from its header alone -- /// what a library row says about a file it has not placed anywhere. The whole /// file is not decoded. /// /// The turn is applied to the answer for the same reason /// [`DecodeSession::open_still`]'s is: a portrait phone photo stores landscape /// and says so in its EXIF block, and a row that answered 4000x3000 for a /// picture that is shown 3000x4000 states the wrong shape on the one surface /// that exists before anything places the file. Header-only still -- /// `into_decoder` parses the container and stops. pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> { if let Some(g) = crate::generate::Gen::parse(path) { return Ok((g.width, g.height)); } let header = probe_header(path)?; let rotation = rotation_of_exif(header.orientation)?; let (width, height) = (header.width, header.height); Ok(match rotation.swaps_axes() { true => (height, width), false => (width, height), }) } /// 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; #[allow( clippy::too_many_arguments, reason = "the plane triple and its dimensions are threaded positionally through every painter's stamp calls; a planes struct would restructure all of them" )] 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; } } } #[allow( clippy::too_many_arguments, reason = "forwards the same plane triple and ink as viz_stamp, positionally" )] 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. pub(crate) fn open_hw(path: &Path, start_frame: u32) -> Option { if crate::envcfg::var_os("VE_SW").is_some_and(|v| v == "1") { return None; } // A VP9 stream the GPU cannot take goes straight to the ec-vp9 software seat. if vp9_off_gpu(path).is_some() || h264_software_only(path) { return None; } HwSession::open_at(path, start_frame) } /// Whether a VP9 stream of this profile and chroma is one the VA-API plugin cannot /// take: the GPU decodes profiles 0 and 2 only, which are 4:2:0. Profiles 1 and 3 /// are the 4:2:2 and 4:4:4 ones. Used by both the import probe and the decode /// open, through [`hw_decodes`] and [`open_hw`], so the two cannot disagree. fn vp9_needs_420_for_vaapi(profile: u8, chroma: Chroma) -> bool { matches!(profile, 1 | 3) && chroma != Chroma::C420 } /// The VP9 profile and chroma of `path` when it is a stream the GPU cannot take /// ([`vp9_needs_420_for_vaapi`]), `None` for every other file. Not a refusal: such /// a stream plays on the ec-vp9 software seat, which takes all four profiles. fn vp9_off_gpu(path: &Path) -> Option<(u8, Chroma)> { let (meta, demuxer) = Demuxer::open(path).ok()?; if meta.codec != Codec::Vp9 { return None; } let chroma = demuxer.chroma()?; // Profile 1 is 8-bit and profile 3 is 10-bit (12-bit is refused by the demuxer), // so the depth names the profile without the header keeping a second field. let profile = if demuxer.bit_depth() == 10 { 3 } else { 1 }; vp9_needs_420_for_vaapi(profile, chroma).then_some((profile, chroma)) } /// A [`Render`] as a span over `demuxer`'s file builds it, for tests that need /// the plain conversion of a picture a decoder handed over. #[cfg(test)] pub(crate) fn test_render(meta: VideoMeta, demuxer: &Demuxer) -> Render { Render::new( ColorParams::default(), TransformParams::default(), meta.rotation, meta.pixel_aspect, meta.color, Composer::passthrough(), tonemap::Preset::default(), demuxer.light().peak(), ) } /// The clip's deinterlace setting as it applies to this stream: `Frame` for /// anything that is not interlaced H.264, which ignores the setting. fn effective_deint( deint: crate::project::Deinterlace, meta: &VideoMeta, demuxer: &Demuxer, ) -> crate::project::Deinterlace { if matches!(deint, crate::project::Deinterlace::IvtcAuto | crate::project::Deinterlace::Ivtc) { // Resolved against the file: `Ivtc` when it has a cadence, else `Frame`. demuxer.path().map_or(crate::project::Deinterlace::Frame, |p| crate::deinterlace::effective(deint, p)) } else if meta.codec == Codec::H264 && demuxer.h264_interlaced() { deint } else { crate::project::Deinterlace::Frame } } /// Pictures per frame of the file: 2 in field mode, where the numbers are fields. fn deint_units(deint: crate::project::Deinterlace) -> u32 { if deint == crate::project::Deinterlace::Field { 2 } else { 1 } } /// Whether `path` is H.264 the GPU is never offered: above 8 bits (High 10, which /// VA-API has no profile for), 4:4:4 / monochrome / High 4:4:4 Predictive, or interlaced (PAFF and MBAFF, whose field order /// and picture order this engine reads off `ec-h264`'s own pictures and /// deinterlaces with their neighbours, see [`crate::deinterlace`]). Both play on /// the ec-h264 software seat. fn h264_software_only(path: &Path) -> bool { Demuxer::open(path) .is_ok_and(|(meta, d)| { meta.codec == Codec::H264 && (d.bit_depth() > 8 || d.h264_interlaced() // High 4:4:4 Predictive / CAVLC 4:4:4 Intra (also 4:2:0 lossless // under them), 4:4:4 and monochrome: no VA-API H.264 profile. || matches!(d.chroma(), Some(Chroma::C444 | Chroma::Gray)) || d.profile().is_some_and(|p| p.contains("4:4:4"))) }) } /// Why a VP9 stream [`vp9_off_gpu`] names is on the software seat: the profile, its /// chroma, and where it plays. Named so the probe's reason can be read off it. fn vp9_software_route(profile: u8, chroma: Chroma) -> String { let format = match chroma { Chroma::C422 => "4:2:2", Chroma::C444 => "4:4:4", Chroma::Gray => "grey", Chroma::C420 => "4:2:0", }; format!( "VP9 profile {profile} ({format}) is not 4:2:0, which the GPU does not take: it plays on the ec-vp9 software seat" ) } /// `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: &Path, start_frame: u32, codec: Codec) -> Result<(), String> { // The plugin's VA-API path takes Main, Main 10, Main Still and SCC (profile // 1, 2, 3, 9). A range-extensions stream (profile 4 and up: 4:2:2, 4:4:4, // 12-bit) reaches an `unimplemented!` in the vendored decoder, which panics. // Refused by name here instead, before the plugin is asked for anything. if codec == Codec::Hevc && let Ok((_, demuxer)) = Demuxer::open(path) && let Some(profile) = demuxer.hevc_profile().filter(|p| !matches!(p, 1 | 2 | 3 | 9)) { // Named by the chroma the stream states, in the words `demux` uses for // the same refusal at open, so probe and import say one thing. let what = match demuxer.chroma() { Some(Chroma::C422) => "HEVC 4:2:2".to_string(), Some(Chroma::C444) => "HEVC 4:4:4".to_string(), Some(Chroma::Gray) => "HEVC 4:0:0".to_string(), _ => format!("HEVC profile {profile}"), }; return Err(format!( "{what} (HEVC profile {profile}) is not offered to VA-API, which takes Main and Main 10 only: it plays on the ec-h265 software seat" )); } // VP9 profiles 1 and 3 are the 4:2:2 and 4:4:4 ones; the GPU takes 4:2:0 only, so // such a stream is not the plugin's: it is routed to the ec-vp9 software seat. if codec == Codec::Mpeg2 { return Err("MPEG-2 video has no VA-API path here: it plays on the ec-mpeg2 software seat".into()); } if matches!(codec, Codec::ProRes | Codec::Dnxhd | Codec::Mjpeg | Codec::Dv | Codec::Mpeg4 | Codec::MsMpeg4 | Codec::Raw) { return Err(format!("{} has no VA-API path: it plays on its own software seat", codec.name())); } if codec == Codec::Vp9 && let Some((profile, chroma)) = vp9_off_gpu(path) { return Err(vp9_software_route(profile, chroma)); } if codec == Codec::H264 && h264_software_only(path) { return Err("H.264 High 10, 4:4:4, monochrome and interlaced H.264 are not offered to VA-API: they play on the ec-h264 software seat, deinterlaced".into()); } let Some(mut hw) = open_hw(path, start_frame) else { return Err(format!("the VA-API plugin did not open this {} stream", codec.name())); }; // 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()), } } /// One software or hardware pass over a span: the frames `start_frame..end_frame` /// go to `tx`, drawn through `render`, and the pass ends early on `abort`. /// `speed` and `failure` are the session's own. struct Pass<'a> { tx: &'a SyncSender, start_frame: u32, end_frame: u32, render: &'a mut Render, abort: &'a Abort<'a>, speed: Speed, failure: &'a DecodeFailure, /// The clip's deinterlace setting, already narrowed to what applies to the /// stream (`Frame` for anything not interlaced). deint: crate::project::Deinterlace, } /// How a hardware pass over a span ended. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum HwEnd { /// The span was decoded to its end, or its consumer or abort stopped it. Done, /// Hardware gave nothing at all before the first picture, so software takes /// the whole span. Refused, /// Hardware failed after the first picture, at this display index: software /// takes the span from there. FellBackAt(u32), } /// Reports how the pass ended: [`HwEnd::Refused`] only when hardware decode /// failed without emitting a single frame, [`HwEnd::FellBackAt`] when it failed /// after some, so software can take over either way. /// /// 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, pass: Pass) -> HwEnd { let Pass { tx, start_frame, end_frame, render, abort, speed, failure: _, deint: _, } = pass; 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 HwEnd::Done; } 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 HwEnd::Done; // 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 HwEnd::Done; // consumer went away } } if index >= end_frame { return HwEnd::Done; // end of the requested range } } // End of stream before the first picture is the same signal as an // error there: the plugin opened and gave nothing, and software // takes the span. A mid-GOP start on AV1 does exactly this -- the // plugin's seek leaves the leading inter frames undecodable and the // stream then ends with no picture. Ok(None) if index == start_frame => return HwEnd::Refused, Ok(None) => return HwEnd::Done, Err(e) => { // Before the first picture this is not a failure to report but // the signal that software should take over, and it is reported // by the caller that does the falling back -- saying it here as // well would put a fault on the strip for a span that is about // to decode cleanly. if index == start_frame { return HwEnd::Refused; } // Mid-span: not a fault to report, because the software seat // takes the rest of the span from `index`. eprintln!("hardware decode error at frame {index}: {e}; continuing in software"); return HwEnd::FellBackAt(index); } } } } /// 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, deep: &mut Deep, ) -> bool { // A High 10 picture is narrowed to the 8-bit planes below first. deep.load(pic, false); if deep.on { let n = &deep.narrow; let frame = render.frame(due, &n.y, &n.u, &n.v, n.width, n.height); return tx.send(frame).is_err(); } // 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() } fn run(demuxer: &mut Demuxer, pass: Pass) { let Pass { tx, start_frame, end_frame, render, abort, speed, failure, deint: mode, } = pass; // 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. // // An interlaced stream is deinterlaced against the picture before and the // picture after each one ([`crate::deinterlace`]), so a seek lands one // picture earlier: the target's predecessor is decoded too, and the first // picture shown is filtered from the same neighbours a sequential decode // gave it. let interlaced = demuxer.h264_interlaced(); let mut deint = crate::deinterlace::Deinterlacer::with_mode( mode, interlaced, i64::from(start_frame), ec_core::frame::Interlace::Progressive, ) .cadenced(mode, demuxer); // In field mode `start_frame`, `end_frame` and every `due` below are field // numbers; the demuxer lands on the frame holding the first one. let mut index = demuxer.seek_to_sync_at_or_before(deint.landing(start_frame)); let mut pending = std::collections::VecDeque::new(); // 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; let mut deep = Deep::default(); // 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) { failure.set(format!("decode error at access unit {index}: {e}")); break; } } Ok(None) => { flushed = true; if let Err(e) = decoder.flush() { failure.set(format!("decode error at end of stream: {e}")); break; } } Err(e) => { failure.set(format!("demux error: {e}")); break; } } // Take everything the packet released; `NeedMore` is the signal to go // back for the next access unit. loop { let (due, pic) = match pending.pop_front() { Some(ready) => ready, None => match decoder.receive_frame() { Ok(ec_core::frame::Frame::Video(pic)) => { let tag = index; index += 1; // A disabled stage hands the picture straight back; an // interlaced stream's comes one picture late (two, // fields, in field mode), and nothing while it primes // or for a picture below the target. pending.extend(deint.push_all(tag, pic)); continue; } Ok(_) => continue, Err(e) if e.is_need_more() || e.is_eof() => { // The end of the stream releases the picture the stage // was holding for a successor. if flushed { pending.extend(deint.finish_all()); } if pending.is_empty() { break; } continue; } Err(e) => { failure.set(format!("decode error at access unit {index}: {e}")); break; } }, }; if due < i64::from(start_frame) { continue; } let due = due as u32; if abort.late(due) { if skipped < LATE_RUN { skipped += 1; } else { skipped = 0; if send_picture(&pic, due, render, tx, &mut deep) { 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, &mut deep) { done = true; // consumer went away break; } } if due + 1 >= 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. pub(crate) 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 and a 12-bit one's by four, /// 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. /// /// `depth` is the stream's bits per luma sample. A 4:2:2 or 4:4:4 picture /// (profiles 1 and 2) has its chroma averaged down to 4:2:0 first, rounding to /// nearest, at the depth it was decoded in: a pair of rows for 4:2:2, a 2x2 box /// for 4:4:4 (the export's [`crate::export::chroma_420`], which the export seat /// has applied already when the planes arrive here at 4:2:0). pub(crate) fn narrow_av1( picture: &Av1Picture, depth: u8, y: &mut Vec, u: &mut Vec, v: &mut Vec, ) { let shift = depth.saturating_sub(8); let plane = |src: &[u16], dst: &mut Vec| { dst.clear(); dst.extend(src.iter().map(|&sample| (sample >> shift) as u8)); }; plane(&picture.y, y); let (w, h) = (picture.width, picture.height); let (ow, oh) = (w.div_ceil(2), h.div_ceil(2)); match crate::export::chroma_shape(picture.u.len(), w, h) { Some((cw, ch)) if (cw, ch) != (ow, oh) => { let down = |src: &[u16], dst: &mut Vec| { dst.clear(); dst.extend( crate::export::chroma_420(src, cw, ch, ow, oh) .into_iter() .map(|s| (s >> shift) as u8), ); }; down(&picture.u, u); down(&picture.v, v); } _ => { 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, depth: u8, render: &mut Render, tx: &SyncSender, (y, u, v): (&mut Vec, &mut Vec, &mut Vec), ) -> bool { narrow_av1(picture, depth, 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, pass: Pass) { let Pass { tx, start_frame, end_frame, render, abort, speed, failure, deint: _, } = pass; // 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) => { failure.set(format!("demux error: {e}")); return; } } } let depth = demuxer.bit_depth(); 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, depth, 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, depth, 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 && !done { failure.set(format!("software AV1 decode failed at frame {index}: {e}")); done = 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"); // One cold deferred open: how long the call took, the stream's first // frame, and when that arrived. let deferred = || { 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"); (returned, frame, start.elapsed()) }; // The call's cost is a wall-clock sample, and a thread spawn on a // machine under a parallel build can be descheduled for tens of ms -- // the fastest of a few tries is the cost the code itself has, as the // tonemap perf gate does. A real read-before-return costs every try. let (mut returned, frame, mut first_frame) = deferred(); for _ in 0..7 { if returned < Duration::from_millis(10) { break; } let (r, _, f) = deferred(); if r < returned { (returned, first_frame) = (r, f); } } // 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}" ); } } /// Serialises the pins: `VE_SW` is process-wide and this file's unit tests /// share one process, so two pinned tests must not see each other's pin /// cleared under them. static SW_PIN: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// The `VE_SW=1` pin, held for one test and put back as it was. struct SwPin { _lock: std::sync::MutexGuard<'static, ()>, was: Option, } impl SwPin { fn set() -> Self { let lock = SW_PIN .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()); let was = crate::envcfg::var_os("VE_SW"); crate::envcfg::set("VE_SW", "1"); Self { _lock: lock, was } } } impl Drop for SwPin { fn drop(&mut self) { match &self.was { Some(was) => crate::envcfg::set("VE_SW", was), None => crate::envcfg::unset("VE_SW"), } } } /// HEVC has a software seat of its own (`ec-h265`), so with the plugin off a /// span on it is on that seat: it reports `Software`, and decodes what it was /// asked for. Driven through [`run_span`] itself, the door the front-end's /// spans come through; `VE_SW=1` is what makes the plugin's absence /// box-independent; see [`SwPin`]. #[test] fn an_hevc_span_with_no_hardware_takes_the_software_seat() { let _pin = SwPin::set(); let path = asset("test_hevc.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); let failure = DecodeFailure::default(); 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, deint: Default::default(), tx, }, &abort, &cell, &failure, ); assert_eq!( cell.get(), Backend::Software, "an HEVC span with no hardware is on the software seat, not a gap" ); assert_eq!( rx.try_iter().count(), 2, "the software seat decodes the span's two pictures" ); assert!( failure.reason().is_none(), "and a span that decoded what it was asked for says nothing went wrong" ); } #[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 } /// An AV1 clip of `pix_fmt` from ffmpeg's libaom-av1, in the temp dir. fn gen_av1(name: &str, pix_fmt: &str) -> PathBuf { let path = std::env::temp_dir().join(format!("{name}-{}.mkv", std::process::id())); let out = std::process::Command::new("ffmpeg") .args(["-v", "error", "-y", "-f", "lavfi", "-i"]) .arg("testsrc2=size=128x96:rate=30:duration=1") .args(["-frames:v", "6", "-c:v", "libaom-av1", "-cpu-used", "8"]) .args(["-crf", "20", "-b:v", "0", "-pix_fmt", pix_fmt]) .arg(&path) .output() .expect("run ffmpeg"); assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); path } /// 4:2:2 at 8 bits, 4:4:4 at 10 and 4:2:0 at 12 open, decode every frame on /// the software seat's own narrowing, and land within 45 dB of ffmpeg's /// `-pix_fmt yuv420p` decode of the same file. #[test] fn non_420_and_12_bit_av1_decodes_within_45_db_of_ffmpeg() { let _pin = SwPin::set(); for (pix, depth) in [("yuv422p", 8u8), ("yuv444p10le", 10), ("yuv420p12le", 12), ("yuv444p12le", 12)] { let clip = gen_av1(&format!("av1chroma-{pix}"), pix); let (meta, mut demuxer) = Demuxer::open(&clip).unwrap_or_else(|e| panic!("{pix}: {e}")); assert_eq!(demuxer.bit_depth(), depth, "{pix}"); let mut stream = Vec::new(); while let Some(au) = demuxer.next_access_unit().unwrap() { stream.extend_from_slice(&au); } let mut got = Vec::new(); decode_stream_with(&stream, |picture, _, shown| { if shown { let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new()); narrow_av1(picture, depth, &mut y, &mut u, &mut v); for p in [&y, &u, &v] { got.extend_from_slice(p); } } Ok(()) }) .unwrap_or_else(|e| panic!("{pix}: {e}")); let want = std::process::Command::new("ffmpeg") .args(["-v", "error", "-i"]) .arg(&clip) .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-fps_mode", "passthrough", "-"]) .output() .expect("run ffmpeg") .stdout; let seat_frames = DecodeSession::open(&clip).map(|(_, rx)| rx.into_iter().count()); let _ = std::fs::remove_file(&clip); assert_eq!(got.len(), want.len(), "{pix}: picture count"); assert_eq!(got.len(), 128 * 96 * 3 / 2 * meta.frame_count as usize, "{pix}"); let squared: f64 = got .iter() .zip(&want) .map(|(&a, &b)| (f64::from(a) - f64::from(b)).powi(2)) .sum(); let db = 10.0 * (255.0f64 * 255.0 * got.len() as f64 / squared.max(1e-9)).log10(); eprintln!("AV1 {pix} -> 4:2:0 against ffmpeg yuv420p: {db:.2} dB"); assert!(db >= 45.0, "{pix} is {db:.2} dB from ffmpeg, want 45"); assert_eq!(seat_frames.unwrap(), meta.frame_count as usize, "{pix}: session frames"); } } /// A span whose file no seat can take -- nothing opens it 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. /// /// Every codec edith decodes now has a seat (VP8 included), so the gap is built /// from a file no seat takes: a 45-degree display matrix, which `Demuxer::open` refuses by name, /// so `Source::open` yields nothing and the span has no seat to report. /// Driven through [`run_span`] itself, the only door that reaches the arm. /// `VE_SW=1` keeps the test box-independent; see [`SwPin`]. #[test] fn a_span_with_no_seat_at_all_reports_the_gap() { let _pin = SwPin::set(); let path = asset("test_rotation45.mkv"); 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); let failure = DecodeFailure::default(); 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, deint: Default::default(), tx, }, &abort, &cell, &failure, ); assert_eq!( cell.get(), Backend::Gap, "a span no seat takes 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" ); assert!( failure.reason().is_some(), "and it says why: a span that decoded nothing is the one case where \ a closed channel is definitely not the end of the file" ); } /// The VA-API plugin takes 4:2:0 VP9 only: profiles 0 and 2 pass, and profiles 1 /// and 3 pass only where the chroma is 4:2:0 (which no such profile writes). #[test] fn vp9_non_420_profiles_are_off_the_gpu() { assert!(vp9_needs_420_for_vaapi(1, Chroma::C444)); assert!(vp9_needs_420_for_vaapi(1, Chroma::C422)); assert!(vp9_needs_420_for_vaapi(3, Chroma::C444)); assert!(vp9_needs_420_for_vaapi(3, Chroma::C422)); assert!(!vp9_needs_420_for_vaapi(0, Chroma::C420)); assert!(!vp9_needs_420_for_vaapi(2, Chroma::C420)); assert!(!vp9_needs_420_for_vaapi(1, Chroma::C420)); } /// The route names the profile and its chroma, and says where the stream plays: /// the ec-vp9 software seat, not a refusal. #[test] fn vp9_non_420_route_names_profile_chroma_and_the_seat() { let text = vp9_software_route(1, Chroma::C444); assert_eq!( text, "VP9 profile 1 (4:4:4) is not 4:2:0, which the GPU does not take: it plays on the ec-vp9 software seat" ); assert!(vp9_software_route(3, Chroma::C422).starts_with("VP9 profile 3 (4:2:2)")); } }