forge
Explore
Log in

Don't you dare go Hollow

The queue runs deeper and stops carrying pictures nobody can see

Browse files at this commit

fffcda0214ae2cef683bd86e14db87b5248f3403Ahmet Kaan GümüşParent: bbdd4d6
  • perf
    • the queue runs deeper and stops carrying pictures nobody can see
Show full message
⚡ perf(decode): the queue runs deeper and stops carrying pictures nobody can see

Two frames of decode-ahead was the whole buffer, so any hiccup emptied it
and the decoder could never build a lead. The bound is now a budget in
bytes (~96 MB: eleven 1080p pictures, two 4K ones), which is what makes
the second half safe: a deeper queue full of stale pictures would be
worse than a shallow one, so the worker is told where the playhead
stands and stops paying the conversion and the queue slot for anything
already behind it.

The policy has a floor of its own. A machine that cannot decode in real
time is late on every picture, and dropping every picture is a black
screen rather than a stutter, so one in nine is handed over regardless --
roughly what the front-end's restart-every-two-seconds produced, without
the VA-API init each restart cost.

Off unless a caller says it is watching in real time: an export, the
file-level API and a test draining as fast as it can each asked for a
range of frames and are owed every one of them. The window turns it on,
where `Player::pump` was already taking those pictures off the channel
and throwing them away one repaint later.

