forge
Explore
Log in

Don't you dare go Hollow

Two-stage reference promises -- meta at the tile boundary, pixels after the filters

Browse files at this commit

b8ec726982a086ae514e9095e4ba432814cf9814Ahmet Kaan GümüşParent: a263e1e
  • perf
    • two-stage reference promises -- meta at the tile boundary, pixels after the filters
Show full message
perf(av1): two-stage reference promises -- meta at the tile boundary, pixels after the filters

A consumer frame used to wait for its references' FILTERED pixels before it
could start: the tile decoder built the reference `PlaneBuf`s at frame entry,
so the borrow existed from the first block even though the first pixel READ
comes later. Measured on a 4K stream (272 frames, 16/4/2): an inter tile
parses 4.2% of its own length before its first `ref_planes` call, and the
producer tail a consumer waits through (recon tail + filters + publish) is
8.2% of the decode chain.

So a reference slot is published in two stages. Stage 1 -- end-of-tile CDFs
(spec 7.20's `save_cdfs`, shared with the frame's own slot store), segment
map, motion field and picture size -- is fulfilled the moment the last tile
symbol is read, before the filters run; the motion field moves up with it
(it is built from the mode-info grid, no pixel). Stage 2 is the filtered
picture, fulfilled where the single promise was fulfilled before. A consumer
waits stage 1 for setup and carries a `RefPix` handle into the tile decoder,
which serves reference SIZES (`mc::scale_factor`) from stage-1 metadata and
waits stage 2 at the first `ref_planes` call.

DEADLOCK: unchanged in shape. Both stages of a producer are fulfilled by the
producer itself and wait on nothing but its own decode; every wait still
points from a later coded frame to an earlier one, so the wait graph is the
reference DAG. A failing frame now fails BOTH promises.

