forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-thread3' (f4946b69): dependency-aware frame scheduling with per-slot promises; every non-key frame decodes on a worker waiting only on its reference slots; show_existing output dispatched; byte-exact at 1, 2 and 4 threads; 4K 8.0 to 14.6 fps at 6 threads, 1080p 29 to 41 fps

Browse files at this commit

a5126ca5c8434e1d165442cc87962c75a6e441ebAhmet Kaan GümüşParent: d6f9cd4fada71e
crates/ec-av1/examples/decode_probe.rsmodified+2 -2
@@ -154,8 +154,8 @@ fn main() {
154154 // lane-thread2: proof the frame-parallel path actually fired (0 at
155155 // the default EC_AV1_THREADS=1).
156156 println!(
157- "leaf_frames_dispatched: {}",
158- ec_av1::stream::leaf_frames_dispatched()
157+ "frames_dispatched: {}",
158+ ec_av1::stream::frames_dispatched()
159159 );
160160 };
161161 // lane-tiles: the tiling a real stream actually uses is a decision input
crates/ec-av1/src/motion_field.rsmodified+10 -3
@@ -337,8 +337,8 @@ pub fn refstamp_intra_frames() -> (usize, usize) {
337337 /// constructed, so also `None` — motion field, contributes nothing);
338338 /// `ref_frame_idx` is the current frame header's own `ref_frame_idx`
339339 /// (`LAST_FRAME..=ALTREF_FRAME`, indexed `[i]` for `LAST_FRAME + i`).
340-pub fn setup_motion_field(
341- slots: &[Option<MotionField>; 8],
340+pub fn setup_motion_field<M: std::borrow::Borrow<MotionField>>(
341+ slots: &[Option<M>; 8],
342342 ref_frame_idx: [u8; 7],
343343 cur_order_hint: u32,
344344 order_hint_bits: u32,
@@ -355,7 +355,14 @@ pub fn setup_motion_field(
355355 }
356356
357357 let slot_of =
358- |ref_frame: i8| slots[ref_frame_idx[(ref_frame - LAST_FRAME) as usize] as usize].as_ref();
358+ // lane-thread3: `M` is an owned `MotionField` on the single-threaded
359+ // path and a `&MotionField` borrowed out of a resolved reference-slot
360+ // promise on a worker; the projection reads the same field either way.
361+ |ref_frame: i8| {
362+ slots[ref_frame_idx[(ref_frame - LAST_FRAME) as usize] as usize]
363+ .as_ref()
364+ .map(M::borrow)
365+ };
359366 let order_hint_of = |ref_frame: i8| slot_of(ref_frame).map_or(0, |m| m.order_hint);
360367
361368 let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1
crates/ec-av1/src/stream.rsmodified+393 -127
@@ -318,38 +318,140 @@ impl Reorder {
318318 }
319319 }
320320
321-/// lane-thread2: how many leaf frames this PROCESS has dispatched to a worker
322-/// thread (see [`decode_stream_with_threads`]). Process-global and atomic on
323-/// purpose: it is the only counter here a caller can read after a threaded
324-/// decode, and it is what keeps a "decodes identically with 4 threads" gate
325-/// from silently proving nothing because every frame ran inline.
326-static LEAF_FRAMES_DISPATCHED: std::sync::atomic::AtomicUsize =
321+/// lane-thread2/3: how many coded frames this PROCESS has dispatched to a
322+/// worker thread (see [`decode_stream_with_threads`]). Process-global and
323+/// atomic on purpose: it is the only counter here a caller can read after a
324+/// threaded decode, and it is what keeps a "decodes identically with 4
325+/// threads" gate from silently proving nothing because every frame ran
326+/// inline. (lane-thread2 counted only LEAF frames, the only ones it could
327+/// dispatch; lane-thread3 dispatches every non-key, non-`show_existing_frame`
328+/// frame, hence the rename.)
329+static FRAMES_DISPATCHED: std::sync::atomic::AtomicUsize =
327330 std::sync::atomic::AtomicUsize::new(0);
328331
329-/// Reads [`LEAF_FRAMES_DISPATCHED`].
330-pub fn leaf_frames_dispatched() -> usize {
331- LEAF_FRAMES_DISPATCHED.load(std::sync::atomic::Ordering::Relaxed)
332+/// Reads [`FRAMES_DISPATCHED`].
333+pub fn frames_dispatched() -> usize {
334+ FRAMES_DISPATCHED.load(std::sync::atomic::Ordering::Relaxed)
332335 }
333336
334-/// One finished leaf frame from a worker: its output position, and either the
335-/// (grain-synthesised) picture with the decode index to report or the error
336-/// that aborts the stream.
337-type LeafResult = (usize, Result<(Picture, usize, bool)>);
337+/// lane-thread3: what one decoded frame stores into every reference slot its
338+/// `refresh_frame_flags` names (spec 7.20), as one shared, never-mutated
339+/// object -- so a slot costs an `Arc` clone instead of a picture copy.
340+struct SlotValue {
341+ picture: std::sync::Arc<Picture>,
342+ cdfs: Cdfs,
343+ motion_field: crate::motion_field::MotionField,
344+ seg_map: Vec<u8>,
345+ order_hint: u32,
346+}
347+
348+/// lane-thread3: a reference slot's contents as a FUTURE. At `threads > 1`
349+/// the 8-slot bank holds these instead of values: a slot refreshed by a frame
350+/// that is still decoding on a worker holds the promise from the moment the
351+/// parsing thread DISPATCHES that frame, so the next frame can be dispatched
352+/// straight away and waits, on its own worker, for exactly the slots it
353+/// reads. This is what makes a pyramid stream (aomenc's default, where nearly
354+/// every coded frame refreshes a slot, so lane-thread2's leaf rule dispatched
355+/// almost nothing) decode in parallel.
356+///
357+/// DEADLOCK ARGUMENT. A promise is installed into a slot on the parsing
358+/// thread, in decode order, when its producer is dispatched; a consumer
359+/// captures the promises of the slots it reads at ITS dispatch, which is
360+/// strictly later in decode order. Every wait therefore points from a later
361+/// coded frame to an earlier one -- the wait graph is the reference DAG, and
362+/// is acyclic. The parsing thread waits only for a `show_existing_frame`
363+/// output (again an earlier frame) and at the in-flight bound, where it waits
364+/// for ANY worker to answer: the earliest in-flight frame has no earlier
365+/// in-flight producer, so it is always runnable and the bound always clears.
366+/// Each dispatched frame gets its own thread, so a blocked waiter never holds
367+/// a resource its producer needs. A producer that errors or panics marks its
368+/// promise `Failed`, so no consumer can wait for a value that never comes.
369+struct SlotPromise {
370+ state: std::sync::Mutex<PromiseState>,
371+ ready: std::sync::Condvar,
372+}
373+
374+enum PromiseState {
375+ Pending,
376+ Ready(std::sync::Arc<SlotValue>),
377+ Failed,
378+}
379+
380+impl SlotPromise {
381+ fn pending() -> std::sync::Arc<Self> {
382+ std::sync::Arc::new(Self {
383+ state: std::sync::Mutex::new(PromiseState::Pending),
384+ ready: std::sync::Condvar::new(),
385+ })
386+ }
387+
388+ /// A slot filled by a frame the parsing thread decoded itself.
389+ fn ready(value: std::sync::Arc<SlotValue>) -> std::sync::Arc<Self> {
390+ std::sync::Arc::new(Self {
391+ state: std::sync::Mutex::new(PromiseState::Ready(value)),
392+ ready: std::sync::Condvar::new(),
393+ })
394+ }
395+
396+ fn fulfil(&self, value: std::sync::Arc<SlotValue>) {
397+ *self.state.lock().expect("slot promise") = PromiseState::Ready(value);
398+ self.ready.notify_all();
399+ }
400+
401+ fn fail(&self) {
402+ let mut state = self.state.lock().expect("slot promise");
403+ if matches!(*state, PromiseState::Pending) {
404+ *state = PromiseState::Failed;
405+ }
406+ self.ready.notify_all();
407+ }
408+
409+ /// Blocks until the producing frame has published this slot.
410+ fn wait(&self) -> Result<std::sync::Arc<SlotValue>> {
411+ let mut state = self.state.lock().expect("slot promise");
412+ loop {
413+ match &*state {
414+ PromiseState::Ready(value) => return Ok(value.clone()),
415+ PromiseState::Failed => {
416+ return Err(Error::corrupt(
417+ "AV1 decode_stream: a reference frame this frame depends on failed to decode",
418+ ));
419+ }
420+ PromiseState::Pending => {
421+ state = self.ready.wait(state).expect("slot promise");
422+ }
423+ }
424+ }
425+ }
426+}
427+
428+/// One finished frame from a worker: its output position, whether the job was
429+/// a frame DECODE (as opposed to a `show_existing_frame` output, which only
430+/// waits for a slot and synthesises grain -- lane-thread3 counts the two
431+/// against separate in-flight bounds, since a waiting output job costs no
432+/// CPU), and either the (grain-synthesised) picture with the decode index to
433+/// report or the error that aborts the stream.
434+type LeafResult = (usize, bool, Result<(Picture, usize, bool)>);
338435
339-/// Waits for one in-flight leaf frame and emits whatever that unblocks.
436+/// Waits for one in-flight job and emits whatever that unblocks.
340437 fn collect_one(
341438 rx: &std::sync::mpsc::Receiver<LeafResult>,
342- in_flight: &mut usize,
439+ decodes: &mut usize,
440+ shows: &mut usize,
343441 reorder: &mut Reorder,
344442 sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>,
345443 ) -> Result<()> {
346444 // Every dispatched worker answers exactly once, panic included (it is
347445 // caught and turned into an error below), so the sender count cannot
348446 // reach zero while `in_flight > 0`.
349- let (seq, result) = rx
447+ let (seq, decode_job, result) = rx
350448 .recv()
351449 .map_err(|_| Error::corrupt("AV1 decode_stream: a worker thread vanished"))?;
352- *in_flight -= 1;
450+ if decode_job {
451+ *decodes -= 1;
452+ } else {
453+ *shows -= 1;
454+ }
353455 let (picture, decode_idx, shown) = result?;
354456 reorder.push(seq, picture, decode_idx, shown);
355457 reorder.drain(sink)
@@ -422,15 +524,21 @@ pub fn decode_stream_with_threads(
422524 // pushed).
423525 let mut emit_seq = 0usize;
424526 let mut reorder = Reorder::default();
425- let mut in_flight = 0usize;
426- let in_flight_cap = threads + 1;
527+ // lane-thread3: frame decodes and `show_existing_frame` outputs are
528+ // bounded separately -- an output job is a promise wait plus a memcpy, so
529+ // letting it eat a decode's budget just idles a core (measured: sharing
530+ // one bound cost 4K 18.7 s at 244% CPU against 17.7 s at 287%).
531+ let mut in_flight_decodes = 0usize;
532+ let mut in_flight_shows = 0usize;
533+ let in_flight_cap = threads + 2;
427534 let (tx, rx) = std::sync::mpsc::channel::<LeafResult>();
428- // A worker needs its references to outlive the main thread's next
429- // `refresh_frame_flags` write, so a dispatched slot is copied once into an
430- // `Arc` and re-shared until that slot is overwritten (cleared alongside
431- // every `ref_slots` write below). The DPB itself stays owned `Picture`s:
432- // an `Arc` DPB measured ~1% SLOWER single-threaded (lane-perf9).
433- let mut ref_arcs: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] =
535+ // lane-thread3: at `threads > 1` THIS is the reference bank -- one
536+ // [`SlotPromise`] per DPB slot, ready for a slot the parsing thread filled
537+ // itself and pending for one an in-flight frame will fill. The owned
538+ // arrays above are then untouched (and the single-threaded path never
539+ // creates a promise: it stays exactly the decoder it was, which is what
540+ // keeps every counter-reading gate meaningful).
541+ let mut slot_promises: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
434542 std::array::from_fn(|_| None);
435543
436544 let mut pos = 0usize;
@@ -471,22 +579,93 @@ pub fn decode_stream_with_threads(
471579 // was emitted (wrongly, in decode order) and its real
472580 // `show_existing_frame` output was silently dropped.
473581 let slot = header.frame_to_show_map_idx as usize;
474- let picture = ref_slots[slot].clone().ok_or_else(|| {
582+ let empty_slot = || {
475583 Error::unsupported(
476584 "AV1 decode_stream",
477585 "a show_existing_frame header naming an empty reference slot",
478586 )
479- })?;
480- for i in 0..NUM_REF_FRAMES {
481- if header.refresh_frame_flags & (1 << i) != 0 {
482- cdf_slots[i] = cdf_slots[slot].clone();
483- ref_slots[i] = Some(picture.clone());
484- ref_arcs[i] = None;
485- motion_field_slots[i] = motion_field_slots[slot].clone();
486- seg_map_slots[i] = seg_map_slots[slot].clone();
487- order_hint_slots[i] = order_hint_slots[slot];
587+ };
588+ if threads > 1 {
589+ // lane-thread3: the named slot may still be decoding on a
590+ // worker, and the copy into the slots this header refreshes
591+ // is then just the promise -- no value needed. The OUTPUT
592+ // does need the picture, so it is produced on a worker too:
593+ // waiting for it here would stall the parsing thread, and a
594+ // stalled parser dispatches nothing (measured before this
595+ // arm existed: 7.9 s of an 8.8 s 1080p decode, 18.9 s of
596+ // 23.3 s at 4K, spent in this one wait). The wait still
597+ // points at an earlier coded frame, so the argument in
598+ // [`SlotPromise`] is unchanged.
599+ let promise = slot_promises[slot].clone().ok_or_else(empty_slot)?;
600+ for i in 0..NUM_REF_FRAMES {
601+ if header.refresh_frame_flags & (1 << i) != 0 {
602+ slot_promises[i] = Some(promise.clone());
603+ }
604+ }
605+ while in_flight_shows >= in_flight_cap {
606+ collect_one(
607+ &rx,
608+ &mut in_flight_decodes,
609+ &mut in_flight_shows,
610+ &mut reorder,
611+ &mut sink,
612+ )?;
613+ }
614+ let (job_seq, decode_idx) = (emit_seq, pictures_decoded);
615+ emit_seq += 1;
616+ pictures_shown += 1;
617+ let grain = header.film_grain;
618+ let seq = SeqFlags::read(&parser);
619+ let tx = tx.clone();
620+ scope.spawn(move || {
621+ let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
622+ let value = promise.wait()?;
623+ let output = if grain.apply_grain && !no_grain() {
624+ crate::film_grain::apply_grain(
625+ &value.picture,
626+ &grain,
627+ seq.mc_identity,
628+ u32::from(seq.bit_depth),
629+ &crate::decode::FrameCtx::new(),
630+ )
631+ } else {
632+ value.picture.as_ref().clone()
633+ };
634+ Ok((output, decode_idx, true))
635+ }))
636+ .unwrap_or_else(|_| {
637+ Err(Error::corrupt(
638+ "AV1 decode_stream: a worker thread panicked on a show_existing_frame output",
639+ ))
640+ });
641+ let _ = tx.send((job_seq, false, reply));
642+ });
643+ in_flight_shows += 1;
644+ while let Ok((seq, decode_job, result)) = rx.try_recv() {
645+ if decode_job {
646+ in_flight_decodes -= 1;
647+ } else {
648+ in_flight_shows -= 1;
649+ }
650+ let (picture, decode_idx, shown) = result?;
651+ reorder.push(seq, picture, decode_idx, shown);
652+ reorder.drain(&mut sink)?;
488653 }
654+ continue;
489655 }
656+ let picture = {
657+ let picture = ref_slots[slot].clone().ok_or_else(empty_slot)?;
658+ for i in 0..NUM_REF_FRAMES {
659+ if header.refresh_frame_flags & (1 << i) != 0 {
660+ cdf_slots[i] = cdf_slots[slot].clone();
661+ ref_slots[i] = Some(picture.clone());
662+ motion_field_slots[i] = motion_field_slots[slot].clone();
663+ seg_map_slots[i] = seg_map_slots[slot].clone();
664+ order_hint_slots[i] = order_hint_slots[slot];
665+ }
666+ }
667+ picture
668+ };
490669 let output = if header.film_grain.apply_grain && !no_grain() {
491670 // lane-hbd10 r1: grain synthesis is bit-depth generic
492671 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
@@ -612,57 +791,84 @@ pub fn decode_stream_with_threads(
612791 })
613792 .collect::<Result<_>>()?;
614793 let seq = SeqFlags::read(&parser);
615- // A LEAF of the reference graph: shown, not a key frame, and
616- // refreshing no slot -- so nothing it produces except its own picture
617- // is ever read again (spec 7.20's bank update is keyed entirely on
618- // `refresh_frame_flags`), and it can be decoded anywhere.
619- if threads > 1
620- && header.refresh_frame_flags == 0
621- && header.show_frame
622- && !header.show_existing_frame
623- && header.frame_type != FrameType::Key
624- {
625- while in_flight >= in_flight_cap {
626- collect_one(&rx, &mut in_flight, &mut reorder, &mut sink)?;
627- }
628- let mut arcs: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] =
794+ // lane-thread3: at `threads > 1` every coded frame that is not a key
795+ // frame is decoded on a worker -- frames that refresh reference slots
796+ // included, which on a pyramid stream is nearly all of them. Its
797+ // inputs are taken as promises and its output is published as one,
798+ // installed into the slots it refreshes HERE, on the parsing thread,
799+ // in decode order, so the next frame's dependencies are known without
800+ // waiting for this one to finish (see [`SlotPromise`] for the
801+ // deadlock argument). A key frame stays inline: it resets the whole
802+ // bank and reads nothing, so there is nothing to gain.
803+ if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame {
804+ while in_flight_decodes >= in_flight_cap {
805+ collect_one(
806+ &rx,
807+ &mut in_flight_decodes,
808+ &mut in_flight_shows,
809+ &mut reorder,
810+ &mut sink,
811+ )?;
812+ }
813+ // Exactly the slots this frame reads: `ref_frame_idx` names its
814+ // references, and its `primary_ref_frame` CDFs/segment map, its
815+ // reference order hints and every field `setup_motion_field`
816+ // projects all come from those same slots. Nothing else is
817+ // waited on.
818+ let mut deps: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
629819 std::array::from_fn(|_| None);
630820 for i in 0..7 {
631821 let slot = header.ref_frame_idx[i] as usize;
632- if arcs[slot].is_none()
633- && let Some(picture) = ref_slots[slot].as_ref()
634- {
635- arcs[slot] = Some(
636- ref_arcs[slot]
637- .get_or_insert_with(|| std::sync::Arc::new(picture.clone()))
638- .clone(),
639- );
822+ deps[slot] = slot_promises[slot].clone();
823+ }
824+ let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending);
825+ if let Some(promise) = &produces {
826+ for i in 0..NUM_REF_FRAMES {
827+ if header.refresh_frame_flags & (1 << i) != 0 {
828+ slot_promises[i] = Some(promise.clone());
829+ }
640830 }
641831 }
642- let snap = RefSnapshot::take(
643- &header,
644- seq,
645- std::array::from_fn(|_| None),
646- &cdf_slots,
647- &seg_map_slots,
648- &motion_field_slots,
649- &order_hint_slots,
650- );
651832 let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown);
652833 emit_seq += 1;
653834 pictures_decoded += 1;
654- pictures_shown += 1;
835+ let shown = header.show_frame;
836+ if shown {
837+ pictures_shown += 1;
838+ }
655839 let tx = tx.clone();
656840 let dump = final_dump.clone();
657841 scope.spawn(move || {
842+ let promise = produces;
658843 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
844+ // The wait happens HERE, off the parsing thread, and only
845+ // for this frame's own references.
846+ let mut resolved: [Option<std::sync::Arc<SlotValue>>; NUM_REF_FRAMES] =
847+ std::array::from_fn(|_| None);
848+ for (slot, dep) in deps.iter().enumerate() {
849+ if let Some(dep) = dep {
850+ resolved[slot] = Some(dep.wait()?);
851+ }
852+ }
659853 // Fresh per-thread state: every field this path reads is
660854 // written from this frame's own header before it is read.
661855 let fctx = crate::decode::FrameCtx::new();
662- let snap = RefSnapshot {
663- refs: std::array::from_fn(|i| arcs[i].as_deref()),
664- ..snap
665- };
856+ // spec 7.9's `av1_setup_motion_field` runs inside
857+ // `RefSnapshot::take`, i.e. here, after those waits --
858+ // it reads the referenced slots' saved motion fields.
859+ let motion_fields =
860+ std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.motion_field));
861+ let snap = RefSnapshot::take(
862+ &header,
863+ seq,
864+ std::array::from_fn(|i| resolved[i].as_ref().map(|v| &*v.picture)),
865+ std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)),
866+ std::array::from_fn(|i| {
867+ resolved[i].as_ref().map(|v| v.seg_map.as_slice())
868+ }),
869+ &motion_fields,
870+ std::array::from_fn(|i| resolved[i].as_ref().map_or(0, |v| v.order_hint)),
871+ );
666872 let out = decode_frame(
667873 &fctx,
668874 &header,
@@ -673,31 +879,58 @@ pub fn decode_stream_with_threads(
673879 shown_idx,
674880 dump.as_deref(),
675881 )?;
676- let picture = if header.film_grain.apply_grain && !no_grain() {
882+ // Publish before grain synthesis: every frame waiting on
883+ // this slot can start the moment the clean picture exists
884+ // (spec 7.18.3.1 -- the bank never stores grain).
885+ let picture = std::sync::Arc::new(out.picture);
886+ if let Some(promise) = &promise {
887+ promise.fulfil(std::sync::Arc::new(SlotValue {
888+ picture: picture.clone(),
889+ cdfs: out.stored_cdfs,
890+ motion_field: out.motion_field,
891+ seg_map: out.seg_map,
892+ order_hint: header.order_hint,
893+ }));
894+ }
895+ // Grain is synthesised for OUTPUT only: a hidden frame is
896+ // reported to the sink clean, exactly as the inline path
897+ // below reports it (spec 7.18.3.1).
898+ let output = if shown && header.film_grain.apply_grain && !no_grain() {
677899 crate::film_grain::apply_grain(
678- &out.picture,
900+ &picture,
679901 &header.film_grain,
680902 seq.mc_identity,
681903 u32::from(seq.bit_depth),
682904 &fctx,
683905 )
684906 } else {
685- out.picture
907+ std::sync::Arc::try_unwrap(picture).unwrap_or_else(|p| (*p).clone())
686908 };
687- Ok((picture, decode_idx, true))
909+ Ok((output, decode_idx, shown))
688910 }))
689911 .unwrap_or_else(|_| {
690912 Err(Error::corrupt(
691- "AV1 decode_stream: a worker thread panicked decoding a leaf frame",
913+ "AV1 decode_stream: a worker thread panicked decoding a frame",
692914 ))
693915 });
694- let _ = tx.send((job_seq, reply));
916+ // A frame nobody can decode must not leave its consumers
917+ // waiting for a slot that will never be filled.
918+ if reply.is_err()
919+ && let Some(promise) = &promise
920+ {
921+ promise.fail();
922+ }
923+ let _ = tx.send((job_seq, true, reply));
695924 });
696- in_flight += 1;
697- LEAF_FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
925+ in_flight_decodes += 1;
926+ FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
698927 // Anything that finished while this frame was being set up.
699- while let Ok((seq, result)) = rx.try_recv() {
700- in_flight -= 1;
928+ while let Ok((seq, decode_job, result)) = rx.try_recv() {
929+ if decode_job {
930+ in_flight_decodes -= 1;
931+ } else {
932+ in_flight_shows -= 1;
933+ }
701934 let (picture, decode_idx, shown) = result?;
702935 reorder.push(seq, picture, decode_idx, shown);
703936 reorder.drain(&mut sink)?;
@@ -708,10 +941,10 @@ pub fn decode_stream_with_threads(
708941 &header,
709942 seq,
710943 std::array::from_fn(|i| ref_slots[i].as_ref()),
711- &cdf_slots,
712- &seg_map_slots,
713- &motion_field_slots,
714- &order_hint_slots,
944+ std::array::from_fn(|i| cdf_slots[i].as_ref()),
945+ std::array::from_fn(|i| seg_map_slots[i].as_deref()),
946+ &std::array::from_fn(|i| motion_field_slots[i].as_ref()),
947+ order_hint_slots,
715948 );
716949 let bit_depth = seq.bit_depth;
717950 let FrameOutput {
@@ -730,18 +963,38 @@ pub fn decode_stream_with_threads(
730963 final_dump.as_deref(),
731964 )?;
732965 pictures_decoded += 1;
733- for i in 0..NUM_REF_FRAMES {
734- if header.refresh_frame_flags & (1 << i) != 0 {
735- cdf_slots[i] = Some(stored_cdfs.clone());
736- // Spec 7.18.3.1: synthesized grain is never stored for later
737- // prediction -- the reference bank always keeps the clean,
738- // pre-grain decode, even though the frame pushed onto the
739- // caller's output below carries the grained picture.
740- ref_slots[i] = Some(picture.clone());
741- ref_arcs[i] = None;
742- motion_field_slots[i] = Some(motion_field.clone());
743- seg_map_slots[i] = Some(decoded_seg_map.clone());
744- order_hint_slots[i] = header.order_hint;
966+ if threads > 1 {
967+ // lane-thread3: only a key frame reaches this inline path at
968+ // `threads > 1`, and the bank it fills is the promise array --
969+ // already resolved, since the picture exists right here.
970+ if header.refresh_frame_flags != 0 {
971+ let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue {
972+ picture: std::sync::Arc::new(picture.clone()),
973+ cdfs: stored_cdfs,
974+ motion_field,
975+ seg_map: decoded_seg_map,
976+ order_hint: header.order_hint,
977+ }));
978+ for i in 0..NUM_REF_FRAMES {
979+ if header.refresh_frame_flags & (1 << i) != 0 {
980+ slot_promises[i] = Some(promise.clone());
981+ }
982+ }
983+ }
984+ } else {
985+ for i in 0..NUM_REF_FRAMES {
986+ if header.refresh_frame_flags & (1 << i) != 0 {
987+ cdf_slots[i] = Some(stored_cdfs.clone());
988+ // Spec 7.18.3.1: synthesized grain is never stored for
989+ // later prediction -- the reference bank always keeps the
990+ // clean, pre-grain decode, even though the frame pushed
991+ // onto the caller's output below carries the grained
992+ // picture.
993+ ref_slots[i] = Some(picture.clone());
994+ motion_field_slots[i] = Some(motion_field.clone());
995+ seg_map_slots[i] = Some(decoded_seg_map.clone());
996+ order_hint_slots[i] = header.order_hint;
997+ }
745998 }
746999 }
7471000 // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a
@@ -777,8 +1030,14 @@ pub fn decode_stream_with_threads(
7771030 reorder.drain(&mut sink)?;
7781031 }
7791032 }
780- while in_flight > 0 {
781- collect_one(&rx, &mut in_flight, &mut reorder, &mut sink)?;
1033+ while in_flight_decodes + in_flight_shows > 0 {
1034+ collect_one(
1035+ &rx,
1036+ &mut in_flight_decodes,
1037+ &mut in_flight_shows,
1038+ &mut reorder,
1039+ &mut sink,
1040+ )?;
7821041 }
7831042 debug_assert!(reorder.pending.is_empty(), "a frame was never emitted");
7841043 Ok(())
@@ -842,17 +1101,19 @@ pub(crate) struct RefSnapshot<'a> {
8421101 }
8431102
8441103 impl<'a> RefSnapshot<'a> {
845- /// Reads the banks for `header`. `refs` is passed in so that the
846- /// single-threaded path can borrow the DPB pictures in place while the
847- /// worker path hands over its own `Arc` clones.
1104+ /// Reads the banks for `header`. Every slot is passed in by reference so
1105+ /// that the single-threaded path can borrow the DPB in place while a
1106+ /// worker borrows the resolved [`SlotPromise`] values it waited on --
1107+ /// spec 7.9's `setup_motion_field` therefore runs on the DECODING thread
1108+ /// (lane-thread3), after those waits.
8481109 fn take(
8491110 header: &FrameHeader,
8501111 seq: SeqFlags,
8511112 refs: [Option<&'a Picture>; NUM_REF_FRAMES],
852- cdf_slots: &[Option<Cdfs>; NUM_REF_FRAMES],
853- seg_map_slots: &[Option<Vec<u8>>; NUM_REF_FRAMES],
854- motion_field_slots: &[Option<crate::motion_field::MotionField>; NUM_REF_FRAMES],
855- order_hint_slots: &[u32; NUM_REF_FRAMES],
1113+ cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES],
1114+ seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES],
1115+ motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES],
1116+ order_hint_slots: [u32; NUM_REF_FRAMES],
8561117 ) -> Self {
8571118 let primary = (header.primary_ref_frame != PRIMARY_REF_NONE)
8581119 .then(|| header.ref_frame_idx[header.primary_ref_frame as usize] as usize);
@@ -883,8 +1144,8 @@ impl<'a> RefSnapshot<'a> {
8831144 }
8841145 Self {
8851146 refs,
886- primary_cdfs: primary.and_then(|slot| cdf_slots[slot].clone()),
887- prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].clone()),
1147+ primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),
1148+ prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].map(<[u8]>::to_vec)),
8881149 tpl_field,
8891150 ref_order_hints: std::array::from_fn(|i| {
8901151 order_hint_slots[header.ref_frame_idx[i] as usize]
@@ -32415,24 +32676,25 @@ mod tests {
3241532676 /// [`decode_stream_with_threads`] at 1 and at 4 threads and every sink
3241632677 /// call is compared -- decode index, shown flag, and all three planes.
3241732678 ///
32418- /// `reelb_arf_witness.obu` is the one that proves the parallel path: 18 of
32419- /// its 40 coded frames are leaves of the reference graph (shown,
32420- /// non-key, `refresh_frame_flags == 0`), so 18 frames really are decoded
32421- /// off the main thread, and it carries hidden alt-refs, which is exactly
32422- /// the case where "output in coded order" is not the same as "output in
32423- /// the order workers finish". `palette_screen_witness.obu` is the
32424- /// complement: an 8-bit screen stream whose every coded frame refreshes a
32425- /// slot, so at 4 threads it dispatches NOTHING and pins that the threaded
32426- /// entry point is byte-identical on the inline path too. The dispatch
32427- /// counter is asserted in both directions, so neither arm can pass
32428- /// vacuously.
32679+ /// `reelb_arf_witness.obu` is the one that proves the parallel path: it
32680+ /// carries hidden alt-refs, which is exactly the case where "output in
32681+ /// coded order" is not the same as "output in the order workers finish",
32682+ /// and under lane-thread3's dependency-aware scheduling 39 of its 40
32683+ /// coded frames (all but the key frame) are decoded off the main thread
32684+ /// -- MORE than its 37 shown frames, which is the point: lane-thread2's
32685+ /// leaf rule dispatched 18. `palette_screen_witness.obu` is the
32686+ /// complement, an 8-bit screen stream whose every coded frame refreshes a
32687+ /// slot: lane-thread2 dispatched NOTHING for it, lane-thread3 dispatches
32688+ /// all 14 of its non-key frames. Both counts are asserted exactly, plus
32689+ /// the "more than half the shown frames really ran on a worker" bound, so
32690+ /// neither arm can pass vacuously.
3242932691 #[test]
3243032692 fn a_real_stream_decodes_identically_with_one_and_four_threads() {
3243132693 const NAME: &str = "a_real_stream_decodes_identically_with_one_and_four_threads";
32432- // (fixture, shown frames, leaf frames a 4-thread run must dispatch)
32433- for (fixture, shown_frames, want_leaves) in [
32434- ("fixtures/reelb_arf_witness.obu", 37usize, 18usize),
32435- ("fixtures/palette_screen_witness.obu", 15, 0),
32694+ // (fixture, shown frames, frames a 4-thread run must dispatch)
32695+ for (fixture, shown_frames, want_dispatched) in [
32696+ ("fixtures/reelb_arf_witness.obu", 37usize, 39usize),
32697+ ("fixtures/palette_screen_witness.obu", 15, 14),
3243632698 ] {
3243732699 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture);
3243832700 let stream = std::fs::read(&path)
@@ -32447,12 +32709,16 @@ mod tests {
3244732709 out
3244832710 };
3244932711 let serial = run(1);
32450- let before = leaf_frames_dispatched();
32712+ let before = frames_dispatched();
3245132713 let parallel = run(4);
32452- let dispatched = leaf_frames_dispatched() - before;
32714+ let dispatched = frames_dispatched() - before;
3245332715 assert_eq!(
32454- dispatched, want_leaves,
32455- "{NAME}: {fixture} dispatched {dispatched} leaf frames to workers, expected {want_leaves}"
32716+ dispatched, want_dispatched,
32717+ "{NAME}: {fixture} dispatched {dispatched} frames to workers, expected {want_dispatched}"
32718+ );
32719+ assert!(
32720+ dispatched * 2 > shown_frames,
32721+ "{NAME}: {fixture} dispatched {dispatched} frames, not even half of its {shown_frames} shown frames -- the parallel path is barely exercised"
3245632722 );
3245732723 assert_eq!(
3245832724 serial.iter().filter(|f| f.1).count(),