The playback suite's own pump asserted contiguous indices; it now asserts
increasing ones, which is the invariant that survives a drop -- nothing
out of order, nothing twice.
crates/app/src/player/library.rsmodified+9 -2
@@ -467,8 +467,13 @@ impl Player {
467 place: bool,467 place: bool,
468 ) -> String {468 ) -> String {
469 match opened {469 match opened {
470- Ok((session, subs)) => {470+ Ok((mut session, subs)) => {
471 self.fps = session.meta().frame_rate;471 self.fps = session.meta().frame_rate;
472+ // This window *is* the real-time viewer: a picture already past
473+ // the clock is one `pump` takes off the channel and throws away,
474+ // so the worker stops paying for it instead
475+ // ([`PlaybackSession::drop_late_pictures`]).
476+ session.drop_late_pictures(true);
472 // Read before the session moves: a file that plays silent says477 // Read before the session moves: a file that plays silent says
473 // so here or nowhere.478 // so here or nowhere.
474 let silent = audio_notice(&session);479 let silent = audio_notice(&session);
@@ -729,8 +734,10 @@ impl Player {
729 return;734 return;
730 }735 }
731 let text = match opened {736 let text = match opened {
732- Ok(session) => {737+ Ok(mut session) => {
733 self.fps = session.meta().frame_rate;738 self.fps = session.meta().frame_rate;
739+ // As at the file door above: the window watches in real time.
740+ session.drop_late_pictures(true);
734 let silent = audio_notice(&session);741 let silent = audio_notice(&session);
735 // A project is named after itself but still exports beside its742 // A project is named after itself but still exports beside its
736 // media: that is the only place an export has ever landed.743 // media: that is the only place an export has ever landed.
crates/engine/src/decode.rsmodified+137 -21
@@ -3,7 +3,7 @@
3 3
4 use std::path::{Path, PathBuf};4 use std::path::{Path, PathBuf};
5 use std::sync::Arc;5 use std::sync::Arc;
6-use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};6+use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
7 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};7 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
8 use std::thread;8 use std::thread;
9 9
@@ -159,6 +159,11 @@ struct Reuse {
159 /// decodes -- so a reseek onto a file already open says "hardware" from the159 /// decodes -- so a reseek onto a file already open says "hardware" from the
160 /// first repaint instead of going back through `opening`.160 /// first repaint instead of going back through `opening`.
161 backend: BackendCell,161 backend: BackendCell,
162+ /// Where the caller's playhead stands, in this file's own frames
163+ /// ([`Worker::playhead`]): the worker converts and sends nothing behind it.
164+ /// Rewritten to the target by every reseek, so it can never carry one span's
165+ /// position into the next.
166+ floor: Arc<AtomicU32>,
162 }167 }
163 168
164 /// One span asked of a persistent worker: the range in the file's own frames,169 /// One span asked of a persistent worker: the range in the file's own frames,
@@ -178,16 +183,34 @@ struct SpanCmd {
178 /// What stops a decode loop: the worker's terminal flag (the thread itself is183 /// What stops a decode loop: the worker's terminal flag (the thread itself is
179 /// going away) and the generation of the span it was handed (only *this* span is184 /// going away) and the generation of the span it was handed (only *this* span is
180 /// going away). One check, so every loop treats them alike.185 /// going away). One check, so every loop treats them alike.
186+///
187+/// ...and where the playhead has reached ([`Abort::late`]), which is the same
188+/// question one picture at a time: a frame due before it is a frame nobody can
189+/// be shown any more.
181 struct Abort<'a> {190 struct Abort<'a> {
182 cancel: &'a AtomicBool,191 cancel: &'a AtomicBool,
183 generation: &'a AtomicU64,192 generation: &'a AtomicU64,
184 mine: u64,193 mine: u64,
194+ floor: &'a AtomicU32,
185 }195 }
186 196
187 impl Abort<'_> {197 impl Abort<'_> {
188 fn hit(&self) -> bool {198 fn hit(&self) -> bool {
189 self.cancel.load(Ordering::Relaxed) || self.generation.load(Ordering::Acquire) != self.mine199 self.cancel.load(Ordering::Relaxed) || self.generation.load(Ordering::Acquire) != self.mine
190 }200 }
201+
202+ /// Whether the picture at source frame `index` is already past due: the
203+ /// caller's playhead has gone by it, so converting it (a full BGRA pass over
204+ /// 8 MB at 1080p) and queueing it would only push a picture nobody sees in
205+ /// front of the one they are waiting for.
206+ ///
207+ /// It is still *decoded* -- the pictures after it reference it -- and the
208+ /// floor only ever moves with the playhead the session publishes, so a
209+ /// paused session (and every seek, which republishes its own target) drops
210+ /// nothing at all.
211+ fn late(&self, index: u32) -> bool {
212+ self.floor.load(Ordering::Relaxed) > index
213+ }
191 }214 }
192 215
193 impl Worker {216 impl Worker {
@@ -221,6 +244,17 @@ impl Worker {
221 }244 }
222 }245 }
223 246
247+ /// Tells the worker where the caller's playhead stands, in the file's own
248+ /// frames: it converts and queues nothing behind that, because a picture
249+ /// whose moment has passed cannot be shown and would only delay the one that
250+ /// can (see [`Abort::late`]). A worker with no reuse door -- a still, a gap
251+ /// -- has nothing to tell, and this costs it nothing to say.
252+ pub(crate) fn playhead(&self, source_frame: u32) {
253+ if let Some(reuse) = &self.reuse {
254+ reuse.floor.store(source_frame, Ordering::Relaxed);
255+ }
256+ }
257+
224 /// Points this worker at another range of the file it already has open,258 /// Points this worker at another range of the file it already has open,
225 /// handing back the channel the new span's pictures arrive on and the cell259 /// handing back the channel the new span's pictures arrive on and the cell
226 /// that says what is decoding them. `None` when this worker cannot take the260 /// that says what is decoding them. `None` when this worker cannot take the
@@ -246,7 +280,11 @@ impl Worker {
246 if reuse.path != path || self.is_finished() {280 if reuse.path != path || self.is_finished() {
247 return None;281 return None;
248 }282 }
249- let (tx, rx) = sync_channel(QUEUE);283+ let (tx, rx) = sync_channel(canvas.queue_depth());
284+ // The new span's own playhead, before its first picture is decoded: a
285+ // floor left over from where the timeline *was* would drop every
286+ // picture of a seek that went backwards.
287+ reuse.floor.store(start, Ordering::Relaxed);
250 // Bumped before the command is queued, so the span running now stops at288 // Bumped before the command is queued, so the span running now stops at
251 // its next picture whatever order the two threads are scheduled in.289 // its next picture whatever order the two threads are scheduled in.
252 let generation = reuse.generation.fetch_add(1, Ordering::Release) + 1;290 let generation = reuse.generation.fetch_add(1, Ordering::Release) + 1;
@@ -613,11 +651,6 @@ impl DecodeSession {
613 }651 }
614 }652 }
615 653
616-/// How many decoded pictures a worker may run ahead of its consumer. Small on
617-/// purpose: a 1080p BGRA frame is ~8 MB, so the decoder must not run ahead of
618-/// the display without limit.
619-const QUEUE: usize = 2;
620-
621 /// Spawns a decode worker over `path` and gives it its first span. The thread654 /// Spawns a decode worker over `path` and gives it its first span. The thread
622 /// **outlives that span**: it parks on its command channel afterwards, so the655 /// **outlives that span**: it parks on its command channel afterwards, so the
623 /// next seek onto the same file reaches it through [`Worker::reseek`] and costs656 /// next seek onto the same file reaches it through [`Worker::reseek`] and costs
@@ -637,13 +670,15 @@ fn span_worker(
637 canvas: Composer,670 canvas: Composer,
638 tone: tonemap::Preset,671 tone: tonemap::Preset,
639 ) -> FrameStream {672 ) -> FrameStream {
640- let (tx, rx) = sync_channel(QUEUE);673+ let (tx, rx) = sync_channel(canvas.queue_depth());
641 let cancel = Arc::new(AtomicBool::new(false));674 let cancel = Arc::new(AtomicBool::new(false));
642 // Written by the worker the moment it knows, so a caller reading it sees675 // Written by the worker the moment it knows, so a caller reading it sees
643 // what opened rather than what was hoped for -- and kept across the spans676 // what opened rather than what was hoped for -- and kept across the spans
644 // that follow, since they are decoded by that very decoder.677 // that follow, since they are decoded by that very decoder.
645 let backend = BackendCell::default();678 let backend = BackendCell::default();
646 let generation = Arc::new(AtomicU64::new(0));679 let generation = Arc::new(AtomicU64::new(0));
680+ // The playhead starts where the span does: nothing is behind it yet.
681+ let floor = Arc::new(AtomicU32::new(start_frame));
647 let (spans, commands) = std::sync::mpsc::channel();682 let (spans, commands) = std::sync::mpsc::channel();
648 let first = SpanCmd {683 let first = SpanCmd {
649 generation: 0,684 generation: 0,
@@ -657,6 +692,7 @@ fn span_worker(
657 let worker_cancel = Arc::clone(&cancel);692 let worker_cancel = Arc::clone(&cancel);
658 let worker_backend = backend.clone();693 let worker_backend = backend.clone();
659 let worker_generation = Arc::clone(&generation);694 let worker_generation = Arc::clone(&generation);
695+ let worker_floor = Arc::clone(&floor);
660 let worker_path = path.clone();696 let worker_path = path.clone();
661 let handle = thread::Builder::new()697 let handle = thread::Builder::new()
662 .name("decode".into())698 .name("decode".into())
@@ -668,6 +704,7 @@ fn span_worker(
668 cancel: &worker_cancel,704 cancel: &worker_cancel,
669 generation: &worker_generation,705 generation: &worker_generation,
670 mine: cmd.generation,706 mine: cmd.generation,
707+ floor: &worker_floor,
671 };708 };
672 // Superseded (or cancelled) before this thread was even709 // Superseded (or cancelled) before this thread was even
673 // scheduled: do not open the file, and do not enter VA-API710 // scheduled: do not open the file, and do not enter VA-API
@@ -697,12 +734,22 @@ fn span_worker(
697 spans,734 spans,
698 generation,735 generation,
699 backend: backend.clone(),736 backend: backend.clone(),
737+ floor,
700 }),738 }),
701 },739 },
702 backend,740 backend,
703 }741 }
704 }742 }
705 743
744+/// How many pictures in a row a worker may drop for being late before it hands
745+/// one over regardless. The policy needs a floor of its own: a machine that
746+/// cannot decode a file in real time is late on *every* picture, and dropping
747+/// every picture is a black screen rather than a stutter -- so the slowest seat
748+/// still gets one in nine, which is roughly what it could paint before (the
749+/// front-end restarted the decoder once every two seconds to the same effect,
750+/// and paid a VA-API init for each restart).
751+const LATE_RUN: u32 = 8;
752+
706 /// What a decode worker keeps **between** the spans it is asked for: the753 /// What a decode worker keeps **between** the spans it is asked for: the
707 /// container it read, what the stream says about itself, and the hardware754 /// container it read, what the stream says about itself, and the hardware
708 /// session -- the three things a seek used to throw away and buy again.755 /// session -- the three things a seek used to throw away and buy again.
@@ -1154,16 +1201,25 @@ fn run_hw(
1154 abort: &Abort,1201 abort: &Abort,
1155 ) -> bool {1202 ) -> bool {
1156 let mut index = start_frame;1203 let mut index = start_frame;
1204+ // Pictures dropped for being late since the last one handed over; see
1205+ // [`LATE_RUN`].
1206+ let mut skipped = 0;
1157 loop {1207 loop {
1158 if abort.hit() {1208 if abort.hit() {
1159 return true;1209 return true;
1160 }1210 }
1161 match hw.next_frame() {1211 match hw.next_frame() {
1162 Ok(Some((y, u, v, width, height))) => {1212 Ok(Some((y, u, v, width, height))) => {
1163- let frame = render.frame(index, y, u, v, width, height);1213+ let due = index;
1164 index += 1;1214 index += 1;
1165- if tx.send(frame).is_err() {1215+ if abort.late(due) && skipped < LATE_RUN {
1166- return true; // consumer went away1216+ skipped += 1;
1217+ } else {
1218+ skipped = 0;
1219+ let frame = render.frame(due, y, u, v, width, height);
1220+ if tx.send(frame).is_err() {
1221+ return true; // consumer went away
1222+ }
1167 }1223 }
1168 if index >= end_frame {1224 if index >= end_frame {
1169 return true; // end of the requested range1225 return true; // end of the requested range
@@ -1275,6 +1331,59 @@ mod tests {
1275 );1331 );
1276 }1332 }
1277 1333
1334+ /// The late-picture policy, at the one place it is decided. A worker told
1335+ /// the playhead is already at frame 20 must not spend a conversion and a
1336+ /// queue slot on the twenty pictures behind it -- they can never be shown --
1337+ /// and it must not go silent either, which is what [`LATE_RUN`] bounds: a
1338+ /// machine that cannot decode in real time is late on every picture, and one
1339+ /// in nine still reaches the screen.
1340+ ///
1341+ /// Deterministic on purpose: the floor is set by hand rather than by a clock
1342+ /// that would have to outrun a debug-build decoder to prove anything.
1343+ #[test]
1344+ fn a_worker_skips_the_pictures_the_playhead_has_gone_past() {
1345+ let take = |floor: u32| {
1346+ let stream = DecodeSession::open_worker_deferred(
1347+ asset("test_baseline.mp4"),
1348+ 0,
1349+ u32::MAX,
1350+ ColorParams::default(),
1351+ Composer::passthrough(),
1352+ tonemap::Preset::default(),
1353+ );
1354+ stream.worker.playhead(floor);
1355+ let mut indices = Vec::new();
1356+ while indices.len() < 4 {
1357+ let frame = stream
1358+ .frames
1359+ .recv_timeout(Duration::from_secs(10))
1360+ .expect("a picture");
1361+ indices.push(frame.index);
1362+ }
1363+ indices
1364+ };
1365+
1366+ // Nobody has moved: every picture of the range is owed, in order.
1367+ assert_eq!(take(0), vec![0, 1, 2, 3]);
1368+
1369+ // The playhead is at 20, so the pictures before it are decoded (the ones
1370+ // after reference them) and dropped unconverted -- all but the one in
1371+ // nine [`LATE_RUN`] lets through, so the caller never goes blind.
1372+ let caught_up = take(20);
1373+ assert!(
1374+ caught_up[0] > 0 && caught_up.windows(2).any(|w| w[1] > w[0] + 1),
1375+ "nothing was skipped: {caught_up:?}"
1376+ );
1377+ assert!(
1378+ caught_up.iter().any(|&i| i >= 20),
1379+ "the playhead was never reached: {caught_up:?}"
1380+ );
1381+ assert!(
1382+ caught_up.len() >= 4,
1383+ "the worker went silent instead of dropping down to one in nine"
1384+ );
1385+ }
1386+
1278 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.1387 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
1279 /// The channel is bounded, so such a worker is parked in `send` within a1388 /// The channel is bounded, so such a worker is parked in `send` within a
1280 /// few frames, and the only thing that can wake it is its receiver going1389 /// few frames, and the only thing that can wake it is its receiver going
@@ -1329,6 +1438,7 @@ fn run(
1329 // converted or sent. Signed, because the landing sync sample can sit inside1438 // converted or sent. Signed, because the landing sync sample can sit inside
1330 // what the file's edit list trims, i.e. *before* frame 0.1439 // what the file's edit list trims, i.e. *before* frame 0.
1331 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);1440 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
1441+ let mut skipped = 0;
1332 1442
1333 // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames);1443 // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames);
1334 // reordering streams need POC-sorted output before display.1444 // reordering streams need POC-sorted output before display.
@@ -1356,17 +1466,23 @@ fn run(
1356 index += 1;1466 index += 1;
1357 continue;1467 continue;
1358 }1468 }
1359- let frame = render.frame(1469+ let due = index as u32;
1360- index as u32,
1361- &yuv.y,
1362- &yuv.u,
1363- &yuv.v,
1364- yuv.width as u32,
1365- yuv.height as u32,
1366- );
1367 index += 1;1470 index += 1;
1368- if tx.send(frame).is_err() {1471+ if abort.late(due) && skipped < LATE_RUN {
1369- break; // consumer went away1472+ skipped += 1;
1473+ } else {
1474+ skipped = 0;
1475+ let frame = render.frame(
1476+ due,
1477+ &yuv.y,
1478+ &yuv.u,
1479+ &yuv.v,
1480+ yuv.width as u32,
1481+ yuv.height as u32,
1482+ );
1483+ if tx.send(frame).is_err() {
1484+ break; // consumer went away
1485+ }
1370 }1486 }
1371 if index >= i64::from(end_frame) {1487 if index >= i64::from(end_frame) {
1372 break; // end of the requested range1488 break; // end of the requested range
crates/engine/src/playback.rsmodified+60 -0
@@ -311,6 +311,10 @@ pub struct PlaybackSession {
311 /// of a restart is never counted as timeline time. See311 /// of a restart is never counted as timeline time. See
312 /// [`Audio::content_at`].312 /// [`Audio::content_at`].
313 priming: bool,313 priming: bool,
314+ /// Whether the decode worker may drop a picture whose moment has already
315+ /// passed ([`Self::drop_late_pictures`]). Off unless a caller says it is
316+ /// watching this in real time.
317+ drop_late: bool,
314 }318 }
315 319
316 /// What an edit dirtied -- which half of the pipeline has to be rebuilt for the320 /// What an edit dirtied -- which half of the pipeline has to be rebuilt for the
@@ -423,6 +427,7 @@ impl PlaybackSession {
423 eos: false,427 eos: false,
424 mix: None,428 mix: None,
425 priming: false,429 priming: false,
430+ drop_late: false,
426 })431 })
427 }432 }
428 433
@@ -533,6 +538,7 @@ impl PlaybackSession {
533 eos: false,538 eos: false,
534 mix: None,539 mix: None,
535 priming: false,540 priming: false,
541+ drop_late: false,
536 })542 })
537 }543 }
538 544
@@ -607,6 +613,7 @@ impl PlaybackSession {
607 eos: false,613 eos: false,
608 mix: None,614 mix: None,
609 priming: false,615 priming: false,
616+ drop_late: false,
610 })617 })
611 }618 }
612 619
@@ -898,6 +905,7 @@ impl PlaybackSession {
898 eos: false,905 eos: false,
899 mix: None,906 mix: None,
900 priming: false,907 priming: false,
908+ drop_late: false,
901 };909 };
902 // The scaffolding above opened source 0 from its first frame and the910 // The scaffolding above opened source 0 from its first frame and the
903 // whole of its audio; this puts both onto the clip the playhead is911 // whole of its audio; this puts both onto the clip the playhead is
@@ -1166,6 +1174,7 @@ impl PlaybackSession {
1166 /// big film, seconds off a cold cache). End of stream is1174 /// big film, seconds off a cold cache). End of stream is
1167 /// [`PlaybackSession::is_eos`].1175 /// [`PlaybackSession::is_eos`].
1168 pub fn try_frame(&mut self) -> Option<Frame> {1176 pub fn try_frame(&mut self) -> Option<Frame> {
1177+ self.publish_playhead();
1169 loop {1178 loop {
1170 match self.frames.try_recv() {1179 match self.frames.try_recv() {
1171 Ok(mut frame) => {1180 Ok(mut frame) => {
@@ -1221,6 +1230,32 @@ impl PlaybackSession {
1221 self.eos1230 self.eos
1222 }1231 }
1223 1232
1233+ /// Tells the decode worker which frame of its *file* the clock has reached,
1234+ /// so the pictures it is holding that are already behind the playhead are
1235+ /// dropped where they are cheap to drop -- before the conversion and before
1236+ /// the queue -- instead of being converted, queued and thrown away by the
1237+ /// caller one repaint later. The whole of the late-frame policy: a decoder
1238+ /// that has fallen behind catches up by not painting what nobody can see,
1239+ /// rather than by being restarted every two seconds (`Player::pump`).
1240+ ///
1241+ /// The stamp is the exact inverse of the one [`try_frame`](Self::try_frame)
1242+ /// puts on a decoded frame: timeline frame -> the clip's own frames
1243+ /// ([`Span::speed`]) -> the file's ([`Rate`]). A gap and the emptied
1244+ /// timeline have no file to be inside of, and publish nothing.
1245+ fn publish_playhead(&self) {
1246+ if !self.drop_late {
1247+ return;
1248+ }
1249+ let Some(span) = self.span else { return };
1250+ let Some((_, in_frame)) = span.from else {
1251+ return;
1252+ };
1253+ let now = secs_to_frame(self.clock.now(), self.meta.frame_rate);
1254+ let offset = now.saturating_sub(span.start).min(span.len);
1255+ self.worker
1256+ .playhead(self.span_rate.source_at(in_frame + span.speed.source_at(offset)));
1257+ }
1258+
1224 /// Installs `replacement` as the decode worker, parking the outgoing one in1259 /// Installs `replacement` as the decode worker, parking the outgoing one in
1225 /// [`retired`](Self::retired) rather than joining it here, and reaping the1260 /// [`retired`](Self::retired) rather than joining it here, and reaping the
1226 /// parked ones that have already returned.1261 /// parked ones that have already returned.
@@ -2473,6 +2508,25 @@ impl PlaybackSession {
2473 Some((tap, audio.sample_rate))2508 Some((tap, audio.sample_rate))
2474 }2509 }
2475 2510
2511+ /// Says that this session is being **watched in real time**, so a picture
2512+ /// whose moment has passed is worth nothing and the decode worker may drop
2513+ /// it where it is cheap to drop -- before the conversion (a full BGRA pass
2514+ /// over 8 MB at 1080p) and before the queue.
2515+ ///
2516+ /// Off by default, and that is the contract every *pull* consumer relies on:
2517+ /// an export, the file-level [`DecodeSession`] API and a test draining as
2518+ /// fast as it can all ask for a range of frames and must be given every one
2519+ /// of them, in order. Only a viewer has a moment for a picture to be past.
2520+ ///
2521+ /// A front-end that turns this on was dropping those very frames itself, one
2522+ /// repaint later (`Player::pump` takes everything due and shows the last):
2523+ /// what changes is where the work stops, and therefore how quickly a decoder
2524+ /// that fell behind catches up -- without the restart-every-two-seconds that
2525+ /// was the only way back before ([`Self::resync_picture`]).
2526+ pub fn drop_late_pictures(&mut self, on: bool) {
2527+ self.drop_late = on;
2528+ }
2529+
2476 /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode2530 /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode
2477 /// workers are replaced rather than steered: a fresh channel cannot hold a2531 /// workers are replaced rather than steered: a fresh channel cannot hold a
2478 /// stale frame, and it works just as well after EOF, where the old workers2532 /// stale frame, and it works just as well after EOF, where the old workers
@@ -2732,6 +2786,12 @@ impl PlaybackSession {
2732 /// Moves the clock forward; the caller runs this once per rendered frame.2786 /// Moves the clock forward; the caller runs this once per rendered frame.
2733 /// Costs an atomic load, and once per session a mode switch.2787 /// Costs an atomic load, and once per session a mode switch.
2734 pub fn tick(&mut self) {2788 pub fn tick(&mut self) {
2789+ // Before every early return below: where the playhead stands is what the
2790+ // decode worker drops its stale pictures against, and a front-end that
2791+ // repaints without draining (a slow frame, a busy render thread) must
2792+ // still be moving it -- otherwise the queue fills with pictures whose
2793+ // moment passed while nobody was taking them.
2794+ self.publish_playhead();
2735 let Some(audio) = &self.audio else {2795 let Some(audio) = &self.audio else {
2736 return; // wall time from the start, nothing to poll2796 return; // wall time from the start, nothing to poll
2737 };2797 };
crates/engine/src/scale.rsmodified+18 -0
@@ -386,6 +386,24 @@ impl Composer {
386 Self::new(0, 0, FitPolicy::Fit)386 Self::new(0, 0, FitPolicy::Fit)
387 }387 }
388 388
389+ /// How many decoded pictures a worker over this canvas may keep ahead of
390+ /// its consumer: a budget in *bytes*, so a 4K project runs a shallower queue
391+ /// than a 1080p one instead of the same number of far bigger frames.
392+ ///
393+ /// The floor is 2 -- the bound this engine ran on everywhere before there
394+ /// was a decode-ahead at all -- and it is also what a pass-through canvas
395+ /// gets, since that one does not know what size the pictures will be (they
396+ /// are the source's) and its callers pull frame by frame anyway.
397+ pub(crate) fn queue_depth(&self) -> usize {
398+ /// ~96 MB of BGRA in flight: eleven 1080p pictures, two 4K ones.
399+ const BUDGET: usize = 96 << 20;
400+ let bytes = self.width as usize * self.height as usize * 4;
401+ if bytes == 0 {
402+ return 2;
403+ }
404+ (BUDGET / bytes).clamp(2, 16)
405+ }
406+
389 /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this407 /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this
390 /// composer would hand it back untouched. What lets a caller keep a fused408 /// composer would hand it back untouched. What lets a caller keep a fused
391 /// fast path (the graded conversion) for the common case.409 /// fast path (the graded conversion) for the common case.
crates/engine/tests/playback.rsmodified+35 -4
@@ -47,10 +47,16 @@ fn pump(session: &mut PlaybackSession, last_index: &mut Option<u32>) {
47 let target = session.now() * session.meta().frame_rate;47 let target = session.now() * session.meta().frame_rate;
48 while let Some(frame) = session.try_frame() {48 while let Some(frame) = session.try_frame() {
49 if let Some(previous) = *last_index {49 if let Some(previous) = *last_index {
50- assert_eq!(50+ // Forwards, never twice and never backwards -- but not necessarily
51- frame.index,51+ // one at a time: a worker whose pictures have fallen behind the
52- previous + 1,52+ // playhead drops them where they are cheap to drop rather than
53- "frames must arrive in index order"53+ // converting and queueing what nobody can be shown
54+ // (`PlaybackSession::publish_playhead`), so a decoder that cannot
55+ // keep real time skips instead of falling further behind.
56+ assert!(
57+ frame.index > previous,
58+ "frames must arrive in index order: {} after {previous}",
59+ frame.index
54 );60 );
55 }61 }
56 *last_index = Some(frame.index);62 *last_index = Some(frame.index);
@@ -1485,3 +1491,28 @@ fn an_emptied_timeline_plays_black_saves_loads_and_undoes() {
1485 assert!((session.timeline_duration() - whole).abs() < 1e-9);1491 assert!((session.timeline_duration() - whole).abs() < 1e-9);
1486 assert_eq!(session.clip_spans().len(), 1);1492 assert_eq!(session.clip_spans().len(), 1);
1487 }1493 }
1494+
1495+/// The session half of the late-frame policy: a *watched* session still lands
1496+/// exactly on the frame a seek asked for. The floor the worker drops against is
1497+/// the playhead mapped back into the file own frames, and a floor even one
1498+/// frame ahead of the landing would eat the very picture the seek exists to
1499+/// show ([`PlaybackSession::drop_late_pictures`]).
1500+#[test]
1501+fn a_watched_session_still_lands_on_the_frame_a_seek_asked_for() {
1502+ let mut session = open(asset("test_baseline.mp4"));
1503+ session.drop_late_pictures(true);
1504+ let fps = session.meta().frame_rate;
1505+ session.seek(3.0);
1506+ assert_eq!(
1507+ next_index(&mut session, "seek(3.0) on a watched session"),
1508+ (3.0 * fps) as u32,
1509+ "the landing frame was dropped as late"
1510+ );
1511+ // ...and again backwards: a floor left where the last span ended would drop
1512+ // every picture of a seek that went back.
1513+ session.seek(1.0);
1514+ assert_eq!(
1515+ next_index(&mut session, "seek(1.0) on a watched session"),
1516+ (1.0 * fps) as u32
1517+ );
1518+}