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() {
154 // lane-thread2: proof the frame-parallel path actually fired (0 at154 // lane-thread2: proof the frame-parallel path actually fired (0 at
155 // the default EC_AV1_THREADS=1).155 // the default EC_AV1_THREADS=1).
156 println!(156 println!(
157- "leaf_frames_dispatched: {}",157+ "frames_dispatched: {}",
158- ec_av1::stream::leaf_frames_dispatched()158+ ec_av1::stream::frames_dispatched()
159 );159 );
160 };160 };
161 // lane-tiles: the tiling a real stream actually uses is a decision input161 // 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) {
337 /// constructed, so also `None` — motion field, contributes nothing);337 /// constructed, so also `None` — motion field, contributes nothing);
338 /// `ref_frame_idx` is the current frame header's own `ref_frame_idx`338 /// `ref_frame_idx` is the current frame header's own `ref_frame_idx`
339 /// (`LAST_FRAME..=ALTREF_FRAME`, indexed `[i]` for `LAST_FRAME + i`).339 /// (`LAST_FRAME..=ALTREF_FRAME`, indexed `[i]` for `LAST_FRAME + i`).
340-pub fn setup_motion_field(340+pub fn setup_motion_field<M: std::borrow::Borrow<MotionField>>(
341- slots: &[Option<MotionField>; 8],341+ slots: &[Option<M>; 8],
342 ref_frame_idx: [u8; 7],342 ref_frame_idx: [u8; 7],
343 cur_order_hint: u32,343 cur_order_hint: u32,
344 order_hint_bits: u32,344 order_hint_bits: u32,
@@ -355,7 +355,14 @@ pub fn setup_motion_field(
355 }355 }
356 356
357 let slot_of =357 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+ };
359 let order_hint_of = |ref_frame: i8| slot_of(ref_frame).map_or(0, |m| m.order_hint);366 let order_hint_of = |ref_frame: i8| slot_of(ref_frame).map_or(0, |m| m.order_hint);
360 367
361 let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1368 let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1
crates/ec-av1/src/stream.rsmodified+393 -127
@@ -318,38 +318,140 @@ impl Reorder {
318 }318 }
319 }319 }
320 320
321-/// lane-thread2: how many leaf frames this PROCESS has dispatched to a worker321+/// lane-thread2/3: how many coded frames this PROCESS has dispatched to a
322-/// thread (see [`decode_stream_with_threads`]). Process-global and atomic on322+/// worker thread (see [`decode_stream_with_threads`]). Process-global and
323-/// purpose: it is the only counter here a caller can read after a threaded323+/// atomic on purpose: it is the only counter here a caller can read after a
324-/// decode, and it is what keeps a "decodes identically with 4 threads" gate324+/// threaded decode, and it is what keeps a "decodes identically with 4
325-/// from silently proving nothing because every frame ran inline.325+/// threads" gate from silently proving nothing because every frame ran
326-static LEAF_FRAMES_DISPATCHED: std::sync::atomic::AtomicUsize =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 =
327 std::sync::atomic::AtomicUsize::new(0);330 std::sync::atomic::AtomicUsize::new(0);
328 331
329-/// Reads [`LEAF_FRAMES_DISPATCHED`].332+/// Reads [`FRAMES_DISPATCHED`].
330-pub fn leaf_frames_dispatched() -> usize {333+pub fn frames_dispatched() -> usize {
331- LEAF_FRAMES_DISPATCHED.load(std::sync::atomic::Ordering::Relaxed)334+ FRAMES_DISPATCHED.load(std::sync::atomic::Ordering::Relaxed)
332 }335 }
333 336
334-/// One finished leaf frame from a worker: its output position, and either the337+/// lane-thread3: what one decoded frame stores into every reference slot its
335-/// (grain-synthesised) picture with the decode index to report or the error338+/// `refresh_frame_flags` names (spec 7.20), as one shared, never-mutated
336-/// that aborts the stream.339+/// object -- so a slot costs an `Arc` clone instead of a picture copy.
337-type LeafResult = (usize, Result<(Picture, usize, bool)>);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)>);
338 435
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.
340 fn collect_one(437 fn collect_one(
341 rx: &std::sync::mpsc::Receiver<LeafResult>,438 rx: &std::sync::mpsc::Receiver<LeafResult>,
342- in_flight: &mut usize,439+ decodes: &mut usize,
440+ shows: &mut usize,
343 reorder: &mut Reorder,441 reorder: &mut Reorder,
344 sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>,442 sink: &mut impl FnMut(&Picture, usize, bool) -> Result<()>,
345 ) -> Result<()> {443 ) -> Result<()> {
346 // Every dispatched worker answers exactly once, panic included (it is444 // Every dispatched worker answers exactly once, panic included (it is
347 // caught and turned into an error below), so the sender count cannot445 // caught and turned into an error below), so the sender count cannot
348 // reach zero while `in_flight > 0`.446 // reach zero while `in_flight > 0`.
349- let (seq, result) = rx447+ let (seq, decode_job, result) = rx
350 .recv()448 .recv()
351 .map_err(|_| Error::corrupt("AV1 decode_stream: a worker thread vanished"))?;449 .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+ }
353 let (picture, decode_idx, shown) = result?;455 let (picture, decode_idx, shown) = result?;
354 reorder.push(seq, picture, decode_idx, shown);456 reorder.push(seq, picture, decode_idx, shown);
355 reorder.drain(sink)457 reorder.drain(sink)
@@ -422,15 +524,21 @@ pub fn decode_stream_with_threads(
422 // pushed).524 // pushed).
423 let mut emit_seq = 0usize;525 let mut emit_seq = 0usize;
424 let mut reorder = Reorder::default();526 let mut reorder = Reorder::default();
425- let mut in_flight = 0usize;527+ // lane-thread3: frame decodes and `show_existing_frame` outputs are
426- let in_flight_cap = threads + 1;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;
427 let (tx, rx) = std::sync::mpsc::channel::<LeafResult>();534 let (tx, rx) = std::sync::mpsc::channel::<LeafResult>();
428- // A worker needs its references to outlive the main thread's next535+ // lane-thread3: at `threads > 1` THIS is the reference bank -- one
429- // `refresh_frame_flags` write, so a dispatched slot is copied once into an536+ // [`SlotPromise`] per DPB slot, ready for a slot the parsing thread filled
430- // `Arc` and re-shared until that slot is overwritten (cleared alongside537+ // itself and pending for one an in-flight frame will fill. The owned
431- // every `ref_slots` write below). The DPB itself stays owned `Picture`s:538+ // arrays above are then untouched (and the single-threaded path never
432- // an `Arc` DPB measured ~1% SLOWER single-threaded (lane-perf9).539+ // creates a promise: it stays exactly the decoder it was, which is what
433- let mut ref_arcs: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] =540+ // keeps every counter-reading gate meaningful).
541+ let mut slot_promises: [Option<std::sync::Arc<SlotPromise>>; NUM_REF_FRAMES] =
434 std::array::from_fn(|_| None);542 std::array::from_fn(|_| None);
435 543
436 let mut pos = 0usize;544 let mut pos = 0usize;
@@ -471,22 +579,93 @@ pub fn decode_stream_with_threads(
471 // was emitted (wrongly, in decode order) and its real579 // was emitted (wrongly, in decode order) and its real
472 // `show_existing_frame` output was silently dropped.580 // `show_existing_frame` output was silently dropped.
473 let slot = header.frame_to_show_map_idx as usize;581 let slot = header.frame_to_show_map_idx as usize;
474- let picture = ref_slots[slot].clone().ok_or_else(|| {582+ let empty_slot = || {
475 Error::unsupported(583 Error::unsupported(
476 "AV1 decode_stream",584 "AV1 decode_stream",
477 "a show_existing_frame header naming an empty reference slot",585 "a show_existing_frame header naming an empty reference slot",
478 )586 )
479- })?;587+ };
480- for i in 0..NUM_REF_FRAMES {588+ if threads > 1 {
481- if header.refresh_frame_flags & (1 << i) != 0 {589+ // lane-thread3: the named slot may still be decoding on a
482- cdf_slots[i] = cdf_slots[slot].clone();590+ // worker, and the copy into the slots this header refreshes
483- ref_slots[i] = Some(picture.clone());591+ // is then just the promise -- no value needed. The OUTPUT
484- ref_arcs[i] = None;592+ // does need the picture, so it is produced on a worker too:
485- motion_field_slots[i] = motion_field_slots[slot].clone();593+ // waiting for it here would stall the parsing thread, and a
486- seg_map_slots[i] = seg_map_slots[slot].clone();594+ // stalled parser dispatches nothing (measured before this
487- order_hint_slots[i] = order_hint_slots[slot];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)?;
488 }653 }
654+ continue;
489 }655 }
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+ };
490 let output = if header.film_grain.apply_grain && !no_grain() {669 let output = if header.film_grain.apply_grain && !no_grain() {
491 // lane-hbd10 r1: grain synthesis is bit-depth generic670 // lane-hbd10 r1: grain synthesis is bit-depth generic
492 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).671 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
@@ -612,57 +791,84 @@ pub fn decode_stream_with_threads(
612 })791 })
613 .collect::<Result<_>>()?;792 .collect::<Result<_>>()?;
614 let seq = SeqFlags::read(&parser);793 let seq = SeqFlags::read(&parser);
615- // A LEAF of the reference graph: shown, not a key frame, and794+ // lane-thread3: at `threads > 1` every coded frame that is not a key
616- // refreshing no slot -- so nothing it produces except its own picture795+ // frame is decoded on a worker -- frames that refresh reference slots
617- // is ever read again (spec 7.20's bank update is keyed entirely on796+ // included, which on a pyramid stream is nearly all of them. Its
618- // `refresh_frame_flags`), and it can be decoded anywhere.797+ // inputs are taken as promises and its output is published as one,
619- if threads > 1798+ // installed into the slots it refreshes HERE, on the parsing thread,
620- && header.refresh_frame_flags == 0799+ // in decode order, so the next frame's dependencies are known without
621- && header.show_frame800+ // waiting for this one to finish (see [`SlotPromise`] for the
622- && !header.show_existing_frame801+ // deadlock argument). A key frame stays inline: it resets the whole
623- && header.frame_type != FrameType::Key802+ // bank and reads nothing, so there is nothing to gain.
624- {803+ if threads > 1 && header.frame_type != FrameType::Key && !header.show_existing_frame {
625- while in_flight >= in_flight_cap {804+ while in_flight_decodes >= in_flight_cap {
626- collect_one(&rx, &mut in_flight, &mut reorder, &mut sink)?;805+ collect_one(
627- }806+ &rx,
628- let mut arcs: [Option<std::sync::Arc<Picture>>; NUM_REF_FRAMES] =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] =
629 std::array::from_fn(|_| None);819 std::array::from_fn(|_| None);
630 for i in 0..7 {820 for i in 0..7 {
631 let slot = header.ref_frame_idx[i] as usize;821 let slot = header.ref_frame_idx[i] as usize;
632- if arcs[slot].is_none()822+ deps[slot] = slot_promises[slot].clone();
633- && let Some(picture) = ref_slots[slot].as_ref()823+ }
634- {824+ let produces = (header.refresh_frame_flags != 0).then(SlotPromise::pending);
635- arcs[slot] = Some(825+ if let Some(promise) = &produces {
636- ref_arcs[slot]826+ for i in 0..NUM_REF_FRAMES {
637- .get_or_insert_with(|| std::sync::Arc::new(picture.clone()))827+ if header.refresh_frame_flags & (1 << i) != 0 {
638- .clone(),828+ slot_promises[i] = Some(promise.clone());
639- );829+ }
640 }830 }
641 }831 }
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- );
651 let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown);832 let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown);
652 emit_seq += 1;833 emit_seq += 1;
653 pictures_decoded += 1;834 pictures_decoded += 1;
654- pictures_shown += 1;835+ let shown = header.show_frame;
836+ if shown {
837+ pictures_shown += 1;
838+ }
655 let tx = tx.clone();839 let tx = tx.clone();
656 let dump = final_dump.clone();840 let dump = final_dump.clone();
657 scope.spawn(move || {841 scope.spawn(move || {
842+ let promise = produces;
658 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {843 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+ }
659 // Fresh per-thread state: every field this path reads is853 // Fresh per-thread state: every field this path reads is
660 // written from this frame's own header before it is read.854 // written from this frame's own header before it is read.
661 let fctx = crate::decode::FrameCtx::new();855 let fctx = crate::decode::FrameCtx::new();
662- let snap = RefSnapshot {856+ // spec 7.9's `av1_setup_motion_field` runs inside
663- refs: std::array::from_fn(|i| arcs[i].as_deref()),857+ // `RefSnapshot::take`, i.e. here, after those waits --
664- ..snap858+ // it reads the referenced slots' saved motion fields.
665- };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+ );
666 let out = decode_frame(872 let out = decode_frame(
667 &fctx,873 &fctx,
668 &header,874 &header,
@@ -673,31 +879,58 @@ pub fn decode_stream_with_threads(
673 shown_idx,879 shown_idx,
674 dump.as_deref(),880 dump.as_deref(),
675 )?;881 )?;
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() {
677 crate::film_grain::apply_grain(899 crate::film_grain::apply_grain(
678- &out.picture,900+ &picture,
679 &header.film_grain,901 &header.film_grain,
680 seq.mc_identity,902 seq.mc_identity,
681 u32::from(seq.bit_depth),903 u32::from(seq.bit_depth),
682 &fctx,904 &fctx,
683 )905 )
684 } else {906 } else {
685- out.picture907+ std::sync::Arc::try_unwrap(picture).unwrap_or_else(|p| (*p).clone())
686 };908 };
687- Ok((picture, decode_idx, true))909+ Ok((output, decode_idx, shown))
688 }))910 }))
689 .unwrap_or_else(|_| {911 .unwrap_or_else(|_| {
690 Err(Error::corrupt(912 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",
692 ))914 ))
693 });915 });
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));
695 });924 });
696- in_flight += 1;925+ in_flight_decodes += 1;
697- LEAF_FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);926+ FRAMES_DISPATCHED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
698 // Anything that finished while this frame was being set up.927 // Anything that finished while this frame was being set up.
699- while let Ok((seq, result)) = rx.try_recv() {928+ while let Ok((seq, decode_job, result)) = rx.try_recv() {
700- in_flight -= 1;929+ if decode_job {
930+ in_flight_decodes -= 1;
931+ } else {
932+ in_flight_shows -= 1;
933+ }
701 let (picture, decode_idx, shown) = result?;934 let (picture, decode_idx, shown) = result?;
702 reorder.push(seq, picture, decode_idx, shown);935 reorder.push(seq, picture, decode_idx, shown);
703 reorder.drain(&mut sink)?;936 reorder.drain(&mut sink)?;
@@ -708,10 +941,10 @@ pub fn decode_stream_with_threads(
708 &header,941 &header,
709 seq,942 seq,
710 std::array::from_fn(|i| ref_slots[i].as_ref()),943 std::array::from_fn(|i| ref_slots[i].as_ref()),
711- &cdf_slots,944+ std::array::from_fn(|i| cdf_slots[i].as_ref()),
712- &seg_map_slots,945+ std::array::from_fn(|i| seg_map_slots[i].as_deref()),
713- &motion_field_slots,946+ &std::array::from_fn(|i| motion_field_slots[i].as_ref()),
714- &order_hint_slots,947+ order_hint_slots,
715 );948 );
716 let bit_depth = seq.bit_depth;949 let bit_depth = seq.bit_depth;
717 let FrameOutput {950 let FrameOutput {
@@ -730,18 +963,38 @@ pub fn decode_stream_with_threads(
730 final_dump.as_deref(),963 final_dump.as_deref(),
731 )?;964 )?;
732 pictures_decoded += 1;965 pictures_decoded += 1;
733- for i in 0..NUM_REF_FRAMES {966+ if threads > 1 {
734- if header.refresh_frame_flags & (1 << i) != 0 {967+ // lane-thread3: only a key frame reaches this inline path at
735- cdf_slots[i] = Some(stored_cdfs.clone());968+ // `threads > 1`, and the bank it fills is the promise array --
736- // Spec 7.18.3.1: synthesized grain is never stored for later969+ // already resolved, since the picture exists right here.
737- // prediction -- the reference bank always keeps the clean,970+ if header.refresh_frame_flags != 0 {
738- // pre-grain decode, even though the frame pushed onto the971+ let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue {
739- // caller's output below carries the grained picture.972+ picture: std::sync::Arc::new(picture.clone()),
740- ref_slots[i] = Some(picture.clone());973+ cdfs: stored_cdfs,
741- ref_arcs[i] = None;974+ motion_field,
742- motion_field_slots[i] = Some(motion_field.clone());975+ seg_map: decoded_seg_map,
743- seg_map_slots[i] = Some(decoded_seg_map.clone());976+ order_hint: header.order_hint,
744- order_hint_slots[i] = 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+ }
745 }998 }
746 }999 }
747 // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a1000 // lane-defon r1: a forward keyframe (aomenc `--enable-fwd-kf`) is a
@@ -777,8 +1030,14 @@ pub fn decode_stream_with_threads(
777 reorder.drain(&mut sink)?;1030 reorder.drain(&mut sink)?;
778 }1031 }
779 }1032 }
780- while in_flight > 0 {1033+ while in_flight_decodes + in_flight_shows > 0 {
781- collect_one(&rx, &mut in_flight, &mut reorder, &mut sink)?;1034+ collect_one(
1035+ &rx,
1036+ &mut in_flight_decodes,
1037+ &mut in_flight_shows,
1038+ &mut reorder,
1039+ &mut sink,
1040+ )?;
782 }1041 }
783 debug_assert!(reorder.pending.is_empty(), "a frame was never emitted");1042 debug_assert!(reorder.pending.is_empty(), "a frame was never emitted");
784 Ok(())1043 Ok(())
@@ -842,17 +1101,19 @@ pub(crate) struct RefSnapshot<'a> {
842 }1101 }
843 1102
844 impl<'a> RefSnapshot<'a> {1103 impl<'a> RefSnapshot<'a> {
845- /// Reads the banks for `header`. `refs` is passed in so that the1104+ /// Reads the banks for `header`. Every slot is passed in by reference so
846- /// single-threaded path can borrow the DPB pictures in place while the1105+ /// that the single-threaded path can borrow the DPB in place while a
847- /// worker path hands over its own `Arc` clones.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.
848 fn take(1109 fn take(
849 header: &FrameHeader,1110 header: &FrameHeader,
850 seq: SeqFlags,1111 seq: SeqFlags,
851 refs: [Option<&'a Picture>; NUM_REF_FRAMES],1112 refs: [Option<&'a Picture>; NUM_REF_FRAMES],
852- cdf_slots: &[Option<Cdfs>; NUM_REF_FRAMES],1113+ cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES],
853- seg_map_slots: &[Option<Vec<u8>>; NUM_REF_FRAMES],1114+ seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES],
854- motion_field_slots: &[Option<crate::motion_field::MotionField>; NUM_REF_FRAMES],1115+ motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES],
855- order_hint_slots: &[u32; NUM_REF_FRAMES],1116+ order_hint_slots: [u32; NUM_REF_FRAMES],
856 ) -> Self {1117 ) -> Self {
857 let primary = (header.primary_ref_frame != PRIMARY_REF_NONE)1118 let primary = (header.primary_ref_frame != PRIMARY_REF_NONE)
858 .then(|| header.ref_frame_idx[header.primary_ref_frame as usize] as usize);1119 .then(|| header.ref_frame_idx[header.primary_ref_frame as usize] as usize);
@@ -883,8 +1144,8 @@ impl<'a> RefSnapshot<'a> {
883 }1144 }
884 Self {1145 Self {
885 refs,1146 refs,
886- primary_cdfs: primary.and_then(|slot| cdf_slots[slot].clone()),1147+ primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),
887- prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].clone()),1148+ prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].map(<[u8]>::to_vec)),
888 tpl_field,1149 tpl_field,
889 ref_order_hints: std::array::from_fn(|i| {1150 ref_order_hints: std::array::from_fn(|i| {
890 order_hint_slots[header.ref_frame_idx[i] as usize]1151 order_hint_slots[header.ref_frame_idx[i] as usize]
@@ -32415,24 +32676,25 @@ mod tests {
32415 /// [`decode_stream_with_threads`] at 1 and at 4 threads and every sink32676 /// [`decode_stream_with_threads`] at 1 and at 4 threads and every sink
32416 /// call is compared -- decode index, shown flag, and all three planes.32677 /// call is compared -- decode index, shown flag, and all three planes.
32417 ///32678 ///
32418- /// `reelb_arf_witness.obu` is the one that proves the parallel path: 18 of32679+ /// `reelb_arf_witness.obu` is the one that proves the parallel path: it
32419- /// its 40 coded frames are leaves of the reference graph (shown,32680+ /// carries hidden alt-refs, which is exactly the case where "output in
32420- /// non-key, `refresh_frame_flags == 0`), so 18 frames really are decoded32681+ /// coded order" is not the same as "output in the order workers finish",
32421- /// off the main thread, and it carries hidden alt-refs, which is exactly32682+ /// and under lane-thread3's dependency-aware scheduling 39 of its 40
32422- /// the case where "output in coded order" is not the same as "output in32683+ /// coded frames (all but the key frame) are decoded off the main thread
32423- /// the order workers finish". `palette_screen_witness.obu` is the32684+ /// -- MORE than its 37 shown frames, which is the point: lane-thread2's
32424- /// complement: an 8-bit screen stream whose every coded frame refreshes a32685+ /// leaf rule dispatched 18. `palette_screen_witness.obu` is the
32425- /// slot, so at 4 threads it dispatches NOTHING and pins that the threaded32686+ /// complement, an 8-bit screen stream whose every coded frame refreshes a
32426- /// entry point is byte-identical on the inline path too. The dispatch32687+ /// slot: lane-thread2 dispatched NOTHING for it, lane-thread3 dispatches
32427- /// counter is asserted in both directions, so neither arm can pass32688+ /// all 14 of its non-key frames. Both counts are asserted exactly, plus
32428- /// vacuously.32689+ /// the "more than half the shown frames really ran on a worker" bound, so
32690+ /// neither arm can pass vacuously.
32429 #[test]32691 #[test]
32430 fn a_real_stream_decodes_identically_with_one_and_four_threads() {32692 fn a_real_stream_decodes_identically_with_one_and_four_threads() {
32431 const NAME: &str = "a_real_stream_decodes_identically_with_one_and_four_threads";32693 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)32694+ // (fixture, shown frames, frames a 4-thread run must dispatch)
32433- for (fixture, shown_frames, want_leaves) in [32695+ for (fixture, shown_frames, want_dispatched) in [
32434- ("fixtures/reelb_arf_witness.obu", 37usize, 18usize),32696+ ("fixtures/reelb_arf_witness.obu", 37usize, 39usize),
32435- ("fixtures/palette_screen_witness.obu", 15, 0),32697+ ("fixtures/palette_screen_witness.obu", 15, 14),
32436 ] {32698 ] {
32437 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture);32699 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(fixture);
32438 let stream = std::fs::read(&path)32700 let stream = std::fs::read(&path)
@@ -32447,12 +32709,16 @@ mod tests {
32447 out32709 out
32448 };32710 };
32449 let serial = run(1);32711 let serial = run(1);
32450- let before = leaf_frames_dispatched();32712+ let before = frames_dispatched();
32451 let parallel = run(4);32713 let parallel = run(4);
32452- let dispatched = leaf_frames_dispatched() - before;32714+ let dispatched = frames_dispatched() - before;
32453 assert_eq!(32715 assert_eq!(
32454- dispatched, want_leaves,32716+ dispatched, want_dispatched,
32455- "{NAME}: {fixture} dispatched {dispatched} leaf frames to workers, expected {want_leaves}"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"
32456 );32722 );
32457 assert_eq!(32723 assert_eq!(
32458 serial.iter().filter(|f| f.1).count(),32724 serial.iter().filter(|f| f.1).count(),