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 {
467467 place: bool,
468468 ) -> String {
469469 match opened {
470- Ok((session, subs)) => {
470+ Ok((mut session, subs)) => {
471471 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);
472477 // Read before the session moves: a file that plays silent says
473478 // so here or nowhere.
474479 let silent = audio_notice(&session);
@@ -729,8 +734,10 @@ impl Player {
729734 return;
730735 }
731736 let text = match opened {
732- Ok(session) => {
737+ Ok(mut session) => {
733738 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);
734741 let silent = audio_notice(&session);
735742 // A project is named after itself but still exports beside its
736743 // media: that is the only place an export has ever landed.
crates/engine/src/decode.rsmodified+137 -21
@@ -3,7 +3,7 @@
33
44 use std::path::{Path, PathBuf};
55 use std::sync::Arc;
6-use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
6+use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
77 use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
88 use std::thread;
99
@@ -159,6 +159,11 @@ struct Reuse {
159159 /// decodes -- so a reseek onto a file already open says "hardware" from the
160160 /// first repaint instead of going back through `opening`.
161161 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>,
162167 }
163168
164169 /// One span asked of a persistent worker: the range in the file's own frames,
@@ -178,16 +183,34 @@ struct SpanCmd {
178183 /// What stops a decode loop: the worker's terminal flag (the thread itself is
179184 /// going away) and the generation of the span it was handed (only *this* span is
180185 /// 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.
181190 struct Abort<'a> {
182191 cancel: &'a AtomicBool,
183192 generation: &'a AtomicU64,
184193 mine: u64,
194+ floor: &'a AtomicU32,
185195 }
186196
187197 impl Abort<'_> {
188198 fn hit(&self) -> bool {
189199 self.cancel.load(Ordering::Relaxed) || self.generation.load(Ordering::Acquire) != self.mine
190200 }
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+ }
191214 }
192215
193216 impl Worker {
@@ -221,6 +244,17 @@ impl Worker {
221244 }
222245 }
223246
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+
224258 /// Points this worker at another range of the file it already has open,
225259 /// handing back the channel the new span's pictures arrive on and the cell
226260 /// that says what is decoding them. `None` when this worker cannot take the
@@ -246,7 +280,11 @@ impl Worker {
246280 if reuse.path != path || self.is_finished() {
247281 return None;
248282 }
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);
250288 // Bumped before the command is queued, so the span running now stops at
251289 // its next picture whatever order the two threads are scheduled in.
252290 let generation = reuse.generation.fetch_add(1, Ordering::Release) + 1;
@@ -613,11 +651,6 @@ impl DecodeSession {
613651 }
614652 }
615653
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-
621654 /// Spawns a decode worker over `path` and gives it its first span. The thread
622655 /// **outlives that span**: it parks on its command channel afterwards, so the
623656 /// next seek onto the same file reaches it through [`Worker::reseek`] and costs
@@ -637,13 +670,15 @@ fn span_worker(
637670 canvas: Composer,
638671 tone: tonemap::Preset,
639672 ) -> FrameStream {
640- let (tx, rx) = sync_channel(QUEUE);
673+ let (tx, rx) = sync_channel(canvas.queue_depth());
641674 let cancel = Arc::new(AtomicBool::new(false));
642675 // Written by the worker the moment it knows, so a caller reading it sees
643676 // what opened rather than what was hoped for -- and kept across the spans
644677 // that follow, since they are decoded by that very decoder.
645678 let backend = BackendCell::default();
646679 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));
647682 let (spans, commands) = std::sync::mpsc::channel();
648683 let first = SpanCmd {
649684 generation: 0,
@@ -657,6 +692,7 @@ fn span_worker(
657692 let worker_cancel = Arc::clone(&cancel);
658693 let worker_backend = backend.clone();
659694 let worker_generation = Arc::clone(&generation);
695+ let worker_floor = Arc::clone(&floor);
660696 let worker_path = path.clone();
661697 let handle = thread::Builder::new()
662698 .name("decode".into())
@@ -668,6 +704,7 @@ fn span_worker(
668704 cancel: &worker_cancel,
669705 generation: &worker_generation,
670706 mine: cmd.generation,
707+ floor: &worker_floor,
671708 };
672709 // Superseded (or cancelled) before this thread was even
673710 // scheduled: do not open the file, and do not enter VA-API
@@ -697,12 +734,22 @@ fn span_worker(
697734 spans,
698735 generation,
699736 backend: backend.clone(),
737+ floor,
700738 }),
701739 },
702740 backend,
703741 }
704742 }
705743
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+
706753 /// What a decode worker keeps **between** the spans it is asked for: the
707754 /// container it read, what the stream says about itself, and the hardware
708755 /// session -- the three things a seek used to throw away and buy again.
@@ -1154,16 +1201,25 @@ fn run_hw(
11541201 abort: &Abort,
11551202 ) -> bool {
11561203 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;
11571207 loop {
11581208 if abort.hit() {
11591209 return true;
11601210 }
11611211 match hw.next_frame() {
11621212 Ok(Some((y, u, v, width, height))) => {
1163- let frame = render.frame(index, y, u, v, width, height);
1213+ let due = index;
11641214 index += 1;
1165- if tx.send(frame).is_err() {
1166- return true; // consumer went away
1215+ if abort.late(due) && skipped < LATE_RUN {
1216+ 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+ }
11671223 }
11681224 if index >= end_frame {
11691225 return true; // end of the requested range
@@ -1275,6 +1331,59 @@ mod tests {
12751331 );
12761332 }
12771333
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+
12781387 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
12791388 /// The channel is bounded, so such a worker is parked in `send` within a
12801389 /// few frames, and the only thing that can wake it is its receiver going
@@ -1329,6 +1438,7 @@ fn run(
13291438 // converted or sent. Signed, because the landing sync sample can sit inside
13301439 // what the file's edit list trims, i.e. *before* frame 0.
13311440 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
1441+ let mut skipped = 0;
13321442
13331443 // corner-cut: emits pictures in decode order. Fine for Baseline (no B-frames);
13341444 // reordering streams need POC-sorted output before display.
@@ -1356,17 +1466,23 @@ fn run(
13561466 index += 1;
13571467 continue;
13581468 }
1359- let frame = render.frame(
1360- index as u32,
1361- &yuv.y,
1362- &yuv.u,
1363- &yuv.v,
1364- yuv.width as u32,
1365- yuv.height as u32,
1366- );
1469+ let due = index as u32;
13671470 index += 1;
1368- if tx.send(frame).is_err() {
1369- break; // consumer went away
1471+ if abort.late(due) && skipped < LATE_RUN {
1472+ 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+ }
13701486 }
13711487 if index >= i64::from(end_frame) {
13721488 break; // end of the requested range
crates/engine/src/playback.rsmodified+60 -0
@@ -311,6 +311,10 @@ pub struct PlaybackSession {
311311 /// of a restart is never counted as timeline time. See
312312 /// [`Audio::content_at`].
313313 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,
314318 }
315319
316320 /// What an edit dirtied -- which half of the pipeline has to be rebuilt for the
@@ -423,6 +427,7 @@ impl PlaybackSession {
423427 eos: false,
424428 mix: None,
425429 priming: false,
430+ drop_late: false,
426431 })
427432 }
428433
@@ -533,6 +538,7 @@ impl PlaybackSession {
533538 eos: false,
534539 mix: None,
535540 priming: false,
541+ drop_late: false,
536542 })
537543 }
538544
@@ -607,6 +613,7 @@ impl PlaybackSession {
607613 eos: false,
608614 mix: None,
609615 priming: false,
616+ drop_late: false,
610617 })
611618 }
612619
@@ -898,6 +905,7 @@ impl PlaybackSession {
898905 eos: false,
899906 mix: None,
900907 priming: false,
908+ drop_late: false,
901909 };
902910 // The scaffolding above opened source 0 from its first frame and the
903911 // whole of its audio; this puts both onto the clip the playhead is
@@ -1166,6 +1174,7 @@ impl PlaybackSession {
11661174 /// big film, seconds off a cold cache). End of stream is
11671175 /// [`PlaybackSession::is_eos`].
11681176 pub fn try_frame(&mut self) -> Option<Frame> {
1177+ self.publish_playhead();
11691178 loop {
11701179 match self.frames.try_recv() {
11711180 Ok(mut frame) => {
@@ -1221,6 +1230,32 @@ impl PlaybackSession {
12211230 self.eos
12221231 }
12231232
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+
12241259 /// Installs `replacement` as the decode worker, parking the outgoing one in
12251260 /// [`retired`](Self::retired) rather than joining it here, and reaping the
12261261 /// parked ones that have already returned.
@@ -2473,6 +2508,25 @@ impl PlaybackSession {
24732508 Some((tap, audio.sample_rate))
24742509 }
24752510
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+
24762530 /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode
24772531 /// workers are replaced rather than steered: a fresh channel cannot hold a
24782532 /// stale frame, and it works just as well after EOF, where the old workers
@@ -2732,6 +2786,12 @@ impl PlaybackSession {
27322786 /// Moves the clock forward; the caller runs this once per rendered frame.
27332787 /// Costs an atomic load, and once per session a mode switch.
27342788 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();
27352795 let Some(audio) = &self.audio else {
27362796 return; // wall time from the start, nothing to poll
27372797 };
crates/engine/src/scale.rsmodified+18 -0
@@ -386,6 +386,24 @@ impl Composer {
386386 Self::new(0, 0, FitPolicy::Fit)
387387 }
388388
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+
389407 /// Whether a `src_w` x `src_h` picture is already the canvas, i.e. this
390408 /// composer would hand it back untouched. What lets a caller keep a fused
391409 /// 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>) {
4747 let target = session.now() * session.meta().frame_rate;
4848 while let Some(frame) = session.try_frame() {
4949 if let Some(previous) = *last_index {
50- assert_eq!(
51- frame.index,
52- previous + 1,
53- "frames must arrive in index order"
50+ // Forwards, never twice and never backwards -- but not necessarily
51+ // one at a time: a worker whose pictures have fallen behind the
52+ // playhead drops them where they are cheap to drop rather than
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
5460 );
5561 }
5662 *last_index = Some(frame.index);
@@ -1485,3 +1491,28 @@ fn an_emptied_timeline_plays_black_saves_loads_and_undoes() {
14851491 assert!((session.timeline_duration() - whole).abs() < 1e-9);
14861492 assert_eq!(session.clip_spans().len(), 1);
14871493 }
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+}