`EC_AV1_TWO_STAGE=0` restores the old publish point (meta after the filters).
crates/ec-av1/src/decode.rsmodified+219 -300
@@ -12963,7 +12963,6 @@ struct PlaneBuf<'a> {
12963 /// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already12963 /// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
12964 /// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/12964 /// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
12965 /// `ALTREF2`/`ALTREF`).12965 /// `ALTREF2`/`ALTREF`).
12966-type RefSlots<'a> = [Option<(&'a PlaneBuf<'a>, &'a PlaneBuf<'a>, &'a PlaneBuf<'a>)>; 8];
12967 12966
12968 impl PlaneBuf<'_> {12967 impl PlaneBuf<'_> {
12969 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/12968 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
@@ -23163,27 +23162,124 @@ fn read_single_ref(
23163 /// own doc. Called from [`decode_inter_block`] once its own `reference_select`23162 /// own doc. Called from [`decode_inter_block`] once its own `reference_select`
23164 /// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same23163 /// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
23165 /// way with a coarser (`LAST_FRAME`-only) neighbour shape.23164 /// way with a coarser (`LAST_FRAME`-only) neighbour shape.
23166-/// Resolves a compound reference's own planes -- the same `ref_frame ==23165+/// lane-twostage: this frame's references as DIMENSIONS now and PIXELS on
23167-/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup23166+/// demand. An inter tile's parse reads reference SIZES (`mc::scale_factor`)
23168-/// [`decode_inter_block`]'s single-ref path already does, factored out so23167+/// but touches no reference PIXEL until its first prediction -- measured 4.2%
23169-/// the compound path can call it twice (lane-av1comp).23168+/// of a 4K tile's parse into it -- so the pictures are resolved here, at the
23170-fn ref_planes<'a>(23169+/// first [`ref_planes`] call, rather than at frame entry. On the threaded
23170+/// path that resolution is a WAIT on the producing frame's pixels, which is
23171+/// what lets a consumer parse while its references are still being filtered.
23172+pub(crate) struct RefPix<'p> {
23173+ /// `(width, height)` per `ref_frame` index (`LAST_FRAME` = 1). `None` is
23174+ /// a slot this frame may not use: empty, or -- for a non-`LAST_FRAME`
23175+ /// slot -- not the same size as `LAST_FRAME`'s own picture (spec 7.9's
23176+ /// compatible-size rule, the filter the eager `owned_refs` array applied).
23177+ dims: [Option<(usize, usize)>; 8],
23178+ src: RefSrc<'p>,
23179+ bufs: std::sync::OnceLock<[Option<(PlaneBuf<'p>, PlaneBuf<'p>, PlaneBuf<'p>)>; 8]>,
23180+}
23181+
23182+/// Where a [`RefPix`] gets its pictures: already in hand, or behind a wait
23183+/// the caller owns (`stream.rs`'s reference promises).
23184+enum RefSrc<'p> {
23185+ Ready([Option<&'p Picture>; 8]),
23186+ Lazy(&'p (dyn Fn() -> Result<[Option<&'p Picture>; 8]> + Send + Sync + 'p)),
23187+}
23188+
23189+/// `LAST_FRAME`'s own index in a [`RefPix`] (spec 6.10.24).
23190+const LAST_REF: usize = 1;
23191+
23192+impl<'p> RefPix<'p> {
23193+ /// References already decoded: the single-threaded path and the test
23194+ /// entry points, where [`ref_planes`] never waits.
23195+ pub(crate) fn ready(refs: [Option<&'p Picture>; 8]) -> Self {
23196+ let dims = Self::compatible(std::array::from_fn(|i| {
23197+ refs[i].map(|p| (p.width, p.height))
23198+ }));
23199+ Self { dims, src: RefSrc::Ready(refs), bufs: std::sync::OnceLock::new() }
23200+ }
23201+
23202+ /// References whose sizes are known (from their producers' headers) but
23203+ /// whose pixels `wait` still has to produce.
23204+ pub(crate) fn lazy(
23205+ dims: [Option<(usize, usize)>; 8],
23206+ wait: &'p (dyn Fn() -> Result<[Option<&'p Picture>; 8]> + Send + Sync + 'p),
23207+ ) -> Self {
23208+ Self { dims: Self::compatible(dims), src: RefSrc::Lazy(wait), bufs: std::sync::OnceLock::new() }
23209+ }
23210+
23211+ /// Spec 7.9's compatible-size rule: a non-`LAST_FRAME` slot at a
23212+ /// different size than `LAST_FRAME`'s is treated as absent, exactly as
23213+ /// the eager `owned_refs.filter(..)` did.
23214+ fn compatible(mut dims: [Option<(usize, usize)>; 8]) -> [Option<(usize, usize)>; 8] {
23215+ let last = dims[LAST_REF];
23216+ for (i, d) in dims.iter_mut().enumerate() {
23217+ if i != LAST_REF && *d != last {
23218+ *d = None;
23219+ }
23220+ }
23221+ dims
23222+ }
23223+
23224+ /// This slot's picture size, without touching its pixels.
23225+ pub(crate) fn dims(&self, ref_frame: i8) -> Option<(usize, usize)> {
23226+ self.dims.get(ref_frame as usize).copied().flatten()
23227+ }
23228+
23229+ /// Every usable slot's three planes, resolving (and, on the threaded
23230+ /// path, waiting for) the pictures on the first call.
23231+ fn planes(&self) -> Result<&[Option<(PlaneBuf<'p>, PlaneBuf<'p>, PlaneBuf<'p>)>; 8]> {
23232+ if let Some(bufs) = self.bufs.get() {
23233+ return Ok(bufs);
23234+ }
23235+ let pics = match &self.src {
23236+ RefSrc::Ready(refs) => *refs,
23237+ RefSrc::Lazy(wait) => wait()?,
23238+ };
23239+ let dims = self.dims;
23240+ let bufs = std::array::from_fn(|i| {
23241+ dims[i].and(pics[i]).map(|g| {
23242+ (
23243+ whole_plane(&g.y, g.width, g.height),
23244+ whole_plane(&g.u, g.width / 2, g.height / 2),
23245+ whole_plane(&g.v, g.width / 2, g.height / 2),
23246+ )
23247+ })
23248+ });
23249+ let _ = self.bufs.set(bufs);
23250+ Ok(self.bufs.get().expect("the plane array was just set"))
23251+ }
23252+}
23253+
23254+/// A whole reference plane as a [`PlaneBuf`]: no tile window, no margin.
23255+fn whole_plane(data: &[u16], width: usize, height: usize) -> PlaneBuf<'_> {
23256+ PlaneBuf {
23257+ data: std::borrow::Cow::Borrowed(data),
23258+ width,
23259+ height,
23260+ true_width: width,
23261+ true_height: height,
23262+ tile_x0: 0,
23263+ tile_y0: 0,
23264+ tile_x1: width,
23265+ tile_y1: height,
23266+ }
23267+}
23268+
23269+/// Resolves a reference's own planes -- the `ref_frame -> picture` lookup
23270+/// [`decode_inter_block`]'s single-ref path does, factored out so the
23271+/// compound path can call it twice (lane-av1comp), and the point where
23272+/// lane-twostage's pixel wait happens.
23273+fn ref_planes<'a, 'p>(
23171 ref_frame: i8,23274 ref_frame: i8,
23172- ref_y: &'a PlaneBuf<'a>,23275+ refpix: &'a RefPix<'p>,
23173- ref_u: &'a PlaneBuf<'a>,23276+) -> Result<(&'a PlaneBuf<'p>, &'a PlaneBuf<'p>, &'a PlaneBuf<'p>)> {
23174- ref_v: &'a PlaneBuf<'a>,23277+ match refpix.planes()?.get(ref_frame as usize).and_then(Option::as_ref) {
23175- other_refs: &'a RefSlots,23278+ Some((y, u, v)) => Ok((y, u, v)),
23176-) -> Result<(&'a PlaneBuf<'a>, &'a PlaneBuf<'a>, &'a PlaneBuf<'a>)> {23279+ None => Err(unsupported(
23177- if ref_frame == LAST_FRAME {23280+ "a reference frame selected with no picture at this frame's own \
23178- Ok((ref_y, ref_u, ref_v))
23179- } else {
23180- match other_refs[ref_frame as usize] {
23181- Some((ry, ru, rv)) => Ok((ry, ru, rv)),
23182- None => Err(unsupported(
23183- "a reference frame selected with no picture at this frame's own \
23184 ref_frame_idx slot for it",23281 ref_frame_idx slot for it",
23185- )),23282+ )),
23186- }
23187 }23283 }
23188 }23284 }
23189 23285
@@ -23897,10 +23993,7 @@ fn obmc_blend(
23897 py: usize,23993 py: usize,
23898 cpx: usize,23994 cpx: usize,
23899 cpy: usize,23995 cpy: usize,
23900- ref_y: &PlaneBuf<'_>,23996+ refpix: &RefPix<'_>,
23901- ref_u: &PlaneBuf<'_>,
23902- ref_v: &PlaneBuf<'_>,
23903- other_refs: &RefSlots,
23904 interp_fixed: Option<mc::InterpFilterKind>,23997 interp_fixed: Option<mc::InterpFilterKind>,
23905 // lane-scaledref r1: this frame's own coded luma width -- each OBMC23998 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
23906 // neighbour is re-predicted against ITS OWN reference, which may be23999 // neighbour is re-predicted against ITS OWN reference, which may be
@@ -24011,7 +24104,7 @@ fn obmc_blend(
24011 );24104 );
24012 let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?;24105 let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?;
24013 ec_obmc_trace("above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);24106 ec_obmc_trace("above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);
24014- let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;24107+ let (ny, nu, nv) = ref_planes(nb.ref_frame, refpix)?;
24015 let nb_scale = mc::scale_factor(ny.width, frame_width);24108 let nb_scale = mc::scale_factor(ny.width, frame_width);
24016 if mi_col + off4 + span4 > mi_cols {24109 if mi_col + off4 + span4 > mi_cols {
24017 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));24110 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));
@@ -24047,7 +24140,7 @@ fn obmc_blend(
24047 );24140 );
24048 let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?;24141 let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?;
24049 ec_obmc_trace("left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);24142 ec_obmc_trace("left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);
24050- let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;24143+ let (ny, nu, nv) = ref_planes(nb.ref_frame, refpix)?;
24051 let nb_scale = mc::scale_factor(ny.width, frame_width);24144 let nb_scale = mc::scale_factor(ny.width, frame_width);
24052 if mi_row + off4 + span4 > mi_rows {24145 if mi_row + off4 + span4 > mi_rows {
24053 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));24146 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));
@@ -24480,16 +24573,13 @@ fn decode_inter_block(
24480 y: &mut PlaneBuf<'static>,24573 y: &mut PlaneBuf<'static>,
24481 u: &mut PlaneBuf<'static>,24574 u: &mut PlaneBuf<'static>,
24482 v: &mut PlaneBuf<'static>,24575 v: &mut PlaneBuf<'static>,
24483- ref_y: &PlaneBuf<'_>,24576+ refpix: &RefPix<'_>,
24484- ref_u: &PlaneBuf<'_>,
24485- ref_v: &PlaneBuf<'_>,
24486 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own24577 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
24487 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`24578 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
24488 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`24579 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
24489 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the24580 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
24490 // slot's still empty (an error-resilient stream, or too early in the24581 // slot's still empty (an error-resilient stream, or too early in the
24491 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.24582 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
24492- other_refs: &RefSlots,
24493 sign_bias_table: &SignBiasTable,24583 sign_bias_table: &SignBiasTable,
24494 // lane-gm r2: this frame header's own `global_motion` table (spec24584 // lane-gm r2: this frame header's own `global_motion` table (spec
24495 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`24585 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
@@ -24901,8 +24991,8 @@ fn decode_inter_block(
24901 if gm_nontrans_models && !gm_nontrans {24991 if gm_nontrans_models && !gm_nontrans {
24902 GM_NONTRANS_SMALL_SIDE_HITS.with(|c| c.set(c.get() + 1));24992 GM_NONTRANS_SMALL_SIDE_HITS.with(|c| c.set(c.get() + 1));
24903 }24993 }
24904- let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;24994+ let (py0, pu0, pv0) = ref_planes(ref0, refpix)?;
24905- let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;24995+ let (py1, pu1, pv1) = ref_planes(ref1, refpix)?;
24906 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is24996 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is
24907 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and24997 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and
24908 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from24998 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from
@@ -24944,7 +25034,7 @@ fn decode_inter_block(
24944 // scaled (superres) is predicted translationally while its25034 // scaled (superres) is predicted translationally while its
24945 // sibling may still warp.25035 // sibling may still warp.
24946 let ref_unscaled = |rf: i8| {25036 let ref_unscaled = |rf: i8| {
24947- ref_planes(rf, ref_y, ref_u, ref_v, other_refs)25037+ ref_planes(rf, refpix)
24948 .is_ok_and(|(py, _, _)| {25038 .is_ok_and(|(py, _, _)| {
24949 mc::scale_factor(py.width, frame_width) == mc::REF_NO_SCALE25039 mc::scale_factor(py.width, frame_width) == mc::REF_NO_SCALE
24950 })25040 })
@@ -26025,19 +26115,7 @@ fn decode_inter_block(
26025 // below same as every other non-`LAST_FRAME` reference. lane-av1refs26115 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
26026 // widens this from GOLDEN alone to every reference `read_single_ref`26116 // widens this from GOLDEN alone to every reference `read_single_ref`
26027 // can name.26117 // can name.
26028- let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {26118+ let (py_ref, pu_ref, pv_ref) = ref_planes(ref_frame, refpix)?;
26029- (ref_y, ref_u, ref_v)
26030- } else {
26031- match other_refs[ref_frame as usize] {
26032- Some((ry, ru, rv)) => (ry, ru, rv),
26033- None => {
26034- return Err(unsupported(
26035- "a reference frame selected with no picture at this frame's own \
26036- ref_frame_idx slot for it",
26037- ));
26038- }
26039- }
26040- };
26041 26119
26042 let (mi_row, mi_col) = (rmi, cmi);26120 let (mi_row, mi_col) = (rmi, cmi);
26043 // lane-rect r2: the mv stack must be queried with the block's26121 // lane-rect r2: the mv stack must be queried with the block's
@@ -26834,10 +26912,7 @@ fn decode_inter_block(
26834 py,26912 py,
26835 cpx,26913 cpx,
26836 cpy,26914 cpy,
26837- ref_y,26915+ refpix,
26838- ref_u,
26839- ref_v,
26840- other_refs,
26841 interp_fixed,26916 interp_fixed,
26842 frame_width,26917 frame_width,
26843 &mut pred_y,26918 &mut pred_y,
@@ -26866,7 +26941,7 @@ fn decode_inter_block(
26866 // reference was scaled, which silently left the whole-block26941 // reference was scaled, which silently left the whole-block
26867 // prediction in place instead of refusing. It scales off the26942 // prediction in place instead of refusing. It scales off the
26868 // PREVIOUS strip's own reference, not this block's.26943 // PREVIOUS strip's own reference, not this block's.
26869- let (prev_y_plane, prev_u, prev_v_plane) = ref_planes(prev_ref, ref_y, ref_u, ref_v, other_refs)?;26944+ let (prev_y_plane, prev_u, prev_v_plane) = ref_planes(prev_ref, refpix)?;
26870 let prev_scale = mc::scale_factor(prev_y_plane.width, frame_width);26945 let prev_scale = mc::scale_factor(prev_y_plane.width, frame_width);
26871 for (src, dst) in [(prev_u, &mut pred_u), (prev_v_plane, &mut pred_v)] {26946 for (src, dst) in [(prev_u, &mut pred_u), (prev_v_plane, &mut pred_v)] {
26872 let mut piece = vec![0u16; piece_w * piece_h];26947 let mut piece = vec![0u16; piece_w * piece_h];
@@ -28267,10 +28342,7 @@ fn decode_inter_sub8_split4(
28267 y: &mut PlaneBuf<'static>,28342 y: &mut PlaneBuf<'static>,
28268 u: &mut PlaneBuf<'static>,28343 u: &mut PlaneBuf<'static>,
28269 v: &mut PlaneBuf<'static>,28344 v: &mut PlaneBuf<'static>,
28270- ref_y: &PlaneBuf<'_>,28345+ refpix: &RefPix<'_>,
28271- ref_u: &PlaneBuf<'_>,
28272- ref_v: &PlaneBuf<'_>,
28273- other_refs: &RefSlots,
28274 sign_bias_table: &SignBiasTable,28346 sign_bias_table: &SignBiasTable,
28275 global_motion: &[ec_av1_syntax::WarpParams; 7],28347 global_motion: &[ec_av1_syntax::WarpParams; 7],
28276 base_q_idx: u8,28348 base_q_idx: u8,
@@ -28388,7 +28460,7 @@ fn decode_inter_sub8_split4(
28388 neighbours.left_ref[rmi],28460 neighbours.left_ref[rmi],
28389 neighbours.left_ref1[rmi],28461 neighbours.left_ref1[rmi],
28390 );28462 );
28391- let (sref_y, _sref_u, _sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;28463+ let (sref_y, _sref_u, _sref_v) = ref_planes(ref_frame, refpix)?;
28392 // lane-t900 r28: refusal lifted -- this sub-block's own reference may28464 // lane-t900 r28: refusal lifted -- this sub-block's own reference may
28393 // be scaled (superres); spec 7.11.3.3's walk is per reference, and28465 // be scaled (superres); spec 7.11.3.3's walk is per reference, and
28394 // each of the group's pieces (luma and its 2x2 chroma) carries its28466 // each of the group's pieces (luma and its 2x2 chroma) carries its
@@ -28658,7 +28730,7 @@ fn decode_inter_sub8_split4(
28658 continue;28730 continue;
28659 };28731 };
28660 let (piece_ref_y, sref_u, sref_v) =28732 let (piece_ref_y, sref_u, sref_v) =
28661- ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;28733+ ref_planes(ref_frame, refpix)?;
28662 let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width);28734 let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width);
28663 let (ox, oy) = if mixed {28735 let (ox, oy) = if mixed {
28664 (cpx, cpy)28736 (cpx, cpy)
@@ -29222,10 +29294,7 @@ fn decode_inter_sub8_rect2(
29222 y: &mut PlaneBuf<'static>,29294 y: &mut PlaneBuf<'static>,
29223 u: &mut PlaneBuf<'static>,29295 u: &mut PlaneBuf<'static>,
29224 v: &mut PlaneBuf<'static>,29296 v: &mut PlaneBuf<'static>,
29225- ref_y: &PlaneBuf<'_>,29297+ refpix: &RefPix<'_>,
29226- ref_u: &PlaneBuf<'_>,
29227- ref_v: &PlaneBuf<'_>,
29228- other_refs: &RefSlots,
29229 sign_bias_table: &SignBiasTable,29298 sign_bias_table: &SignBiasTable,
29230 global_motion: &[ec_av1_syntax::WarpParams; 7],29299 global_motion: &[ec_av1_syntax::WarpParams; 7],
29231 base_q_idx: u8,29300 base_q_idx: u8,
@@ -29361,7 +29430,7 @@ fn decode_inter_sub8_rect2(
29361 neighbours.left_ref[rmi],29430 neighbours.left_ref[rmi],
29362 neighbours.left_ref1[rmi],29431 neighbours.left_ref1[rmi],
29363 );29432 );
29364- let (sref_y, _, _) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;29433+ let (sref_y, _, _) = ref_planes(ref_frame, refpix)?;
29365 // lane-t900 r28: refusal lifted -- see the split arm above.29434 // lane-t900 r28: refusal lifted -- see the split arm above.
29366 let luma_scale = mc::scale_factor(sref_y.width, frame_width);29435 let luma_scale = mc::scale_factor(sref_y.width, frame_width);
29367 if luma_scale != mc::REF_NO_SCALE {29436 if luma_scale != mc::REF_NO_SCALE {
@@ -29673,7 +29742,7 @@ fn decode_inter_sub8_rect2(
29673 continue;29742 continue;
29674 };29743 };
29675 let (piece_ref_y, sref_u, sref_v) =29744 let (piece_ref_y, sref_u, sref_v) =
29676- ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;29745+ ref_planes(ref_frame, refpix)?;
29677 let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width);29746 let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width);
29678 let (ox, oy) = if mixed {29747 let (ox, oy) = if mixed {
29679 (cpx, cpy)29748 (cpx, cpy)
@@ -29827,10 +29896,7 @@ fn decode_inter_block8(
29827 y: &mut PlaneBuf<'static>,29896 y: &mut PlaneBuf<'static>,
29828 u: &mut PlaneBuf<'static>,29897 u: &mut PlaneBuf<'static>,
29829 v: &mut PlaneBuf<'static>,29898 v: &mut PlaneBuf<'static>,
29830- ref_y: &PlaneBuf<'_>,29899+ refpix: &RefPix<'_>,
29831- ref_u: &PlaneBuf<'_>,
29832- ref_v: &PlaneBuf<'_>,
29833- other_refs: &RefSlots,
29834 base_q_idx: u8,29900 base_q_idx: u8,
29835 scan8: &[u16],29901 scan8: &[u16],
29836 scan4: &[u16],29902 scan4: &[u16],
@@ -30292,8 +30358,8 @@ fn decode_inter_block8(
30292 COMPOUND8_FILTER_HITS.with(|c| c.set(c.get() + 1));30358 COMPOUND8_FILTER_HITS.with(|c| c.set(c.get() + 1));
30293 }30359 }
30294 30360
30295- let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;30361+ let (py0, pu0, pv0) = ref_planes(ref0, refpix)?;
30296- let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;30362+ let (py1, pu1, pv1) = ref_planes(ref1, refpix)?;
30297 let scale0 = mc::scale_factor(py0.width, frame_width);30363 let scale0 = mc::scale_factor(py0.width, frame_width);
30298 let scale1 = mc::scale_factor(py1.width, frame_width);30364 let scale1 = mc::scale_factor(py1.width, frame_width);
30299 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {30365 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
@@ -30346,7 +30412,7 @@ fn decode_inter_block8(
30346 // lane-t900 r28: same per-slot `allow_warp` scale bail-out as30412 // lane-t900 r28: same per-slot `allow_warp` scale bail-out as
30347 // the 16x16-and-bigger compound path above.30413 // the 16x16-and-bigger compound path above.
30348 let leaf_ref_unscaled = |rf: i8| {30414 let leaf_ref_unscaled = |rf: i8| {
30349- ref_planes(rf, ref_y, ref_u, ref_v, other_refs)30415+ ref_planes(rf, refpix)
30350 .is_ok_and(|(py, _, _)| {30416 .is_ok_and(|(py, _, _)| {
30351 mc::scale_factor(py.width, frame_width) == mc::REF_NO_SCALE30417 mc::scale_factor(py.width, frame_width) == mc::REF_NO_SCALE
30352 })30418 })
@@ -30721,7 +30787,7 @@ fn decode_inter_block8(
30721 neighbours.left_ref1[rmi],30787 neighbours.left_ref1[rmi],
30722 );30788 );
30723 leaf_refs = (ref_frame, None);30789 leaf_refs = (ref_frame, None);
30724- let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;30790+ let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, refpix)?;
30725 30791
30726 let (mi_row, mi_col) = leaf_mi;30792 let (mi_row, mi_col) = leaf_mi;
30727 // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS30793 // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS
@@ -31156,10 +31222,7 @@ fn decode_inter_block8(
31156 py,31222 py,
31157 cpx,31223 cpx,
31158 cpy,31224 cpy,
31159- ref_y,31225+ refpix,
31160- ref_u,
31161- ref_v,
31162- other_refs,
31163 interp_fixed,31226 interp_fixed,
31164 frame_width,31227 frame_width,
31165 &mut pred_y,31228 &mut pred_y,
@@ -31861,8 +31924,7 @@ pub(crate) fn decode_inter_frame_tile(
31861 base_q_idx: u8,31924 base_q_idx: u8,
31862 frame_width: u32,31925 frame_width: u32,
31863 frame_height: u32,31926 frame_height: u32,
31864- reference: &Picture,31927+ refpix: &RefPix<'_>,
31865- other_refs: [Option<&Picture>; 8],
31866 cdef: &CdefParams,31928 cdef: &CdefParams,
31867 loop_filter: &LoopFilterParams,31929 loop_filter: &LoopFilterParams,
31868 allow_high_precision_mv: bool,31930 allow_high_precision_mv: bool,
@@ -31885,8 +31947,7 @@ pub(crate) fn decode_inter_frame_tile(
31885 crate::quant::QuantDeltas::default(),31947 crate::quant::QuantDeltas::default(),
31886 frame_width,31948 frame_width,
31887 frame_height,31949 frame_height,
31888- reference,31950+ refpix,
31889- other_refs,
31890 cdef,31951 cdef,
31891 loop_filter,31952 loop_filter,
31892 &LoopRestorationParams::default(),31953 &LoopRestorationParams::default(),
@@ -31918,7 +31979,9 @@ pub(crate) fn decode_inter_frame_tile(
31918 // `enable_filter_intra`: this crate's own encoder never writes the31979 // `enable_filter_intra`: this crate's own encoder never writes the
31919 // sequence bit (`encode.rs`), so no intra-in-inter block of a stream31980 // sequence bit (`encode.rs`), so no intra-in-inter block of a stream
31920 // reaching this entry point reads a `use_filter_intra` symbol.31981 // reaching this entry point reads a `use_filter_intra` symbol.
31921- false, fctx,31982+ false,
31983+ None,
31984+ fctx,
31922 )31985 )
31923 .map(|(picture, _, _)| picture)31986 .map(|(picture, _, _)| picture)
31924 }31987 }
@@ -31938,8 +32001,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
31938 deltas: crate::quant::QuantDeltas,32001 deltas: crate::quant::QuantDeltas,
31939 frame_width: u32,32002 frame_width: u32,
31940 frame_height: u32,32003 frame_height: u32,
31941- reference: &Picture,32004+ refpix: &RefPix<'_>,
31942- other_refs: [Option<&Picture>; 8],
31943 cdef: &CdefParams,32005 cdef: &CdefParams,
31944 loop_filter: &LoopFilterParams,32006 loop_filter: &LoopFilterParams,
31945 lr: &LoopRestorationParams,32007 lr: &LoopRestorationParams,
@@ -32006,8 +32068,18 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32006 // (spec 5.5.2), stashed in a thread-local with `tx_select` rather than32068 // (spec 5.5.2), stashed in a thread-local with `tx_select` rather than
32007 // threaded through `decode_inter_block`'s fifty parameters -- read by the32069 // threaded through `decode_inter_block`'s fifty parameters -- read by the
32008 // intra-in-inter arms' `read_filter_intra_mode_info`.32070 // intra-in-inter arms' `read_filter_intra_mode_info`.
32009- enable_filter_intra: bool, fctx: &crate::decode::FrameCtx,32071+ enable_filter_intra: bool,
32010-) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {32072+ // lane-twostage: called with this frame's own end-of-tile CDFs, motion
32073+ // field and picture size the moment its last tile symbol is read --
32074+ // BEFORE its filters run, so a frame that references this one can start
32075+ // parsing while this one is still being deblocked/CDEF'd/restored (it
32076+ // waits for the pixels themselves at its first prediction). `None`, and
32077+ // the motion field comes back in the return tuple as it always did:
32078+ // the single-threaded path, and a superres frame (whose final width is
32079+ // only known after the upscale).
32080+ stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>,
32081+ fctx: &crate::decode::FrameCtx,
32082+) -> Result<(Picture, Cdfs, Option<crate::motion_field::MotionField>)> {
32011 set_inter_tx_mode(tx_select, reduced_tx_set, enable_filter_intra, fctx);32083 set_inter_tx_mode(tx_select, reduced_tx_set, enable_filter_intra, fctx);
32012 let tpl_frame = tpl_field.map(|field| TplFrameArgs {32084 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
32013 field,32085 field,
@@ -32037,7 +32109,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32037 // refused every same-size reference (class av1-truesize-lane: true32109 // refused every same-size reference (class av1-truesize-lane: true
32038 // frame size vs mi-rounded). Height must still MATCH: AV1 superres32110 // frame size vs mi-rounded). Height must still MATCH: AV1 superres
32039 // never scales height, and no path here has a vertical scaling pass.32111 // never scales height, and no path here has a vertical scaling pass.
32040- if reference.height != frame_height as usize {32112+ if refpix.dims(1).is_none_or(|(_, h)| h != frame_height as usize) {
32041 return Err(unsupported(32113 return Err(unsupported(
32042 "a reference picture whose height does not match this frame's own true size",32114 "a reference picture whose height does not match this frame's own true size",
32043 ));32115 ));
@@ -32050,90 +32122,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32050 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);32122 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
32051 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);32123 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
32052 32124
32053- let ref_y = PlaneBuf {
32054- data: std::borrow::Cow::Borrowed(&reference.y),
32055- width: reference.width,
32056- height: reference.height,
32057- true_width: reference.width,
32058- true_height: reference.height,
32059- tile_x0: 0,
32060- tile_y0: 0,
32061- tile_x1: reference.width,
32062- tile_y1: reference.height,
32063- };
32064- let ref_u = PlaneBuf {
32065- data: std::borrow::Cow::Borrowed(&reference.u),
32066- width: reference.width / 2,
32067- height: reference.height / 2,
32068- true_width: reference.width / 2,
32069- true_height: reference.height / 2,
32070- tile_x0: 0,
32071- tile_y0: 0,
32072- tile_x1: reference.width / 2,
32073- tile_y1: reference.height / 2,
32074- };
32075- let ref_v = PlaneBuf {
32076- data: std::borrow::Cow::Borrowed(&reference.v),
32077- width: reference.width / 2,
32078- height: reference.height / 2,
32079- true_width: reference.width / 2,
32080- true_height: reference.height / 2,
32081- tile_x0: 0,
32082- tile_y0: 0,
32083- tile_x1: reference.width / 2,
32084- tile_y1: reference.height / 2,
32085- };
32086- // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
32087- // names a live DPB slot for (lane-av1refs: generalised from the old
32088- // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
32089- // now per-reference). `decode_inter_block` refuses by name when the
32090- // block it is decoding selects an index that is still `None` here
32091- // (spec 7.9 requires every *active* reference be a compatible size;
32092- // an inactive one this frame never selects is simply left `None`).
32093- let owned_refs: [Option<(PlaneBuf<'_>, PlaneBuf<'_>, PlaneBuf<'_>)>; 8] = std::array::from_fn(|i| {
32094- other_refs[i]
32095- .filter(|g| g.width == reference.width && g.height == reference.height)
32096- .map(|g| {
32097- (
32098- PlaneBuf {
32099- data: std::borrow::Cow::Borrowed(&g.y),
32100- width: g.width,
32101- height: g.height,
32102- true_width: g.width,
32103- true_height: g.height,
32104- tile_x0: 0,
32105- tile_y0: 0,
32106- tile_x1: g.width,
32107- tile_y1: g.height,
32108- },
32109- PlaneBuf {
32110- data: std::borrow::Cow::Borrowed(&g.u),
32111- width: g.width / 2,
32112- height: g.height / 2,
32113- true_width: g.width / 2,
32114- true_height: g.height / 2,
32115- tile_x0: 0,
32116- tile_y0: 0,
32117- tile_x1: g.width / 2,
32118- tile_y1: g.height / 2,
32119- },
32120- PlaneBuf {
32121- data: std::borrow::Cow::Borrowed(&g.v),
32122- width: g.width / 2,
32123- height: g.height / 2,
32124- true_width: g.width / 2,
32125- true_height: g.height / 2,
32126- tile_x0: 0,
32127- tile_y0: 0,
32128- tile_x1: g.width / 2,
32129- tile_y1: g.height / 2,
32130- },
32131- )
32132- })
32133- });
32134- let ref_slots: RefSlots =
32135- std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
32136-
32137 let mut y = PlaneBuf {32125 let mut y = PlaneBuf {
32138 data: std::borrow::Cow::Owned(fresh_plane(width * height)),32126 data: std::borrow::Cow::Owned(fresh_plane(width * height)),
32139 width,32127 width,
@@ -32494,10 +32482,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32494 &mut y,32482 &mut y,
32495 &mut u,32483 &mut u,
32496 &mut v,32484 &mut v,
32497- &ref_y,32485+ refpix,
32498- &ref_u,
32499- &ref_v,
32500- &ref_slots,
32501 &sign_bias_table,32486 &sign_bias_table,
32502 &global_motion,32487 &global_motion,
32503 base_q_idx,32488 base_q_idx,
@@ -32567,10 +32552,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32567 &mut y,32552 &mut y,
32568 &mut u,32553 &mut u,
32569 &mut v,32554 &mut v,
32570- &ref_y,32555+ refpix,
32571- &ref_u,
32572- &ref_v,
32573- &ref_slots,
32574 base_q_idx,32556 base_q_idx,
32575 &scan8,32557 &scan8,
32576 &scan4,32558 &scan4,
@@ -32869,10 +32851,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32869 &mut y,32851 &mut y,
32870 &mut u,32852 &mut u,
32871 &mut v,32853 &mut v,
32872- &ref_y,32854+ refpix,
32873- &ref_u,
32874- &ref_v,
32875- &ref_slots,
32876 &sign_bias_table,32855 &sign_bias_table,
32877 &global_motion,32856 &global_motion,
32878 base_q_idx,32857 base_q_idx,
@@ -33040,10 +33019,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33040 &mut y,33019 &mut y,
33041 &mut u,33020 &mut u,
33042 &mut v,33021 &mut v,
33043- &ref_y,33022+ refpix,
33044- &ref_u,
33045- &ref_v,
33046- &ref_slots,
33047 &sign_bias_table,33023 &sign_bias_table,
33048 &global_motion,33024 &global_motion,
33049 base_q_idx,33025 base_q_idx,
@@ -33190,10 +33166,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33190 &mut y,33166 &mut y,
33191 &mut u,33167 &mut u,
33192 &mut v,33168 &mut v,
33193- &ref_y,33169+ refpix,
33194- &ref_u,
33195- &ref_v,
33196- &ref_slots,
33197 &sign_bias_table,33170 &sign_bias_table,
33198 &global_motion,33171 &global_motion,
33199 base_q_idx,33172 base_q_idx,
@@ -33301,10 +33274,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33301 &mut y,33274 &mut y,
33302 &mut u,33275 &mut u,
33303 &mut v,33276 &mut v,
33304- &ref_y,33277+ refpix,
33305- &ref_u,
33306- &ref_v,
33307- &ref_slots,
33308 &sign_bias_table,33278 &sign_bias_table,
33309 &global_motion,33279 &global_motion,
33310 base_q_idx,33280 base_q_idx,
@@ -33388,10 +33358,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33388 &mut y,33358 &mut y,
33389 &mut u,33359 &mut u,
33390 &mut v,33360 &mut v,
33391- &ref_y,33361+ refpix,
33392- &ref_u,
33393- &ref_v,
33394- &ref_slots,
33395 &sign_bias_table,33362 &sign_bias_table,
33396 &global_motion,33363 &global_motion,
33397 base_q_idx,33364 base_q_idx,
@@ -33632,11 +33599,11 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33632 // 7.11.3.3's scaled walk. The counter is what33599 // 7.11.3.3's scaled walk. The counter is what
33633 // proves a gate actually reached a scaled33600 // proves a gate actually reached a scaled
33634 // leaf rather than a same-size reference.33601 // leaf rather than a same-size reference.
33635- if ref_y.width != frame_width as usize33602+ if (1..8).any(|rf| {
33636- || ref_slots.iter().flatten().any(|(py, _, _)| {33603+ refpix.dims(rf).is_some_and(|(w, _)| {
33637- py.width != frame_width as usize33604+ w != frame_width as usize
33638 })33605 })
33639- {33606+ }) {
33640 SCALED_LEAF8_HITS.with(|c| c.set(c.get() + 1));33607 SCALED_LEAF8_HITS.with(|c| c.set(c.get() + 1));
33641 }33608 }
33642 let mut prev_leaves: Vec<((usize, usize), bool, bool, i8, Option<i8>)> = Vec::new();33609 let mut prev_leaves: Vec<((usize, usize), bool, bool, i8, Option<i8>)> = Vec::new();
@@ -33659,10 +33626,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33659 &mut y,33626 &mut y,
33660 &mut u,33627 &mut u,
33661 &mut v,33628 &mut v,
33662- &ref_y,33629+ refpix,
33663- &ref_u,
33664- &ref_v,
33665- &ref_slots,
33666 &sign_bias_table,33630 &sign_bias_table,
33667 &global_motion,33631 &global_motion,
33668 base_q_idx,33632 base_q_idx,
@@ -33700,10 +33664,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33700 &mut y,33664 &mut y,
33701 &mut u,33665 &mut u,
33702 &mut v,33666 &mut v,
33703- &ref_y,33667+ refpix,
33704- &ref_u,
33705- &ref_v,
33706- &ref_slots,
33707 &sign_bias_table,33668 &sign_bias_table,
33708 &global_motion,33669 &global_motion,
33709 base_q_idx,33670 base_q_idx,
@@ -33739,10 +33700,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33739 &mut y,33700 &mut y,
33740 &mut u,33701 &mut u,
33741 &mut v,33702 &mut v,
33742- &ref_y,33703+ refpix,
33743- &ref_u,
33744- &ref_v,
33745- &ref_slots,
33746 base_q_idx,33704 base_q_idx,
33747 &scan8,33705 &scan8,
33748 &scan4,33706 &scan4,
@@ -33836,10 +33794,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33836 &mut y,33794 &mut y,
33837 &mut u,33795 &mut u,
33838 &mut v,33796 &mut v,
33839- &ref_y,33797+ refpix,
33840- &ref_u,
33841- &ref_v,
33842- &ref_slots,
33843 &sign_bias_table,33798 &sign_bias_table,
33844 &global_motion,33799 &global_motion,
33845 base_q_idx,33800 base_q_idx,
@@ -33889,10 +33844,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33889 &mut y,33844 &mut y,
33890 &mut u,33845 &mut u,
33891 &mut v,33846 &mut v,
33892- &ref_y,33847+ refpix,
33893- &ref_u,
33894- &ref_v,
33895- &ref_slots,
33896 &sign_bias_table,33848 &sign_bias_table,
33897 &global_motion,33849 &global_motion,
33898 base_q_idx,33850 base_q_idx,
@@ -33943,10 +33895,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33943 &mut y,33895 &mut y,
33944 &mut u,33896 &mut u,
33945 &mut v,33897 &mut v,
33946- &ref_y,33898+ refpix,
33947- &ref_u,
33948- &ref_v,
33949- &ref_slots,
33950 &sign_bias_table,33899 &sign_bias_table,
33951 &global_motion,33900 &global_motion,
33952 base_q_idx,33901 base_q_idx,
@@ -34007,10 +33956,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34007 &mut y,33956 &mut y,
34008 &mut u,33957 &mut u,
34009 &mut v,33958 &mut v,
34010- &ref_y,33959+ refpix,
34011- &ref_u,
34012- &ref_v,
34013- &ref_slots,
34014 &sign_bias_table,33960 &sign_bias_table,
34015 &global_motion,33961 &global_motion,
34016 base_q_idx,33962 base_q_idx,
@@ -34063,10 +34009,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34063 &mut y,34009 &mut y,
34064 &mut u,34010 &mut u,
34065 &mut v,34011 &mut v,
34066- &ref_y,34012+ refpix,
34067- &ref_u,
34068- &ref_v,
34069- &ref_slots,
34070 &sign_bias_table,34013 &sign_bias_table,
34071 &global_motion,34014 &global_motion,
34072 base_q_idx,34015 base_q_idx,
@@ -34120,10 +34063,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34120 &mut y,34063 &mut y,
34121 &mut u,34064 &mut u,
34122 &mut v,34065 &mut v,
34123- &ref_y,34066+ refpix,
34124- &ref_u,
34125- &ref_v,
34126- &ref_slots,
34127 &sign_bias_table,34067 &sign_bias_table,
34128 &global_motion,34068 &global_motion,
34129 base_q_idx,34069 base_q_idx,
@@ -34176,10 +34116,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34176 &mut y,34116 &mut y,
34177 &mut u,34117 &mut u,
34178 &mut v,34118 &mut v,
34179- &ref_y,34119+ refpix,
34180- &ref_u,
34181- &ref_v,
34182- &ref_slots,
34183 &sign_bias_table,34120 &sign_bias_table,
34184 &global_motion,34121 &global_motion,
34185 base_q_idx,34122 base_q_idx,
@@ -34234,10 +34171,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34234 &mut y,34171 &mut y,
34235 &mut u,34172 &mut u,
34236 &mut v,34173 &mut v,
34237- &ref_y,34174+ refpix,
34238- &ref_u,
34239- &ref_v,
34240- &ref_slots,
34241 &sign_bias_table,34175 &sign_bias_table,
34242 &global_motion,34176 &global_motion,
34243 base_q_idx,34177 base_q_idx,
@@ -34287,10 +34221,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34287 &mut y,34221 &mut y,
34288 &mut u,34222 &mut u,
34289 &mut v,34223 &mut v,
34290- &ref_y,34224+ refpix,
34291- &ref_u,
34292- &ref_v,
34293- &ref_slots,
34294 &sign_bias_table,34225 &sign_bias_table,
34295 &global_motion,34226 &global_motion,
34296 base_q_idx,34227 base_q_idx,
@@ -34340,10 +34271,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34340 &mut y,34271 &mut y,
34341 &mut u,34272 &mut u,
34342 &mut v,34273 &mut v,
34343- &ref_y,34274+ refpix,
34344- &ref_u,
34345- &ref_v,
34346- &ref_slots,
34347 &sign_bias_table,34275 &sign_bias_table,
34348 &global_motion,34276 &global_motion,
34349 base_q_idx,34277 base_q_idx,
@@ -34395,10 +34323,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34395 &mut y,34323 &mut y,
34396 &mut u,34324 &mut u,
34397 &mut v,34325 &mut v,
34398- &ref_y,34326+ refpix,
34399- &ref_u,
34400- &ref_v,
34401- &ref_slots,
34402 &sign_bias_table,34327 &sign_bias_table,
34403 &global_motion,34328 &global_motion,
34404 base_q_idx,34329 base_q_idx,
@@ -34448,10 +34373,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34448 &mut y,34373 &mut y,
34449 &mut u,34374 &mut u,
34450 &mut v,34375 &mut v,
34451- &ref_y,34376+ refpix,
34452- &ref_u,
34453- &ref_v,
34454- &ref_slots,
34455 &sign_bias_table,34377 &sign_bias_table,
34456 &global_motion,34378 &global_motion,
34457 base_q_idx,34379 base_q_idx,
@@ -34501,10 +34423,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34501 &mut y,34423 &mut y,
34502 &mut u,34424 &mut u,
34503 &mut v,34425 &mut v,
34504- &ref_y,34426+ refpix,
34505- &ref_u,
34506- &ref_v,
34507- &ref_slots,
34508 &sign_bias_table,34427 &sign_bias_table,
34509 &global_motion,34428 &global_motion,
34510 base_q_idx,34429 base_q_idx,
@@ -34557,10 +34476,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34557 &mut y,34476 &mut y,
34558 &mut u,34477 &mut u,
34559 &mut v,34478 &mut v,
34560- &ref_y,34479+ refpix,
34561- &ref_u,
34562- &ref_v,
34563- &ref_slots,
34564 &sign_bias_table,34480 &sign_bias_table,
34565 &global_motion,34481 &global_motion,
34566 base_q_idx,34482 base_q_idx,
@@ -34606,10 +34522,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34606 &mut y,34522 &mut y,
34607 &mut u,34523 &mut u,
34608 &mut v,34524 &mut v,
34609- &ref_y,34525+ refpix,
34610- &ref_u,
34611- &ref_v,
34612- &ref_slots,
34613 &sign_bias_table,34526 &sign_bias_table,
34614 &global_motion,34527 &global_motion,
34615 base_q_idx,34528 base_q_idx,
@@ -34659,10 +34572,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34659 &mut y,34572 &mut y,
34660 &mut u,34573 &mut u,
34661 &mut v,34574 &mut v,
34662- &ref_y,34575+ refpix,
34663- &ref_u,
34664- &ref_v,
34665- &ref_slots,
34666 &sign_bias_table,34576 &sign_bias_table,
34667 &global_motion,34577 &global_motion,
34668 base_q_idx,34578 base_q_idx,
@@ -34766,6 +34676,28 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34766 }34676 }
34767 }34677 }
34768 crate::timeline::recon_done();34678 crate::timeline::recon_done();
34679+ // lane-twostage: the motion field is built from the mode-info grid alone
34680+ // (no pixel), so it moves up here with the CDFs -- everything a
34681+ // consuming frame's SETUP needs, published before this frame's filters.
34682+ let mut motion_field = Some(build_motion_field(
34683+ &grid,
34684+ mi_cols as usize,
34685+ mi_rows as usize,
34686+ order_hint,
34687+ order_hint_bits,
34688+ ref_order_hints,
34689+ fctx,
34690+ ));
34691+ if let Some(stage1) = stage1
34692+ && superres(fctx).is_none()
34693+ {
34694+ stage1(
34695+ result_cdfs.clone(),
34696+ motion_field.take().expect("the motion field was just built"),
34697+ frame_width as usize,
34698+ frame_height as usize,
34699+ );
34700+ }
34769 34701
34770 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's34702 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
34771 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against34703 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
@@ -34912,15 +34844,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34912 }34844 }
34913 34845
34914 crate::timeline::filters_done();34846 crate::timeline::filters_done();
34915- let motion_field = build_motion_field(
34916- &grid,
34917- mi_cols as usize,
34918- mi_rows as usize,
34919- order_hint,
34920- order_hint_bits,
34921- ref_order_hints,
34922- fctx,
34923- );
34924 34847
34925 let (fw, fh) = (lr_w, frame_height as usize);34848 let (fw, fh) = (lr_w, frame_height as usize);
34926 // An upscaled frame is already at its final size with no mi-aligned34849 // An upscaled frame is already at its final size with no mi-aligned
@@ -35772,27 +35695,25 @@ mod tests {
35772 fn a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name() {35695 fn a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name() {
35773 const REFUSAL: &str =35696 const REFUSAL: &str =
35774 "a reference frame selected with no picture at this frame's own ref_frame_idx slot";35697 "a reference frame selected with no picture at this frame's own ref_frame_idx slot";
35775- let plane = PlaneBuf {35698+ let pic = Picture {
35776- data: std::borrow::Cow::Owned(vec![0u16; 16]),
35777 width: 4,35699 width: 4,
35778 height: 4,35700 height: 4,
35779- true_width: 4,35701+ y: vec![0u16; 16],
35780- true_height: 4,35702+ u: vec![0u16; 4],
35781- tile_x0: 0,35703+ v: vec![0u16; 4],
35782- tile_y0: 0,
35783- tile_x1: 4,
35784- tile_y1: 4,
35785 };35704 };
35786- let empty: RefSlots = [None; 8];35705+ let mut refs: [Option<&Picture>; 8] = [None; 8];
35706+ refs[1] = Some(&pic);
35707+ let refpix = RefPix::ready(refs);
35787 for ref_frame in [LAST2_FRAME, LAST3_FRAME, GOLDEN_FRAME, BWDREF_FRAME, ALTREF2_FRAME, ALTREF_FRAME] {35708 for ref_frame in [LAST2_FRAME, LAST3_FRAME, GOLDEN_FRAME, BWDREF_FRAME, ALTREF2_FRAME, ALTREF_FRAME] {
35788- let err = match ref_planes(ref_frame, &plane, &plane, &plane, &empty) {35709+ let err = match ref_planes(ref_frame, &refpix) {
35789 Ok(_) => panic!("ref {ref_frame}: an empty slot resolved to a picture"),35710 Ok(_) => panic!("ref {ref_frame}: an empty slot resolved to a picture"),
35790 Err(e) => e.to_string(),35711 Err(e) => e.to_string(),
35791 };35712 };
35792 assert!(err.contains(REFUSAL), "ref {ref_frame}: expected {REFUSAL:?}, got: {err}");35713 assert!(err.contains(REFUSAL), "ref {ref_frame}: expected {REFUSAL:?}, got: {err}");
35793 }35714 }
35794 // `LAST_FRAME` never consults the slots: `decode_stream` checked it.35715 // `LAST_FRAME` never consults the slots: `decode_stream` checked it.
35795- let Ok((y, _, _)) = ref_planes(LAST_FRAME, &plane, &plane, &plane, &empty) else {35716+ let Ok((y, _, _)) = ref_planes(LAST_FRAME, &refpix) else {
35796 panic!("LAST_FRAME resolves to the frame's own reference planes")35717 panic!("LAST_FRAME resolves to the frame's own reference planes")
35797 };35718 };
35798 assert_eq!(y.width, 4);35719 assert_eq!(y.width, 4);
@@ -36581,9 +36502,7 @@ mod tests {
36581 &mut y,36502 &mut y,
36582 &mut u,36503 &mut u,
36583 &mut v,36504 &mut v,
36584- &ref_y,36505+ refpix,
36585- &ref_u,
36586- &ref_v,
36587 &[None; 8],36506 &[None; 8],
36588 &NO_SIGN_BIAS,36507 &NO_SIGN_BIAS,
36589 &[ec_av1_syntax::WarpParams::default(); 7],36508 &[ec_av1_syntax::WarpParams::default(); 7],
crates/ec-av1/src/stream.rsmodified+202 -58
@@ -343,7 +343,12 @@ pub fn frames_dispatched() -> usize {
343 /// `refresh_frame_flags` names (spec 7.20), as one shared, never-mutated343 /// `refresh_frame_flags` names (spec 7.20), as one shared, never-mutated
344 /// object -- so a slot costs an `Arc` clone instead of a picture copy.344 /// object -- so a slot costs an `Arc` clone instead of a picture copy.
345 struct SlotValue {345 struct SlotValue {
346- picture: std::sync::Arc<Picture>,346+ /// lane-twostage: this frame's FILTERED pixels, still being produced
347+ /// when the rest of this value is published.
348+ pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>>,
349+ /// The size those pixels will have, known from the tile decode.
350+ width: usize,
351+ height: usize,
347 cdfs: Cdfs,352 cdfs: Cdfs,
348 motion_field: crate::motion_field::MotionField,353 motion_field: crate::motion_field::MotionField,
349 seg_map: Vec<u8>,354 seg_map: Vec<u8>,
@@ -371,18 +376,18 @@ struct SlotValue {
371 /// Each dispatched frame gets its own thread, so a blocked waiter never holds376 /// Each dispatched frame gets its own thread, so a blocked waiter never holds
372 /// a resource its producer needs. A producer that errors or panics marks its377 /// a resource its producer needs. A producer that errors or panics marks its
373 /// promise `Failed`, so no consumer can wait for a value that never comes.378 /// promise `Failed`, so no consumer can wait for a value that never comes.
374-struct SlotPromise {379+struct SlotPromise<T = std::sync::Arc<SlotValue>> {
375- state: std::sync::Mutex<PromiseState>,380+ state: std::sync::Mutex<PromiseState<T>>,
376 ready: std::sync::Condvar,381 ready: std::sync::Condvar,
377 }382 }
378 383
379-enum PromiseState {384+enum PromiseState<T> {
380 Pending,385 Pending,
381- Ready(std::sync::Arc<SlotValue>),386+ Ready(T),
382 Failed,387 Failed,
383 }388 }
384 389
385-impl SlotPromise {390+impl<T: Clone> SlotPromise<T> {
386 fn pending() -> std::sync::Arc<Self> {391 fn pending() -> std::sync::Arc<Self> {
387 std::sync::Arc::new(Self {392 std::sync::Arc::new(Self {
388 state: std::sync::Mutex::new(PromiseState::Pending),393 state: std::sync::Mutex::new(PromiseState::Pending),
@@ -391,18 +396,29 @@ impl SlotPromise {
391 }396 }
392 397
393 /// A slot filled by a frame the parsing thread decoded itself.398 /// A slot filled by a frame the parsing thread decoded itself.
394- fn ready(value: std::sync::Arc<SlotValue>) -> std::sync::Arc<Self> {399+ fn ready(value: T) -> std::sync::Arc<Self> {
395 std::sync::Arc::new(Self {400 std::sync::Arc::new(Self {
396 state: std::sync::Mutex::new(PromiseState::Ready(value)),401 state: std::sync::Mutex::new(PromiseState::Ready(value)),
397 ready: std::sync::Condvar::new(),402 ready: std::sync::Condvar::new(),
398 })403 })
399 }404 }
400 405
401- fn fulfil(&self, value: std::sync::Arc<SlotValue>) {406+ fn fulfil(&self, value: T) {
402 *self.state.lock().expect("slot promise") = PromiseState::Ready(value);407 *self.state.lock().expect("slot promise") = PromiseState::Ready(value);
403 self.ready.notify_all();408 self.ready.notify_all();
404 }409 }
405 410
411+ /// lane-twostage: fulfils only a promise the stage-1 sink did not
412+ /// already fill (a superres frame, or a key frame, whose meta is
413+ /// published here as it always was).
414+ fn fulfil_if_pending(&self, value: impl FnOnce() -> T) {
415+ let mut state = self.state.lock().expect("slot promise");
416+ if matches!(*state, PromiseState::Pending) {
417+ *state = PromiseState::Ready(value());
418+ }
419+ self.ready.notify_all();
420+ }
421+
406 fn fail(&self) {422 fn fail(&self) {
407 let mut state = self.state.lock().expect("slot promise");423 let mut state = self.state.lock().expect("slot promise");
408 if matches!(*state, PromiseState::Pending) {424 if matches!(*state, PromiseState::Pending) {
@@ -412,7 +428,7 @@ impl SlotPromise {
412 }428 }
413 429
414 /// Blocks until the producing frame has published this slot.430 /// Blocks until the producing frame has published this slot.
415- fn wait(&self) -> Result<std::sync::Arc<SlotValue>> {431+ fn wait(&self) -> Result<T> {
416 let mut state = self.state.lock().expect("slot promise");432 let mut state = self.state.lock().expect("slot promise");
417 loop {433 loop {
418 match &*state {434 match &*state {
@@ -643,16 +659,17 @@ pub fn decode_stream_with_threads(
643 jobs.submit(move || {659 jobs.submit(move || {
644 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {660 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
645 let value = promise.wait()?;661 let value = promise.wait()?;
662+ let shown_picture = value.pixels.wait()?;
646 let output = if grain.apply_grain && !no_grain() {663 let output = if grain.apply_grain && !no_grain() {
647 std::sync::Arc::new(crate::film_grain::apply_grain(664 std::sync::Arc::new(crate::film_grain::apply_grain(
648- &value.picture,665+ &shown_picture,
649 &grain,666 &grain,
650 seq.mc_identity,667 seq.mc_identity,
651 u32::from(seq.bit_depth),668 u32::from(seq.bit_depth),
652 &crate::decode::FrameCtx::new(),669 &crate::decode::FrameCtx::new(),
653 ))670 ))
654 } else {671 } else {
655- std::sync::Arc::clone(&value.picture)672+ std::sync::Arc::clone(&shown_picture)
656 };673 };
657 Ok((output, decode_idx, true))674 Ok((output, decode_idx, true))
658 }))675 }))
@@ -871,6 +888,12 @@ pub fn decode_stream_with_threads(
871 crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown);888 crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown);
872 jobs.submit(move || {889 jobs.submit(move || {
873 let promise = produces;890 let promise = produces;
891+ // lane-twostage: stage 2 -- this frame's filtered pixels. Its
892+ // consumers hold this promise from the moment stage 1 (CDFs,
893+ // segment map, motion field, size) is published at the tile
894+ // boundary, and wait on it at their first prediction.
895+ let pixels: std::sync::Arc<SlotPromise<std::sync::Arc<Picture>>> =
896+ SlotPromise::pending();
874 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {897 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
875 crate::timeline::start(decode_idx);898 crate::timeline::start(decode_idx);
876 // The wait happens HERE, off the parsing thread, and only899 // The wait happens HERE, off the parsing thread, and only
@@ -893,6 +916,71 @@ pub fn decode_stream_with_threads(
893 // Fresh per-thread state: every field this path reads is916 // Fresh per-thread state: every field this path reads is
894 // written from this frame's own header before it is read.917 // written from this frame's own header before it is read.
895 let fctx = crate::decode::FrameCtx::new();918 let fctx = crate::decode::FrameCtx::new();
919+ // lane-twostage: the pictures behind this frame's own
920+ // references, waited for at the first `ref_planes` call
921+ // inside the tile decode rather than here.
922+ let ref_metas: [Option<std::sync::Arc<SlotValue>>; 8] =
923+ std::array::from_fn(|i| {
924+ if i == 0 {
925+ None
926+ } else {
927+ resolved
928+ .get(header.ref_frame_idx[i - 1] as usize)
929+ .cloned()
930+ .flatten()
931+ }
932+ });
933+ let pix_cell: std::sync::OnceLock<
934+ [Option<std::sync::Arc<Picture>>; 8],
935+ > = std::sync::OnceLock::new();
936+ let wait_pixels = || -> Result<[Option<&Picture>; 8]> {
937+ if pix_cell.get().is_none() {
938+ let mut pics: [Option<std::sync::Arc<Picture>>; 8] =
939+ Default::default();
940+ for (i, meta) in ref_metas.iter().enumerate() {
941+ if let Some(meta) = meta {
942+ let slot = header.ref_frame_idx[i - 1] as usize;
943+ let t0 = crate::timeline::now();
944+ pics[i] = Some(meta.pixels.wait()?);
945+ crate::timeline::ref_wait(
946+ decode_idx,
947+ slot,
948+ dep_owner[slot],
949+ crate::timeline::now().saturating_sub(t0),
950+ );
951+ }
952+ }
953+ let _ = pix_cell.set(pics);
954+ }
955+ let pics = pix_cell.get().expect("the pictures were just set");
956+ Ok(std::array::from_fn(|i| pics[i].as_deref()))
957+ };
958+ let refpix = decode::RefPix::lazy(
959+ std::array::from_fn(|i| {
960+ ref_metas[i].as_ref().map(|m| (m.width, m.height))
961+ }),
962+ &wait_pixels,
963+ );
964+ // Stage 1: published at this frame's tile boundary, before
965+ // its filters run (`take_segment_ids` copies the map, so
966+ // the filters that read it are unaffected).
967+ let stage1 = |cdfs: Cdfs,
968+ motion_field: crate::motion_field::MotionField,
969+ width: usize,
970+ height: usize| {
971+ if let Some(promise) = &promise {
972+ promise.fulfil(std::sync::Arc::new(SlotValue {
973+ pixels: pixels.clone(),
974+ width,
975+ height,
976+ cdfs,
977+ motion_field,
978+ seg_map: decode::take_segment_ids(&fctx),
979+ order_hint: header.order_hint,
980+ }));
981+ crate::timeline::slot_fulfil();
982+ }
983+ };
896 // spec 7.9's `av1_setup_motion_field` runs inside984 // spec 7.9's `av1_setup_motion_field` runs inside
897 // `RefSnapshot::take`, i.e. here, after those waits --985 // `RefSnapshot::take`, i.e. here, after those waits --
898 // it reads the referenced slots' saved motion fields.986 // it reads the referenced slots' saved motion fields.
@@ -901,7 +989,7 @@ pub fn decode_stream_with_threads(
901 let snap = RefSnapshot::take(989 let snap = RefSnapshot::take(
902 &header,990 &header,
903 seq,991 seq,
904- std::array::from_fn(|i| resolved[i].as_ref().map(|v| &*v.picture)),992+ &refpix,
905 std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)),993 std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)),
906 std::array::from_fn(|i| {994 std::array::from_fn(|i| {
907 resolved[i].as_ref().map(|v| v.seg_map.as_slice())995 resolved[i].as_ref().map(|v| v.seg_map.as_slice())
@@ -918,19 +1006,35 @@ pub fn decode_stream_with_threads(
918 decode_idx,1006 decode_idx,
919 shown_idx,1007 shown_idx,
920 dump.as_deref(),1008 dump.as_deref(),
1009+ // lane-twostage kill switch: `EC_AV1_TWO_STAGE=0`
1010+ // publishes a frame's meta where it always was
1011+ // (after its filters), for bisecting a mismatch.
1012+ crate::envflags::var("EC_AV1_TWO_STAGE")
1013+ .is_ok_and(|v| v == "0")
1014+ .then_some(())
1015+ .map_or(Some(&stage1 as &dyn Fn(_, _, _, _)), |()| None),
921 )?;1016 )?;
922 // Publish before grain synthesis: every frame waiting on1017 // Publish before grain synthesis: every frame waiting on
923 // this slot can start the moment the clean picture exists1018 // this slot can start the moment the clean picture exists
924 // (spec 7.18.3.1 -- the bank never stores grain).1019 // (spec 7.18.3.1 -- the bank never stores grain).
925 let picture = std::sync::Arc::new(out.picture);1020 let picture = std::sync::Arc::new(out.picture);
1021+ pixels.fulfil(picture.clone());
926 if let Some(promise) = &promise {1022 if let Some(promise) = &promise {
927- promise.fulfil(std::sync::Arc::new(SlotValue {1023+ // Only a frame whose stage-1 sink never fired (a
928- picture: picture.clone(),1024+ // superres frame) still has meta to publish here.
929- cdfs: out.stored_cdfs,1025+ promise.fulfil_if_pending(|| {
930- motion_field: out.motion_field,1026+ std::sync::Arc::new(SlotValue {
931- seg_map: out.seg_map,1027+ pixels: pixels.clone(),
932- order_hint: header.order_hint,1028+ width: picture.width,
933- }));1029+ height: picture.height,
1030+ cdfs: out.stored_cdfs,
1031+ motion_field: out.motion_field.expect(
1032+ "a frame that published no stage 1 carries its motion field back",
1033+ ),
1034+ seg_map: out.seg_map,
1035+ order_hint: header.order_hint,
1036+ })
1037+ });
934 crate::timeline::slot_fulfil();1038 crate::timeline::slot_fulfil();
935 }1039 }
936 // Grain is synthesised for OUTPUT only: a hidden frame is1040 // Grain is synthesised for OUTPUT only: a hidden frame is
@@ -957,10 +1061,13 @@ pub fn decode_stream_with_threads(
957 });1061 });
958 // A frame nobody can decode must not leave its consumers1062 // A frame nobody can decode must not leave its consumers
959 // waiting for a slot that will never be filled.1063 // waiting for a slot that will never be filled.
960- if reply.is_err()1064+ if reply.is_err() {
961- && let Some(promise) = &promise1065+ // Neither stage may leave a consumer waiting for a value
962- {1066+ // that will never come.
963- promise.fail();1067+ if let Some(promise) = &promise {
1068+ promise.fail();
1069+ }
1070+ pixels.fail();
964 }1071 }
965 let _ = tx.send((job_seq, true, reply));1072 let _ = tx.send((job_seq, true, reply));
966 });1073 });
@@ -979,10 +1086,21 @@ pub fn decode_stream_with_threads(
979 }1086 }
980 continue;1087 continue;
981 }1088 }
1089+ // lane-twostage: the inline path's references are decoded already,
1090+ // so its handle never waits.
1091+ let inline_refpix = decode::RefPix::ready(std::array::from_fn(|i| {
1092+ if i == 0 {
1093+ None
1094+ } else {
1095+ ref_slots
1096+ .get(header.ref_frame_idx[i - 1] as usize)
1097+ .and_then(|p| p.as_deref())
1098+ }
1099+ }));
982 let snap = RefSnapshot::take(1100 let snap = RefSnapshot::take(
983 &header,1101 &header,
984 seq,1102 seq,
985- std::array::from_fn(|i| ref_slots[i].as_deref()),1103+ &inline_refpix,
986 std::array::from_fn(|i| cdf_slots[i].as_ref()),1104 std::array::from_fn(|i| cdf_slots[i].as_ref()),
987 std::array::from_fn(|i| seg_map_slots[i].as_deref()),1105 std::array::from_fn(|i| seg_map_slots[i].as_deref()),
988 &std::array::from_fn(|i| motion_field_slots[i].as_ref()),1106 &std::array::from_fn(|i| motion_field_slots[i].as_ref()),
@@ -1003,7 +1121,10 @@ pub fn decode_stream_with_threads(
1003 pictures_decoded,1121 pictures_decoded,
1004 pictures_shown,1122 pictures_shown,
1005 final_dump.as_deref(),1123 final_dump.as_deref(),
1124+ None,
1006 )?;1125 )?;
1126+ let motion_field =
1127+ motion_field.expect("the inline path passes no stage-1 sink");
1007 pictures_decoded += 1;1128 pictures_decoded += 1;
1008 // lane-pool1: one allocation, then every slot store and the output1129 // lane-pool1: one allocation, then every slot store and the output
1009 // itself are refcount bumps instead of plane copies.1130 // itself are refcount bumps instead of plane copies.
@@ -1014,7 +1135,9 @@ pub fn decode_stream_with_threads(
1014 // already resolved, since the picture exists right here.1135 // already resolved, since the picture exists right here.
1015 if header.refresh_frame_flags != 0 {1136 if header.refresh_frame_flags != 0 {
1016 let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue {1137 let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue {
1017- picture: std::sync::Arc::clone(&picture),1138+ pixels: SlotPromise::ready(std::sync::Arc::clone(&picture)),
1139+ width: picture.width,
1140+ height: picture.height,
1018 cdfs: stored_cdfs,1141 cdfs: stored_cdfs,
1019 motion_field,1142 motion_field,
1020 seg_map: decoded_seg_map,1143 seg_map: decoded_seg_map,
@@ -1131,8 +1254,9 @@ impl SeqFlags {
1131 /// banks `decode_stream_with` owns -- taken on the parsing thread, before any1254 /// banks `decode_stream_with` owns -- taken on the parsing thread, before any
1132 /// later frame can overwrite a slot, so a frame can be decoded anywhere.1255 /// later frame can overwrite a slot, so a frame can be decoded anywhere.
1133 pub(crate) struct RefSnapshot<'a> {1256 pub(crate) struct RefSnapshot<'a> {
1134- /// The 8 DPB slots, indexed by slot (NOT by `ref_frame_idx`).1257+ /// lane-twostage: this frame's references, indexed by `ref_frame`
1135- pub(crate) refs: [Option<&'a Picture>; NUM_REF_FRAMES],1258+ /// (`LAST_FRAME` = 1) -- sizes now, pixels at the first prediction.
1259+ pub(crate) refpix: &'a decode::RefPix<'a>,
1136 /// `cdf_slots[ref_frame_idx[primary_ref_frame]]`, `None` when this frame1260 /// `cdf_slots[ref_frame_idx[primary_ref_frame]]`, `None` when this frame
1137 /// names `PRIMARY_REF_NONE` *or* that slot holds no saved table (the1261 /// names `PRIMARY_REF_NONE` *or* that slot holds no saved table (the
1138 /// second case is the refusal [`decode_frame`] raises where it always1262 /// second case is the refusal [`decode_frame`] raises where it always
@@ -1155,7 +1279,7 @@ impl<'a> RefSnapshot<'a> {
1155 fn take(1279 fn take(
1156 header: &FrameHeader,1280 header: &FrameHeader,
1157 seq: SeqFlags,1281 seq: SeqFlags,
1158- refs: [Option<&'a Picture>; NUM_REF_FRAMES],1282+ refpix: &'a decode::RefPix<'a>,
1159 cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES],1283 cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES],
1160 seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES],1284 seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES],
1161 motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES],1285 motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES],
@@ -1189,7 +1313,7 @@ impl<'a> RefSnapshot<'a> {
1189 );1313 );
1190 }1314 }
1191 Self {1315 Self {
1192- refs,1316+ refpix,
1193 primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),1317 primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),
1194 prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].map(<[u8]>::to_vec)),1318 prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].map(<[u8]>::to_vec)),
1195 tpl_field,1319 tpl_field,
@@ -1206,10 +1330,27 @@ impl<'a> RefSnapshot<'a> {
1206 pub(crate) struct FrameOutput {1330 pub(crate) struct FrameOutput {
1207 pub(crate) picture: Picture,1331 pub(crate) picture: Picture,
1208 pub(crate) stored_cdfs: Cdfs,1332 pub(crate) stored_cdfs: Cdfs,
1209- pub(crate) motion_field: crate::motion_field::MotionField,1333+ /// lane-twostage: `None` when this frame handed its motion field to the
1334+ /// stage-1 sink at its tile boundary instead of carrying it back here.
1335+ pub(crate) motion_field: Option<crate::motion_field::MotionField>,
1210 pub(crate) seg_map: Vec<u8>,1336 pub(crate) seg_map: Vec<u8>,
1211 }1337 }
1212 1338
1339+/// Spec 7.20's own `save_cdfs`: what a frame's `refresh_frame_flags` slots
1340+/// keep -- the frame's INITIAL table when `disable_frame_end_update_cdf`,
1341+/// otherwise the adapted end-of-tile table with every symbol counter zeroed
1342+/// (libaom `av1_reset_cdf_symbol_counters`). lane-twostage: shared with the
1343+/// stage-1 publish, which hands a consumer the same table it always got.
1344+fn stored_cdfs_for(header: &FrameHeader, end_cdfs: Cdfs, started_from: Option<Cdfs>) -> Cdfs {
1345+ if header.disable_frame_end_update_cdf {
1346+ started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
1347+ } else {
1348+ let mut end_cdfs = end_cdfs;
1349+ end_cdfs.reset_counts();
1350+ end_cdfs
1351+ }
1352+}
1353+
1213 /// lane-thread2: one coded frame, decoded from its header, its tile payload1354 /// lane-thread2: one coded frame, decoded from its header, its tile payload
1214 /// and a snapshot of the reference banks -- and from nothing else. Lifted1355 /// and a snapshot of the reference banks -- and from nothing else. Lifted
1215 /// verbatim out of [`decode_stream_with`]'s loop so that the same code can1356 /// verbatim out of [`decode_stream_with`]'s loop so that the same code can
@@ -1233,6 +1374,8 @@ fn decode_frame(
1233 decode_idx: usize,1374 decode_idx: usize,
1234 shown_idx: usize,1375 shown_idx: usize,
1235 final_dump: Option<&str>,1376 final_dump: Option<&str>,
1377+ // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`.
1378+ stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>,
1236 ) -> Result<FrameOutput> {1379 ) -> Result<FrameOutput> {
1237 if header.segmentation.enabled {1380 if header.segmentation.enabled {
1238 for segment in 0..MAX_SEGMENTS {1381 for segment in 0..MAX_SEGMENTS {
@@ -1568,15 +1711,16 @@ fn decode_frame(
1568 // never a projection source, and never spends a `ref_stamp`.1711 // never a projection source, and never spends a `ref_stamp`.
1569 true,1712 true,
1570 );1713 );
1571- (picture, end_cdfs, motion_field)1714+ (picture, end_cdfs, Some(motion_field))
1572 } else {1715 } else {
1573 let last_slot = header.ref_frame_idx[0] as usize;1716 let last_slot = header.ref_frame_idx[0] as usize;
1574- let reference = snap.refs[last_slot].ok_or_else(|| {1717+ let _ = last_slot;
1575- Error::unsupported(1718+ if snap.refpix.dims(1).is_none() {
1719+ return Err(Error::unsupported(
1576 "AV1 decode_stream",1720 "AV1 decode_stream",
1577 "an inter frame with no key frame before it",1721 "an inter frame with no key frame before it",
1578- )1722+ ));
1579- })?;1723+ }
1580 // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`1724 // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
1581 // (spec 7.8/7.20). Any of them having no picture yet is not a1725 // (spec 7.8/7.20). Any of them having no picture yet is not a
1582 // stream error on its own: `decode_inter_block` only needs a1726 // stream error on its own: `decode_inter_block` only needs a
@@ -1589,20 +1733,26 @@ fn decode_frame(
1589 if header.force_integer_mv {1733 if header.force_integer_mv {
1590 decode::note_force_integer_mv_frame();1734 decode::note_force_integer_mv_frame();
1591 }1735 }
1592- let other_refs: [Option<&Picture>; 8] = std::array::from_fn(|ref_frame| {
1593- if ref_frame == 0 {
1594- None
1595- } else {
1596- snap.refs
1597- .get(header.ref_frame_idx[ref_frame - 1] as usize)
1598- .copied()
1599- .flatten()
1600- }
1601- });
1602 // spec 7.9's own driver, `av1_setup_motion_field`: only run when1736 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
1603 // this frame's header actually asks for temporal candidates --1737 // this frame's header actually asks for temporal candidates --
1604 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`1738 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
1605 // behaviour bit for bit when this is `None` (see its own doc).1739 // behaviour bit for bit when this is `None` (see its own doc).
1740+ // lane-twostage: the stage-1 sink is handed the table a consumer
1741+ // would have read out of the slot, not the raw end-of-tile one.
1742+ let started_from_stage1 = started_from.clone();
1743+ let stage1_adapter = stage1.map(|sink| {
1744+ move |end_cdfs: Cdfs,
1745+ motion_field: crate::motion_field::MotionField,
1746+ width: usize,
1747+ height: usize| {
1748+ sink(
1749+ stored_cdfs_for(header, end_cdfs, started_from_stage1.clone()),
1750+ motion_field,
1751+ width,
1752+ height,
1753+ )
1754+ }
1755+ });
1606 let tpl_field = &snap.tpl_field;1756 let tpl_field = &snap.tpl_field;
1607 let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(1757 let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(
1608 &tile_bufs,1758 &tile_bufs,
@@ -1619,8 +1769,7 @@ fn decode_frame(
1619 },1769 },
1620 header.frame_width,1770 header.frame_width,
1621 header.frame_height,1771 header.frame_height,
1622- reference,1772+ snap.refpix,
1623- other_refs,
1624 &header.cdef,1773 &header.cdef,
1625 &header.loop_filter,1774 &header.loop_filter,
1626 &header.loop_restoration,1775 &header.loop_restoration,
@@ -1647,7 +1796,11 @@ fn decode_frame(
1647 header.allow_warped_motion,1796 header.allow_warped_motion,
1648 header.allow_screen_content_tools,1797 header.allow_screen_content_tools,
1649 header.delta,1798 header.delta,
1650- enable_filter_intra, fctx,1799+ enable_filter_intra,
1800+ stage1_adapter
1801+ .as_ref()
1802+ .map(|f| f as &dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)),
1803+ fctx,
1651 )?;1804 )?;
1652 (picture, end_cdfs, motion_field)1805 (picture, end_cdfs, motion_field)
1653 };1806 };
@@ -1657,16 +1810,7 @@ fn decode_frame(
1657 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's1810 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
1658 // *initial* table into the slots it refreshes, not the adapted1811 // *initial* table into the slots it refreshes, not the adapted
1659 // end-of-tile one.1812 // end-of-tile one.
1660- let stored_cdfs = if header.disable_frame_end_update_cdf {1813+ let stored_cdfs = stored_cdfs_for(header, end_cdfs, started_from);
1661- started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
1662- } else {
1663- // Spec 7.20 `save_cdfs` (libaom `av1_reset_cdf_symbol_counters`):
1664- // the adapted table is saved with every symbol counter zeroed,
1665- // not with the counts the tile's own decode left behind.
1666- let mut end_cdfs = end_cdfs;
1667- end_cdfs.reset_counts();
1668- end_cdfs
1669- };
1670 if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {1814 if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
1671 use std::io::Write;1815 use std::io::Write;
1672 if let Ok(mut f) = std::fs::OpenOptions::new()1816 if let Ok(mut f) = std::fs::OpenOptions::new()