forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-twostage' (fe745ecc): two-stage reference promises (CDFs per spec 7.20, seg map, motion field, size at the tile boundary; filtered pixels after the filters) through a RefPix handle waited at the first ref_planes; default OFF (EC_AV1_TWO_STAGE=1) because inline 8x8-leaf/OBMC/sub-8x8 predictions touch ref pixels 4% into the parse; byte-exact on 16 gate hashes + 6 film cuts both ways

Browse files at this commit

1d9f0d30841fa23c9a6df27ed01e87d54bc4a879Ahmet Kaan GümüşParent: c8709314231093
crates/ec-av1/src/decode.rsmodified+242 -335
@@ -13006,7 +13006,6 @@ struct PlaneBuf<'a> {
1300613006 /// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
1300713007 /// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
1300813008 /// `ALTREF2`/`ALTREF`).
13009-type RefSlots<'a> = [Option<(&'a PlaneBuf<'a>, &'a PlaneBuf<'a>, &'a PlaneBuf<'a>)>; 8];
1301013009
1301113010 impl PlaneBuf<'_> {
1301213011 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
@@ -23199,27 +23198,124 @@ fn read_single_ref(
2319923198 /// own doc. Called from [`decode_inter_block`] once its own `reference_select`
2320023199 /// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
2320123200 /// way with a coarser (`LAST_FRAME`-only) neighbour shape.
23202-/// Resolves a compound reference's own planes -- the same `ref_frame ==
23203-/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup
23204-/// [`decode_inter_block`]'s single-ref path already does, factored out so
23205-/// the compound path can call it twice (lane-av1comp).
23206-fn ref_planes<'a>(
23201+/// lane-twostage: this frame's references as DIMENSIONS now and PIXELS on
23202+/// demand. An inter tile's parse reads reference SIZES (`mc::scale_factor`)
23203+/// but touches no reference PIXEL until its first prediction -- measured 4.2%
23204+/// of a 4K tile's parse into it -- so the pictures are resolved here, at the
23205+/// first [`ref_planes`] call, rather than at frame entry. On the threaded
23206+/// path that resolution is a WAIT on the producing frame's pixels, which is
23207+/// what lets a consumer parse while its references are still being filtered.
23208+pub(crate) struct RefPix<'p> {
23209+ /// `(width, height)` per `ref_frame` index (`LAST_FRAME` = 1). `None` is
23210+ /// a slot this frame may not use: empty, or -- for a non-`LAST_FRAME`
23211+ /// slot -- not the same size as `LAST_FRAME`'s own picture (spec 7.9's
23212+ /// compatible-size rule, the filter the eager `owned_refs` array applied).
23213+ dims: [Option<(usize, usize)>; 8],
23214+ src: RefSrc<'p>,
23215+ bufs: std::sync::OnceLock<[Option<(PlaneBuf<'p>, PlaneBuf<'p>, PlaneBuf<'p>)>; 8]>,
23216+}
23217+
23218+/// Where a [`RefPix`] gets its pictures: already in hand, or behind a wait
23219+/// the caller owns (`stream.rs`'s reference promises).
23220+enum RefSrc<'p> {
23221+ Ready([Option<&'p Picture>; 8]),
23222+ Lazy(&'p (dyn Fn() -> Result<[Option<&'p Picture>; 8]> + Send + Sync + 'p)),
23223+}
23224+
23225+/// `LAST_FRAME`'s own index in a [`RefPix`] (spec 6.10.24).
23226+const LAST_REF: usize = 1;
23227+
23228+impl<'p> RefPix<'p> {
23229+ /// References already decoded: the single-threaded path and the test
23230+ /// entry points, where [`ref_planes`] never waits.
23231+ pub(crate) fn ready(refs: [Option<&'p Picture>; 8]) -> Self {
23232+ let dims = Self::compatible(std::array::from_fn(|i| {
23233+ refs[i].map(|p| (p.width, p.height))
23234+ }));
23235+ Self { dims, src: RefSrc::Ready(refs), bufs: std::sync::OnceLock::new() }
23236+ }
23237+
23238+ /// References whose sizes are known (from their producers' headers) but
23239+ /// whose pixels `wait` still has to produce.
23240+ pub(crate) fn lazy(
23241+ dims: [Option<(usize, usize)>; 8],
23242+ wait: &'p (dyn Fn() -> Result<[Option<&'p Picture>; 8]> + Send + Sync + 'p),
23243+ ) -> Self {
23244+ Self { dims: Self::compatible(dims), src: RefSrc::Lazy(wait), bufs: std::sync::OnceLock::new() }
23245+ }
23246+
23247+ /// Spec 7.9's compatible-size rule: a non-`LAST_FRAME` slot at a
23248+ /// different size than `LAST_FRAME`'s is treated as absent, exactly as
23249+ /// the eager `owned_refs.filter(..)` did.
23250+ fn compatible(mut dims: [Option<(usize, usize)>; 8]) -> [Option<(usize, usize)>; 8] {
23251+ let last = dims[LAST_REF];
23252+ for (i, d) in dims.iter_mut().enumerate() {
23253+ if i != LAST_REF && *d != last {
23254+ *d = None;
23255+ }
23256+ }
23257+ dims
23258+ }
23259+
23260+ /// This slot's picture size, without touching its pixels.
23261+ pub(crate) fn dims(&self, ref_frame: i8) -> Option<(usize, usize)> {
23262+ self.dims.get(ref_frame as usize).copied().flatten()
23263+ }
23264+
23265+ /// Every usable slot's three planes, resolving (and, on the threaded
23266+ /// path, waiting for) the pictures on the first call.
23267+ fn planes(&self) -> Result<&[Option<(PlaneBuf<'p>, PlaneBuf<'p>, PlaneBuf<'p>)>; 8]> {
23268+ if let Some(bufs) = self.bufs.get() {
23269+ return Ok(bufs);
23270+ }
23271+ let pics = match &self.src {
23272+ RefSrc::Ready(refs) => *refs,
23273+ RefSrc::Lazy(wait) => wait()?,
23274+ };
23275+ let dims = self.dims;
23276+ let bufs = std::array::from_fn(|i| {
23277+ dims[i].and(pics[i]).map(|g| {
23278+ (
23279+ whole_plane(&g.y, g.width, g.height),
23280+ whole_plane(&g.u, g.width / 2, g.height / 2),
23281+ whole_plane(&g.v, g.width / 2, g.height / 2),
23282+ )
23283+ })
23284+ });
23285+ let _ = self.bufs.set(bufs);
23286+ Ok(self.bufs.get().expect("the plane array was just set"))
23287+ }
23288+}
23289+
23290+/// A whole reference plane as a [`PlaneBuf`]: no tile window, no margin.
23291+fn whole_plane(data: &[u16], width: usize, height: usize) -> PlaneBuf<'_> {
23292+ PlaneBuf {
23293+ data: std::borrow::Cow::Borrowed(data),
23294+ width,
23295+ height,
23296+ true_width: width,
23297+ true_height: height,
23298+ tile_x0: 0,
23299+ tile_y0: 0,
23300+ tile_x1: width,
23301+ tile_y1: height,
23302+ }
23303+}
23304+
23305+/// Resolves a reference's own planes -- the `ref_frame -> picture` lookup
23306+/// [`decode_inter_block`]'s single-ref path does, factored out so the
23307+/// compound path can call it twice (lane-av1comp), and the point where
23308+/// lane-twostage's pixel wait happens.
23309+fn ref_planes<'a, 'p>(
2320723310 ref_frame: i8,
23208- ref_y: &'a PlaneBuf<'a>,
23209- ref_u: &'a PlaneBuf<'a>,
23210- ref_v: &'a PlaneBuf<'a>,
23211- other_refs: &'a RefSlots,
23212-) -> Result<(&'a PlaneBuf<'a>, &'a PlaneBuf<'a>, &'a PlaneBuf<'a>)> {
23213- if ref_frame == LAST_FRAME {
23214- Ok((ref_y, ref_u, ref_v))
23215- } else {
23216- match other_refs[ref_frame as usize] {
23217- Some((ry, ru, rv)) => Ok((ry, ru, rv)),
23218- None => Err(unsupported(
23219- "a reference frame selected with no picture at this frame's own \
23311+ refpix: &'a RefPix<'p>,
23312+) -> Result<(&'a PlaneBuf<'p>, &'a PlaneBuf<'p>, &'a PlaneBuf<'p>)> {
23313+ match refpix.planes()?.get(ref_frame as usize).and_then(Option::as_ref) {
23314+ Some((y, u, v)) => Ok((y, u, v)),
23315+ None => Err(unsupported(
23316+ "a reference frame selected with no picture at this frame's own \
2322023317 ref_frame_idx slot for it",
23221- )),
23222- }
23318+ )),
2322323319 }
2322423320 }
2322523321
@@ -23933,10 +24029,7 @@ fn obmc_blend(
2393324029 py: usize,
2393424030 cpx: usize,
2393524031 cpy: usize,
23936- ref_y: &PlaneBuf<'_>,
23937- ref_u: &PlaneBuf<'_>,
23938- ref_v: &PlaneBuf<'_>,
23939- other_refs: &RefSlots,
24032+ refpix: &RefPix<'_>,
2394024033 interp_fixed: Option<mc::InterpFilterKind>,
2394124034 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
2394224035 // neighbour is re-predicted against ITS OWN reference, which may be
@@ -24047,7 +24140,7 @@ fn obmc_blend(
2404724140 );
2404824141 let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?;
2404924142 ec_obmc_trace("above", 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)?;
2405124144 let nb_scale = mc::scale_factor(ny.width, frame_width);
2405224145 if mi_col + off4 + span4 > mi_cols {
2405324146 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));
@@ -24083,7 +24176,7 @@ fn obmc_blend(
2408324176 );
2408424177 let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?;
2408524178 ec_obmc_trace("left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);
24086- let (ny, nu, nv) = ref_planes(nb.ref_frame, ref_y, ref_u, ref_v, other_refs)?;
24179+ let (ny, nu, nv) = ref_planes(nb.ref_frame, refpix)?;
2408724180 let nb_scale = mc::scale_factor(ny.width, frame_width);
2408824181 if mi_row + off4 + span4 > mi_rows {
2408924182 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));
@@ -24516,16 +24609,13 @@ fn decode_inter_block(
2451624609 y: &mut PlaneBuf<'static>,
2451724610 u: &mut PlaneBuf<'static>,
2451824611 v: &mut PlaneBuf<'static>,
24519- ref_y: &PlaneBuf<'_>,
24520- ref_u: &PlaneBuf<'_>,
24521- ref_v: &PlaneBuf<'_>,
24612+ refpix: &RefPix<'_>,
2452224613 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
2452324614 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
2452424615 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
2452524616 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
2452624617 // slot's still empty (an error-resilient stream, or too early in the
2452724618 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
24528- other_refs: &RefSlots,
2452924619 sign_bias_table: &SignBiasTable,
2453024620 // lane-gm r2: this frame header's own `global_motion` table (spec
2453124621 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
@@ -24937,8 +25027,8 @@ fn decode_inter_block(
2493725027 if gm_nontrans_models && !gm_nontrans {
2493825028 GM_NONTRANS_SMALL_SIDE_HITS.with(|c| c.set(c.get() + 1));
2493925029 }
24940- let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
24941- let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
25030+ let (py0, pu0, pv0) = ref_planes(ref0, refpix)?;
25031+ let (py1, pu1, pv1) = ref_planes(ref1, refpix)?;
2494225032 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is
2494325033 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and
2494425034 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from
@@ -24980,7 +25070,7 @@ fn decode_inter_block(
2498025070 // scaled (superres) is predicted translationally while its
2498125071 // sibling may still warp.
2498225072 let ref_unscaled = |rf: i8| {
24983- ref_planes(rf, ref_y, ref_u, ref_v, other_refs)
25073+ ref_planes(rf, refpix)
2498425074 .is_ok_and(|(py, _, _)| {
2498525075 mc::scale_factor(py.width, frame_width) == mc::REF_NO_SCALE
2498625076 })
@@ -26061,19 +26151,7 @@ fn decode_inter_block(
2606126151 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
2606226152 // widens this from GOLDEN alone to every reference `read_single_ref`
2606326153 // can name.
26064- let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {
26065- (ref_y, ref_u, ref_v)
26066- } else {
26067- match other_refs[ref_frame as usize] {
26068- Some((ry, ru, rv)) => (ry, ru, rv),
26069- None => {
26070- return Err(unsupported(
26071- "a reference frame selected with no picture at this frame's own \
26072- ref_frame_idx slot for it",
26073- ));
26074- }
26075- }
26076- };
26154+ let (py_ref, pu_ref, pv_ref) = ref_planes(ref_frame, refpix)?;
2607726155
2607826156 let (mi_row, mi_col) = (rmi, cmi);
2607926157 // lane-rect r2: the mv stack must be queried with the block's
@@ -26870,10 +26948,7 @@ fn decode_inter_block(
2687026948 py,
2687126949 cpx,
2687226950 cpy,
26873- ref_y,
26874- ref_u,
26875- ref_v,
26876- other_refs,
26951+ refpix,
2687726952 interp_fixed,
2687826953 frame_width,
2687926954 &mut pred_y,
@@ -26902,7 +26977,7 @@ fn decode_inter_block(
2690226977 // reference was scaled, which silently left the whole-block
2690326978 // prediction in place instead of refusing. It scales off the
2690426979 // PREVIOUS strip's own reference, not this block's.
26905- let (prev_y_plane, prev_u, prev_v_plane) = ref_planes(prev_ref, ref_y, ref_u, ref_v, other_refs)?;
26980+ let (prev_y_plane, prev_u, prev_v_plane) = ref_planes(prev_ref, refpix)?;
2690626981 let prev_scale = mc::scale_factor(prev_y_plane.width, frame_width);
2690726982 for (src, dst) in [(prev_u, &mut pred_u), (prev_v_plane, &mut pred_v)] {
2690826983 let mut piece = vec![0u16; piece_w * piece_h];
@@ -28303,10 +28378,7 @@ fn decode_inter_sub8_split4(
2830328378 y: &mut PlaneBuf<'static>,
2830428379 u: &mut PlaneBuf<'static>,
2830528380 v: &mut PlaneBuf<'static>,
28306- ref_y: &PlaneBuf<'_>,
28307- ref_u: &PlaneBuf<'_>,
28308- ref_v: &PlaneBuf<'_>,
28309- other_refs: &RefSlots,
28381+ refpix: &RefPix<'_>,
2831028382 sign_bias_table: &SignBiasTable,
2831128383 global_motion: &[ec_av1_syntax::WarpParams; 7],
2831228384 base_q_idx: u8,
@@ -28424,7 +28496,7 @@ fn decode_inter_sub8_split4(
2842428496 neighbours.left_ref[rmi],
2842528497 neighbours.left_ref1[rmi],
2842628498 );
28427- let (sref_y, _sref_u, _sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
28499+ let (sref_y, _sref_u, _sref_v) = ref_planes(ref_frame, refpix)?;
2842828500 // lane-t900 r28: refusal lifted -- this sub-block's own reference may
2842928501 // be scaled (superres); spec 7.11.3.3's walk is per reference, and
2843028502 // each of the group's pieces (luma and its 2x2 chroma) carries its
@@ -28694,7 +28766,7 @@ fn decode_inter_sub8_split4(
2869428766 continue;
2869528767 };
2869628768 let (piece_ref_y, sref_u, sref_v) =
28697- ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
28769+ ref_planes(ref_frame, refpix)?;
2869828770 let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width);
2869928771 let (ox, oy) = if mixed {
2870028772 (cpx, cpy)
@@ -29258,10 +29330,7 @@ fn decode_inter_sub8_rect2(
2925829330 y: &mut PlaneBuf<'static>,
2925929331 u: &mut PlaneBuf<'static>,
2926029332 v: &mut PlaneBuf<'static>,
29261- ref_y: &PlaneBuf<'_>,
29262- ref_u: &PlaneBuf<'_>,
29263- ref_v: &PlaneBuf<'_>,
29264- other_refs: &RefSlots,
29333+ refpix: &RefPix<'_>,
2926529334 sign_bias_table: &SignBiasTable,
2926629335 global_motion: &[ec_av1_syntax::WarpParams; 7],
2926729336 base_q_idx: u8,
@@ -29397,7 +29466,7 @@ fn decode_inter_sub8_rect2(
2939729466 neighbours.left_ref[rmi],
2939829467 neighbours.left_ref1[rmi],
2939929468 );
29400- let (sref_y, _, _) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
29469+ let (sref_y, _, _) = ref_planes(ref_frame, refpix)?;
2940129470 // lane-t900 r28: refusal lifted -- see the split arm above.
2940229471 let luma_scale = mc::scale_factor(sref_y.width, frame_width);
2940329472 if luma_scale != mc::REF_NO_SCALE {
@@ -29709,7 +29778,7 @@ fn decode_inter_sub8_rect2(
2970929778 continue;
2971029779 };
2971129780 let (piece_ref_y, sref_u, sref_v) =
29712- ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
29781+ ref_planes(ref_frame, refpix)?;
2971329782 let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width);
2971429783 let (ox, oy) = if mixed {
2971529784 (cpx, cpy)
@@ -29863,10 +29932,7 @@ fn decode_inter_block8(
2986329932 y: &mut PlaneBuf<'static>,
2986429933 u: &mut PlaneBuf<'static>,
2986529934 v: &mut PlaneBuf<'static>,
29866- ref_y: &PlaneBuf<'_>,
29867- ref_u: &PlaneBuf<'_>,
29868- ref_v: &PlaneBuf<'_>,
29869- other_refs: &RefSlots,
29935+ refpix: &RefPix<'_>,
2987029936 base_q_idx: u8,
2987129937 scan8: &[u16],
2987229938 scan4: &[u16],
@@ -30328,8 +30394,8 @@ fn decode_inter_block8(
3032830394 COMPOUND8_FILTER_HITS.with(|c| c.set(c.get() + 1));
3032930395 }
3033030396
30331- let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;
30332- let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;
30397+ let (py0, pu0, pv0) = ref_planes(ref0, refpix)?;
30398+ let (py1, pu1, pv1) = ref_planes(ref1, refpix)?;
3033330399 let scale0 = mc::scale_factor(py0.width, frame_width);
3033430400 let scale1 = mc::scale_factor(py1.width, frame_width);
3033530401 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
@@ -30382,7 +30448,7 @@ fn decode_inter_block8(
3038230448 // lane-t900 r28: same per-slot `allow_warp` scale bail-out as
3038330449 // the 16x16-and-bigger compound path above.
3038430450 let leaf_ref_unscaled = |rf: i8| {
30385- ref_planes(rf, ref_y, ref_u, ref_v, other_refs)
30451+ ref_planes(rf, refpix)
3038630452 .is_ok_and(|(py, _, _)| {
3038730453 mc::scale_factor(py.width, frame_width) == mc::REF_NO_SCALE
3038830454 })
@@ -30757,7 +30823,7 @@ fn decode_inter_block8(
3075730823 neighbours.left_ref1[rmi],
3075830824 );
3075930825 leaf_refs = (ref_frame, None);
30760- let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, ref_y, ref_u, ref_v, other_refs)?;
30826+ let (sref_y, sref_u, sref_v) = ref_planes(ref_frame, refpix)?;
3076130827
3076230828 let (mi_row, mi_col) = leaf_mi;
3076330829 // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS
@@ -31192,10 +31258,7 @@ fn decode_inter_block8(
3119231258 py,
3119331259 cpx,
3119431260 cpy,
31195- ref_y,
31196- ref_u,
31197- ref_v,
31198- other_refs,
31261+ refpix,
3119931262 interp_fixed,
3120031263 frame_width,
3120131264 &mut pred_y,
@@ -31897,8 +31960,7 @@ pub(crate) fn decode_inter_frame_tile(
3189731960 base_q_idx: u8,
3189831961 frame_width: u32,
3189931962 frame_height: u32,
31900- reference: &Picture,
31901- other_refs: [Option<&Picture>; 8],
31963+ refpix: &RefPix<'_>,
3190231964 cdef: &CdefParams,
3190331965 loop_filter: &LoopFilterParams,
3190431966 allow_high_precision_mv: bool,
@@ -31921,8 +31983,7 @@ pub(crate) fn decode_inter_frame_tile(
3192131983 crate::quant::QuantDeltas::default(),
3192231984 frame_width,
3192331985 frame_height,
31924- reference,
31925- other_refs,
31986+ refpix,
3192631987 cdef,
3192731988 loop_filter,
3192831989 &LoopRestorationParams::default(),
@@ -31954,7 +32015,9 @@ pub(crate) fn decode_inter_frame_tile(
3195432015 // `enable_filter_intra`: this crate's own encoder never writes the
3195532016 // sequence bit (`encode.rs`), so no intra-in-inter block of a stream
3195632017 // reaching this entry point reads a `use_filter_intra` symbol.
31957- false, fctx,
32018+ false,
32019+ None,
32020+ fctx,
3195832021 )
3195932022 .map(|(picture, _, _)| picture)
3196032023 }
@@ -31974,8 +32037,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3197432037 deltas: crate::quant::QuantDeltas,
3197532038 frame_width: u32,
3197632039 frame_height: u32,
31977- reference: &Picture,
31978- other_refs: [Option<&Picture>; 8],
32040+ refpix: &RefPix<'_>,
3197932041 cdef: &CdefParams,
3198032042 loop_filter: &LoopFilterParams,
3198132043 lr: &LoopRestorationParams,
@@ -32042,8 +32104,18 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3204232104 // (spec 5.5.2), stashed in a thread-local with `tx_select` rather than
3204332105 // threaded through `decode_inter_block`'s fifty parameters -- read by the
3204432106 // intra-in-inter arms' `read_filter_intra_mode_info`.
32045- enable_filter_intra: bool, fctx: &crate::decode::FrameCtx,
32046-) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {
32107+ enable_filter_intra: bool,
32108+ // lane-twostage: called with this frame's own end-of-tile CDFs, motion
32109+ // field and picture size the moment its last tile symbol is read --
32110+ // BEFORE its filters run, so a frame that references this one can start
32111+ // parsing while this one is still being deblocked/CDEF'd/restored (it
32112+ // waits for the pixels themselves at its first prediction). `None`, and
32113+ // the motion field comes back in the return tuple as it always did:
32114+ // the single-threaded path, and a superres frame (whose final width is
32115+ // only known after the upscale).
32116+ stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>,
32117+ fctx: &crate::decode::FrameCtx,
32118+) -> Result<(Picture, Cdfs, Option<crate::motion_field::MotionField>)> {
3204732119 set_inter_tx_mode(tx_select, reduced_tx_set, enable_filter_intra, fctx);
3204832120 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
3204932121 field,
@@ -32073,7 +32145,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3207332145 // refused every same-size reference (class av1-truesize-lane: true
3207432146 // frame size vs mi-rounded). Height must still MATCH: AV1 superres
3207532147 // never scales height, and no path here has a vertical scaling pass.
32076- if reference.height != frame_height as usize {
32148+ if refpix.dims(1).is_none_or(|(_, h)| h != frame_height as usize) {
3207732149 return Err(unsupported(
3207832150 "a reference picture whose height does not match this frame's own true size",
3207932151 ));
@@ -32086,90 +32158,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3208632158 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
3208732159 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
3208832160
32089- let ref_y = PlaneBuf {
32090- data: std::borrow::Cow::Borrowed(&reference.y),
32091- width: reference.width,
32092- height: reference.height,
32093- true_width: reference.width,
32094- true_height: reference.height,
32095- tile_x0: 0,
32096- tile_y0: 0,
32097- tile_x1: reference.width,
32098- tile_y1: reference.height,
32099- };
32100- let ref_u = PlaneBuf {
32101- data: std::borrow::Cow::Borrowed(&reference.u),
32102- width: reference.width / 2,
32103- height: reference.height / 2,
32104- true_width: reference.width / 2,
32105- true_height: reference.height / 2,
32106- tile_x0: 0,
32107- tile_y0: 0,
32108- tile_x1: reference.width / 2,
32109- tile_y1: reference.height / 2,
32110- };
32111- let ref_v = PlaneBuf {
32112- data: std::borrow::Cow::Borrowed(&reference.v),
32113- width: reference.width / 2,
32114- height: reference.height / 2,
32115- true_width: reference.width / 2,
32116- true_height: reference.height / 2,
32117- tile_x0: 0,
32118- tile_y0: 0,
32119- tile_x1: reference.width / 2,
32120- tile_y1: reference.height / 2,
32121- };
32122- // Every non-`LAST_FRAME` reference this frame header's own `ref_frame_idx`
32123- // names a live DPB slot for (lane-av1refs: generalised from the old
32124- // GOLDEN_FRAME-only block -- same empty-slot/size-mismatch refusal,
32125- // now per-reference). `decode_inter_block` refuses by name when the
32126- // block it is decoding selects an index that is still `None` here
32127- // (spec 7.9 requires every *active* reference be a compatible size;
32128- // an inactive one this frame never selects is simply left `None`).
32129- let owned_refs: [Option<(PlaneBuf<'_>, PlaneBuf<'_>, PlaneBuf<'_>)>; 8] = std::array::from_fn(|i| {
32130- other_refs[i]
32131- .filter(|g| g.width == reference.width && g.height == reference.height)
32132- .map(|g| {
32133- (
32134- PlaneBuf {
32135- data: std::borrow::Cow::Borrowed(&g.y),
32136- width: g.width,
32137- height: g.height,
32138- true_width: g.width,
32139- true_height: g.height,
32140- tile_x0: 0,
32141- tile_y0: 0,
32142- tile_x1: g.width,
32143- tile_y1: g.height,
32144- },
32145- PlaneBuf {
32146- data: std::borrow::Cow::Borrowed(&g.u),
32147- width: g.width / 2,
32148- height: g.height / 2,
32149- true_width: g.width / 2,
32150- true_height: g.height / 2,
32151- tile_x0: 0,
32152- tile_y0: 0,
32153- tile_x1: g.width / 2,
32154- tile_y1: g.height / 2,
32155- },
32156- PlaneBuf {
32157- data: std::borrow::Cow::Borrowed(&g.v),
32158- width: g.width / 2,
32159- height: g.height / 2,
32160- true_width: g.width / 2,
32161- true_height: g.height / 2,
32162- tile_x0: 0,
32163- tile_y0: 0,
32164- tile_x1: g.width / 2,
32165- tile_y1: g.height / 2,
32166- },
32167- )
32168- })
32169- });
32170- let ref_slots: RefSlots =
32171- std::array::from_fn(|i| owned_refs[i].as_ref().map(|(a, b, c)| (a, b, c)));
32172-
3217332161 let mut y = PlaneBuf {
3217432162 data: std::borrow::Cow::Owned(fresh_plane(width * height)),
3217532163 width,
@@ -32530,10 +32518,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3253032518 &mut y,
3253132519 &mut u,
3253232520 &mut v,
32533- &ref_y,
32534- &ref_u,
32535- &ref_v,
32536- &ref_slots,
32521+ refpix,
3253732522 &sign_bias_table,
3253832523 &global_motion,
3253932524 base_q_idx,
@@ -32603,10 +32588,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3260332588 &mut y,
3260432589 &mut u,
3260532590 &mut v,
32606- &ref_y,
32607- &ref_u,
32608- &ref_v,
32609- &ref_slots,
32591+ refpix,
3261032592 base_q_idx,
3261132593 &scan8,
3261232594 &scan4,
@@ -32905,10 +32887,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3290532887 &mut y,
3290632888 &mut u,
3290732889 &mut v,
32908- &ref_y,
32909- &ref_u,
32910- &ref_v,
32911- &ref_slots,
32890+ refpix,
3291232891 &sign_bias_table,
3291332892 &global_motion,
3291432893 base_q_idx,
@@ -33076,10 +33055,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3307633055 &mut y,
3307733056 &mut u,
3307833057 &mut v,
33079- &ref_y,
33080- &ref_u,
33081- &ref_v,
33082- &ref_slots,
33058+ refpix,
3308333059 &sign_bias_table,
3308433060 &global_motion,
3308533061 base_q_idx,
@@ -33226,10 +33202,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3322633202 &mut y,
3322733203 &mut u,
3322833204 &mut v,
33229- &ref_y,
33230- &ref_u,
33231- &ref_v,
33232- &ref_slots,
33205+ refpix,
3323333206 &sign_bias_table,
3323433207 &global_motion,
3323533208 base_q_idx,
@@ -33337,10 +33310,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3333733310 &mut y,
3333833311 &mut u,
3333933312 &mut v,
33340- &ref_y,
33341- &ref_u,
33342- &ref_v,
33343- &ref_slots,
33313+ refpix,
3334433314 &sign_bias_table,
3334533315 &global_motion,
3334633316 base_q_idx,
@@ -33424,10 +33394,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3342433394 &mut y,
3342533395 &mut u,
3342633396 &mut v,
33427- &ref_y,
33428- &ref_u,
33429- &ref_v,
33430- &ref_slots,
33397+ refpix,
3343133398 &sign_bias_table,
3343233399 &global_motion,
3343333400 base_q_idx,
@@ -33668,11 +33635,11 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3366833635 // 7.11.3.3's scaled walk. The counter is what
3366933636 // proves a gate actually reached a scaled
3367033637 // leaf rather than a same-size reference.
33671- if ref_y.width != frame_width as usize
33672- || ref_slots.iter().flatten().any(|(py, _, _)| {
33673- py.width != frame_width as usize
33638+ if (1..8).any(|rf| {
33639+ refpix.dims(rf).is_some_and(|(w, _)| {
33640+ w != frame_width as usize
3367433641 })
33675- {
33642+ }) {
3367633643 SCALED_LEAF8_HITS.with(|c| c.set(c.get() + 1));
3367733644 }
3367833645 let mut prev_leaves: Vec<((usize, usize), bool, bool, i8, Option<i8>)> = Vec::new();
@@ -33695,10 +33662,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3369533662 &mut y,
3369633663 &mut u,
3369733664 &mut v,
33698- &ref_y,
33699- &ref_u,
33700- &ref_v,
33701- &ref_slots,
33665+ refpix,
3370233666 &sign_bias_table,
3370333667 &global_motion,
3370433668 base_q_idx,
@@ -33736,10 +33700,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3373633700 &mut y,
3373733701 &mut u,
3373833702 &mut v,
33739- &ref_y,
33740- &ref_u,
33741- &ref_v,
33742- &ref_slots,
33703+ refpix,
3374333704 &sign_bias_table,
3374433705 &global_motion,
3374533706 base_q_idx,
@@ -33775,10 +33736,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3377533736 &mut y,
3377633737 &mut u,
3377733738 &mut v,
33778- &ref_y,
33779- &ref_u,
33780- &ref_v,
33781- &ref_slots,
33739+ refpix,
3378233740 base_q_idx,
3378333741 &scan8,
3378433742 &scan4,
@@ -33872,10 +33830,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3387233830 &mut y,
3387333831 &mut u,
3387433832 &mut v,
33875- &ref_y,
33876- &ref_u,
33877- &ref_v,
33878- &ref_slots,
33833+ refpix,
3387933834 &sign_bias_table,
3388033835 &global_motion,
3388133836 base_q_idx,
@@ -33925,10 +33880,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3392533880 &mut y,
3392633881 &mut u,
3392733882 &mut v,
33928- &ref_y,
33929- &ref_u,
33930- &ref_v,
33931- &ref_slots,
33883+ refpix,
3393233884 &sign_bias_table,
3393333885 &global_motion,
3393433886 base_q_idx,
@@ -33979,10 +33931,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3397933931 &mut y,
3398033932 &mut u,
3398133933 &mut v,
33982- &ref_y,
33983- &ref_u,
33984- &ref_v,
33985- &ref_slots,
33934+ refpix,
3398633935 &sign_bias_table,
3398733936 &global_motion,
3398833937 base_q_idx,
@@ -34043,10 +33992,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3404333992 &mut y,
3404433993 &mut u,
3404533994 &mut v,
34046- &ref_y,
34047- &ref_u,
34048- &ref_v,
34049- &ref_slots,
33995+ refpix,
3405033996 &sign_bias_table,
3405133997 &global_motion,
3405233998 base_q_idx,
@@ -34099,10 +34045,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3409934045 &mut y,
3410034046 &mut u,
3410134047 &mut v,
34102- &ref_y,
34103- &ref_u,
34104- &ref_v,
34105- &ref_slots,
34048+ refpix,
3410634049 &sign_bias_table,
3410734050 &global_motion,
3410834051 base_q_idx,
@@ -34156,10 +34099,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3415634099 &mut y,
3415734100 &mut u,
3415834101 &mut v,
34159- &ref_y,
34160- &ref_u,
34161- &ref_v,
34162- &ref_slots,
34102+ refpix,
3416334103 &sign_bias_table,
3416434104 &global_motion,
3416534105 base_q_idx,
@@ -34212,10 +34152,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3421234152 &mut y,
3421334153 &mut u,
3421434154 &mut v,
34215- &ref_y,
34216- &ref_u,
34217- &ref_v,
34218- &ref_slots,
34155+ refpix,
3421934156 &sign_bias_table,
3422034157 &global_motion,
3422134158 base_q_idx,
@@ -34270,10 +34207,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3427034207 &mut y,
3427134208 &mut u,
3427234209 &mut v,
34273- &ref_y,
34274- &ref_u,
34275- &ref_v,
34276- &ref_slots,
34210+ refpix,
3427734211 &sign_bias_table,
3427834212 &global_motion,
3427934213 base_q_idx,
@@ -34323,10 +34257,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3432334257 &mut y,
3432434258 &mut u,
3432534259 &mut v,
34326- &ref_y,
34327- &ref_u,
34328- &ref_v,
34329- &ref_slots,
34260+ refpix,
3433034261 &sign_bias_table,
3433134262 &global_motion,
3433234263 base_q_idx,
@@ -34376,10 +34307,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3437634307 &mut y,
3437734308 &mut u,
3437834309 &mut v,
34379- &ref_y,
34380- &ref_u,
34381- &ref_v,
34382- &ref_slots,
34310+ refpix,
3438334311 &sign_bias_table,
3438434312 &global_motion,
3438534313 base_q_idx,
@@ -34431,10 +34359,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3443134359 &mut y,
3443234360 &mut u,
3443334361 &mut v,
34434- &ref_y,
34435- &ref_u,
34436- &ref_v,
34437- &ref_slots,
34362+ refpix,
3443834363 &sign_bias_table,
3443934364 &global_motion,
3444034365 base_q_idx,
@@ -34484,10 +34409,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3448434409 &mut y,
3448534410 &mut u,
3448634411 &mut v,
34487- &ref_y,
34488- &ref_u,
34489- &ref_v,
34490- &ref_slots,
34412+ refpix,
3449134413 &sign_bias_table,
3449234414 &global_motion,
3449334415 base_q_idx,
@@ -34537,10 +34459,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3453734459 &mut y,
3453834460 &mut u,
3453934461 &mut v,
34540- &ref_y,
34541- &ref_u,
34542- &ref_v,
34543- &ref_slots,
34462+ refpix,
3454434463 &sign_bias_table,
3454534464 &global_motion,
3454634465 base_q_idx,
@@ -34593,10 +34512,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3459334512 &mut y,
3459434513 &mut u,
3459534514 &mut v,
34596- &ref_y,
34597- &ref_u,
34598- &ref_v,
34599- &ref_slots,
34515+ refpix,
3460034516 &sign_bias_table,
3460134517 &global_motion,
3460234518 base_q_idx,
@@ -34642,10 +34558,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3464234558 &mut y,
3464334559 &mut u,
3464434560 &mut v,
34645- &ref_y,
34646- &ref_u,
34647- &ref_v,
34648- &ref_slots,
34561+ refpix,
3464934562 &sign_bias_table,
3465034563 &global_motion,
3465134564 base_q_idx,
@@ -34695,10 +34608,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3469534608 &mut y,
3469634609 &mut u,
3469734610 &mut v,
34698- &ref_y,
34699- &ref_u,
34700- &ref_v,
34701- &ref_slots,
34611+ refpix,
3470234612 &sign_bias_table,
3470334613 &global_motion,
3470434614 base_q_idx,
@@ -34802,6 +34712,28 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3480234712 }
3480334713 }
3480434714 crate::timeline::recon_done();
34715+ // lane-twostage: the motion field is built from the mode-info grid alone
34716+ // (no pixel), so it moves up here with the CDFs -- everything a
34717+ // consuming frame's SETUP needs, published before this frame's filters.
34718+ let mut motion_field = Some(build_motion_field(
34719+ &grid,
34720+ mi_cols as usize,
34721+ mi_rows as usize,
34722+ order_hint,
34723+ order_hint_bits,
34724+ ref_order_hints,
34725+ fctx,
34726+ ));
34727+ if let Some(stage1) = stage1
34728+ && superres(fctx).is_none()
34729+ {
34730+ stage1(
34731+ result_cdfs.clone(),
34732+ motion_field.take().expect("the motion field was just built"),
34733+ frame_width as usize,
34734+ frame_height as usize,
34735+ );
34736+ }
3480534737
3480634738 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
3480734739 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
@@ -34948,15 +34880,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3494834880 }
3494934881
3495034882 crate::timeline::filters_done();
34951- let motion_field = build_motion_field(
34952- &grid,
34953- mi_cols as usize,
34954- mi_rows as usize,
34955- order_hint,
34956- order_hint_bits,
34957- ref_order_hints,
34958- fctx,
34959- );
3496034883
3496134884 let (fw, fh) = (lr_w, frame_height as usize);
3496234885 // An upscaled frame is already at its final size with no mi-aligned
@@ -35027,6 +34950,14 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
3502734950
3502834951 #[cfg(test)]
3502934952 mod tests {
34953+ /// lane-twostage: the reference bank these gates decode against --
34954+ /// `LAST_FRAME` alone, already in hand (`ref_frame` index 1).
34955+ fn last_only(reference: &Picture) -> RefPix<'_> {
34956+ let mut refs: [Option<&Picture>; 8] = [None; 8];
34957+ refs[1] = Some(reference);
34958+ RefPix::ready(refs)
34959+ }
34960+
3503034961
3503134962 /// lane-perf6 step 2: the CDEF kernel now reads a pre-gathered window and
3503234963 /// a pre-resolved damping shift instead of a bounds-testing closure and a
@@ -35808,27 +35739,25 @@ mod tests {
3580835739 fn a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name() {
3580935740 const REFUSAL: &str =
3581035741 "a reference frame selected with no picture at this frame's own ref_frame_idx slot";
35811- let plane = PlaneBuf {
35812- data: std::borrow::Cow::Owned(vec![0u16; 16]),
35742+ let pic = Picture {
3581335743 width: 4,
3581435744 height: 4,
35815- true_width: 4,
35816- true_height: 4,
35817- tile_x0: 0,
35818- tile_y0: 0,
35819- tile_x1: 4,
35820- tile_y1: 4,
35745+ y: vec![0u16; 16],
35746+ u: vec![0u16; 4],
35747+ v: vec![0u16; 4],
3582135748 };
35822- let empty: RefSlots = [None; 8];
35749+ let mut refs: [Option<&Picture>; 8] = [None; 8];
35750+ refs[1] = Some(&pic);
35751+ let refpix = RefPix::ready(refs);
3582335752 for ref_frame in [LAST2_FRAME, LAST3_FRAME, GOLDEN_FRAME, BWDREF_FRAME, ALTREF2_FRAME, ALTREF_FRAME] {
35824- let err = match ref_planes(ref_frame, &plane, &plane, &plane, &empty) {
35753+ let err = match ref_planes(ref_frame, &refpix) {
3582535754 Ok(_) => panic!("ref {ref_frame}: an empty slot resolved to a picture"),
3582635755 Err(e) => e.to_string(),
3582735756 };
3582835757 assert!(err.contains(REFUSAL), "ref {ref_frame}: expected {REFUSAL:?}, got: {err}");
3582935758 }
3583035759 // `LAST_FRAME` never consults the slots: `decode_stream` checked it.
35831- let Ok((y, _, _)) = ref_planes(LAST_FRAME, &plane, &plane, &plane, &empty) else {
35760+ let Ok((y, _, _)) = ref_planes(LAST_FRAME, &refpix) else {
3583235761 panic!("LAST_FRAME resolves to the frame's own reference planes")
3583335762 };
3583435763 assert_eq!(y.width, 4);
@@ -36102,8 +36031,7 @@ mod tests {
3610236031 40,
3610336032 64,
3610436033 64,
36105- &reference,
36106- [None; 8],
36034+ &last_only(&reference),
3610736035 &CdefParams::default(),
3610836036 &LoopFilterParams::default(),
3610936037 false,
@@ -36444,8 +36372,7 @@ mod tests {
3644436372 frame.base_q_idx,
3644536373 width as u32,
3644636374 height as u32,
36447- &reference,
36448- [None; 8],
36375+ &last_only(&reference),
3644936376 &CdefParams::default(),
3645036377 &LoopFilterParams::default(),
3645136378 false,
@@ -36563,37 +36490,21 @@ mod tests {
3656336490
3656436491 let (width, height) = (64usize, 64usize);
3656536492 let ref_pattern: Vec<u16> = (0..width * height).map(|i| (i % 251) as u16).collect();
36566- let ref_plane = |scale: usize| PlaneBuf {
36567- data: std::borrow::Cow::Owned(
36568- ref_pattern
36569- .iter()
36570- .step_by(scale.max(1))
36571- .take((width / scale) * (height / scale))
36572- .copied()
36573- .collect(),
36574- ),
36575- width: width / scale,
36576- height: height / scale,
36577- true_width: width / scale,
36578- true_height: height / scale,
36579- tile_x0: 0,
36580- tile_y0: 0,
36581- tile_x1: width / scale,
36582- tile_y1: height / scale,
36583- };
36584- let ref_y = PlaneBuf {
36585- data: std::borrow::Cow::Owned(ref_pattern.clone()),
36493+ let chroma: Vec<u16> = ref_pattern
36494+ .iter()
36495+ .step_by(2)
36496+ .take((width / 2) * (height / 2))
36497+ .copied()
36498+ .collect();
36499+ let reference = Picture {
3658636500 width,
3658736501 height,
36588- true_width: width,
36589- true_height: height,
36590- tile_x0: 0,
36591- tile_y0: 0,
36592- tile_x1: width,
36593- tile_y1: height,
36502+ y: ref_pattern.clone(),
36503+ u: chroma.clone(),
36504+ v: chroma,
3659436505 };
36595- let ref_u = ref_plane(2);
36596- let ref_v = ref_plane(2);
36506+ let refpix = &last_only(&reference);
36507+ let ref_y = whole_plane(&reference.y, width, height);
3659736508
3659836509 let mut y = PlaneBuf {
3659936510 data: std::borrow::Cow::Owned(vec![0u16; width * height]),
@@ -36644,10 +36555,7 @@ mod tests {
3664436555 &mut y,
3664536556 &mut u,
3664636557 &mut v,
36647- &ref_y,
36648- &ref_u,
36649- &ref_v,
36650- &[None; 8],
36558+ refpix,
3665136559 &NO_SIGN_BIAS,
3665236560 &[ec_av1_syntax::WarpParams::default(); 7],
3665336561 100,
@@ -36773,8 +36681,7 @@ mod tests {
3677336681 frame.base_q_idx,
3677436682 coded_w,
3677536683 coded_h,
36776- &reference,
36777- [None; 8],
36684+ &last_only(&reference),
3677836685 &CdefParams::default(),
3677936686 &LoopFilterParams::default(),
3678036687 false,
crates/ec-av1/src/stream.rsmodified+208 -58
@@ -343,7 +343,12 @@ pub fn frames_dispatched() -> usize {
343343 /// `refresh_frame_flags` names (spec 7.20), as one shared, never-mutated
344344 /// object -- so a slot costs an `Arc` clone instead of a picture copy.
345345 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,
347352 cdfs: Cdfs,
348353 motion_field: crate::motion_field::MotionField,
349354 seg_map: Vec<u8>,
@@ -371,18 +376,18 @@ struct SlotValue {
371376 /// Each dispatched frame gets its own thread, so a blocked waiter never holds
372377 /// a resource its producer needs. A producer that errors or panics marks its
373378 /// promise `Failed`, so no consumer can wait for a value that never comes.
374-struct SlotPromise {
375- state: std::sync::Mutex<PromiseState>,
379+struct SlotPromise<T = std::sync::Arc<SlotValue>> {
380+ state: std::sync::Mutex<PromiseState<T>>,
376381 ready: std::sync::Condvar,
377382 }
378383
379-enum PromiseState {
384+enum PromiseState<T> {
380385 Pending,
381- Ready(std::sync::Arc<SlotValue>),
386+ Ready(T),
382387 Failed,
383388 }
384389
385-impl SlotPromise {
390+impl<T: Clone> SlotPromise<T> {
386391 fn pending() -> std::sync::Arc<Self> {
387392 std::sync::Arc::new(Self {
388393 state: std::sync::Mutex::new(PromiseState::Pending),
@@ -391,18 +396,29 @@ impl SlotPromise {
391396 }
392397
393398 /// 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> {
395400 std::sync::Arc::new(Self {
396401 state: std::sync::Mutex::new(PromiseState::Ready(value)),
397402 ready: std::sync::Condvar::new(),
398403 })
399404 }
400405
401- fn fulfil(&self, value: std::sync::Arc<SlotValue>) {
406+ fn fulfil(&self, value: T) {
402407 *self.state.lock().expect("slot promise") = PromiseState::Ready(value);
403408 self.ready.notify_all();
404409 }
405410
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+
406422 fn fail(&self) {
407423 let mut state = self.state.lock().expect("slot promise");
408424 if matches!(*state, PromiseState::Pending) {
@@ -412,7 +428,7 @@ impl SlotPromise {
412428 }
413429
414430 /// Blocks until the producing frame has published this slot.
415- fn wait(&self) -> Result<std::sync::Arc<SlotValue>> {
431+ fn wait(&self) -> Result<T> {
416432 let mut state = self.state.lock().expect("slot promise");
417433 loop {
418434 match &*state {
@@ -643,16 +659,17 @@ pub fn decode_stream_with_threads(
643659 jobs.submit(move || {
644660 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
645661 let value = promise.wait()?;
662+ let shown_picture = value.pixels.wait()?;
646663 let output = if grain.apply_grain && !no_grain() {
647664 std::sync::Arc::new(crate::film_grain::apply_grain(
648- &value.picture,
665+ &shown_picture,
649666 &grain,
650667 seq.mc_identity,
651668 u32::from(seq.bit_depth),
652669 &crate::decode::FrameCtx::new(),
653670 ))
654671 } else {
655- std::sync::Arc::clone(&value.picture)
672+ std::sync::Arc::clone(&shown_picture)
656673 };
657674 Ok((output, decode_idx, true))
658675 }))
@@ -871,6 +888,12 @@ pub fn decode_stream_with_threads(
871888 crate::timeline::submit(decode_idx, if shown { 'P' } else { 'A' }, shown);
872889 jobs.submit(move || {
873890 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();
874897 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
875898 crate::timeline::start(decode_idx);
876899 // The wait happens HERE, off the parsing thread, and only
@@ -893,6 +916,71 @@ pub fn decode_stream_with_threads(
893916 // Fresh per-thread state: every field this path reads is
894917 // written from this frame's own header before it is read.
895918 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+ };
896984 // spec 7.9's `av1_setup_motion_field` runs inside
897985 // `RefSnapshot::take`, i.e. here, after those waits --
898986 // it reads the referenced slots' saved motion fields.
@@ -901,7 +989,7 @@ pub fn decode_stream_with_threads(
901989 let snap = RefSnapshot::take(
902990 &header,
903991 seq,
904- std::array::from_fn(|i| resolved[i].as_ref().map(|v| &*v.picture)),
992+ &refpix,
905993 std::array::from_fn(|i| resolved[i].as_ref().map(|v| &v.cdfs)),
906994 std::array::from_fn(|i| {
907995 resolved[i].as_ref().map(|v| v.seg_map.as_slice())
@@ -918,19 +1006,41 @@ pub fn decode_stream_with_threads(
9181006 decode_idx,
9191007 shown_idx,
9201008 dump.as_deref(),
1009+ // lane-twostage is OFF by default: it is byte-exact
1010+ // and the chain shows the producer tail overlapped,
1011+ // but it does not move the wall (the consumer parses
1012+ // only 4.2% of its tile before its first reference
1013+ // pixel read, which is shorter than the tail it
1014+ // hides). `EC_AV1_TWO_STAGE=1` publishes a frame's
1015+ // meta at its tile boundary instead of after its
1016+ // filters; it pays only once the 8x8-leaf, OBMC and
1017+ // sub-8x8-piece predictions are deferred to the recon
1018+ // workers as well.
1019+ crate::envflags::var("EC_AV1_TWO_STAGE")
1020+ .is_ok_and(|v| v == "1")
1021+ .then_some(&stage1 as &dyn Fn(_, _, _, _)),
9211022 )?;
9221023 // Publish before grain synthesis: every frame waiting on
9231024 // this slot can start the moment the clean picture exists
9241025 // (spec 7.18.3.1 -- the bank never stores grain).
9251026 let picture = std::sync::Arc::new(out.picture);
1027+ pixels.fulfil(picture.clone());
9261028 if let Some(promise) = &promise {
927- promise.fulfil(std::sync::Arc::new(SlotValue {
928- picture: picture.clone(),
929- cdfs: out.stored_cdfs,
930- motion_field: out.motion_field,
931- seg_map: out.seg_map,
932- order_hint: header.order_hint,
933- }));
1029+ // Only a frame whose stage-1 sink never fired (a
1030+ // superres frame) still has meta to publish here.
1031+ promise.fulfil_if_pending(|| {
1032+ std::sync::Arc::new(SlotValue {
1033+ pixels: pixels.clone(),
1034+ width: picture.width,
1035+ height: picture.height,
1036+ cdfs: out.stored_cdfs,
1037+ motion_field: out.motion_field.expect(
1038+ "a frame that published no stage 1 carries its motion field back",
1039+ ),
1040+ seg_map: out.seg_map,
1041+ order_hint: header.order_hint,
1042+ })
1043+ });
9341044 crate::timeline::slot_fulfil();
9351045 }
9361046 // Grain is synthesised for OUTPUT only: a hidden frame is
@@ -957,10 +1067,13 @@ pub fn decode_stream_with_threads(
9571067 });
9581068 // A frame nobody can decode must not leave its consumers
9591069 // waiting for a slot that will never be filled.
960- if reply.is_err()
961- && let Some(promise) = &promise
962- {
963- promise.fail();
1070+ if reply.is_err() {
1071+ // Neither stage may leave a consumer waiting for a value
1072+ // that will never come.
1073+ if let Some(promise) = &promise {
1074+ promise.fail();
1075+ }
1076+ pixels.fail();
9641077 }
9651078 let _ = tx.send((job_seq, true, reply));
9661079 });
@@ -979,10 +1092,21 @@ pub fn decode_stream_with_threads(
9791092 }
9801093 continue;
9811094 }
1095+ // lane-twostage: the inline path's references are decoded already,
1096+ // so its handle never waits.
1097+ let inline_refpix = decode::RefPix::ready(std::array::from_fn(|i| {
1098+ if i == 0 {
1099+ None
1100+ } else {
1101+ ref_slots
1102+ .get(header.ref_frame_idx[i - 1] as usize)
1103+ .and_then(|p| p.as_deref())
1104+ }
1105+ }));
9821106 let snap = RefSnapshot::take(
9831107 &header,
9841108 seq,
985- std::array::from_fn(|i| ref_slots[i].as_deref()),
1109+ &inline_refpix,
9861110 std::array::from_fn(|i| cdf_slots[i].as_ref()),
9871111 std::array::from_fn(|i| seg_map_slots[i].as_deref()),
9881112 &std::array::from_fn(|i| motion_field_slots[i].as_ref()),
@@ -1003,7 +1127,10 @@ pub fn decode_stream_with_threads(
10031127 pictures_decoded,
10041128 pictures_shown,
10051129 final_dump.as_deref(),
1130+ None,
10061131 )?;
1132+ let motion_field =
1133+ motion_field.expect("the inline path passes no stage-1 sink");
10071134 pictures_decoded += 1;
10081135 // lane-pool1: one allocation, then every slot store and the output
10091136 // itself are refcount bumps instead of plane copies.
@@ -1014,7 +1141,9 @@ pub fn decode_stream_with_threads(
10141141 // already resolved, since the picture exists right here.
10151142 if header.refresh_frame_flags != 0 {
10161143 let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue {
1017- picture: std::sync::Arc::clone(&picture),
1144+ pixels: SlotPromise::ready(std::sync::Arc::clone(&picture)),
1145+ width: picture.width,
1146+ height: picture.height,
10181147 cdfs: stored_cdfs,
10191148 motion_field,
10201149 seg_map: decoded_seg_map,
@@ -1131,8 +1260,9 @@ impl SeqFlags {
11311260 /// banks `decode_stream_with` owns -- taken on the parsing thread, before any
11321261 /// later frame can overwrite a slot, so a frame can be decoded anywhere.
11331262 pub(crate) struct RefSnapshot<'a> {
1134- /// The 8 DPB slots, indexed by slot (NOT by `ref_frame_idx`).
1135- pub(crate) refs: [Option<&'a Picture>; NUM_REF_FRAMES],
1263+ /// lane-twostage: this frame's references, indexed by `ref_frame`
1264+ /// (`LAST_FRAME` = 1) -- sizes now, pixels at the first prediction.
1265+ pub(crate) refpix: &'a decode::RefPix<'a>,
11361266 /// `cdf_slots[ref_frame_idx[primary_ref_frame]]`, `None` when this frame
11371267 /// names `PRIMARY_REF_NONE` *or* that slot holds no saved table (the
11381268 /// second case is the refusal [`decode_frame`] raises where it always
@@ -1155,7 +1285,7 @@ impl<'a> RefSnapshot<'a> {
11551285 fn take(
11561286 header: &FrameHeader,
11571287 seq: SeqFlags,
1158- refs: [Option<&'a Picture>; NUM_REF_FRAMES],
1288+ refpix: &'a decode::RefPix<'a>,
11591289 cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES],
11601290 seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES],
11611291 motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES],
@@ -1189,7 +1319,7 @@ impl<'a> RefSnapshot<'a> {
11891319 );
11901320 }
11911321 Self {
1192- refs,
1322+ refpix,
11931323 primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),
11941324 prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].map(<[u8]>::to_vec)),
11951325 tpl_field,
@@ -1206,10 +1336,27 @@ impl<'a> RefSnapshot<'a> {
12061336 pub(crate) struct FrameOutput {
12071337 pub(crate) picture: Picture,
12081338 pub(crate) stored_cdfs: Cdfs,
1209- pub(crate) motion_field: crate::motion_field::MotionField,
1339+ /// lane-twostage: `None` when this frame handed its motion field to the
1340+ /// stage-1 sink at its tile boundary instead of carrying it back here.
1341+ pub(crate) motion_field: Option<crate::motion_field::MotionField>,
12101342 pub(crate) seg_map: Vec<u8>,
12111343 }
12121344
1345+/// Spec 7.20's own `save_cdfs`: what a frame's `refresh_frame_flags` slots
1346+/// keep -- the frame's INITIAL table when `disable_frame_end_update_cdf`,
1347+/// otherwise the adapted end-of-tile table with every symbol counter zeroed
1348+/// (libaom `av1_reset_cdf_symbol_counters`). lane-twostage: shared with the
1349+/// stage-1 publish, which hands a consumer the same table it always got.
1350+fn stored_cdfs_for(header: &FrameHeader, end_cdfs: Cdfs, started_from: Option<Cdfs>) -> Cdfs {
1351+ if header.disable_frame_end_update_cdf {
1352+ started_from.unwrap_or_else(|| Cdfs::new(q_ctx_of(header.quantization.base_q_idx)))
1353+ } else {
1354+ let mut end_cdfs = end_cdfs;
1355+ end_cdfs.reset_counts();
1356+ end_cdfs
1357+ }
1358+}
1359+
12131360 /// lane-thread2: one coded frame, decoded from its header, its tile payload
12141361 /// and a snapshot of the reference banks -- and from nothing else. Lifted
12151362 /// verbatim out of [`decode_stream_with`]'s loop so that the same code can
@@ -1233,6 +1380,8 @@ fn decode_frame(
12331380 decode_idx: usize,
12341381 shown_idx: usize,
12351382 final_dump: Option<&str>,
1383+ // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`.
1384+ stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>,
12361385 ) -> Result<FrameOutput> {
12371386 if header.segmentation.enabled {
12381387 for segment in 0..MAX_SEGMENTS {
@@ -1568,15 +1717,16 @@ fn decode_frame(
15681717 // never a projection source, and never spends a `ref_stamp`.
15691718 true,
15701719 );
1571- (picture, end_cdfs, motion_field)
1720+ (picture, end_cdfs, Some(motion_field))
15721721 } else {
15731722 let last_slot = header.ref_frame_idx[0] as usize;
1574- let reference = snap.refs[last_slot].ok_or_else(|| {
1575- Error::unsupported(
1723+ let _ = last_slot;
1724+ if snap.refpix.dims(1).is_none() {
1725+ return Err(Error::unsupported(
15761726 "AV1 decode_stream",
15771727 "an inter frame with no key frame before it",
1578- )
1579- })?;
1728+ ));
1729+ }
15801730 // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`
15811731 // (spec 7.8/7.20). Any of them having no picture yet is not a
15821732 // stream error on its own: `decode_inter_block` only needs a
@@ -1589,20 +1739,26 @@ fn decode_frame(
15891739 if header.force_integer_mv {
15901740 decode::note_force_integer_mv_frame();
15911741 }
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- });
16021742 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
16031743 // this frame's header actually asks for temporal candidates --
16041744 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
16051745 // behaviour bit for bit when this is `None` (see its own doc).
1746+ // lane-twostage: the stage-1 sink is handed the table a consumer
1747+ // would have read out of the slot, not the raw end-of-tile one.
1748+ let started_from_stage1 = started_from.clone();
1749+ let stage1_adapter = stage1.map(|sink| {
1750+ move |end_cdfs: Cdfs,
1751+ motion_field: crate::motion_field::MotionField,
1752+ width: usize,
1753+ height: usize| {
1754+ sink(
1755+ stored_cdfs_for(header, end_cdfs, started_from_stage1.clone()),
1756+ motion_field,
1757+ width,
1758+ height,
1759+ )
1760+ }
1761+ });
16061762 let tpl_field = &snap.tpl_field;
16071763 let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(
16081764 &tile_bufs,
@@ -1619,8 +1775,7 @@ fn decode_frame(
16191775 },
16201776 header.frame_width,
16211777 header.frame_height,
1622- reference,
1623- other_refs,
1778+ snap.refpix,
16241779 &header.cdef,
16251780 &header.loop_filter,
16261781 &header.loop_restoration,
@@ -1647,7 +1802,11 @@ fn decode_frame(
16471802 header.allow_warped_motion,
16481803 header.allow_screen_content_tools,
16491804 header.delta,
1650- enable_filter_intra, fctx,
1805+ enable_filter_intra,
1806+ stage1_adapter
1807+ .as_ref()
1808+ .map(|f| f as &dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)),
1809+ fctx,
16511810 )?;
16521811 (picture, end_cdfs, motion_field)
16531812 };
@@ -1657,16 +1816,7 @@ fn decode_frame(
16571816 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
16581817 // *initial* table into the slots it refreshes, not the adapted
16591818 // end-of-tile one.
1660- let stored_cdfs = if header.disable_frame_end_update_cdf {
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- };
1819+ let stored_cdfs = stored_cdfs_for(header, end_cdfs, started_from);
16701820 if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
16711821 use std::io::Write;
16721822 if let Ok(mut f) = std::fs::OpenOptions::new()