diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index a964d43..1eac006 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -475,8 +475,13 @@ impl Player { place: bool, ) -> String { match opened { - Ok((session, subs)) => { + Ok((mut session, subs)) => { self.fps = session.meta().frame_rate; + // This window *is* the real-time viewer: a picture already past + // the clock is one `pump` takes off the channel and throws away, + // so the worker stops paying for it instead + // ([`PlaybackSession::drop_late_pictures`]). + session.drop_late_pictures(true); // Read before the session moves: a file that plays silent says // so here or nowhere. let silent = audio_notice(&session); @@ -737,8 +742,10 @@ impl Player { return; } let text = match opened { - Ok(session) => { + Ok(mut session) => { self.fps = session.meta().frame_rate; + // As at the file door above: the window watches in real time. + session.drop_late_pictures(true); let silent = audio_notice(&session); // A project is named after itself but still exports beside its // media: that is the only place an export has ever landed. diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 52d26b0..33336ea 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -308,6 +308,49 @@ impl Session { Some(session) } + /// Repositions an **open** session, exactly as [`Session::open_at`] positions + /// a new one: the next [`Session::pump`] hands back sample `target_sample`. + /// + /// This is what a seek costs when the session is kept: a demuxer seek and a + /// decoder flush, and *not* the VA-API initialisation (~90 ms measured), the + /// render node probe, the container parse and the surface pool that opening + /// one again pays for. + /// + /// The flush is the whole of the decoder's reset: cros-codecs finishes what + /// is in flight and goes to `Reset`, from where it resumes on the next + /// parameter set or key frame -- and every sync sample this demuxer hands + /// out carries the parameter sets in front of it (`demux`'s `is_sync` + /// re-injection), which is exactly where a seek lands. The pictures the + /// flush makes ready are dropped with `ready`: they belong to where the + /// session *was*. + fn seek_to(&mut self, target_sample: u32) -> Result<(), String> { + self.decoder.get().flush().map_err(|e| e.to_string())?; + // Drain what the flush completed, dropping every handle: each one holds + // a pool buffer out of circulation, and none of them is ours to show. + while let Some(event) = self.decoder.get().next_event() { + if let DecoderEvent::FormatChanged = event { + let info = self + .decoder + .get() + .stream_info() + .ok_or("format changed without stream info")? + .clone(); + self.pool.resize(&info); + } + } + self.ready.clear(); + self.pending.clear(); + self.flushed = false; + // The same arithmetic `open_at` does, for the same reason. + let target_frame = target_sample.saturating_sub(1); + let first = self.demuxer.seek_to_sync_at_or_before(target_frame); + self.skip = (i64::from(target_frame) - first).max(0) as u32; + // ...and the same open-GOP window: a session positioned anywhere but the + // start may meet leading pictures that reference what it never decoded. + self.leading = if target_frame > 0 { 0 } else { LEADING_LIMIT }; + Ok(()) + } + /// Pumps the decoder until one picture is ready. `Ok(false)` is clean EOF. fn pump(&mut self) -> Result { let mut stalls = 0u32; @@ -599,6 +642,32 @@ pub unsafe extern "C" fn vh_next_frame(session: *mut c_void, out: *mut VhFrame) .unwrap_or(-1) } +/// Repositions an open session so the next [`vh_next_frame`] returns sample +/// `target_sample` (1-based, as [`vh_open_at`]). 0 on success, negative on +/// failure -- and a caller that gets one closes the session and opens another, +/// which is what it did for every seek before this symbol existed. +/// +/// # Safety +/// `session` must come from [`vh_open_at`] and still be open. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn vh_seek(session: *mut c_void, target_sample: u32) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + if session.is_null() { + return -1; + } + // SAFETY: caller-guaranteed live session. + let session = unsafe { &mut *(session as *mut Session) }; + match session.seek_to(target_sample) { + Ok(()) => 0, + Err(e) => { + eprintln!("engine_hw: seek failed: {e}"); + -2 + } + } + })) + .unwrap_or(-1) +} + /// Releases a session. Safe to call with null. /// /// # Safety diff --git a/crates/engine/src/decode.rs b/crates/engine/src/decode.rs index 31404e3..4edb4c7 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -3,8 +3,8 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, AtomicU8, Ordering}; -use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel}; use std::thread; use rusty_h264::Decoder; @@ -136,15 +136,171 @@ pub(crate) struct Worker { /// `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, + canvas: Composer, + tone: tonemap::Preset, + 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 + } } impl Worker { - /// Stops the worker at its 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. - pub(crate) fn cancel(&self) { + /// 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. + pub(crate) fn reseek( + &mut self, + path: &Path, + start: u32, + end: u32, + color: ColorParams, + canvas: Composer, + tone: tonemap::Preset, + ) -> 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, + canvas, + tone, + tx, + }) + .ok()?; + Some((rx, reuse.backend.clone())) } /// Whether the thread has already returned, i.e. dropping this would not @@ -158,8 +314,14 @@ impl Worker { /// 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) } } @@ -167,6 +329,8 @@ impl Worker { 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(); } @@ -258,6 +422,7 @@ impl DecodeSession { worker: Worker { cancel, handle: None, + reuse: None, }, backend: BackendCell::new(Backend::Gap), }; @@ -287,7 +452,11 @@ impl DecodeSession { .ok(); FrameStream { frames: rx, - worker: Worker { cancel, handle }, + worker: Worker { + cancel, + handle, + reuse: None, + }, backend: BackendCell::new(Backend::Gap), } } @@ -317,6 +486,7 @@ impl DecodeSession { worker: Worker { cancel, handle: None, + reuse: None, }, backend: BackendCell::new(Backend::Still), }); @@ -369,7 +539,11 @@ impl DecodeSession { .ok(); Ok(FrameStream { frames: rx, - worker: Worker { cancel, handle }, + worker: Worker { + cancel, + handle, + reuse: None, + }, backend: BackendCell::new(Backend::Still), }) } @@ -414,57 +588,34 @@ impl DecodeSession { hw_decodes(&path, start_frame, meta.codec)?; } let end_frame = end_frame.min(meta.frame_count); - // Small bound: a 720p BGRA frame is ~3.5 MB, so we must not let the - // decoder run ahead of the display without limit. - let (tx, rx) = sync_channel(2); - let cancel = Arc::new(AtomicBool::new(false)); - // Written by the worker below the moment it knows, so a caller reading - // it sees what opened rather than what was hoped for. - let backend = BackendCell::default(); if end_frame <= start_frame { - // Nothing to decode: dropping `tx` here closes the channel cleanly, + // 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, + cancel: Arc::new(AtomicBool::new(false)), handle: None, + reuse: None, }, - backend, + backend: BackendCell::default(), }, )); } - let worker_cancel = Arc::clone(&cancel); - let worker_backend = backend.clone(); - let handle = thread::Builder::new() - .name("decode".into()) - .spawn(move || { - decode_span( - &path, - demuxer, - meta, - start_frame, - end_frame, - color, - canvas, - tone, - tx, - &worker_cancel, - &worker_backend, - ) - })?; Ok(( meta, - FrameStream { - frames: rx, - worker: Worker { - cancel, - handle: Some(handle), - }, - backend, - }, + span_worker( + path, + Some(Source::demuxed(demuxer, meta)), + start_frame, + end_frame, + color, + canvas, + tone, + ), )) } @@ -488,120 +639,312 @@ impl DecodeSession { canvas: Composer, tone: tonemap::Preset, ) -> FrameStream { - let path = path.as_ref().to_path_buf(); - let (tx, rx) = sync_channel(2); - let cancel = Arc::new(AtomicBool::new(false)); - let backend = BackendCell::default(); - let worker_cancel = Arc::clone(&cancel); - let worker_backend = backend.clone(); - let handle = thread::Builder::new() - .name("decode".into()) - .spawn(move || { - // Cancelled before this thread was even scheduled: do not open - // the file at all. A scrub abandons workers by the dozen and - // this is where all but the last of them stop. - if worker_cancel.load(Ordering::Relaxed) { - return; - } - let (meta, demuxer) = match Demuxer::open(&path) { - Ok(opened) => opened, - Err(e) => { - eprintln!("video open failed: {e}"); - // Dropping `tx` disconnects the receiver, which is the - // session's "walk on to the next span". - worker_backend.set(Backend::Gap); - return; - } - }; - decode_span( - &path, - demuxer, - meta, - start_frame, - // The clamp the sync opener does with the metadata it read - // on the caller's thread; here the metadata arrives first. - end_frame.min(meta.frame_count), - color, - canvas, - tone, - tx, - &worker_cancel, - &worker_backend, - ) - }) - .ok(); - FrameStream { - frames: rx, - worker: Worker { cancel, handle }, - backend, - } + span_worker( + path.as_ref().to_path_buf(), + None, + start_frame, + end_frame, + color, + canvas, + tone, + ) } } -/// One worker thread's whole job, on that thread: pick the decoder, decode -/// `[start_frame, end_frame)`, send the pictures. Both openers end here -- the -/// sync one, which demuxed on the caller's thread, and the deferred one, which -/// demuxed on this one -- so there is exactly one description of what a decode -/// worker does, whoever opened the file. +/// Spawns a decode worker over `path` and gives it its first span. The thread +/// **outlives that span**: it parks on its command channel afterwards, so the +/// next seek onto the same file reaches it through [`Worker::reseek`] and costs +/// a demuxer seek and a decoder flush instead of a thread, a container parse and +/// a VA-API initialisation (98 ms measured worst case). +/// +/// `opened` is the file when the caller already read it (the sync opener, which +/// demuxes on the caller's thread to have metadata to return); `None` is the +/// deferred one, where the worker opens it and nothing here touches the disk. #[allow(clippy::too_many_arguments)] -fn decode_span( - path: &PathBuf, - demuxer: Demuxer, - meta: VideoMeta, +fn span_worker( + path: PathBuf, + opened: Option, start_frame: u32, end_frame: u32, color: ColorParams, canvas: Composer, tone: tonemap::Preset, - tx: SyncSender, - cancel: &AtomicBool, +) -> FrameStream { + // The depth is the size of the pictures this worker will *emit*, which for a + // pass-through canvas is the stream's own -- and the sync opener has already + // read that on the caller's thread. Asking the canvas alone is how the file + // door came up with 2: every session opens pass-through (a freshly opened + // file *is* the project resolution), so a whole file would play at the + // decode-ahead this engine had before there was one, until the first seek + // built a real canvas. + let depth = match (&opened, canvas.places_nothing()) { + (Some(source), true) => crate::scale::queue_depth(source.meta.width, source.meta.height), + _ => canvas.queue_depth(), + }; + let (tx, rx) = sync_channel(depth); + let cancel = Arc::new(AtomicBool::new(false)); + // Written by the worker the moment it knows, so a caller reading it sees + // what opened rather than what was hoped for -- and kept across the spans + // that follow, since they are decoded by that very decoder. + let backend = BackendCell::default(); + let generation = Arc::new(AtomicU64::new(0)); + // The playhead starts where the span does: nothing is behind it yet. + let floor = Arc::new(AtomicU32::new(start_frame)); + let (spans, commands) = std::sync::mpsc::channel(); + let first = SpanCmd { + generation: 0, + start: start_frame, + end: end_frame, + color, + canvas, + tone, + tx, + }; + let worker_cancel = Arc::clone(&cancel); + let worker_backend = backend.clone(); + let worker_generation = Arc::clone(&generation); + let worker_floor = Arc::clone(&floor); + let worker_path = path.clone(); + let handle = thread::Builder::new() + .name("decode".into()) + .spawn(move || { + let mut source = opened; + let mut cmd = first; + loop { + let abort = Abort { + cancel: &worker_cancel, + generation: &worker_generation, + mine: cmd.generation, + floor: &worker_floor, + }; + // Superseded (or cancelled) before this thread was even + // scheduled: do not open the file, and do not enter VA-API + // initialisation, which is the one stretch a cancel cannot + // interrupt. A scrub abandons spans by the dozen and this is + // where all but the last of them stop. + if !abort.hit() { + run_span(&worker_path, &mut source, cmd, &abort, &worker_backend); + } + // Parked between spans. A seek and a clip boundary arrive in + // milliseconds and find the decoder still open, which is the + // whole point of this thread -- but a session nobody comes back + // to (the timeline played out, the window was left alone) must + // not sit on the driver: it would hold a live libva thread into + // whatever exit path the process takes, which is the SIGSEGV in + // Mesa's `atexit` the retired pool exists to prevent, and + // holding it *while idle* would widen that from "quit during a + // decode" to "quit any time after opening a file". + // + // So the wait is in two halves: the fast one keeps everything, + // and past [`IDLE`] the hardware session is closed. The demuxer + // stays -- it is a file handle and an index, not driver state, + // and rebuilding it is what costs seconds on a big Matroska -- + // so the reseek after a long pause pays one VA-API init and + // nothing else. + match commands.recv_timeout(IDLE) { + Ok(next) => cmd = next, + Err(RecvTimeoutError::Timeout) => { + if let Some(source) = &mut source + && source.hw.take().is_some() + { + eprintln!("decode worker idle: hardware session closed"); + } + // The session dropped the command channel: this worker + // is retired (or was detached), so the file goes now. + match commands.recv() { + Ok(next) => cmd = next, + Err(_) => return, + } + } + Err(RecvTimeoutError::Disconnected) => return, + } + } + }) + .ok(); + FrameStream { + frames: rx, + worker: Worker { + cancel, + handle, + reuse: Some(Reuse { + path, + spans, + generation, + backend: backend.clone(), + floor, + }), + }, + backend, + } +} + +/// How long a parked worker keeps its hardware session before closing it. Long +/// enough that a seek, a scrub step and a clip boundary all find the decoder +/// where they left it; short enough that a session left alone is not holding +/// libva when the process exits. +const IDLE: std::time::Duration = std::time::Duration::from_secs(2); + +/// How many pictures in a row a worker may drop for being late before it hands +/// one over regardless. The policy needs a floor of its own: a machine that +/// cannot decode a file in real time is late on *every* picture, and dropping +/// every picture is a black screen rather than a stutter -- so the slowest seat +/// still gets one in nine, which is roughly what it could paint before (the +/// front-end restarted the decoder once every two seconds to the same effect, +/// and paid a VA-API init for each restart). +const LATE_RUN: u32 = 8; + +/// What a decode worker keeps **between** the spans it is asked for: the +/// container it read, what the stream says about itself, and the hardware +/// session -- the three things a seek used to throw away and buy again. +struct Source { + meta: VideoMeta, + /// What the film says its brightest picture is ([`Demuxer::light`]): the + /// tone map's assumed peak on the reference rendition, so a 1759 cd/m^2 + /// grade is converted at 1759 rather than at the 1000 a file that declared + /// nothing is assumed at. A property of the stream, read once with it. + peak: Option, + demuxer: Demuxer, + /// The plugin's session, opened on this thread (its VA-API state is not + /// `Send`-safe across a hand-off) and *kept*. `None` for software: forced by + /// `VE_SW`, refused by the plugin, or handed back by a session that opened + /// and then decoded nothing. + hw: Option, +} + +impl Source { + /// The file as the sync opener already read it. + fn demuxed(demuxer: Demuxer, meta: VideoMeta) -> Self { + Self { + meta, + peak: demuxer.light().peak(), + demuxer, + hw: None, + } + } + + /// ...and as the deferred opener reads it, on the worker. `None` is a file + /// that would not open: the caller drops the sender, and the disconnected + /// receiver is the session's "walk on to the next span". + fn open(path: &Path) -> Option { + match Demuxer::open(path) { + Ok((meta, demuxer)) => Some(Self::demuxed(demuxer, meta)), + Err(e) => { + eprintln!("video open failed: {e}"); + None + } + } + } + + /// Puts the hardware decoder at `start`, keeping the session open where the + /// plugin can reposition it. `None` when there is no hardware here at all; + /// otherwise whether the session was **reused** -- which is what lets the + /// caller tell a driver that cannot decode this stream from one that merely + /// did not follow a reseek. + fn position_hw(&mut self, path: &Path, start: u32) -> Option { + if let Some(hw) = &mut self.hw { + if hw.seek(start) { + eprintln!("decode backend: hardware (VA-API plugin, session kept, seek to {start})"); + return Some(true); + } + // A plugin too old to reposition, or a decoder that would not + // flush: closed and opened again, which is what every seek did. + self.hw = None; + } + self.hw = open_hw(path, start); + self.hw.as_ref().map(|_| { + eprintln!("decode backend: hardware (VA-API plugin)"); + false + }) + } +} + +/// One span on a worker's thread: position the decoder, decode +/// `[start, end)`, send the pictures. Every opener ends here -- the sync one, +/// which demuxed on the caller's thread, the deferred one, which demuxes on +/// this one, and every reseek after them -- so there is exactly one description +/// of what a decode worker does. +fn run_span( + path: &Path, + source: &mut Option, + cmd: SpanCmd, + abort: &Abort, backend: &BackendCell, ) { + let SpanCmd { + start, + end, + color, + canvas, + tone, + tx, + .. + } = cmd; + let opened = match source { + Some(opened) => opened, + None => { + let Some(fresh) = Source::open(path) else { + backend.set(Backend::Gap); + return; + }; + source.insert(fresh) + } + }; + // The clamp the sync opener does with the metadata it read on the caller's + // thread; here the metadata arrives first. + let end = end.min(opened.meta.frame_count); // An empty range decodes nothing and must send nothing: `run_hw` counts a // frame *out* before it compares, so without this a zero-length span would - // emit one picture. The sync opener never even spawns for this case. - if end_frame <= start_frame { + // emit one picture. + if end <= start { return; } - // Cancelled before this thread was even scheduled -- do not enter VA-API - // initialisation at all, because that is the one stretch a cancel cannot - // interrupt (~65-90 ms of driver setup that would then have to be torn - // down again). - if cancel.load(Ordering::Relaxed) { - return; - } - // The stream's own colour, and with it 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. Both are - // properties of the stream, so neither can change while one range decodes. - let mut render = Render::new(color, meta.color, canvas, tone, demuxer.light().peak()); - // The plugin has to be opened on the thread that uses it: its VA-API state - // is not `Send`-safe across a later hand-off. - if let Some(hw) = open_hw(path, start_frame) { - // Cancelled *during* init: close the session (dropping `hw` does it) - // and leave without decoding anything. - if cancel.load(Ordering::Relaxed) { + // 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, 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; } - eprintln!("decode backend: hardware (VA-API plugin)"); backend.set(Backend::Hardware); - if run_hw(hw, &tx, start_frame, end_frame, &mut render, cancel) { + let mut decoded = run_hw( + opened.hw.as_mut().expect("positioned above"), + &tx, + start, + end, + &mut render, + abort, + ); + // A *reused* session that produced nothing may simply be one this + // reseek left where the driver would not follow; a session opened fresh + // at the same frame is the honest second question, and only its silence + // is a software fallback. Without this a single unfollowed seek would + // collapse the rest of the file to software. + if !decoded && reused { + eprintln!("hardware decode produced nothing after a reseek; reopening at frame {start}"); + opened.hw = open_hw(path, start); + if let Some(hw) = opened.hw.as_mut() { + decoded = run_hw(hw, &tx, start, end, &mut render, abort); + } + } + if decoded { return; } // A driver that opens but cannot decode a single frame is still a // fallback case, not a dead session. + opened.hw = None; eprintln!("hardware decode failed before any frame, falling back to software"); } // ...except where there is nothing to fall back to. Feeding HEVC or VP9 // bytes to `rusty_h264` would be garbage, not a fallback. - if meta.codec != Codec::H264 { - eprintln!("{}", meta.codec.needs_plugin()); + if opened.meta.codec != Codec::H264 { + eprintln!("{}", opened.meta.codec.needs_plugin()); return; } eprintln!("decode backend: software (rusty_h264)"); backend.set(Backend::Software); - run(demuxer, tx, start_frame, end_frame, &mut render, cancel) + run(&mut opened.demuxer, &tx, start, end, &mut render, abort) } /// One clip's pictures on their way to the renderer: graded, placed on the @@ -856,7 +1199,7 @@ fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec, Vec, Ve /// `None` when the software path must be used: forced by `VE_SW=1`, or the /// plugin is absent/broken/unable to open this particular file. -fn open_hw(path: &PathBuf, start_frame: u32) -> Option { +fn open_hw(path: &Path, start_frame: u32) -> Option { if std::env::var_os("VE_SW").is_some_and(|v| v == "1") { return None; } @@ -893,24 +1236,33 @@ fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), Stri /// 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( - mut hw: HwSession, + hw: &mut HwSession, tx: &SyncSender, start_frame: u32, end_frame: u32, render: &mut Render, - cancel: &AtomicBool, + abort: &Abort, ) -> bool { let mut index = start_frame; + // Pictures dropped for being late since the last one handed over; see + // [`LATE_RUN`]. + let mut skipped = 0; loop { - if cancel.load(Ordering::Relaxed) { + if abort.hit() { return true; } match hw.next_frame() { Ok(Some((y, u, v, width, height))) => { - let frame = render.frame(index, y, u, v, width, height); + let due = index; index += 1; - if tx.send(frame).is_err() { - return true; // consumer went away + if abort.late(due) && skipped < LATE_RUN { + skipped += 1; + } else { + skipped = 0; + let frame = render.frame(due, y, u, v, width, height); + if tx.send(frame).is_err() { + return true; // consumer went away + } } if index >= end_frame { return true; // end of the requested range @@ -1022,6 +1374,59 @@ mod tests { ); } + /// 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(), + Composer::passthrough(), + tonemap::Preset::default(), + ); + 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" + ); + } + /// 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 @@ -1060,24 +1465,28 @@ mod tests { } fn run( - mut demuxer: Demuxer, - tx: SyncSender, + demuxer: &mut Demuxer, + tx: &SyncSender, start_frame: u32, end_frame: u32, render: &mut Render, - cancel: &AtomicBool, + abort: &Abort, ) { + // 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 = Decoder::new(); // Decoding has to restart at a sync sample, so pictures between it and // `start_frame` are decoded (the target frame references them) but never // converted or sent. Signed, because the landing sync sample can sit inside // what the file's edit list trims, i.e. *before* frame 0. let mut index = demuxer.seek_to_sync_at_or_before(start_frame); + let mut skipped = 0; // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames); // reordering streams need POC-sorted output before display. loop { - if cancel.load(Ordering::Relaxed) { + if abort.hit() { break; } let au = match demuxer.next_access_unit() { @@ -1100,17 +1509,23 @@ fn run( index += 1; continue; } - let frame = render.frame( - index as u32, - &yuv.y, - &yuv.u, - &yuv.v, - yuv.width as u32, - yuv.height as u32, - ); + let due = index as u32; index += 1; - if tx.send(frame).is_err() { - break; // consumer went away + if abort.late(due) && skipped < LATE_RUN { + skipped += 1; + } else { + skipped = 0; + let frame = render.frame( + due, + &yuv.y, + &yuv.u, + &yuv.v, + yuv.width as u32, + yuv.height as u32, + ); + if tx.send(frame).is_err() { + break; // consumer went away + } } if index >= i64::from(end_frame) { break; // end of the requested range diff --git a/crates/engine/src/hw.rs b/crates/engine/src/hw.rs index 79852bf..8a08941 100644 --- a/crates/engine/src/hw.rs +++ b/crates/engine/src/hw.rs @@ -95,6 +95,11 @@ struct Plugin { /// missing: a plugin built before it exports the four above and not this, /// which costs a front-end the listing and never a decode. caps: Option i32>, + /// Repositioning an open session, and optional for the reason `caps` is: a + /// plugin built before it decodes exactly as it did, and a caller that + /// cannot reposition closes the session and opens another -- which is what + /// every seek did before this symbol existed. + seek: Option i32>, // Never dropped (lives in a static), so the fn pointers above stay valid. _lib: Library, } @@ -131,6 +136,7 @@ fn load() -> Option { next_frame: *lib.get(b"vh_next_frame\0").ok()?, close: *lib.get(b"vh_close\0").ok()?, caps: lib.get(b"vh_caps\0").ok().map(|s| *s), + seek: lib.get(b"vh_seek\0").ok().map(|s| *s), _lib: lib, }) })() @@ -194,6 +200,27 @@ impl HwSession { Some(Self { plugin, handle }) } + /// Repositions this very session so the next [`HwSession::next_frame`] + /// returns display index `start_frame` -- the same landing + /// [`HwSession::open_at`] gives, without the VA-API initialisation (~90 ms), + /// the render node probe and the container parse that opening one again + /// costs. What lets a decode worker outlive the seeks its caller makes. + /// + /// `false` when the plugin cannot do it -- too old to export the symbol, or + /// a decoder that would not flush -- and the caller then opens a new session + /// exactly as it always did. The session is left untouched either way, so a + /// `false` is never a half-moved decoder. + pub fn seek(&mut self, start_frame: u32) -> bool { + let Some(seek) = self.plugin.seek else { + return false; + }; + // Sample ids are 1-based, frame indices 0-based -- as in `open_at`. + let target_sample = start_frame.saturating_add(1); + // SAFETY: `handle` came from `vh_open_at` and is still open; the plugin + // writes nothing through it and the call cannot unwind (it catches). + unsafe { seek(self.handle, target_sample) == 0 } + } + pub fn meta(&self) -> Option { let mut meta = VhMeta::default(); // SAFETY: `handle` came from `vh_open_at` and is still open. diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index f03a1cf..22fe559 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -374,6 +374,10 @@ pub struct PlaybackSession { /// of a restart is never counted as timeline time. See /// [`Audio::content_at`]. priming: bool, + /// Whether the decode worker may drop a picture whose moment has already + /// passed ([`Self::drop_late_pictures`]). Off unless a caller says it is + /// watching this in real time. + drop_late: bool, } /// What an edit dirtied -- which half of the pipeline has to be rebuilt for the @@ -488,6 +492,7 @@ impl PlaybackSession { eos: false, mix: None, priming: false, + drop_late: false, }) } @@ -600,6 +605,7 @@ impl PlaybackSession { eos: false, mix: None, priming: false, + drop_late: false, }) } @@ -676,6 +682,7 @@ impl PlaybackSession { eos: false, mix: None, priming: false, + drop_late: false, }) } @@ -969,6 +976,7 @@ impl PlaybackSession { eos: false, mix: None, priming: false, + drop_late: false, }; // The scaffolding above opened source 0 from its first frame and the // whole of its audio; this puts both onto the clip the playhead is @@ -1237,6 +1245,7 @@ impl PlaybackSession { /// big film, seconds off a cold cache). End of stream is /// [`PlaybackSession::is_eos`]. pub fn try_frame(&mut self) -> Option { + self.publish_playhead(); loop { match self.frames.try_recv() { Ok(mut frame) => { @@ -1292,6 +1301,32 @@ impl PlaybackSession { self.eos } + /// Tells the decode worker which frame of its *file* the clock has reached, + /// so the pictures it is holding that are already behind the playhead are + /// dropped where they are cheap to drop -- before the conversion and before + /// the queue -- instead of being converted, queued and thrown away by the + /// caller one repaint later. The whole of the late-frame policy: a decoder + /// that has fallen behind catches up by not painting what nobody can see, + /// rather than by being restarted every two seconds (`Player::pump`). + /// + /// The stamp is the exact inverse of the one [`try_frame`](Self::try_frame) + /// puts on a decoded frame: timeline frame -> the clip's own frames + /// ([`Span::speed`]) -> the file's ([`Rate`]). A gap and the emptied + /// timeline have no file to be inside of, and publish nothing. + fn publish_playhead(&self) { + if !self.drop_late { + return; + } + let Some(span) = self.span else { return }; + let Some((_, in_frame)) = span.from else { + return; + }; + let now = secs_to_frame(self.clock.now(), self.meta.frame_rate); + let offset = now.saturating_sub(span.start).min(span.len); + self.worker + .playhead(self.span_rate.source_at(in_frame + span.speed.source_at(offset))); + } + /// Installs `replacement` as the decode worker, parking the outgoing one in /// [`retired`](Self::retired) rather than joining it here, and reaping the /// parked ones that have already returned. @@ -1301,9 +1336,20 @@ impl PlaybackSession { /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's /// worker on this seek and the list stays a handful long. Nothing waits. fn retire(&mut self, replacement: Worker) { + // A *replacement*, which is now the narrow case: a seek onto the file + // the worker already has open steers it instead ([`Worker::reseek`]) + // and never comes here, so this count is the picture restarts that + // really cost a thread and a decoder open -- which is what makes it + // worth counting. self.restarts += 1; - self.retired - .push(std::mem::replace(&mut self.worker, replacement)); + let mut outgoing = std::mem::replace(&mut self.worker, replacement); + // Terminal, unlike the [`Worker::abandon`] a seek does: this worker is + // being replaced rather than steered, so its thread has to end -- and + // the cancel is what drops its command channel, without which a worker + // parked between spans would sit in `recv` forever, never reaped here + // and never joined in any bounded time at exit. + outgoing.cancel(); + self.retired.push(outgoing); self.retired.retain(|w| !w.is_finished()); } @@ -1357,9 +1403,11 @@ impl PlaybackSession { let Some(span) = self.project.composite_span_at(next) else { return false; }; - // We only get here on a disconnect, so the old worker has already - // returned; cancel anyway, so `retire` treats every path alike. - self.worker.cancel(); + // We only get here on a disconnect, so the old span is already done; + // abandon anyway, so `start_span` treats every path alike -- and the + // *worker* is kept, because the next clip is very often the same file + // (a split cuts one clip in two) and it already has it open. + self.worker.abandon(); self.start_span(Some(span)); true } @@ -1419,36 +1467,58 @@ impl PlaybackSession { start, from: Some((source, in_frame)), .. - }) => Ok(DecodeSession::open_worker_deferred( - &self.project.sources()[source].path, - // The file's own frames, which is the only place they exist: - // a clip counts the timeline's ([`Rate`]). - self.span_rate.source_at(in_frame), + }) => { + let path = &self.project.sources()[source].path; + // The file's own frames, which is the only place they exist: a + // clip counts the timeline's ([`Rate`]). + let start_frame = self.span_rate.source_at(in_frame); // Source frames, which a speed makes more (or fewer) than the // timeline frames the span covers -- and which a file shot at // another rate makes fewer (or more) again. One past the last // frame this span shows, not one past its length: at another // rate those are two different frames. - self.span_rate.source_at( + let end_frame = self.span_rate.source_at( in_frame + span.expect("matched above").source_len().saturating_sub(1), - ) + 1, - self.project + ) + 1; + let color = self + .project .composite_color_at(start) .copied() - .unwrap_or_default(), + .unwrap_or_default(); // ...and the canvas it is placed on: the project's resolution // and this clip's own fit policy, constant across the span for - // the reason the grade is. - Composer::new( - self.meta.width, - self.meta.height, - self.project.composite_fit_at(start), - ), + // the reason the grade is. Built where it is handed over rather + // than kept in a local, because a `Composer` owns the scratch + // buffers it places through -- the value is not copied about. + let fit = self.project.composite_fit_at(start); + let canvas = || Composer::new(self.meta.width, self.meta.height, fit); // ...and the rendition an HDR source among them is mapped to, - // the project's own and constant across the span for that reason - // too. - self.project.tone(), - )), + // the project's own and constant across the span for that + // reason too. + let tone = self.project.tone(); + // The worker already decoding this very file takes the new span + // itself: no thread, no container parse, no VA-API init -- the + // whole of what a seek used to cost. It answers `None` for any + // other file (and for a worker whose thread has ended), and the + // deferred opener below is then exactly the path it always was. + if let Some((frames, backend)) = + self.worker + .reseek(path, start_frame, end_frame, color, canvas(), tone) + { + self.frames = frames; + self.backend = backend; + self.span = span; + return; + } + Ok(DecodeSession::open_worker_deferred( + &self.project.sources()[source].path, + start_frame, + end_frame, + color, + canvas(), + tone, + )) + } // A gap: black for as long as it runs. An emptied timeline has no // span at all and gets one frame of it -- enough to put black on // screen, and it ends where the timeline does, at once. @@ -1467,8 +1537,9 @@ impl PlaybackSession { // [`decode_backend`](Self::decode_backend) describing a worker that // is no longer feeding anything). A dead receiver instead, which is // what carries the session on to the next span. The old worker stays - // parked in `self.worker` where the caller already cancelled it; the - // next span retires it. + // parked in `self.worker`, where the caller has already abandoned + // the span it was decoding ([`Worker::abandon`]) without ending the + // thread; the next span reseeks it or retires it. self.frames = std::sync::mpsc::channel().1; self.backend = BackendCell::new(Backend::Gap); self.span = span; @@ -2584,6 +2655,31 @@ impl PlaybackSession { Some((tap, audio.sample_rate)) } + /// Says that this session is being **watched in real time**, so a picture + /// whose moment has passed is worth nothing and the decode worker may drop + /// it where it is cheap to drop -- before the conversion (a full BGRA pass + /// over 8 MB at 1080p) and before the queue. + /// + /// Off by default, and that is the contract every *pull* consumer relies on: + /// an export, the file-level [`DecodeSession`] API and a test draining as + /// fast as it can all ask for a range of frames and must be given every one + /// of them, in order. Only a viewer has a moment for a picture to be past. + /// + /// A front-end that turns this on was dropping those very frames itself, one + /// repaint later (`Player::pump` takes everything due and shows the last): + /// what changes is where the work stops, and therefore how quickly a decoder + /// that fell behind catches up. + /// + /// It does not replace [`resync_picture`](Self::resync_picture): both + /// mechanisms are live and this one is the first line. It catches up without + /// restarting anything, which is why the front-end's resync -- a picture + /// restart, once per `RESYNC_GAP` -- now fires only where dropping was not + /// enough (a decoder so far behind that even one picture in nine + /// ([`crate::decode`]'s `LATE_RUN`) cannot close the gap). + pub fn drop_late_pictures(&mut self, on: bool) { + self.drop_late = on; + } + /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode /// workers are replaced rather than steered: a fresh channel cannot hold a /// stale frame, and it works just as well after EOF, where the old workers @@ -2629,12 +2725,15 @@ impl PlaybackSession { /// keeps playing out of the same stream, the clock keeps running, and a /// grade dragged during playback is therefore silent. fn start_picture(&mut self, target: u32) { - // Cancel first, drop second: the old worker may be parked in `send` on + // Abandon first, drop second: the old worker may be parked in `send` on // the bounded channel, where only the disconnect wakes it -- and it - // then finds the flag already set. It is then parked, not joined; see - // [`retire`](Self::retire), which is what keeps a scrub off the price - // of a VA-API init. - self.worker.cancel(); + // then finds the span already superseded. The *thread* is kept, and + // with it the open file and the open decoder, so a seek onto the same + // source costs a demuxer seek and a decoder flush rather than the + // VA-API init (98 ms) a new worker would pay; a worker that cannot take + // the new span is retired by [`retire`](Self::retire) instead, and + // nothing on this thread joins either way. + self.worker.abandon(); // The span runs from `target` to the end of whatever it landed in -- a // clip, or a gap, which starts a black-frame worker instead. `None` is // the emptied timeline, black too, and `start_span` says so. @@ -2847,6 +2946,12 @@ impl PlaybackSession { /// Moves the clock forward; the caller runs this once per rendered frame. /// Costs an atomic load, and once per session a mode switch. pub fn tick(&mut self) { + // Before every early return below: where the playhead stands is what the + // decode worker drops its stale pictures against, and a front-end that + // repaints without draining (a slow frame, a busy render thread) must + // still be moving it -- otherwise the queue fills with pictures whose + // moment passed while nobody was taking them. + self.publish_playhead(); let Some(audio) = &self.audio else { return; // wall time from the start, nothing to poll }; diff --git a/crates/engine/src/scale.rs b/crates/engine/src/scale.rs index 4423db3..09732db 100644 --- a/crates/engine/src/scale.rs +++ b/crates/engine/src/scale.rs @@ -345,6 +345,24 @@ pub fn compose_i420( /// lift the black frame around the picture. Callers therefore grade the source /// planes and place the result; the bars stay exactly [`black_i420`]. /// +/// How many `width` x `height` BGRA pictures a decode worker may keep ahead of +/// its consumer: ~96 MB of them, so the queue is a memory budget rather than a +/// frame count -- 16 at 720p (the ceiling), 12 at 1080p, 3 at 3840x2160, 2 at +/// 4096x2160 (the floor), all measured. A worker holds one more than this in its +/// hand, so a burst off a full queue is `queue_depth + 1`. +/// +/// The floor of 2 is the bound this engine ran on everywhere before there was +/// any decode-ahead; the ceiling keeps a small picture from queueing a second of +/// video the consumer would have to walk through after a seek. +pub(crate) fn queue_depth(width: u32, height: u32) -> usize { + const BUDGET: usize = 96 << 20; + let bytes = width as usize * height as usize * 4; + if bytes == 0 { + return 2; + } + (BUDGET / bytes).clamp(2, 16) +} + /// A canvas of the picture's own size is a pass-through: [`place`](Composer::place) /// hands the caller's own planes straight back, allocates nothing and touches no /// byte, which is what keeps a project at its media's resolution the byte-for-byte @@ -386,6 +404,27 @@ impl Composer { Self::new(0, 0, FitPolicy::Fit) } + /// Whether this canvas is the one that places nothing + /// ([`passthrough`](Self::passthrough)) -- asked without a picture in hand, + /// unlike [`is_passthrough`](Self::is_passthrough), because the caller that + /// needs it is sizing a queue before anything has been decoded. + pub(crate) fn places_nothing(&self) -> bool { + self.width == 0 || self.height == 0 + } + + /// How many decoded pictures a worker over this canvas may keep ahead of + /// its consumer: a budget in *bytes*, so a 4K project runs a shallower queue + /// than a 1080p one instead of the same number of far bigger frames. + /// + /// A **pass-through** canvas has no size of its own -- the pictures come out + /// at the source's -- so it cannot answer, and the caller that knows the + /// stream asks [`queue_depth`] with those dimensions instead. Answering 2 + /// here would be the pre-decode-ahead bound, which is exactly the bug this + /// pair exists to keep out of the file-open path. + pub(crate) fn queue_depth(&self) -> usize { + queue_depth(self.width, self.height) + } + /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this /// composer would hand it back untouched. What lets a caller keep a fused /// fast path (the graded conversion) for the common case. diff --git a/crates/engine/tests/playback.rs b/crates/engine/tests/playback.rs index 50ab242..e2a4691 100644 --- a/crates/engine/tests/playback.rs +++ b/crates/engine/tests/playback.rs @@ -47,6 +47,12 @@ fn pump(session: &mut PlaybackSession, last_index: &mut Option) { let target = session.now() * session.meta().frame_rate; while let Some(frame) = session.try_frame() { if let Some(previous) = *last_index { + // One at a time, in order. Every session here is a *pull* consumer + // -- `open` leaves `drop_late_pictures` off -- and such a caller is + // owed every frame of the range it asked for, which is the contract + // an export and the file-level API rest on. Only a session told it + // is being watched in real time may skip, and the two tests that + // turn that on take their frames through `next_index` instead. assert_eq!( frame.index, previous + 1, @@ -1637,3 +1643,171 @@ fn an_emptied_timeline_plays_black_saves_loads_and_undoes() { assert!((session.timeline_duration() - whole).abs() < 1e-9); assert_eq!(session.clip_spans().len(), 1); } + +/// The session half of the late-frame policy: a *watched* session still lands +/// exactly on the frame a seek asked for. The floor the worker drops against is +/// the playhead mapped back into the file own frames, and a floor even one +/// frame ahead of the landing would eat the very picture the seek exists to +/// show ([`PlaybackSession::drop_late_pictures`]). +#[test] +fn a_watched_session_still_lands_on_the_frame_a_seek_asked_for() { + let mut session = open(asset("test_baseline.mp4")); + session.drop_late_pictures(true); + let fps = session.meta().frame_rate; + session.seek(3.0); + assert_eq!( + next_index(&mut session, "seek(3.0) on a watched session"), + (3.0 * fps) as u32, + "the landing frame was dropped as late" + ); + // ...and again backwards: a floor left where the last span ended would drop + // every picture of a seek that went back. + session.seek(1.0); + assert_eq!( + next_index(&mut session, "seek(1.0) on a watched session"), + (1.0 * fps) as u32 + ); +} + +/// The pixels a *reused* decoder hands back are the pixels a fresh one does. +/// One session takes three seeks -- forwards, backwards, forwards again -- and +/// the worker survives all of them (`Worker::reseek`: the file stays open, the +/// hardware session is repositioned rather than reopened), so a decoder left +/// holding one span references while another span is asked for would show here +/// as a smear and nowhere else. The reference is the file-level API, which +/// opens a decoder of its own per frame. +#[test] +fn a_reseek_decodes_the_same_picture_a_fresh_decoder_does() { + let path = asset("test_baseline.mp4"); + let mut session = open(&path); + let fps = session.meta().frame_rate; + // Small targets on purpose: the fixture's only sync sample is frame 0, so + // every one of these decodes from the start of the file and a debug-build + // software decoder is what runs the suite. + for target in [20u32, 5, 35] { + session.seek(f64::from(target) / fps); + let frame = next_frame(&mut session, "a seek onto a worker already open"); + assert_eq!(frame.index, target, "the seek landed elsewhere"); + assert!( + frame.bgra == source_frame(&path, target), + "frame {target} off the reused decoder is not the picture a fresh one decodes" + ); + } +} + +/// What the drop policy must never do: thin a picture the decoder was keeping up +/// with. `pump`'s own contiguity assert covers every *pull* consumer above; +/// nothing there bounds what a **watched** session delivers, and a one-in-N +/// regression inside the worker would pass the whole suite otherwise. +/// +/// The fixture is the smallest one here (320x180) so the question can be asked +/// on a debug build at the file's own rate -- no retime, because a retimed +/// timeline legitimately shows only every n-th source frame and the sharp half +/// of this test is that the indices arrive one at a time. A box too slow even +/// for this says so and stops: thinning the picture there is the policy working +/// (`LATE_RUN`), not a regression. +#[test] +fn a_watched_session_keeps_every_picture_its_decoder_keeps_up_with() { + let path = asset("test_speed_sync.mp4"); + + // What this box decodes, flat out, with nothing dropped: frames per second. + let mut measure = open(&path); + let fps = measure.meta().frame_rate; + measure.play(); + let mut decoded = 0u32; + let taken = Instant::now(); + while taken.elapsed() < Duration::from_millis(500) && !measure.is_eos() { + measure.tick(); + while measure.try_frame().is_some() { + decoded += 1; + } + sleep(Duration::from_millis(2)); + } + let capable = f64::from(decoded) / taken.elapsed().as_secs_f64(); + drop(measure); + eprintln!("this box decodes the fixture at {capable:.1} fps, which plays at {fps:.1}"); + if capable < fps * 1.2 { + eprintln!("SKIP: too slow to ask the question at all"); + return; + } + + // Watched, playing at its own rate, drained like a front-end that keeps up: + // every picture is due when it arrives and none of them may be dropped. + let mut session = open(&path); + session.drop_late_pictures(true); + session.play(); + let mut delivered = 0u32; + let mut last: Option = None; + let watched = Instant::now(); + while watched.elapsed() < Duration::from_millis(500) && !session.is_eos() { + session.tick(); + while let Some(frame) = session.try_frame() { + delivered += 1; + if let Some(previous) = last { + assert_eq!( + frame.index, + previous + 1, + "a picture was dropped while the decoder was keeping up" + ); + } + last = Some(frame.index); + } + sleep(Duration::from_millis(2)); + } + // Frames the clock went over, which is what the timeline owed the screen. + let passed = session.now() * fps; + let density = f64::from(delivered) / passed.max(1.0); + eprintln!("watched: {delivered} delivered over {passed:.1} frames of clock"); + assert!( + density >= 0.9, + "the worker thinned a picture it was keeping up with: {delivered} of \ + {passed:.1} frames ({density:.2}), decoder measured at {capable:.1} fps" + ); +} + +/// The decode-ahead a **freshly opened** file gets. Every session opens its first +/// worker pass-through -- a file just opened *is* the project resolution -- and +/// asking a pass-through canvas how deep to queue answers 2, the bound this +/// engine had before there was any decode-ahead: the whole file would then play +/// at that depth until the first seek built a real canvas. The depth is taken +/// from the stream instead (`scale::queue_depth`), and this is where that is +/// visible from outside: a paused session left alone fills its queue, and the +/// burst that comes off it is the depth plus the picture in the worker's hand. +/// +/// 720p fixture: ~96 MB of BGRA is 16 pictures at that size (the ceiling), so +/// the burst is 17 and the regression it guards against is a burst of 3. +#[test] +fn a_freshly_opened_file_queues_more_than_two_pictures() { + let mut session = open(asset("test_baseline.mp4")); + // Paused throughout: no seek, no play, nothing that would build a canvas. + // The best of three attempts, because filling the queue is the decoder's own + // work and this box shares itself with whatever else is running. + let mut burst = 0; + for _ in 0..3 { + sleep(Duration::from_millis(1500)); + let mut n = 0; + while session.try_frame().is_some() { + n += 1; + } + burst = burst.max(n); + } + eprintln!("burst off a freshly opened file: {burst} pictures"); + assert!( + burst > 8, + "a freshly opened file queued {burst} pictures: the first worker is \ + still sizing its queue from a pass-through canvas" + ); + + // ...and the same worker still answers. Four and a half seconds parked is + // well past the idle mark at which it closes its hardware session + // (`decode`'s `IDLE`), so this is the seek that has to reopen one lazily -- + // the one path that would have gone quiet if closing it left the worker + // holding a decoder it could no longer use. + let fps = session.meta().frame_rate; + session.seek(2.0); + assert_eq!( + next_index(&mut session, "a seek after the worker went idle"), + (2.0 * fps) as u32, + "the worker did not come back from its idle park" + ); +}