diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index c40c901..0811365 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -467,8 +467,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); @@ -729,8 +734,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/src/decode.rs b/crates/engine/src/decode.rs index 71bdcd9..8632972 100644 --- a/crates/engine/src/decode.rs +++ b/crates/engine/src/decode.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::thread; @@ -159,6 +159,11 @@ struct Reuse { /// 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, @@ -178,16 +183,34 @@ struct SpanCmd { /// 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 { @@ -221,6 +244,17 @@ impl Worker { } } + /// 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 @@ -246,7 +280,11 @@ impl Worker { if reuse.path != path || self.is_finished() { return None; } - let (tx, rx) = sync_channel(QUEUE); + 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; @@ -613,11 +651,6 @@ impl DecodeSession { } } -/// How many decoded pictures a worker may run ahead of its consumer. Small on -/// purpose: a 1080p BGRA frame is ~8 MB, so the decoder must not run ahead of -/// the display without limit. -const QUEUE: usize = 2; - /// 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 @@ -637,13 +670,15 @@ fn span_worker( canvas: Composer, tone: tonemap::Preset, ) -> FrameStream { - let (tx, rx) = sync_channel(QUEUE); + let (tx, rx) = sync_channel(canvas.queue_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, @@ -657,6 +692,7 @@ fn span_worker( 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()) @@ -668,6 +704,7 @@ fn span_worker( 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 @@ -697,12 +734,22 @@ fn span_worker( spans, generation, backend: backend.clone(), + floor, }), }, backend, } } +/// 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. @@ -1154,16 +1201,25 @@ fn run_hw( 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 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 @@ -1275,6 +1331,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 @@ -1329,6 +1438,7 @@ fn run( // 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. @@ -1356,17 +1466,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/playback.rs b/crates/engine/src/playback.rs index 3193fc1..97a54bb 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -311,6 +311,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 @@ -423,6 +427,7 @@ impl PlaybackSession { eos: false, mix: None, priming: false, + drop_late: false, }) } @@ -533,6 +538,7 @@ impl PlaybackSession { eos: false, mix: None, priming: false, + drop_late: false, }) } @@ -607,6 +613,7 @@ impl PlaybackSession { eos: false, mix: None, priming: false, + drop_late: false, }) } @@ -898,6 +905,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 @@ -1166,6 +1174,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) => { @@ -1221,6 +1230,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. @@ -2473,6 +2508,25 @@ 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 -- without the restart-every-two-seconds that + /// was the only way back before ([`Self::resync_picture`]). + 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 @@ -2732,6 +2786,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..a7fad37 100644 --- a/crates/engine/src/scale.rs +++ b/crates/engine/src/scale.rs @@ -386,6 +386,24 @@ impl Composer { Self::new(0, 0, FitPolicy::Fit) } + /// 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. + /// + /// The floor is 2 -- the bound this engine ran on everywhere before there + /// was a decode-ahead at all -- and it is also what a pass-through canvas + /// gets, since that one does not know what size the pictures will be (they + /// are the source's) and its callers pull frame by frame anyway. + pub(crate) fn queue_depth(&self) -> usize { + /// ~96 MB of BGRA in flight: eleven 1080p pictures, two 4K ones. + const BUDGET: usize = 96 << 20; + let bytes = self.width as usize * self.height as usize * 4; + if bytes == 0 { + return 2; + } + (BUDGET / bytes).clamp(2, 16) + } + /// 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 30d680b..5c7dcf2 100644 --- a/crates/engine/tests/playback.rs +++ b/crates/engine/tests/playback.rs @@ -47,10 +47,16 @@ 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 { - assert_eq!( - frame.index, - previous + 1, - "frames must arrive in index order" + // Forwards, never twice and never backwards -- but not necessarily + // one at a time: a worker whose pictures have fallen behind the + // playhead drops them where they are cheap to drop rather than + // converting and queueing what nobody can be shown + // (`PlaybackSession::publish_playhead`), so a decoder that cannot + // keep real time skips instead of falling further behind. + assert!( + frame.index > previous, + "frames must arrive in index order: {} after {previous}", + frame.index ); } *last_index = Some(frame.index); @@ -1485,3 +1491,28 @@ 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 + ); +}