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+237 -330
@@ -13006,7 +13006,6 @@ struct PlaneBuf<'a> {
13006 /// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already13006 /// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
13007 /// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/13007 /// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
13008 /// `ALTREF2`/`ALTREF`).13008 /// `ALTREF2`/`ALTREF`).
13009-type RefSlots<'a> = [Option<(&'a PlaneBuf<'a>, &'a PlaneBuf<'a>, &'a PlaneBuf<'a>)>; 8];
13010 13009
13011 impl PlaneBuf<'_> {13010 impl PlaneBuf<'_> {
13012 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/13011 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
@@ -23199,29 +23198,126 @@ fn read_single_ref(
23199 /// own doc. Called from [`decode_inter_block`] once its own `reference_select`23198 /// own doc. Called from [`decode_inter_block`] once its own `reference_select`
23200 /// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same23199 /// parameter is set; [`decode_inter_block8`]'s 8x8 leaf path gates the same
23201 /// way with a coarser (`LAST_FRAME`-only) neighbour shape.23200 /// way with a coarser (`LAST_FRAME`-only) neighbour shape.
23202-/// Resolves a compound reference's own planes -- the same `ref_frame ==23201+/// lane-twostage: this frame's references as DIMENSIONS now and PIXELS on
23203-/// LAST_FRAME -> ref_y/u/v, else other_refs[ref_frame]` lookup23202+/// demand. An inter tile's parse reads reference SIZES (`mc::scale_factor`)
23204-/// [`decode_inter_block`]'s single-ref path already does, factored out so23203+/// but touches no reference PIXEL until its first prediction -- measured 4.2%
23205-/// the compound path can call it twice (lane-av1comp).23204+/// of a 4K tile's parse into it -- so the pictures are resolved here, at the
23206-fn ref_planes<'a>(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>(
23207 ref_frame: i8,23310 ref_frame: i8,
23208- ref_y: &'a PlaneBuf<'a>,23311+ refpix: &'a RefPix<'p>,
23209- ref_u: &'a PlaneBuf<'a>,23312+) -> Result<(&'a PlaneBuf<'p>, &'a PlaneBuf<'p>, &'a PlaneBuf<'p>)> {
23210- ref_v: &'a PlaneBuf<'a>,23313+ match refpix.planes()?.get(ref_frame as usize).and_then(Option::as_ref) {
23211- other_refs: &'a RefSlots,23314+ Some((y, u, v)) => Ok((y, u, v)),
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(23315 None => Err(unsupported(
23219 "a reference frame selected with no picture at this frame's own \23316 "a reference frame selected with no picture at this frame's own \
23220 ref_frame_idx slot for it",23317 ref_frame_idx slot for it",
23221 )),23318 )),
23222 }23319 }
23223 }23320 }
23224-}
23225 23321
23226 /// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row23322 /// libaom `foreach_overlappable_nb_above` (`obmc.h`): walks the mi row
23227 /// directly above this block's own column span, one bordering block at a23323 /// directly above this block's own column span, one bordering block at a
@@ -23933,10 +24029,7 @@ fn obmc_blend(
23933 py: usize,24029 py: usize,
23934 cpx: usize,24030 cpx: usize,
23935 cpy: usize,24031 cpy: usize,
23936- ref_y: &PlaneBuf<'_>,24032+ refpix: &RefPix<'_>,
23937- ref_u: &PlaneBuf<'_>,
23938- ref_v: &PlaneBuf<'_>,
23939- other_refs: &RefSlots,
23940 interp_fixed: Option<mc::InterpFilterKind>,24033 interp_fixed: Option<mc::InterpFilterKind>,
23941 // lane-scaledref r1: this frame's own coded luma width -- each OBMC24034 // lane-scaledref r1: this frame's own coded luma width -- each OBMC
23942 // neighbour is re-predicted against ITS OWN reference, which may be24035 // neighbour is re-predicted against ITS OWN reference, which may be
@@ -24047,7 +24140,7 @@ fn obmc_blend(
24047 );24140 );
24048 let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?;24141 let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?;
24049 ec_obmc_trace("above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);24142 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)?;
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_col + off4 + span4 > mi_cols {24145 if mi_col + off4 + span4 > mi_cols {
24053 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));24146 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));
@@ -24083,7 +24176,7 @@ fn obmc_blend(
24083 );24176 );
24084 let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?;24177 let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?;
24085 ec_obmc_trace("left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind);24178 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)?;
24087 let nb_scale = mc::scale_factor(ny.width, frame_width);24180 let nb_scale = mc::scale_factor(ny.width, frame_width);
24088 if mi_row + off4 + span4 > mi_rows {24181 if mi_row + off4 + span4 > mi_rows {
24089 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));24182 OBMC_EDGE_SPAN_HITS.with(|c| c.set(c.get() + 1));
@@ -24516,16 +24609,13 @@ fn decode_inter_block(
24516 y: &mut PlaneBuf<'static>,24609 y: &mut PlaneBuf<'static>,
24517 u: &mut PlaneBuf<'static>,24610 u: &mut PlaneBuf<'static>,
24518 v: &mut PlaneBuf<'static>,24611 v: &mut PlaneBuf<'static>,
24519- ref_y: &PlaneBuf<'_>,24612+ refpix: &RefPix<'_>,
24520- ref_u: &PlaneBuf<'_>,
24521- ref_v: &PlaneBuf<'_>,
24522 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own24613 // lane-av1refs: every non-`LAST_FRAME` reference this frame header's own
24523 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`24614 // `ref_frame_idx` names a live DPB slot for, indexed `[ref_frame]`
24524 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`24615 // (`LAST2_FRAME`=2 .. `ALTREF_FRAME`=7; index 0/1 unused, `LAST_FRAME`
24525 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the24616 // stays on `ref_y`/`u`/`v` above) -- `None` at a live index means the
24526 // slot's still empty (an error-resilient stream, or too early in the24617 // slot's still empty (an error-resilient stream, or too early in the
24527 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.24618 // GOP), matching `GOLDEN_FRAME`'s existing empty-slot refusal below.
24528- other_refs: &RefSlots,
24529 sign_bias_table: &SignBiasTable,24619 sign_bias_table: &SignBiasTable,
24530 // lane-gm r2: this frame header's own `global_motion` table (spec24620 // lane-gm r2: this frame header's own `global_motion` table (spec
24531 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`24621 // 5.9.24), indexed `[ref_frame - LAST_FRAME]` same as `sign_bias_table`
@@ -24937,8 +25027,8 @@ fn decode_inter_block(
24937 if gm_nontrans_models && !gm_nontrans {25027 if gm_nontrans_models && !gm_nontrans {
24938 GM_NONTRANS_SMALL_SIDE_HITS.with(|c| c.set(c.get() + 1));25028 GM_NONTRANS_SMALL_SIDE_HITS.with(|c| c.set(c.get() + 1));
24939 }25029 }
24940- let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;25030+ let (py0, pu0, pv0) = ref_planes(ref0, refpix)?;
24941- let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;25031+ let (py1, pu1, pv1) = ref_planes(ref1, refpix)?;
24942 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is25032 // lane-cwarp r1: `is_global_mv_block` (blockd.h:421-429) is
24943 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and25033 // PER REFERENCE SLOT -- mode GLOBAL_GLOBALMV, block >= 8x8, and
24944 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from25034 // THAT slot's own gm model > TRANSLATION. `bw4`/`bh4` come from
@@ -24980,7 +25070,7 @@ fn decode_inter_block(
24980 // scaled (superres) is predicted translationally while its25070 // scaled (superres) is predicted translationally while its
24981 // sibling may still warp.25071 // sibling may still warp.
24982 let ref_unscaled = |rf: i8| {25072 let ref_unscaled = |rf: i8| {
24983- ref_planes(rf, ref_y, ref_u, ref_v, other_refs)25073+ ref_planes(rf, refpix)
24984 .is_ok_and(|(py, _, _)| {25074 .is_ok_and(|(py, _, _)| {
24985 mc::scale_factor(py.width, frame_width) == mc::REF_NO_SCALE25075 mc::scale_factor(py.width, frame_width) == mc::REF_NO_SCALE
24986 })25076 })
@@ -26061,19 +26151,7 @@ fn decode_inter_block(
26061 // below same as every other non-`LAST_FRAME` reference. lane-av1refs26151 // below same as every other non-`LAST_FRAME` reference. lane-av1refs
26062 // widens this from GOLDEN alone to every reference `read_single_ref`26152 // widens this from GOLDEN alone to every reference `read_single_ref`
26063 // can name.26153 // can name.
26064- let (py_ref, pu_ref, pv_ref) = if ref_frame == LAST_FRAME {26154+ let (py_ref, pu_ref, pv_ref) = ref_planes(ref_frame, refpix)?;
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- };
26077 26155
26078 let (mi_row, mi_col) = (rmi, cmi);26156 let (mi_row, mi_col) = (rmi, cmi);
26079 // lane-rect r2: the mv stack must be queried with the block's26157 // lane-rect r2: the mv stack must be queried with the block's
@@ -26870,10 +26948,7 @@ fn decode_inter_block(
26870 py,26948 py,
26871 cpx,26949 cpx,
26872 cpy,26950 cpy,
26873- ref_y,26951+ refpix,
26874- ref_u,
26875- ref_v,
26876- other_refs,
26877 interp_fixed,26952 interp_fixed,
26878 frame_width,26953 frame_width,
26879 &mut pred_y,26954 &mut pred_y,
@@ -26902,7 +26977,7 @@ fn decode_inter_block(
26902 // reference was scaled, which silently left the whole-block26977 // reference was scaled, which silently left the whole-block
26903 // prediction in place instead of refusing. It scales off the26978 // prediction in place instead of refusing. It scales off the
26904 // PREVIOUS strip's own reference, not this block's.26979 // 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)?;
26906 let prev_scale = mc::scale_factor(prev_y_plane.width, frame_width);26981 let prev_scale = mc::scale_factor(prev_y_plane.width, frame_width);
26907 for (src, dst) in [(prev_u, &mut pred_u), (prev_v_plane, &mut pred_v)] {26982 for (src, dst) in [(prev_u, &mut pred_u), (prev_v_plane, &mut pred_v)] {
26908 let mut piece = vec![0u16; piece_w * piece_h];26983 let mut piece = vec![0u16; piece_w * piece_h];
@@ -28303,10 +28378,7 @@ fn decode_inter_sub8_split4(
28303 y: &mut PlaneBuf<'static>,28378 y: &mut PlaneBuf<'static>,
28304 u: &mut PlaneBuf<'static>,28379 u: &mut PlaneBuf<'static>,
28305 v: &mut PlaneBuf<'static>,28380 v: &mut PlaneBuf<'static>,
28306- ref_y: &PlaneBuf<'_>,28381+ refpix: &RefPix<'_>,
28307- ref_u: &PlaneBuf<'_>,
28308- ref_v: &PlaneBuf<'_>,
28309- other_refs: &RefSlots,
28310 sign_bias_table: &SignBiasTable,28382 sign_bias_table: &SignBiasTable,
28311 global_motion: &[ec_av1_syntax::WarpParams; 7],28383 global_motion: &[ec_av1_syntax::WarpParams; 7],
28312 base_q_idx: u8,28384 base_q_idx: u8,
@@ -28424,7 +28496,7 @@ fn decode_inter_sub8_split4(
28424 neighbours.left_ref[rmi],28496 neighbours.left_ref[rmi],
28425 neighbours.left_ref1[rmi],28497 neighbours.left_ref1[rmi],
28426 );28498 );
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)?;
28428 // lane-t900 r28: refusal lifted -- this sub-block's own reference may28500 // lane-t900 r28: refusal lifted -- this sub-block's own reference may
28429 // be scaled (superres); spec 7.11.3.3's walk is per reference, and28501 // be scaled (superres); spec 7.11.3.3's walk is per reference, and
28430 // each of the group's pieces (luma and its 2x2 chroma) carries its28502 // each of the group's pieces (luma and its 2x2 chroma) carries its
@@ -28694,7 +28766,7 @@ fn decode_inter_sub8_split4(
28694 continue;28766 continue;
28695 };28767 };
28696 let (piece_ref_y, sref_u, sref_v) =28768 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)?;
28698 let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width);28770 let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width);
28699 let (ox, oy) = if mixed {28771 let (ox, oy) = if mixed {
28700 (cpx, cpy)28772 (cpx, cpy)
@@ -29258,10 +29330,7 @@ fn decode_inter_sub8_rect2(
29258 y: &mut PlaneBuf<'static>,29330 y: &mut PlaneBuf<'static>,
29259 u: &mut PlaneBuf<'static>,29331 u: &mut PlaneBuf<'static>,
29260 v: &mut PlaneBuf<'static>,29332 v: &mut PlaneBuf<'static>,
29261- ref_y: &PlaneBuf<'_>,29333+ refpix: &RefPix<'_>,
29262- ref_u: &PlaneBuf<'_>,
29263- ref_v: &PlaneBuf<'_>,
29264- other_refs: &RefSlots,
29265 sign_bias_table: &SignBiasTable,29334 sign_bias_table: &SignBiasTable,
29266 global_motion: &[ec_av1_syntax::WarpParams; 7],29335 global_motion: &[ec_av1_syntax::WarpParams; 7],
29267 base_q_idx: u8,29336 base_q_idx: u8,
@@ -29397,7 +29466,7 @@ fn decode_inter_sub8_rect2(
29397 neighbours.left_ref[rmi],29466 neighbours.left_ref[rmi],
29398 neighbours.left_ref1[rmi],29467 neighbours.left_ref1[rmi],
29399 );29468 );
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)?;
29401 // lane-t900 r28: refusal lifted -- see the split arm above.29470 // lane-t900 r28: refusal lifted -- see the split arm above.
29402 let luma_scale = mc::scale_factor(sref_y.width, frame_width);29471 let luma_scale = mc::scale_factor(sref_y.width, frame_width);
29403 if luma_scale != mc::REF_NO_SCALE {29472 if luma_scale != mc::REF_NO_SCALE {
@@ -29709,7 +29778,7 @@ fn decode_inter_sub8_rect2(
29709 continue;29778 continue;
29710 };29779 };
29711 let (piece_ref_y, sref_u, sref_v) =29780 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)?;
29713 let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width);29782 let piece_scale = mc::scale_factor(piece_ref_y.width, frame_width);
29714 let (ox, oy) = if mixed {29783 let (ox, oy) = if mixed {
29715 (cpx, cpy)29784 (cpx, cpy)
@@ -29863,10 +29932,7 @@ fn decode_inter_block8(
29863 y: &mut PlaneBuf<'static>,29932 y: &mut PlaneBuf<'static>,
29864 u: &mut PlaneBuf<'static>,29933 u: &mut PlaneBuf<'static>,
29865 v: &mut PlaneBuf<'static>,29934 v: &mut PlaneBuf<'static>,
29866- ref_y: &PlaneBuf<'_>,29935+ refpix: &RefPix<'_>,
29867- ref_u: &PlaneBuf<'_>,
29868- ref_v: &PlaneBuf<'_>,
29869- other_refs: &RefSlots,
29870 base_q_idx: u8,29936 base_q_idx: u8,
29871 scan8: &[u16],29937 scan8: &[u16],
29872 scan4: &[u16],29938 scan4: &[u16],
@@ -30328,8 +30394,8 @@ fn decode_inter_block8(
30328 COMPOUND8_FILTER_HITS.with(|c| c.set(c.get() + 1));30394 COMPOUND8_FILTER_HITS.with(|c| c.set(c.get() + 1));
30329 }30395 }
30330 30396
30331- let (py0, pu0, pv0) = ref_planes(ref0, ref_y, ref_u, ref_v, other_refs)?;30397+ let (py0, pu0, pv0) = ref_planes(ref0, refpix)?;
30332- let (py1, pu1, pv1) = ref_planes(ref1, ref_y, ref_u, ref_v, other_refs)?;30398+ let (py1, pu1, pv1) = ref_planes(ref1, refpix)?;
30333 let scale0 = mc::scale_factor(py0.width, frame_width);30399 let scale0 = mc::scale_factor(py0.width, frame_width);
30334 let scale1 = mc::scale_factor(py1.width, frame_width);30400 let scale1 = mc::scale_factor(py1.width, frame_width);
30335 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {30401 if scale0 != mc::REF_NO_SCALE || scale1 != mc::REF_NO_SCALE {
@@ -30382,7 +30448,7 @@ fn decode_inter_block8(
30382 // lane-t900 r28: same per-slot `allow_warp` scale bail-out as30448 // lane-t900 r28: same per-slot `allow_warp` scale bail-out as
30383 // the 16x16-and-bigger compound path above.30449 // the 16x16-and-bigger compound path above.
30384 let leaf_ref_unscaled = |rf: i8| {30450 let leaf_ref_unscaled = |rf: i8| {
30385- ref_planes(rf, ref_y, ref_u, ref_v, other_refs)30451+ ref_planes(rf, refpix)
30386 .is_ok_and(|(py, _, _)| {30452 .is_ok_and(|(py, _, _)| {
30387 mc::scale_factor(py.width, frame_width) == mc::REF_NO_SCALE30453 mc::scale_factor(py.width, frame_width) == mc::REF_NO_SCALE
30388 })30454 })
@@ -30757,7 +30823,7 @@ fn decode_inter_block8(
30757 neighbours.left_ref1[rmi],30823 neighbours.left_ref1[rmi],
30758 );30824 );
30759 leaf_refs = (ref_frame, None);30825 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)?;
30761 30827
30762 let (mi_row, mi_col) = leaf_mi;30828 let (mi_row, mi_col) = leaf_mi;
30763 // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS30829 // lane-inter8 r2: the frame's temporal mv candidates, keyed on THIS
@@ -31192,10 +31258,7 @@ fn decode_inter_block8(
31192 py,31258 py,
31193 cpx,31259 cpx,
31194 cpy,31260 cpy,
31195- ref_y,31261+ refpix,
31196- ref_u,
31197- ref_v,
31198- other_refs,
31199 interp_fixed,31262 interp_fixed,
31200 frame_width,31263 frame_width,
31201 &mut pred_y,31264 &mut pred_y,
@@ -31897,8 +31960,7 @@ pub(crate) fn decode_inter_frame_tile(
31897 base_q_idx: u8,31960 base_q_idx: u8,
31898 frame_width: u32,31961 frame_width: u32,
31899 frame_height: u32,31962 frame_height: u32,
31900- reference: &Picture,31963+ refpix: &RefPix<'_>,
31901- other_refs: [Option<&Picture>; 8],
31902 cdef: &CdefParams,31964 cdef: &CdefParams,
31903 loop_filter: &LoopFilterParams,31965 loop_filter: &LoopFilterParams,
31904 allow_high_precision_mv: bool,31966 allow_high_precision_mv: bool,
@@ -31921,8 +31983,7 @@ pub(crate) fn decode_inter_frame_tile(
31921 crate::quant::QuantDeltas::default(),31983 crate::quant::QuantDeltas::default(),
31922 frame_width,31984 frame_width,
31923 frame_height,31985 frame_height,
31924- reference,31986+ refpix,
31925- other_refs,
31926 cdef,31987 cdef,
31927 loop_filter,31988 loop_filter,
31928 &LoopRestorationParams::default(),31989 &LoopRestorationParams::default(),
@@ -31954,7 +32015,9 @@ pub(crate) fn decode_inter_frame_tile(
31954 // `enable_filter_intra`: this crate's own encoder never writes the32015 // `enable_filter_intra`: this crate's own encoder never writes the
31955 // sequence bit (`encode.rs`), so no intra-in-inter block of a stream32016 // sequence bit (`encode.rs`), so no intra-in-inter block of a stream
31956 // reaching this entry point reads a `use_filter_intra` symbol.32017 // reaching this entry point reads a `use_filter_intra` symbol.
31957- false, fctx,32018+ false,
32019+ None,
32020+ fctx,
31958 )32021 )
31959 .map(|(picture, _, _)| picture)32022 .map(|(picture, _, _)| picture)
31960 }32023 }
@@ -31974,8 +32037,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
31974 deltas: crate::quant::QuantDeltas,32037 deltas: crate::quant::QuantDeltas,
31975 frame_width: u32,32038 frame_width: u32,
31976 frame_height: u32,32039 frame_height: u32,
31977- reference: &Picture,32040+ refpix: &RefPix<'_>,
31978- other_refs: [Option<&Picture>; 8],
31979 cdef: &CdefParams,32041 cdef: &CdefParams,
31980 loop_filter: &LoopFilterParams,32042 loop_filter: &LoopFilterParams,
31981 lr: &LoopRestorationParams,32043 lr: &LoopRestorationParams,
@@ -32042,8 +32104,18 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32042 // (spec 5.5.2), stashed in a thread-local with `tx_select` rather than32104 // (spec 5.5.2), stashed in a thread-local with `tx_select` rather than
32043 // threaded through `decode_inter_block`'s fifty parameters -- read by the32105 // threaded through `decode_inter_block`'s fifty parameters -- read by the
32044 // intra-in-inter arms' `read_filter_intra_mode_info`.32106 // intra-in-inter arms' `read_filter_intra_mode_info`.
32045- enable_filter_intra: bool, fctx: &crate::decode::FrameCtx,32107+ enable_filter_intra: bool,
32046-) -> Result<(Picture, Cdfs, crate::motion_field::MotionField)> {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>)> {
32047 set_inter_tx_mode(tx_select, reduced_tx_set, enable_filter_intra, fctx);32119 set_inter_tx_mode(tx_select, reduced_tx_set, enable_filter_intra, fctx);
32048 let tpl_frame = tpl_field.map(|field| TplFrameArgs {32120 let tpl_frame = tpl_field.map(|field| TplFrameArgs {
32049 field,32121 field,
@@ -32073,7 +32145,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32073 // refused every same-size reference (class av1-truesize-lane: true32145 // refused every same-size reference (class av1-truesize-lane: true
32074 // frame size vs mi-rounded). Height must still MATCH: AV1 superres32146 // frame size vs mi-rounded). Height must still MATCH: AV1 superres
32075 // never scales height, and no path here has a vertical scaling pass.32147 // 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) {
32077 return Err(unsupported(32149 return Err(unsupported(
32078 "a reference picture whose height does not match this frame's own true size",32150 "a reference picture whose height does not match this frame's own true size",
32079 ));32151 ));
@@ -32086,90 +32158,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32086 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);32158 fctx.cdef_idx_grid.with(|g| *g.borrow_mut() = vec![0u8; sb_cols as usize * sb_rows as usize]);
32087 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);32159 let (width, height) = (cols as usize * BLOCK, rows as usize * BLOCK);
32088 32160
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-
32173 let mut y = PlaneBuf {32161 let mut y = PlaneBuf {
32174 data: std::borrow::Cow::Owned(fresh_plane(width * height)),32162 data: std::borrow::Cow::Owned(fresh_plane(width * height)),
32175 width,32163 width,
@@ -32530,10 +32518,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32530 &mut y,32518 &mut y,
32531 &mut u,32519 &mut u,
32532 &mut v,32520 &mut v,
32533- &ref_y,32521+ refpix,
32534- &ref_u,
32535- &ref_v,
32536- &ref_slots,
32537 &sign_bias_table,32522 &sign_bias_table,
32538 &global_motion,32523 &global_motion,
32539 base_q_idx,32524 base_q_idx,
@@ -32603,10 +32588,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32603 &mut y,32588 &mut y,
32604 &mut u,32589 &mut u,
32605 &mut v,32590 &mut v,
32606- &ref_y,32591+ refpix,
32607- &ref_u,
32608- &ref_v,
32609- &ref_slots,
32610 base_q_idx,32592 base_q_idx,
32611 &scan8,32593 &scan8,
32612 &scan4,32594 &scan4,
@@ -32905,10 +32887,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
32905 &mut y,32887 &mut y,
32906 &mut u,32888 &mut u,
32907 &mut v,32889 &mut v,
32908- &ref_y,32890+ refpix,
32909- &ref_u,
32910- &ref_v,
32911- &ref_slots,
32912 &sign_bias_table,32891 &sign_bias_table,
32913 &global_motion,32892 &global_motion,
32914 base_q_idx,32893 base_q_idx,
@@ -33076,10 +33055,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33076 &mut y,33055 &mut y,
33077 &mut u,33056 &mut u,
33078 &mut v,33057 &mut v,
33079- &ref_y,33058+ refpix,
33080- &ref_u,
33081- &ref_v,
33082- &ref_slots,
33083 &sign_bias_table,33059 &sign_bias_table,
33084 &global_motion,33060 &global_motion,
33085 base_q_idx,33061 base_q_idx,
@@ -33226,10 +33202,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33226 &mut y,33202 &mut y,
33227 &mut u,33203 &mut u,
33228 &mut v,33204 &mut v,
33229- &ref_y,33205+ refpix,
33230- &ref_u,
33231- &ref_v,
33232- &ref_slots,
33233 &sign_bias_table,33206 &sign_bias_table,
33234 &global_motion,33207 &global_motion,
33235 base_q_idx,33208 base_q_idx,
@@ -33337,10 +33310,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33337 &mut y,33310 &mut y,
33338 &mut u,33311 &mut u,
33339 &mut v,33312 &mut v,
33340- &ref_y,33313+ refpix,
33341- &ref_u,
33342- &ref_v,
33343- &ref_slots,
33344 &sign_bias_table,33314 &sign_bias_table,
33345 &global_motion,33315 &global_motion,
33346 base_q_idx,33316 base_q_idx,
@@ -33424,10 +33394,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33424 &mut y,33394 &mut y,
33425 &mut u,33395 &mut u,
33426 &mut v,33396 &mut v,
33427- &ref_y,33397+ refpix,
33428- &ref_u,
33429- &ref_v,
33430- &ref_slots,
33431 &sign_bias_table,33398 &sign_bias_table,
33432 &global_motion,33399 &global_motion,
33433 base_q_idx,33400 base_q_idx,
@@ -33668,11 +33635,11 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33668 // 7.11.3.3's scaled walk. The counter is what33635 // 7.11.3.3's scaled walk. The counter is what
33669 // proves a gate actually reached a scaled33636 // proves a gate actually reached a scaled
33670 // leaf rather than a same-size reference.33637 // leaf rather than a same-size reference.
33671- if ref_y.width != frame_width as usize33638+ if (1..8).any(|rf| {
33672- || ref_slots.iter().flatten().any(|(py, _, _)| {33639+ refpix.dims(rf).is_some_and(|(w, _)| {
33673- py.width != frame_width as usize33640+ w != frame_width as usize
33674 })33641 })
33675- {33642+ }) {
33676 SCALED_LEAF8_HITS.with(|c| c.set(c.get() + 1));33643 SCALED_LEAF8_HITS.with(|c| c.set(c.get() + 1));
33677 }33644 }
33678 let mut prev_leaves: Vec<((usize, usize), bool, bool, i8, Option<i8>)> = Vec::new();33645 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(
33695 &mut y,33662 &mut y,
33696 &mut u,33663 &mut u,
33697 &mut v,33664 &mut v,
33698- &ref_y,33665+ refpix,
33699- &ref_u,
33700- &ref_v,
33701- &ref_slots,
33702 &sign_bias_table,33666 &sign_bias_table,
33703 &global_motion,33667 &global_motion,
33704 base_q_idx,33668 base_q_idx,
@@ -33736,10 +33700,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33736 &mut y,33700 &mut y,
33737 &mut u,33701 &mut u,
33738 &mut v,33702 &mut v,
33739- &ref_y,33703+ refpix,
33740- &ref_u,
33741- &ref_v,
33742- &ref_slots,
33743 &sign_bias_table,33704 &sign_bias_table,
33744 &global_motion,33705 &global_motion,
33745 base_q_idx,33706 base_q_idx,
@@ -33775,10 +33736,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33775 &mut y,33736 &mut y,
33776 &mut u,33737 &mut u,
33777 &mut v,33738 &mut v,
33778- &ref_y,33739+ refpix,
33779- &ref_u,
33780- &ref_v,
33781- &ref_slots,
33782 base_q_idx,33740 base_q_idx,
33783 &scan8,33741 &scan8,
33784 &scan4,33742 &scan4,
@@ -33872,10 +33830,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33872 &mut y,33830 &mut y,
33873 &mut u,33831 &mut u,
33874 &mut v,33832 &mut v,
33875- &ref_y,33833+ refpix,
33876- &ref_u,
33877- &ref_v,
33878- &ref_slots,
33879 &sign_bias_table,33834 &sign_bias_table,
33880 &global_motion,33835 &global_motion,
33881 base_q_idx,33836 base_q_idx,
@@ -33925,10 +33880,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33925 &mut y,33880 &mut y,
33926 &mut u,33881 &mut u,
33927 &mut v,33882 &mut v,
33928- &ref_y,33883+ refpix,
33929- &ref_u,
33930- &ref_v,
33931- &ref_slots,
33932 &sign_bias_table,33884 &sign_bias_table,
33933 &global_motion,33885 &global_motion,
33934 base_q_idx,33886 base_q_idx,
@@ -33979,10 +33931,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
33979 &mut y,33931 &mut y,
33980 &mut u,33932 &mut u,
33981 &mut v,33933 &mut v,
33982- &ref_y,33934+ refpix,
33983- &ref_u,
33984- &ref_v,
33985- &ref_slots,
33986 &sign_bias_table,33935 &sign_bias_table,
33987 &global_motion,33936 &global_motion,
33988 base_q_idx,33937 base_q_idx,
@@ -34043,10 +33992,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34043 &mut y,33992 &mut y,
34044 &mut u,33993 &mut u,
34045 &mut v,33994 &mut v,
34046- &ref_y,33995+ refpix,
34047- &ref_u,
34048- &ref_v,
34049- &ref_slots,
34050 &sign_bias_table,33996 &sign_bias_table,
34051 &global_motion,33997 &global_motion,
34052 base_q_idx,33998 base_q_idx,
@@ -34099,10 +34045,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34099 &mut y,34045 &mut y,
34100 &mut u,34046 &mut u,
34101 &mut v,34047 &mut v,
34102- &ref_y,34048+ refpix,
34103- &ref_u,
34104- &ref_v,
34105- &ref_slots,
34106 &sign_bias_table,34049 &sign_bias_table,
34107 &global_motion,34050 &global_motion,
34108 base_q_idx,34051 base_q_idx,
@@ -34156,10 +34099,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34156 &mut y,34099 &mut y,
34157 &mut u,34100 &mut u,
34158 &mut v,34101 &mut v,
34159- &ref_y,34102+ refpix,
34160- &ref_u,
34161- &ref_v,
34162- &ref_slots,
34163 &sign_bias_table,34103 &sign_bias_table,
34164 &global_motion,34104 &global_motion,
34165 base_q_idx,34105 base_q_idx,
@@ -34212,10 +34152,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34212 &mut y,34152 &mut y,
34213 &mut u,34153 &mut u,
34214 &mut v,34154 &mut v,
34215- &ref_y,34155+ refpix,
34216- &ref_u,
34217- &ref_v,
34218- &ref_slots,
34219 &sign_bias_table,34156 &sign_bias_table,
34220 &global_motion,34157 &global_motion,
34221 base_q_idx,34158 base_q_idx,
@@ -34270,10 +34207,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34270 &mut y,34207 &mut y,
34271 &mut u,34208 &mut u,
34272 &mut v,34209 &mut v,
34273- &ref_y,34210+ refpix,
34274- &ref_u,
34275- &ref_v,
34276- &ref_slots,
34277 &sign_bias_table,34211 &sign_bias_table,
34278 &global_motion,34212 &global_motion,
34279 base_q_idx,34213 base_q_idx,
@@ -34323,10 +34257,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34323 &mut y,34257 &mut y,
34324 &mut u,34258 &mut u,
34325 &mut v,34259 &mut v,
34326- &ref_y,34260+ refpix,
34327- &ref_u,
34328- &ref_v,
34329- &ref_slots,
34330 &sign_bias_table,34261 &sign_bias_table,
34331 &global_motion,34262 &global_motion,
34332 base_q_idx,34263 base_q_idx,
@@ -34376,10 +34307,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34376 &mut y,34307 &mut y,
34377 &mut u,34308 &mut u,
34378 &mut v,34309 &mut v,
34379- &ref_y,34310+ refpix,
34380- &ref_u,
34381- &ref_v,
34382- &ref_slots,
34383 &sign_bias_table,34311 &sign_bias_table,
34384 &global_motion,34312 &global_motion,
34385 base_q_idx,34313 base_q_idx,
@@ -34431,10 +34359,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34431 &mut y,34359 &mut y,
34432 &mut u,34360 &mut u,
34433 &mut v,34361 &mut v,
34434- &ref_y,34362+ refpix,
34435- &ref_u,
34436- &ref_v,
34437- &ref_slots,
34438 &sign_bias_table,34363 &sign_bias_table,
34439 &global_motion,34364 &global_motion,
34440 base_q_idx,34365 base_q_idx,
@@ -34484,10 +34409,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34484 &mut y,34409 &mut y,
34485 &mut u,34410 &mut u,
34486 &mut v,34411 &mut v,
34487- &ref_y,34412+ refpix,
34488- &ref_u,
34489- &ref_v,
34490- &ref_slots,
34491 &sign_bias_table,34413 &sign_bias_table,
34492 &global_motion,34414 &global_motion,
34493 base_q_idx,34415 base_q_idx,
@@ -34537,10 +34459,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34537 &mut y,34459 &mut y,
34538 &mut u,34460 &mut u,
34539 &mut v,34461 &mut v,
34540- &ref_y,34462+ refpix,
34541- &ref_u,
34542- &ref_v,
34543- &ref_slots,
34544 &sign_bias_table,34463 &sign_bias_table,
34545 &global_motion,34464 &global_motion,
34546 base_q_idx,34465 base_q_idx,
@@ -34593,10 +34512,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34593 &mut y,34512 &mut y,
34594 &mut u,34513 &mut u,
34595 &mut v,34514 &mut v,
34596- &ref_y,34515+ refpix,
34597- &ref_u,
34598- &ref_v,
34599- &ref_slots,
34600 &sign_bias_table,34516 &sign_bias_table,
34601 &global_motion,34517 &global_motion,
34602 base_q_idx,34518 base_q_idx,
@@ -34642,10 +34558,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34642 &mut y,34558 &mut y,
34643 &mut u,34559 &mut u,
34644 &mut v,34560 &mut v,
34645- &ref_y,34561+ refpix,
34646- &ref_u,
34647- &ref_v,
34648- &ref_slots,
34649 &sign_bias_table,34562 &sign_bias_table,
34650 &global_motion,34563 &global_motion,
34651 base_q_idx,34564 base_q_idx,
@@ -34695,10 +34608,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34695 &mut y,34608 &mut y,
34696 &mut u,34609 &mut u,
34697 &mut v,34610 &mut v,
34698- &ref_y,34611+ refpix,
34699- &ref_u,
34700- &ref_v,
34701- &ref_slots,
34702 &sign_bias_table,34612 &sign_bias_table,
34703 &global_motion,34613 &global_motion,
34704 base_q_idx,34614 base_q_idx,
@@ -34802,6 +34712,28 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34802 }34712 }
34803 }34713 }
34804 crate::timeline::recon_done();34714 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+ }
34805 34737
34806 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's34738 // lane-comppin r4: pre-loop-filter decode-order dump, matching aomdec's
34807 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against34739 // own EC_AV1_PREFILT_DUMP shape (decodeframe.c ~5451) -- diffs against
@@ -34948,15 +34880,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
34948 }34880 }
34949 34881
34950 crate::timeline::filters_done();34882 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- );
34960 34883
34961 let (fw, fh) = (lr_w, frame_height as usize);34884 let (fw, fh) = (lr_w, frame_height as usize);
34962 // An upscaled frame is already at its final size with no mi-aligned34885 // 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(
35027 34950
35028 #[cfg(test)]34951 #[cfg(test)]
35029 mod tests {34952 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+
35030 34961
35031 /// lane-perf6 step 2: the CDEF kernel now reads a pre-gathered window and34962 /// lane-perf6 step 2: the CDEF kernel now reads a pre-gathered window and
35032 /// a pre-resolved damping shift instead of a bounds-testing closure and a34963 /// a pre-resolved damping shift instead of a bounds-testing closure and a
@@ -35808,27 +35739,25 @@ mod tests {
35808 fn a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name() {35739 fn a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name() {
35809 const REFUSAL: &str =35740 const REFUSAL: &str =
35810 "a reference frame selected with no picture at this frame's own ref_frame_idx slot";35741 "a reference frame selected with no picture at this frame's own ref_frame_idx slot";
35811- let plane = PlaneBuf {35742+ let pic = Picture {
35812- data: std::borrow::Cow::Owned(vec![0u16; 16]),
35813 width: 4,35743 width: 4,
35814 height: 4,35744 height: 4,
35815- true_width: 4,35745+ y: vec![0u16; 16],
35816- true_height: 4,35746+ u: vec![0u16; 4],
35817- tile_x0: 0,35747+ v: vec![0u16; 4],
35818- tile_y0: 0,
35819- tile_x1: 4,
35820- tile_y1: 4,
35821 };35748 };
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);
35823 for ref_frame in [LAST2_FRAME, LAST3_FRAME, GOLDEN_FRAME, BWDREF_FRAME, ALTREF2_FRAME, ALTREF_FRAME] {35752 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) {
35825 Ok(_) => panic!("ref {ref_frame}: an empty slot resolved to a picture"),35754 Ok(_) => panic!("ref {ref_frame}: an empty slot resolved to a picture"),
35826 Err(e) => e.to_string(),35755 Err(e) => e.to_string(),
35827 };35756 };
35828 assert!(err.contains(REFUSAL), "ref {ref_frame}: expected {REFUSAL:?}, got: {err}");35757 assert!(err.contains(REFUSAL), "ref {ref_frame}: expected {REFUSAL:?}, got: {err}");
35829 }35758 }
35830 // `LAST_FRAME` never consults the slots: `decode_stream` checked it.35759 // `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 {
35832 panic!("LAST_FRAME resolves to the frame's own reference planes")35761 panic!("LAST_FRAME resolves to the frame's own reference planes")
35833 };35762 };
35834 assert_eq!(y.width, 4);35763 assert_eq!(y.width, 4);
@@ -36102,8 +36031,7 @@ mod tests {
36102 40,36031 40,
36103 64,36032 64,
36104 64,36033 64,
36105- &reference,36034+ &last_only(&reference),
36106- [None; 8],
36107 &CdefParams::default(),36035 &CdefParams::default(),
36108 &LoopFilterParams::default(),36036 &LoopFilterParams::default(),
36109 false,36037 false,
@@ -36444,8 +36372,7 @@ mod tests {
36444 frame.base_q_idx,36372 frame.base_q_idx,
36445 width as u32,36373 width as u32,
36446 height as u32,36374 height as u32,
36447- &reference,36375+ &last_only(&reference),
36448- [None; 8],
36449 &CdefParams::default(),36376 &CdefParams::default(),
36450 &LoopFilterParams::default(),36377 &LoopFilterParams::default(),
36451 false,36378 false,
@@ -36563,37 +36490,21 @@ mod tests {
36563 36490
36564 let (width, height) = (64usize, 64usize);36491 let (width, height) = (64usize, 64usize);
36565 let ref_pattern: Vec<u16> = (0..width * height).map(|i| (i % 251) as u16).collect();36492 let ref_pattern: Vec<u16> = (0..width * height).map(|i| (i % 251) as u16).collect();
36566- let ref_plane = |scale: usize| PlaneBuf {36493+ let chroma: Vec<u16> = ref_pattern
36567- data: std::borrow::Cow::Owned(
36568- ref_pattern
36569 .iter()36494 .iter()
36570- .step_by(scale.max(1))36495+ .step_by(2)
36571- .take((width / scale) * (height / scale))36496+ .take((width / 2) * (height / 2))
36572 .copied()36497 .copied()
36573- .collect(),36498+ .collect();
36574- ),36499+ let reference = Picture {
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()),
36586 width,36500 width,
36587 height,36501 height,
36588- true_width: width,36502+ y: ref_pattern.clone(),
36589- true_height: height,36503+ u: chroma.clone(),
36590- tile_x0: 0,36504+ v: chroma,
36591- tile_y0: 0,
36592- tile_x1: width,
36593- tile_y1: height,
36594 };36505 };
36595- let ref_u = ref_plane(2);36506+ let refpix = &last_only(&reference);
36596- let ref_v = ref_plane(2);36507+ let ref_y = whole_plane(&reference.y, width, height);
36597 36508
36598 let mut y = PlaneBuf {36509 let mut y = PlaneBuf {
36599 data: std::borrow::Cow::Owned(vec![0u16; width * height]),36510 data: std::borrow::Cow::Owned(vec![0u16; width * height]),
@@ -36644,10 +36555,7 @@ mod tests {
36644 &mut y,36555 &mut y,
36645 &mut u,36556 &mut u,
36646 &mut v,36557 &mut v,
36647- &ref_y,36558+ refpix,
36648- &ref_u,
36649- &ref_v,
36650- &[None; 8],
36651 &NO_SIGN_BIAS,36559 &NO_SIGN_BIAS,
36652 &[ec_av1_syntax::WarpParams::default(); 7],36560 &[ec_av1_syntax::WarpParams::default(); 7],
36653 100,36561 100,
@@ -36773,8 +36681,7 @@ mod tests {
36773 frame.base_q_idx,36681 frame.base_q_idx,
36774 coded_w,36682 coded_w,
36775 coded_h,36683 coded_h,
36776- &reference,36684+ &last_only(&reference),
36777- [None; 8],
36778 &CdefParams::default(),36685 &CdefParams::default(),
36779 &LoopFilterParams::default(),36686 &LoopFilterParams::default(),
36780 false,36687 false,
crates/ec-av1/src/stream.rsmodified+204 -54
@@ -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,41 @@ 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 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(_, _, _, _)),
921 )?;1022 )?;
922 // Publish before grain synthesis: every frame waiting on1023 // Publish before grain synthesis: every frame waiting on
923 // this slot can start the moment the clean picture exists1024 // this slot can start the moment the clean picture exists
924 // (spec 7.18.3.1 -- the bank never stores grain).1025 // (spec 7.18.3.1 -- the bank never stores grain).
925 let picture = std::sync::Arc::new(out.picture);1026 let picture = std::sync::Arc::new(out.picture);
1027+ pixels.fulfil(picture.clone());
926 if let Some(promise) = &promise {1028 if let Some(promise) = &promise {
927- promise.fulfil(std::sync::Arc::new(SlotValue {1029+ // Only a frame whose stage-1 sink never fired (a
928- picture: picture.clone(),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,
929 cdfs: out.stored_cdfs,1036 cdfs: out.stored_cdfs,
930- motion_field: out.motion_field,1037+ motion_field: out.motion_field.expect(
1038+ "a frame that published no stage 1 carries its motion field back",
1039+ ),
931 seg_map: out.seg_map,1040 seg_map: out.seg_map,
932 order_hint: header.order_hint,1041 order_hint: header.order_hint,
933- }));1042+ })
1043+ });
934 crate::timeline::slot_fulfil();1044 crate::timeline::slot_fulfil();
935 }1045 }
936 // Grain is synthesised for OUTPUT only: a hidden frame is1046 // Grain is synthesised for OUTPUT only: a hidden frame is
@@ -957,11 +1067,14 @@ pub fn decode_stream_with_threads(
957 });1067 });
958 // A frame nobody can decode must not leave its consumers1068 // A frame nobody can decode must not leave its consumers
959 // waiting for a slot that will never be filled.1069 // waiting for a slot that will never be filled.
960- if reply.is_err()1070+ if reply.is_err() {
961- && let Some(promise) = &promise1071+ // Neither stage may leave a consumer waiting for a value
962- {1072+ // that will never come.
1073+ if let Some(promise) = &promise {
963 promise.fail();1074 promise.fail();
964 }1075 }
1076+ pixels.fail();
1077+ }
965 let _ = tx.send((job_seq, true, reply));1078 let _ = tx.send((job_seq, true, reply));
966 });1079 });
967 in_flight_decodes += 1;1080 in_flight_decodes += 1;
@@ -979,10 +1092,21 @@ pub fn decode_stream_with_threads(
979 }1092 }
980 continue;1093 continue;
981 }1094 }
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+ }));
982 let snap = RefSnapshot::take(1106 let snap = RefSnapshot::take(
983 &header,1107 &header,
984 seq,1108 seq,
985- std::array::from_fn(|i| ref_slots[i].as_deref()),1109+ &inline_refpix,
986 std::array::from_fn(|i| cdf_slots[i].as_ref()),1110 std::array::from_fn(|i| cdf_slots[i].as_ref()),
987 std::array::from_fn(|i| seg_map_slots[i].as_deref()),1111 std::array::from_fn(|i| seg_map_slots[i].as_deref()),
988 &std::array::from_fn(|i| motion_field_slots[i].as_ref()),1112 &std::array::from_fn(|i| motion_field_slots[i].as_ref()),
@@ -1003,7 +1127,10 @@ pub fn decode_stream_with_threads(
1003 pictures_decoded,1127 pictures_decoded,
1004 pictures_shown,1128 pictures_shown,
1005 final_dump.as_deref(),1129 final_dump.as_deref(),
1130+ None,
1006 )?;1131 )?;
1132+ let motion_field =
1133+ motion_field.expect("the inline path passes no stage-1 sink");
1007 pictures_decoded += 1;1134 pictures_decoded += 1;
1008 // lane-pool1: one allocation, then every slot store and the output1135 // lane-pool1: one allocation, then every slot store and the output
1009 // itself are refcount bumps instead of plane copies.1136 // itself are refcount bumps instead of plane copies.
@@ -1014,7 +1141,9 @@ pub fn decode_stream_with_threads(
1014 // already resolved, since the picture exists right here.1141 // already resolved, since the picture exists right here.
1015 if header.refresh_frame_flags != 0 {1142 if header.refresh_frame_flags != 0 {
1016 let promise = SlotPromise::ready(std::sync::Arc::new(SlotValue {1143 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,
1018 cdfs: stored_cdfs,1147 cdfs: stored_cdfs,
1019 motion_field,1148 motion_field,
1020 seg_map: decoded_seg_map,1149 seg_map: decoded_seg_map,
@@ -1131,8 +1260,9 @@ impl SeqFlags {
1131 /// banks `decode_stream_with` owns -- taken on the parsing thread, before any1260 /// 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.1261 /// later frame can overwrite a slot, so a frame can be decoded anywhere.
1133 pub(crate) struct RefSnapshot<'a> {1262 pub(crate) struct RefSnapshot<'a> {
1134- /// The 8 DPB slots, indexed by slot (NOT by `ref_frame_idx`).1263+ /// lane-twostage: this frame's references, indexed by `ref_frame`
1135- pub(crate) refs: [Option<&'a Picture>; NUM_REF_FRAMES],1264+ /// (`LAST_FRAME` = 1) -- sizes now, pixels at the first prediction.
1265+ pub(crate) refpix: &'a decode::RefPix<'a>,
1136 /// `cdf_slots[ref_frame_idx[primary_ref_frame]]`, `None` when this frame1266 /// `cdf_slots[ref_frame_idx[primary_ref_frame]]`, `None` when this frame
1137 /// names `PRIMARY_REF_NONE` *or* that slot holds no saved table (the1267 /// names `PRIMARY_REF_NONE` *or* that slot holds no saved table (the
1138 /// second case is the refusal [`decode_frame`] raises where it always1268 /// second case is the refusal [`decode_frame`] raises where it always
@@ -1155,7 +1285,7 @@ impl<'a> RefSnapshot<'a> {
1155 fn take(1285 fn take(
1156 header: &FrameHeader,1286 header: &FrameHeader,
1157 seq: SeqFlags,1287 seq: SeqFlags,
1158- refs: [Option<&'a Picture>; NUM_REF_FRAMES],1288+ refpix: &'a decode::RefPix<'a>,
1159 cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES],1289 cdf_slots: [Option<&Cdfs>; NUM_REF_FRAMES],
1160 seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES],1290 seg_map_slots: [Option<&[u8]>; NUM_REF_FRAMES],
1161 motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES],1291 motion_field_slots: &[Option<&crate::motion_field::MotionField>; NUM_REF_FRAMES],
@@ -1189,7 +1319,7 @@ impl<'a> RefSnapshot<'a> {
1189 );1319 );
1190 }1320 }
1191 Self {1321 Self {
1192- refs,1322+ refpix,
1193 primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),1323 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)),1324 prev_seg_map: primary.and_then(|slot| seg_map_slots[slot].map(<[u8]>::to_vec)),
1195 tpl_field,1325 tpl_field,
@@ -1206,10 +1336,27 @@ impl<'a> RefSnapshot<'a> {
1206 pub(crate) struct FrameOutput {1336 pub(crate) struct FrameOutput {
1207 pub(crate) picture: Picture,1337 pub(crate) picture: Picture,
1208 pub(crate) stored_cdfs: Cdfs,1338 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>,
1210 pub(crate) seg_map: Vec<u8>,1342 pub(crate) seg_map: Vec<u8>,
1211 }1343 }
1212 1344
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+
1213 /// lane-thread2: one coded frame, decoded from its header, its tile payload1360 /// lane-thread2: one coded frame, decoded from its header, its tile payload
1214 /// and a snapshot of the reference banks -- and from nothing else. Lifted1361 /// 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 can1362 /// verbatim out of [`decode_stream_with`]'s loop so that the same code can
@@ -1233,6 +1380,8 @@ fn decode_frame(
1233 decode_idx: usize,1380 decode_idx: usize,
1234 shown_idx: usize,1381 shown_idx: usize,
1235 final_dump: Option<&str>,1382 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)>,
1236 ) -> Result<FrameOutput> {1385 ) -> Result<FrameOutput> {
1237 if header.segmentation.enabled {1386 if header.segmentation.enabled {
1238 for segment in 0..MAX_SEGMENTS {1387 for segment in 0..MAX_SEGMENTS {
@@ -1568,15 +1717,16 @@ fn decode_frame(
1568 // never a projection source, and never spends a `ref_stamp`.1717 // never a projection source, and never spends a `ref_stamp`.
1569 true,1718 true,
1570 );1719 );
1571- (picture, end_cdfs, motion_field)1720+ (picture, end_cdfs, Some(motion_field))
1572 } else {1721 } else {
1573 let last_slot = header.ref_frame_idx[0] as usize;1722 let last_slot = header.ref_frame_idx[0] as usize;
1574- let reference = snap.refs[last_slot].ok_or_else(|| {1723+ let _ = last_slot;
1575- Error::unsupported(1724+ if snap.refpix.dims(1).is_none() {
1725+ return Err(Error::unsupported(
1576 "AV1 decode_stream",1726 "AV1 decode_stream",
1577 "an inter frame with no key frame before it",1727 "an inter frame with no key frame before it",
1578- )1728+ ));
1579- })?;1729+ }
1580 // `ref_frame_idx[i]` names the DPB slot for `LAST_FRAME + i`1730 // `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 a1731 // (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 a1732 // stream error on its own: `decode_inter_block` only needs a
@@ -1589,20 +1739,26 @@ fn decode_frame(
1589 if header.force_integer_mv {1739 if header.force_integer_mv {
1590 decode::note_force_integer_mv_frame();1740 decode::note_force_integer_mv_frame();
1591 }1741 }
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 when1742 // spec 7.9's own driver, `av1_setup_motion_field`: only run when
1603 // this frame's header actually asks for temporal candidates --1743 // this frame's header actually asks for temporal candidates --
1604 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`1744 // `find_mv_stack_with_sign_bias` reproduces its old always-`None`
1605 // behaviour bit for bit when this is `None` (see its own doc).1745 // 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+ });
1606 let tpl_field = &snap.tpl_field;1762 let tpl_field = &snap.tpl_field;
1607 let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(1763 let (picture, end_cdfs, motion_field) = decode_inter_frame_tile_with_cdfs(
1608 &tile_bufs,1764 &tile_bufs,
@@ -1619,8 +1775,7 @@ fn decode_frame(
1619 },1775 },
1620 header.frame_width,1776 header.frame_width,
1621 header.frame_height,1777 header.frame_height,
1622- reference,1778+ snap.refpix,
1623- other_refs,
1624 &header.cdef,1779 &header.cdef,
1625 &header.loop_filter,1780 &header.loop_filter,
1626 &header.loop_restoration,1781 &header.loop_restoration,
@@ -1647,7 +1802,11 @@ fn decode_frame(
1647 header.allow_warped_motion,1802 header.allow_warped_motion,
1648 header.allow_screen_content_tools,1803 header.allow_screen_content_tools,
1649 header.delta,1804 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,
1651 )?;1810 )?;
1652 (picture, end_cdfs, motion_field)1811 (picture, end_cdfs, motion_field)
1653 };1812 };
@@ -1657,16 +1816,7 @@ fn decode_frame(
1657 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's1816 // Spec 7.20: `disable_frame_end_update_cdf` stores the frame's
1658 // *initial* table into the slots it refreshes, not the adapted1817 // *initial* table into the slots it refreshes, not the adapted
1659 // end-of-tile one.1818 // end-of-tile one.
1660- let stored_cdfs = if header.disable_frame_end_update_cdf {1819+ 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") {1820 if let Ok(path) = std::env::var("EC_AV1_DUMP_TABLES") {
1671 use std::io::Write;1821 use std::io::Write;
1672 if let Ok(mut f) = std::fs::OpenOptions::new()1822 if let Ok(mut f) = std::fs::OpenOptions::new()